text:
Q: Can't remove object from stage I have a problem. I am trying to make a copter game in Adobe Flash with ActionScript 3.0, but now the game works, but the obstacles can't be removed from stage. The obstacles are still going miles out of the stage. How can I remove the obstacles?? and same problem if you are game over, if you are game over the event end, but the last spawned obstacles you see still and aren't removed. And how can I make the obstacles go faster after a period of time??
There are standing some dutch words in it, such as 'hoeSpelen' that is for instructions text en 'af' is for the gameover text and 'tijd' = time and 'balkje' = obstacles.
I hope you can help me.
package
{
    import flash.display.MovieClip;
    import flash.events.MouseEvent;
    import flash.utils.getTimer;
    import flash.events.Event;

    public class iCopter extends MovieClip
    {
        private var copter : Copter = null;
        private var gameover : GameOver = null;
        private var balkje : Balkje = null;
        private var tijd : int
        var score = 0;
        var highscore = 0;

        public function onStartButton(event:MouseEvent)
        {
            startiCopter()
        }

        public function iCopter()
        {
            startButton.addEventListener(MouseEvent.CLICK, onStartButton);

            af.visible = false
            output.visible = false
            hscore.visible = false
        }

        public function startiCopter()
        {
            removeChild(startButton);
            removeChild(hoeSpelen);
            removeChild(af);

            score = 0

            icopterlogo.visible = false

            output.visible = true
            hscore.visible = true

            copter = new Copter();
            copter.x = 100;
            copter.y = 200;

            addChild(copter);

            tijd = getTimer();

            addEventListener(Event.ENTER_FRAME, onEnterFrame);
        }

        public function onEnterFrame(event:Event)
        {
            var now:int = getTimer();

            if (now - tijd  > 1250)
            {
                var balkje = new Balkje();
                balkje.x = 350;
                balkje.y = Math.random() * 150;

                addChild (balkje);

                tijd = now

                score = score + 10;

                output.text = "score: "+score;

                if (balkje.x <= -10) //don't work.
                { //don't work.
                    removeChild (balkje); //don't work.
                } //don't work.
            }

            addEventListener(Event.ENTER_FRAME, botsing);

        }

        function botsing (event:Event)
        {

            for (var i = 0; i < numChildren; i++)
            {
                if (getChildAt(i) is Balkje || getChildAt(i) is Vloer)
                {
                    var b = getChildAt(i) as MovieClip;

                    if (b.hitTestObject(copter))
                    {
                        removeChild (copter);
                        removeEventListener(Event.ENTER_FRAME, onEnterFrame);

                        var gameover = new GameOver();

                        addChild(af);

                        af.visible = true

                        addChild(hoeSpelen);

                        addChild(startButton);

                        if (score > highscore)
                        {
                            highscore = score
                            hscore.text = "highscore: "+highscore;
                        }
                    }
                }
            }
        }
    }
}

Here are the scripts for the copter and obstacle
copter:
muisKlik = mouseClick
muisDruk = mousePush
muisOmhoog = mouseUp
package
{
    import flash.display.MovieClip;
    import flash.events.MouseEvent;
    import flash.events.Event;

    public class Copter extends MovieClip
    {
        var vy : Number = 0;
        var muisKlik : Boolean = false;

        public function Copter()
        {
             vy = 5;
             addEventListener(Event.ENTER_FRAME, onEnterFrame);
             addEventListener(Event.ADDED_TO_STAGE, init);
        }

        private function init(event:Event)
        {
            stage.addEventListener(MouseEvent.MOUSE_DOWN, muisDruk);
            stage.addEventListener(MouseEvent.MOUSE_UP, muisOmhoog);
        }

        public function onEnterFrame(event:Event)
        {
            if (muisKlik == true)
            {
                y -= vy;
            }
            else
            {
                y += vy;
            }
        }

        public function muisDruk (event:MouseEvent)
        {
            muisKlik = true
        }

        public function muisOmhoog (event:MouseEvent)
        {
            muisKlik = false
        }
    }
}

obstacle:
package
{
    import flash.display.MovieClip;
    import flash.events.Event;

    public class Balkje extends MovieClip
    {
        var vx : Number = 1;

        public function Balkje()
        {
            vx = 5;
            addEventListener( Event.ENTER_FRAME, onEnterFrame );
        }

        public function onEnterFrame( event:Event )
        {
            x -= vx;
        }
    }
}

A: Not tested - probably full of errors, and I haven't done AS3 in a while:
When you initialize obstacles, pass in the stage object (not sure if this is the best practice)
package {
import flash.display.MovieClip;
import flash.events.Event;

public class Balkje extends MovieClip
{
    var vx : Number = 1;

    public function Balkje()
    {
        vx = 5;
        if(!stage){
            //if stage isn't populated yet, wait for it
            this.addEventListner(Event.ADDED_TO_STAGE,addedToStage);
        }else{
            init();
        }
    }

    private function addedToStage(e:Event):void {
        this.removeEventListener(Event.ADDED_TO_STAGE,addedToStage);
        init();
    }

    protected function init():void {
        this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
    }

    public function onEnterFrame( event:Event )
    {
        x -= vx;

        //check x
        if(this.x + this.width <= 0 || this.x >= stage.stageWidth) {
            if(this.parent) this.parent.remmoveChild(this);
            removeEventListener( Event.ENTER_FRAME, onEnterFrame );
        }
    }
}
}

