text:
Q: Create Sql subcategory table I have went to give interview today there is question that i didn't hear about, i wana know how to do this ... how to make this with query
create a single table that can hold up till n-level category's. create a table to expandable category tree given the following example . Now the table should be designed in such way that category level can be extended to as much as required .
                                  root
                                  /   \
                                 /     \
                               MEN      women------------
                               / \         /            |
                              /   \       Shirt&top     paints
                         shirt   trousers                /   \
                                                        /     \
                                                       /       \
                                                      /         \
                                                    trouser     Skirts and jeans

A: The "cookbook" solution would be to have a parent id column pointing to a category id in a single table:
CREATE TABLE categories (
    category_id INT PRIMARY KEY,
    parent_id INT REFERENCES category_id,
    name VARCHAR(100)
)

So, for the example given above:
INSERT INTO categories VALUES (1, null, 'root'),
(2, 1, 'Men'),
(3, 2, 'shirt'),
(4, 2, 'trousers'),
(5, 1, 'women'),
(6, 5, 'shirt & top'),
(7, 5, 'pants'),
(8, 7, 'trousers'),
(9, 7, 'skirts and jeans');

A: If you need to implement that structure in a single table, you could store per row the following information:

*

*id (primary key, category id)

*parent_id (points to the parent category id)

*category_name (textual representation of the category name)

So in your example, the data would be stored as such:
1 | 0 | root
2 | 1 | MEN
3 | 2 | shirt
4 | 2 | trousers
5 | 1 | women
6 | 5 | shirt & top

... and so on


text:
Q: Issue in a Django's template Actually, I know it is impossible in a Django's template, but I would like to execute {{ Perception.objects.filter(loan__request__customer__pk = 207) }}
Here is the views I use for that template :
class PerceptionIndexView(StaffRestrictedMixin, FrontendListView):
    page_title = _('Perception')
    model = Perception
    template_name = 'loanwolf/perception/index.html'
    pjax_template_name = 'loanwolf/perception/index.pjax.html'
    row_actions_template_name = 'loanwolf/perception/list-actions.inc.html'
    url_namespace = 'perception'

    def active(self, obj):
        if obj.is_active:
            return icon(obj.get_icon(), css_class='green-text', tooltip=_('Active'))
        else:
            return icon(obj.get_icon(), css_class='red-text', tooltip=_('Inactive'))

    def notes_count(self, obj):
        return obj.notes.count()
    notes_count_label = _('Notes')

    def get_change_url(self, obj):
        return obj.get_absolute_url()

    def my_view(self, A_pk):
        filter_perceptions= Perception.objects.filter(loan__request__customer__pk=A_pk)
        return render_to_response('../template/loanwolf/perception/list-view-#2.inc.html', {'filter_perceptions': filter_perceptions})

I tried to use render_to_response with different path, but nothing happen so far. knowing that my view is located in loanwolf/perception and my template list-view-#2.inc.html is located in loanwolf/templates/loanwolf/perception. Furthermore, it is important to know that FrontendListView use a ListView. I think I could not use a 'render_to_response', but it is unclear.
Could anyone have an alternative solution so that I could access the list Perception.objects.filter(loan__request__customer__pk) in my template?
Thanks in advance!

A: Put the code that is inside your my_view into a method called get_context_data, similar to this:
def get_context_data(self, **kwargs):
    context = super(PerceiptionIndexView, self).get_context_data(**kwargs)
    filter_perceptions = Perception.objects.filter(loan__request__customer__pk=...)
    context["filter_perceptions"] = filter_perceptions
    return context

Then filter_perceptions will be available in your template via {{filter_perceptions}}
Look at the docs for more examples if you need something slightly different.

redpajama_set_name: RedPajamaStackExchange


text:
Q: VSCode kill running processes I have been using
Python debug and LLDB attach debug since I have code in Python and C++
I have run this multiple times. It looks like everytime there is an exception in the middle of debugging, the process doesn't get killed.
As a result, now after multiple runs, when I try to use LLDB Attach debug it shows multiple instances of the same file being run
Unable to know which is the latest process
Also how to kill processes that haven't terminated.
For reference, here's an image

A: Those processes can probably be termed as ghost processes. Those are caused from the previous run when one does not detach the lldb from it.
Manually searching for the process ID of those and killing them solved the problem.
List python related processes
ps -ef | grep python

Killing the ones you identify as ghost.
kill -9 <process-id>

A: As an alternative to command line, you should be able to see that ghost python process in the process explorer (command "Open Process Explorer"), and then use Ctrl+e to kill it.
The Ctrl+e is available in VSCode 1.75 (Jan. 2023), or right now in VSCode Insiders, with issue 119345 and PR 168943 delivered.


text:
Q: How can I make the Entities in a ParallaxBackground move vertically in AndEngine? Title says it all, currently I'm making a game where my character moves vertically and I want the ParallaxBackground entities to do the same, how can I achieve this?

A: One way to do this is to extend the ParallaxEntity contained in the ParallaxBackground class and have that move vertically, here's some code showing how I've done that. It's basically swapping the changes in x-coordinates to y-coordinates. I've adapted it to the current version of AndEngine, the original version of the code that targeted an old version can be found here.
import org.andengine.engine.camera.Camera;
import org.andengine.entity.IEntity;
import org.andengine.entity.scene.background.ParallaxBackground.ParallaxEntity;
import org.andengine.opengl.util.GLState;

public class VerticalParallaxEntity extends ParallaxEntity
{
    final float mParallaxFactor;
    final IEntity mEntity;

    public VerticalParallaxEntity(final float pParallaxFactor, final IEntity pEntity)
    {
        super(pParallaxFactor, pEntity);
        this.mParallaxFactor = pParallaxFactor;
        this.mEntity = pEntity;
    }

    public void onDraw(final GLState pGLState, final Camera pCamera, final float pParallaxValue)
    {
        pGLState.pushModelViewGLMatrix();
        {
            final float cameraHeight = pCamera.getHeight();
            final float entityHeightScaled = this.mEntity.getHeight() * this.mEntity.getScaleY();

            float baseOffset = (pParallaxValue * this.mParallaxFactor) % entityHeightScaled;

            while(baseOffset > 0) {
                baseOffset -= entityHeightScaled;
            }
            pGLState.translateModelViewGLMatrixf(0, baseOffset, 0);

            float currentMaxY = baseOffset;

            do
            {
                this.mEntity.onDraw(pGLState, pCamera);
                pGLState.translateModelViewGLMatrixf(0, entityHeightScaled, 0);
                currentMaxY += entityHeightScaled;
            } while(currentMaxY < cameraHeight);
        }
        pGLState.popModelViewGLMatrix();
    }
}


text:
Q: How can i integrate google location view and street view map i able to integrate google street view and google location view map in my application separately.But now i need to map view integrate in one view.
google location marker and street marker at present in location view.I am unable to do that.can any one give me the sample code.

A: Md. Shahjalal, take a look on this library: https://hpneo.github.io/gmaps/examples.html


text:
Q: Determining the End-of-stream I made a loop for a webserver.
On a windows client I didn't have any problems but on a linux client the server didn't responding to requests.
The problem: I found out that if request_size % buffer_size == 0 then the loop runs once more waiting for more data.
The question: Is there an efficient way of reading data that takes into consideration slow connections, connections that drop packages. (Not just using non_blocking or nodelay.)
let listener = TcpListener::bind("127.0.0.1:80").unwrap();

while let Ok((mut stream, _)) = listener.accept() {
  let mut data: Vec<u8> = Vec::new();
  let mut buf = [0u8; 32];
  while let Ok(size) = stream.read(&mut buf) {
    data.extend(buf[..size].iter());
    if size != buf.len() { break; }
  }

  // do something with the data
}

I could increase the buffer size but that wouldn't solve the problem.

A: First, to detect EOF reliably, you should test the returned size of Read::read against zero and not your buffer size, because if you have a 'slow connections' you might not get enough data to fill the entire buffer at once, causing your loop to quite early with an incomplete message in data.

There are essentially 3 ways to make sure you received the entire message:

*

*Read until EOF

*Read a fixed-sized message

*Encode some 'content length' and read that many bytes

Notice, that only the last two variants allow your client to eventually send more data over the same stream. Also notice, that these two variants can be implemented comparably easy via Read::read_exact.
Besides notice, if you don't trust your client, it might be helpful to set up TcpStream::set_read_timeout with a reasonably long timeout (e.g. 2 min).
Read until EOF
This is probably the easiest and, according to your title and code, probably the method you are aiming for. However, to generate an EOF, the client must shutdown at least its write channel. So, if your server is stuck in read, I assume you forgot to shutdown your client (tho I have to guess here).
On the server side, if you really want to read until EOF, you don't need a loop yourself, you can simply use the Read::read_to_end utility function. Here is an example for a client & server with the client sending a single message terminated by EOF:
use std::io::Read;
use std::io::Write;
use std::net::TcpListener;
use std::net::TcpStream;

// --- Client code
const SERVER_ADDR: &str = "localhost:1234";
pub fn client() {
    let mut socket = TcpStream::connect(SERVER_ADDR).expect("Failed to connect");
    // Send a 'single' message, the flushes kinda simulates a very slow connection
    for _ in 0..3 {
        socket.write(b"Hello").expect("Failed to send");
        socket.flush().unwrap();
    }
    // Instead of shutdow, you can also drop(socket), but than you can't read.
    socket.shutdown(std::net::Shutdown::Write).unwrap();
    // go reading, or whatever
}

// --- Server code
const SERVER_BIND: &str = "127.0.0.1:1234";
pub fn server() {
    let listener = TcpListener::bind(SERVER_BIND).expect("Failed to bind");
    while let Ok((stream, _)) = listener.accept() {
        let _ = handle_client(stream); // don't care if the client screwed up
    }
}
pub fn handle_client(mut socket: TcpStream) -> std::io::Result<()> {
    let mut data: Vec<u8> = Vec::new();
    // Read all bytes until EOF
    socket.read_to_end(&mut data)?;
    println!("Data: {:?}", data); // or whatever
    Ok(())
}


text:
Q: Descendientes de categoria en laravel Tengo una duda que creo q es simple, pero no sé como resolverla.
Tengo en mi aplicación, en el modelo categoría, lo siguiente:
public function children()
{
    return $this -> hasMany(Category::Class, 'parent_id');
}

public function descendants()
{
    return $this -> children() -> with('descendants');
}

A partir de esto, ya tengo todos los descendientes, pero no sé cómo hacer para traer todos los ID de los descendientes en mi componente.
Yo hice lo siguiente:
$subcats = array();
foreach ($this -> category -> descendants as $sc) {
     $subcats[] = $sc -> id;
}

Con esto me trae solo los ID de los descendientes directos, pero yo quiero obtener los de los hijos, los hijos de los hijos, y así sucesivamente.
¡Espero me puedan ayudar!


text:
Q: Handle tab correctly when counting location information in Lex? I have read the manual about how to track location information, but still have problem. It seems that Lex (2.5) counts both space and tab as one character, and that makes the error reporting with wrong column number. Currently, I have the editor to replace tab with spaces for the parser. But I wonder if there is a way to handle tab correctly in Lex itself.

A: You could use unputc to perform dirty trickery with the input stream. When you match a tab use unputc to put four spaces in the input steam...
Manual extract:

unput(c) puts the character c back onto the input stream. It will be
  the next character scanned. The following action will take the current
  token and cause it to be rescanned enclosed in parentheses.
{
int i;
/* Copy yytext because unput() trashes yytext */
char *yycopy = strdup( yytext );
unput( ')' );
for ( i = yyleng - 1; i >= 0; --i )
    unput( yycopy[i] );
unput( '(' );
free( yycopy );
}

