text:
Q: How to query an elasticsearch aggregation with a term and sum on different nested objects? I have the following object whose value attribute is a nested object type:
{
    "metadata": {
        "tenant": "home",
        "timestamp": "2016-03-24T23:59:38Z"
    },
    "value": {
        { "key": "foo", "int_value": 100 },
        { "key": "bar", "str_value": "taco" }
    }
}

This type of object has the following mapping:
{
    "my_index": {
        "mappings": {
            "my_doctype": {
                "properties": {
                    "metadata": {
                        "properties": {
                            "tenant": {
                                "type": "string",
                                "index": "not_analyzed"
                            },
                            "timestamp": {
                                "type": "date",
                                "format": "dateOptionalTime"
                            }
                        }
                    },
                    "value": {
                        "type": "nested",
                        "properties": {
                            "str_value": {
                                "type": "string",
                                "index": "not_analyzed"
                            },
                            "int_value": {
                                "type": "long"
                            },
                            "key": {
                                "type": "string",
                                "index": "not_analyzed"
                            }
                        }
                    }
                }
            }
        }
    }
}

With this setup, I would like to perform an aggregation that performs the following result:

*

*Perform a term aggregation on the str_value attribute of objects where the key is set to "bar"

*In each bucket created from the above aggregation, calculate the sum of the int_value attributes where the key is set to "foo"

*Have the results laid out in a date_histogram for a given time range.