Again, not tested (is stage.stageWidth correct to get the stage width?) but you get the idea. Check the x of the object, if it is outside the visible stage remove it from its parent (I just put this.parent because you didn't add the obstacle to the stage).
Also, why do you add event listener to ENTER_FRAME in a function called by ENTER_FRAME?


text:
Q: Ошибка автоматического запуска chromedriver'а Несколько дней назад по необъяснимым мне пока причинам фоновая работа selenium'а (через Xvfb) стала сопровождаться автоматическим запуском экземпляра chromedriver'а.
Выглядят эти процесса вида
/home/chromedriver --port=12328 --log-path=/var/log/selenium-chrome.log
/home/chromedriver --port=20727 --log-path=/var/log/selenium-chrome.log
/home/chromedriver --port=28574 --log-path=/var/log/selenium-chrome.log

И так далее. Каждый из них пытается запустить при этом экземпляр chrome'а, что в сумме приводит к очень высокой нагрузке на сервер.
Сам скрипт запуска выглядит следующим образом:
#!/usr/bin/env bash
DISPLAY=:1 xvfb-run -a java -jar -Dwebdriver.chrome.driver="/home/chromedriver" -Dwebdriver.chrome.logfile="/var/log/selenium-chrome.log" /home/selenium-server-standalone-3.4.0.jar

Обновление chromedriver'а и самого chrome'а ни к чему не привели.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Previewing raster catalogs raster field in Windows form? What I want to achieve:
The attribute table for an ArcGIS Raster Catalog contains a raster field.  When a raster field cell is clicked with the mouse, a preview window displaying the raster associated with the row is displayed.  I want to achieve the same or equivalent functionality, but within a windows form.
What I've tried:
I have managed to display the full attribute table of a RasterCatalog layer within a .Net DataGrid using this code
'Bind a geodatabase table to a .NET control'.   However, whilst the raster column is populated with text 'raster', it is not possible to get a preview of the raster.
One solution could be to add the image for each row to the datagrid as detailed here, but I'd prefer if I could keep the Esri raster field functionality if possible.


text:
Q: Extract tables from SSAS TABULAR in Databricks We are working on a solution where we have data in SSAS Tabular solution and that need to be imported into Databricks for further transpose. Currently we are connecting to excel export the data and load it manually into data bricks.
We want to automate this process to avoid manual effort. We are looking for any scala or python connector available which could extract data from SSAS and load into databricks dataframe.
Any help or suggestion is welcome.


text:
Q: Symfony 4 - grouping categories I have table for category and parent_category with ralation ManyToOne.
This is my 'category' table:

And this is my 'parent_category' table:

This is my code in FormType:
->add('category',EntityType::class,array(
                'class'=>Category::class,
                'choice_label'=>'name',
                'group_by'=>'parent_id'

            ))

And this is the answer in browser.

My parent category must be for 1-Якета (Jackets) ,2-Блузи (Blouses),3->Панталони (Pants).I want the string value of this parent_id,like this:
Якета
--Пролетни
--Зимни
--Жилетки
Блузи
--Тениски
--Ризи
--Дълъг ръкав
Панталони
--Къси
--Дълги
--Дънки

How to do that? Thanks!

A: Maybe you can try this:
'group_by' => function($value, $key, $index) {
       return $value->getParent()->getName();
    }

A: (Posted solution on behalf of the question author).
New updated code in FormType:
'group_by' => function(Category $category) {
                    return $category->getParent()->getName();

                }


text:
Q: Where head of this Link list points after recursive statement I have simple link list program, that would create/print it, and later on print the last 2 number from it (in reverse order)
cat link_list.c
/**
 * C program to create and traverse a Linked List
 */

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

/* Structure of a node */
struct node {
    int data;          // Data
    struct node *next; // Address
}*head;

/*
 * Functions to create and display list
 */
void createList(int n);
void traverseList();
void ReverseList(struct node *);

int main()
{
    int n;

    printf("Enter the total number of nodes: ");
    scanf("%d", &n);

    createList(n);

    printf("\nData in the list \n");
    traverseList();

    ReverseList(head);

    return 0;
}

/*
 * Create a list of n nodes
 */
void createList(int n)
{
    struct node *newNode, *temp;
    int data, i;

    head = (struct node *)malloc(sizeof(struct node));

    // Terminate if memory not allocated
    if(head == NULL)
    {
        printf("Unable to allocate memory.");
        exit(0);
    }

    // Input data of node from the user
    printf("Enter the data of node 1: ");
    scanf("%d", &data);

    head->data = data; // Link data field with data
    head->next = NULL; // Link address field to NULL

    // Create n - 1 nodes and add to list
    temp = head;
    for(i=2; i<=n; i++)
    {
        newNode = (struct node *)malloc(sizeof(struct node));

        /* If memory is not allocated for newNode */
        if(newNode == NULL)
        {
            printf("Unable to allocate memory.");
            break;
        }

        printf("Enter the data of node %d: ", i);
        scanf("%d", &data);

        newNode->data = data; // Link data field of newNode
        newNode->next = NULL; // Make sure new node points to NULL

        temp->next = newNode; // Link previous node with newNode
        temp = temp->next;    // Make current node as previous node
    }
}

/*
 * Display entire list
 */
void traverseList()
{
    struct node *temp;

    // Return if list is empty
    if(head == NULL)
    {
        printf("List is empty.");
        return;
    }

    temp = head;
    while(temp != NULL)
    {
        printf("Data = %d\n", temp->data); // Print data of current node
        temp = temp->next;                 // Move to next node
    }
}

static count=0, k=2;

ReverseList(struct node *head)
{
    if (head == NULL)
        return;
    else {
        ReverseList(head->next);
        count++;
        if (count <= k)
            printf("Data = %d\n", head->data);
    }
}

For an input 1 2 3 , it would first print 3 2 1 and then 3 2 correctly but I have confusion about the :
    if (head == NULL)
        return;

what exactly it returns with return;, and where head is pointing after the
ReverseList(head->next); statement ?

A: Lets say we have a simple three-node list like this:

1 -> 2 -> 3

When we initially call ReverseList we pass the 1 node as the head and we have this call-chain:

ReverseList(1 -> 2 -> 3 -> NULL)
  ReverseList(2 -> 3 -> NULL)
    ReverseList(3 -> NULL)
      ReverseList(NULL)
    printf(3)
  printf(2)
printf(1)

A: For starters you forgot to specify the return type of the function in the function definition:
ReverseList(struct node *head)
{
    if (head == NULL)
        return;
    else {
        ReverseList(head->next);
        count++;
        if (count <= k)
            printf("Data = %d\n", head->data);
    }
}

You have to write:
void ReverseList(struct node *head)

As for your question:

I have confusion about the :
if (head == NULL)
    return;

what exactly it returns with return;, and where head is pointing after the ReverseList(head->next); statement ?

Then as the function has the return type void and the return statement does not include an expression then the return statement returns nothing.
The function parameter head is a local variable of the function. The function does not change the pointer head declared in the file scope
struct node {
    int data;          // Data
    struct node *next; // Address
}*head;

In the first call of the function the parameter head has the value of the global variable head due to this statement:
 ReverseList(head);

If the value is not equal to NULL then the function recursively calls itself passing the value of the  pointer head->next:
ReverseList(head->next);

So in the second recursive call of the function itself the value of its parameter head is equal to the value of head->next where in this expression head is the function parameter of the previous call of the function.
That is the parameter head at first gets the value of the global variable head and then the parameter is initialized sequentially by values of the data member next of the next node in the sequence.
So for the list that contains nodes with values 1, 2, 3 you have
1-st call
parameter head is equal to the global variable head
2-nd call
parameter head is equal to head->next that points to the node with the value 1
3-rd call
parameter head is equal to head->next->next that points to the node with the value 2
4-th call
parameter head is equal to head->next->next->next that points to the node with the value 3
5-th call
parameter head is equal to head->next->next->next->next and equal to NULL
Pay attention to that it is not a good idea to use static global variables within the function
static count=0, k=2;

You need to remember reinitialize them if you want to call the function one more time. It is better to make the variable k a function parameter.
The function could be defined the following way as it is shown in the demonstrative program below.
#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};

int push( struct node **head, int data )
{
    struct node *new_node = malloc( sizeof( *new_node ) );
    int success = new_node != NULL;

    if ( success )
    {
        new_node->data = data;
        new_node->next = *head;
        *head = new_node;
    }

    return success;
}

void display( const struct node *head )
{
    for ( ; head != NULL; head = head->next )
    {
        printf( "%d -> ", head->data );
    }

    puts( "null" );
}

size_t display_last_n( const struct node *head, size_t n )
{
    size_t i = 0;

    if ( head != NULL )
    {
        i = display_last_n( head->next, n ) + 1;

        if ( !( n < i ) )
        {
            if ( i != 1 ) printf( ", " );
            printf( "%d", head->data );
        }
    }

    return i;
}

void clear( struct node **head )
{
    while ( *head )
    {
        struct node *tmp = *head;
        *head = ( *head )->next;
        free( tmp );
    }
}

int main(void)
{
    struct node *head = NULL;
    const int N = 10;

    for ( int n = N; n--; )
    {
        push( &head, n );
    }

    display( head );

    for ( size_t i = 0; i < N; i++ )
    {
        display_last_n( head, i + 1 );
        putchar( '\n' );
    }

    clear( &head );

    return 0;
}

The program output is:
0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null
9
9, 8
9, 8, 7
9, 8, 7, 6
9, 8, 7, 6, 5
9, 8, 7, 6, 5, 4
9, 8, 7, 6, 5, 4, 3
9, 8, 7, 6, 5, 4, 3, 2
9, 8, 7, 6, 5, 4, 3, 2, 1
9, 8, 7, 6, 5, 4, 3, 2, 1, 0


text:
Q: Mongo startup warning & records are getting corrupted This is what I get when i start to work on mongo on my server.
MongoDB shell version: 3.0.11
connecting to: test
Server has startup warnings:
2016-05-04T12:40:04.269+0000 I CONTROL  [initandlisten]
2016-05-04T12:40:04.269+0000 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2016-05-04T12:40:04.269+0000 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2016-05-04T12:40:04.269+0000 I CONTROL  [initandlisten]
2016-05-04T12:40:04.269+0000 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2016-05-04T12:40:04.269+0000 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2016-05-04T12:40:04.269+0000 I CONTROL  [initandlisten]

Due to above error my data in mongo is getting corrupted.
For example. _id of the collection change automatically from NumberLong to any random negative value (without datatype NumberLong) Queries of the database are not working as well.
I am using mongo to store my groups information. Groups are getting created just like before but its _id is automatically getting into negative value. Which then do not system to ready the data from the server.
Data Example:
Old entry:
{ "_id" : NumberLong("5832929604864"), "battles" : [ "1478882936384", "1474596010496", "1475809103872", "1470752181248", "1475980114432", "1478966261248" ], "cat" : "57", "created_by" : "3697315148736", "date" : "2015-10-16 17:21:41", "description" : "Amazing night for houston texansqa\nAll undone with one game ending.", "is_deleted" : NumberLong(0), "members" : [ "3697315148736", "3695601014400", "3692104837824", "3690345909504", "3698247126528" ], "title" : "nfl" }

Automatically changing values, here's a new group created:
{ "_id" : -1535373376, "created_by" : "3692102996096", "title" : "fsf", "lowcase_title" : "fsf", "date" : "2016-04-18 06:02:45", "cat" : "988", "description" : "sfsdf", "members" : [ "3692102996096" ], "battles" : [ ], "is_deleted" : 0 }

_id: from above record converted to negative value and so "is_deleted".
Also both the above records are no longer being readed using my queries.
The same code and database is working fine on my first server.
Recently I copied my website on a different server for testing. Both the servers are on amazon's ec2 server.
On previous server when I access mongo I get this:
MongoDB shell version: 2.4.9
connecting to: test

No error and every thing is working fine on this server.
Can the version of mongo causing this error or
I need to set
/sys/kernel/mm/transparent_hugepage/enabled is 'always' to 'never

If above, then can you please guide me what & how to set it to 'never'?


text:
Q: How to force the gravity of bubbles in D3.js In the code below, I need to make the bubbles with the highest values float to the left of the screen, but I have no deep knowledge of D3.js and I can't find a way to do this.
My code
<script type="text/javascript">

     dataset = {
        "children": [{"Name":"Olives","Count":10},
            {"Name":"Tea","Count":8},
            {"Name":"Mashed Potatoes","Count":6},
            {"Name":"Boiled Potatoes","Count":5},
            {"Name":"Milk","Count":4},
            {"Name":"Chicken Salad","Count":4},
            {"Name":"Vanilla Ice Cream","Count":2},
            {"Name":"Cocoa","Count":7}];

    var diameter = 600;
    var color = d3.scaleOrdinal(d3.schemeCategory20);

    var bubble = d3.pack(dataset)
        .size([diameter, diameter])
        .padding(1.5);

    var svg = d3.select("body")
        .append("svg")
        .attr("width", diameter)
        .attr("height", diameter)
        .attr("class", "bubble");

    var nodes = d3.hierarchy(dataset)
        .sum(function(d) { return d.Count; });

    var node = svg.selectAll(".node")
        .data(bubble(nodes).descendants())
        .enter()
        .filter(function(d){
            return  !d.children
        })
        .append("g")
        .attr("class", "node")
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        });

    node.append("title")
        .text(function(d) {
            return d.Name + ": " + d.Count;
        });

    node.append("circle")
        .attr("r", function(d) {
            return d.r;
        })
        .style("fill", function(d,i) {
            return color(i);
        });

    node.append("text")
        .attr("dy", ".2em")
        .style("text-anchor", "middle")
        .text(function(d) {
            return d.data.Name.substring(0, d.r / 3);
        })
        .attr("font-family", "sans-serif")
        .attr("font-size", function(d){
            return d.r/5;
        })
        .attr("fill", "white");

    node.append("text")
        .attr("dy", "1.3em")
        .style("text-anchor", "middle")
        .text(function(d) {
            return d.data.Count;
        })
        .attr("font-family",  "Gill Sans", "Gill Sans MT")
        .attr("font-size", function(d){
            return d.r/5;
        })
        .attr("fill", "white");

    d3.select(self.frameElement)
        .style("height", diameter + "px");

</script>

Edit in JS Fiddle
The code produces this result

I need the bubbles with the highest values to be on the left, as in the image below.

What property or function of D3.js can I use to control the severity of the bubbles as I need them?
Thanks!

A: There's not a function specifically in d3.pack for this. d3.force allows you specify x and y positions based on the data's value, and could achieve the result you are looking for.
The force simulation has an .x and .y function that is based on the data's count, and then to avoid overlaps, the .collide function adjusts the circles positions based on their radius (plus a small paddding of 3px).
 var simulation = d3.forceSimulation(nodes)
        .force("forceX", d3.forceX().strength(.051).x(d => xScale(d.Count)))
        .force("forceY", d3.forceY().strength(.051).y(d => yScale(d.Count)))
        .force('collision', d3.forceCollide().radius(d => rScale(d.Count) + 3))

dataset = {
        "children": [{"Name":"Olives","Count":10},
            {"Name":"Tea","Count":8},
            {"Name":"Mashed Potatoes","Count":6},
            {"Name":"Boiled Potatoes","Count":5},
            {"Name":"Milk","Count":4},
            {"Name":"Chicken Salad","Count":4},
            {"Name":"Vanilla Ice Cream","Count":2},
            {"Name":"Cocoa","Count":7}]
    }

    let nodes = dataset.children

    var width = 600;
    var height = 600;
    var margin = 50
    var color = d3.scaleOrdinal(d3.schemeCategory20);

    let extentCount = d3.extent(nodes, d => d.Count)
    let maxRadius = 100

    let yScale = d3.scaleLinear()
     .domain(extentCount)
     .range([height - maxRadius, maxRadius])

    let xScale = d3.scaleLinear()
     .domain(extentCount)
     .range([(width - maxRadius), maxRadius])

    let rScale = d3.scaleSqrt()
     .domain(extentCount)
     .range([5, maxRadius])

    var svg = d3.select("body")
        .append("svg")
        .attr("width", width + margin + margin)
        .attr("height", height + margin + margin)
        .attr("class", "bubble");

    var g = svg.append("g")
     .attr("transform", "translate(" + margin + "," + margin + ")")

    var simulation = d3.forceSimulation(nodes)
        .force("forceX", d3.forceX().strength(.051).x(d => xScale(d.Count)))
        .force("forceY", d3.forceY().strength(.051).y(d => yScale(d.Count)))
        .force('collision', d3.forceCollide().radius(d => rScale(d.Count) + 3))
      .on("tick", function(d){
            node
                .attr("cx", function(d){ return d.x; })
                .attr("cy", function(d){ return d.y; })
          })
      .stop()

    for (var i = 0; i < 120; i++) {
      simulation.tick()
    }

    var node = g.selectAll(".node")
        .data(nodes)
        .enter()
        .append("g")
        .attr("class", "node")
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        });

    node.append("title")
        .text(function(d) {
            return d.Name + ": " + d.Count;
        });

    node.append("circle")
        .attr("r", d => rScale(d.Count))
        .style("fill", function(d,i) {
            return color(i);
        });

    node.append("text")
        .attr("dy", ".2em")
        .style("text-anchor", "middle")
        .text(function(d) {
            return d.Name.substring(0, rScale(d.Count) / 3);
        })
        .attr("font-family", "sans-serif")
        .attr("font-size", function(d){
            return rScale(d.Count)/5;
        })
        .attr("fill", "white");

    node.append("text")
        .attr("dy", "1.3em")
        .style("text-anchor", "middle")
        .text(function(d) {
            return d.Count;
        })
        .attr("font-family",  "Gill Sans", "Gill Sans MT")
        .attr("font-size", function(d){
            return d.r/5;
        })
        .attr("fill", "white");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>