Note that since each unput() puts the given character back at the beginning of the input stream, pushing back strings must be done
  back-to-front.


text:
Q: Add the drupal commerce products to cart without page reload programmatically How to implement following task :-
I have 2 div, In first div i have product name and add link, If user click on add link related product should be add in second div.
In second div at bottom i have add to cart button so on click cart button all added products should be add in drupal commerce add to cart page.
Just for reference please check below link :-
http://buildabagpartyfavours.ca/pages/build-your-own-goodie-bag

A: If anybody use Drupal 8, and want to solve this question, can in this way:
If you have the product variation id $var_id, you can create an "a" tag with "use-ajax" class:
Add to cart

In routing.yml you have to add the following path with controller:
path: '/add/product/{pid}'
_controller: Drupal\MY_MODULE\Controller\ShopProductController::addToCart

And you have to create controller with ajax response:
    namespace Drupal\MY_MODULE\Controller;

    use Drupal\commerce_order\Entity\OrderInterface;
    use Drupal\commerce_order\Entity\OrderItem;
    use Drupal\commerce_order\Entity\Order;
    use Drupal\Core\Ajax\AjaxResponse;
    use Drupal\Core\Ajax\HtmlCommand;
    use Drupal\Core\Ajax\CssCommand;

class ShopProductController {
    public function addToCart($pid) {

        $ajax_response = new AjaxResponse();
        #### ADD TO CART ####
        // variation_id of product.

        if (isset($pid) && !empty($pid)) {

            $store_id = 1;
            $order_type = 'default';
            $variation_id = $pid;

            $entity_manager = \Drupal::entityManager();
            $cart_manager = \Drupal::service('commerce_cart.cart_manager');
            $cart_provider = \Drupal::service('commerce_cart.cart_provider');

            // Drupal\commerce_store\Entity\Store::load($store_id);
            $store = $entity_manager->getStorage('commerce_store')->load($store_id);
            $product_variation = $entity_manager->getStorage('commerce_product_variation')->load($variation_id);

            // order type and store
            $cart = $cart_provider->getCart($order_type, $store);
            if (!$cart) {
                $cart = $cart_provider->createCart($order_type, $store);
            }

            //Create new order item
            $order_item = $entity_manager->getStorage('commerce_order_item')->create(array(
                'type' => 'default',
                'purchased_entity' => (string) $variation_id,
                'quantity' => 1,
                'unit_price' => $product_variation->getPrice(),
            ));

            $order_item->save();
            $cart_manager->addOrderItem($cart, $order_item);

            $ajax_response->addCommand(new HtmlCommand('.-add-to-cart', 'Added'));

            }

            return $ajax_response;

        }
}

A: Make your button triggers some AJAX call, pass product id and on other side in your AJAX callback script collect product id, create line item from it and add it to the cart ( https://www.drupal.org/node/1288414 ).
When AJAX call is finished you'll have to call another one, to update cart block.


text:
Q: Grappling Hook Mechanic in unity 2D im trying to add a mechanic to my game where you can launch a grappling hook and once it hits a wall you get brought to it allowing things like long distance wall jumps but it isnt working and i don't know why but i am getting this error
i want the rope to work like in celeste classic 2
ArgumentException: The Object you want to instantiate is null.
UnityEngine.Object.Instantiate (UnityEngine.Object original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at <86acb61e0d2b4b36bc20af11093be9a5>:0)
RopeLauncher.LaunchRope () (at Assets/Scripts/Player/RopeLauncher.cs:73)
RopeLauncher.Update () (at Assets/Scripts/Player/RopeLauncher.cs:36)
using UnityEngine;

public class RopeLauncher : MonoBehaviour
{
    public Transform targetTransform;
    public LayerMask ropeObstacleLayer;

    public float ropeSpeed = 10f;
    public float ropeLength = 5f;

    private bool ropeActive = false;
    private bool ropeHitObstacle = false;
    private bool playerOnRope = false;
    private float ropeDistanceTraveled = 0f;

    private GameObject ropeInstance;
    private LineRenderer ropeLineRenderer;
    private Vector2 ropeStartPoint;
    private Vector2 ropeEndPoint;

    public GameObject ropePrefab;

    private Rigidbody2D playerRigidbody;
    private Vector2 playerVelocityBeforeRope;

    void Start()
    {
        playerRigidbody = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        // Check for input to launch rope
        if (Input.GetButtonDown("GrappleDown") && !ropeActive)
        {
            LaunchRope();
        }

        // If rope is active, update its position and check for collisions
        if (ropeActive)
        {
            UpdateRopePosition();

            if (!ropeHitObstacle)
            {
                CheckForRopeCollisions();
            }
            else
            {
                // If rope hit an obstacle, bring player to that position
                Vector2 hitPosition = ropeEndPoint;
                playerRigidbody.position = hitPosition;
                EndRope();
            }
        }

        // If player is on rope, update their position
        if (playerOnRope)
        {
            UpdatePlayerOnRopePosition();

            // Check if player has reached the end of the rope
            if (ropeDistanceTraveled >= ropeLength)
            {
                EndRope();
            }
        }
    }

    void LaunchRope()
    {
        // Spawn rope prefab and get reference to its LineRenderer component
        ropeInstance = Instantiate(Resources.Load("Rope"), transform.position, Quaternion.identity) as GameObject;
        ropeLineRenderer = ropeInstance.GetComponent<LineRenderer>();

        // Set start and end points of rope
        ropeStartPoint = transform.position;
        ropeEndPoint = targetTransform.position;
        ropeLineRenderer.SetPosition(0, ropeStartPoint);
        ropeLineRenderer.SetPosition(1, ropeStartPoint);

        // Set ropeActive to true and freeze player movement
        ropeActive = true;
        playerRigidbody.constraints = RigidbodyConstraints2D.FreezeAll;
    }

    void UpdateRopePosition()
    {
        // Move rope endpoint towards target position
        Vector2 ropeMovement = (ropeEndPoint - ropeStartPoint).normalized * ropeSpeed * Time.deltaTime;
        ropeEndPoint -= ropeMovement;

        // Update rope distance traveled
        ropeDistanceTraveled = Vector2.Distance(ropeStartPoint, ropeEndPoint);

        // Update LineRenderer positions
        ropeLineRenderer.SetPosition(1, ropeEndPoint);
    }

    void CheckForRopeCollisions()
    {
        // Check for collision with RopeObstacles layer
        RaycastHit2D hit = Physics2D.Linecast(ropeStartPoint, ropeEndPoint, ropeObstacleLayer);
        if (hit.collider != null)
        {
            // If rope hit an obstacle, set ropeHitObstacle to true and update end point
            ropeHitObstacle = true;
            ropeEndPoint = hit.point;
        }
    }

    void UpdatePlayerOnRopePosition()
    {
        // Move player along rope
        Vector2 playerPosition = playerRigidbody.position;
        Vector2 ropeDirection = (ropeEndPoint - ropeStartPoint).normalized;
        float distanceFromRopeStart = Vector2.Distance(playerPosition, ropeStartPoint);
        Vector2 newPosition = ropeStartPoint + ropeDirection * distanceFromRopeStart;
        playerRigidbody.MovePosition(newPosition);

        // Update rope distance traveled
        ropeDistanceTraveled = Vector2.Distance(ropeStartPoint, newPosition);

        // If player jumps while on rope, end rope
        if (Input.GetButtonDown("Jump"))
        {
            EndRope();
        }
    }

    void EndRope()
    {
        // Destroy rope prefab and reset variables
        Destroy(ropeInstance);
        ropeActive = false;
        ropeHitObstacle = false;
        playerOnRope = false;
        ropeDistanceTraveled = 0f;

        // Unfreeze player movement
        playerRigidbody.constraints = RigidbodyConstraints2D.None;
        playerRigidbody.constraints = RigidbodyConstraints2D.FreezeRotation;
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        // If player collides with an obstacle while on rope, end rope
        if (playerOnRope && collision.collider.gameObject.layer == LayerMask.NameToLayer("RopeObstacles"))
        {
            EndRope();
        }
    }
}

i tried putting the rope in a prefab adding a slot for it i want to have a line renderer send a rope out but it isnt working


text:
Q: Android tvdpi vs xhdpi screen issue I'm developing an app for a tablet which until recently was tested in an emulator for Nexus 7 (7.27'',800x1280:tvdpi). Everything was fine until I decided to test the app in a different emulator, one created similar to samsung galaxy note 2 (5.6'',720x1280:xhdpi) and it doesn't look so well.
For example, take a look at this custom alert dialog I'm using.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/dialog_layout_root"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:padding="10dp"
          android:background="@color/light_gray">
         <Button
             android:id="@+id/facebook_login_button"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_centerHorizontal="true"
             android:layout_marginTop="40dp"/>
         <TextView
             android:id="@+id/or_text"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:textIsSelectable="true"
             android:layout_centerHorizontal="true"
             android:layout_marginTop="20dp"
             android:textSize="20sp"
             android:textColor="@color/black"
             android:layout_below="@id/facebook_login_button"/>
         <TextView
             android:id="@+id/sign_in_text"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:textIsSelectable="true"
             android:layout_marginLeft="10dp"
             android:layout_marginTop="20dp"
             android:textSize="20sp"
             android:textColor="@color/gray"
             android:layout_below="@id/or_text"/>
         <EditText
             android:id="@+id/login_email"
             android:layout_width="320dp"
             android:layout_height="wrap_content"
             android:layout_marginLeft="10dp"
             android:layout_below="@id/sign_in_text"
             android:hint="@string/email_login"
             android:inputType="textEmailAddress"/>
         <EditText
             android:id="@+id/login_password"
             android:layout_width="320dp"
             android:layout_height="wrap_content"
             android:layout_marginLeft="10dp"
             android:layout_below="@id/login_email"
             android:hint="@string/pass_login"
             android:inputType="textPassword"/>
         <TextView
             android:id="@+id/case_sensitive_text"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:textIsSelectable="true"
             android:layout_marginLeft="10dp"
             android:layout_marginTop="20dp"
             android:textSize="18sp"
             android:textColor="@color/gray"
             android:layout_below="@id/login_password"/>
         <CheckBox
             android:id="@+id/remember_login"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:textColor="@color/black"
             android:layout_below="@id/case_sensitive_text"/>
         <Button
             android:id="@+id/sign_in_button"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_below="@id/remember_login"
             android:layout_marginLeft="300dp"/>
         <TextView
             android:id="@+id/forget_password_text"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:textIsSelectable="true"
             android:layout_marginLeft="180dp"
             android:textSize="18sp"
             android:textColor="@color/black"
             android:layout_below="@id/sign_in_button"/>
         <View
            android:id="@+id/horizontal_line"
            android:layout_width="360dp"
            android:layout_marginTop="20dp"
            android:layout_height="1dp"
            android:background="@android:color/darker_gray"
            android:layout_below="@id/forget_password_text"/>
         <TextView
             android:id="@+id/new_app_text"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:textIsSelectable="true"
             android:textSize="18sp"
             android:textColor="@color/black"
             android:layout_below="@id/horizontal_line"/>
         <TextView
             android:id="@+id/create_account_text"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:textIsSelectable="true"
             android:textSize="18sp"
             android:textColor="@color/gray"
             android:layout_below="@id/new_app_text"/>
         <Button
             android:id="@+id/create_account_button"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_below="@id/create_account_text"
             android:layout_marginLeft="250dp"
             android:layout_marginTop="10dp"/>
         <TextView
             android:id="@+id/terms_conditions_text"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:textIsSelectable="true"
             android:textSize="12sp"
             android:textColor="@color/gray"
             android:layout_below="@id/create_account_button"/>
         <TextView
             android:id="@+id/vertical_rule"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:textIsSelectable="true"
             android:textSize="12sp"
             android:textColor="@color/gray"
             android:layout_below="@id/create_account_button"
             android:layout_toRightOf="@id/terms_conditions_text"/>
         <TextView
             android:id="@+id/privacy_policy_text"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:textIsSelectable="true"
             android:textSize="12sp"
             android:textColor="@color/gray"
             android:layout_below="@id/create_account_button"
             android:layout_toRightOf="@id/vertical_rule"/>
</RelativeLayout>

As you can see I'm using Relative Layout and I use dp everywhere and sp for font size.
If you notice on the background of the alert dialog not even the fragments are displaying correct.
You can take a look here: http://imageshack.us/g/692/tvdpi.jpg/
Any suggestions why is this happening?
Thanks in advance.

A: You can create different Drawable folder for  tvdpi images like drawable-tvdpi and drawable-xhdpi is already created if you use eclipse .
Keep diffrent images accourding to their density.
Note also create different layout folder for Nexus7 and  samsung galaxy note .
Example layout-sw600dp for nexus-7 and layout-sw360dpi for Galaxy nexus .
Keep your layout files in both folders.
This will work :)


