Are Monotone functions Borel Measurable?

Question: Could you guide me how to prove that any monotone function from $R\rightarrow R$ is Borel measurable?
Since monotone functions are continuous away from countably many points, would that be helpful in proving the measurability?
Comment: I'd try to apply the definition directly. That is, try to show that sets of the form $\{x\in \mathbb{R}\ |\ F(x)\ge t\}$ are Borel.
Comment: By definition, a function $\mathbb{R}\to \mathbb{R}$ is Borel-measurable when the preimages of open subsets of $\mathbb{R}$ are Borel sets of $\mathbb{R}$. Do you agree with this definition?
Comment: If you agree, then you can convince yourself that, actually, it is enough to check that the preimages of half-lines are Borel. More precisely, $F\colon \mathbb{R}\to \mathbb{R}$ is Borel measurable if and only if for every $t \in \mathbb{R}$ the following set is Borel:
$$\{x\in \mathbb{R}\ |\ F(x)\ge t\}$$
(Cfr. Rudin, *Real and complex analysis*, 3rd ed., Theorem 1.12)
Comment: Hi @GiuseppeNegro, I actually have hard time understanding this method. I always use the basic definition of looking at pre-image. Could you explain this a little more. How we show/use this?
Comment: Yes, it completely matches my definition of $\forall B \in \text{Borel Set} \{w: f(w)\in B\} \in F \text{ where F is also Borel Set}$
Comment: See this answer: https://math.stackexchange.com/questions/3968451/monotone-functions-are-borel-measurable.
Answer: Hint: If $f$ is monotone, then, for every real number $x$, the set $$f^{-1}((-\infty,x])=\{t\mid f(t)\leqslant x\}$$ is either $\varnothing$ or $(-\infty,+\infty)$ or $(-\infty,z)$ or $(-\infty,z]$ or $(z,+\infty)$ or $[z,+\infty)$ for some real number $z$.
To show this, assume for example that $f$ is nondecreasing and that $u$ is in $f^{-1}((-\infty,x])$, then show that, for every $v\leqslant u$, $v$ is also in $f^{-1}((-\infty,x])$.


SQL group by ranges and keep 0

Question: I justed read this page: In SQL, how can you "group by" in ranges?
The response helped me but I have a question, If the count() for a range equals 0, the range will not showed, how can I show the range when the count() equals to 0 ?
Here is my query:
select
    w.Période,
    nb from( select t.Période, count(*) as nb
from (select
          *,
          case
              when report.creation_date between '2017-05-28 00:00:00' and '2017-06-25 00:00:00'
                  then 'P3'
              when report.creation_date between '2017-06-25 00:00:00' and '2017-07-23 00:00:00'
                  then 'P4'
              when report.creation_date between '2017-07-23 00:00:00' and '2017-08-20 00:00:00'
                  then 'P5'
              when report.creation_date between '2017-08-20 00:00:00' and '2017-09-17 00:00:00'
                  then 'P6'
              else 'Avant'
          end as Période
      from report
      where report.office_id = 11) as t
      group by t.Période ) as w

Here is my result:
Avant 57
P3 1
P5 2
P6 4

I would like to have:
Avant 57
P3 1
P4 0
P5 2
P6 4

I have tried to use these but it doesn't work. case when count() is null then 0 else count() end as nb or case when count() = 0 then 0 else count() end as nb or case when count() REGEXP '[^[:digit:]]' then 0 else count() end as nb
Answer: You should join them against a derived table:
SELECT t.period,
       COALESCE(s.nb,0) as yourCount
FROM(SELECT 'P1' as period
     UNION ALL
     SELECT 'P2'
     UNION ALL
     ...) t -- This is the derived table
LEFT JOIN(Your Query Here) s -- This is your query
 ON(t.period = s.period)

Answer: To slightly cleanup from what was offered by sagi, you have extra bloat and grouping, but will need a pre-query for all the qualified periods you want in your output...  This will be your primary table being queried.  Then, a simple select from/group by is the LEFT-JOIN
select
     preQuery.Période,
     coalesce( PreSum.AllRecs, 0 ) as TotalRecs
   from
      ( select 'P3' as Période
        union all select 'P4'
        union all select 'P5'
        union all select 'P6'
        union all select 'Avant' ) preQuery
         LEFT JOIN
         ( select
                 case when r.creation_date between '2017-05-28 00:00:00'
                                               and '2017-06-25 00:00:00'
                      then 'P3'
                      when r.creation_date between '2017-06-25 00:00:00'
                                               and '2017-07-23 00:00:00'
                      then 'P4'
                      when r.creation_date between '2017-07-23 00:00:00'
                                               and '2017-08-20 00:00:00'
                      then 'P5'
                      when r.creation_date between '2017-08-20 00:00:00'
                                               and '2017-09-17 00:00:00'
                      then 'P6'
                      else 'Avant'
                 end as Période,
                 count(*) as AllRecs
            from
               report r
            where
               r.office_id = 11
            group by
                 case when r.creation_date between '2017-05-28 00:00:00'
                                               and '2017-06-25 00:00:00'
                      then 'P3'
                      when r.creation_date between '2017-06-25 00:00:00'
                                               and '2017-07-23 00:00:00'
                      then 'P4'
                      when r.creation_date between '2017-07-23 00:00:00'
                                               and '2017-08-20 00:00:00'
                      then 'P5'
                      when r.creation_date between '2017-08-20 00:00:00'
                                               and '2017-09-17 00:00:00'
                      then 'P6'
                      else 'Avant' end ) PreSum
             on PreQuery.Période = PreSum.Période

Comment: Merci pour votre aide !
Comment: Thanks for your help !
Answer: If you have the values in the table, but just not for that office, you can do:
  select (case when r.creation_date between '2017-05-28' and '2017-06-25'
               then 'P3'
               when r.creation_date between '2017-06-25' and '2017-07-23'
               then 'P4'
               when r.creation_date between '2017-07-23' and '2017-08-20'
               then 'P5'
               when r.creation_date between '2017-08-20' and '2017-09-17'
               then 'P6'
               else 'Avant'
           end) as Période ,
          sum(r.office_id = 11) as cnt
  from report r
  group by Période;

The conditional aggregation method is often simpler to implement than using an outer join.  The outer join is more general in the sense that you explicit select the rows that you want.  This method is more general in the sense that any period in the data will be represented -- even if it is a new one.
Some notes:

There is no need for so many subqueries.  That just makes the work of the optimizer harder to do and more difficult for humans to follow the query.
I'm a big fan of qualified column names (the r.s in the query).
You don't need to include 00:00:00 when specifying a date.

In fact, clearer logic would be:
If you have the values in the table, but just not for that office, you can do:
  select (case when r.creation_date < '2017-06-26'
               then 'P3'
               when r.creation_date < '2017-07-24'
               then 'P4'
               when r.creation_date < '2017-08-21'
               then 'P5'
               when r.creation_date < '2017-09-18'
               then 'P6'
               else 'Avant'
           end) as Période ,
          sum(r.office_id = 11) as cnt
  from report r
  where r.creation_date >= '2017-05-28'
  group by Période;

Note that the inequality < is used.  This is handy because it works consistently for both dates and date/times.
Comment: yes, but he wants records where there may NOT be any values for the 'P4' period, thus a count of zero would not be returned.  That is why I did the sub-select.  I do agree with context of the where clause for filtering the date periods, but don't know their purpose of  the "Avant" group.
Comment: @DRapp . . . This answer is only applicable if some office has any given group.  Otherwise an explicit list is needed.  This is just a convenience in many similar cases.
Comment: Understood, and probably would have been better to have a secondary table of "Period" records with date ranges vs hard-coded references, then a simple left-join as needed.

SQL group by ranges and keep 0


Apache installed but not running Debian