text:
Q: Put a list of arrays in a php variable I have a big piece of php code that builds a dropdown menu and I want to minimize it by loading the select options from a text file. How to do this in the right way with php?
An example of original code:
$field['options'] = array(
    array('value' => 'Anenii Noi', 'text' => 'Anenii Noi', 'depth' => 0),
    array('value' => 'Bălţi', 'text' => 'Bălţi', 'depth' => 0),
    array('value' => 'Basarabeasca', 'text' => 'Basarabeasca', 'depth' => 0),
    ....
    array('value' => 'Ungheni', 'text' => 'Ungheni', 'depth' => 0)
);

And this is what I try to do, but without success:
// read a text file with select options
// where each option is a seperate line
$file_array = str_replace("\n","", file($file_path));

// build the list of arrays with select options
foreach ($file_array as $location)
    $options .= "array('value' => '" . $location . "', 'text' => '" . $location . "', 'depth' => 0),";

foreach($form['field'] as $k => $field) {

    // replace the big list of arrays with $options variable
    $field['options'] = array($options);

    $form['field'][$k] = $field;
    break;
}

A: Looks like you had it almost. But you tried to mimic the pure php code, that might have worked if you use eval() later on, but you need to mimic its functionality.
// read a text file with select options
// where each option is a seperate line
$file_array = str_replace("\n","", file($file_path));

// build the list of arrays with select options
$options = array();
foreach ($file_array as $location) {
    $options[] = array('value' => $location, 'text' => $location, 'depth' => 0);
}

foreach($form['field'] as $k => $field) {

    $field['options'] = $options;

    $form['field'][$k] = $field;
    break;
}


text:
Q: Seeking contour data for Oregon? Does anyone know where I can find good contour layers for Oregon?
I do not have spatial analyst, so I can not make my own.

A: You can make you own with a really straightforward workflow and a couple of free gdal tools
1) download the SRTM data from http://dwtkns.com/srtm/
2) merge multiple tifs into one
gdal_merge.py -a_nodata -32768 -o output.tif tiff1.tiff tiff2.tiff ..

3) make your own contours
gdal_contour -a elevation -i 10 output.tif oregan.shp

A: The Oregon Spatial Data Library (search for contour) has 100ft & 500ft contours available as shape files. They are split up into 9 sections to keep the sizes down.


text:
Q: Java Streams filter and replace an item in list if it meets criteria I am using Java 8 streams and would like to remove an item in my list if multiple items with the same room number are present and use the one with the most current date.
I have this list:
final List<TestClass> testClasses = Arrays.asList(
            new TestClass(100L, LocalDate.of(2020, 1, 10)),
            new TestClass(100L, LocalDate.of(2019, 1, 10)),
            new TestClass(101L, LocalDate.of(2020, 7, 20)),
            new TestClass(102L, LocalDate.of(2020, 1, 9)),
            new TestClass(103L, LocalDate.of(2020, 1, 11)),
            new TestClass(104L, LocalDate.of(2020, 2, 13))
    );

I would like to filter this list down in a way such that if the roomNumber (first param of TestClass constructor) occurs multiple times in the list then that entry should be removed and the one with the most current date will be saved.
Sample output from above list after filtering:
[
       TestClass(100L, LocalDate.of(2020, 1, 10)),
       TestClass(101L, LocalDate.of(2020, 7, 20)),
       TestClass(102L, LocalDate.of(2020, 1, 9)),
       TestClass(103L, LocalDate.of(2020, 1, 11)),
       TestClass(104L, LocalDate.of(2020, 2, 13))
]

As you can see the second TestClass object with a roomNumber of 100 has been removed and we are left with the first TestClass object that also has a roomNumber of 100 but we keep it since the date is higher or more recent than the other entry.
I have read through the Java streams documentation and am aware of filtering. Is there a way to achieve this functionality using Java streams? I feel like there is but there may be a way to use this api that I am unaware of.
TIA and please let me know if more information is required :)
EDIT:
This is the attempt that I made. I learned about the groupingBy function and was able to get the TestClasses into a list grouped by their room number. I am not sure where to go from there.
 Map<Long, List<TestClass>> c = testClasses.stream()
            .collect(Collectors.groupingBy(TestClass::getRoomNumber));

A: You've made a great attempt! You can continue to process the map by converting each value (a list of TestClass instances) to a single TestClass instance by getting the maximum value using the date:
 List<TestClass> c = testClasses.stream()
        .collect(Collectors.groupingBy(TestClass::getRoomNumber))
        .values() // returns the collection of values from the map
        .stream() // converts that collection to a stream
        .map(group -> // converts each item (a list of TestClass for a given room number)
                group.stream() // converts that list to a stream
                        .max( // returns the maximum value of the list using the following Comparator
                                Comparator.comparing(TestClass::getDate)
                                // creates a comparator for TestClass based on calling getDate on each item,
                                // using the natural ordering for LocalDate
                        ) // This returns Optional<TestClass>
        ) // This returns Stream<Optional<TestClass>>
        .filter(Optional::isPresent) // This removes empty Optional values
        .map(Optional::get) // Converts the non-empty Optional to the value it contains
        .collect(Collectors.toList()); // Collects the resulting stream into a list

One point of further clarification: why does max return an Optional<TestClass>? This handles the case of an empty stream (in other words, a room number in the map with no TestClass items), in which case an empty Optional is returned. Now, we know that this can't possibly happen, because of the way the data structure is built, but the compiler cannot infer that, so it is required to handle the impossible case of empty values. Strictly speaking, the filter part could be eliminated, but having it will ensure the code is robust in the face of some future change that allows empty values to appear.

A: Using Java Streams toMap function
Approach Here:
You can try the below approach in which i have first sorted the list by id and then date in reverse order (so that the list will have the latest record at top corresponding to each id) and then using Collectors.toMap function created a map with key as id and value as the object of TestClass along with the merger function (a, b) -> a(which will help in getting the latest value corresponding to each key) and TreeMap::new will give the sorted map.
After that, I have created a new ArrayList of TestClass type with the values using .values of the map created above.
public class Test {
    public static void main(String[] args) {
        final List<TestClass> testClasses = Arrays.asList(
                new TestClass(100L, LocalDate.of(2020, 1, 10)),
                new TestClass(100L, LocalDate.of(2019, 1, 10)),
                new TestClass(101L, LocalDate.of(2020, 7, 20)),
                new TestClass(102L, LocalDate.of(2020, 1, 9)),
                new TestClass(103L, LocalDate.of(2020, 1, 11)),
                new TestClass(104L, LocalDate.of(2020, 2, 13))
        );

        List<TestClass> uniqueListWithLatestData =
            new ArrayList<>(testClasses.stream()
            .sorted((Comparator.comparing(TestClass::id)
                          .thenComparing(TestClass::date).reversed()))
            .collect(Collectors.toMap(TestClass::id, x -> x,(a, b) -> a,
                                       TreeMap::new)).values());
             System.out.println(uniqueListWithLatestData);

    }
}

Note:
Here, I have created a record for TestClass for the solution, you can have your own TestClass POJO.(Records are available from JDK14)
public record TestClass(long id, LocalDate date) {}

Output:
[TestClass[id=100, date=2020-01-10],
TestClass[id=101, date=2020-07-20],
TestClass[id=102, date=2020-01-09],
TestClass[id=103, date=2020-01-11],
TestClass[id=104, date=2020-02-13]]


text:
Q: Display a TextBlock over a MediaElement when in full screen I have a MediaElement and a TextBlock next to it. But when I set MediaElement to fullscreen, this TextBlock disappears. Can anyone share a solution?
<MediaElement Name="player" Margin="10,5" AreTransportControlsEnabled="True" />
<TextBlock Margin="10"/>

A: As I have said in this thread, when we are in the Full Window mode, it will go to the FullWindowMediaRoot layer with the MediaTransportControls. In this way the TextBlock will disapper, because there is no place to show the TextBlock. In order to let the TextBlock show, I will recommend you refer to this article to create a custom transport controls for the MediaEelement.


text:
Q: How to the plot results of a differential equation Please help me to plot the solution of a differential equation as a parameter of Delta. Here is what I've tried.
(**Constants**)

tin := -50;
tfin := 50;
t := 0.05;
v := 1;

(**Solve differential equation**)