text:
Q: Can't push view controller while in its own function I made A UIViewController which has a Completion handler function on it because it has to load data from a database, the code for the segue there is :
func S0000 () {

    let V = self.storyboard!.instantiateViewControllerWithIdentifier("V0003") as! V0003

    V.Cv { (Con) -> Void in

        NSOperationQueue.mainQueue().addOperationWithBlock {
            self.showViewController(V, sender: self)
        }
    }
}

This throws the error :
fatal error: unexpectedly found nil while unwrapping an Optional value

How could I make it work and what am I doing wrong.
And just for information I found out that when I run it this way It works but ofcours is not finished loading when pushing to It becuase It pushes before the completion handler returns.
func S0000 () {

    let V = self.storyboard!.instantiateViewControllerWithIdentifier("V0003") as! V0003

self.showViewController(V, sender: self)

    V.Cv { (Con) -> Void in
        NSOperationQueue.mainQueue().addOperationWithBlock {
        }
    }
}

A: Try this
V.Cv { (Con) -> Void in

NSOperationQueue.mainQueue().addOperationWithBlock {
    let V = self.storyboard!.instantiateViewControllerWithIdentifier("V0003") as! V0003
    self.showViewController(V, sender: self)
    }
}


text:
Q: Prime number make negative to positive and 0,1 = not prime My code:
        int n = int.Parse(Console.ReadLine());
        bool result= true;

        if (n < 0)
        {
            n = -n;
        }

        for (int i = 2; i < n; i++)
        {
            if (n % i == 0)
            {
                result = false;
                break;
            }
        }

        if (result)
        {
            Console.WriteLine("Prime");
        }
        else
        {
            Console.WriteLine("Not prime");
        }

So I want to make it when is negative number for example -11 to add 1 more - and make it positive I tried with:
        if (n < 0)
        {
            n = -n;
        }

But it didn't worked as I expect also I need when is 0 or 1 to say Not Prime

A: You have 3 conditions to check:

if n is 0 or 1, not a prime number

if n is 2, prime number

if n is greater than 2, you need to check if they have any divisors (if yes, they are not prime)

int n = int.Parse(Console.ReadLine());
bool result= true;

if (n < 0)
{
    n = -n;
}
if (n<2)
    result = false;
else if (n==2)
    result = true;
else
    for (int i = 2; i < n; i++)
    {
        if (n % i == 0)
        {
            result = false;
            break;
        }
    }

if (result)
{
    Console.WriteLine("Prime");
}
else
{
     Console.WriteLine("Not prime");
}


text:
Q: SequelizeDatabaseError error: column does not exist When I try to create a provider, sequelize apparently is trying to return the provider_id field but it is from the users table and not from the provider (see in sql executed).
In models is defined the relationship by the fields, and I use the same relationship in other tables and works fine, I don't now why this not works.
I'm using postgres db.
Error thrown:

name: 'SequelizeDatabaseError',
parent: error: column "provider_id" does not exist
length: 112,
severity: 'ERROR',
code: '42703',
detail: undefined,
hint: undefined,
position: '186',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_relation.c',
line: '3337',
routine: 'errorMissingColumn',
sql: 'INSERT INTO "providers" ("id","advice_number","created_at","updated_at","company_id") VALUES (DEFAULT,$1,$2,$3,$4) RETURNING "id","advice_number","created_at","updated_at","deleted_at","provider_id","company_id","advice_id";',
parameters: [
'00000000',
'2022-10-06 17:11:28.621 +00:00',
'2022-10-06 17:11:28.621 +00:00',
1
]
},
original: error: column "provider_id" does not exist

User model:
const { Model, DataTypes } = require('sequelize');

class User extends Model {
  static init(sequelize) {
    super.init(
      {
        name: {
          type: DataTypes.STRING,
          allowNull: false,
        },
        email: {
          type: DataTypes.STRING,
          allowNull: false,
        },
        password: {
          type: DataTypes.STRING,
          allowNull: false,
        },
        insuranceNumber: {
          type: DataTypes.STRING,
          allowNull: false,
        },
        phone: {
          type: DataTypes.STRING,
          allowNull: false,
        },
        type: {
          type: DataTypes.STRING,
          allowNull: false,
        },
      },
      {
        scopes: {
          noPassword: {
            attributes: { exclude: ['password'] },
          },
        },
        sequelize,
        paranoid: true,
        tableName: 'users',
      }
    );
  }
  static associate(models) {
    this.hasMany(models.Address, { foreignKey: 'userId', as: 'addresses' });
    this.belongsTo(models.Provider, { foreignKey: 'providerId', as: 'provider' });
    this.belongsTo(models.Customer, { foreignKey: 'customerId', as: 'customer' });
  }
}

module.exports = User;

Provider model:
const { Model, DataTypes } = require('sequelize');

class Provider extends Model {
  static init(sequelize) {
    super.init(
      {
        adviceNumber: {
          type: DataTypes.STRING,
          allowNull: false,
        },
      },
      {
        sequelize,
        paranoid: true,
        tableName: 'providers',
        underscored: true,
      }
    );
  }
  static associate(models) {
    this.belongsTo(models.Company, { foreignKey: 'companyId', as: 'companies' });
    this.belongsTo(models.Advice, { foreignKey: 'adviceId', as: 'advices' });
    this.hasOne(models.User, { foreignKey: 'providerId', as: 'user' });
  }
}

module.exports = Provider;

store function:
async store(req, res) {
    const { name, email, password, insuranceNumber, phone, type } = req.body;
    let { provider} = req.body;

    const { adviceNumber, companyId, adviceId } = provider;
    provider = await Provider.create({ adviceNumber, companyId, adviceId }, { raw: true });

    let user = await User.create(
      {
        name,
        email,
        password,
        insuranceNumber,
        phone,
        type,
        providerId: provider.id ,
      },
      { raw: true }
    );

    return res.json(user);
  }

A: It seems for relations what you have written is not according to your definition
  static associate(models) {
    this.belongsTo(models.Company, { foreignKey: 'companyId', as: 'companies' });
    this.belongsTo(models.Advice, { foreignKey: 'adviceId', as: 'advices' });
    this.hasOne(models.User, { foreignKey: 'providerId', as: 'user' });
  }

in  belongsTo  foreignKey should be of the source table key so it should be from provider table only, you have defined the relation but the keys are not present in the schema definition.

class Provider extends Model {
  static init(sequelize) {
    super.init(
      {
        adviceNumber: {
          type: DataTypes.STRING,
          allowNull: false,
        },
        adviceId: {
          type: DataTypes.STRING,
          allowNull: false,
        },
        companyId: {
          type: DataTypes.STRING,
          allowNull: false,
        },
      },
      {
        sequelize,
        paranoid: true,
        tableName: 'providers',
        underscored: true,
      }
    );
  }
  static associate(models) {
    this.belongsTo(models.Company, { foreignKey: 'companyId', as: 'companies' });
    this.belongsTo(models.Advice, { foreignKey: 'adviceId', as: 'advices' });
    this.hasOne(models.User, { foreignKey: 'providerId', as: 'user' });
  }
}


text:
Q: ESLint: constructors and enum values are reported as unused but they are used in app.ts I have a NodeJS project with Express and TypeScript.
Some of the classes/enums usied in the project are reported by ESLint as unused althought they are used in the project's entrypoint file (app.ts in my case).
For instance,  I have a class defined in handler/RequestHandler.ts as follows:
export class RequestHandler {
    constructor (private readonly manager: Manager) {}
    ...
}

The in the app.ts it is used like this:
 import { RequestHandler } from './handler/RequestHandler'
 //....
 const handler = new RequestHandler(manager)

But when I run linter I get:
/path-to-my-project-root/src/handler/RequestHandler.ts
  5:2  error  Useless constructor  no-useless-constructor

I thought it ignores app.ts but if I break linter rules for app.ts (for instance by adding unneeded spaces) it would report it.
The same happens with enumeration values.
Question: How to make ESLint see constructor/enum usages in the app.ts file?

A: Check out the project FAQ which answers your question:
https://typescript-eslint.io/docs/linting/troubleshooting#i-am-using-a-rule-from-eslint-core-and-it-doesnt-work-correctly-with-typescript-code
Specifically, you're using the wrong lint rule.
https://typescript-eslint.io/rules/no-useless-constructor/