Question: i have installed apache in debian lenny distro but everytime i start it or check its status it says apache running with certain process id. but when i check the defualt web page (i.e http://server-ip) it gives "It Works"
but when i try my pages it doesnt works
Giving this error "The requested URL /click-to-call.php was not found on this server.
Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny3 with Suhosin-Patch mod_python/3.3.1 Python/2.5.2 Server at 18.104.22.168 Port 80"
Please help
in response to questions posed:

I have placed click-to-call.php inside /var/www/html if i am wrong then where should I place this file.
When i try "/etc/init.d/httpd status " it gives file not found
I have root access.
I have placed the file inside /var/www/html
Comment: apache itself is working if you got that error message.
Answer: Where you put the 'click-to-call.php' file?
have you tried to put it in the right place like "/var/www/"?
You'll need a root account to have access to this folder (I guess you have :D)
Comment: have the root access. and i have placed the file inside /var/www/html
Comment: The debian/ubuntu default docroot is */var/www/* **not** */var/www/html/*
Answer: that's because your click-to-call.php not located inside your apache's default directory
Answer: In Debian it's

/etc/init.d/apache2 status

But we already know apache is running. So, try browsing to:

http://your.ip.address/html/click-to-call.php

Apache installed but not running Debian


Why is the 'time ago' not displayed in my view?

Question: I'm not sure whether this is a bug or not, so I'm just going to ask this. I created a view (and block) with a 'Comment: Post date' field with 'Time ago (with "ago" appended)' as Date format. I didn't fill in a custom date format.
Everything is previewed perfectly, but when I go to my dashboard, I only see the "ago": the actual numbers (hours, minutes, seconds...) aren't displayed.
I cleared caches, but nothing happened. I'm still using the default Seven 7.23 administration theme for my dashboard and I didn't set a custom template file or anything else. I just created the view.
How can I solve this?
Edit: I exported my view, so you can read the code here.
Comment: Are you using a custom theme? try switching to drupal default theme and try again. Clearing the cache is also a good idea.
Comment: I cleared caches, but nothing happened. I'm still using the default Seven 7.23 administration theme for my dashboard.
Comment: Could you please export that view so I could take a look at it?
Comment: I updated my question and added a link to the code.
Comment: I've imported your view and placed the block on the sidebar of a test installation. It shows the time as it supposed to. I can take a screenshot of it. Did you set any custom template file for that view?
Comment: Here is the screenshot: http://oi41.tinypic.com/2ppaqnd.jpg I have only generated some random content with devel module, unapproved some comments and imported your view. It works.
Comment: That's soo strange! I didn't use a custom template file or anything else. I just created the view.
Comment: Any errors in your recent log messages (watchdog) list?
Comment: Also, if you view the source code in your browser are the times still missing there?
Comment: @rooby: There are no error messages. What do you mean with "view the source code in my browser"?
Comment: What browser are you using?
Comment: @rooby: I'm using Firefox's latest version (24.0). I've just checked it: the problem is there in Internet Explorer 10 too.
Comment: In firefox, right click somewhere on the page and then click "View Page Source", then you can use CTRL+F for find and search for the part where your view displays to see if the time is also missing from the html source or if it is just hidden from view via css. You could also try disabling javascript and seeing if the problem persists to eliminate that as a possibility too.
Comment: The page source doesn't provide any information about my dashboard and views. Disabling javascript doesn't work, because I can't access my dashboard anymore.
Answer: I don't know what causes the problem, but I solved it temporally. I changed the Date format to 'Time ago' an added the 'ago' manually via the 'Rewrite results' function.


Migrate VM from MS Virtual Server 2005 to Hyper-V?

Question: Is there a supported path of migrating a virtual machine running in Microsoft Virtual Server 2005 R2 SP1, to Hyper-V on Windows Server 2008 R2 SP1? The guest is running a version of Windows Server 2003.
Answer: Yes, SCVMM can V2V a MS Virtual Server 2005 VM to Hyper-V. You can also treat the VM like it's physical and P2V it, but that generally takes a much longer time to convert that way.
Comment: I suppose "expensive" depends on the size of your budget, but I've never seen a quote for it that would warrant it to be written in all capital letters :)
Comment: The question was not about cost, it was about migration paths. I suggest we all stay on topic.
Comment: -1. This is not a solution, even if a not educated OP answer s it. It requires and EXPENSIVE additoinal piece of software that the poster has not said he uses (and that is not something a small Hyper-V install would use).
Comment: Well, Hyper-V costs 0 and someone using from Virtual Server unlikely runs a 100 machine farm, you know. In this case, without SPLA, this is a ridiculous additional expense.
Comment: The OP may have awarded the delivery of the answer as well. Attitude matters.
Answer: There is an official MS guide for this type of migration which describe all the necessary requirements and steps to be performed:
Virtual Machine Migration Guide: How To Migrate from Virtual Server to Hyper-V


What causes the error in App Delegate: Type 'AppDelegate' does not conform to protocol 'UITableViewDataSource?

Question: I think error stems from elsewhere, not AppDelegate.
So, in a viewcontroller type file (class homepage) I want to fetch info from firebase and display. After finishing that section of code, App delegate gives an error.
I've removed the UITableViewDataSource from AppDelegate, then it runs, but doesn't display Firebase info.
<code>class homepage: UITableViewController, CLLocationManagerDelegate{

    var people = [Userx]()

    @IBOutlet weak var table: UITableView!

    public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return people.count
    }

    public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            as! ViewControllerTableViewCell

        let person: Userx = people[indexPath.row]

        cell.lblName.text = person.Education
        cell.lblgenre.text = person.WhatIamConsideringBuying

        return cell

    }

    var locationManager = CLLocationManager()

 override func viewDidLoad() {

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(signOut))

    super.viewDidLoad()

    let databaseRef = Database.database().reference()
    databaseRef.child("Education").observe(DataEventType.value,  with: {snapshot in

        if snapshot.childrenCount>0{
            self.people.removeAll()
            for people in snapshot.children.allObjects as! [DataSnapshot] {
                let peopleObject = people.value as? [String: AnyObject]
                let peopleEducation = peopleObject?["Education"]
                let peopleWhatIamConsideringBuying = peopleObject?["WhatIamConsideringBuying"]
                let peoplePhotoPosts = peopleObject?["PhotoPosts"]
                let people = Userx(Education: peopleEducation as! String?, WhatIamConsideringBuying: peopleWhatIamConsideringBuying as! String?, PhotoPosts: peoplePhotoPosts as AnyObject)
                    self.people.append(people)

            }
            self.table.reloadData()

        }

    })

///this is different file code for class ViewControllerTableViewCell

class ViewControllerTableViewCell: UITableViewCell {

    @IBOutlet weak var lblName: UILabel!
    @IBOutlet weak var lblgenre: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
</code>
Since the error may be in storyboard, the path of homepage is:Homepage Scene - Homepage - Table - Cell - Content View - label 1 and label 2. DataSource and Delegate from Table is connected to Homepage via Outlets.
I just want the error in AppDelegate to disappear so that data can be fetched from firebase.
Here is App Delegate code:
<code>@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UITableViewDelegate, UITableViewDataSource {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FirebaseApp.configure()

            return true
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
</code>
}
Database Structure: https://i.stack.imgur.com/xh0LK.jpg
Comment: Post the code of your AppDelegate if the error says something is wrong there
Comment: Ok, will add now. I am pretty sure error is not there though as I never changed it.
Comment: You don't control a table with AppDelegate.
Comment: Thanks. I removed both table references there. It works (like mentioned in the question), but then no data gets fetched from Firebase.
Comment: I think the error may have something to do with not having textfield outlets in homepage. However adding them makes error: Illegal Configuration. Outlets cannot be connected to repeating content.
Answer: Write this code in your viewDidLoad() method
<code>   table.dataSource = self
   table.delegate = self
</code>
And update your code in cellForRowAt
<code>     public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

       let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell

       if let person = people[indexPath.row] {
              cell.lblName.text = person.Education
             cell.lblgenre.text = person.WhatIamConsideringBuying
       }

      return cell

 }
</code>
To Prevent App from crash
<code> override func viewDidLoad() {

navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(signOut))

super.viewDidLoad()

let databaseRef = Database.database().reference()
databaseRef.child("Education").observe(DataEventType.value,  with: {snapshot in

    if snapshot.childrenCount>0{
        self.people.removeAll()
        for people in snapshot.children.allObjects as! [DataSnapshot] {
            let peopleObject = people.value as? [String: AnyObject]
            let peopleEducation = peopleObject?["Education"]
            let peopleWhatIamConsideringBuying = peopleObject?["WhatIamConsideringBuying"]
            let peoplePhotoPosts = peopleObject?["PhotoPosts"]

     if let peopleEducation =  peopleEducation as? String {
        if let whatIAmConsideringBuying = peopleWhatIamConsideringBuying as? String? {
          if let photoPosts = photoPost as? AnyObject {
            let people = Userx(Education: peopleEducation, WhatIamConsideringBuying: whatIAmConsideringBuying, PhotoPosts: photoPosts)
              self.people.append(people)
    }
   }
 }

}
        self.table.reloadData()

    }

})
</code>
Comment: Where do you find viewDidLoad in AppDelegate?
Comment: I am saying for viewController viewDidLoad method. I think error occurs because it does not make tableView delegate to controller
Comment: I think the error may have something to do with not having textfield outlets in homepage. However adding them makes error: Illegal Configuration. Outlets cannot be connected to repeating content.
Comment: There is no need of outlets in homepage if they have in ViewControllerTableViewCell .
Comment: Thanks for the help. I think I know what's wrong. (no idea how to fix though). I think it has to do with how the firebase Database is structured. It is structured like this:
Education >
>>>> userkey x…p : ""
>>>> userkey y…….: ""
PhotoPost
>>>> userkey x…p: ""
>>>> userkey y…….: ""

I think my code is written so that the children would be where the user keys are in the database at the moment. Do you agree?
Comment: It's hard to properly describe the database structure in comment. I have added it in a link in the question.
Comment: Yes database structure is the main problem . According to your written code PhotoPost is the child of Education but as structure seems PhotoPost is not a child . But according to some good practices your code should be written like if data unable to fetch from server your app should not crashed . So to prevent crash does not forecast and make it optional . I am editing my answer to show you to to prevent from crash.
Comment: Thanks. I changed the database structure last night and it work.


most trouble/hassle free way of running a backup of a server

Question: We're running windows server 2003 and as of now, we are using NTBACKUP - however, we are looking for another tool, preferably something free which offers mediocore features.
The reason we want to move away from NTBACKUP is that it is not very reliable. Sometimes our full backups are 70GB and sometimes they come up to 110+GB with the exact same options and files selected. Incrementals (run a day after) also run up to something silly like 40GB which is impossible since nothing much changes on the server.
edit: We're looking into remote backup too (something like jungle disk) but for now, we have 2 hdd's; one for offsite storage and one onsite.
edit1:
Okay so one thing I'm trying tomorrow is a tool called 'handy backup'. Apparently we already have a licence for it on the server so I'll see how that goes.
Still open to suggestions - we did have a trial of 'shadow copy' however, the licence (500$) was a bit too expensive for our liking.
Answer: NTBackup isn't very flashy, but it does work fine. Certainly, if you want more / better features then moving to a more feature-rich backup management program may be in the cards.
It sounds like you haven't done a lot of investigation about the problems you've been seeing. I'd strongly suggest that you pinpoint the root cause of these wild size discrepancies, as you're likely to have the same problems with whatever backup program you end up choosing. You could have in-use files as a result of server-side applications locking files, etc.
If your "backup" is just a couple of hard disk drives I'd argue that you probably aren't taking backup seriously enough. You ought to be thinking about what the cost to the business would be when you lose weeks, months, or all of the data, and spending accordingly.
Comment: We did have a trial of 'shadow protect' and that backed up at a constant 40GB or so (compressed) every single time - I will however, try and pin point the cause of the size issues of NTBackup :)

Also, as I said above, we are still looking into remote backup, but as of now, I believe our current backup solution is adequate. We keep one full backup offsite weekly and one on site which contains a full backup in between the weekly.
Answer: For online backups (which I highly recommend) I have used USDataTrust in the past. Very nice set and forget. There may be more cost effective solutions but 2 years ago they were great. Just Google "Online Server Backups".
HTH  Mike


Automatic copy node from Drupal A to Drupal B

Question: Drupal A and B are different domain (example: drupal A: www.aaa.com and drupal B: www.bbb.com)but at the same server.
At Drupal A, there are lot of fields, but I only need to send date field value to Drupal B (Everytime when it update or add new content). Drupal B will get date value and display at the content page. May I know how to do that?
I had tried Deploy (not working at all)
How to add data from one Drupal site to other?
I had tried aggregate but I send everything to Drupal B.
I need help. Many thanks.
For far my current solution is:
At Drupal B: php code connect drupal A database and get the date vaule. Echo to display at the content page.
Comment: what exactly your problem you are not able send all field data or only want to send date?
Comment: @VimalGoradiya I had edited my question
Comment: How the node form Drupal A and Drupal B are related? When you edit a node in Drupal A another node in Drupal B should get the date field value, and display? What you mean with 'display'?
Comment: @tunic I had edited my question.
Answer: I would solve the problem with either of the following
1) Write a 5 minute custom php script that would show the node ids and data value and then update the nodes with data value in the second database with a simple update query on field_data_field_<your-field-name> table based on entity id.
2) Use services 3 module to expose your data and then import that field with put method with only the field you want.
Answer: You have several options:

Use Migrate: This is like what you have but more Drupal way. The migration code should be the iterator that queries your Drupal A and returns the list of nodes and the code that takes each node and updates or creates nodes on Drupal B. I recommend you to put it in a Drush command and call it from system cron (not Drupal cron but system cron).
Using some kind of services: When Drupal A detects a change that should be sent to Drupal B make a service petition to a service on Drupal B. You have to set up the service on Drupal B and the code that consumes the service in Drupal A.
Exposing info from Drupal A: A simpler option is to export the data in Drupal A as a View and Drupal B access the URL to check new data and import it, using Drupal cron. You can protect the URL with Basic Auth allowing only local connections.

You can even combine (for example, use Migrate but instead of connect directly to the other database consume data from a View form Drupal A).
Disclaimer: I've not tested other modules to copy content, may be there's a module that suits your needs, I'm extending your current solution.
Answer: I would suggest that you use drupal_sync module. it allow sync content between multiple websites. Its built on top of API so you can create your own custom module on top of it.


Migration from mysql to sql server

Question: I am working on to migrating my mysql server (phpmyadmin) to sql server 2012. I am using the SQl migration tool, but have came this far. When I chose my database: nih_bw I cant access "Convert Schema".
When I double click on database I get: Target Metadata does not exist.
This is my sql file for the database:
-- phpMyAdmin SQL Dump
-- version 4.0.4
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 10, 2014 at 04:23 PM
-- Server version: 5.6.12-log
-- PHP Version: 5.4.12

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `nih_bw`
--
CREATE DATABASE IF NOT EXISTS `nih_bw` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `nih_bw`;

-- --------------------------------------------------------

--
-- Table structure for table `change_log`
--

CREATE TABLE IF NOT EXISTS `change_log` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `routine_id` int(11) NOT NULL,
  `title` varchar(25) NOT NULL,
  `value_old` varchar(10) NOT NULL,
  `value_new` varchar(10) DEFAULT NULL,
  `action` varchar(10) NOT NULL,
  `changed_at` date NOT NULL,
  `date` date NOT NULL,
  `time` time NOT NULL,
  `changed_by` varchar(6) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `change_log`
--

INSERT INTO `change_log` (`id`, `routine_id`, `title`, `value_old`, `value_new`, `action`, `changed_at`, `date`, `time`, `changed_by`) VALUES
(2, 250, 'T_Badende_per_time', '25', '35', 'Redigert', '2014-04-07', '2014-04-04', '15:41:20', 'TomCzi');

-- --------------------------------------------------------

--
-- Table structure for table `emps`
--

CREATE TABLE IF NOT EXISTS `emps` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(25) NOT NULL,
  `first_name` varchar(15) NOT NULL,
  `last_name` varchar(15) NOT NULL,
  `email` varchar(25) NOT NULL,
  `password` varchar(60) NOT NULL,
  `user_type` char(5) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `emps`
--

INSERT INTO `emps` (`id`, `user_name`, `first_name`, `last_name`, `email`, `password`, `user_type`) VALUES
(1, 'BilAhm', 'Bilal', 'Ahmad', 'firstname.lastname@example.com', '$2y$10$8/CSeWtfzkWIPE/B1F58D.2XiOPkm84RHk9WqjYTIY0Crn9qe1G.W', 'admin'),
(2, 'TomCzi', 'Tomas', 'Czipri', 'firstname.lastname@example.com', '$2y$10$8CidOVjejN0Gn1vYdwSf.usSeP.dHeNKWKx1fC022qsnQ5Edh88uG', 'admin'),
(4, 'BenPau', 'Benedicte', 'Paulsen', 'firstname.lastname@example.com', '$2y$10$lQRDmqmNbmv3QGSg2onxOueMnMlNN00KSYK0Ggtjr3urzZFpE21iK', 'user');

-- --------------------------------------------------------

--
-- Table structure for table `measurements`
--

CREATE TABLE IF NOT EXISTS `measurements` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(25) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=25 ;

--
-- Dumping data for table `measurements`
--

INSERT INTO `measurements` (`id`, `title`) VALUES
(1, 'T_Badende_per_Time'),
(2, 'T_Temperatur'),
(3, 'T_Luft_Temperatur'),
(4, 'M_Fritt_Klor'),
(5, 'M_Bundet_Klor'),
(6, 'M_Total_Klor'),
(7, 'M_PH'),
(8, 'M_Auto_Klor'),
(9, 'M_Auto_PH'),
(10, 'M_Redox'),
(11, 'O_Vannbalanse'),
(12, 'O_Alakalitet'),
(13, 'O_Hardhet'),
(14, 'O_Natrium_Bk'),
(15, 'O_Kals_Klor'),
(16, 'O_Sjokklor'),
(17, 'O_Fellingsmiddel'),
(18, 'O_Sirkulasjonsmengde'),
(19, 'O_Filtertrykk'),
(20, 'O_Spyl_Av_Filter'),
(21, 'O_Vannforbruk'),
(22, 'O_Slamsuging'),
(23, 'O_Harsil'),
(24, 'O_Ren_Utj_Tank');

-- --------------------------------------------------------

--
-- Table structure for table `measure_routine`
--

CREATE TABLE IF NOT EXISTS `measure_routine` (
  `routine_id` int(11) NOT NULL,
  `measure_id` int(11) NOT NULL,
  `pool_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`routine_id`,`measure_id`),
  KEY `pool_id` (`pool_id`),
  KEY `link3` (`measure_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `pools`
--

CREATE TABLE IF NOT EXISTS `pools` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=100 ;

--
-- Dumping data for table `pools`
--

INSERT INTO `pools` (`id`, `name`) VALUES
(1, 'Hovedbasseng'),
(2, 'Plaskebasseng'),
(99, 'Svommehall');

-- --------------------------------------------------------

--
-- Table structure for table `routines`
--

CREATE TABLE IF NOT EXISTS `routines` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `date` date NOT NULL,
  `time` time NOT NULL,
  `value` varchar(10) NOT NULL,
  `emp_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `emp_id` (`emp_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=561 ;

--
-- Dumping data for table `routines`
--

INSERT INTO `routines` (`id`, `date`, `time`, `value`, `emp_id`) VALUES
(554, '2014-04-10', '17:00:23', 'Utført', 1),
(555, '2014-04-10', '17:00:23', 'Utført', 1),
(556, '2014-04-10', '17:00:23', 'Utført', 1),
(557, '2014-04-10', '17:00:23', 'Utført', 1),
(558, '2014-04-10', '17:00:23', 'Utført', 1),
(559, '2014-04-10', '17:00:23', 'Utført', 1),
(560, '2014-04-10', '17:06:12', 'Utført', 1);

-- --------------------------------------------------------

--
-- Table structure for table `tasks`
--

CREATE TABLE IF NOT EXISTS `tasks` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(25) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=99 ;

--
-- Dumping data for table `tasks`
--

INSERT INTO `tasks` (`id`, `title`) VALUES
(40, 'D_Slamsuge_Pl_Bass'),
(41, 'D_Filter_Rens'),
(42, 'D_Bypass_Pl_Bass'),
(43, 'D_Vaske_Gulv_CM'),
(44, 'D_Garderobe_0730'),
(45, 'D_Garderobe_Dag'),
(46, 'D_Male_Temp_Just'),
(47, 'D_Vaske_Pl_Bass'),
(48, 'D_Vaske_H_Bass'),
(49, 'D_Renhold_Av_Wc'),
(50, 'D_Ettersyn_Utst_Skap'),
(51, 'D_Handicap_Heis'),
(52, 'D_Ettersyn_solarier'),
(53, 'D_Vannprove_0745'),
(54, 'D_Vannprover_1100'),
(55, 'D_Vannprover_1400'),
(56, 'D_Enkle_Vedliks_Oppg'),
(57, 'D_Sjekk_Skiftplan'),
(58, 'K_Oppdatere_Seg_IkkeUtf'),
(59, 'K_Vannprover_1700'),
(60, 'K_Vannprover_2000'),
(61, 'K_Vaske_Pl_Bass'),
(62, 'K_Vaske_H_Bass'),
(63, 'K_Sla_Av_Bypass'),
(64, 'K_Ettersyn_Materiell'),
(65, 'K_Ettersyn_Solarier'),
(66, 'K_Ettersyn_Sal_4'),
(67, 'K_Runde_Gard_Kveld'),
(68, 'K_Runde_Gard_For_Steng'),
(69, 'K_Enkle_Vedlik_Oppg'),
(70, 'K_Rullestolheis_lading'),
(71, 'K_Etterfylle_Skoposer'),
(72, 'K_Skap_Lases'),
(73, 'K_Sjekk_Skiftplan'),
(74, 'K_Rydd_Tribune'),
(75, 'K_Slamsug_H_Bass'),
(76, 'K_Stenge_Prosedyre'),
(77, 'K_Beskjed_H_Vakt'),
(79, 'C_Timeteller'),
(80, 'C_AllRent'),
(81, 'C_Grovrent_Ekstra'),
(82, 'C_Ren_Opplos_Tank'),
(83, 'C_Ren_Opps_Tank'),
(84, 'C_Ren_Flott_gitter'),
(85, 'C_Ren_Opplos_Filter'),
(86, 'C_Ren_Nal'),
(87, 'C_Kontr_Slang_Tank'),
(88, 'C_Kont_Ren_KostPad'),
(89, 'K_Forrige_Uke_Badende'),
(90, 'K_Sjekk_Flockmiddel_Kalsk'),
(91, 'K_Sjekk_Klorfat_Syrekanne'),
(92, 'K_Sjekk_Klorfat_Syrekanne'),
(93, 'K_Klorfat_Syrekanner'),
(94, 'K_Flockmiddel_Kalsklorid'),
(95, 'K_Sjekk_syreflow'),
(96, 'K_Kontroll_Wc'),
(97, 'K_Soppel_WC'),
(98, 'D_Vannmengde');

-- --------------------------------------------------------

--
-- Table structure for table `task_routine`
--

CREATE TABLE IF NOT EXISTS `task_routine` (
  `routine_id` int(11) NOT NULL,
  `task_id` int(11) NOT NULL,
  PRIMARY KEY (`routine_id`,`task_id`),
  KEY `link6` (`task_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `task_routine`
--

INSERT INTO `task_routine` (`routine_id`, `task_id`) VALUES
(554, 89),
(556, 93),
(555, 94),
(557, 95),
(558, 96),
(559, 97),
(560, 98);

--
-- Constraints for dumped tables
--

--
-- Constraints for table `measure_routine`
--
ALTER TABLE `measure_routine`
  ADD CONSTRAINT `link2` FOREIGN KEY (`routine_id`) REFERENCES `routines` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `link3` FOREIGN KEY (`measure_id`) REFERENCES `measurements` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `link99` FOREIGN KEY (`pool_id`) REFERENCES `pools` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `routines`
--
ALTER TABLE `routines`
  ADD CONSTRAINT `link1` FOREIGN KEY (`emp_id`) REFERENCES `emps` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `task_routine`
--
ALTER TABLE `task_routine`
  ADD CONSTRAINT `link5` FOREIGN KEY (`routine_id`) REFERENCES `routines` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `link6` FOREIGN KEY (`task_id`) REFERENCES `tasks` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Comment: Have you tried sqlserver migration assistant. It worked well for me migrating from oracle - sql server http://technet.microsoft.com/en-us/library/hh313129.aspx
Answer: http://www.mssqltips.com/sqlservertutorial/2205/mysql-to-sql-server-data-migration
This seemed like a pretty straight-forward tool for migration with screenshots and step-by-step instructions.
Based on reading about the issue you're having it seems like a pretty common problem. Sometimes it can even be the charset that you're using.

Migration from mysql to sql server


How to create a large(10gb+) persistent cache in .NET

Question: Spin-off from my other question.
.NET Garbagecollector trouble. Blocks for 15-40 mins
I want to create a simple persistent cache. For simplicity, everything that goes in stays in. I have currently implemented this with a ImmutableDictionary<int,DataItem> but I have problem with the garbage collector.
It seems to think I use lots of data which is true it as it contains 10 000-100 000 complex objects, and then it begins to think its a good idea to scan the cache very often. With blocking Generation 2. At least that's what I believe it does. "%Time in gc" is 90%+ and my application is blazing slow.
Can I somehow mark the cache as untouchable or let my app use more memory before GC thinks it should do a full collect? I have loads of free memory on the server.
Might switching to NCache or Redis for Windows (MSOpenTech) be a better solution?
Comment: Agree with Laurence, it sounds like you are describing a database with a key-value storage system like memcache, rather than an in-memory cache... Can you prioritise the frequently read items into a primary in-process cache and store the rest of the items in an out-of-process store like memcache?
Comment: In case of Redis there will be some cross process communication between your app and Redis even if they are on the same server, so it might slightly reduce performance of that operation. But you won't get GC issues in that approach as it will be stored in Redis
Comment: _"Might switching to xx or yy for Windows(MSOpenTech) be a better solution?"_ Depends.  Pro is that you can use them now. Cons - might not suit your needs.  Additionally, _Microsoft Windows Server AppFabric_ has a built-in object cache.  It can be local or distributed
Comment: I would recommend taking a different approach to this problem, you're fighting the system when it should be you who is conforming to it.  You state "It seems to think I use lots of data..", you do, you are caching 10gb+ worth of objects in memory.  Further stating "it begins to think its a good idea to scan the cache very often...", yes, sounds like GC is behaving exactly as it should.  Do you really need to cache 10GB+ worth of objects?  Whats the *real* cost of recreating one of the objects in the case of a cache miss?
Comment: "everything that goes in stays in" - that's a memory leak, not a cache.
Comment: There will be a ttl, but that was'nt the part i was interested in.
Your talking about memcached, which is a in-memory key-value storage and to me the term "cache" seems correct but it might be a database. If i have the memory is 10gb data in Memcached a bad idea? If i was to implement memcached in .Net, how would i do it? Object pooling?
I'm stuck with a existing MS-Sql database otherwise i believe a document database would fit my needs.
Comment: If anyone is interested i found some tips here.
http://blog.marcgravell.com/2011/10/assault-by-gc.html
Answer: You could use GC.TryStartNoGCRegion to strictly limit the times at which GC occurs.  Though in line with my previous comment, I believe this is not a good approach.
Have you considered examining how the cached objects are cleaning themselves up?  Perhaps when objects exceed the 4 hour ttl, cleaning them up takes too long?
Are the objects disposable?  Are they finalizable?  If yes to either one, whats the time cost of a Dispose or Finalize operation on an individual object?  If they are Finalizable, do they need to be?
Comment: The objects are not disposable or finalizable, and none of the objects inside them.
TTL is implemented with a sorted key,value storage with datetimes and when i access the store i check the object in one end if the datetime is more then ttl ago. if so i remove it from the list and check the next.
Might an immutabledictionary be bad to use here for my key/val storage? The dictionary will be replaced everytime a change is made.
I have this because the reading is 95% of the activity and i want a lock free solution.
Comment: ImmutableDictionary could be part of the problem, yes.  How are your objects moved from the old Dictionary to the new Dictionary?  Are they cloned, giving you 20gb worth objects, from which 10gb must be GC'ed?  As for locking, you could use a ReaderWriterLock instead of a standard lock, thus allowing simultaneous Read access, only requiring exclusive access when writing to the collection.
Comment: There are no standard locks, we use the built in system in ImmutableDictionary. So no cloning and no locks.
It builds a new dictionary containg the difference and repoints the cache to that. So readers never get locked. instead they might get some ms old data.
ImmutableCol = ImmutableCol.Add(myNewItem)
there are locks on the write though
Comment: @JohanLindberg I proposed the ReaderWriterLock because you stated that 95% of operations were Reads and that you wanted a lock free solution.  I assumed that to mean you were trying to avoid exclusive locks on reads.  The ReaderWriterLock allows simultaneous read locks, only requiring an exclusive lock during a write.
Comment: @JohanLindberg Also, ImmutableDictionary is Thread-Safe, so there is inherently some level of locking already present in your solution.
Comment: I thought the ImmutableDictionary was Thread-safe because its read-only? Not that it hold locks. You cannot alter an ImmutableDictionary. So the read performance should be better then using an readerwriterlock?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/72246/discussion-between-johan-lindberg-and-laurence-adams).


SASS to watch over whole root

Question: I'm attempting to use SASS on a development server I have at home.
I'm trying to find a way to have SASS by default watching all the different sites (folders inside the web root). I wouldn't like if I had to manually set SASS to watch over each and every site and everytime I created a new site.
Basically, it would need to find every .scss/.sass modified inside the root and create a .css at the same location.
All I could find is the basic sass --watch origin:destination but it's not what I need, since all my SASS files would be in different folders.
Just in case, I'm running an Ubuntu server and I do have ruby+sass already installed.
Thanks.
Answer: ...Duh.
The obvious way is the correct way.
The basic sass --watch origin:destination is recursive and does watch subfolders.
I feel dumb.
Comment: Not sure now... but 3 years ago it was.
Comment: It works as expected if your .scss files are not named as partials (file name beginning with underscore). Partials need to be further compiled using some other build tool I guess.
Comment: Keep in mind that this question/answer is almost 5 years old. If this is not the correct to do it now, you can edit the answer or send a new one, I guess...

SASS to watch over whole root


Recommendation of unique items

Question: I want to build a recommender for my e-commerce service.
The main problem is that every item in the system is unique,
and can be bought only once (so this item should be not recommended to anyone after the sale).
Service is similar to the eBay, where each item is unique, and, despite the fact that seller can publish the same item again, it will be considered as a new item in the system.
Also, there are not much common information between each item (the most common is the seller ID and the category ID),
so I can not easily find similar items based on what user had purchased before.
What techniques can I use in this situation?
Comment: Are users able to purchase more than one item or, alternatively, multiple unique items over some period of time, e.g., six months or one year? If so, you could base a recommender on the co-purchases occurring within that time span. Another option would be to cluster users and base a recommender on the co-purchases occurring within a cluster.
Comment: Just updated the description, the buying and selling process is similar to eBay.
Answer: As you point out, since each item can only be bought once, you cannot use that information to get a typical recommender system algorithm to discover categories among your items. What you could do, however, is assign certain labels to each item according to your own best judgment, or that of other human raters. (In theory I suppose you could try to solve this with machine learning as well, but that seems like it would require fairly cutting-edge, or even currently non-existent algorithms.) You could then train a recommender system on those labels and the purchases that people make. That is, you would fix one half of the recommender system that you'd normally get from data (the part where it would discover labels or categories that are predictive of what users will like) while you leave the other half to be learnt still (where it learns how each category influences a given user's preferences).
Alternatively, perhaps you could introduce a system of "likes", or something similar whereby users can rate items independent without (necessarily) buying them? If you get enough data from that, you could just use a regular recommender system that discovers its own labels without supervision (from similarities between users' ratings).
Answer: This is the typical setting of collaborative filtering. For example, in the Netflix prize, a reasonable assumption is that each person saw a set of movies once and that they should not be recommended movies that they have seen already.
There are a large number of collaborative filtering algorithms that could be used to address this problem. A simple one is related to Amazon's "Customers that bought this also bought that". This method finds the items most similar to each item as measured by how frequently they are purchased by the same person. For example, Harry Potter 1 and 2 are similar because they are often bought by the same person. To give a recommendation to a particular person, you would find which items are similar to the ones they have already purchased. This method is typically called a item-based collaborative filtering.
Comment: Each item is unique, so it can not be "bought together" by definition. I somewhat aware about Amazon's approach for this example, but association rules will not work for this case.
Comment: I see. In that case, you will need some way to assess the content of the items. A similar approach could be used with the category IDs. If the items have images or text descriptions, you could do unsupervised learning to derive features to use in a classifier.

Recommendation of unique items


Proof $\sum_{k=1}^{p-1}\left\lfloor\dfrac{km}{p}\right\rfloor=\dfrac{(m-1)(p-1)}{2}$ with $m$ and $p$ co-prime numbers

Question: We want to that:
$$\sum_{k=0}^{p-1}\left\lfloor\dfrac{km}{p}\right\rfloor=\dfrac{(m-1)(p-1)}{2}$$
with the following conditions:
$$\begin{cases}p\geqslant1,\ m\geqslant2, \\ m\text{ is even},\\ m\text{ and }p\text{ are co-prime.}\end{cases}$$
Comment: Given that $p+1$ will be even, have you tried proving ut for $p+2$?
Comment: @BBC3 I haven't, let me try ;-) thanks
Answer: Let $q_k, r_k$ be the quotient and remainder of the euclidean division of $mk$ by $p$, ie $$mk = pq_k  + r_k \text{ for } k\in[1, p-1]\quad \text{and } 0\le r_k\lt p$$
Now working mod $p$, since $r_1$ is coprime with $p$, it generates $\Bbb Z_p$ and therefore : $$\{r_k, k\in[1, p-1]\} = [1, p-1]$$
Notice we are trying to compute $$\begin{align}\sum_{k=1}^{p-1} q_k &= \sum_{k=1}^{p-1} {mk-r_k\over p} \\&= m{p(p-1)\over 2p} - \sum_{r=1}^{p-1}{r\over p} \\&= {m(p-1)\over2} - {p-1\over 2} \\&= {(p-1)(m-1)\over 2}\end{align}$$
Note : Using induction on this particular problem is not a good idea since $$\left\lfloor{m\over p}\right\rfloor \text{ and } \left\lfloor{m\over p+1}\right\rfloor$$
are not connected.
Answer: $$m-1<\bigg[\dfrac{m(p-1)}p\bigg]+\bigg[\dfrac1p\bigg]<m$$
$$→\bigg[\dfrac{m(p-1)}p\bigg]+\bigg[\dfrac1p\bigg]=m-1$$
This leads
$$\sum_{k=0}^{p-1}\bigg[\dfrac{km}p\bigg]=\dfrac{(m-1)(p-1)}2$$
Comment: Are those floor brackets ?


How to maintain scroll position in LazyVStack / VStack when insert item at the top of a list

Question: I create a simple vertical list that contain items to show.
The problem is when I insert items at the top of the list via insertAtTop(). The scroll view does not stay in the same place.
See the video: https://streamable.com/i7ywab

How can I make the scroll view stay in the same position?
Here is the sample code.
struct TestView: View {

    @State private var items: [Item] = []

    var body: some View {
        NavigationView {
            ScrollView {
                LazyVStack {
                    ForEach(items, id: \._id) { item in
                        Text(item.text)
                            .background(Color.green)
                            .padding(.bottom, 10)
                    }
                }
            }
            .navigationBarItems(trailing: HStack {
                Button("[Insert at top]", action: {
                    insertAtTop()
                })
                Spacer(minLength: 20)
                Button("[Load]", action: {
                    load()
                })
            })
            .navigationTitle("Item List")
        }
    }

    private func load() {
        items = (1...50).map { _ in Item() }
    }

    private func insertAtTop() {
        let newItems = (1...20).map { _ in Item() }
        items.insert(contentsOf: newItems, at: 0)
    }

}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView()
    }
}

struct Item {
    var _id = UUID()
    var text = UUID().uuidString.prefix(5)
}

Comment: Well, actually it maintains scroll position but changes content and, as I assume, you want to change scroll position  to preserve previously visible content.
Comment: Yeah, that what I want to solve. As you mentioned, the scroll offset actually does not change, but the content size has changed. I can solve this with UITableView, by setting offset after reloadData.
Comment: Did you figure this one out @nRewik? I'm having a similar issue here: https://stackoverflow.com/questions/65614647/infinite-vertical-scrollview-both-ways-add-items-dynamically-at-top-bottom-tha
Answer: The problem only seems to arise if you add new views at the top of the list. If you modify or replace existing views, there isn't a problem.
...so one workaround is to loop your ForEach over a placeholder array with a very large number of views in the negative direction (e.g. 10000). Then in your ForEach, check the index to see whether it exists in the real/non placeholder array.
If so -> the real view
If not -> a cheap view (e.g. Rectangle() with the right background colour and a height of 1).
LazyVStack {
    ForEach(placeholderIndices, id: \.self) { index in
        if indices.contains(index) {
            REAL VIEW
        } else {
            Rectangle()
                .fill(Color.bg)
                .frame(height: 0)
        }
    }
}

When you expand your view, placeholderIndices stays the same; only the 'real' indices change
Answer: I faced the same problem, but decided to take another way to solve it by simply saving the id of the top element (I'm inserting items to the top) to @State before fetching a new pack of items. Maybe it could help someone in the future :)
@State private var lastId = -1

ScrollView {
    ScrollViewReader { value in
        LazyVStack {

            ForEach(Array(items.enumerated()), id: \.element) { index, item in

                Element
                    .id(item.id)
                    .onAppear {
                       if (items.first == message) {
                          lastId = item.id
                          doFetch()
                       }
                    }

            }
            // listening to the changes in items list (the one I update) p.s. I have items in the viewmodel
            .onChange(of: items, perform: { new in
                // on first fetch I scroll to the bottom
                if (lastId == -1) {
                    value.scrollTo(items.last?.id ?? 0)
                } else {
                    // on any next I scroll to the last saved id
                    value.scrollTo(self.lastId)
                }
            })
        }
    }
}


Selenium Java - Webpage Dialog - Close Dialog and Quit (Only if it is displayed)

Question: I have a doubt with a Webpage Dialog:
The situation is the next: I try to log in a login page with wrong credentials, so I use any data in the login page. With this, is displayed a Webpage Dialog telling that the username or password is invalid.
This message is a Webpage Dialog, so I'm using the next code to close it:
Robot robot = null;

try {
    robot = new Robot();
    Thread.sleep(3000);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
} catch (AWTException e) {
    e.printStackTrace();
}

This is working, but when I put a condition like the next:
try {
    robot = new Robot();
    Thread.sleep(3000);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
} catch (AWTException e) {
    e.printStackTrace();
} finally{
    driver.quit();
}

This is not working any when I move the driver.quit(); to any position in the code.
I just want to close the driver when this Webpage Dialog is present, just in this situation.
Could anybody help me?
Answer: if you want to close the driver only when Webpage Dialog is present, you should write driver.quit(); in the end of try block.
try {
    robot = new Robot();
    Thread.sleep(3000);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
    driver.quit();
} catch (AWTException e) {
    e.printStackTrace();
}

Comment: When the password is invalid the river.quit(); at that point of the code is working, but when the password is OK, the system still closing the driver.
Comment: 1) are you deleted finally block? 2) if login-pass is good is  Webpage Dialog is present?
Comment: I deleted the finnaly block, because it always closes the driver with or without the display of the Webpage Dialog. If the login is valid the Webpage is not present anymore.
Comment: i understand you. 1) you can don't use robot, but try to use `Alert alert = webDriver.switchTo().alert(); alert.accept();` 2) if  first will not work you can make some that will understand have you a Webpage Dialog, if yes make Robot clicks and then driver.quit();. Now your code make Robot clicks in all cases/
Comment: Actually it doesn't work, because this is not an alert, but a Webpage Dialog.


CORS Error: Spring Boot Multiple WebSecurityConfigurerAdapter

Question: I have multiple WebSecurityConfigurerAdapter in my code:
@Configuration
@Order(1)
public class BoardSecurityConf extends WebSecurityConfigurerAdapter {
    private final X509BoardDetailsService x509BoardDetailsService;

    public BoardSecurityConf(X509BoardDetailsService x509BoardDetailsService) {
        this.x509BoardDetailsService = x509BoardDetailsService;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers("/board/**")
                .and()
                .authorizeRequests()
                .antMatchers("/board/all")
                .authenticated()
                .anyRequest()
                .permitAll()
                .and()
                .x509()
                .subjectPrincipalRegex("CN=(.*?)(?:,|$)")
                .userDetailsService(x509BoardDetailsService);
    }
}

@Configuration
@Order(2)
public class UserSecurityConf extends WebSecurityConfigurerAdapter {

    private final JwtRequestFilter jwtRequestFilter;
    private final JwtUserDetailsService jwtUserDetailsService;

    public UserSecurityConf(JwtRequestFilter jwtRequestFilter, JwtUserDetailsService jwtUserDetailsService) {
        this.jwtRequestFilter = jwtRequestFilter;
        this.jwtUserDetailsService = jwtUserDetailsService;
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers("/user/**")
                .and()
                .authorizeRequests()
                .antMatchers("/user/authenticate")
                .permitAll()
                .antMatchers(HttpMethod.POST, "/user")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint())
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint() {
        return new JwtAuthenticationEntryPoint();
    }
}

@EnableWebSecurity
@Order(3)
public class SecurityConf extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .cors().configurationSource(corsConfigurationSource())
                .and()
                .csrf()
                .disable();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Collections.singletonList("*"));
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

When I access my site from an ajax request I get:
Access to XMLHttpRequest at 'http://localhost:8080/user/authenticate' from origin 'http://localhost:8082' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I think I have some missconfiguration in my WebSecurityConfigurerAdapters. Already checked Spring documentation but coult not find anything about cors and mutltiple WebSecurityConfigurerAdapter configurations
@EDIT:
Now I get this exception:

java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
    at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:473) ~[spring-web-5.3.16.jar:5.3.16]
    at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:532) ~[spring-webmvc-5.3.16.jar:5.3.16]
    at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1261) ~[spring-webmvc-5.3.16.jar:5.3.16]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1043) ~[spring-webmvc-5.3.16.jar:5.3.16]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.16.jar:5.3.16]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.16.jar:5.3.16]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.16.jar:5.3.16]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) ~[tomcat-embed-core-9.0.58.jar:4.0.FR]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.16.jar:5.3.16]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.58.jar:4.0.FR]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.58.jar:9.0.58]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.58.jar:9.0.58]

Comment: Does this answer your question? [CORS issue - No 'Access-Control-Allow-Origin' header is present on the requested resource](https://stackoverflow.com/questions/42016126/cors-issue-no-access-control-allow-origin-header-is-present-on-the-requested)
Comment: You didn't configure CORS for `http://localhost:8080/user/authenticate`, you only configured it for other URLs than `/board/**` and `/user/**`.
Answer: I fixed the issue. Apparently the libary SockJS that I am using as STOMP Client sets the withCredentials flag to true (see Issue) in their XHR. When this flag is set you are not allowed to use a wildcard as AllowedOrigin on Cors.
Therefore I changed:
@Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Collections.singletonList("*"));
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

to this:
@Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8082", "https://localhost:8082"));
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

I also added .cors(withDefaults()) to each WebSecurityConfigurerAdapter which automatically uses my bean from corsConfigurationSource() see here


Closure of a subset of a subspace of a topological space

Question: Let $X$ be a topological space.
Let $Y$ be a subspace of $X$.
Let $T$ be a subset of $Y$.
Let $\overline T$ be the closure of $T$ in $X$.
Then $Y \cap \overline T$ is the closure of $T$ in $Y$?.
Answer: Hint: Use the characterization of the closure of $T$ in $X$ as
$$\overline{T}=\bigcap_{\substack{\text{closed}\, C\,\subseteq X\\ C\,\supseteq T}} C$$
together with the definition of the subspace topology on $Y$ to prove that the statement is true, i.e. that the closure of $T$ in $Y$ is $\overline{T}\cap Y$.
Comment: Basically this is a full proof ...
Comment: Please write a full proof. Then I will accept it.
Answer: Suppose $x$ is in $\overline{T}^{(Y)}$, the closure of $T$ in $Y$. This means in particular that $x \in Y$, obviously. If $O$ is an open subset of $X$ that contains $x$, then $O \cap Y$ is an open subset of $Y$ that contains $x$ and so $(O \cap Y) \cap T \neq \emptyset$, so in particular $O \cap T \neq \emptyset$. Hence every open neighbourhood (in $X$) of $x$ intersects $T$, so $x \in \overline{T}$. So $\overline{T}^{(Y)} \subset Y \cap \overline{T}$.
The other implication is also not too hard: suppose $x$ is in $Y \cap \overline{T}$. Let $O$ be any open neighbourhood of $x$ in $Y$. By the definition of the subspace topology this means that $O = U \cap Y$ for some open subset $U$ of $X$. As $x \in \overline{T}$, $U$ intersects $T$, so (recall that $T \subset Y$): $\emptyset \neq U \cap T = U \cap (T \cap Y) = (U \cap Y)  \cap T = O \cap T$. So we have shown that every open neighbourhood (in $Y$) of $x$ intersects $T$, so $Y \cap \overline{T} \subset \overline{T}^{(Y)}$.
So we have the required equality.


R/exams d2l multiple choice question doesn't select correct answer

Question: I use the following to create a D2L exam from the "capital.Rmd" example (I converted the question to schoice)
exams2blackboard("capitals.Rmd", n =3,  name = "testquiz" )
After I upload the testquiz.zip file, I notice that the correct answer must be manually chosen on the D2L platform.
I was wondering if there is a workaround.
Many Thanks,
Umut
Comment: There have been some recent changes in `exams2blackboard` which may have affected the behavior when importing into D2L. Did you try this with the current CRAN release version of R/exams (2.3-6) or the current development version on R-Forge (2.4-0)? Do both lead to the same problems in D2L? The R-Forge version can be installed via: `install.packages("exams", repos = "http://R-Forge.R-project.org")`
Comment: I tried it with both versions. Same behaviour.
Comment: OK, thanks for checking. I'm not sure how to proceed, does D2L have an option to re-export the exercise in (zipped) XML format? If so: You could try to import a question, edit it in D2L by manually choosing the correct answer, and then re-export the (zipped) XML. Maybe that will tell us which XML tag is missing or needs to be modified.
Comment: Thank you. I will check if tests are exportable to XML. Another venue I was thinking of is CSV. D2L provides CSV templates. If R/exams could export to CSV it'd be very transparent what is going on.
Comment: I've written a prototype function for that. It works ok for simple text-based questions. However, for questions with more formatting (graphics, math, code) it did not. I'm collecting all of this in a new answer now. This will not be a complete answer to your problem but at least provide you with some hints where to continue...
Answer: If you want the correct solution to be selected, do not use the Import option from the Question Library or from the Quiz itself. Use the Import/Export/Copy Components under the Course Admin tab.
If you import the questions through the following steps, BrightSpace correctly picks the right solution. It's a bit longer but seems to correctly choose the solution.
Under the Course Admin tab of your course, go to

'Import/Export/Copy Components' -> 'Import Components' -> Start -> (drag and drop the ZIP file)

Click 'Advanced Options…'

This step will take a few minutes for large files; if you do not click
Advanced Options, then the import will automatically import the
questions into the 'Question Library' and will generate a Quiz with the
imported questions; you do not want this.

-> Continue -> Continue -> at this point choose 'Question Library' from the section 'Select Components to Import'

I would not choose 'Quizzes' because it automatically creates a quiz
and makes it available to students. It has the unfortunate side-effect
of making ALL the questions available, which means all the versions of
various dynamic questions; this is not something we want.

-> Continue -> Continue. This stage takes a few minutes for large
imports.

Now the Questions are available in the Question Library and can be used to generate new quizzes. Each question has the correct answer selected already. This works for 'schoice' and 'mchoice' versions of questions. Currently, plots are not imported, though, still trying to figure out why.
Comment: Brilliant! This worked for me. Thank you. The downside is that it takes much longer than manually choosing the correct answer.
Comment: Hi Umut. This may take longer for 1 question, but when I imported 1200 questions for 1 midterm (60 questions, 20 iterations of each question), this is significantly faster.
Comment: Great! I really appreciate your help. This will make my life so much easier.
Comment: By the way, Umut. If you decide to use plots in your tests, I have found a workable solution as well. It relies on using the 'base64' option. Line that I use:

exams2blackboard(questions, n = iterations, edir = edir,
   name=name1, dir=dir, converter='pandoc-mathml',base64 = c("png", "rda"),verbose = T)

The 'base64' option replaces creation of files and folders and instead creates a plot as a base64-encoded vector. Check out some examples here:

https://community.brightspace.com/s/question/0D55W000001AfSw/importing-blackboard-quiz-questions-generated-via-rexams?t=1613230923582
Comment: Fantastic! I do use graphs. Thank you again.
Answer: This problem is new to me. In earlier versions of Brightspace/D2L the import of single-choice and multiple-choice exercises via exams2blackboard() worked well. Possibly, D2L changed in the meantime given that neither the current release version from CRAN nor the development version from R-Forge work for you.
D2L also supports other import formats and we did play around with some of these. See the following discussions in the R/exams forum on R-Forge:

https://R-Forge.R-project.org/forum/forum.php?thread_id=33404&forum_id=4377&group_id=1337

https://R-Forge.R-project.org/forum/forum.php?thread_id=33657&forum_id=4377&group_id=1337

Notably we tried to use the XML-based QTI 2.1 format that seems to be employed by D2L internally. However, D2L apparently uses a particular custom flavor of QTI 2.1. It should be possible to reverse engineer that and improve exams2qti21() correspondingly but so far (to the best of my knowledge) no one put the time and effort into this that would be needed.
For simple single/multiple choice questions a CSV-based exchange format can also be used. I have put together a very basic exams2d2l() function that was posted in the threads above and that I'm also including below. It can set up the CSV file for a single exercise like the capitals.Rmd exercise that you use above. For plain text exercises like that it seems to work well but not for more complex elements (graphics, code, math, etc.).
exams2d2l <- function(file, dir = ".", ## n = 1L, nsamp = NULL disabled for now
  name = NULL, quiet = TRUE, edir = NULL, tdir = NULL, sdir = NULL, verbose = FALSE,
  resolution = 100, width = 4, height = 4, svg = FALSE,
  encoding = "", converter = NULL, ...)
{
  ## for Rnw exercises use "ttm" converter otherwise "pandoc" converter
  if(any(tolower(tools::file_ext(unlist(file))) == "rmd")) {
    if(is.null(converter)) converter <- "pandoc"
  } else {
    if(is.null(converter)) converter <- "ttm"
  }

  ## output directory or display on the fly
  ## output name processing
  if(is.null(name)) name <- tools::file_path_sans_ext(basename(file))

  ## set up .html transformer and writer function
  htmltransform <- make_exercise_transform_html(converter = converter, ...)

  ## create exam with HTML text
  rval <- xexams(file,
    driver = list(sweave = list(quiet = quiet, pdf = FALSE, png = !svg, svg = svg,
      resolution = resolution, width = width, height = height, encoding = encoding),
      read = NULL, transform = htmltransform, write = NULL),
    dir = dir, edir = edir, tdir = tdir, sdir = sdir, verbose = verbose)

  ## currently: only a single exercise
  rval <- rval[[1L]][[1L]]

  ## put together CSV
  cleanup <- function(x) gsub('"', '""', paste(x, collapse = "\n"), fixed = TRUE)
  rval <- c(
    'NewQuestion,MC,,,',
    sprintf('ID,"%s",,,', cleanup(rval$metainfo$file)),
    sprintf('Title,"%s",,,', cleanup(rval$metainfo$name)),
    sprintf('QuestionText,"%s",,,', cleanup(rval$question)),
    sprintf('Points,%s,,,', if(is.null(rval$metainfo$points)) 1 else rval$metainfo$points),
    'Difficulty,1,,,',
    'Image,,,,',
    paste0('Option,', ifelse(rval$metainfo$solution, 100, 0), ',"', cleanup(rval$questionlist), '",,"', cleanup(rval$solutionlist), '"'),
    'Hint,,,,',
    sprintf('Feedback,"%s",,,', cleanup(rval$solution))
  )
  writeLines(rval, file.path(dir, paste0(name, ".csv")))
  invisible(rval)
}

Comment: Thank you so much. `exams2d2l()` selects the correct answer, although now all answers appear in each answer option. I will dig into your code and report back if I can make it work for me. Thank you again.


Simplifying trig expression cos and sin.

Question: I'm reading a solution right now, and I am stuck.
$$\frac{\cos\left(\frac{\theta}{2}\right) - \cos\left(n + \frac{1}{2}\right)\theta}{2} \sin\left(\frac{\theta}{2}\right) =\frac{\sin(n\frac{\theta}{2}))\sin\left(\left[n+1\right]\frac{\theta}{2}\right)}{\sin\left(\frac{\theta}{2}\right)}$$
How could these two equations be equal.
Comment: Do you have your own thought?
Comment: @therexists you still should post what you have tried, other wise you might end up with hints like: "use trigonometrical properties", and also, whay did you tag this in abstract algebra?
Comment: @Dre You edited my post wrongly.... sin(theta/2) should be in the denominator of LHS.
Comment: I also think $\cos(n+1/2)\theta$ in the LHS should be actually $\cos\{(n+1)\theta/2\}$. Because then the RHS will be exactly equal to the LHS.
Comment: @Shuchang I posted this because I don't have any thought.
Comment: @AnaGalois Because this problem is from abstract algebra book. I will edit to post what I have tried now.
Comment: @therexists My apologies. I am unable to fix that, but someone else can.
Comment: Is the problem correct?? I think there are typos.
Comment: @AbishankaSaha Not yet. The only thing needs to be corrected is sin(theta/2) should be in the denominator of left hand side. So denominator of LHS is 2*sin(theta/2)
Comment: I wish I can post my work, but I don't have idea for this...
Comment: @therexists Is this your original problem?: $${\cos (\frac {\theta}{2}) - \cos(n+(\frac12\theta)) \over 2\sin(\frac {\theta}{2})}= {\sin(n\frac{\theta}{2})\sin ((n+1) \frac {\theta}{2})) \over \sin(\frac {\theta}{2})}$$
Answer: Not sure about the accuracy/format of the problem as
using $\displaystyle \cos C-\cos D=2\sin\frac{C+D}2\sin\frac{D-C}2$
$$\cos\frac\theta2-\cos\left(n+\frac12\right)\theta=2\sin\frac{n\theta}2\sin\frac{(n+1)\theta}2 $$


Is a normed $\mathbb R $ vectorspace complete in general?

Question: I would like to find out if a normed $\mathbb R$-Vectorspace is complete in general. Or even in a more general case if a normed $K$-Vectorpace, where K is a close field is complete?
I somehow think that this is not true, however I am not able to construct a counter example since by intuition the abelian group over $\mathbb R$ must be at least as "large" as $\mathbb R$ since otherwise i dont see how the abelian group will be closed under multiplication by elements of $\mathbb R$.
I would be happy about some hints, thanks!
It would be even sufficent if someone could tell me if the statement is true or not such that I could work on a prove.
Comment: FInite dimensional normed spaces over $\mathbb{R}$ (or $\mathbb{C}$) are complete, because all norms over them are equivalent; see [Understanding of the theorem that all norms are equivalent in finite dimensional spaces](http://math.stackexchange.com/questions/57686/). Completeness may fail for infinite dimensional space.
Comment: @egreg Thanks for the comment, I just realised that the question was actually quite stupid since in my functionalanlysis course we are just considering $\mathbb R$ and $\mathbb C$ Vectorspaces. And assuming that every VS over those two fields was complete would make all proves that show that some space is a Banach-Space sensless :D
Answer: The answer to the first question is no. Consider a space of continuous functions on the interval $[0,1]$ with the $L^1$-norm. It's a normed vector space, but it's not complete.
Comment: @Thorben you are welcome!


Optimizing queries on a relational DB where entities are full json objects and with another table with entity-value design

Question: In my database, entities are stored as full JSON formatted objects. There is another table for properties of entities. Each property of an entity is stored its own row. In a sense, the second table holds properties of JSON entity.
I'm aware that this is a terrible design violating normal forms and also it is an anti-pattern called Entity-Attribute-Value.
For a simple query, I must make a number of joins and it is terrible for performance.
I wonder if there is a way for optimizing queries by reducing number of joins?
Solutions out of question since there are lots of constraints:

normalizing tables
migrating to a nosql engine

By the way, the database engine is MySQL 5.6.21. If I update the mysql db to another version of mysql, can I create queries on JSON objects directly?
Thank you in advance.
Answer: MySQL 5.7.8 supports JSON as a datatype. Without more details, it's hard to see if that will help you - but it will almost certainly be faster than the EAV queries you currently have to do.


Validar EditText dentro do AlertDialog

Question: Tenho um AlertDialog e dentro dele tenho um EditText e preciso validar e depois que validar executar o método enviarEmail(), como faço?
Meu AlertDialog :
AlertDialog.Builder caixaDialog = new AlertDialog.Builder(getContext());
            caixaDialog.setView(vView)
                    .setCancelable(false)
                    .setPositiveButton("Enviar", null)
                    .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                            // Habilitar todos os botões
                            btnSatisfacaoRuim.setBackgroundResource(R.drawable.img_satisfacao_ruim);
                            btnSatisfacaoBom.setBackgroundResource(R.drawable.img_satisfacao_bom);
                            btnSatisfacaoNormal.setBackgroundResource(R.drawable.img_satisfacao_normal);
                            llSatisfacao.setVisibility(View.INVISIBLE);

                        }
                    });

            final AlertDialog mDialog = caixaDialog.create();
            mDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialog) {
                    Button positive = mDialog.getButton(AlertDialog.BUTTON_POSITIVE);
                    positive.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (edtMensagemSatEmail.getText().length() == 0) {
                                edtMensagemSatEmail.setError("Campo obrigatório");
                                edtMensagemSatEmail.setFocusable(true);
                                edtMensagemSatEmail.requestFocus();
                            } else {
                                // Barra de progresso
                                progresso = new ProgressDialog(getContext());
                                progresso.setCancelable(false);
                                progresso.setMessage("Processando...");
                                progresso.show();

                                // Metodo de envio
                                inserirWEBService();
                                enviarEmail();
                                mDialog.dismiss();
                            }
                            getFragmentManager().beginTransaction().replace(R.id.content_principal, new avalieViagem()).addToBackStack(null).commit();
                        }
                    });
                }
            });

            mDialog.show();

Meu XML do Dialog:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="#ffffff"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="Linha: "
            android:textColor="#548ddf"
            android:textSize="18dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/txt_linha_sat_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="linha"
            android:textColor="#548ddf"
            android:textSize="18dp"
            android:textStyle="bold"
            app:layout_constraintStart_toEndOf="@+id/textView"
            app:layout_constraintTop_toTopOf="parent" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="Horário: "
            android:textColor="#548ddf"
            android:textSize="18dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView" />

        <TextView
            android:id="@+id/txt_horario_sat_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="horario"
            android:textColor="#548ddf"
            android:textSize="18dp"
            android:textStyle="bold"
            app:layout_constraintStart_toEndOf="@+id/textView1"
            app:layout_constraintTop_toBottomOf="@+id/txt_linha_sat_email" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/img_sat_email"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_marginTop="5dp"
            app:srcCompat="@drawable/img_satisfacao_bom_off"
            tools:layout_editor_absoluteX="10dp"
            tools:layout_editor_absoluteY="69dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <TextView
            android:id="@+id/txt_satisfacao_sat_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="satisfacao"
            android:textColor="#548ddf"
            android:textSize="18dp"
            android:textStyle="bold"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/img_sat_email" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="Deixe seu Comentário:"
            android:textColor="#548ddf"
            android:textSize="18dp" />

        <EditText
            android:id="@+id/txt_Mensagem_sat_email"
            android:layout_width="250dp"
            android:layout_height="100dp"
            android:layout_marginTop="0dp"
            android:background="#d8d6d3"
            android:gravity="top|left"
            android:hint="Comente aqui"
            android:inputType="textMultiLine"
            android:lines="6"
            android:overScrollMode="always"
            android:scrollbarStyle="insideInset"
            android:scrollbars="vertical"
            android:scrollHorizontally="false"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />

    </LinearLayout>

</LinearLayout>

Comment: Qual o problema com o seu código?
Comment: Ele não está validando o `EditText` quando clico no Enviar do `AlertDialog`.
Comment: txtMensagemSatEmail é um TextView ta querendo validar um TextView? Ta validando algo baseado num TextView ?
Comment: Ele é um `EditText`, foi apenas a nome da variável.
Comment: Não bastaria por um `return` no fim do código dentro do `if`?
Comment: Coloquei, apenas fechou o `AlertDialog`.
Comment: Se quer manter o dialog aberto no caso dos dados introduzidos não serem válidos veja esta [resposta](https://pt.stackoverflow.com/a/63039/2541).
Comment: Não consegui, no 2º passo, eu travo, na parte de declarar o `button`, não existe `setButton`.
Answer: Na criacao da instancia voce esta colocando edtMensagemSatEmail = (TextView) e nao edtMensagemSatEmail = (EditText )
e coloca o else
if (edtMensagemSatEmail.getText().length() == 0) {
                        edtMensagemSatEmail.setError("Campo obrigatório");
                        edtMensagemSatEmail.setFocusable(true);
                        edtMensagemSatEmail.requestFocus();
                    }
else
    enviarEmail();

provavelmente ele valida sim, mas logo em seguida vai para o método enviarEmail(); e la nele você deve ter colocado alguma rotina para fechar, se colocar no else ele só vai para o enviarEmail() se passar na validação.
Comment: mesmo com `EditText` não está validando, quando clico em enviar passa direto.
Comment: editei a resposta
Comment: acho que faltava o else, testa de novo
Comment: Certo, ele não envia. Só que ele fecha o `AlertDialog`, queria que ele ficasse com o `Dialog` aberto e setasse no campo `edtMensagemSatEmail.setError("Campo obrigatório");`
Answer: Olá, para tratar um evento de click do botão no alertdialog, sem que ele feche, chame o método setOnShowListener (new DialogInterface.OnShowLister);
Nesse método você recupera o botão positive para tratar o evento no click dentro do método onShow(), segue o exemplo para o seu código:
View vView = getLayoutInflater().inflate(R.layout.envio_satisfacao_ruim, null);
        edtMensagemSatEmail = (EditText) vView.findViewById(R.id.edt_Mensagem_sat_email);
        edtMensagemSatEmail.setFocusable(true);

AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Seu Titulo")
            .setView( vView)
            .setCancelable(false)
            .setPositiveButton("Enviar", null)
            .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    final AlertDialog mDialog = builder.create();
    //Aqui você trata o click do button positive sem que o alertdialog feche em caso de convergência
    mDialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(final DialogInterface dialog) {
            Button postive = mDialog.getButton(AlertDialog.BUTTON_POSITIVE);
            postive.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //aqui você trata o evento
                    if (edtMensagemSatEmail.getText().length() == 0) {
                        edtMensagemSatEmail.setError("Campo obrigatório");
                        edtMensagemSatEmail.setFocusable(true);
                        edtMensagemSatEmail.requestFocus();
                    } else {
                        //Como ao clicar no botão positivo a condição é verificada
                        //caso esteja tudo certo com o edittext, então chama o seu método
                        //enviar email
                        enviarEmail();
                        //No final como já completou a condição pode dar dismiss
                        //no alertdialog, pois está tudo ok
                        dialog.dismiss();

                    }

                }
            });
        }
    });
    mDialog.show();

Obs: Eu não testei, mas tenho certeza que está funcionando pra sua necessidade. Funcionando ou não, dá um feedback. Abraço
Comment: Ao invés de usar os botões do próprio `AlertDialog`, criei 2 botões no layout, e funcionou a validação, vlw.
Comment: olá, ele rodou, mas ainda continua fechando o alerta se não informar nada no `EditText`, editei e postei o meu atualizado pelo seu.
Comment: Mesmo informando no `EditText` Está fechando o `Dialog` sem fazer a ação
Comment: @AriMelo testei e tá funcionando sim, siga fielmente a minha resposta que dará certo. Pelo código que você editou no final do alertdialog vc tá chamando:

`caixaDialog.setView(vView);
            AlertDialog dialog = caixaDialog.create();
            dialog.show();`

Ou seja, está recriando o alerta sem os métodos de onShow.  Então remova essa parte e coloque apenas: `mDialog.show();`
Comment: Só me corrigindo, ali no final do alertdialog pelo seu código, você está criando uma outra view pro dialog, e não criando um novo alerta. Isso anula os métodos que está fazendo o tratamento do evento de click.
Comment: Não funcionou, quando abre o `Dialog`, mostra apenas os botões cancelar e enviar mais nada, como se o corpo sumisse, editei novamente do jeito que está o projeto.
Comment: tem como colocar o xml do seu alerta? Pelo código deveria estar funcionando. Testei esse meu em uma api 28 e tá ok. Única diferença no seu código é no método do botão Cancel, coloque o dialog.cancel, no final do método, pois do jeito que está os métodos abaixo não é executado. E no envento de click do botão positivo ao invés de mDialog.dismiss(); é dialog.dismiss()
Comment: Postado no Início.
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/94075/discussion-between-murillo-comino-and-ari-melo).
Comment: Que bom brother, mas estranho desse jeito com os botões do alertdialog não ir.

Validar EditText dentro do AlertDialog


Regarding vector spaces

Question: If $A$ and $B$ are $n$ dimensional vector spaces

Is $A+B$ a vector space?

Is $A$ and $B$ a vector space?
Comment: What do you mean $A+B$? Direct sum? What about "$A$ and $B$"?
Answer: The set $\{(w,v)\mid w\in A, v\in B\}$ is a vector space of dimension $2n$.
Hereafter, suppose that $A$ and $B$ are two subspaces of a third vector space.
The set $\{w+v\mid w\in A, v\in B\}$ is also a vector space, but its dimension can vary depending on how much $A$ and $B$ overlap, but for sure its dimension is at least $n$.
Finally, $A\cap B$ is also a vector space, and again its dimension can vary, but its dimension can be no more than $n$. This was the best interpretation of "A and B" in your post that I could see. However, the intersection does not make any sense unless $A$ and $B$ are subsets of a common vector space.
Answer: yes
$\forall \alpha_1= ,\alpha_2 \in A+B$and for each $c\in F$ exist $a_1,a_2\in A$ and $b_1,b_2\in B$ such that $\alpha_1=a_1+b_1$and$\alpha_2=a_2+b_2$
$c\alpha_1+\alpha_2=c(a_1+b_1)+(a_2+b_2)=ca_1+a_2+cb_1+b_2\in A+B$
($ca_1+a_2\in A$ $cb_1+b_2\in B$ becuase A and B are vector spaces.)
$\forall \alpha_1$ and $\alpha_2 \in A\cap B$ and $c\in F$
$\alpha_1,\alpha_2\in A$ so $c\alpha_1+\alpha_2 \in A$
$\alpha_1,\alpha_2\in B$ so $c\alpha_1+\alpha_2 \in B$
so : $c\alpha_1+\alpha_2 \in A\cap B$

Regarding vector spaces


httpd logs show different time then machine

Question: I am having an issue with my webserver, in that the logs that apache is writing have a different timestamp then my machine. This is causing some issues with other services parsing this file..
$firstname.lastname@example.com:/logs/httpd/example.com# date
Thu Nov 10 10:56:12 EST 2016

$email@example.com:/logs/httpd/example.com# tail -n 1 whatismyip.insecure_access.log
22.214.171.124 - - [10/Nov/2016:09:56:01 -0600] "GET / HTTP/1.1" 200 11 "-" "curl/7.29.0"
                                       /\ EST Should be -0500

I am unsure what to change next:
$firstname.lastname@example.com:/logs/httpd/example.com# ll /etc/localtime
lrwxrwxrwx. 1 root root 38 Oct 28  2015 /etc/localtime -> ../usr/share/zoneinfo/America/New_York

$email@example.com:/etc/httpd# grep "TZ" /etc/httpd/* -r
/etc/httpd/conf/httpd.conf:SetEnv TZ America/New_York
Binary file /etc/httpd/modules/mod_wsgi.so matches
Binary file /etc/httpd/modules/mod_substitute.so matches
Binary file /etc/httpd/modules/libphp5.so matches

How can I fix the logged timestamp to be in sync with my local time?
Comment: Check your other conf files too
Comment: edited, just ran a recursive grep against all httpd conf files, and nothing.
Answer: If the webserver is running with php you can also have a look in:
/etc/php.ini
Add time zone by adding or modifying a line like:
date.timezone="America/New_York"
restart apache
/etc/init.d/httpd restart


How do you get a Drupal webform in Gatsby (React)

Question: I am planning to build a Drupal 8 site fully decoupled using Gatsby (React). So I will use Drupal only to structure (Content types, paragraphs), enter and update all the content and data and use React (and Gatsby) for the frontend.
The website also needs a (simple) form. I will use the webform module for this.
But how do you get a Drupal form in Gatsby (React) and after submitting send all completed fields to the database?
Answer: If you are looking for an extremely simple form, consider hosting your Gatsby site (for free) on Netlify and use Netlify Forms. Add any fields to your form (Captcha is a good idea too) and just add the Netlify tag to the form itself and Netlify will store it for you in their admin panel.
<form name="contact" method="POST" data-netlify="true">

Cheack out https://www.netlify.com/docs/form-handling/
Answer: You can access a Webform from React via jsonapi by addding the Webform to a Webform node.
In "Add content" select content type "Webform", then select the name of the form from the dropdown below the WYSIWYG editor, publish the node and record the ID.
The request will look something like this:
http://dev.local.com/jsonapi/node/webform?filter[nodeID][condition][path]=drupal_internal__nid&filter[nodeID][condition][value]=177007

Answer: There's a Gatsby plugin called Gatsby Drupal Webform that makes it possible to expose forms made using Webform module in Drupal 8. You will also need module Gatsby Webform Backend as dependency in Drupal.
Answer: Crazy :) Sounds like an early adopter approach. Gatsby is great for static content but when it comes to dynamic (including forms, submissions, error validation) then good luck as we won't see you for a loooong loooing time until you master secret JS JEDI knowledge... see you in a few years :)