sol = NDSolve[Delta == Module[{x0},
  Table[x0, {x0, 0, 10}]],
  {I y1'[t] == v t y1[t] +
    Delta y2[t], I y2'[t] == -v t y2[t] + Delta y1[t], y1[tin] == 1, y2[tin] == 0}, {y1, y2}, {t, tin, tfin}];

(**Probability**)

Prob1[t_] :=
      Re[Evaluate[y1[t] /. sol]]^2 + Im[Evaluate[y1[t] /. sol]]^2;

(**we need to plot this result as a function of delta**)

a = Plot[{Prob1[t]}, {Delta, -10, 10}]

A: Is this the plot you want?
(**Constants**)
tin := -50;
tfin := 50;
t1 := 0.05;
v := 1;

(**Solve differential equation**)
sol = ParametricNDSolve[{I y1'[t] == v t y1[t] + Delta y2[t],
    I y2'[t] == -v t y2[t] + Delta y1[t], y1[tin] == 1,
    y2[tin] == 0}, {y1, y2}, {t, tin, tfin}, Delta];

(**Probability**)
Prob1[Delta_, t_] := Abs[y1[Delta][t]]^2;

(**we need to plot this result as a function of delta**)
a = ListPlot[Table[{Delta, Prob1[Delta, t1]} /. sol, {Delta, -10, 10}]]


text:
Q: yii2 mongodb - add comments to existing field how to I have a collection called work-monitor where-in I have two fields namely
assignor_remarks and assignee_remarks.
so when a comment is submitted by either assignor or assignee, I want to add those comments in the respective comment filed.
I am able to save the comments in the collection, but new comments is overriding the existing one.
my code is like this:
public function actionWorkUpdate($id)
      {
        \Yii::$app->request->enableCsrfValidation = false;
        $work = $this->modelClass::find()->where(['_id'=>$id])->one();

        $work->load(Yii::$app->getRequest()->getBodyParams(), '');

        $work->assignee_remarks = ["timestamp"=>date('d-m-Y h:i'),"comments"=>$work->assignee_remarks];
    $work->update();
    return "success";
  }

how I can achieve this.
update like in the example below:
"assignee_remarks":{"comment":"test comment","commentTime":2020-04-29 12.41},
{"comment":"test comment2","commentTime":2020-04-29 12.45},
{"comment":"test comment3","commentTime":2020-04-29 12.50}

A: Try something like that, if I have understood you correctly.
// In Work Model

public $assignee_remarks;

public function rules()
{
    return [
        //...
        ['assignee_remarks', 'safe'] // for free load
    ];
}

// In controller

/**
 * In bodyParams you have new comment like assignee_remarks: 'some text'
 * @param $id
 * @return mixed
 */
public function actionWorkUpdate($id)
{
    \Yii::$app->request->enableCsrfValidation = false;
    $work = $this->modelClass::find()->where(['_id' => $id])->one();

    $currentComments = $work->assignee_remarks ?? [];
    $work->load(Yii::$app->getRequest()->getBodyParams(), '');

    $currentComments[] = ["commentTime" => date('d-m-Y h:i'), "comment" => $work->assignee_remarks];
    $work->assignee_remarks = $currentComments;

    $result = $work->update();

    if ($result === false) {
        // validation error
    } else {
        return $result > 0 ? 'success' : 'fail';
    }
}


text:
Q: Why won't my flutter firestore string or image_picker function carry over to another page, or vice-versa? I have two files: a ListView storing Firestore strings, and an image_picker. The flutter plugins are: cloud_firestore, esys_flutter_share and image_picker
I want the app user (non-authenticated) to either share a text string ('title' from firestore db) OR attach an image (from image_picker) - to simply share one or both.
I trying to learn this and I do not have github yet. Here is my entire code, how can I get the Esys share plugin to share both items in the same function _shareImageAndText(), although they are on separate pages?
I thought the functions from the ImageInput() class from image.dart would still work when imported on the main page ( Recipe ) but they don't work, I get: '_imageFile is undefined' on main page, or 'title' is undefined when trying to call it on second page. What am I not understanding? Both image and text share functions work on their respective pages but I can get them to work on the same page at the same time.
    import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'dart:ui';
import 'package:google_fonts/google_fonts.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:esys_flutter_share/esys_flutter_share.dart';
import 'dart:async';
import 'image.dart';

class Recipe extends StatefulWidget {
@override
_RecipeState createState() => _RecipeState();
}

 class _RecipeState extends State<Recipe> {
var firestoreDb = Firestore.instance.collection("recipes").snapshots();

   Future<void> _shareText(snapshot, index) async {
try {
  Share.text('Share Text ',
      (snapshot.data.documents[index].data['title']), 'text/plain');
} catch (e) {
  print('error: $e');
}

}
@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Container(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                'Recipes',
                style: GoogleFonts.lato(
                  fontSize: 22.0,
                  color: Colors.amberAccent.shade50,
                ),
              )),
          IconButton(
            icon: Icon(MdiIcons.foodForkDrink, color: Color(0xffffe0b2), size: 32.0),
            onPressed: () {
             null;
            },
          ),
        ]),
    backgroundColor: Colors.lightBlue,
    elevation: 50.0,
  ), //AppBar

  body: Container(
    width: MediaQuery.of(context).size.width,
    child: StreamBuilder(
        stream: firestoreDb,
        builder: (context, snapshot) {
          if (!snapshot.hasData) Text('Loading...');
          return StaggeredGridView.countBuilder(
            crossAxisCount: 2,
            mainAxisSpacing: 1.0,
            crossAxisSpacing: 1.0,
            padding: EdgeInsets.symmetric(horizontal: 2.0, vertical: 6.0),
            shrinkWrap: true,
            itemCount: snapshot.data.documents.length,
            itemBuilder: (context, int index) => Container(
              child: Column(
                children: <Widget>[
                  Card(
                    color: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12.0),
                    ),

                    child: Column(children: <Widget>[
                      ListTile(
                        title: Text(
                          '${(snapshot.data.documents[index]['title'])}',
                          style: GoogleFonts.lato(
                            fontSize: 20.0,
                            height: 1.2,
                            fontWeight: FontWeight.w500,
                          ),
                          textAlign: TextAlign.center,
                        ),

                        subtitle: Row(
                            mainAxisSize: MainAxisSize.max,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[

                              MaterialButton(         // This shares the Firebase string of text, 'title'
                                child: Text('Share text'),
                                onPressed: () async => await _shareText(snapshot, index),
                              ),

                              SizedBox(height: 5.0),
                              ImageInput(),  //this displays image called from image_picker to share , it works for sharing an image only.

                              Expanded(
                                child: Text(
                                  '${(snapshot.data.documents[index]['subtitle'])}',
                                  textAlign: TextAlign.right,
                                  style: GoogleFonts.lato(
                                    fontSize: 13.0,
                                    fontWeight: FontWeight.w900,
                                    fontStyle: FontStyle.italic,
                                    color: Colors.blue,
                                  ),
                                ), //subtitle: Text
                              ),
                            ] //children
                        ), //Row
                      ), //listtile
                    ]),
                  ),
                ],
              ),
            ),
            staggeredTileBuilder: (int index) => StaggeredTile.fit(2),
          );
        }),
  ),
 );
} //build
} //class

This is the second page that contains the share both image and text function. I can share an image only from this method, the Firestore string (snapshot.data.documents[index].data['title']) will not work:
    import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:esys_flutter_share/esys_flutter_share.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/foundation.dart';

  File _imageFile;

  class ImageInput extends StatefulWidget {

  //final String _imageFile;
  //final String title;
  //ImageInput(this._imageFile, this.title);

   @override
  _ImageInputState createState() => _ImageInputState();
  }

 class _ImageInputState extends State<ImageInput> {

 void _getImage(BuildContext context, ImageSource source){
ImagePicker.pickImage(source: source, maxWidth: 500.0, imageQuality: 80).then((File image){
  setState((){
    _imageFile = image;
  });
  Navigator.pop(context);

});
}

void _openImagePicker(BuildContext context) {
 showModalBottomSheet(context: context, builder: (BuildContext context) {
  return Container(
    height: 180.0,
    padding: EdgeInsets.all(10.0),
  child: Column(
    children: [
    Text('Choose photo',
      style:TextStyle(fontWeight: FontWeight.bold),),
      SizedBox(height: 10.0),
      FlatButton(
        textColor: Theme.of(context).primaryColor,
        child: Text('Use Camera'),
      onPressed: () {
          _getImage(context, ImageSource.camera);
      },),
      FlatButton(
        textColor: Theme.of(context).primaryColor,child:
      Text('Open Gallery'),
        onPressed: () {
          _getImage(context, ImageSource.gallery);
        },)

    ]
  ),);
});
}

 Future<void> _shareImageAndText() async {
 try {
  List<int> imageBytes = await _imageFile.readAsBytes();
  var uint8List = Uint8List.fromList(imageBytes);
  await Share.file('esys image', 'esys.jpg', uint8List, 'image/jpeg',
      text: 'My optional text.');
      //text:  (snapshot.data.documents[index].data['title']) );        <======= this does not carry over to main page
} catch (e) {
  print('error: $e');
}
}

@override
Widget build(BuildContext context) {
return Column(
  children: <Widget>[
    OutlineButton(
    onPressed: () {
      _openImagePicker(context);
    },
    child:Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Icon(Icons.camera_alt, color: Colors.blue.shade700,),
          SizedBox(
            width:1.0,
          ),
          // Text('Add Image'),
        ]
    ),//Row
  ),//outline button

   SizedBox(height: 1.0),
    _imageFile == null ? Text('Add a Pic')  : Image.file(_imageFile,
        fit: BoxFit.cover,
        height: 200.0,
     width: 200.0,
     // width: MediaQuery.of(context).size.width,
      alignment: Alignment.topCenter,
    ),

    MaterialButton(
      child: Text('Send it!'),
      onPressed: () async => await _shareImageAndText(),
    ),
    //pass the snapshot parameter inside your StreamBuilder
    //onPressed: () async => await _shareText(snapshot, index),

  ],
);
}
}

I've tried adding constructors and initializers but I am not smart enough to figure this out.

A: First, add this. it adds a parameter for the data(title) to be passed to the second class.

final String title;
ImageInput({@required this.yourText});

I added directly to your code like below.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:esys_flutter_share/esys_flutter_share.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/foundation.dart';

  File _imageFile;

  class ImageInput extends StatefulWidget {

  final String title;
  ImageInput({@required this.title});

  //final String _imageFile;
  //final String title;
  //ImageInput(this._imageFile, this.title);

   @override
  _ImageInputState createState() => _ImageInputState();
  }

 class _ImageInputState extends State<ImageInput> {

 void _getImage(BuildContext context, ImageSource source){
ImagePicker.pickImage(source: source, maxWidth: 500.0, imageQuality: 80).then((File image){
  setState((){
    _imageFile = image;
  });
  Navigator.pop(context);

});
}

void _openImagePicker(BuildContext context) {
 showModalBottomSheet(context: context, builder: (BuildContext context) {
  return Container(
    height: 180.0,
    padding: EdgeInsets.all(10.0),
  child: Column(
    children: [
    Text('Choose photo',
      style:TextStyle(fontWeight: FontWeight.bold),),
      SizedBox(height: 10.0),
      FlatButton(
        textColor: Theme.of(context).primaryColor,
        child: Text('Use Camera'),
      onPressed: () {
          _getImage(context, ImageSource.camera);
      },),
      FlatButton(
        textColor: Theme.of(context).primaryColor,child:
      Text('Open Gallery'),
        onPressed: () {
          _getImage(context, ImageSource.gallery);
        },)

    ]
  ),);
});
}

 Future<void> _shareImageAndText() async {
 try {
  List<int> imageBytes = await _imageFile.readAsBytes();
  var uint8List = Uint8List.fromList(imageBytes);
  await Share.file('esys image', 'esys.jpg', uint8List, 'image/jpeg',
      text: widget.title );
      //text:  (snapshot.data.documents[index].data['title']) );        <======= this does not carry over to main page
} catch (e) {
  print('error: $e');
}
}

@override
Widget build(BuildContext context) {
return Column(
  children: <Widget>[
    OutlineButton(
    onPressed: () {
      _openImagePicker(context);
    },
    child:Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Icon(Icons.camera_alt, color: Colors.blue.shade700,),
          SizedBox(
            width:1.0,
          ),
          // Text('Add Image'),
        ]
    ),//Row
  ),//outline button

   SizedBox(height: 1.0),
    _imageFile == null ? Text('Add a Pic')  : Image.file(_imageFile,
        fit: BoxFit.cover,
        height: 200.0,
     width: 200.0,
     // width: MediaQuery.of(context).size.width,
      alignment: Alignment.topCenter,
    ),

    MaterialButton(
      child: Text('Send it!'),
      onPressed: () async => await _shareImageAndText(),
    ),
    //pass the snapshot parameter inside your StreamBuilder
    //onPressed: () async => await _shareText(snapshot, index),

  ],
);
}
}