text:
Q: improve performance of custom CartoDB layer visualization with join I am fairly new to CartoDB (which is awesome, btw) and using CartoDB.js to build a custom visualization but the solution I have is quite slow on initial load (takes ~1 minute plus to load), which based on the documentation here I believe is a result of using CTE in my SQL (which I confirmed on their GUI for this map: http://cdb.io/1hL3pzF, much faster without CTE); however I have not seen reference to another approach - does anyone have a good solution for this?
I assume there is a default name assigned to the query (eg in the cartodb.com GUI the associate CartoCSS uses whatever table you started with...) but have not seen reference yet.
Here is a jsfiddle of my working approach, also here:
HTML

CSS
#map { position: absolute; top: 5px; left: 3px; height: 400px; width: 600px; }

JS
    var map = new L.map('map');

/* this works but is quite slow...
what is result of query called from cartodb?
*/
var cartocss = '#summary_tbl{ polygon-fill: #F1EEF6; polygon-opacity: 0.8; line-color: #FFF; line-width: 0.5; line-opacity: 1;}';
cartocss = cartocss + '#summary_tbl [ methane <= 158.47731712611244] { polygon-fill: #91003F; }';
    cartocss = cartocss + '#summary_tbl [ methane <= 135] { polygon-fill: #CE1256; }';
    cartocss = cartocss + '#summary_tbl [ methane <= 120.95519348268839] { polygon-fill: #E7298A; }';
    cartocss = cartocss + '#summary_tbl [ methane <= 112.3529411764706] { polygon-fill: #DF65B0; }';
    cartocss = cartocss + '#summary_tbl [ methane <= 108.42857142857143] { polygon-fill: #C994C7; }';
    cartocss = cartocss + '#summary_tbl [ methane <= 104.09859154929578] { polygon-fill: #D4B9DA; }';
    cartocss = cartocss + '#summary_tbl [ methane <= 98.36206896551724] { polygon-fill: #F1EEF6; }';

var sql_summ = "WITH summary_tbl AS (SELECT avg(n.methane) as methane, count(n.cartodb_id) record_count, h.the_geom_webmercator ";
    sql_summ = sql_summ + "FROM nurve_sample_boston_0828 n JOIN hex_base_v500m h ON ST_Within(n.the_geom, h.the_geom) ";
    sql_summ = sql_summ + "GROUP BY h.the_geom_webmercator) SELECT methane, the_geom_webmercator FROM summary_tbl";

var cbd_layer = {
  user_name: 'crshunter', // Required
  type: 'cartodb', // Required
  sublayers: [{
    sql: sql_summ,
    cartocss: cartocss, // Required
    interactivity: "methane"
  }]
};

$(document).ready(function () {
    map.on('load', function(e){
        // grab OSM basemap for context
        L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(map);
        cartodb.createLayer(map, cbd_layer).addTo(map);
    });
});

var startPosition = new L.LatLng(42.3601, -71.0589); // Boston, MA
map.setView(startPosition, 12);

A: In case helpful for anyone, a much better approach has been to move this function to the backend using the cartodb-nodejs library - silly of me not to do that from the beginning really.


text:
Q: How to get clicked-on filename as argument of shell script triggered by this mouse-click If, in Ubuntu's Nautilus, I click a midi-file, a window opens to specify an application for processing the file. Another option is a "user generated command" (UGC). (Let me choose Ubuntu, Nautilus, midi and bash for example). I know how to play midi files in the terminal using timidity, so I hope I can set up a bash script playmidi (example) for that purpose.

*

*However, I do not know how to get the filename as a script parameter. If possible, this "mouse parameter" should go together with "ordinary" fixed ones for timidity.

*What syntax has to be used in the UGC?

*If UGC space allows, can I insert the timidity command directly, but once more, how do I refer to the file?

A: your script would look something like:
#!/bin/bash
/path/to/timidity "$1"

But, can you right-click the midi file and "open with" timidity instead? Seems simpler.


text:
Q: Creating new record through collection_select rails 4 I am a newbie in ROR and I want to create new record from collection_select if the existing collection does not have the record needed
I tried this solution but it doesn't work for me
Rails' collection_select helper method and the "Create item" option at the end
May be i need to add something to my create controller method


text:
Q: Split multi-month records into individual months I have data in a table in this format - where date range is multi-month:
SourceSink  Class   ShadowPrice Round   Period  StartDate   EndDate
 AEC        Peak    447.038      3     WIN2020  2020-12-01  2021-02-28

I want to create a view/ insert into a new table - the above record broken by month as shown below:
SourceSink  Class   ShadowPrice Round   Period  StartDate   EndDate
 AEC        Peak    447.038      3     WIN2020  2020-12-01  2021-12-31
 AEC        Peak    447.038      3     WIN2020  2021-01-01  2021-01-31
 AEC        Peak    447.038      3     WIN2020  2021-02-01  2021-02-28

Please advise.

A: One option is a recursive query. Assuming that periods always start on the the first day of a month and end on the last day of a month, as shown in your sample data, that would be:
with cte as (
    select t.*, startDate newStartDate, eomonth(startDate) newEndDate
    from mytable t
    union all
    select
        sourceSink,
        class,
        shadowPrice,
        period,
        startDate,
        endDate,
        dateadd(month, 1, newStartDate),
        eomonth(dateadd(month, 1, newStartDate))
    from cte
    where newStartDate < endDate
)
select * from cte

If periods start and end on variying month days, then we need a little more logic:
with cte as (
    select
        t.*,
        startDate newStartDate,
        case when eomonth(startDate) <= endDate then eomonth(startDate) else endDate end newEndDate
    from mytable t
    union all
    select
        sourceSink,
        class,
        shadowPrice,
        period,
        startDate,
        endDate,
        dateadd(month, 1, datefromparts(year(newStartDate), month(newStartDate), 1)),
        case when eomonth(dateadd(month, 1, datefromparts(year(newStartDate), month(newStartDate), 1))) <= endDate
            then eomonth(dateadd(month, 1, datefromparts(year(newStartDate), month(newStartDate), 1)))
            else endDate
        end
    from cte
    where datefromparts(year(newStartDate), month(newStartDate), 1) < endDate
)
select * from cte

A: Just another option using a CROSS APPLY and an ad-hoc tally table
Example
Select A.[SourceSink]
      ,A.[Class]
      ,A.[ShadowPrice]
      ,A.[Round]
      ,A.[Period]
      ,B.[StartDate]
      ,B.[EndDate]
 From YourTable A
 Cross Apply (
                Select StartDate=min(D)
                      ,EndDate  =max(D)
                  From (
                         Select Top (DateDiff(DAY,[StartDate],[EndDate])+1)
                                D=DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),[StartDate])
                          From  master..spt_values n1,master..spt_values n2
                       ) B1
                  Group By Year(D),Month(D)
             ) B

Returns


text:
Q: Ingresar caracteres de forma continua en la terminal sin necesidad de pulsar Enter Me gustaría crear un programa que fuese leyendo caracteres introducidos por el usuario pero de forma continua, sin tener que pulsar Enter cada vez que meto uno y que pare de leer, por ejemplo, al introducir un '.'
Algo así como:
palabra = []

while True:
    letra = input()
    if letra == '.':
        break
    else:
        palabra.append(letra)

A: Ni input ni sys.stdout.read te van a valer para leer carácter a carácter sin el debido EOL. Para esto vas a tener que trabajar a más bajo nivel con la terminal de turno. En Windows puedes usar el módulo msvcrt y las funciones getch, getche, getwch y getwche:
import msvcrt

palabra = []

while True:
    letra = msvcrt.getwche()
    if letra == '.':
        break
    else:
        palabra.append(letra)

print("\n" + "".join(palabra))

En POSIX puedes usar termios:
import os
import sys
import termios

file_descriptor = sys.stdin.fileno()
old = termios.tcgetattr(file_descriptor)
new = old[:]

palabra = []

try:
    new[3] &= ~(termios.ICANON | termios.ECHOCTL)
    termios.tcsetattr(file_descriptor, termios.TCSADRAIN, new)

    while True:
        letra = sys.stdin.read(1)
        if letra == '.':
            break
        else:
            palabra.append(letra)
finally:
    termios.tcsetattr(file_descriptor, termios.TCSADRAIN, old)

print("\n" + "".join(palabra))

En ambos casos el carácter es impreso cuando se ingresa, aunque podemos hacer que no sea así si lo deseamos:

*

*En Windows cambiar msvcrt.getwche por msvcrt.getwch.

*En POSIX cambiar la línea:
  new[3] &= ~(termios.ICANON | termios.ECHOCTL)

por:
  new[3] &= ~(termios.ICANON | termios.ECHO)

Nota: El script a de ejecutarse en la terminal del sistema directamente. Normalmente no va a funcionar en la terminal o intérprete interactivo del IDE de turno.


text:
Q: Textbox not getting updated in for loop I have a for loop in my WPF. The textbox does not get updated until the loop has finished.
My code:
for (int i = 0; i < 10; i++)
{
    Thread.Sleep(1500);
    // MessageBox.Show(i.ToString());
    updateTextBox(i);
}

Update function:
private void updateTextBox(int i)
{
    // MessageBox.Show("reached here:" + i.ToString());
    txtExecLog.AppendText("\n" + i.ToString());
 }

If I uncomment the messagebox text, it updates one by one, otherwise it updates after 15 secs (1.5*10) the textbox with all the values.

A: You're blocking the UI thread when you sleep. You mustn't do that - nothing can be processed on the UI thread while you're sleeping. If you want to take an action periodically (on the UI thread) use DispatcherTimer.

A: You are running your loop in the UI thread. When you call Thread.Sleep() the UI thread sleeps and therefore the textbox can't be updated before end of the UI thread blocking for loop.


text:
Q: php ajax autocomplete - exact matches are missing I have a simple PHP/MySQL/Ajax Autocomplete app, which is showing available addresses while the user is typing (as google maps does).
Application works and shows the results

Once the user starts adding property number, results are changing (e.g. 260 and 269 are gone)

and if the user add additional number, there is only 1 result (numbers 270-277 are gone)

Query in PMA (records exists)

and here is my code for getting the data from DB
        $search_param = "%{$this->text}%";

        $query = 'SELECT * FROM (SELECT * FROM '.$this->table.' WHERE address like ?) AS x LIMIT 5,5';

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1,$search_param);
        $stmt->execute();

and then save the result in array
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                extract($row);
                $address_item = array(
                    'address' => $address
                );

            //Push the data
            array_push($address_arr['data'], $address_item);

            }

A: Try this query:
$query = 'SELECT * FROM (SELECT * FROM '.$this->table.' WHERE address like ?) AS x LIMIT 0,5';


text:
Q: simple 2d animation in glut I have an assignment to do, but i can't seem to trully comprehend it.
The assignment is as follows : Adding a texture to background (solar system), adding texture to 2 objects (drawn shapes) and adding an animation where the two objects have to bounce from eachother & from far walls (as in end of screen).
I have managed to do everything except the animation.
How can I do this kind of animation?
p.s. animation in there is the best i could come up with.
#include <gl/glut.h>
#include <gl/gl.h >
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

float x;
float y;

unsigned char *imageData;
int imageRows, imageCols;

extern void loadBMP(char *);
char cotton1[] = "cotton1.bmp";
char cotton2[] = "cotton2.bmp";
char fons[] = "solar.bmp";

GLuint texture[3];
float cube[1], Vcube[1];

/* GLUT callback Handlers */

void init()
{
cube[0]=0;
Vcube[0]=0.01;
cube[1]=0;
Vcube[1]=0.01;

glShadeModel(GL_SMOOTH);

glGenTextures( 3, &texture[0] );

   loadBMP(cotton1);
   glBindTexture( GL_TEXTURE_2D, texture[0] );
   glTexImage2D(GL_TEXTURE_2D, 0, 3, imageCols, imageRows,
         0, GL_RGB, GL_UNSIGNED_BYTE, imageData);

   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

     loadBMP(cotton2);
   glBindTexture( GL_TEXTURE_2D, texture[1] );
   glTexImage2D(GL_TEXTURE_2D, 0, 3, imageCols, imageRows,
         0, GL_RGB, GL_UNSIGNED_BYTE, imageData);

   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

        loadBMP(fons);
   glBindTexture( GL_TEXTURE_2D, texture[2] );
   glTexImage2D(GL_TEXTURE_2D, 0, 3, imageCols, imageRows,
         0, GL_RGB, GL_UNSIGNED_BYTE, imageData);

   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

}

static void
resize(int width, int height)
{
    const float ar = (float) width / (float) height;

    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity() ;
}

static void
idle(void)
{
    glutPostRedisplay();
}

void animation()
{
cube[1]+=Vcube[1];
if (cube[1]<0.1)
{ Vcube[1]+=Vcube[1]; }
if (cube[1]>0.095)
{ Vcube[1]=-0.01; }
if (cube[1]<0)
{ Vcube[1]=+0.01; }

glTranslatef(cube[1],0,0);
       Sleep(100);
       glutPostRedisplay();
}

void animation2()
{
  cube[0]+=Vcube[0];
if (cube[0]<(-0.1))
{ Vcube[0]-=0.01; }
if (cube[0]>0)
{ Vcube[0]-=0.01; }
if (cube[0]<0.1)
{ Vcube[0]+=0.01; }

glTranslatef(cube[0],0,0);
       Sleep(100);
       glutPostRedisplay();
}

void display() {

    glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);