With this goal in mind, I have been able to get the term and date_histogram aggregations to work on my nested objects, but have not had luck performing the second level of calculation. Here is the current query I am attempting to get working:
{
  "query": {
    "match_all": {}
  },
  "aggs": {
    "filters": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "metadata.org": "gw"
              }
            },
            {
              "range": {
                "metadata.timestamp": {
                  "gte": "2016-03-24T00:00:00.000Z",
                  "lte": "2016-03-24T23:59:59.999Z"
                }
              }
            }
          ]
        }
      },
      "aggs": {
        "intervals": {
          "date_histogram": {
            "field": "metadata.timestamp",
            "interval": "1d",
            "min_doc_count": 0,
            "extended_bounds": {
              "min": "2016-03-24T00:00:00Z",
              "max": "2016-03-24T23:59:59Z"
            },
            "format": "yyyy-MM-dd'T'HH:mm:ss'Z'"
          },
          "aggs": {
            "nested_type": {
              "nested": {
                "path": "value"
              },
              "aggs": {
                "key_filter": {
                  "filter": {
                    "term": {
                      "value.key": "bar"
                    }
                  },
                  "aggs": {
                    "groupBy": {
                      "terms": {
                        "field": "value.str_value"
                      },
                      "aggs": {
                        "other_nested": {
                          "reverse_nested": {
                            "path": "value"
                          },
                          "aggs": {
                            "key_filter": {
                              "filter": {
                                "term": {
                                  "value.key": "foo"
                                }
                              },
                              "aggs": {
                                "amount_sum": {
                                  "sum": {
                                    "field": "value.int_value"
                                  }
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

The result I am expecting to receive from Elasticsearch would look like the following:
{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 7,
    "max_score": 0.0,
    "hits": []
  },
  "aggregations": {
    "filters": {
      "doc_count": 2,
      "intervals": {
        "buckets": [
          {
            "key_as_string": "2016-03-24T00:00:00Z",
            "key": 1458777600000,
            "doc_count": 2,
            "nested_type": {
              "doc_count": 5,
              "key_filter": {
                "doc_count": 2,
                "groupBy": {
                  "doc_count_error_upper_bound": 0,
                  "sum_other_doc_count": 0,
                  "buckets": [
                    {
                      "key": "taco",
                      "doc_count": 1,
                      "other_nested": {
                        "doc_count": 1,
                        "key_filter": {
                          "doc_count": 1,
                          "amount_sum": {
                            "value": 100.0
                          }
                        }
                      }
                    }
                  ]
                }
              }
            }
          }
        ]
      }
    }
  }
}

However, the innermost object (...groupBy.buckets.key_filter.amount_sum) is having its value return 0.0 instead of 100.0.
I think this is due to the fact that nested objects are indexed as separate documents, so filtering by one key attribute's value is not allowing me to query to against another key.
Would anyone have any idea on how to get this type of query to work?
For a bit more context, the reason for this document structure is because I do not control the content of the JSON documents that get indexed, so different tenants may have conflicting key names with different values (e.g. {"tenant": "abc", "value": {"foo": "a"} } vs. {"tenant": "xyz", "value": {"foo": 1} }. The method I am trying to use is the one laid out by this Elasticsearch Blog Post, where it recommends to transform objects that you don't control into a structure that you do and to use nested objects to help with this (specifically the Nested fields for each data type section of the article). I would also be open to learn of a better way to handle this situation of not controlling the document's JSON structure if there is one so that I can perform aggregations.
Thank you!
EDIT: I am using Elasticsearch 1.5.

A: Solved this situation by utilizing the reverse_nested aggregation in the correct way as described here: http://www.shayne.me/blog/2015/2015-05-18-elasticsearch-nested-docs/


text:
Q: Картинка поверх Input Здравствуйте! Мне нужно сделать смайлик поверх Input'а, он в формате png. Как можно это реализовать? Благодарен за любую помощь!

A: С помощью абсолютного позиционирования:

input {
  border: 1px black solid;
  height: 31px;
  padding: 4px 40px 4px 4px;
}

img {
  position: absolute;
  margin: 4px 0 0 -37px;
}
<input>
<img src='https://www.gravatar.com/avatar/4284dcaa7857f5035883f7f50b1f48cd?s=32&d=identicon&r=PG'>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bottom align TextField? So, by default, when you add text to a TextField, the text appears at the top, and works it's way down to the bottom. I would like to do the opposite: I would like to have it appear at the bottom of the TextField, and move it's way up to the top.
I'm using the code below and it sorta works haha. The only issue i'm having is that if the text gets longer and longer, it seems to be pushing the whole TextField down and not keeping it in the same x and y position on stage. (hope I explained that correctly).
var bottomCoord;
bottomCoord = myDescription_txt.y + myDescription_txt.height;
myDescription_txt.autoSize = "left";

myDescription_txt.y = bottomCoord - bottomCoord.height;
myDescription_txt.text = "Pellentesque habitant morbi tristique senectus"

Anyway to do this?
Thanks! :)

A: All you need to do is adjust the textfield y positioning in relation to the height as you add text to it.
Here's a SO post explaining it: How to vertically align a TextField
public static function verticalAlignTextField(tf: TextField): void {
    tf.y += Math.round((tf.height - tf.textHeight) / 2);
}


text:
Q: PHP code not executing on AWS web server? I have an AWS EC2 instance that I'm running my website on. I have set up and installed PHP and PostGreSQL on the instance via PuTTY and loaded my website files onto it. However, the PHP code is not executing at all on my website and I really don't know why.
A few prerequisites to my question before people offer suggestions:

*

*I have modified the httpd.conf file and added the correct MIME Type for PHP and loaded the correct modules using the LoadModule markup.

*I have installed PHP on the server which I have confirmed using which php.

*I am using the correct <?php and ?> tags.

I have no idea why my AWS isn't running my PHP scripts and as I have a heavily PHP driven website, this is becoming an issue.
Has anyone got any other suggestions?


text:
Q: Programmatically add A records to DNS zone file? I am working for a company and we have a domain name hosted on GoDaddy. For the website/application we are creating, we need to be able to programmatically add "A records" to the DNS zone file to point specific subdomains to specific IP addresses/servers. This will be done via PHP or C#, we have two different servers for our application and it doesn't matter, we just need that functionality. I know GoDaddy doesn't give you this functionality nor an API, but I was wondering if anyone could recommend a cheap/affordable service that would let me do this? I don't think we need something like dynamic DNS (or maybe we will), but if anyone knows anything I would much appreciate.
All in all, we are looking for a super cheap and easy way to add custom A records to a zone file programmatically. A free code base would be nice for this as well. The way our application works, we cannot use wildcards or make this too convoluted, it would be most beneficial to have control over the DNS zone file. Thank you!

A: Unfortunately the other responses here did not quite help, but I did find a problem to our solution on my own. I am going to post my solution to help others who may need to programmatically create A records and modify other DNS zone file settings from their website scripting.
I signed up on the website www.cloudflare.com.  They are a cloud-based DNS service that manages your DNS for free but also has paid solutions for bigger scale projects. They have a complete, integrated API solution for programmatically modifying DNS zone settings. All I had to do was point my nameservers on GoDaddy to use theirs, and then I was able to use their free cloud-based DNS service.
Now with PHP, I am able to programmatically create DNS records through their service, including A, CNAME, and everything in between. Very simple and intuitive service that solved a big problem we had. Setup was a snap and only took a few minutes to propagate initially. There are other cloud-based DNS services, but CloudFlare lets you sign up for free, no questions asked. I was able to play with their API before committing to it. And their prices are very reasonable with the pro-plan costing only $20/month if you need higher performance.

A: You could have your own DNS server (e.g.: unbound), then you can just make your program change the zone file and reload the service, if needed.
Here's an example of changing a zone file using the unbound API. Though it's written in Python and modifying resolv.conf, but with a few changes you can make it work with the actual DNS server zone file.
Maybe it's not the best solution, but it's an easy one.

A: dns-zonefile https://github.com/elgs/dns-zonefile is what you are looking for. This is a javascript library/utility that converts dns zone file from/to JSON formats.


text:
Q: Getting random N rows by SQL query which will be proportional to the total number of rows in different sections I have a table that persists a lot of questions, each question belongs to a section:
Id      Question        SectionId
 1      What is ...     3
 2      Who is...       3
 3      When is...      2
 4      Why is...       1
 5      How is...       3

There is like 1000 questions, and around 50 sections. However, my query is simple, I select a given number of questions from the table from specific sections, for example
SELECT TOP 10 [Id], [Question] FROM [Questions]
WHERE [SectionId] IN (1,2)
ORDER BY NEWID()

This is simple and working fine, except that sometimes I get 5 questions out of the requested 10 from a section that has only 6 questions, and 2 from a section that has 100 questions, and 3 from a section that has 20 questions.
How can I make the result "proportional" with the number of the questions in each section. For example if I request 10 questions, I get more questions from the section that has more questions, and less questions from the sections with less questions.
The only I can think of currently is to make multiple queries, first one to get the number of questions in each section, then do some math and decide how many questions from each section, and then make another few queries to get the number of questions as I want. This sound intensive and I hope there's a more practical way.
Note: An SQL query, or EF Linq query would work.

A: For a stratified sample, do an nth sample on the ordering.  This is a little tricky, but this should work:
SELECT TOP (10) q.*
FROM (SELECT q.*,
             ROW_NUMBER() OVER (ORDER BY section, NEWID()) as seqnum,
             COUNT(*) OVER (ORDER BY section, NEWID()) as cnt
      FROM [Questions] q
      WHERE [SectionId] IN (1, 2)
     ) q
ORDER BY seqnum % (cnt / 10);

There may be some boundary conditions on this logic, but as the number of questions grows and the sample is large enough, it should do what you want.

A: I can't think of a way to do this in a single step, unless you know in advance the number of sections and the proportions of each.
If these values have to be calculated at query time, you will need to run a query to get the sections and proportions and use that to build a Dynamic SQL query.
Use a GROUP BY query to get the SectionIDs and the number of questions in each Section, filtered by the Sections you want to include.
Iterate through that result to build a dynamic UNION ALL query that gets a TOP n (calculate n based on the percentage of the Section's Count / Total Count) of questions for each Section (one query per section), so that you end up dynamically building something that looks something like this:
SELECT TOP 5 ID, Question --because SectionID 1 is 50% of the questions
FROM Questions
WHERE SectionID=1
ORDER BY NEWID()
UNION ALL
SELECT TOP 3 ID, Question  --because SectionID 2 is 30% of the questions
FROM Questions
WHERE SectionID=2
ORDER BY NEWID()
UNION ALL
SELECT TOP 2 ID, Question  --because SectionID 3 is 20% of the questions
FROM Questions
WHERE SectionID=3
ORDER BY NEWID()

Another approach you could think about is to create an artificial ranking column that is factored by the relative density of the section.
What I mean, for example (super simplifying it) is suppose Section 1 was 75% of the questions, and Section 2 was 25%.
You'd use ROW_NUMBER(), partitioned by SectionID, ordered by NEWID() and factored so that:
Section 1 would have values like 1,2,3,5,6,7, etc (3 out of every 4 cardinal values)
Section 2 would have values like 1, 5, 9, 10 etc  (1 out of every 4)
Then Order your query result by this artificial column.

A: This is untested in the absence of sample data, however, something like this might work:
WITH CTE AS(
    SELECT ID,
           Question,
           SectionID,
           ROW_NUMBER() OVER (ORDER BY NEWID()) AS RN,
           (COUNT(ID) OVER (PARTITION BY SectionID) / (COUNT(ID) OVER () *1.0)) *10 AS Perc
    FROM YourTable
)
SELECT TOP 10
       ID,
       Question,
       SectionID
FROM CTE
WHERE RN <= CEILING(Perc)
ORDER BY RN ASC;

A: Another alternative, for example...return 20% of total rows per section
DECLARE @percentage numeric(10,2)

SET @percentage = 0.20 --20% of total question for section

SELECT [SectionID],[ID],[Question]
FROM (  SELECT
            [ID],
            [Question],
            [SectionID],
            ROW_NUMBER() OVER(PARTITION BY SectionID ORDER BY NEWID()) [idx],
            COUNT(1) OVER(PARTITION BY SectionID) * @percentage AS [Proportional]
        FROM [Questions]) tbl
WHERE
    (tbl.[SectionID] = 1 AND tbl.[idx] <= [Proportional])
OR (tbl.[SectionID] = 2 AND tbl.[idx] <= [Proportional])
OR (tbl.[SectionID] = 3 AND tbl.[idx] <= [Proportional])

A: You can use the NTILE(100) function along with a over clause partition by section to get
SELECT TOP 10 [Id], [Question] FROM [Questions]
WHERE [SectionId] IN (1,2)
ORDER BY NEWID()

should be
declare @limit int = 10;

;with data as (
   SELECT NTILE(100) over (partition by sectionid ORDER BY NEWID() ) as Centile, [Id], [Question]
   FROM [Questions]
   WHERE [SectionId] IN (1,2)
)
select * from data where centile <= @limit

https://learn.microsoft.com/en-us/sql/t-sql/functions/ntile-transact-sql

A: You could select always 10% of your records in any sections with this:
SELECT TOP ( select CAST(( COUNT(*) * 0.1 ) AS INT )
FROM QUESTION WHERE SECTIONID IN ( 1,2)) * FROM QUESTION
WHERE [SectionId] IN (1,2)
ORDER BY NEWID()


text:
Q: moduleNotFoundError: No module named 'flask' (SQLAlchemy) I am new to the python and flask. I am watching a you tube tutorial and i am stuck at 20:05 where he run the code "from app import db". I follow exactly the step he taught but yet I still face this problem.Below are the program I type and at the terminal there it shows the error.
The Program:
from flask import Flask, render_template, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(200), nullable=False) #This is to set the character the person input
    date_created = db.Column(db.DateTime, default=datetime.utcnow) #This is to set the time

    def __repr__(self):
        return '<Task %r>' % self.id

@app.route('/')
def index():
    return render_template('index.html')

if __name__ =="__main__":
    app.run(debug=True)

The Program I type In Terminal:
from app import db

The Respond After Typing The Command At Terminal:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Visual Studio Code Project\app.py", line 1, in <module>
    from flask import Flask, render_template, url_for
ModuleNotFoundError: No module named 'flask'

The You Tube Link: https://www.youtube.com/watch?v=Z1RJmh_OqeA&t=335s
The Program
Can anyone help me please?

A: "flask" is used as a Python module in VSCode, we need to install it in the current Python environment: please use "pip install flask" (or "pip3 install flask") in the VSCode terminal.
In addition, the module "flask_sqlalchemy" also needs to be installed. (pip install flask_sqlalchemy)

For more information about the use of "flask" in VSCode, please refer to Flask Tutorial in Visual Studio Code.
Update:


text:
Q: SQL Server 2008 R2 Express accepts only local connections? Coming from question SQL Server 2008 connection tagged under sql-server-2008-express
Chris S wrote in SQL Server 2008 R2 vs. SQL Server 2008 R2 Express:

*

*"The biggest different I see others have missed is that Express does not accept network connections (only local ones)"

I am having difficulties to find reference where is it written. Can you give me one?
What are "network connections (only local ones)" - on the same network, in the same AD, inside the same developing machine? Can they be from the same workgroup Windows computer?

A: It's not anywhere because you can access SQL server express from the network. It's just not turned on by default, you need to enable network connections manually.


text:
Q: Is it true that $z(z^3-1)/(z^3-1)$ is regular? Let $K$ be an algebraically closed field. I have a map $h:\mathbb{A}^1\rightarrow \mathbb{A}^2: z\mapsto (z^3-1,z(z^3-1))$ and a map $t:\mathbb{A}^2\rightarrow K: (x,y)\mapsto y/x$. I am asked if the composition is regular.
$(t\circ h)(z) =  z(z^3-1)/(z^3-1)$. Clearly this is regular if $z\neq 1$. When $z = 1$, I say that there exist polynomials $f(z) = z, g(z) = 1$ such that $f(z)(z^3-1) = g(z)z(z^3-1)$ for any $z\in\mathbb{A}^1$. Hence $f/g = z(z^3-1)/(z^3-1)$ for any neighborhood of $1$.
I conclude that the composition is regular, but I am afraid that what I wrote is not correct and I may be dividing by zero in some way. Is what I am doing correct? Why or why not? Can you give me some intuition on how to do this?


text:
Q: Degree of $\pi_p(C)$, where $\pi_p$ is the projection from $p$ Consider the rational projection map from a point $p$, $\pi_p:\mathbb{P}^n\longrightarrow \mathbb{P}^{n-1}$ given by sending $q\neq p$ to the intersection of the line containing $q,p$ with $\mathbb{P}^{n-1}$, and sending $p$ to $\infty$. Consider the image $\pi_p(C)$ for some curve $C\subset \mathbb{P}^n$.
I am trying to determine the bound $\deg(\pi_p(C))\leq \deg(C)-1$.
How does one go about this?
Edit: the map $\pi_p$ is not defined at $p$ (see @Kreiser's comment below)

A: Let's assume $n\ge 3$, so the target is not $\mathbb P^1$ and $\pi_p|_C:C\to \pi_p(C)$ is birational.
Choose a general hyperplane $H\subseteq \mathbb P^{n-1}$ that intersects $\pi_p(C)$ transversely at $m$ points. So
$$\deg(\pi_p(C))=\#(H\cap \pi_p(C))=m.$$
Now, the cone of $H$ and $p$ defines a hyperplane $\tilde{H}$ of $\mathbb P^{n}$, which intersects $C$ at the preimages of those $m$ points plus a point $p$. By generality, all intersections are simple, so
$$\deg(C)=\#(\tilde{H}\cap C)=1+\deg(\pi_p(C)).$$


text:
Q: *ngFor not working for html table(angular 2) html
ngFor not working for html table
<!DOCTYPE html>

                        {{category.CategoryName}}

                        <button type="button" class="btn btn-sm">Delete</button>

component
I am getting the data from database but unable to do a ngFor ,Please find the error Information below
import { Component,OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { CategoriesService } from './categories.component.service';
import { EventsEmitter } from '../../../assets/scripts/services/eventsEmitter';

@Component({
    selector: 'categories',
    templateUrl: 'app/components/admin/categories/categories.component.html',
    styleUrls: ['app/components/admin/categories/categories.component.css'],
    providers: [CategoriesService]
})
export class CategoriesComponent {
    categoriesInfo: any;

    constructor(
        private router: Router,
        private categoriesService: CategoriesService,
        private eventsEmitter: EventsEmitter) {
    }

    ngOnInit() {
        this.getCategoriesResource();
    }

    getCategoriesResource() {
        this.categoriesService.getCategoriesResource()
            .subscribe(response => {
                debugger;
                this.categoriesInfo = response;
            },
            error => {
                this.eventsEmitter.broadcast('Error', 'Error Occured');
            });
    }

}

error information
my application breaks , can you please tell me what changes do i make to make it work

App Module
I am using only one module in my application
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { HttpModule, JsonpModule, Http, RequestOptions, XHRBackend, RequestOptionsArgs, Response, ConnectionBackend} from '@angular/http';
import { AppRoutingModule } from './app.routes';

import { AppComponent }  from './app.component';
import { CategoriesComponent } from './components/admin/categories/categories.component';

import { LoadingInterceptor } from './assets/scripts/services/loadingInterceptor';
import { EventsEmitter } from './assets/scripts/services/eventsEmitter';
import { ToasterModule} from 'angular2-toaster';

@NgModule({
    imports: [AppRoutingModule, BrowserModule, FormsModule, ReactiveFormsModule, HttpModule, JsonpModule, ToasterModule ],
    declarations: [AppComponent, CategoriesComponent],
    bootstrap: [AppComponent],
    providers: [EventsEmitter,LoadingInterceptor,
        {
           provide: Http,
           useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, eventsEmitter: EventsEmitter) => new LoadingInterceptor(xhrBackend, requestOptions, eventsEmitter),
           deps: [XHRBackend, RequestOptions,EventsEmitter]
        },{ provide: LocationStrategy, useClass: HashLocationStrategy }]
})
export class AppModule { }

A: You need to import CommonModule for directive *ngFor and use let as garth74 said:
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [ CommonModule ],  // use 'imports' not 'import', s is mandatory
  ...
})

A: You're just missing the let keyword in *ngFor


text:
Q: How to display image if path is in json I am new in Angular and I am using Angular 8
I have list of path of images in 'dataSource' variable in JSON format like this:
hotdeals: Array(4)
    0: {uri: "/Home/HotDeals/hotdeal1.png", id: "2"}
    1: {uri: "/Home/HotDeals/hotdeal2.png", id: "3"}
    2: {uri: "/Home/HotDeals/hotdeal3.png", id: "4"}
    3: {uri: "/Home/HotDeals/hotdeal4.png", id: "6"}

How can i show all this images on HTML if my base url is "http://localhost" and file path is above in JSON.
Note: Image path may increase or decrease. Means this time 4 image i got, but if i get 5 image path. So how can i handle this?

dashboard.component.html

ngOnInit()
  {
    this.apiService.getHotDeals('pop').subscribe(home=>{
      this.dataSource=home;
console.log(this.dataSource)

}

dashboard.component.html

<owl-carousel [options]="{items:3, dots:true, navigation:true}"
          [carouselClasses]="['owl-theme', 'row', 'sliding']" >

 </owl-carousel>

Screenshot of console of dataSource

A: You must use a loop to display all images:
component:
@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class YourComponentComponent {
  imgHost = environment.imgHost;
}

template:
<owl-carousel
  *ngIf="dataSource.hotdeals"
  [options]="{items:3, dots:true, navigation:true}"
  [carouselClasses]="['owl-theme', 'row', 'sliding']"
  [items]="dataSource.hotdeals"
>

</owl-carousel>

environment.json
export const environment = {
  imgHost: 'https://example.com'
};

and if your images are on the same server as the application
environment.prod.json
export const environment = {
  imgHost: ''
};


text:
Q: Hubzilla won't start: /store/[data]/smarty3 must be writable by webserver I followed the manual instructions to set up Hubzilla here.
https://project.hubzilla.org/help/en/admin/administrator_guide#Manual_Installation
I ran the command
chmod -R 777 store

But it still gives me this error when I view the page in the browser.
ERROR: folder /var/www/html//store/[data]/smarty3 must be writable by webserver.

I tried chown -R apache:apache store and chmod o-w -R store to tighten it up, but that didn't work so I just ran chmod -R 777 store again. Here are the permissions.
[root@fsphub html]# ls -ld store
drwxrwxrwx. 3 apache apache 20 Dec  1 22:08 store

[root@fsphub html]# ls -lR store
store:
total 0
drwxrwxrwx. 3 apache apache 21 Dec  1 22:08 [data]

store/[data]:
total 0
drwxrwxrwx. 2 apache apache 6 Dec  1 22:08 smarty3

store/[data]/smarty3:
total 0

Apache is running as apache.
[root@fsphub html]# ps -ef | grep http
root     16997     1  0 21:47 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache   16998 16997  0 21:47 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND

What could be wrong?
PHP 7.2.12

A: It was due to SELinux being on. https://wiki.centos.org/HowTos/SELinux
# sestatus
SELinux status:                 enabled
Current mode:                   enforcing

# sealert -a /var/log/audit/audit.log

SELinux is preventing /usr/sbin/httpd from write access on the directory smarty3.
*****  Plugin httpd_write_content (92.2 confidence) suggests   ***************
If you want to allow httpd to have write access on the smarty3 directory
      Then you need to change the label on 'smarty3'
      Do
# semanage fcontext -a -t httpd_sys_rw_content_t 'smarty3'
# restorecon -v 'smarty3'
Raw Audit Messages
  type=AVC msg=audit(1543792561.65:60034): avc:  denied  { write } for  pid=21907 comm="httpd" name="smarty3" dev="vda1" ino=621797 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:httpd_sys_content_t:s0 tclass=dir

# ls -lZd store/\[data\]/smarty3/
drwxrwxrwx. apache apache unconfined_u:object_r:httpd_sys_content_t:s0 store/[data]/smarty3/

So I ran
# semanage fcontext -a -t httpd_sys_rw_content_t store/\[data\]/smarty3/
# restorecon -v store/\[data\]/smarty3/

But that just didn't work so I used
setenforce 0

To change the mode to permissive.


text:
Q: Not able to understand a concept from Classical Mechanics by H. Goldstein I was reading classical mechanics by H. Goldstein and I came across the calculation of total potential energy of a system of particles. I am not able to understand what this derivation is conveying and how is the math done. I am attaching the text for reference.

A: Please note that for future reference we use Mathjax for equations on this site. Images of equations are very strongly discouraged and it's not uncommon to get downvoted for using them.  Mathjax is based on Latex which is widely used in science and mathematics publication.

Equations 1.32 1.33 and 1.34

First remember that everything in bold is a vector and everything else is a scalar.  Learn the way the $\nabla$ operator ("nabla") works - it's very important in theoretical physics.

$$V_{ij}=V_{ij}(|\mathbf{r}_i-\mathbf{r}_j|)\tag{1.32}$$

This is just the statement that potential between two objects depends on the distance between them.

$$\mathbf{F}_{ji}=-\nabla_{i}V_{ij}=+\nabla_{j}V_{ij}=-\mathbf{F}_{ij} \tag{1.33}$$

Not sure I've copied that notion correctly as the image is poor (another reason we discourage posting images of equations and prefer Mathjax).
The forces between two particles are equal and opposite.  The expressions for forces in terms of potentials are standard and the result follows because of the definition of the form of the potential in (1.32).  The only way to see this properly is to actually work out the math in detail (which would be covered by the homework-rule and you should do to get an understanding of the way it works).

$$\nabla V_{ij}(|\mathbf{r}_i-\mathbf{r}_j|)=(\mathbf{r}_i-\mathbf{r}_j) f\tag{1.34}$$

This is simply an expression stating what the author's text does - that the force (the nabla operator on the potential) is a vector along the line between the two particles.  This again follows from the definition (1.32).  $f$ is just a scalar to indicate the form of the result, the particular value would depend on the specifics of the force laws and particles.


text:
Q: FillRectangle Parameter is not valid This is the exception I am getting
System.ArgumentException was unhandled
  HResult=-2147024809
  Message=Parameter is not valid.
  Source=System.Drawing
  StackTrace:
       at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
       at System.Drawing.Graphics.FillRectangle(Brush brush, Int32 x, Int32 y, Int32 width, Int32 height)
       at System.Drawing.Graphics.FillRectangle(Brush brush, Rectangle rect)
       at frmMain.drawCboxItem(Object sender, DrawItemEventArgs e) in frmMain.cs:line 465
       at frmMain.cboxSectionCell_DrawItem(Object sender, DrawItemEventArgs e) in frmMain.cs:line 485
       at System.Windows.Forms.ComboBox.OnDrawItem(DrawItemEventArgs e)
       at System.Windows.Forms.ComboBox.WmReflectDrawItem(Message& m)
       at System.Windows.Forms.ComboBox.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at System.Windows.Forms.Control.SendMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.Control.ReflectMessageInternal(IntPtr hWnd, Message& m)
       at System.Windows.Forms.Control.WmOwnerDraw(Message& m)
       at System.Windows.Forms.Control.WmDrawItem(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ContainerControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
       at System.Windows.Forms.Control.DefWndProc(Message& m)
       at System.Windows.Forms.Control.WmOwnerDraw(Message& m)
       at System.Windows.Forms.Control.WmDrawItem(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ComboBox.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  InnerException:

And the code
if (e.Index > -1)
{
    e.DrawBackground();

    Brush bgColourBrush = null;
    Brush fgColourBrush = null;
    ComboBox combo = (ComboBox)sender;
    objPDT.ListCell pdt = (objPDT.ListCell)combo.Items[e.Index];

    if (e.ForeColor == SystemColors.HighlightText)
    {
        bgColourBrush = new SolidBrush(e.BackColor);
        fgColourBrush = new SolidBrush(e.ForeColor);
    }
    else if (pdt.bgColour == null)
    {
        bgColourBrush = Brushes.Black;
        fgColourBrush = Brushes.White;
    }
    else
    {
        bgColourBrush = pdt.bgColour;
        fgColourBrush = pdt.fgColour;
    }

        // background
        e.Graphics.FillRectangle(bgColourBrush, e.Bounds);
        //foreground
        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
        e.Graphics.DrawString(pdt.Name, combo.Font, fgColourBrush, e.Bounds.X, e.Bounds.Y);

}

And finally the values being passed to it:
pdt {
    Section 8--> CELL}  objPDT.ListCell
    _bgcolour   {Color = {Color [A=255, R=166, G=166, B=166]}}  System.Drawing.Brush {System.Drawing.SolidBrush}
    _CellID 27  int
    _fgcolour   {Color = {Color [A=255, R=255, G=255, B=255]}}  System.Drawing.Brush {System.Drawing.SolidBrush}
    _name   "Section 8--> CELL" string
    _SectionID  8   int
    bgColour    {Color = {Color [A=255, R=166, G=166, B=166]}}  System.Drawing.Brush {System.Drawing.SolidBrush}
    fgColour    {Color = {Color [A=255, R=255, G=255, B=255]}}  System.Drawing.Brush {System.Drawing.SolidBrush}
    Name    "Section 8--> CELL" string
    Value   "8:27"  string
}

e.Bounds    {X = 0 Y = 30 Width = 290 Height = 15}  System.Drawing.Rectangle
    Bottom  45  int
    Height  15  int
    IsEmpty false   bool
    Left    0   int
    Location    {X = 0 Y = 30}  System.Drawing.Point
    Right   290 int
    Size    {Width = 290 Height = 15}   System.Drawing.Size
    Top 30  int
    Width   290 int
    X   0   int
    Y   30  int

A: You should always dispose unmanaged classes like Brush, SolidBrush, Pen. Assuming the pdt.bgColour and pdt.fgColour are of type Color, something like the following code should prevent that crash. Warning: Untested code.
if (e.Index > -1)
{
    e.DrawBackground();

    SolidBrush bgColourBrush = null;
    SolidBrush fgColourBrush = null;
    ComboBox combo = (ComboBox)sender;
    objPDT.ListCell pdt = (objPDT.ListCell)combo.Items[e.Index];
    try {
        if (e.ForeColor == SystemColors.HighlightText)
        {
            bgColourBrush = new SolidBrush(e.BackColor);
            fgColourBrush = new SolidBrush(e.ForeColor);
        }
        else if (pdt.bgColour == null)
        {
            bgColourBrush = new SolidBrush(Color.Black);
            fgColourBrush = new SolidBrush(Color.White);
        }
        else
        {
            bgColourBrush = pdt.bgColour;
            fgColourBrush = pdt.fgColour;
        }

        // background
        e.Graphics.FillRectangle(bgColourBrush, e.Bounds);
        //foreground
        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
        e.Graphics.DrawString(pdt.Name, combo.Font, fgColourBrush, e.Bounds.X, e.Bounds.Y);
    } finally {
        if(bgColorBrush != null) {
            bgColorBrush.Dispose();
        }
        if(fgColorBrush != null) {
            fgColorBrush.Dispose();
        }
    }
}

A: Instead of creating Brush objects with each draw, perhaps you can make bgColourBrush and fgColourBrush global variables and then just change their color instead. Please forgive me if the code below doesn't compile as-is, I did this freehand.
Like this:
if (e.Index > -1)
{
    e.DrawBackground();

    ComboBox combo = (ComboBox)sender;
    objPDT.ListCell pdt = (objPDT.ListCell)combo.Items[e.Index];

    if (e.ForeColor == SystemColors.HighlightText)
    {
        this.bgColourBrush.Color = e.BackColor;
        this.fgColourBrush.Color = e.ForeColor;
    }
    else if (pdt.bgColour == null)
    {
        this.bgColourBrush.Color = Brushes.Black.Color;
        this.fgColourBrush.Color = Brushes.White.Color;
    }
    else
    {
        this.bgColourBrush.Color = pdt.bgColour;
        this.fgColourBrush.Color = pdt.fgColour;
    }

    // background
    e.Graphics.FillRectangle(bgColourBrush, e.Bounds);
    //foreground
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    e.Graphics.DrawString(pdt.Name, combo.Font, fgColourBrush, e.Bounds.X, e.Bounds.Y);
}

UPDATE
So I see that your pdt ListCell object has a bgColour and a fgColour property. In order for my above solution to work, bgColour and fgColour need to be of type Color. Or if they are type SolidColorBrush, then you need to do this: bgColour.Color and fgColour.Color.


text:
Q: "The cohort were followed up at 2 months" or "The cohort was followed up at 2 months" Here, cohort is a group of 12-13 year olds.

A: Neither works, because you follow up 'with' a cohort. If you rewrite your sentence to say, "The researchers followed up with the cohort after two months."


text:
Q: Created a new database on SQL Server, can't be seen by web apps because permissions aren't set So I created a new database on my SQL Server box and then added an ODBC entry so my ASP code knows what it is.  Now I am getting this error:
Cannot open database "DB_NAME" requested by the login. The login failed.
I checked out the permissions by right clicking the db in Management Studio and checked permissions and low and behold it is empty.
I am just trying to duplicate the permissions of one of any of the other twenty or so databases sitting on the box.   Is there a quick way to do this?  Either way I just need to open up the lines of communication between my ASP code and my SQL Server db
Here is my connect code in ASP:
Set sqlConnection = Server.CreateObject("ADODB.CONNECTION")
sqlConnection.Open "DB_NAME"

A: Is there some reason to avoid using a proper connection string:-
sqlConnection.Open "Provider=sqloledb;Data Source=myServerAddress;Initial Catalog=DB_NAME;User Id=myUsername;Password=myPassword;"

A: On top of what John said, when you create a new database, you have to map the login (either SQL login or Windows login from Application Pool) to this database. You can use management studio to do this - open login properties and map it to the new database. Open Object Explorer, then click Security, Logins and rightclick login that is used by your application. Select Properties. Click User Mapping and add appropriate entry for your database in the grid you will see.
The other option is to run statement to create user within the database:
Use DB_NAME
go
create user [web_user] from login [web_login]
go

Another question is to see what rights have to be assigned to the user in the database. You have to check users permissions in one of the existing databases. Again in Object Explorer, click your existing database, then Security, Users and rightclick Properties of the user that you want to check. Observe information displayed on the dialog box in the General tab and check if there are any Securables assigned to the user. You have to copy these settings to the user in your new database.
HTH
Piotr

A: Try adding the user id and password into your connection string.


text:
Q: i5 vs. i7 MBP Refurb Realistically, besides processing speed, what is the difference between the i5 and i7? Can you really tell a difference? I may be developing apps with it (I haven't tried yet, nor have I ever owned a Mac), so I'd also like to hear from a developer if there is a major difference or preference between the two.

A: i7 processors differ
I assume - since you are comparing the i5 to the i7 - that you are thinking of the 13'' MBP models. The 15''-17'' MBP models offer only i7 processors.
The i7 processors of the 15''17'' MBP are quad core, while both the i7 and i5 in the 13'' MBP are dual core.
2 important things to notice

*

*Due to hyper-threading one can also talk of 2 physical cores (4 logical cores) and 4 physical cores (8 logical cores).

*The clock speed you usually see is just the base frequency. The introduced Intel Turbo Boost technology allows the cores to dynamically clock at higher speeds. However, not all cores at once.

Comparison chart
An offical Intel documentation including all features of all 4 processors can be found here. The two processors offered in the 13'' MBP are on the right. Differences are highlighted yellow.


text:
Q: Possible to use curl upload an external json file instead of --data? When testing a REST POST api via curl, is it possible to send data from an external json file, instead of inline via --data?

A: To specify the data from a file, use --data @filename. From man page of curl:

If you start the data with the letter @, the rest should be a file name to read the data from, or - if you want curl  to  read the data from stdin.  The contents of the file must already be URL-encoded. Multiple files can also be specified. Posting data from a file named 'foobar' would thus be done with --data @foobar.


text:
Q: React update url using selectbox on change I am learning react and I found a video on youtube of someone creating a PWA using a news api, I decided I would try replicate it using react as his video was just in vanilla JS and I learn things a little easier if I build stuff.
on the news API there is a sources and an articles API.
Articles:
https://newsapi.org/v1/articles?source=bbc-news&apiKey=${API_KEY}
Sources:
https://newsapi.org/v1/sources?language=en
I have created a select box which contains the sources from the sources api and I get the news by updating the source in the URL from the select box. I have managed to get the select box to put its value into state onchange but I cant get that up to the NewsItem component to change the source in the articles url.
I have put a codepen together here https://codepen.io/crash1989/pen/JZLQxr it is slightly different to how I have my code, as I have had to create the sources and  news manually as I didnt want to publish my API key.
Where you see componentDidMount I am using async/await functions to get the data from the API and putting it into state.
In my actual code I want to have a url like this for the articles https://newsapi.org/v1/articles?source=${this.state.source}&apiKey=${API_KEY}
so the bottom line is I need help getting the select box value into the NewsItem component to update my news.

A: Your App is build like this
<App>
  <Nav />
  <News />
</App>

You select a value in <Nav /> and want to pass it to <News />. You should do so by storing the value in the state of App, and pass the value and the changeHandler as property to the children.
class App extends Component {
   constructor(props) {
      this.state = {
         source: "BBC News"
      }
   }

   setSource = source => {
      this.setState({source})
   }

   render() {
       let {source} = this.state
       return (
           <div>
               <Nav source={source} setSource={this.setSource} />
               <News source={source} />
           </div>
       )
   }
}


text:
Q: Можно ли рассчитывать идентичные последовательности на основе srand? Вопрос чисто философского характера:
Можно ли полагаться на базу рандомизации при генерации идентичных последовательностей на разных устройствах?
Например, задав некоторую базу(srand) и cгенерировав 100 чисел, можно ли быть уверенным в том, что именно эти самые числа будут сгенерированы с той же базой на более быстром/медленном по частоте процессора компьютере/телефоне etc..?
P.S В основе вопроса - функция srand из стандартной библиотеки C.
P.P.S В разных компиляторах получаются разные последовательности.

A: В случае одного и того же компилятора на разных машинах, например - да.
В случае разных компиляторов - нет.

A: Нет, нельзя. Реализация srand зависит от используемой стандартной библиотеки языка C - а она на разных компьютерах может отличаться. И даже на одном и том же компьютере она может отличаться. Даже если собирать одним и тем же компилятором.
Если вам требуется переносимый детерминированный генератор псевдослучайных чисел - его лучше написать самостоятельно.


text:
Q: Run two run-until-cancel commands at once with Fabric I use Fabric  to develop, manage and deploy my Django sites. I've toned my workflow into an agile beast... And yet, my scope for laziness seems infinite...
I've recently started to use a lot of Bootstrap. I feel as if I could  reimplement most of Grunt's functionality in Fabric but that's really not what I'd like to do. What I want is a Fabric command that simultaneously runs:

*

*(with lcd into my bootstrap directory) grunt watch to auto-rebuild my Bootstrap output if I edit it

*./manage.py runserver to run a dev server for Django (which also auto-rebuilds)

Both of these commands will run indefinitely until I cancel them... And that seems like a problem. If I used Fabric's @parallel decorator, I'm not going to have any control over the commands, am I? The output (while not critical) is also going to be a bit messed up.
So given this situation, what's the best way of handling two commands like this and automating them?

A: In similar scenarios, where I want to run multiple processes locally during development (web app, asset builder, database server...) I typically use supervisor.
Once configured, you can control (ie. start, stop, etc.) all processes using the supervisorctl command.


text:
Q: How do I figure out the language generated by this context-free grammar? I am dealing with the following grammar:
G = ( {S, A}, {a, b}, P, S )
P = { S -> aAb, S -> bAa,
A -> aSa,
A -> S,
A -> epsilon}

I need to find out L(G).
The thing is, I figured out that the words in the grammar are of the form:
starts with a and ends with b, or starts with b and ends with a, and between these letters one of the combinations : ab, ba, aaba, abaa; then the next word is formed by inserting one of these 4 combinations between the a and b in the middle..but how can I express this formally?
I mean, as far as I could tell, L(A) = a^n S a^n and if w belongs to L(G), then w reversed also belongs to L(G).
I tried to express it as a regular expression but failed...could anyone please help?
Thank you.

A: You see that L is not regular, to prove you can use Pumping lemma or Myhill–Nerode theorem, so regular expression can't be discussed
You can notice, that since L consists just of {a,b} you can use it's power
We see that language is in the form of aAb or bAa or aAa with exception that aAa can't be located at begin-end of the word
So let's use this, the only thing we miss is the combination of bAb
A can generate almost everything (words |w| = 2k, and |w|>=2) but words where position of b matches position of b from the reverse
Formally

Sorry for my tex skills and my formal expression
there must be some error, because I didn't have so much time to think about this, but it can be some way how to continue, it's homework so it's fine, think about it! :)

A:
I tried to express it as a regular expression but failed

This language is 'probably' not regular. Context-free languages are more complex/powerful than regular expressions.
Try generating a few words and see if you can come up with a name, properties for the language. Or try to find words that are not in the language.
Some hints, a few properties you can easily see:

*

*The smallest string is at least size 2.

*The size of the string is even.

*The count of b's is <= than a's.
If you take out A -> aSa, and compare a word with its reversed version, a pattern should be visible. If you include the left out rule, the pattern changes slightly...

A: You are asked to find the language generated by the grammar G with productions
S → aAb | bAa
A → aSa | S | λ

First, consider small derivations beginning from the start symbol S
S ⇒1 aAb ⇒1 aaSab | aSb | ab

S ⇒1 bAa ⇒1 baSaa | bSa | ba

The difficult step is dealing with the recursion generated by the rules A → aSa, S → aAb and S → bAa. The clue to dealing with this difficulty is revealed by considering an inductive definition of the language generated by G:
1. ab ∈ L4
2. ba ∈ L4
3. w ∈ L4 → awb ∈ L4
4. w ∈ L4 → bwa ∈ L4
5. w ∈ L4 → awa ∈ L4

The rules (3)-(5) correspond to the rules A → aAa, S → aAb and S → bAa in G. It is easy to see that the inductive definition and the rules of G define the same language. The inductive definition shows that the language of G can be build incrementally in steps. Starting with the smallest strings generable in G, we build larger and larger sets of strings corresponding to the problematic rules:
L(1)     = {ab, ba}
L(n + 1) = {awb, bwa, awa : w ∈ L(n)}

The set L(1) contains the smallest strings generable in G. The set L(n + 1) contains strings awb, bwa and awa for each string w ∈ L(n). That is, the strings in L(n + 1) correspond to the strings obtained by applying the rules S → aAb, S → bAa and A → aAa once to strings in L(n). All that remains is to construct the union of the L(n), which is a set:
L = ⋃ {L(n) : n ∈ ℕ}

To see that L is equivalent to the language generated by the grammar G, you can argue by induction on the length of derivations in G. Starting with the smallest strings genreable in G (i.e, ab and ba), working backwards using appropriate induction hypotheses.

A: the language generated is : (a)n(b)m  Were n>=m


text:
Q: Getting an "ambiguous use of 'components' error" while running HKStatisticsCollectionQuery example code let calendar = NSCalendar.current
let interval = NSDateComponents()
interval.day = 7

// Set the anchor date to Monday at 3:00 a.m.
let anchorComponents = calendar.components([.Day, .Month, .Year, .Weekday], fromDate: NSDate())

let offset = (7 + anchorComponents.weekday - 2) % 7
anchorComponents.day -= offset
anchorComponents.hour = 3

I'm getting an Ambiguous use of 'components' error at anchor components declaration when I'm running the code

A: You  should  use  Date,  DateComponents  and  Calendar  instead of NSDate, NSDateComponents and NSCalendar. Then the old syntax needs to be updated to latest  Swift version.  Also you need to change constant(let) interval and anchorComponents to variable(var) as you are changing the values. Below is the fixed snippet,solution:
let calendar = Calendar.current
var interval = DateComponents()
interval.day = 7

// Set the anchor date to Monday at 3:00 a.m.
var anchorComponents = calendar.dateComponents([.day, .month, .year, .weekday], from: Date())

let offset = (7 + (anchorComponents.weekday ?? 0) - 2) % 7
anchorComponents.day = (anchorComponents.day ?? 0) - offset
anchorComponents.hour = 3


text:
Q: mysql procedure return only one/first row I'm trying now for the 100 time to find out the reason why my code give as output only the first row. I made one procedure which select all products and I called it in php in that way:
$query      = "CALL create_helper()";
$exec       = mysql_query( $query, $connexion );

while($row = mysql_fetch_row($exec)) {
   var_dump(  $row  );
}

CREATE PROCEDURE create_helper ()
BEGIN
  DECLARE prod CURSOR FOR SELECT id FROM pC;
  ...
  OPEN prod;
   pd_loop: LOOP
      FETCH pd INTO id_s;
         IF finished = 1 THEN
            LEAVE pd_loop;
         END IF;
         SELECT name, ag, pdt, pname FROM clt WHERE id = id_s;
         ...
      END LOOP pd_loop;
   CLOSE prod;
END;

The Procedure under mysql works fine but the only and the one problem is in php. It shows always the first row.

A: Try it

Returns an numerical array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
mysql_fetch_array()

Fetch a result row as an associative array, a numeric array and also it fetches by both associative & numeric array.
<?php
$query      = "CALL create_helper()";
$exec       = mysql_query( $query, $connexion );

while($row = mysql_fetch_array($exec))
{
  var_dump($row);
}
?>


text:
Q: Copy file from one ubuntu to another ubuntu By using cron job I've successfully created a backup of mysql database on the Ubuntu. Below is the command under mysqldump.sh
/opt/lampp/bin/./mysqldump -u root database-name | gzip >/db-backup/"mysql_db-$(date +"%Y-%m-%d %T").sql.gz"

I'm running above using cron job below is the command of cron job
* * * * * /db-backup/mysqldump.sh

My question is, I don't want to create the sql backup file to the same ubuntu (IP: 192.168.2.10). Actually I need to copy the sql backup file to another ubuntu (IP: 192.168.2.11) which is in same network
I tried to change cron job command to * * * * * /192.168.2.11/db-backup/mysqldump.sh but sql backup file is not copying to 192.168.2.11/db-backup/
Any help will be highly appreciable.

A: You can send the backup file to the other Ubuntu using rsync or scp then you can delete the backup on your system or not
Use this link for learning rsync
RSync useful options:
    -r                      --> Recursive
    -b                      --> Backup
    -u                      --> Update (--inplace, --append)
    -d                      --> Transfering dirs without recursive
    -l                      --> Copy symbolics as symbolics
    -p                      --> Preserve permissions
    -E                      --> Preserve Executability
    -o                      --> Preserve OwenrShip
    -g                      --> Preserve Groups
    -t                      --> Preserve modifition time
    -z                      --> Compress
    -v                      --> Increase verbosity
    -a                      --> Archive mode
    -H                      --> Preserve hard links
    -e                      --> To run shell command on the remote server
    -e <protocol>           --> Over that protocol (e.g. ssh)
    -h                      --> Human readable
    -P                      --> Show the progress during the progress (SMILE), Same as --progress
    --safe-link             --> Ignore symbolic links that point out of the tree
    --existing              --> Ignore creating new files
    --ignore-existing       --> Ignore updating existing files
    --remove-source-files   --> Sender remove synced files
    --progress              --> Show the progress during the progress (SMILE)
    --log-file=FILE         --> Sending logs will be stored to FILE
    --include=PATTERN       --> Sync files that have PATTERN filter in themselves
    --exclude=PATTERN       --> Don't sync files that have PATTERN filter in themselves
    --max-size='SomeK'      --> Only send or recieve files less than SomeK

And some examples:
    rsync -t [Pattern (e.g. *.c)] [PurposeMachine]:Path
        Send all file with that pattern in the current dir to purpose machine in the path (if exist only send differences)
        e.g. rsync -t *.c foo:/src

    rsync -avz [Machine]:Path/dir PathHere :
        Download all files recursivly that are in the dir directory to the PathHere/dir
        File transfering is archive mode that means Symbolic links, devices, attributes, permissons, ownerships, etc are preseved
        e.g. rsync -avz foo:src/bar /data/tmp

    rsync -avz [Machine]:Path/dir/ PathHere :
        Download all files recursivly that are in the dir directory to the PathHere/
        File transfering is archive mode that means Symbolic links, devices, attributes, permissons, ownerships, etc are preseved
        e.g. rsync -avz foo:src/bar/ /data/tmp

    rsync -av NowHere/dir[/] /Dest :

    rsync -av [host]:: /Dest: [OR rsync -av [host]::moudle /Dest]
        All files in remote dir will be transfered


text:
Q: Checking strings held in a list against those being read in from another device I have a list filed with data which I have already set up like so:
public List<string> stringValues = new List<string>();

void Start()
{
    stringValues.Add( "D5B51D14-9ED8-1530-5455-CFF2C4B86151");
    stringValues.Add( "335B8649-AB22-E146-05A0-E9A4F3813A1F");
    stringValues.Add( "28797BB5-9020-C0B5-F0CE-72AB7F1830E2");
    stringValues.Add( "CD377141-422D-E8B0-B845-A0AF408E565A");
    stringValues.Add( "DEEE65FB-FF1F-A6A9-4C3C-5784F41B0D39");
    stringValues.Add( "70489FFA-6C88-A40D-C615-FD1EDEBD7643");

}

I also have a method which reads in data being sent in from a device and displays it on the screen. I've had to cut a chop bits off of the string to make sure I only get the data I want, to appear on the screen.
This is what the method looks like:
private void AppendString(string message)
{
    int startIndex = 38;
    int endIndex = 36;
    message = message.Substring(startIndex,endIndex);
    messageCount = "length is " + message.Length.ToString();
    outputContent.text += "\n" + message;
}

The thing is, the data getting sent into my program is something I have no idea about. It could contain anything. What I'm needing my program to do is check the portion of the string I need and compare the value it finds against those in my list. Then, should the list contain the same data, do something.
How can I go about comparing my list against data that is dynamically getting passed into it with my code above?
edit
I'll explain the appendMessage function a bit more and why it is like that:
the devices Im reading in send out data in the following way:
<CBPeripheral: 0xda4bab0 identifier = D5B51D14-9ED8-1530-5455-CFF2C4B86151, Name = "estimote", state = connecting>

Most of that is fine, but the only part I'm caring about is the long number held in the identifier portion of the line. In my program when I run the app, instead of displaying that entire line, the only part it puts out is that number there. Nothing else.
So, having chopped up that line, I'm storing in a UILabel (unity gui string) called outputContent and I'm accessing the data held in it when by calling outputContent.text
Which, when combined with the sample answer given below, my list check looks like this:
if(stringValues.Contains(outputContent.text))
{
    Instantiate(estimote6Model, new Vector3(2.5f,0.7f,0), Quaternion.identity);
    uuidString = "got an estimote 6";
}

However, whilst the string on display is the part of the line I want, nothing happens and I'm still trying to work out why.

A: You can search if the list with the method .Contains(). So something like this:
if (stringValues.Contains(message))
{
   // do something
}

You can add this snipped at the end of your AppendString() method, because there, the variable message should hold the id's, which could be part of the stringValues list, right?
If you don't want to check for this within the AppendString() method, you must store your id's from the device in a separate list:
public List<string> deviceValues = new List<string>();

private void AppendString(string message)
{
    int startIndex = 38;
    int endIndex = 36;
    message = message.Substring(startIndex,endIndex);
    messageCount = "length is " + message.Length.ToString();
    outputContent.text += "\n" + message;

    deviceValues.Add(message); // add here the input from the device
}

Then you can check if stringValues contains any of the values from deviceValues with:
if (stringValues.Any(x => deviceValues.Contains(x)))
{
   // do something
}


text:
Q: FrontEnd-Login with CouchDB What is the best approach for developing a web-application with CouchDB, in which front-end-users have to log in [for example a forum]? For this, i need some authentication-mechanism for checking username/password and storing them in a session/cookie.
How can i realize that in CouchDB? Is there a way to run server-side code directly on the couch? Do I need an additional software-component like node.js or a php-interpreter?
Thanks a lot.

A: Superlogin is a new NodeJS login framework that supports CouchDb logins.
I've recently integrated this new Authentication API into one of my mobile apps and it was very easy to do. The clear documentation and demo app code were excellent kick starters. Although only newly open sourced, the code maturity and test coverage feels like it's been used in production for a while. The developer has been very helpful and responsive.

*

*Extensive server API and Optional Angular client API.

*Comprehensive demo app.

*Supports local username/password, password reset, password update, user profile updating.

*Attach any number of social OAuth logins (Facebook, Twitter, Google etc) per user account. Uses PassportJS that support over 300 authentication plugins.

*Can integrate SendGrid API to verify emails and send other user event notifications

*Generates temporary long and random CouchDb user/passwords per user session
so you can still replicate into PouchDb using Basic Auth directly to the CouchDb server but with significantly improved security.

*100% cookie free, preventing CSRF attacks

*Fast and scalable with optional Redis session store

*Comprehensive test suite.

Fully open source and MIT licence:

*

*Superlogin Server

*NG Superlogin Client

*Superlogin Demo App | Live Demo

A: You now want to check out the new Hoodie project at http://Hood.ie .
It includes an API to manage CouchDb user accounts including:
// sign up
hoodie.account.signUp('joe@example.com', 'secret');

// sign in
hoodie.account.signIn('joe@example.com', 'secret');

// sign out
hoodie.account.signOut();

// change password
hoodie.account.changePassword('currentpassword', 'newpassword');

// change username
hoodie.account.changeUsername('currentpassword', 'newusername');

// reset password
hoodie.account.resetPassword('joe@example.com');

// destroy account and all its data
hoodie.account.destroy();

// find out who the currently logged in user is (returns undefined if none)
hoodie.account.username;

And events ...
// user has signed up (this also triggers the authenticated event, see below)
hoodie.account.on('signup', function (user) {});

// user has signed in (this also triggers the authenticated event, see below)
hoodie.account.on('signin', function (user) {});

// user has signed out
hoodie.account.on('signout', function (user) {});

// user has re-authenticated after their session timed out (this does _not_ trigger the signin event)
hoodie.account.on('authenticated', function (user) {});

// user's session has timed out. This means the user is still signed in locally, but Hoodie cannot sync remotely, so the user must sign in again
hoodie.account.on('unauthenticated', function (user) {});

A: Although I have no direct experience with couchDB, as far as I know its a database, meaning that you will definitely need a server side language to interface with it from the browser. Node.js and php are possible choices in that case (although I think couchdb has extremely good support for node.js, although I might be mistaken). Either way, here there is a possible setup within node.js: http://artem.posterous.com/nodejs-authentication-with-couchdb-and-expres

A: Couchdb can handle this for you.  It will do couch level authentication and database level authentication.
http://wiki.apache.org/couchdb/Security_Features_Overview
Basically there is a _users db that has all your users and you can set users in a _security document to protect the database.
For document level security you have to role your own.  I've been told this is not recommended and database per user model is favored here.
You can also use BrowserID (Persona)
https://github.com/iriscouch/browserid_couchdb
Kan.so has some nice packages for creating users from the front end if you are building a couchapp and would like some package management.


text:
Q: Getting HTTP xml error response using cURL I am currently using cURL to communicate to a cloud site... everything is going well except for an annoying issue. The issue is that I cannot get the site's xml response when there is an error. for example, when I use Wire Shark to check the transfer I can see that in the HTTP header that I'm getting which contains the error code; there is an XML data that contains in addition to the error code, a message that describes the code. I have tried many cURL options to try and get the XML but all my attempts failed.
Could someone tell me how can I get the XML. please note that I'm using the cURL C APIs as my code is in c++ and moreover, I can get XML responses when the operation succeeds using my write callback function.

A: Set CURLOPT_FAILONERROR to 0.  If this is set to 1, then any HTTP response >= 300 will result in an error rather than processing like you want.


text:
Q: Is there any way to get the acSysCmdInitMeter and shows it on the form? I have the following query running in the background when the user press a button on the form.
    'Insert new data
    strSQL = "INSERT INTO TBL_DIRECTORS " & _
             "SELECT importDirectors.* " & _
             "FROM importDirectors LEFT JOIN TBL_DIRECTORS ON importDirectors.[CompanyRegNumber] = TBL_DIRECTORS.[CompanyRegNumber];"

    DoCmd.RunSQL strSQL

    'Update existent data
    strSQL = "UPDATE TBL_DIRECTORS INNER JOIN importDirectors ON (importDirectors.[OperatorName] = " & _
             "TBL_DIRECTORS.[OperatorName]) AND (importDirectors.CompanyRegNumber = TBL_DIRECTORS.CompanyRegNumber) SET "

    For Each field In fields
        strSQL = strSQL & strFormat("TBL_DIRECTORS.[{0}] = [importDirectors].[{1}], ", field.Name, field.Name)
    Next

    strSQL = Left(strSQL, InStrRev(strSQL, ",") - 1) & ";"
    DoCmd.RunSQL strSQL

When the UPDATE query is running I know that we have this on the status bar:

It is a acSysCmdInitMeter.
Is there a way to get this and shows in other place, like on my form?


text:
Q: $\{g_n\}$ be uniformly bounded sequence of functions on $[0,1]$ and converges pointwise to $g$. My question is -suppose $\{g_n\}$ be uniformly bounded sequence of functions on $[0,1]$ and converges pointwise to a function. Then can I say $\int_{0}^{1} |g_n(x)-g(x)| dx\to 0$ as $n\to\infty$?
If I can conclude $\{g_n\}$ converges uniformly to $g$, then I easily say that the above statement is true.
I first thought that uniform boundedness may imply uniform convergence but it is not true (example: $g_n(x)=x^n$ on $[0,1]$, it is uniformly bounded by $1$).
I can't prove or disprove the statements.
Can anybody answer the question? Thanks for assistance in advance.


text:
Q: Check public DNS health and RFC compliance Every now and again I like to run checks on my DNS servers to make sure they are running right and to RFC spec. I used to use the DNSTools website to do this as it gave me a pretty good picture of what was going on - are all my servers responding to the outside world, and the important (NS, MX especially ) records still up and replicated right. Also to see if my MX records have managed to make it onto any blacklists.
Blacklists have always been kind of a pain as I haven't been able to find a reliable "one stop shop" that lets you check against most of the major blacklists out there.
I haven't used DNS tools in a while and now they are requiring you to pay (which I have nothing against, just hard to justify to the superiors when you have invested in a large internal monitoring solution and I'm just doing a "feel good check")
What do my fellow sysadmins uses to check on their DNS records?

A: It's not like the old DNSStuff but http://www.iptools.com/ and http://www.mxtoolbox.com are good replacements.

A: I've found http://clez.net/net.dns to be good replacement has some other tools which are worth looking at too.

A: I use zonecheck (http://www.zonecheck.fr/). It doesn't do everything that some paid DNS checking services do, but it does do many check, is both free and Free, and is available in many distros' standard repositories (see here and here for Debian/Lenny) so is relatively easy to install on your own internal services instead of relying on other sites.

A: What about intodns.com ? It's a really good site an provides a really good analysis of your DNS.

A: http://www.squish.net/dnscheck/ is what i used even before dnstools limited their services. it's really good, reports open recursive dns and possible misconfigurations straight from root dnses down to your server.
http://robtex.com/ has also some nice dns tool - mostly for checking blacklists, although this site is mainly useful for whois and bgp ASNs lookups.

A: I've used http://atrey.karlin.mff.cuni.cz/~mj/sleuth/ before. You can use the online form or download the program used to do the checks.

A: There is a long list of current online DNS checking services (with explanations of why some are better than others) in my paper.
Executive summary: Zonecheck and DNScheck.


text:
Q: How to switch between different workbooks to copy/paste information This is my first attempt at writing a macro at work, so please go easy on me if this is really simple, I couldn't find a solution online and kept getting errors in my code:
Basically, I have a Raw Data file and I want to copy different filtered data into a new workbook. I already pass the part where I copy column M into a new created workbook but I don't know how to make the code go back to the Raw Data file and copy another column, then paste it into another column in the same new workbook.
Here's what I have so far, the lines with ''' are what I tried and got errors for. Not sure why it's not working
Dim FilePath As String
Dim SourceFile As String

Sub Reconcile()

FilePath = Sheets("Reconcile").Range("E5")     'location of saved attachment
If Right(FilePath, 1) <> "\" Then FilePath = FilePath & "\"

SourceFile = Sheets("Reconcile").Range("E7") 'name of attachment file

FilePath = FilePath & SourceFile

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Workbooks.Open Filename:=FilePath, UpdateLinks:=False 'open sourcefile     workbook
ActiveWorkbook.CheckCompatibility = False

'''Set DataFile = Workbooks(ActiveWorkbook.Name) 'activeworkbook is the raw data file

'Copy the date column into a new wb and remove duplicates
    Columns("M:M").Select
    Selection.Copy
    Workbooks.Add
    ActiveSheet.Paste
    Application.CutCopyMode = False
    ActiveSheet.Range("$A$1:$A$1666").RemoveDuplicates Columns:=1, Header:=xlNo
    Rows(1).Delete

'''DataFile.Sheets("Sheet1").Range("A1").Select

End Sub

The last line is just me trying to go back to the raw data file and selecting cell A1.
Thanks!

A: Start off by creating a Worksheet object and a couple of Workbook objects
Dim wsReconcile As Worksheet
Dim wbDatafile As Workbook
Dim wbNewfile As Workbook

Then, at the start of your code, before you open any new workbooks set wsReconcile to your Reconcile sheet
Set wsReconcile = Worksheets("Reconcile")

Then, when you do your WorkBooks.Open of your datafile, you can assign it to the wbDatafile object
Set wbDatafile = Workbooks.Open(Filename:=FilePath, UpdateLinks:=False) 'open sourcefile     workbook

And, when you add your new workbook, assign it to the wbNewfile object
Set wbNewfile = Workbooks.Add

Then, every time you need to refer to the data file, use the wbDatafile object, e.g.
wbDatafile.Sheets("Sheet1").Range("A1").Select

Every time you need to refer to the new file, use the wbNewfile object, e.g.
wbNewfile.Sheets("Sheet1").Range("$A$1:$A$1666").RemoveDuplicates Columns:=1, Header:=xlNo
wbNewfile.Sheets("Sheet1").Rows(1).Delete

And, when you want to refer to the original Reconcile sheet, you can use the wsReconcile object, e.g.
SourceFile = wsReconcile.Range("E7")


text:
Q: Is/when is this property about the totative subset of $(\mathbb{Z}_n , +_n)$ true? Is it possible to show (or when is it true); that for the group $\mathbb{Z}^+_n :=(\mathbb{Z}_n , +_n) $, there exists an $a \in \mathbb{Z}^+_n$ for each $z \in \mathbb{Z}^+_n$, where both $z+_n a$ and $z+_n -a$ are totatives of $n$?
Additional
What is the smallest $a$ that can be constructed?

A: If you want to show that

for each $z\in\mathbb{Z}_n$ there exists $a\in\mathbb{Z}_n$ such that $\gcd(z\pm a,n)=1$,

then proceed like this:
If $\gcd(z,n)=1$ then set $a=0$.
Otherwise $\gcd(z,n)>1$. If for any prime $p$ such that $p\mid n$ we have $p\mid z$ then set $a=1$. Otherwise, there is $p\mid n$ such that $p\nmid z$. In this case let $a$ be the product of all primes in $n$ which don't appear in $z$.


text:
Q: Find $x$ such that $12+13^x$ be a perfect square Find $x \in N$ such that $12+13^x$ be a perfect square
I am going to limit  $k < 12 + 13^x < k+i$ so that I can have $t<x<t+u$, I don't know how to do it, if $x=2k$, it pretty easy but x can also equal $2k +1$ too. So... Stuck here
Update 2:
I can prove that $x$ can't be $2k$, if so, x = 2k $(k \in \mathbb{N})$ then
$13^{2k}<12+13^x = 12 + 13^{2k}<(13^k+1)^2$ => $12+13^x$ can't be a perfect square.
~# if $x=2k+1$
=> $12+13^x = 12+13^{2k+1}$.
Now we need prove that $k$ can not greater than $1$ (how to do that ?, stuck again)

A: There are many ways to solve such problems -- I'm not sure that any of them are particularly easy. One way, since you've observed that your exponent $x$ is necessarily odd, would be to find all the integral points on the elliptic curves given by the equations
$$
y^2 = 13^\delta u^4+12 \; \mbox{ for } \; \delta \in \{ 1, 3 \}.
$$
One can do this in, for example, magma by typing :
IntegralQuarticPoints([13,0,0,0,12]); and IntegralQuarticPoints([13^3,0,0,0,12]);
which lead to the two known solutions (with $|u|=1$ and $|y| =5$ and $47$). These routines are using lower bounds for linear forms in logarithms (elliptic, I believe).
Another approach (which has some similarities) would be to use an argument of de Weger (from his thesis, again based on linear forms in logarithms). This would enable you, for example, to tackle the more general equation
$$
13^x + 2^y 3^z = w^2.
$$
I haven't worked out the details, but one should be able to show that the only solutions are with
$$
\begin{array}{r}
(x,y,z) = (0,0,1), (0,3,0), (0,3,1), (0,4,1), (0,5,2), (1,0,1), (1,0,5), \\
(1,2,1), (1,2,2), (1,2,3), (2,0,3), (2,6,1), (2,10,5), (3,2,1). \\
\end{array}
$$
Yet another way to solve such problems is to use the hypergeometric method of Thue and Siegel. In this context, it enables one to prove an inequality of the shape
$$
\left| y^2 - 13^x \right| > |y|^{0.4},
$$
valid for all integers $y$ and odd $x$. Such an approach is also useful for bounding the number of solutions to equations like the one under consideration here. One can, for example, show that given any odd prime $p$ and integer $D$, there are at most $3$ positive integers $x$ such that
$$
p^x+D = y^2
$$
for integer $y$. This is, of course, not quite sharp when $p=13$ and $D=12$, but it's close.

A: $x=3 \implies 13^x+12=2209=47^2$.

A: I don't think there's a nice way to do this. You can, however, use a calculator or a computer to find solutions. I used the following line in Mathematica:
      Intersection[12+13^(2#-1) & /@Range[100000],#^2&/@Range[300000]]

And it returned
{25, 2209}

Implying the only answers less than $100000$ are $1$ and $3$.
EDIT: changed code and results

A: I think algebraic approach is appropriate to this problem. With some calculation, we get
$$(y+2\sqrt{3})(y-2\sqrt{3})=(4+\sqrt{3})^x (4-\sqrt{3})^x.$$
and $4\pm\sqrt{3}$ is prime on $\mathbb{Z}[\sqrt{3}]$. And
$$\frac{5-2\sqrt{3}}{4+\sqrt{3}}=2-\sqrt{3}$$
$$\frac{47+2\sqrt{3}}{(4+\sqrt{3})^3}=2-\sqrt{3}$$
So I conjectured following propositions:

*

*If $(x,y)$ is solution of this equation, then $y+2\sqrt{3}$ associates $(4+\sqrt{3})^x$ or $(4-\sqrt{3})^x$.

*And each case ($(4+\sqrt{3})^x$ associates $y+2\sqrt{3}$ or $(4-\sqrt{3})^x$ associates $y+2\sqrt{3}$) gives only one solution.
But I can't get more.

A: We want: $$13^x + 12 = a^2$$
Not an answer just compiling results:
$$
x=1,3
$$
Are the first two solutions.
There are no solutions for
$$
3<x<100000
$$
Note that
$$
12+13^x  \equiv  1 \mod 8,  \;\; \forall x>1, \mbox{ such that $x$ is odd}\\
12+13^x  \equiv  5 \mod 8,  \;\; \forall x>1, \mbox{ such that $x$ is even}\\
$$
Hence
$$
a^2 \equiv 1 \
$$
So we have that:
$$
a \equiv 1,3,5 \text{ or } 7 \mod 8
$$

and $x$ is odd since $5$ is a non-residue $\mod 8$
A similar result yields that:
$$
a \equiv 2 \text{ or } 5 \mod 7
$$


text:
Q: SQL: How do I INSERT primary key values from two tables INTO a master table I would appreciate some help with an SQL statement I really can't get my head around.
What I want to do is fairly simple, I need to take the values from two different tables and copy them into an master table when a new row is inserted into one of the two tables.
The problem is perhaps best explained like this:
I have three tables, productcategories, regioncategories and mastertable.
         ---------------------------
TABLE:   PRODUCTCATEGORIES
         ---------------------------
COLUMNS: CODE       | DESCRIPTION
         ---------------------------
VALUES:  BOOKS      | Books
         ---------------------------

         ---------------------------
TABLE:   REGIONCATEGORIES
         ---------------------------
COLUMNS: CODE       | DESCRIPTION
         ---------------------------
VALUES:  EU         | European Union
         ---------------------------

         ------------------------------------------
TABLE:   MASTERTABLE
         ------------------------------------------
COLUMNS: REGION     | PRODUCT       | ACCOUNT
         ------------------------------------------
VALUES:  EU         | BOOKS         | NULL
         ------------------------------------------

I want the values to be inserted like this when a new row is created in either productcategories or regioncategories.
New row is created.
         ---------------------------
TABLE:   PRODUCTCATEGORIES
         ---------------------------
COLUMNS: CODE       | DESCRIPTION
         ---------------------------
VALUES:  BOOKS      | Books
         ---------------------------
VALUES:  DVD        | DVDs
         ---------------------------

And a SQL statement copies the new values into the mastertable.
         ------------------------------------------
TABLE:   MASTERTABLE
         ------------------------------------------
COLUMNS: REGION     | PRODUCT      | ACCOUNT
         ------------------------------------------
VALUES:  EU         | BOOKS        | NULL
         ------------------------------------------
VALUES:  EU         | DVD          | NULL
         ------------------------------------------

The same goes if a row is created in the regioncategories.
New row.
         ---------------------------
TABLE:   REGIONCATEGORIES
         ---------------------------
COLUMNS: CODE       | DESCRIPTION
         ---------------------------
VALUES:  EU         | European Union
         ---------------------------
VALUES:  US         | United States
         ---------------------------

Copied to the mastertable.
         ------------------------------------------
TABLE:   MASTERTABLE
         ------------------------------------------
COLUMNS: REGION     | PRODUCT       | ACCOUNT
         ------------------------------------------
VALUES:  EU         | BOOKS         | NULL
         ------------------------------------------
VALUES:  EU         | DVD           | NULL
         ------------------------------------------
VALUES:  US         | BOOKS         | NULL
         ------------------------------------------
VALUES:  US         | DVD           | NULL
         ------------------------------------------

I hope it makes sense.
Thanks,
Stefan

A: You can easily build your "master table" in runtime:
SELECT  *
FROM    regiontable
CROSS JOIN
        producttable

It will be more efficient, since, unlike the materialized master table, both tables will probably fit into the cache.
If for some reason you'll need to have it materialized, then just write the triggers on both tables:
INSERT
INTO    mastertable
SELECT  r.code, NEW.code
FROM    regiontable t

on mastertable, and
INSERT
INTO    mastertable
SELECT  NEW.code, p.code
FROM    producttable p

on producttable.

A: There are two ways of inserting the extra information into the MASTERTABLE.

*

*Use triggers - when an insert occurs in PRODUCTCATEGORIES or REGIONCATEGORIES, an insert trigger fires and checks if the row exists in the MASTERTABLE. If not it is added.

*Create a stored procedure to insert data into the PRODUCTCATEGORIES and REGIONCATEGORIES table. The stored procedure is then responsible for checking the MASTERTABLE and inserting if necessary.
The 2nd approach has the advantage that it's obvious to someone else maintaining your code what's going on. Triggers can hide important functionality. Stored procedure are usually preferred for transact SQL for performance reasons.

A: Your master table appears to be a cross join of all potential combinations.  Thus when you add a new region, you are having to add all potential products in that region.  This is a lot of effort for data which can simply be inferred from all potential regions and all potential categories.
I know you mention that there are additional columns.  What do these additional columns contain?
I would typically not keep such a table materialized on a normalized database - unless the additional columns you are alluding to need to be assigned in some special way at creation and then altered in some kind of maintenance - even in that case, a sparse table (i.e. only departures from the defaults) with appropriate defaults can work well.
I do have a similar cross join in one of my systems and it contains about 25m rows and allows us to replace very complex logic over a 2-Dimensional 2500 general ledger accounts x 10000 cost centers space where there are "rows" and "columns" of identical logic, yet "islands" of logic.

A: Alright, thank you for your answers and suggestions.
I am working with an access project connected to MsSQL database. I tried to solve this by using a table trigger, but none of the suggestions has done the trick for me. Therefore I decided to solve this on the client side with VBA code instead.
It is probably not the proper way to solve it, but it might be useful to know for anyone reading.
The table structure is the same, but I have made a corresponding form for both the product and region table. On the forms AfterInsert event I have the following code:
Region table:
Private Sub Form_AfterInsert()

Dim varRegion As String
Dim strSQL As String

varRegion = Me![code]
strSQL = "INSERT INTO master([region], [product]) SELECT '" & varRegion & "', & _
          [code] FROM product;"

    DoCmd.RunSQL strSQL

End Sub

Product table:
Private Sub Form_AfterInsert()

Dim varProduct As String
Dim strSQL As String

varProduct = Me![code]
strSQL = "INSERT INTO master([region], [product]) SELECT [code], & _
          '" & varProduct & "' FROM region;"

    DoCmd.RunSQL strSQL

End Sub

EDIT: Having research the matter a little bit more, I found that this is the code you need to be using for the trigger if you are using SQL Server, if you don't want to use the client side setup.
Apparently, in SQL Server you need to reference a hidden table called "inserted" when you want to get the values of the inserted row. View this link for more info: Multirow Considerations for DML Triggers
Great!
Product table:
-- Trigger statement
CREATE TRIGGER "name-of-trigger"
ON producttable
FOR INSERT AS

    -- Insert statement
INSERT INTO mastertable ([region],[product])
SELECT regiontable.[code], inserted.[code]
FROM regiontable, inserted;

Region table:
-- Trigger statement
CREATE TRIGGER "name-of-trigger"
ON regiontable
FOR INSERT AS

    -- Insert statement
INSERT INTO mastertable ([product],[region])
SELECT producttable.[code], inserted.[code]
FROM producttable, inserted;


text:
Q: Why does Tensorflow not override __eq__ for Tensors? Tensorflow overrides multiple operators for the Tensor class, including __lt__, __ge__, etc.
However, the implementation for __eq__ seems to be conspicuously absent:
ops.Tensor._override_operator("__lt__", gen_math_ops.less)
ops.Tensor._override_operator("__le__", gen_math_ops.less_equal)
ops.Tensor._override_operator("__gt__", gen_math_ops.greater)
ops.Tensor._override_operator("__ge__", gen_math_ops.greater_equal)

Why does == for tensorflow's tensors not behave the same way as for numpy arrays?
Code example:
a = tf.constant([1,2])
b = tf.constant([3,4])
a == b
>>> False
a < b
>>> <tf.Tensor 'Less:0' shape=(2,) dtype=bool>

With numpy, on the other hand:
a = np.asarray([1,2])
b = np.asarray([3, 4])
a == b
>>> array([False, False], dtype=bool)

A: Tensors do implement __eq__, but the implementation only tests for identity. I found this GitHub issue, which explains why tensors test for identity, and do not broadcast:

This may be a complication of fact that tensors can be used as keys in dictionaries, which I believe use == to find the matching object with the same hash

The commenter is correct; if __eq__ was overloaded to broadcast then you could not use tensors as keys in a dictionary. Objects that define a __hash__ method (required if you want to use such objects as keys in a dictionary), must produce the same hash value for two objects that are equal; see the __hash__ method:

The only required property is that objects which compare equal have the same hash value

but broadcasting would produce a 'true' tensor object for objects with different hash values.
(the speculation that __eq__ would break boolean testing is wrong; boolean testing uses __bool__, which tensors do implement).
If you need to make element-wise equality tests on tensors, you can use the tf.equal() and tf.not_equal() functions.


text:
Q: How to calculate general formula for this recurrence? The recurrences are
$$F_n = a F_{n - 1} + b G_{n - 2}$$
$$G_n = cG_{n - 1} + d F_{n - 2}$$
$$H_n = e F_{n} + f G_n$$
where $a, b, c, d, e, f$ are constants.
How do I calculate $H_n$ in terms of only constants?

A: the z-transform of a sequence is defined like this:
$$ \mathcal Z\{ x[n]\}=X(z) = \sum_{n=-\infty}^{\infty}x[n]z^{-n} $$
then using this property of Z-transform you get(you can see all information needed for deep introduction to z-transform in https://en.wikipedia.org/wiki/Z-transform ) :
$$\mathcal Z\{ x[n]\}=X(z) \Rightarrow \mathcal Z\{ x[n-k]\}=z^{-k}X(z)$$
then your system of equations change's into this:
$$F_n = a F_{n - 1} + b G_{n - 2}\Rightarrow F(z)(1-az^{-1})=G(z)(bz^{-2})$$
$$G_n = cG_{n - 1} + d F_{n - 2}\Rightarrow G(z)(1-cz^{-1})=F(z)(dz^{-2})$$
$$H_n = e F_{n} + f G_n\Rightarrow H(z)=eF(z)+fG(z)$$


text:
Q: SwiftUI ForEach.onDelete doesn't work correctly in TabView I have tried to implement a basic list with a ForEach loop. I've tried with Both a hashable struct and basic array Using ForEach(..., id: \.self) as shown below. Whenever it's inside a tab view and changing to EditMode.active, you have to press the - for about a sec as if it's a LongPressGesture() until it will show the swipe to delete.
Example of problem

struct HashArray: Hashable {
    let id = UUID()
    init(number: Int) {
        self.number = number
    }
    let number: Int
}

struct TabStuff: View {
    @State var markers: [Int] = [1, 2, 3, 4, 5]
    @State var testArray: [HashArray] = [HashArray(number: 0), HashArray(number: 1), HashArray(number: 2), HashArray(number: 3)]
    var body: some View {
        VStack {
            EditButton()
            List {
                ForEach(testArray, id: \.id) { marker in
                    Text("Number: \(marker.number)")
                }.onDelete(perform: { indexSet in
                    markers.remove(atOffsets: indexSet)
                })
            }
        }
    }
}

struct OtherView: View {
    @State var markers: [Int] = [1, 2, 3, 4, 5]
    var body: some View {
        VStack {
            EditButton()
            List {
                ForEach(markers, id: \.self) { marker in
                   Text("\(marker)")
                }.onDelete(perform: { indexSet in
                    markers.remove(atOffsets: indexSet)
                })
            }
        }
    }
}

both of which don't work when putting inside of a tab view like so
struct ContentView: View {
    @State var selectedTab: NavigationTab = .list

    var body: some View {
        TabView(selection: $selectedTab) {
            TabStuff()
                .onTapGesture {
                    selectedTab = .list
                }
                .tabItem {
                    Text("List Test")
                }

            OtherView()
                .onTapGesture {
                    selectedTab = .secondView
                }.tabItem {
                    Text("Second View")
                }

        }
    }
}

Any ideas on how to get it to react appropriately?

A: It's because you have an .onTapGesture() on the entire view that is taking priority when a user taps anywhere in your view.
The tab items will automatically let you switch between tabs without having to update the selection, so you can just remove the tap gesture entirely. However, if you need to update the selectedTab when switching, you can use a .tag() modifier on the .tabItem.
        TabStuff()
            // REMOVE THIS
            //.onTapGesture {
            //    selectedTab = .list
            //}
            .tabItem {
                Text("List Test")
                    .tag(NavigationTab.list) // ADD THIS
            }


text:
Q: Computationally inexpensive redundancy for partial encoding With partial encoding I mean an encoding of information that only contains some of the information.
An example involves using a set of prime numbers and moduli. A small and silly example:

*

*Choose a set of prime numbers, $\{2,3,5\}$

*Choose a number that is less than the number of prime numbers, $n=2$

*Compute the product of the $n$ smallest numbers in the set, $basis=6$

*Encode data as a string of digits in the $basis$ $6$

*Divide each digit with each prime from the set and call each sequence of remainders a partial encoding
Assembly

*Given a set of sequences of remainders modulo different primes we can reconstruct the string from (4.) using the gcd algorithm iff the product of the basis of the moduli is greater or equal to the basis.

The purpose of partial encoding is to take some data in split it into parts. If you for instance have $10$ users who each have one complete copy of some data then there might be a significant risk that none of them are online. But if $100$ people each have $10\%$ of the data you would have a higher likelihood of reconstructing the original data. You would do this with the algorithm above, except you have to have $100$ primes and you might end up multiplying some really big numbers.
So I'm wondering if there is a more efficient way to partially encode data.

A: There is a protocol where you can give each user 10% of the data in a very precise sense: when 10 users are online, you will have all the data, and when any fewer are online, you will have none of the data. This is known as the Reed-Solomon method.
Suppose you are trying to split up $b$ bits of data so that any $n$ users will together have all the data, but any $n-1$ users will have none of the data. The following math will take place over the finite field $\mathbb F$ with $2^b$ elements. Choose a polynomial
$$
p(x)=x^n+a_{n-1}x^{n-1}+a_{n-2}x^{n-2}+\dots+a_1x+a_0
$$
where $a_1,a_2,\dots,a_{n-1}$ are randomly chosen elements of $\Bbb F$, while $a_0$ represents the $b$ bits of data (i.e, choose a bijection from $\Bbb F$ to the set of binary strings of length $b$).
Then, for $i=1,2,\dots,2^{b}-1$, the $i^\text{th}$ user is given the value of $p(i)$, where we interpret $i$ to be an element of $\Bbb F$. The idea is that a monic polynomial of degree $n$ is uniquely determined by any $n$ of its values, so any $n$ users can recover the polynomial, and therefore the data $a_0$.
Some notes:

*

*$b$ should not be too small, or else you there will not be enough elements of $\Bbb F$ to give each user. You need $2^b$ to be larger than the number of potential users.

*However, if $b$ is too large, the calculations will become cumbersome. If you need $b$ to be large, then it is probability best to encrypt the $b$ bits of data with some asymmetric encryption scheme like AES-$128$, then use this method to share the $128$ bit key.


text:
Q: Building a 2-bit adder with a propagation delay of at most 2 gates An XOR-gate itself counts as 2 gates, so if I use an XOR-gate the delay would already be 2.
I have no idea how to do this, as a full adder for one bit already contains 2 XOR-gates (or 1 XOR-gate, 1 AND gate and 1 OR gate) so that would already have a delay of 4, while I have to build a 2 bit adder with a delay of at most 2 gates.
Is it actually possible to do this? Otherwise there must be an error in my exercise book.

A: Not with only the standard AND, OR, and NOT gates.  For the two-bit adder that takes in two-bit numbers AB and CD, and outputs a three-bit number XYZ, the truth table looks like this:
A B C D | X Y Z
0 0 0 0 | 0 0 0
0 0 0 1 | 0 0 1
0 0 1 0 | 0 1 0
0 0 1 1 | 0 1 1
0 1 0 0 | 0 0 1
0 1 0 1 | 0 1 0
0 1 1 0 | 0 1 1
0 1 1 1 | 1 0 0
1 0 0 0 | 0 1 0
1 0 0 1 | 0 1 1
1 0 1 0 | 1 0 0
1 0 1 1 | 1 0 1
1 1 0 0 | 0 1 1
1 1 0 1 | 1 0 0
1 1 1 0 | 1 0 1
1 1 1 1 | 1 1 0

The Karnaugh map for Y looks like this:
CD AB>
V  00 01 11 10
00  0  0  1  1
01  0  1  0  1
11  1  0  1  0
10  1  1  0  0

The problem is that since you are only allowed two gate delays, and we need both of those: one to AND together the bits in each group, and another to then OR those groups together.  This means that the groups we can specify are limited to those that do not contain any NOTs, i.e. only the following:
   A         B          C         D        A*B       A*C       A*D       B*C
. . x x   . x x .    . . . .   . . . .   . . x .   . . . .   . . . .   . . . .
. . x x   . x x .    . . . .   x x x x   . . x .   . . . .   . . x x   . . . .
. . x x   . x x .    x x x x   x x x x   . . x .   . . x x   . . x x   . x x .
. . x x   . x x .    x x x x   . . . .   . . x .   . . x x   . . . .   . x x .

  B*D       C*D       A*B*C     A*B*D     A*C*D     B*C*D    A*B*C*D    True
. . . .   . . . .    . . . .   . . . .   . . . .   . . . .   . . . .   x x x x
. x x .   . . . .    . . . .   . . x .   . . . .   . . . .   . . . .   x x x x
. x x .   x x x x    . . x .   . . x .   . . x x   . x x .   . . x .   x x x x
. . . .   . . . .    . . x .   . . . .   . . . .   . . . .   . . . .   x x x x

Note that none of these groups covers the 1001 spot without covering the 1101 spot, which we need for Y.  You may be able to get the correct groups using a NAND, NOR, or XNOR; but only if those count as 1 gate delay.
Note that if you are using a technology like CMOS logic where each bit has an inverse available, then using the Karnaugh map technique renders this problem trivial, with an example solution below (where a is NOT A, etc.):
X = AC + ABD + BCD
Y = Acd + abC + Abc + aCd + aBcD + ABCD
Z = bD + Bd