Then call ImageInput like this

ImageInput(title : snapshot.data.documents[index]['title']),

finally inside your second page's state class access title wherever using

widget.title;//this is your title passed from the first class


text:
Q: Bootstrap nav-tabs Disabled and enabled I need to disabled one of my tab when the page is loaded.
After the user select a iten, it's necessary enable that tab and simulate a click on it.
The disabled event it's work for me, but when I remove disabled class that my "li" the event click in this tab not do nothing...

Pesquisa

Dados do Documento

Disabling the tab

// Desabilita a aba de dados do aço interno
$('#navDadosDocumento').attr('class', 'disabled');

Enabling and click in the tab

$('#navDadosDocumento').removeAttr('class', 'disabled');
$('a[href="#divDetalhes"]').trigger('click');

A: .removeAttr() takes only one parameter, the attribute to remove.
To add and remove classes, jQuery provides .addClass() and .removeClass() methods
Ref: https://api.jquery.com/removeAttr/
https://api.jquery.com/removeClass/
So to make your code work, replace
$('#navDadosDocumento').removeAttr('class', 'disabled');

with
$('#navDadosDocumento').removeClass('disabled');

A: try to something like this.
  $( document ).ready(function() {
    $('#navDadosDocumento').attr('class', 'disabled');
  });
  $( "#divDetalhes" ).click(function() {
    $('#navDadosDocumento').removeAttr('class', 'disabled');
    $('a[href="#divDetalhes"]').trigger('click');
  });

Also check here