//Background
    glLoadIdentity();
    glBindTexture( GL_TEXTURE_2D, texture[2]);
    glEnable( GL_TEXTURE_2D );

    glPushMatrix();
     glBegin( GL_QUADS );
      glTexCoord2f(1.0,1.0); glVertex2f(-1.0,1.0);
      glTexCoord2f(0.0,1.0); glVertex2f(1.0,1.0);
      glTexCoord2f(0.0,0.0); glVertex2f(1.0,-1.0);
      glTexCoord2f(1.0,0.0); glVertex2f(-1.0,-1.0);
      glEnd();
      glPopMatrix();
    glDisable(GL_TEXTURE_2D);

  animation();

//TEXTURE 1
    glBindTexture( GL_TEXTURE_2D, texture[0]);

    glEnable( GL_TEXTURE_2D );

    glPushMatrix();
    glBegin( GL_TRIANGLE_FAN );
glTexCoord2f(0.5f, 0.5f);  glVertex2f(  0.5f,  0.0f);   //center
glTexCoord2f(1.0f, 0.5f);  glVertex2f(  0.8f+x,  0.0f);   //right
glTexCoord2f(0.75f, 1.0f); glVertex2f(  0.55f+x, 0.3f+x);  //top right
glTexCoord2f(0.25f, 1.0f); glVertex2f(  0.35f-x, 0.3f+x);   //Top left
glTexCoord2f(0.0f, 0.5f);  glVertex2f(  0.25f-x, 0.0f);   //left
glTexCoord2f(0.25f, 0.0f); glVertex2f(  0.45f-x,-0.3f-x);   //bottom left
glTexCoord2f(0.75f, 0.0f); glVertex2f(  0.7f+x, -0.2f-x);   //bottom right
glTexCoord2f(1.0f, 0.5f);  glVertex2f(  0.8f+x,  0.0f);   //right
      glEnd();
      glPopMatrix();
    glDisable(GL_TEXTURE_2D);
//TEXTURE 2

    animation2();
    glBindTexture( GL_TEXTURE_2D, texture[1]);

    glEnable( GL_TEXTURE_2D );
    glPushMatrix();
    glBegin( GL_TRIANGLE_FAN );
glTexCoord2f(0.5f, 0.5f);  glVertex2f( -0.5f,  0.0f);  //center
glTexCoord2f(1.0f, 0.5f);  glVertex2f( -0.2f+y,  0.0f);  //right
glTexCoord2f(0.75f, 1.0f); glVertex2f( -0.4f+y,  0.2f+y);  //top right
glTexCoord2f(0.25f, 1.0f); glVertex2f( -0.7f-y,  0.1f+y);  //Top left
glTexCoord2f(0.0f, 0.5f);  glVertex2f( -0.8f-y,  0.0f);  //left
glTexCoord2f(0.25f, 0.0f); glVertex2f( -0.7f-y, -0.1f-y);  //bottom left
glTexCoord2f(0.75f, 0.0f); glVertex2f( -0.3f+y, -0.2f-y);  //bottom right
glTexCoord2f(1.0f, 0.5f);  glVertex2f( -0.2f+y,  0.0f);  //right
      glEnd();
      glPopMatrix();
    glDisable(GL_TEXTURE_2D);
glutSwapBuffers();
glFlush();
}

static void
key(unsigned char key, int a, int b)
{
    switch (key)
    {
        case 27 :
        case 'q':
            exit(0);
            break;

        case '+':
             if ((x+0.01)<0.98)
             x=x+0.01;
             if ((y+0.01)<0.98)
             y=y+0.01;
            break;

        case '-':
             if ((x-0.1)>(-0.15))
                x=x-0.01;
             if ((y-0.1)>(-0.10))
                y=y-0.01;
           break;

        case 'o':
             if ((x+0.01)<0.98)
             x=x+0.01;
             break;
        case 'p':
             if ((x-0.1)>(-0.15))
             x=x-0.01;
             break;

        case '[':
             if ((y+0.01)<0.98)
             y=y+0.01;
             break;
        case ']':
             if ((y-0.1)>(-0.10))
             y=y-0.01;
             break;

    }
    glutPostRedisplay();
}

int main(int argc, char *argv[]) {
   glutInit(&argc, argv);

   glutInitWindowSize(640, 640);
   glutInitWindowPosition(50, 50);
   glutCreateWindow("Assignment number 3");
   glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);

   glutReshapeFunc(resize);
   glutDisplayFunc(display);
   glutKeyboardFunc(key);
   glutIdleFunc(idle);

   glClearColor(1.0, 1.0, 1.0, 1.0);

   init();

   glutMainLoop();
   return EXIT_SUCCESS;
}

A: Problem 1: You mistake OpenGL for a scene graph. Take your animation1 function for example:
void animation2(
     )
{
    cube[0] += Vcube[0];
    if( cube[0] < ( -0.1 ) ) {
        Vcube[0] -= 0.01;
    }
    if( cube[0] > 0 ) {
        Vcube[0] -= 0.01;
    }
    if( cube[0] < 0.1 ) {
        Vcube[0] += 0.01;
    }

    glTranslatef( cube[0], 0, 0 );
    Sleep( 100 );
    glutPostRedisplay(  );
}

That glTranslatef there at the end will just trash around on whatever matrix is currently active in the OpenGL context. That's not how to do it.
Next problem: You're calling the animation functions from the drawing code. At the point of drawing all the scene state should be determined. Also, calling that animation function will sleep in your display function. That's not how to do it.
Okay, what to do: First put all the animation progressor functions into the idle loop. Don't sleep, instead measure the time between animation iterations and advance the animation accordingly. Don't call glutPostRedisplay in the animation functions. At the end of the idle handler yes, but not in the animators. In the drawing code use the evaluated animation state to place objects accordingly. Use the matrix stack (glPushMatrix, glPopMatrix) to keep things nicely separated.

#include <GL/glut.h>

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/* for gettimeofday */
#include <sys/time.h>

/* In general, littering your program with global variables should be avoided.
 * I admit, that sometimes even I don't adhere to this rule, and especially
 * using GLUT it takes to jump several very arcane hoops to avoid it.
 * So in this case, yes, having global variables is in order.
 *
 * The principle idea of global variables is to put data into them, that is
 * valid and the same for the whole of the program. More importantly they
 * must not be used to pass around data.
 *
 * It's also a good idea to make those variables static, so that they are
 * contained withing this compilation unit.
 */
static float x;
static float y;

/* This is not how globals should be used. They're used to pass data around between
 * functions. DON'T DO THAT!
 *
 * Also this misses the extern keyword. Unless the compilation unit loading the
 * bmp files declares those being extern, hence relying on another compilation unit
 * to expose them like this, this code is likely to break.

unsigned char *imageData;
int imageRows, imageCols;

extern void loadBMP(char *);

 * BTW: You don't need the extern keyword here.

 * Instead have a nice little function that loads a BMP file and puts it into a
 * newly allocated texture object.
*/

GLuint loadBmpToTexture(char const * const filename)
{
    /* Implementation of this left as an exercise to the reader */
    return 0;
}

static double ftime(void)
{
    /* Now this is a bit complicated: There's no portable high resolution
     * timer function. On Linux and Unices (hence also MacOS X) you have
     * gettimeofday, on Windows there are the High Performance Counters.
     * ... Totally annoying.
     * Look here for a comparison:
     * http://www.songho.ca/misc/timer/timer.html
     *
     * Since I'm on a Linux box this is using gettimeofday
     */

    struct timeval t;
    gettimeofday(&t, NULL);

    return 1.0*t.tv_sec + 1e-6*t.tv_usec;
}

/* In this variable we store the time of the last iteration of the animation
 * loop to determine the time to time difference for the next one. */
static double last_T;

/* Actually those should be of type char const * const
 * This is one of the finer details of C. The arrays like you've declared them
 * here are mutable, but of constant size.
 * However you normally don't want string constant be like this. The preferred
 * modus operandi is to have the string constants in read only memory and pointers
 * to them. Like this:
 */
char const * const cotton1 = "cotton1.bmp";
char const * const cotton2 = "cotton2.bmp";
char const * const fons = "solar.bmp";

/* Okay, now consider what would happen if you had several objects, not just two or
 * three? How would you keep track of all those indices? Really, that's bad style.
 * If you've data belonging together, like state of an object, put it into a struct
 * and then also use useful variable names.
 */

GLuint texture_background;

typedef struct s_Cube {
    float x, V_x;
    GLuint texture;
} Cube;

/* also we can statically initialize here */
Cube cube[2] = {
    {-0.05, 0.01, 0},
    {0.05, -0.02, 0}
};

/* GLUT callback Handlers */

static void init(void)
{
    /* loadBmpToTexture is defined to return 0 in case of failure
     * which is also the OpenGL default texture object, so this
     * fails safely. */
    texture_background = loadBmpToTexture(fons);
    cube[0].texture = loadBmpToTexture(cotton1);
    cube[1].texture = loadBmpToTexture(cotton2);

    glClearColor( 0.0, 0.5, 0.7, 1.0 );

    last_T = ftime();
}

static void animation(
    float const speed
     )
{
    /* The objective is to let the cubes bounce into each other
     * (collision) and with the walls. First the collision: */

    if( cube[0].x > cube[1].x && cube[0].V_x > 0 && cube[1].V_x < 0 ) {
        /* cubes bounced off each other. Exchange their velocities */
        double const V_x = cube[0].V_x;
        cube[0].V_x = cube[1].V_x;
        cube[1].V_x = V_x;

        double const x = cube[0].x;
        cube[0].x = cube[1].x;
        cube[1].x = x;
    }

    /* and the wall bounce */
    if( cube[0].x < -0.1 && cube[0].V_x < 0 ) {
        /* left cube bounced into left wall */
        cube[0].V_x *= -1;
    }

    if( cube[1].x > 0.1 && cube[1].V_x > 0 ) {
        /* right cube bounced into left wall */
        cube[1].V_x *= -1;
    }

    cube[0].x += speed * cube[0].V_x;
    cube[1].x += speed * cube[1].V_x;
}

/* Ideally we'd use a precise animation loop interleaved with event processing here.
 * Unfortunately GLUT doesn't offer those, so we use this arcane kludge.
 *
 * It would get a bit more robust by putting the whole timing into the display function
 * but better abandon GLUT and get a true event loop.
 */
static void idle(
    void )
{
    const double now_T = ftime();
    const double delta_T = now_T - last_T;
    last_T = now_T;

    const double speed = delta_T * 60;

    animation( speed );
    glutPostRedisplay(  );
}

static void display(void)
{
    /* We try to be as stateless as possible. Yes, in the face of a statefull
     * API, like OpenGL, this may sound a bit pedantic. */
    const int width = glutGet(GLUT_WINDOW_WIDTH);
    const int height = glutGet(GLUT_WINDOW_HEIGHT);
    const float ar = ( float ) width / ( float ) height;

    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    /* It's really best practice to set everything related to drawing
     * – and that includes the projection – in the drawing function */
    glViewport( 0, 0, width, height );
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    glOrtho(-ar, ar, -1, 1, -1, 1);

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
//Background
    if(texture_background) {
        glBindTexture( GL_TEXTURE_2D, texture_background );
        glEnable( GL_TEXTURE_2D );
        glBegin( GL_QUADS );
        glTexCoord2f( 1.0, 1.0 );
        glVertex2f( -1.0, 1.0 );
        glTexCoord2f( 0.0, 1.0 );
        glVertex2f( 1.0, 1.0 );
        glTexCoord2f( 0.0, 0.0 );
        glVertex2f( 1.0, -1.0 );
        glTexCoord2f( 1.0, 0.0 );
        glVertex2f( -1.0, -1.0 );
        glEnd();
        glDisable( GL_TEXTURE_2D );
    }

//TEXTURE 1
    glBindTexture( GL_TEXTURE_2D, cube[1].texture );
    glEnable( GL_TEXTURE_2D );
    /* Remember we're still in modelview matrix mode.
     * This push creates a copy of the currently modelview matrix,
     * for our disposal. With a following pop we restore to the
     * state saved now. Pushes and Pops nest. */
    glPushMatrix();

    /* This applies our animation position to the modelview matrix.
     * All geometry drawing to follow is subject to this additional
     * transformation, until the matrix changes again. */
    glTranslatef(cube[1].x, 0, 0);
    glBegin( GL_TRIANGLE_FAN );
    glTexCoord2f( 0.5f, 0.5f );
    glVertex2f( 0.5f, 0.0f );   //center
    glTexCoord2f( 1.0f, 0.5f );
    glVertex2f( 0.8f + x, 0.0f );   //right
    glTexCoord2f( 0.75f, 1.0f );
    glVertex2f( 0.55f + x, 0.3f + x );  //top right
    glTexCoord2f( 0.25f, 1.0f );
    glVertex2f( 0.35f - x, 0.3f + x );  //Top left
    glTexCoord2f( 0.0f, 0.5f );
    glVertex2f( 0.25f - x, 0.0f );  //left
    glTexCoord2f( 0.25f, 0.0f );
    glVertex2f( 0.45f - x, -0.3f - x ); //bottom left
    glTexCoord2f( 0.75f, 0.0f );
    glVertex2f( 0.7f + x, -0.2f - x );  //bottom right
    glTexCoord2f( 1.0f, 0.5f );
    glVertex2f( 0.8f + x, 0.0f );   //right
    glEnd(  );
    glPopMatrix(  );
    glDisable( GL_TEXTURE_2D );
//TEXTURE 2
    /* in the original code you didn't use the other texture,
     * Probably because you lost track of variables and indices. */
    glBindTexture( GL_TEXTURE_2D, cube[0].texture );
    glEnable( GL_TEXTURE_2D );
    glPushMatrix();
    glTranslatef(cube[0].x, 0, 0);
    glBegin( GL_TRIANGLE_FAN );
    glTexCoord2f( 0.5f, 0.5f );
    glVertex2f( -0.5f, 0.0f );  //center
    glTexCoord2f( 1.0f, 0.5f );
    glVertex2f( -0.2f + y, 0.0f );  //right
    glTexCoord2f( 0.75f, 1.0f );
    glVertex2f( -0.4f + y, 0.2f + y );  //top right
    glTexCoord2f( 0.25f, 1.0f );
    glVertex2f( -0.7f - y, 0.1f + y );  //Top left
    glTexCoord2f( 0.0f, 0.5f );
    glVertex2f( -0.8f - y, 0.0f );  //left
    glTexCoord2f( 0.25f, 0.0f );
    glVertex2f( -0.7f - y, -0.1f - y ); //bottom left
    glTexCoord2f( 0.75f, 0.0f );
    glVertex2f( -0.3f + y, -0.2f - y ); //bottom right
    glTexCoord2f( 1.0f, 0.5f );
    glVertex2f( -0.2f + y, 0.0f );  //right
    glEnd();
    glPopMatrix();
    glDisable( GL_TEXTURE_2D );

    glutSwapBuffers();
    /* Your glFinish here was totally pointless.
     * First it would belong _before_ glutSwapBuffers.
     * Second glutSwapBuffers implies a glFinish, so it's totally redundant. */
}

static void key(
    unsigned char key,
    int a,
    int b )
{
    switch ( key ) {
    case 27:
    case 'q':
        exit( 0 );
        break;

    case '+':
        if( ( x + 0.01 ) < 0.98 )
            x = x + 0.01;
        if( ( y + 0.01 ) < 0.98 )
            y = y + 0.01;
        break;

    case '-':
        if( ( x - 0.1 ) > ( -0.15 ) )
            x = x - 0.01;
        if( ( y - 0.1 ) > ( -0.10 ) )
            y = y - 0.01;
        break;

    case 'o':
        if( ( x + 0.01 ) < 0.98 )
            x = x + 0.01;
        break;
    case 'p':
        if( ( x - 0.1 ) > ( -0.15 ) )
            x = x - 0.01;
        break;

    case '[':
        if( ( y + 0.01 ) < 0.98 )
            y = y + 0.01;
        break;
    case ']':
        if( ( y - 0.1 ) > ( -0.10 ) )
            y = y - 0.01;
        break;
    }
    glutPostRedisplay();
}

int main(
    int argc,
    char *argv[] )
{
    glutInit( &argc, argv );

    glutInitWindowSize( 640, 640 );
    glutInitWindowPosition( 50, 50 );
    /* glutInitDisplayMode must be called before calling glutCreateWindow
     * GLUT, like OpenGL is stateful */
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH );
    glutCreateWindow( "Assignment number 3" );

    glutDisplayFunc( display );
    glutKeyboardFunc( key );
    glutIdleFunc( idle );

    init();

    glutMainLoop(  );
    return EXIT_SUCCESS;
}


text:
Q: Rename php.ini.default to the more recognizable and standardized php.ini When I type command:
mv /etc/php.ini.default /etc/php.ini

I get:
bash-3.2# mv /etc/php.ini.default /etc/php.ini
mv: /etc/php.ini.default: No such file or directory

Why cannot I rename php by command mv?

A: What is the output of ls /etc/?
The message tells you, that there is no such file as /etc/php.ini.default.
mv can definitely do what you want, the problem seems to be something different.


text:
Q: How to color individual boxes of an echarts boxplot based on function How do I color each boxes individually in an echarts box-plot based on a function?
The following function works on a simple bar chart and colors the bars appropriately:
series: [{
    data: [120, 200, 150, 80, 70, 110, 130],
    type: 'bar',
    showBackground: true,
    itemStyle: {
        color: function(seriesIndex) {
            return ProfessionColor[seriesIndex.name.split("_", 1).toString()]
        },
    },
}]

However, it does not work on a box-plot:
series: [{
        name: 'boxplot',
        type: 'boxplot',
        datasetIndex: 1,
        itemStyle: {
            color: function(seriesIndex) {
                return ProfessionColor[seriesIndex.name.split('_', 1)];
            }
        },
        encode: {
            tooltip: [1, 2, 3, 4, 5]
        }
    },
    {
        name: 'outlier',
        type: 'scatter',
        encode: {
            x: 1,
            y: 0
        },
        datasetIndex: 2
    }
]

If I provide color: "red" rather than a function all boxes are colored red.  This leads me to believe that it needs to happen in the transform.config which I can't find in the documents or tutorial.
Echarts Box-Plot currently
The link is the complete charts in its current form.

A: This will not get you all the way, but if you add colorBy: "data" to your options and remove the itemStyle, it will look like this:

A: Apparently, echarts only allows scripting (i.e., using a function for) either the line color -- option itemStyle.borderColor or the fill color -- option itemStyle.color.
The difference between the two appears to be made by the value of the internal property BoxplotSeriesModel#visualDrawType. It is now set to "stroke", which means that borderColor can be set via a function.
Since you wanted to set the fill color, its value should be set to "fill". I searched a way to change that property - it was rather difficult for echarts don't document an API for extensions. Still, navigating the source code I came up with this hacky solution:
const BoxplotSeriesModel = echarts.ComponentModel.getClassesByMainType('series').find(cls=>cls.type==='series.boxplot');
const BoxplotSeriesModelFill = function(...args){
    const _this = new BoxplotSeriesModel(...args);
    _this.visualDrawType = 'fill';
    return _this;
}
BoxplotSeriesModelFill.type = BoxplotSeriesModel.type;
echarts.ComponentModel.registerClass(BoxplotSeriesModelFill);

That's a "patch" to be applied at the beginning of your script, immediately after you have the echarts global defined.
Here's a forked version of your code that uses that patch. The only other change I made was to set a borderColor (can now only be a fixed value) to black.


text:
Q: Would the One Ring created by Sauron make a mortal creature immortal? The One Ring extended Gollum/Sméagol's life and vitality by 478 years and Bilbo's vitality by 60 years. Did it have the power to make them truly immortal if they had kept it, or did it just grossly slow down the aging process? The ring was made by a Maia for a Maia (spirit), not a mortal.

A: Immortality in Tolkien is very different to not dying.
To be immortal means that your spirit is bound to the world, the Music of the Ainur is as fate to it, and it does not leave the world until the end of the world, beyond which its not known what happens to it.

The doom of the Elves is to be immortal, to love the beauty of the world, to bring it to full flower with their gifts of delicacy and perfection, to last while it lasts, never leaving it even when 'slain', but returning – and yet, when the Followers come, to teach them, and make way for them, to 'fade' as the Followers grow and absorb the life from which both proceed. (Letter 131)

To be mortal means that your spirit is not bound to the world, it can shape it's own destiny beyond the Music, but it must die and leave the world after a short time; beyond the end of the world it is destined to take part in the Second Music of the Ainur.

Therefore he willed that the hearts of Men should seek beyond the world and should find no rest therein; but they should have a virtue to shape their life, amid the powers and chances of the world, beyond the Music of the Ainur, which is as fate to all things else ... It is one with this gift of freedom that the children of Men dwell only a short space in the world alive, and are not bound to it, and depart soon whither the Elves know not ... Yet of old the Valar declared to the Elves in Valinor that Men shall join in the Second Music of the Ainur; whereas Ilúvatar has not revealed what he purposes for the Elves after the Worlds end ... (Silmarillion, Of the Beginning of Days)

Tolkien is quite clear in several places that only Eru can change a being from mortal to immortal or vice-versa, for example:

Immortality and Mortality being the special gifts of God to the Eruhini (in whose conception and creation the Valar had no part at all) it must be assumed that no alteration of their fundamental kind could be effected by the Valar even in one case: the cases of Lúthien (and Túor) and the position of their descendants was a direct act of God. (Letter 153)

Therefore the One Ring is quite incapable of making a mortal creature become immortal.
This can be seen in Gandalf's words to Frodo concerning the effects of the Rings on mortals in Shadow of the Past (my emphasis):

A mortal, Frodo, who keeps one of the Great Rings, does not die, but he does not grow or obtain more life, he merely continues, until at last every minute is a weariness.

And is completely consistent with statements elsewhere, for example the following footnote to Letter 131:

The view is taken (as clearly reappears later in the case of the Hobbits that have the Ring for a while) that each 'Kind' has a natural span, integral to its biological and spiritual nature. This cannot really be increased qualitatively or quantitatively; so that prolongation in time is like stretching a wire out ever tauter, or 'spreading butter ever thinner' – it becomes an intolerable torment.

A mortal who uses the Ring is therefore still a mortal: merely one who's lifespan has been prolonged (indefinitely and intolerably), but they are still subject to the fate of mortals, which remains completely unchanged.

A: A mortal wearing a ring of power does not age, nor can he die of natural means (Gandalf says this in FOTR when he tells Frodo of the rings of power)
For evidence see the Nazgul, who were men that lived in the middle centuries of the 2nd age, they survived until the end of the 3rd age after being gifted rings of power, a period of around 4-5 thousand years.
Also see Gollum who lived 500 years after taking the ring.
However, whether the rings were capable of immortality without corruption is debatable, I find it hard to believe that the rings were ever created with the intention of corrupting men to evil (Sauron was involved in their creation (except the 3 elven rings)) but I think that it was the creation of the One that corrupted the mortals wearing the rings.
That said the dwarves were originally made by Aule to be resistant to corruption and the devices of Melkor, and as such they resisted the rings more than men, and did not recieve immortality from them. However the Dwarven rings corrupted them with their specific weakness (Gold lust).
Finally any mortal wearing a ring could still be killed, and regardless of how long they lived and their power they would still go to their respective fate. Men (hobbits as well) would go to "Mans Doom" and leave Arda, and Dwarves would be gathered by Mandos.
The fact that a man with a ring of power can be killed is evidenced in several places:

*

*Isildur's death at the Gladden Fields

*Deagol's death in the same place

*Gollum's death in Mt.Doom

*Angmar's death at the battle of the Pelennor Fields

So in answer to your question:

*

*Men with a ring of power do not age

*Men with a ring of power can be killed

*Dwarves with a ring of power age normally

*Maia and Elves are of course immortal anyway and therefore Rings have no effect in that regard.


text:
Q: How to use Android ViewPager I'm planning a port of some apps from Windows Phone 7 over to Android.  Going through some blogs I find an "extra" android control called the ViewPager which seems like a poor man's version of the WP7 Pivot control.  I would like to try using this control since my WP7 apps use the Pivot.
I plan on targeting Android 2.3.3 (API 10) because the info at http://developer.android.com/resources/dashboard/platform-versions.html tells me that any level higher would run on relatively few phones.  So, my Eclipse is setup for that level.
Using the Eclipse SDK manager I tried to add the Extras Android support package but it would not add giving the errors pasted below.  I don't know what all those errors mean but I'm wondering if I need to be running API 11 to be able to use the compatibiity package aka the android Support Package?
So, I suppose my final question is: can I use the VeiwPager control if I target Android 2.3.3?  Also, is there any downloadable complete solution that uses the viewPager?  All I can find are "tutorials" that show code snippets.
Thanks,
Dean
Preparing to install archives
Downloading Android SDK Platform-tools, revision 11
File not found: C:\Program Files (x86)\Android\android-sdk\temp\platform-tools_r11-windows.zip (Access is denied)
Downloading Documentation for Android SDK, API 15, revision 2
File not found: C:\Program Files (x86)\Android\android-sdk\temp\docs-15_r02.zip (Access is denied)
Downloading SDK Platform Android 4.0.3, API 15, revision 3
File not found: C:\Program Files (x86)\Android\android-sdk\temp\android-15_r03.zip (Access is denied)
Downloading Samples for SDK API 15, revision 2
File not found: C:\Program Files (x86)\Android\android-sdk\temp\samples-15_r02.zip (Access is denied)
Downloading ARM EABI v7a System Image, Android API 15, revision 2
File not found: C:\Program Files (x86)\Android\android-sdk\temp\sysimg_armv7a-15_r02.zip (Access is denied)
Downloading Sources for Android SDK, API 15, revision 2
File not found: C:\Program Files (x86)\Android\android-sdk\temp\sources-15_r02.zip (Access is denied)
Downloading Android Support package, revision 8
File not found: C:\Program Files (x86)\Android\android-sdk\temp\support_r08.zip (Access is denied)
Skipping 'Android SDK Tools, revision 19'; it depends on 'Android SDK Platform-tools, revision 11' which was not installed.
Done. Nothing was installed.

A:
I'm wondering if I need to be running API 11 to be able to use the compatibiity package aka the android Support Package?

No.

can I use the VeiwPager control if I target Android 2.3.3?

Yes.

Also, is there any downloadable complete solution that uses the viewPager?

Here is a small sample app showing 10 EditText widgets, one per page, in a ViewPager.
Here is a more complex app, implementing a digital book reader, with one chapter (in a WebView) per page in a ViewPager, but it might not make much sense outside the context of one of my books.
With respect to your errors, my guess is that you installed the Android SDK via the self-installing .EXE file, in which case you will need to run the SDK Manager with Administrator privileges to update it, IIRC.

A: To elaborate on Mark's point a little: in your AndroidManifest.xml, you should put this line:
    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" />

Where 15 may be replaced by whatever is the newest API level at the time you compile, and 8 is the lowest API level you want to run on.  As of this writing, API level 8 (Froyo) and higher will let you target about 94% of the device population.
The Android Support Package (V4) lets you call a bunch of useful functions all the way back to API level 4, including ViewPager.  Try building the Suport4Demos sample app; it includes a nice ViewPager implementation.  To do that, in Eclipse, select: New > Android Sample Project > Android 4.0.3 > Support4Demos > Finish.  Then build & run the project.


text:
Q: Log4j2 not logging to file I'm using Log4j2 in my application and it seems to load and initialize fine.
Console gets logged to, the 2 specified file appenders create their respective files, but those files stay empty!
Is my config faulty? Did I start Log4j2 the wrong way?
Here's the config:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="TRACE">
    <Appenders>
        <File name="file" fileName="${sys:logdir}ftm.log">
            <PatternLayout pattern="%d{MM.dd.yyyy HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
        <File name="file_error" fileName="${sys:logdir}ftm_error.log">
            <PatternLayout pattern="%d{MM.dd.yyyy HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{MM.dd.yyyy HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Root level="ALL">
            <AppenderRef ref="file" level="ALL"/>
            <AppenderRef ref="STDOUT" level="ALL"/>
        </Root>
        <Logger name="FTM" level="ALL" additivity="true">
            <AppenderRef ref="file_error" level="ERROR"/>
        </Logger>
    </Loggers>
</Configuration>

And here's the code:
LoggerContext contextLogging = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);

File file = new File("log4j2.xml");
if (file != null && file.isFile() && file.canRead()){
    contextLogging.setConfigLocation(file.toURI());
}

I start logging at various points throughout the application after this initialization bit.

A: I suspect your call to obtain the LoggerContext is causing Log4j to initialize. You should see a message saying the default configuration is being used. Why not just use one of the Configurator.initialize() methods?

A: Maybe LOG4J2 is buffering your log messages and will write them later.
Have you tried shutting down your app server?
This will force any buffered messages to be written to the file.


text:
Q: Euclidean algorithm for greatest common divisor Using the euclidean algorithm for $\gcd(121, 330)$, how many divisions are required for the process?

A: This in Mathematica will give you the number of subtractions needed:
gcd[a_, b_] := gcd[Abs[a], Abs[b], 0];
gcd[a_, 0, step_] := {a, step};
gcd[0, b_, step_] := {b, step};
gcd[a_, b_, step_] := Which[
   a >= b, gcd[a - b, b, step + 1],
   b > a, gcd[a, b - a, step + 1]];

It's not optimized at all (it manually does each subtraction rather than using Mod) and probably what you want isn't the subtractions, but you can make modifications. It also shows you how you can make these kinds of "algorithmic" things in Mathematica by pattern matching. For example, the step in the algorithm that reads "if either number is 0, stop" is encoded in the 2nd and 3rd lines in the code.
A plot of the subtractions-required looks like this:
data = Table[gcd[i, j][[2]], {i, Range[0, 80]}, {j, Range[0, 80]}];
ListPlot3D[data, InterpolationOrder -> 2, Mesh -> None, Boxed -> False, PlotRange -> Full]

I know this is not exactly what you're looking for, but I wanted to bring in the computational perspective. :)
Update
In response to @Jyrki's comment, here is the 'faster' version of the algorithm which subtracts as many multiples as possible in a given step:
gcd[a_, b_] := gcd[Abs[a], Abs[b], 0];
gcd[a_, 0, step_] := {a, step};
gcd[0, b_, step_] := {b, step};
gcd[a_, b_, step_] := Which[
   a >= b, gcd[a - IntegerPart[a/b]*b, b, step + 1],
   b > a, gcd[a, b - IntegerPart[b/a]*a, step + 1]];

data = Table[gcd[i, j][[2]], {i, Range[0, 599]}, {j, Range[0, 599]}];

Because the algorithm is fast (Max[data] shows that any two numbers between 0 and 599 will resolve in at most 12 steps), the value jumps rapidly between only a few discrete values (0-12), which makes a regular 3D plot very noisy. So I used a density plot instead:
ListDensityPlot[data, ImageSize -> {600, 600}, PlotRangePadding -> None, Frame -> None, Axes -> False]

Here's a "close-up" achieved by plotting in a different range:
data = Table[gcd[i, j][[2]], {i, Range[250949, 250949 + 599]}, {j, Range[0, 599]}];

A: Observe that
\begin{align}
\gcd(121,330) &= \gcd(121,88) \quad (88 = 330 - 2 \times 121.) \\
              &= \gcd(33,88) \quad (33 = 121 - 1 \times 88.) \\
              &= \gcd(33,22) \quad (22 = 88 - 2 \times 33.) \\
              &= \gcd(11,22) \quad (11 = 33 - 1 \times 22.) \\
              &= \gcd(11,0) = 11. \quad (0 = 22 - 2 \times 11.)
\end{align}
Therefore, $ 5 $ steps are needed to terminate the Euclidean Algorithm for the pair $ (121,330) $.
When applying the Euclidean Algorithm, the number of steps needed till termination never exceeds $ 5 $ times the number of decimal digits in the smaller number. This fact is a consequence of Lamé's Theorem. (Some authors label the fact itself as Lamé's Theorem; see this link for an engaging discussion). The proof of the theorem, which can also be found in the preceding link, is interesting for its use of Fibonacci numbers.

A: You don't need any divisions at all! You only need remainders, not quotients. As for how many remainders you need:
330/121 gives remainder 88
121/88 gives remainder 33
and so on. Stop when you get a remainder of 0 (and then the answer is the last non-zero remainder). It won't take you long :-)


text:
Q: Properly format 3d subplots So I have 8 3d plots (7 3d plots and one 2d plot)
I want to position them in 4 x 2 format. Here is my code for it:
sensor_data = self._util_sensor(sub_df)
fig = plt.figure()
fig.tight_layout()

ax = fig.add_subplot(1, 2, 1, projection = '3d')
ax.scatter(sensor_data['chest'][0], sensor_data['chest'][1], sensor_data['chest'][2])
ax.set_title('Chest')

ax = fig.add_subplot(1, 2, 2)
ax.scatter(sensor_data['ecg'][0], sensor_data['ecg'][1])
ax.set_title('ECG')

ax = fig.add_subplot(2, 2, 1, projection = '3d')
ax.scatter(sensor_data['left_accel'][0], sensor_data['left_accel'][1], sensor_data['left_accel'][2])
ax.set_title('left accel')

ax = fig.add_subplot(2, 2, 2, projection = '3d')
ax.scatter(sensor_data['left_gyro'][0], sensor_data['left_gyro'][1], sensor_data['left_gyro'][2])
ax.set_title('left gyro')

ax = fig.add_subplot(3, 2, 1, projection = '3d')
ax.scatter(sensor_data['left_mag'][0], sensor_data['left_mag'][1], sensor_data['left_mag'][2])
ax.set_title('left mag')

ax = fig.add_subplot(3, 2, 2, projection = '3d')
ax.scatter(sensor_data['right_accel'][0], sensor_data['right_accel'][1], sensor_data['right_accel'][2])
ax.set_title('right accel')

ax = fig.add_subplot(4, 2, 1, projection = '3d')
ax.scatter(sensor_data['right_gyro'][0], sensor_data['right_gyro'][1], sensor_data['right_gyro'][2])
ax.set_title('right gyro')

ax = fig.add_subplot(4, 2, 2, projection = '3d')
ax.scatter(sensor_data['right_mag'][0], sensor_data['right_mag'][1], sensor_data['right_mag'][2])
ax.set_title('right mag')
plt.show()

The result is the following image. How do I properly format these?