$( document ).ready(function() {
    $('#navDadosDocumento').attr('class', 'disabled');
});
$( "#divDetalhes" ).click(function() {
    $('#navDadosDocumento').removeAttr('class', 'disabled');
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Pesquisa

Dados do Documento


text:
Q: Книги по asp.net webforms Нужна книга по веб формам желательно без воды

A: В этой книге доходчиво описывается предмет ASP.NET 4 Unleashed, в оригинале использовал, так как перевода на русский нет но это не критично.


text:
Q: Parse css and create key value array of class names and background images If I have css like this:
.featured .featured_1 {
    background-image: url("http://test.com/image.png");
    margin-top:20px;
}

Then this PHP function:
function makeArrayOfBackroundImages($css) {
    if (!preg_match_all('/\.([a-z\d_]+)\s*\{[^{}]*url\("?([^()]+)"?\)?/i', $css, $arr)) return array();
return array_combine($arr[1], $arr[2]);
}

Creates an array of the class name as the key and the background image as the url.
feature => http://test.com/image.png

How can I modify the regex and this function so it matches both the class names. In this example there is two classes, but the number of classes will be variable and will be one or more so I will need to match all the class names depending on how many there are. For example I would like to create an array like this so both the class names are listed as key with the background image url as the value for both keys. Ignoring any other css properties in the classes.
feature => http://test.com/image.png
featured_1 => http://test.com/image.png

A:
How can I modify the regex and this function so it matches both the class names?

It depends.
Is it always going to be a case where you are matching either one or two? Will there ever be three, four or five?
If it is just two, you can simply repeat the first capture group:
\.([a-z\d_]+)\s*(?:\.([a-z\d_]+)\s*)?\{[^{}]*url\("?([^()]+)"?\)?

http://regex101.com/r/fC7wU2


text:
Q: using array of chars and strdup, getting segmentation fault Suppose i write,
char **p;
p[0] = strdup("hello");

Strdup creates a duplicate string in heap with ending character '\0'; As p is pointer to pointer of char, p[0] = strdup("hello") seems perfectly fine for me. But why am i getting segmentation fault.

A: Let's look at a simpler example.  Suppose you say
int *ip;
ip[0] = 5;

ip is a pointer to one or more ints -- but it's not initialized, so it points nowhere, so ip[0] isn't a valid memory location, so we can't store the value 5 there.
In the same way, when you said
char **p;

p is a pointer that points nowhere.  If it did point somewhere, it would point to another pointer.  But it doesn't point anywhere, so
p[0] = strdup("hello");

blows up.
To fix this, you need to make p point somewhere, and specifically to memory allocated to hold one or more pointers.  There are many ways to do this:
char *q;
p = &q;                                 /* way 1 */

char *a[10];
p = a;                                  /* way 2 */

p = malloc(10 * sizeof(char *));        /* way 3 */

or instead of using a pointer, use an array to start with:
char *p[10];                            /* way 4 */

After any of those, p[0] = strdup("hello") should work.
For way 3, we would also need to check that malloc succeeded (that it dd not return a null pointer).
For ways 2 through 4, we could also set p[1] through p[9].  But for way 1, only p[0] is valid.
See also this answer to a different question for more discussion about trying to use uninitialized pointers.

A: There is declared an uninitialized pointer that has an indeterminate value.
char **p;

so dereferencing the pointer in this expression p[0] (that is equivalent to the expression *p) used in this statement
p[0] = strdup("hello");

invokes undefined behavior because there is an attempt to write to memory using an incorrect pointer value of the expression p[0].
You could write either for example
char *s;
char **p = &s;
p[0] = strdup("hello");

Or
char **p = malloc( sizeof( char * ) );
p[0] = strdup("hello");

That is the pointer to pointer p must point to a valid object. Thus dereferencing the pointer you will get a valid object of the type char * that will be assigned by the value returned by the call of strdup..


text:
Q: Como validar data com AngularJS ou jQuery? Tenho um input simples que recebe uma data, como validar essa data se ela é verdadeira?
Por exemplo:

31/02/2006    isso não existe
  20/20/9999    isso não existe

<input name="data"
 ui-mask="99/99/9999"
 kendo-date-picker name="t"
 ng-model="model.data"
 k-format="'dd/MM/yyyy'">

Ou seja validar dias, meses e anos.
Existe no Angular algo pronto pra isso? Ou se for melhor usar Javascript, me mostrem a forma mais simples.

A: Segue:
Expressão regular:
function isValidDate(date)
{
    var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
    if (matches == null) return false;
    var d = matches[2];
    var m = matches[1] - 1;
    var y = matches[3];
    var composedDate = new Date(y, m, d);
    return composedDate.getDate() == d &&
            composedDate.getMonth() == m &&
            composedDate.getFullYear() == y;
}

Diretiva (Angular)
var app = angular.module("myApp",[]);

function Fiddle($scope){}

app.directive('input-data', function() {
    return {
        restrict: 'E',
        require: '?ngModel',
        link: function(scope, elm, attr, ctrl) {
            if (!ctrl) {
                return;
            }

            elm.bind('keyup', function () {

                var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(this.value);
                if(matches){
                var d = matches[1];
                var m = matches[2] - 1;
                var y = matches[3];

                var composedDate = new Date(y, m, d);
                var valid = composedDate.getDate() == d &&
                    composedDate.getMonth() == m &&
                    composedDate.getFullYear() == y;
                }

                if(!matches || !valid)
                    elm.attr('style', 'border:solid 3px #FE2E2E');
                else
                    elm.removeAttr('style');
            });
        }
    };
});

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

function Fiddle($scope) {}

app.directive('input', function() {
  return {
    restrict: 'E',
    require: '?ngModel',
    link: function(scope, elm, attr, ctrl) {
      if (!ctrl) {
        return;
      }

      elm.bind('keyup', function() {

        var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(this.value);
        if (matches) {
          var d = matches[1];
          var m = matches[2] - 1;
          var y = matches[3];

          var composedDate = new Date(y, m, d);
          var valid = composedDate.getDate() == d &&
            composedDate.getMonth() == m &&
            composedDate.getFullYear() == y;
        }

        if (!matches || !valid)
          elm.attr('style', 'border:solid 3px #FE2E2E');
        else
          elm.removeAttr('style');
      });
    }
  };
});

function validarData() {
  var valid = isValidDate(document.getElementById("ipData").value);
  document.getElementById("ipData").style.border = (!valid ? 'solid 3px #FE2E2E' : '');
};

function isValidDate(date) {
  var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
  if (matches == null) return false;
  var d = matches[2];
  var m = matches[1] - 1;
  var y = matches[3];
  var composedDate = new Date(y, m, d);
  return composedDate.getDate() == d &&
    composedDate.getMonth() == m &&
    composedDate.getFullYear() == y;
}
html,
body {
  height: 100%;
}
body,
form {
  padding: 1em;
}
input,
input.ng-invalid.has-visited.has-focus,
form {
  border: 1px solid #8d8d8d;
}
input,
button {
  border-radius: 3px;
  padding: .25em;
}
body {
  background: #528cc2;
  /* Old browsers */
  background: -moz-linear-gradient(top, #6dbbff 0%, #528cc2 100%);
  /* FF3.6+ */
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #6dbbff), color-stop(100%, #528cc2));
  /* Chrome,Safari4+ */
  background: -webkit-linear-gradient(top, #6dbbff 0%, #528cc2 100%);
  /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(top, #6dbbff 0%, #528cc2 100%);
  /* Opera 11.10+ */
  background: -ms-linear-gradient(top, #6dbbff 0%, #528cc2 100%);
  /* IE10+ */
  background: linear-gradient(to bottom, #6dbbff 0%, #528cc2 100%);
  /* W3C */
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#6dbbff', endColorstr='#528cc2', GradientType=0);
  /* IE6-9 */
  font-family: sans-serif;
}
ul,
li {
  list-style: none;
}
form {
  background: #f7f7f7;
  /* Old browsers */
  background: -moz-linear-gradient(top, #f7f7f7 0%, #e5e5e5 100%);
  /* FF3.6+ */
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f7f7f7), color-stop(100%, #e5e5e5));
  /* Chrome,Safari4+ */
  background: -webkit-linear-gradient(top, #f7f7f7 0%, #e5e5e5 100%);
  /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(top, #f7f7f7 0%, #e5e5e5 100%);
  /* Opera 11.10+ */
  background: -ms-linear-gradient(top, #f7f7f7 0%, #e5e5e5 100%);
  /* IE10+ */
  background: linear-gradient(to bottom, #f7f7f7 0%, #e5e5e5 100%);
  /* W3C */
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#f7f7f7', endColorstr='#e5e5e5', GradientType=0);
  /* IE6-9 */
  border: 1px solid #8d8d8d;
  border-radius: 6px;
  box-shadow: 0 3px 5px rgba(0, 0, 0, .3);
  min-width: 400px;
  margin: auto;
  width: 50%;
}
form li {
  margin-bottom: .5em;
}
label {
  color: #8d8d8d;
  display: block;
  line-height: 1.5;
}
:focus {
  outline: 0;
}
input {
  background: rgba(255, 255, 255, .5);
}
input:focus {
  background: #FFF;
}
input.ng-invalid.has-visited {
  border: 1px solid #E44848;
}
input.ng-valid.has-visited {
  border: 1px solid #a3bf57;
}
.error-message {
  color: #E44848;
}
button {
  background: #528CC2;
  color: white;
  cursor: pointer;
  border: 0;
}
button:disabled {
  background: rgba(82, 140, 194, 0.5);
  color: rgba(255, 255, 255, .5);
  font-weight: 400;
}

<form name="myForm" novalidate ng-app="myApp">

      Diretiva Angular
      <input input-data type="datetime" ng-model="barthirty" required />

      Expressao regular
      <input type="datetime" id="ipData" required onkeyup="validarData()"/>

  <button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>

A: Maneira simples, utilizando javascript puro:
Tente realizar um parse dinâmico via construtor de Date(). Se funcionar, a data é válida. Exemplo para datas em formato imperial:
var isValidDate = function(str) {
    return !!new Date(str).getTime();
}

Ou a versão para formato brasileiro:
var isValidDate = function(str) {
    return str == 'dd/mm/yyyy' ||
           ( /^\d{2}\/\d{2}\/\d{4}$/.test(str) && new Date(str).getTime() );
}

Para seus exemplos,
isValidDate('31/02/2006'); // false
isValidDate('20/20/9999'); // false

Porém,
isValidDate('01/31/2006'); //true
isValidDate('01/20/9999'); //true

Versão executável a seguir (no Chrome, pressione F12 antes de clicar em Executar trecho de código de maneira que possa ver o log do console):

var isValidDate = function(str) {
    return !!new Date(str).getTime();
}

console.log(isValidDate('31/02/2006'));
console.log(isValidDate('20/20/9999'));

console.log(isValidDate('01/31/2006'));
console.log(isValidDate('01/20/9999'));

A: Você pode utilizar o jQuery Validation para validar seus campos. Ele está somente em inglês, mas possui algumas bibliotecas para tradução. Uma alternativa é utilizar essas extensões.
Onde você adiciona a validação em seu formulário, desta forma:
$( "#myform" ).validate({
  rules: {
    data: {
      required: true,
      dateBR: true
    }
  }
});

E para traduzir as validações, você adiciona esse método:
jQuery.validator.addMethod("dateBR", function (value, element) {
    //contando chars
    if (value.length != 10) return (this.optional(element) || false);
    // verificando data
    var data = value;
    var dia = data.substr(0, 2);
    var barra1 = data.substr(2, 1);
    var mes = data.substr(3, 2);
    var barra2 = data.substr(5, 1);
    var ano = data.substr(6, 4);
    if (data.length != 10 || barra1 != "/" || barra2 != "/" || isNaN(dia) || isNaN(mes) || isNaN(ano) || dia > 31 || mes > 12) return (this.optional(element) || false);
    if ((mes == 4 || mes == 6 || mes == 9 || mes == 11) && dia == 31) return (this.optional(element) || false);
    if (mes == 2 && (dia > 29 || (dia == 29 && ano % 4 != 0))) return (this.optional(element) || false);
    if (ano < 1900) return (this.optional(element) || false);
    return (this.optional(element) || true);
}, "Informe uma data válida");

Desta forma estará validando datas maiores que 1900.
Lembrando que é necessário separar por /. Mas a máscara creio que você já está fazendo.
Para o seu exemplo, ficaria assim:

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title> - Validade Example</title>

  <link rel="stylesheet" type="text/css" href="/css/result-light.css">

  <form id="myform" novalidate="novalidate">
Data:
<input class="left" id="data" name="data">

<input type="submit" value="Validate!">
</form>

Exemplo JsFiddle

A: O angular não oferece nenhum tipo de função para validar datas, pelo menos não que eu saiba, mas existem diversas diretivas que se encarregam de fazer isso.

Como alternativa existe a biblioteca de javascript Moment.js (http://momentjs.com/) que oferece uma gama de métodos para trabalho com datas.

Além disso, você pode utilizar alguma lib de datepicker conforme lembrado pelo @Techies, segue o exemplo de diretiva angular fornecido por ele: http://720kb.github.io/angular-datepicker/ ou o Jquery-UI datepicker: https://jqueryui.com/datepicker/

A: Vou te passar um código que uso aqui em javascript puro, esse monstrinho valida tudo vai resolver seu problema:
        function validateDate(id) {
      var RegExPattern = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])      [\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/;

     if (!((id.value.match(RegExPattern)) && (id.value!=''))) {
          alert('Data inválida.');
   id.focus();
        }
       else
        alert('Data válidaa.');
    }

A: Segue a função para validar datas em javascript.

if(validateDate("10/01/1985"))
    console.log("OK");
else
    console.log("ERRO");

function validateDate(data) {
        // Ex: 10/01/1985
        var regex = "\\d{2}/\\d{2}/\\d{4}";
        var dtArray = data.split("/");

        if (dtArray == null)
            return false;

        // Checks for dd/mm/yyyy format.
        var dtDay= dtArray[0];
        var dtMonth = dtArray[1];
        var dtYear = dtArray[2];

        if (dtMonth < 1 || dtMonth > 12)
            return false;
        else if (dtDay < 1 || dtDay> 31)
            return false;
        else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
            return false;
        else if (dtMonth == 2)
        {
            var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
            if (dtDay> 29 || (dtDay ==29 && !isleap))
                return false;
        }
        return true;
    }


text:
Q: How to call QMainWindow class method from within extended QListWidget class dropEvent? Here is a working piece of source code.
When you run it, simply drag and drop an item from the first listWidget to the second listWidget.
I have a print statement in the dropEvent where I'd like to call the parent QMainWindow's method named "special".
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt,QString
import sys, os

class ThumbListWidget(QtGui.QListWidget):
    _rows_to_del=[]

    def __init__(self, type, parent=None):
        super(ThumbListWidget, self).__init__(parent)
        self.setIconSize(QtCore.QSize(124, 124))
        self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
        self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.setAcceptDrops(True)
        self._dropping = False

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.accept()
        else:
            super(ThumbListWidget, self).dragEnterEvent(event)

    def dragMoveEvent(self, event):
        if event.mimeData().hasUrls():
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
        else:
            super(ThumbListWidget, self).dragMoveEvent(event)

    def dropEvent(self, event):

        print "How can I call the main window class method called 'special' here?"

        if event.mimeData().hasUrls():
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
            links = []
            for url in event.mimeData().urls():
                links.append(str(url.toLocalFile()))
            self.emit(QtCore.SIGNAL("dropped"), links)
        else:
            event.setDropAction(QtCore.Qt.CopyAction)
            self._dropping = True
            super(ThumbListWidget, self).dropEvent(event)
            self._dropping = False

    def rowsInserted(self, parent, start, end):
        if self._dropping:
            self.emit(QtCore.SIGNAL("dropped"), (start, end))
        super(ThumbListWidget, self).rowsInserted(parent, start, end)

    def dataChanged(self,start,end):
        if self._dropping:
            for row in range(start.row(),end.row()+1):
                index = self.indexFromItem(self.item(row))
                shot = index.data().toString()
                #print len(self.findItems(shot,Qt.MatchExactly))
                if len(self.findItems(shot,Qt.MatchExactly))>1:
                    self._rows_to_del.append(row)

            self._rows_to_del.reverse()

            for row in self._rows_to_del:
                self.takeItem(row)

            self._rows_to_del=[]

class Dialog_01(QtGui.QMainWindow):
    def __init__(self):
        super(QtGui.QMainWindow,self).__init__()
        self.listItems={}

        myQWidget = QtGui.QWidget()
        myBoxLayout = QtGui.QVBoxLayout()
        myQWidget.setLayout(myBoxLayout)
        self.setCentralWidget(myQWidget)

        self.listWidgetA = ThumbListWidget(self)
        for i in range(12):
            QtGui.QListWidgetItem( 'Item '+str(i), self.listWidgetA )

        all_items =  self.listWidgetA.findItems(QString('*'), Qt.MatchWrap | Qt.MatchWildcard)
        for item in all_items:
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable )
            # item.setCheckState(Qt.Checked)

        myBoxLayout.addWidget(self.listWidgetA)

        self.listWidgetB = ThumbListWidget(self)

        self.listWidgetA.setAcceptDrops(False)

        myBoxLayout.addWidget(self.listWidgetB)

        self.connect(self.listWidgetA, QtCore.SIGNAL("dropped"), self.items_dropped)
        self.listWidgetA.currentItemChanged.connect(self.item_clicked)

        self.connect(self.listWidgetB, QtCore.SIGNAL("dropped"), self.items_dropped)
        self.listWidgetB.currentItemChanged.connect(self.item_clicked)

    def items_dropped(self, arg):
        print 'items_dropped', arg
        start,end = arg
        #print range(start,end+1)
        for row in range(start,end+1):
            item = self.listWidgetB.item(row)
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable )
            item.setCheckState(Qt.Checked)

    def special(self):
        print "special called"

    def item_clicked(self, arg):
        print "arg=",arg

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    dialog_1 = Dialog_01()
    dialog_1.show()
    dialog_1.resize(480,320)
    sys.exit(app.exec_())

A: In this case, you're passing the window along to the constructor of your custom widget as self, which becomes the parent of your custom widget.  So you should just be able to do
window = self.parent()
window.special()

You could also use the Qt event system to emit an event that your main window could connect to and call the special method itself.
class ThumbListWidget(QtGui.QListWidget):
    my_signal = pyqtSignal()

    def dropEvent(self, event):
        self.my_signal.emit()

class Dialog_01(QtGui.QMainWindow):
    def __init__(self):
        ...
        self.listWidgetB = ThumbListWidget(self)
        self.listWidgetB.my_signal.connect(self.special)


text:
Q: What's the difference between Windows 8 N (x64) - DVD (English) and Windows 8 (x64) - DVD (English)
Possible Duplicate:
Windows 8 Versions (Final Release)

Windows 8 got released on MSDN 15/8.
I have a subscription to MSDN thru work and wanted to download it. But for each windows 8 there are 2 editions, one have the appending "N".
Is this a language indication? N for "norwegian" maybe? (my MSDN and myself are norwegian)

A: "Windows 7 N
Fast-forward to today, and a Microsoft spokesperson explained to CNET UK, "The European Commission's 2004 decision requires Microsoft to offer an N version of Windows in Europe. We continue to abide by this ruling."
And so Windows 7 N was born. They cost the same as their non-'N' brothers and sisters, and apart from Windows Media Player, offer the same spread of features.
All you have to do now is decide which of the six non-N versions are right for you, and, wouldn't you know it, we have a handy, simple guide for that as well,"
Source

A: No, "N" editions are released in Europe and don't contain Media Player. Beside the lack of a Windows Media Player, there is no other difference.


text:
Q: How to resolve this MySQL error in Mac OS X Sierra? I have been trying to reset the root password for MySQL on my Mac OS X Sierra and I cannot believe I can't find documentation for this anywhere that can resolve my problem.
The first error I got when I tried to access my database is this:
Error: Access denied for user 'root'@'localhost' (using password: NO)

I figured I would completely remove MySQL and install it again with brew but when I tried with mysql_secure_installation and I get this:
Securing the MySQL server deployment.

Enter password for user root:
Error: Access denied for user 'root'@'localhost' (using password: NO)

Also when I try to run:
mysql.server stop

I get this error:
 ERROR! MySQL server PID file could not be found!

A: On mac, I think you have to use root as a password.

A: *

*open mysqld_safe
mysql.server stop
mysqld_safe --skip-grant-tables

*open a new terminal
mysql -uroot -p
use mysql;
update user set password=PASSWORD('123456') where user="root";
flush privileges;
quit;

*close mysqld_safe terminal

*restart mysql
mysql.server start
mysql -uroot -p
123456


text:
Q: How to fetch latest rows from oracle db I tried to use max() function to fetch the latest record from my table but I don't know it's a proper way to fetch the latest record from DB or not.
Query
    select max(writime) from my_table;

writime is epoch time like 1210528050500000 . How to get the latest value/ last row. Need help

A: You can do this two ways:

*

*A subquery in the WHERE clause (will return all rows with the max time, may be more than one)

*Use ORDER BY and ROWNUM to select a row based on criteria you specify (guarantees just one row - but will need to be very specific in order to be deterministic)

Subquery:
SELECT
  <whatever>
FROM
  my_table
WHERE
  writime =
    (
      SELECT
        MAX(writime)
      FROM
        my_table
    )

As I mentioned earlier, if multiple rows have the same value for writime this query will return all of those rows.  If this is your desired output (or acceptable), great!
If not, you'll need to use ROWNUM (see this article for more detail/optimization considerations1):
SELECT
  *
FROM
  (
    SELECT
      <whatever>
    FROM
      my_table
    ORDER BY
      writime DESC
     ,<additional sort columns>
  )
WHERE
  ROWNUM = 1

This is guaranteed to return just one row.  HOWEVER, this is not guaranteed to return exactly the same row (given the same point in time) unless you provide additional criteria in the ORDER BY statement - generally this would be some columns chosen for business context plus the primary key column(s)2 of the table.
You certainly can combine these approaches (which may be better from a performance perspective, depending on what indexes exist on the table and how the data is distributed):
SELECT
  *
FROM
  (
    SELECT
      <whatever>
    FROM
      my_table
    WHERE
      writime =
        (
          SELECT
            MAX(writime)
          FROM
            my_table
        )
    ORDER BY
      <additional sort columns>
  )
WHERE
  ROWNUM = 1

1 Because selecting the top N requires a sort of the heap (in the absence of the table organized by writime or a covering index), this can be a very expensive operation.  You'll need to look at how your table is structured/indexed to determine what the ideal query is - the Ask Tom article has some methods to achieve this.
2 Because the primary key is unique, sorting based on its column(s) will guarantee the same sort order each time.

A: To return the row with the current highest value of writime, you can just do
select * from my_table
order by writetime desc
fetch first 1 row only

If you want all the rows that share the same maximum writetime value you would use the with ties option:
select * from my_table
order by writetime desc
fetch first 1 row with ties

Few things to consider:

*

*If the column is nullable, null values will be returned first. You probably want to include an additional where writetime is not null filter to ensure this doesn't happen and also allow an index to be used (not needed if the column is declared not null)

*You can only read rows that have been committed. Some process may have inserted a row with a higher value writetime but has not yet committed, you will be ignoring that when you select from the table.

*It's a bit of a weird query to be writing for an application

A: The only way is to have a date or timestamp field in your table that is populated by SYSDATE or SYSTIMESTAMP at the time of insertion. Then only can you select the max value of that column.


text:
Q: Cannot update/install other software after failing to install LibreOffice I tried to install LibreOffice through the software centre but an error occurred and the installation failed. Now it is shown as "installed" in software centre while it's actually not. I realised it was because I have OpenOffice4.1.1 installed. I tried to remove OpenOffice but so far none of the commands I found on any of the internet forums worked.
The software centre is now stuck in a loop of repairing and failing to repair the problem caused by OpenOffice. Now my laptop can neither update nor install other software. I manually removed the all the LibreOffice files in a terminal and hoped that it would stop the process, but of course it didn't. Could someone please let me know how I could stop the installation process of LibreOffice for now? Thanks in advance.
Here is the error I get when software centre tried to repair the problem:
installArchives() failed:
Preparing to unpack .../libreoffice-common_1%3a4.2.8-0ubuntu2_all.deb ...
Unpacking libreoffice-common (1:4.2.8-0ubuntu2) ...
dpkg:
error processing archive /var/cache/apt/archives/libreoffice-common_1%3a4.2.8-0ubuntu2_all.deb (--unpack):
trying to overwrite '/usr/bin/soffice', which is also in package openoffice-debian-menus 4.1.1-9775
rmdir: failed to remove /var/lib/libreoffice/share/prereg/: No such file or directory
rmdir: failed to remove /var/lib/libreoffice/share/: No such file or directory
rmdir: failed to remove /var/lib/libreoffice/program/: No such file or directory
rmdir: failed to remove /var/lib/libreoffice: No such file or directory
rmdir: failed to remove /var/lib/libreoffice: No such file or directory
Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
Processing triggers for gnome-icon-theme (3.10.0-0ubuntu2) ...
Processing triggers for hicolor-icon-theme (0.13-1) ...
Processing triggers for shared-mime-info (1.2-0ubuntu3) ...
Unknown media type in type 'all/all'
Unknown media type in type 'all/allfiles'
Unknown media type in type 'uri/mms'
Unknown media type in type 'uri/mmst'
Unknown media type in type 'uri/mmsu'
Unknown media type in type 'uri/pnm'
Unknown media type in type 'uri/rtspt'
Unknown media type in type 'uri/rtspu'
Processing triggers for mime-support (3.54ubuntu1.1) ...
Processing triggers for gnome-menus (3.10.1-0ubuntu2) ...
Processing triggers for desktop-file-utils (0.22-1ubuntu1) ...
Processing triggers for bamfdaemon (0.5.1+14.04.20140409-0ubuntu1) ...
Rebuilding /usr/share/applications/bamf-2.index...
Errors were encountered while processing:
 /var/cache/apt/archives/libreoffice-common_1%3a4.2.8-0ubuntu2_all.deb
Error in function:
dpkg: dependency problems prevent configuration of libreoffice-l10n-en-gb: libreoffice-l10n-en-gb depends on libreoffice-common; however: Package libreoffice-common is not installed.
dpkg: error processing package libreoffice-l10n-en-gb (--configure): dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of libreoffice-java-common:  libreoffice-java-common depends on libreoffice-common; however: Package libreoffice-common is not installed.
dpkg: error processing package libreoffice-java-common (--configure): dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of libreoffice-l10n-en-za: libreoffice-l10n-en-za depends on libreoffice-common; however: Package libreoffice-common is not installed.
dpkg: error processing package libreoffice-l10n-en-za (--configure): dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of libreoffice-help-en-gb:
 libreoffice-help-en-gb depends on libreoffice-l10n-en-gb; however:
  Package libreoffice-l10n-en-gb is not configured yet.
dpkg: error processing package libreoffice-help-en-gb (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of libreoffice-sdbc-hsqldb:
 libreoffice-sdbc-hsqldb depends on libreoffice-java-common (>= 1:4.2.8~); however:
  Package libreoffice-java-common is not configured yet.
dpkg: error processing package libreoffice-sdbc-hsqldb (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of libreoffice-l10n-ja:
 libreoffice-l10n-ja depends on libreoffice-common; however:
  Package libreoffice-common is not installed.
dpkg: error processing package libreoffice-l10n-ja (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of libreoffice-help-en-us:
 libreoffice-help-en-us depends on libreoffice-l10n-en-us; however:
  Package libreoffice-l10n-en-us is not installed.
dpkg: error processing package libreoffice-help-en-us (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of libreoffice-core:
 libreoffice-core depends on libreoffice-common (>> 1:4.2.8); however:
  Package libreoffice-common is not installed.
dpkg: error processing package libreoffice-core (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of python3-uno:
 python3-uno depends on libreoffice-core (= 1:4.2.8-0ubuntu2); however:

A: This is the problem:

trying to overwrite '/usr/bin/soffice', which is also in package
  openoffice-debian-menus 4.1.1-9775

Therefore open a terminal and remove the package openoffice-debian-menus with the command
sudo apt-get purge openoffice-debian-menus

After that repair your installation:
sudo apt-get install -f

A: Just run this command :
sudo apt-get remove --purge libreoffice-core libreoffice-common python3-uno libreoffice-*

as libreoffice and openoffice use same soffice so the error is there.

A: This worked for me:
sudo apt-get remove --purge libreoffice-core libreoffice-common unoconv python3-uno libreoffice-*

It seems that unoconv broke something and prevented to remove its own package which depends on libreoffice.


text:
Q: Electron - Typescript - Cannot find module Trying to build my electron app with typescript generated from the electron-quick-start-typescript project. I have added an additional module called auth.ts which is not recognised when I start the app. I am trying to reference it in renderer.ts with
import { myfunction } from './auth'

However I can see that it is getting converted into js. What could be causing this issue? Why can't my application see my new module?

Additionally here is my package.json file if that helps.
{
  "name": "electron-quick-start-typescript",
  "version": "1.0.0",
  "description": "A minimal Electron application written with Typescript",
  "scripts": {
    "build": "tsc",
    "watch": "tsc -w",
    "lint": "eslint -c .eslintrc --ext .ts ./src",
    "start": "npm run build && electron ./dist/main.js"
  },
  "repository": "https://github.com/electron/electron-quick-start-typescript",
  "keywords": [
    "Electron",
    "quick",
    "start",
    "tutorial",
    "demo",
    "typescript"
  ],
  "author": "GitHub",
  "license": "CC0-1.0",
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^4.33.0",
    "@typescript-eslint/parser": "^4.33.0",
    "electron": "^16.0.2",
    "eslint": "^7.32.0",
    "typescript": "^4.5.2"
  },
  "dependencies": {
    "node-fetch": "^2.6.1"
  }
}

A: Found the answer. For anyone else having the same issue this resolved the issue -
Make sure nodeIntegration is enabled in main.js
webPreferences: {
      nodeIntegration: true,
      preload: path.join(__dirname, "preload.js"),
    },

Index.html
replace:
<script src="./dist/renderer.js"></script>

with:
<script>
    require("./dist/renderer.js");
</script>


text:
Q: Is there a way to use NVARCHAR2 data type in COLUMNS clause of JSON_TABLE? SET SERVEROUTPUT ON
DECLARE
  sample_json   NVARCHAR2(111):= '[{"NAME":"ĄŚĆĘąśćę"},{"NAME":"ЙйКкЛлМм"}]';
  part          NVARCHAR2(111);
BEGIN
 SELECT j.name into part
   FROM JSON_TABLE(sample_json,
                   '$[*]' COLUMNS
                   name NVARCHAR2(20) PATH '$.NAME'
                  ) j
   WHERE j.name ='ЙйКкЛлМм';
END;

Got this error:

PL/SQL: ORA-40484:
My DB NLS_CHARACTERSET: EE8ISO8859P2


text:
Q: Is it possible to align a menu to the right of the menu bar using wxPython? I'm trying to create a menu bar in wxPython 2.8.11.0 and Python 2.7 where most of the menus are left aligned (as normal) but one is - ideally - right aligned, or at least separated in some way from the rest.
Is this possible?
EDIT: This needs to be a cross-platform solution.

A: If the native menubar doesn't support it, then wxPython probably won't either. There is a pure Python implementation of the menubar though. It's called FlatMenu. I would try that. If it doesn't work, at least you can hack it or submit a patch in Python code rather than trying to figure out the C++ for fixing wxWidgets.


text:
Q: SQL Access — Limit subquery only I'm trying to obtain a list of actors a particular director has worked with, and a list of films that these actors have been in from a movie database.
SELECT DISTINCT A_First_Name, A_Last_Name, Film_Title
FROM

  (SELECT *
  FROM Actor, Film, Film_Actor_Director_Genre
  WHERE Actor.AID=Film_Actor_Director_Genre.AID
  AND Film.FID=Film_Actor_Director_Genre.FID)

WHERE A_First_Name IN

  (SELECT A_First_Name
  FROM

    (SELECT *
    FROM Actor, Director,
    Film_Actor_Director_Genre
    WHERE
    Actor.AID=Film_Actor_Director_Genre.AID
    AND
    Director.DID=Film_Actor_Director_Genre.DID)

  WHERE D_First_Name=[Director's first name?]
  OR D_Last_Name=[Director's last name?]);

Assuming I want to know the list of actors that director D01 has worked with, the sample result is like so:
Actor    Film
-----    ----
A01      F01
A01      F02
A01      F03
A01      F04
A02      F01
A02      F02
A02      F05
A02      F06
A03      F01
A04      F01
A04      F02
A04      F09
A05      F01
A05      F02
A06      F10
A07      F01
A07      F02
A07      F04
etc.     etc.

However as the list of actors D01 has worked with could be extremely long, I would like to show only the top 5 actors (i.e. actors that worked in most no. films with D01), and all the films the actors have been in. So I want to only limit actors but not films. The desired result would be:
Actor    Film
-----    ----
A01      F01
A01      F02
A01      F03
A01      F04
A02      F01
A02      F02
A02      F05
A02      F06
A04      F01
A04      F02
A04      F09
A05      F01
A05      F02
A07      F01
A07      F02
A07      F04

I tried to implement the SELECT DISTINCT TOP 5 syntax in various subqueries but they returned strange combinations of 5 results, e.g.
Actor    Film
-----    ----
A01      F01
A01      F02
A02      F01
A02      F02
A06      F10

How can I limit the results to show only the top 5 actors that have worked with D01 and the all the films these actors have acted in? Thanks for your time, would appreciate any help I can get!

A: I think something like this will work
select
  *
from
  actors a

  inner join film_actor_director_genre fadg on
    on fadg.aid = a.aid

  inner join film f on
    f.fid = fadg.fid

  -- This should return all actors that have been in
  -- at lead 5 movies with a director. Note the count
  -- ordering and limit
  inner join (
    select top 5
      a.aid
    from
      film_actor_director_genre
    group by
      a.aid,
      d.did
    having
      count(*) >= 5
    order by
      count(*)
  ) t1 on
    t1.aid = a.aid

Little tricky with out being able to test the query. Should work!

A: This is access?
Assuming his query is correct, you can replace the limit (and having) with something a little more simple:
 select top 5 aid, count(*) as qty from film_actor_director_genre group by aid, did order by 2 desc

If access can't handle that order by clause you can switch it back to
 select top 5 aid, count(*) as qty from film_actor_director_genre group by aid, did order by count(*) desc


text:
Q: Overhead for MySQL SELECTS - Better to Use One, or Many In Sequence Is there an appreciable performance difference between having one SELECT foo, bar, FROM users query that returns 500 rows, and 500 SELECT foo, bar, FROM users WHERE id = x queries coming all at once?
In a PHP application I'm writing, I'm trying to choose between a writing clear, readable section of code that would produce about 500 SELECT statements; or writing a it in an obscure, complex way that would use only one SELECT that returns 500 rows.
I would prefer the way that uses clear, maintainable code, but I'm concerned that the connection overhead for each of the SELECTs will cause performance problems.
Background info, in case it's relevant:
1) This is a Drupal module, coded in PHP
2) The tables in question get very few INSERTs and UPDATEs, and are rarely locked
3) SQL JOINs aren't possible for reasons not relevant to the question
Thanks!

A: It's almost always faster to do one big batch SELECT and parse the results in your application code than doing a massive amount of SELECTs for one row. I would recommend that you implement both and profile them, though. Always strive to minimize the number of assumptions you have to make.

A: I would not worry about the connection overhead of mysql queries too much, especially if you are not closing the connection between every query. Consider that if your query creates a temporary table, you've already spent more time in the query than the overhead of the query took.
I love doing a complex SQL query, personally, but I have found that the size of the tables, mysql query cache and query performance of queries that need to do range checking (even against an index) all make a difference.
I suggest this:
1) Establish the simple, correct baseline. I suspect this is the zillion-query approach. This is not wrong, and very likely helfully correct. Run it a few times and watch your query cache and application performance. The ability to keep your app maintainable is very important, especially if you work with other code maintainers. Also, if you're querying really large tables, small queries will maintain scalability.
2) Code the complex query. Compare the results for accuracy, and then the time. Then use EXPECT on the query to see what the rows scanned are. I have often found that if I have a JOIN, or a WHERE x != y, or a condition that creates a temporary table, the query performance could get pretty bad, especially if I'm in a table that's always getting updated. However, I've also found that a complex query might not be correct, and also that a complex query can more easily break as an application grows. Complex queries typically scan larger sets of rows, often creating temporary tables and invoke using where scans.  The larger the table, the more expensive these get. Also, you might have team considerations where complex queries don't suit your team's strengths.
3) Share the results with your team.
Complex queries are less likely to hit the mysql query cache, and if they are large enough, don't cache them. (You want to save the mysql query cache for frequently hit queries.) Also, query where predicates that have to scan the index will not do as well. (x != y, x > y, x < y). Queries like SELECT foo, bar FROM users WHERE foo != 'g' and mumble < '360' end up doing scans. (The cost of query overhead could be negligible in that case.)
Small queries can often complete without creating temporary tables just by getting all values from the index, so long as the fields you're selecting and predicating on are indexed. So the query performance of SELECT foo, bar FROM users WHERE id = x is really great (esp if columns foo and bar are indexed like, aka alter table users add index ix_a ( foo, bar );.)
Other good ways to increase performance in your application would be to cache those small query results in the application (if appropriate), or doing batch jobs of a materialized view query. Also, consider memcached or some features found in XCache.

A: It seems like you know what the 500 id values are, so why not do something like this:
// Assuming you have already validated that this array contains only integers
// so there is not risk of SQl injection

$ids = join(',' $arrayOfIds);

$sql = "SELECT `foo`, `bar` FROM `users` WHERE `id` IN ($ids)";


text:
Q: from nltk.chat.util import Chat, reflections ModuleNotFoundError: No module named 'nltk' I have installed nltk library in my laptop but when I try to import it in my pycharm project, it says ModuleNotFoundError: No module named 'nltk' . What should I do?
This is my console response when I type pip3 list:
Package           Version
----------------- ---------
blis              0.2.4
certifi           2019.9.11
chardet           3.0.4
ChatterBot        1.0.5
chatterbot-corpus 1.2.0
cycler            0.10.0
cymem             2.0.3
idna              2.8
kiwisolver        1.1.0
mathparse         0.1.2
matplotlib        3.1.1
MouseInfo         0.1.2
murmurhash        1.0.2
nltk              3.4.5
numpy             1.17.2
opencv-python     4.2.0.32
panda             0.3.1
pandas            0.25.1
Pillow            6.2.0
Pint              0.10.1
pip               20.0.2
plac              0.9.6
preshed           2.0.1
PyAutoGUI         0.9.48
PyGetWindow       0.0.8
pymongo           3.10.1
PyMsgBox          1.0.7
pyparsing         2.4.2
pyperclip         1.7.0
PyRect            0.1.4
PyScreeze         0.1.26
python-dateutil   2.7.5
PyTweening        1.0.3
pytz              2019.2
PyYAML            5.1.2
reportlab         3.5.28
requests          2.22.0
selenium          3.141.0
setuptools        40.8.0
six               1.12.0
spacy             2.1.9
SQLAlchemy        1.2.19
srsly             1.0.1
thinc             7.0.8
tqdm              4.41.1
urllib3           1.25.6
wasabi            0.6.0
xlrd              1.2.0

As this shows, nltk is installed but when I run the below code :
from nltk.chat.util import Chat, reflections

It shows :
from nltk.chat.util import Chat, reflections
ModuleNotFoundError: No module named 'nltk'

I experienced this same error while using chatterbot library. What is the solution?

A: Got the answer!
Just had to install the libraries in my pycharm by:

File -> Settings( Preferences in mac ) -> Project:yourProjectName -> Project Interpreter -> '+' button on the right side -> type the library name in the search box -> Click install and you are done!


text:
Q: how windows or linux resolve file rename/move/copy I wonder how linux and windows resolve file rename or file move (drag and drop) at low level?
In java we have File.move but I don't know how it really works ?
In apache common we have FileUtils.moveFile
What "move file" does mean in linux and windows? Does systems put in memory file when moving/rename file then create new file and delete old one ?

A: Copy and rename are different operations.

*

*Copy produces a new file.  It is done by copying bytes1; e.g. open files and use read / write syscalls to copy the bytes.

*Rename changes the pathname for an existing file.   It is done by a syscall that changes the metadata for a file and the source and destination directories.

There are a couple of wrinkles.

*

*Rename (on Linux) only works within a file system.  You cannot rename a file to a pathname in a different file system.

*There is no "move" syscall in Linux / POSIX libraries.  So (for example) the mv command on Linux will either rename the file, or make a copy (and delete the original), depending on where source and destination are.

*Copying a file could be implemented in a lazy way using copy-on-write.  For example, the "btrfs" supports copy-on-write, and it is possible that this functionality could be exposed to the application.
In a Java application, copy is implemented by copying the bytes of the file, and rename is implemented by calling the OS-provide rename syscall (see above).  The move verb is typically a hybrid of copy and move as above.
That is the simple version.  In practice, performance also depends on how the file system metadata is organized and stored, and on the various "tricks" that the OS uses to speed things up; e.g. caching metadata and file data in memory, read ahead / write behind, using "metadata transaction logs" to speed up metadata operations.  And there are hardware-basewd tuning tricks like putting the metadata onto storage media with higher IOPs per second than the data.   (This is particularly necessary if you are dealing with file systems with tens of millions of files ...)

1 - Actually, opening a file and creating a new one both involve reading and writing metadata, but this only happens once per file copied.  By contrast, if you are copying a file, you typically have to write (and possibly read) all disk blocks for the file.  For a large file, the reads and writes will dominate the metadata operations.