A: There is something wrong with how you use rows, columns and index in add_subplot. I hope this here helps:
fig = plt.figure()
for i in range(6):
    ax = fig.add_subplot(3, 2, i+1, projection = '3d')

The first numbers are the (total) number of rows and columns, the 3rd number is the "index", i.e. going from 1..6 (=rows * columns) for each of the subplots.
This is how it looks like:

But to completely answer the question here would be what needs to be done:
fig = plt.figure(figsize=(6, 12))
ax1 = fig.add_subplot(3, 2, 1, projection = '3d')
ax2 = fig.add_subplot(3, 2, 2)
ax3 = fig.add_subplot(3, 2, 3, projection = '3d')
ax4 = fig.add_subplot(3, 2, 4, projection = '3d')
ax5 = fig.add_subplot(3, 2, 5, projection = '3d')
ax6 = fig.add_subplot(3, 2, 6, projection = '3d')

You can then use the axes (ax1..6) as, e.g.,
ax2.plot([1, 3, 2, 7])


text:
Q: I want to delete the Firebase database child, but I can't I want to delete the Firebase database child with this follow code when I click the first item in a list in an app, but I can't. What's wrong?
Query removeCalendar = mCalendarDatabaseReference.limitToFirst(1);
removeCalendar.addListenerForSingleValueEvent(new ValueEventListener() {

   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
       String remCal = dataSnapshot.toString();
       mCalendarioDatabaseReference.child(remCal).removeValue();
       }

   @Override
   public void onCancelled(DatabaseError databaseError) {
       }
   });

A: Firebase Queries return a list of possible locations where the query might be satisfied, you'd need to iterate through your dataSnapshot to access those locations. Moreover, this :
String remCal = dataSnapshot.toString();

is not going to print the String value of this snapshot. If you want to get the string value of a dataSnapshot it should be:
String remCal = dataSnapshot.getValue(String.class);

If you want to get the reference of a datasnapshot just use getRef(), you don't have to access the original reference.
Query removeCalendar = mCalendarDatabaseReference.limitToFirst(1);
removeCalendar.addListenerForSingleValueEvent(new ValueEventListener() {

   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
       for (DataSnapshot child: dataSnapshot.getChildren()) {
            child.getRef().setValue(null); //deleting the value at this location. You can also use removeValue()
        }
       }

   @Override
   public void onCancelled(DatabaseError databaseError) {
       }
   });

A: I solve the problem with this code:
Query removerCalendario = mCalendarioDatabaseReference.limitToFirst(1);
removerCalendario.addListenerForSingleValueEvent(new ValueEventListener() {

@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds : dataSnapshot.getChildren()) {
        ds.getRef().removeValue();

    }
}

A: You can do mCalendarioDatabaseReference.child(remCal).setValue(null);


text:
Q: how to loopover rows in R to split the column based on respective values in adjacent column? I have data frame with two columns as characters:
col1              col2
"Chharodi"       "Jasmine Green-1, Chharodi,Ravalvas, Chharodi,Thakorvas, Chharodi"
"Lapkaman"       "Belavyu Farm, Lapakaman,Ravalvas, Lapakaman,Vankarvas, Lapakaman"
"Ognaj"          "Vav Valo Vas, Oganaj,Marutinadan Society, Oganaj,Ravalvas,Ognaj"

I want to split the col2 with this out put (splitting the text based on adjacent value in col1):
col3                  col4                    col5          col_contd..
Jasmine Green-1      Ravalvas                Thakorvas
Belavyu Farm         Ravalvas                Vankarvas
Vav Valo Vas         Marutinadan Society     Ravalvas

get an error of 'non-character argument' when i use this
for (i in 1:nrow(df)){
  df1<-strsplit(df, df$col2[i],split = df$col1[i])
}

Also, how do I bind the rows together to create final df?

A: A base R solution,
i1 <- max(lengths(strsplit(as.character(df$col2), df$col1)))
do.call(rbind, lapply(strsplit(as.character(df$col2), df$col1),
                                    function(i){length(i) <- i1; i}))

#     [,1] [,2]  [,3]
#[1,] "l " " m " " n "
#[2,] "k " " g " " m "
#[3,] "e " " f " NA

A: Here is a solution with base R, where substring() is used to extract chars in designated positions:
z <- lapply(df[,2], function(v) (x <- unlist(strsplit(v,split = ",")))[seq(1,length(x),by = 2)])

df.out <- `names<-`(r<-data.frame(df,lapply(z, `length<-`,max(lengths(z)))),
                    paste0("col",seq(ncol(r))))

which gives
> df.out
      col1                                                             col2            col3         col4                col5
1 Chharodi Jasmine Green-1, Chharodi,Ravalvas, Chharodi,Thakorvas, Chharodi Jasmine Green-1 Belavyu Farm        Vav Valo Vas
2 Lapkaman Belavyu Farm, Lapakaman,Ravalvas, Lapakaman,Vankarvas, Lapakaman        Ravalvas     Ravalvas Marutinadan Society
3    Ognaj  Vav Valo Vas, Oganaj,Marutinadan Society, Oganaj,Ravalvas,Ognaj       Thakorvas    Vankarvas            Ravalvas

DATA
df <- structure(list(col1 = c("Chharodi", "Lapkaman",
"Ognaj"), col2 = c("Jasmine Green-1, Chharodi,Ravalvas, Chharodi,Thakorvas, Chharodi",
"Belavyu Farm, Lapakaman,Ravalvas, Lapakaman,Vankarvas, Lapakaman",
"Vav Valo Vas, Oganaj,Marutinadan Society, Oganaj,Ravalvas,Ognaj"
)), row.names = c(NA, -3L), class = "data.frame")

A: Here is one option where we split the 'col2', filter out the matching elements with 'col1' and 'col2' and reshape to 'wide' format
library(tidyr)
library(dplyr)
library(stringr)
df %>%
    separate_rows(col2) %>%
    filter(col1 != col2) %>%
    group_by(col1) %>%
    mutate(rn = row_number()) %>%
    ungroup %>%
    pivot_wider(names_from = rn, values_from = col2) %>%
    select(-col1) %>%
    rename_all(~ str_c("col", 3:5))
# A tibble: 3 x 3
#   col3  col4  col5
#  <chr> <chr> <chr>
#1 l     m     n
#2 k     g     m
#3 e     f     <NA>

Or using str_replace_all
library(stringr)
read.table(text = str_replace_all(df$col2, df$col1, ''),
    header = FALSE, fill = TRUE, col.names = paste0("col", 3:5))
#  col3 col4 col5
#1    l    m    n
#2    k    g    m
#3    e    f

data
df <- structure(list(col1 = c("x", "y", "z"), col2 = c("l x m x n x",
"k y g y m y", "e z f z")), class = "data.frame", row.names = c(NA,
-3L))


text:
Q: How do you use a build system like gulp.js with dependency managers like bower After years of being poor - mediocre PHP developer, I decided to up my game and learn a little more about modern workflows and best practice for developing web apps.
I've studied up on task runners, dependency managers, git, and cloud servers. I'm working on a PC predominantly and I've decided to settle with

*

*PHP and Bootstrap 3 for front end work

*MYSQL (NoSQL seemed like overkill for what I need)

*AppFog for cloud hosting with git for repository control

*gulp.js for task automation - it seemed far simpler than grunt for PHP projects

*either bower or composer for dependency management (still can't decide)

I used some of the answers on here to work out how to change the location bower, for example, places the files it downloads but I'm struggling to understand what the best practice is when you use a dependency manager (that seems to download a whole git repo) and a task runner.
For example I can tell bower to download jquery or bootstrap into the src/vendor folder but what gets downloaded is a mix of javascript, css and other files. I could leave them there and reference them in my code but then running a gulp process would involve cherry picking individual files and minimizing or concatenating one by one, avoiding all the other stuff in the folder that I don't need.
Is this best practice for handling this or am I in the wrong ball park. Should I even be using a task runner with a dependency manager?

A: Look at globbing in Gulp. You should be able to pick out your CSS and JS by using gulp.src('src/vendor/**/*.css') and gulp.src('src/vendor/**/*.js') respectively.
Alternatively, a quick search of NPM returns this which could be of some use: https://www.npmjs.org/package/gulp-bower-files/

A: Okay, first off the bat - let's talk about composer and bower. It's not really a one or the other kind of thing - it's more that you would use them both together. You would use composer to manage your PHP dependencies(for example Guzzle HTTP Client) and bower to manage your client side dependencies such as jQuerybootstrap,a sass mixin library like bourbon or maybe something like Font Awesome
As far as bower dependencies and pulling those in are concerned, one way would be to use Gulp in conjunction with  with Main Bower Files. This reads your bower.json file and pulls bower dependencies into your script based on that. If some bower dependencies don't have a main attribute in bower.json(and some don't) then bower-main-files won't pick them up by default...However - you can work round this by providing overrides in your own bower.json file for that like this:
{
  "name": "My Project",
  "version": "1.0.0",
  "dependencies": {
    "autogrow": "https://github.com/ultimatedelman/autogrow.git#master",
    "jquery": "1.12.2",
    "jquery-slimscroll": "^1.3.7"
  },
  "overrides": {
    "jquery-slimscroll": {
      "main": [
        "./jquery.slimscroll.js"
      ]
    }
  }
}

As you may have noticed you can also point bower at a github repo and branch too.
You can then use the actual main-bower-files package itself in your gulp tasks like so:
var gulp = require("gulp"),
    reload = require("browser-sync").reload,
    mainBowerFiles = require("main-bower-files")
    $ = require("gulp-load-plugins")({
        camelize: true
    });
gulp.task("vendorScripts", function() {
    return gulp.src(mainBowerFiles({filter: '*.js'}))
        .pipe($.plumber({
            errorHandler: c.onError
        }))
        .pipe($.concat(c.concatVendorCSSFile))
        .pipe(gulp.dest('assets/styles'))
        .pipe(reload({stream: true, once: true}))
        .pipe($.size({title: "vendorScripts"}));
});

If you're interested, I have a full project with all this setup here


text:
Q: Does chrome store cookies from images? Let's say I have a website (https://example.com), if I have an image on that website that is from my second website (https://example2.com), will Chrome store the cookies that it got from that image?
Like on the image, if I set the Set-Cookie header to store a cookie saying that the image was fetched, will chrome save the cookie in the browser and if I were to visit https://example2.com, I would be able to see that my browser had fetched an image from my servers before.

A: Yes, these are third-party cookies and work just as you describe. The browser will save them under the domain of the specific resource they were sent under, and re-send them on future requests to that domain, whether they are top-level page requests or sub-resource requests (e.g., an image).
The server must authorize a cookie to be sent as a third-party cookie via the SameSite=None cookie attribute. This also requires use of the Secure attribute, meaning in practice that third-party cookies can only be sent over HTTPS.
Third-party cookies currently work (as of July 2021) in modern browsers, but are blocked by default in Chrome's Incognito mode:

Third-party cookies are a major part of how cross-site tracking works: when any site embeds an advertisement or tracking image as a cross-site <img>, the foreign site serving the embedded image may send and read cookies for their domain, allowing them to know who they're serving ads for. (Have we seen this user before on any other partner sites? Do we have ads relevant to our understanding of this user's browsing habits?)
However, Google is trying to cease use of third-party cookies in advertising, so their future is somewhat uncertain.
I have a simple use of third-party cookies on my Arqade profile, which embeds a remote image from repl.co. The image is served with a unique cookie (and thereafter requested with that same unique cookie) to persistently control the same character in a game. There is no other communication with repl.co needed to establish this cookie relationship besides the embedded image.