Swift watchOS 2 - CMSensorDataList

Question: Short: I don't know how to extract the CMRecordedAccelerometerData from the CMSensorDataList after getting one from the CMSensorRecorder.
Apple isn't providing any documentation, yet.
Maybe someone has a hint for me? ;)
func startMovementDetection(){
    var accDataList = self.cmSensorRecorder!.accelerometerDataFrom(self.startDate, to: NSDate()) as CMSensorDataList

    CMRecordedAccelerometerData() //that's the class i want to extract from CMSensorDataList
}

Okay, problem solved with this one here: NSFastEnumeration in Swift
With Swift 3.0 it changes to:
extension CMSensorDataList: Sequence {
    public func makeIterator() -> NSFastEnumerationIterator {
        return NSFastEnumerationIterator(self)
    }
}

Comment: do you have any code snippet
Answer: Here's a Swift 4 approach. First, you'll need to make CMSensorDataList conform to Sequence by means of an extension:
extension CMSensorDataList: Sequence {
    public typealias Iterator = NSFastEnumerationIterator
    public func makeIterator() -> NSFastEnumerationIterator {
        return NSFastEnumerationIterator(self)
    }
}

Now you can iterate over CMSensorDataList to obtain CMRecordedAccelerometerData instances, each consisting of a timestamp and an acceleration:
let rec = CMSensorRecorder() // and d1 and d2 are Dates
if let list = rec.accelerometerData(from: d1, to: d2) {
    for datum in list {
        if let accdatum = datum as? CMRecordedAccelerometerData {
            let accel = accdatum.acceleration
            let t = accdatum.timestamp
            // do something with data here
        }
    }
}

Answer: //First make the extension tu use enumerate in the for-in loop
extension CMSensorDataList: SequenceType {
    public func generate() -> NSFastGenerator {
        return NSFastGenerator(self)
    }
}

//Now you can query the recorded data
func printData(){
    let date = NSDate()
    let recorder = CMSensorRecorder()
    let sensorData: CMSensorDataList = recorder.accelerometerDataFromDate(initialDate!, toDate: date)!

    for (index, data) in sensorData.enumerate() {
        print(index, data)
    }
}

Answer: Marcus's answer in Swift 4:
//First make the extension to use enumerate in the for-in loop
extension CMSensorDataList: Sequence {
    public typealias Iterator = NSFastEnumerationIterator

    public func makeIterator() -> NSFastEnumerationIterator {
        return NSFastEnumerationIterator(self)
    }
}

//Now you can query the recorded data
func printData(){
    let date = Date()
    let recorder = CMSensorRecorder()
      let accelerometerData = recorder.accelerometerData(from: startDate, to: endDate)

     for (index, data) in (accelerometerData?.enumerated())! {
                    print(index, data)
      }
}

Comment: No SequenceType in Swift 4. This doesn't compile.
Comment: It's just Sequence, see amended answer

Swift watchOS 2 - CMSensorDataList


how to set connection timeout for mongodb thru node.js

Question: The following is the connection string and options i'm using from node.js to connect to mongodb. My web application keeps re-trying and never posts back if the mongodb server is down. Where do I set the connection timeout so I can say db server is down when it is? (The following code works perfectly when the mongo server is up).
<code>(function(database) {
    var mongodb = require("mongodb");
    database.ObjectID = mongodb.ObjectID;
    var mongoUrl = "mongodb://localhost:27017/mydb";
    var dbconn = null;
    database.getDBConn = function(next){
        if(dbconn){ next(null, dbconn); return; } //already connected: return dbconn
        mongodb.MongoClient.connect(mongoUrl,
        {server: {socketOptions: {connectTimeoutMS: 500}}}, function(err, database){
            if(err){ next(err, null); return; } //connection fail: return error
            dbconn = {db: database,
                      movies: database.collection("movie") };
            next(null, dbconn); //connection success: return dbconn
        });
    }

})(module.exports);
</code>
Comment: I'm still looking for help. Thanks for taking a look.
Answer: Looking at http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html I would say use

    MongoClient.prototype.close

method to check if the connection is closed.If the connection is closed then emit a notification that the database server is down.


Shopify Orders API response: Discount missing with orders line item

Question: We are having an issue with Shopify order API, while downloading orders with their items, we are not getting discounted line item amount.
An orders is having discounted item "Discount (shoe sale)" with amount -67.50. This amount is not getting with orders from Shopify. There is no node available in orders (also in product) response that returns orders line item discount.
PFA,
Answer: This is a known and very frustrating problem. I have asked Shopify to fix this oversight for 2 years now, about 30 times, to no avail. You are SOL.
You cannot do proper accounting with the Shopify Order API at this time. Perhaps in the future they will fix it. For now, you have to work without knowing the discounts applied per line item. If there is only one line item, of course you can work it backwards... but if there is more than one, you're screwed.


Azure notification hub best practice in social network scenario

Question: I am wondering which is the best practice in Azure notification hub to send push notifications to a couple of certain users (e.g. about followed activities).
Imagine, users can follow other users and these followers should be notified about new activities (facebook, twitter principle).
How to send these notifications in detail, there are two options I am thinking about, but which one is the best?
1) looping through all desired users by code and calling SendTemplateNotificationAsync for each individual user?
foreach(user in allSubscribedUsers) {
    tags.Add("userid:" + userId);
    await hub.SendTemplateNotificationAsync(notification, tags);
}

2) Having special tags a user can register to
registration.Tags = new HashSet<string>(deviceUpdate.Tags);

// the current user follows other users with the ids 1,2 and 3
registration.Tags.Add("followerUserid:1");
registration.Tags.Add("followerUserid:2");
registration.Tags.Add("followerUserid:3");
...
// an acivity by user with id 2 is happen
// send a push notification to all users who follow the user with id 2
tags.Add("followerUserid:2");
await hub.SendTemplateNotificationAsync(notification, tags);

It's possible that a user follows up to 1.000 other users, so he needs to register 1.000 of the followerUserId-Tag.
Is the second approach a reliable solution?
Are there any tag limitations a user can register to?
Answer: This answer describes tag limits on NH. There is a limit of 60 tags per registration, so you won't be able to use your second approach if you want to allow 1k followers.
You can use the SendNotificationAsync(Notification, IEnumerable<String>) overload of the method to "batch" calls in your first scenario in groups of 20 max to save on the number of calls you make to the service.
Comment: This is a bit confusing, but there're many aspects to tag limits. The number of _tags per device_ is 60. But the number of _tags overall_ is capped at 3000. However, devices with <5 tags are excluded from the cap. So in your case, it would mean that if every user has 5 or fewer tags associated with them, you won't hit the 3k cap no matter how many users you have.
Comment: Thanks for your answer! But the next following post in the linked thread, says, that MS had eliminate the tag limit?


Normality, and when to use t-test vs. Mann-Whitney U-test?

Question: I am looking for a few rules of thumb of when to determine that my data is 'normal enough' to use a t-test vs. a Mann-Whitney U-test.
From what I have read, most real world data sets are non-normal, and when sample sizes are large, tests including the Shaprio-Wilk will always reject the null hypothesis. I also know that you can look at the Q-Q plot to determine normality, although this seems to be more of a guesstimate than a hard and fast normal vs. non-normal.
Just a few examples to comment on - would you say Q-Q 1 is normal? What about Q-Q 2?
Comment: Closely related: [How to choose between t-test or non-parametric test e.g. Wilcoxon in small samples?](http://stats.stackexchange.com/q/121852/)
Comment: Do you know how the reference lines were drawn in your software? Usually the line goes through the 25th & 75th percentile, but that doesn't seem to be the case here.
Comment: Thank you for the link above - very good read. I'm using SPSS, but I am not 100% sure how the software is choosing the line.
Comment: The idea that you *can* have "a hard and fast *normal vs non-normal*" is illusory. If you aren't in a position to say (e.g. from some *a priori* knowledge of the distribution shape, the sample size or both) "the t-test should be fine", you should not assume it. Deciding which test to do on the basis of the sample leaves neither test having its nominal properties, and the resulting overall properties are often substantially less useful than simply doing Mann-Whitney; if you have reason (a priori) to think that the tails are not too heavy & distribution not very skew, the t-test should be fine
Comment: If those plots are typical of your distribution shapes, it will matter little which test you choose. You have mild skewness, it won't harm the properties of the t very much (though I'd lean toward MW or a permutation test of means myself). If you use a $t$, make sure you allow for unequal variance (that is, do Welch or something along those lines --- and don't *test* for equal variances, just assume they're different).
Comment: **Updated links:** One can use the [Shapiro-Wilk test to test for *equivalence* to normality](https://alexisdinno.com/stata/tostswilk.txt), rather than difference from normality using the [**tost**](https://alexisdinno.com/stata/tost.html) package for Stata. Doing so and combining with the standard test for different from normality will permit one to distinguish between trivial and relevant difference from normality, as well as to conclude equivalence to normality.
Comment: @Alexis ... I have [moved the conversation to chat](https://chat.stackexchange.com/rooms/81023/discussion-on-question-by-user2416002-normality-and-when-to-use-t-test-vs-mann).
Answer: In general, the $t$-test is very robust.  Three assumptions are typically listed: independence, homoscedasticity, and normality.  The assumption that the residuals are normally distributed comes last and is least important.  If those two qq-plots are for the two groups that you want to compare, you probably have enough data and the data are normal enough, that you can use the $t$-test without fear.
Bear in mind that if the data are not truly normal, the Mann-Whitney $U$-test can be more powerful while maintaining your preferred type I error rate.  The $t$-test, on the other hand, would be less powerful and if not perfectly normal the type I error rate will diverge slightly from the specified level (just not enough to fuss over).  In that sense, if you are concerned it may be better to just use the Mann-Whitney as is explained in the linked thread.


Webform hours/time field

Question: How do you add a field where user can set hours when it's best to call for contacting. The Date field gives only days, months and years.
In this thread Webform: Time Field - Changing Variable Increments he states he has some time field for his Webform. But I can't track it down which module is that?
Answer: Webform module have time field by default.

Webform hours/time field


Display comments only for users with "administer comments" permission

Question: In hook_node_view_alter, I'm trying to restrict the display of comments to users who have the "administer comments" permission.
So far I have this but it is not working.
if (isset($build['comment'])) {
  if (!\Drupal::currentUser()->hasPermission('administer comments')) {
    $build['comment']['#access'] = FALSE;
  }
}

Answer: Solution below:
$build['comment']['#access'] = Drupal::currentUser()->hasPermission('administer comments');


Equation with Side Conditions

Question:
A company has two different types of trucks:
Type A has $20\,\text{m}^3$ space for goods which have to be cooled and $40\,\text{m}^3$ space for goods which do not have to be cooled.
Type B has $30\,\text{m}^3$ space for goods which have to be cooled and $30\,\text{m}^3$ space for goods which do not have to be cooled.
The company has to transport $300\,\text{m}^3$ of cooled and $400\,\text{m}^3$ of uncooled goods. The costs per km for trucks of type A is 30 Euro, the cost per km for type B is 40 Euro.
How many trucks of each type have to be used for achieving minimal total costs?

My ideas:
For the cooled food the equation would be: $20x+30y = 300$
For the uncooled food:  $40x + 30y = 400$
Additionally, the total price should be minimized, but how exactly?
Thanks!
Comment: I have added some more information to my answer. The solution is $(6,6)$, not $(5,7)$, as far as I can tell. This is a fairly difficult problem for high school.
Answer: The constraints should be inequalities. It may be OK to 'waste' space if the total cost is less.
The cost per km is $c(a,b) = 30a+40b$. The constraints are $20a+30b\ge300$, $40a+30b\ge400$.
Addendum: Something about this problem bothered me, so I revisited it.
This is a good problem in that it shows a potential 'pitfall' of rounding when solving a discrete problem by means of a continuous approximation. I quote pitfall because from a practical standpoint, a slightly non-optimal solution is not a huge problem.
It is a poor high school problem because, while the mathematics are not involved, it does require a little mathematical 'maturity'.
One can work through the continuous problem in the following way: Note that $c(a,b) = 30a+40b = \frac{7}{6} (20a+30b) + \frac{1}{6} (40a+30b) $, and given the constraints, we see that $c(a,b) \ge \frac{7}{6} (300) + \frac{1}{6} (400) = \frac{1250}{3} = 416 \frac{2}{3}$. Furthermore, by assuming both constraints are active, we get a two variable linear system which has a solution $c(5,\frac{20}{3}) = 416 \frac{2}{3}$. Hence this is a (in fact, the unique solution, but that is not relevant here) solution of the continuous problem.
However, we should not stop here. If $a,b$ are integers, we note that $10 \mid c(a,b)$, and so the above bound shows that a lower bound on cost, restricted to integers, must be $c(a,b) \ge 420$. So, the question is, can we find a solution that has cost 420?
The equation c(a,b) = 420 reduces to $3a+4b = 42$, or $a = 14-\frac{4}{3}b$, so we should look for pairs $(14-\frac{4}{3}b, b)$ that satisfy the constraints. Since $a$ must be an integer, and $\gcd(3,4) = 1$, we must have $b = 3 n$ for some integer $n$. Hence we look for solutions of the form $(14-4n, 3n)$.
The first constraint gives $2(14-4n) +3(3n) \ge 30$, or $ n \ge 2$.
The second constraint gives $4(14-4n) +3(3n) \ge 40$, or $ n \le \frac{16}{7}$. Since $n$ is an integer, we must have $n \le 2$.
Hence setting $n=2$, we see that $(6,6)$ meets the constraints, hence $(6,6)$ is the minimum cost solution. So, the answer is to use $6$ Type A truck and $6$ Type B truck.
Comment: Ok, and I think I would know how to solve this graphically, but how do I solve such a task analytically?
Comment: It is a linear program, which is not a precalculus tool, perhaps the solution is obvious graphically. Let me have a look...
Comment: well I am in highschool and in the task it tells us also to solve it analytically..>_>
Comment: thanks very much for your efforts.
Comment: You are very welcome. You could let your teacher know that it is perhaps more complicated than intended (the analytic part, at least).

Equation with Side Conditions


Comparing search engine configuration - paired or unpaired test?

Question: I have trouble of deciding whether I should go for paired or unpaired test in my case. Let's say that I need to evaluate the performance of two search engine configurations and check whether the performance of Configuration 2 is better than Configuration 1.
I can either:

compare the search performance on two independent queries samples and test whether the mean(metric for config 1) > mean(metric for config 2)
or
create one sample of queries, pass them through two configuration and compare the means of metrics as well

Is it actually true that I can approach this problem in two different ways ? If that's the case, what are the consequences of going for one option over the other ?
I'd be grateful for any guidance as to how to approach it
Answer: The paired design has greater statistical power, and should almost always be preferred where feasible. Unpaired designs are often necessary when collecting paired data would be difficult (e.g. it's too much of a time commitment for participants), but it's hard to imagine that's the case here.
Comment: Thanks for the answer. As far as I see, the paired test also requires smaller minimal sample for a test to be reliable. So am I correct in saying that in order to test my hypothesis correctly, it is more a matter of creating representative sample of queries rather than creating big enough one ?


css min-width issue

Question: .mainCoverWrapper {
    position: relative;
    min-width:312px;
    background:red
}

I'm trying to center a div with min-width of 312px and make it expand according to its dynamic content while keeping it centered.
Right now the min-with doesn't work at all because it needs a float. I can't use a float because I need the div centered on the page.
In other words, div starts out with margin auto with a width of 312px and expands with its added content while being centered. Is this possible?
Any help would be greatly appreciated.
Comment: Can't understand your question. So, the div starts with 312px. And then when you add content into your div, the div's width will expand accordingly?
Comment: @He Hui, Yes, correct.
Comment: If that's what you're asking, it's impossible with CSS. you'll need javascripts/jquery.
Comment: @He Hui, I supspected that. Javascript would be fine but I don't know how to do that either. Thanks for the help.
Comment: I added an answer that uses CSS and jquery
Answer: If you want the width to be fluid, your best bet is to set display: inline-block; on the to-be-centered element, and text-align: center; to the parent element.
See: CSS center display inline block?
Comment: yes, that would work but Firefox doesn't seem to render the inline-block properly. The div does not expand. Thanks.
Answer: http://jsfiddle.net/FVmvA/
Here's a working example of the parent to follow the width of the child, and the child will expand according to the text given in it.
.myCoverWrapper {
    border: 1px solid Peru;
    margin:auto;
    min-width: 200px;
    max-width: 100%;
    display: inline-block;
    background: red;
}

.test {
    height: 100px;
    margin: 10px;
    background: cyan;
}

This makes the parent div follow the width of the kid.
This however, will disallow you to "center" it. There's no way you can have both. This is because you cant center an image without knowing the width of the element.
The solution is to use jQuery, to add CSS in when necessary.
Here's an example. There's some bugs, but well, you have the general idea.
Comment: Also, set text-algin to the `test` div if you want to center align the text.
Comment: It worked but the javascript is not necessary. The answer below is also good. Thanks for the quick answer.

css min-width issue


quicksort for integers, segmentation fault in rand()

Question: I'm writing a quicksort algorithm for integers and I get a strange segfault error in srand functions. Here is the code from sort.h:
int distributePivot (int *a, int left, int pivot, int right) {
    int i, j;
    if (pivot != right)
        swapInt(&pivot, &right);
    i = left;
    j = right - 1;
    while (i < j) {
        while (i < j && a[i] <= a[right])
            i++;
        while (j > i && a[j] >= a[right])
            j--;
        if (i < j)
            swapInt(&a[i], &a[j]);
    }
    if (i < right)
        swapInt(&a[i], &a[right]);
    return i;
}

void intArrayQuickSort (int *a, int left, int right) {
    int pivot;
    if (left < right) {
            pivot = rand() % (right - left +1) + left;
        pivot = distributePivot(a, left, pivot, right);
        intArrayQuickSort (a, left, pivot -1);
        intArrayQuickSort (a, pivot, right);
    }
}

And here is the calling from sort-test.c:
    srand(time(NULL));
    intArrayQuickSort(temp, 0, n - 1);

Where temp is a pointer to integer.
And here is the error I get when i execute it in gdb:
    Program received signal SIGSEGV, Segmentation fault.
    0x00007ffff77e9884 in rand () from /lib64/libc.so.6

Can you please help me?
Thank you very much.
EDIT: This is the swapInt function:
void swapInt (int *a, int *b) {
    int aux = *a;
    *a = *b;
    *b = aux;
}

Comment: It is likely that you are overwriting a buffer somewhere; have you run this under Valgrind?
Comment: Does the problem go away if you choose a pivot without using rand() ?
Comment: Can we see the `swapInt` function?
Comment: In `distributePivot`, instead of `swapInt(&pivot, &right);` you need `swapInt(&a[pivot], &a[right]);`.
Answer: There is an error in the program logic.
E.g.
in main
array = [1,2]
call intArrayQuickSort(array, 0, 1);// a:array, left:0, right:1
in intArrayQuickSort
pivot = 1 //provisional result of rand() % (right - left +1) + left;
call distributePivot(a, 0, 1, 1)
in distributePivot
not swap (pivot, right) because pivot == righit
i = 0  //left
j = 0  //right - 1
not execute while block because i == j
execute swap (a[i],a[right]) because i < right // 0 < 1
//a = [2, 1]  //!!NG
return 0
//Already illegal state
in intArrayQuickSort
pivot = 0 ;//from return value : 0
call intArrayQuickSort (a, 0, -1);//left:0, pivot -1 :-1
no operation return
call intArrayQuickSort (a, 1,  1);//pivot + 1:1, right : 1
no operation return
in main
result:a = [2, 1] //NG!
Comment: There is a need to review the logic of the program itself.
Comment: Thanks, I already found that error once I solved the other one. Now my functions works.
Comment: @Zagorax - This story is after change to `intArrayQuickSort (a, pivot + 1, right);`. your program logic is still wrong.
Comment: @Zagorax - If you have already solved the problem if you want to delete the question. Alternatively, please edit the code of the question if an error has occurred that fix still on.
Comment: @BLUEPRIX - Oh damn. You were right. I had 50% of chance to fail when I have only two elements (and I always have because of the recursion). I fixed it. Thank you very much. Should I modify the code in the question or it's enough to mark your as correct answer?
Comment: I do not know that whether it is correct because i have not seen the program that was eventually corrected.
Comment: I changed the condition for the main while from `i < j` to `i <= j`, in this way also with two values, i will be incremented to the value of right and so there will be no swap between i and right at the end (and neither between i and j because i > j).
Comment: @Zagorax - if you change `while(i<j)` to `while(i<=j)` , perhaps, it is not what this program properly.
Comment: I think that will not be able to exit the loop if 'j' and 'i' are equal.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/12347/discussion-between-zagorax-and-bluepixy)
Comment: @Zagorax - We're sorry, but I must sleep soon.
Answer: I think a modified version of
int distributePivot (int *a, int left, int pivot, int right) {
    int i, j;
    if (pivot != right)
        swapInt(&a[pivot], &a[right]);
    i = left;
    j = right - 1;
    while (1) {
        while (i < right && a[i] < a[right])
            i++;
        while (left <= j && a[j] >= a[right])
            j--;
        if (i < j)
            swapInt(&a[i], &a[j]);
        else
            break;
    }
    if(i < right)
        swapInt(&a[i], &a[right]);
    return i;
}
void intArrayQuickSort (int *a, int left, int right) {
    int pivot;
    if (left < right) {
        pivot = rand() % (right - left +1) + left ;
        pivot = distributePivot(a, left, pivot, right);
        intArrayQuickSort (a, left, pivot - 1);
        intArrayQuickSort (a, pivot + 1, right);
    }
}

Comment: I don't like that break inside the while. Your solution seems to work, but my teacher always says to avoid this. Have a look to the one I posted on the chat. That one works and does the same.
Comment: @Zagorax - I chose to break because it was unpleasant to have duplicate `i < j`. Good to do it like you want to do.
Answer: Actually I've found a solution, but I don't know why it works.
The second recursive call should be:
intArrayQuickSort (a, pivot + 1, right);

It makes sense for the algorithm, but I can't understand why the error is with rand(). Any explanation?
Comment: It might be a stack overflow: recurring too deeply and so the function call into `rand` runs off the end of the stack and attempts to access memory illegally, hence segfault (you could try putting any function before the `rand` and see if that causes the same problem in the new function).
Comment: @Zagorax - The program is also incorrect to make this change. you can see the my answers
Comment: @dbaupp - But in the case, it's not the rand() functions that generate the stack overflow but some assignment o similar outside the range.
Answer: pivot = rand() % (right - left +1) + left;

Should be:
pivot = left + rand() % (right - left +1);

Or maybe even:
pivot = left +1 + rand() % (right - left);

Comment: Well, maybe it was wrong. In your case, I would do some printf() debugging. It is probably an off-by-one, somewhere. BTW: in most cases it helps if you use only unsigned types for indexing purposes. (when wrapped, unsigned will become 0xfffffffffffff, which will segfault at the first occation, before doing any real damage)
Comment: Oops, me neither. Maybe that's why I added the third?
Comment: Actually I got the same error with all of your possibility. Why they should be different from mine?


Chart in other module

Question: I'm trying to make a graphic in my program, when I put these same codes in "app.module", "app.component.ts" and "app.component.html" it works normally, but when I use it in another module and component, it doesn't work and returns the error, and when I take them out, the component works normal.
And if I using the component in "app.module" it works normal.
Module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { SalesComponent } from './sales.component';
import { GenericModule } from '../generic.module';
import { ChartModule } from 'primeng/chart';

@NgModule({
  declarations: [SalesComponent],
  imports: [
    CommonModule,
    GenericModule,
    ChartModule
  ]
})
export class SalesModule { }

HTML

sales works!

.TS
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'sales',
  templateUrl: './sales.component.html',
  styleUrls: ['./sales.component.scss']
})
export class SalesComponent implements OnInit {

  data = {
    labels: ['A','B','C'],
    datasets: [{
        data: [300, 50, 100],
        backgroundColor: [ "#FF6384", "#36A2EB", "#FFCE56" ],
        hoverBackgroundColor: [ "#FF6384", "#36A2EB", "#FFCE56" ]
    }]
  };

  constructor() { }

  ngOnInit(): void {

  }

}

ERROR:

src/app/components/sales/sales.component.html:2:1 - error NG8001: 'p-chart' is not a known element:
1. If 'p-chart' is an Angular component, then verify that it is part of this module.
2. If 'p-chart' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

2

  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  src/app/components/sales/sales.component.ts:5:16
    5   templateUrl: './sales.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component SalesComponent.
src/app/components/sales/sales.component.html:2:21 - error NG8002: Can't bind to 'data' since it isn't a known property of 'p-chart'.
1. If 'p-chart' is an Angular component and it has 'data' input, then verify that it is part of this module.
2. If 'p-chart' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.

2

                      ~~~~~~~~~~~~~

  src/app/components/sales/sales.component.ts:5:16
    5   templateUrl: './sales.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component SalesComponent.

Answer: You need to add p-chart in declarations : [ ] in  app.module.ts so that you can access it in other components.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SalesComponent } from './sales.component';
import { GenericModule } from '../generic.module';
import { ChartModule } from 'primeng/chart';
import { PChartComponent} from './pchart.component';

@NgModule({
  declarations: [SalesComponent, PChartComponent],
  imports: [
    CommonModule,
    GenericModule,
    ChartModule
  ]
})
export class SalesModule { }

Chart in other module


How to convert data from dataGridView to a PDF file?

Question: I have this dataGridView which I would like to convert to a PDF file. How do I do it? I searched online and found some codes but it seems like the website I found missed out on a lot of things.
using System.IO;
using System.Data;
using System.Reflection;
using iTextSharp.text.pdf;
using iTextSharp.text;

private void btnExportPdf_Click(object sender, EventArgs e)
{
    //Creating iTextSharp Table from the DataTable data
    PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount);
    pdfTable.DefaultCell.Padding = 3;
    pdfTable.WidthPercentage = 30;
    pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
    pdfTable.DefaultCell.BorderWidth = 1;

    //Adding Header row
    foreach (DataGridViewColumn column in dataGridView1.Columns)
    {
        PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
        cell.BackgroundColor = new iTextSharp.text.Color(240, 240, 240);
        pdfTable.AddCell(cell);
    }

    //Adding DataRow
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            pdfTable.AddCell(cell.Value.ToString());
        }
    }

    //Exporting to PDF
    string folderPath = "C:\\PDFs\\";
    if (!Directory.Exists(folderPath))
    {
        Directory.CreateDirectory(folderPath);
    }
    using (FileStream stream = new FileStream(folderPath + "DataGridViewExport.pdf", FileMode.Create))
    {
        Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
        PdfWriter.GetInstance(pdfDoc, stream);
        pdfDoc.Open();
        pdfDoc.Add(pdfTable);
        pdfDoc.Close();
        stream.Close();
    }
}

Answer: I Converted this:
    //Adding DataRow
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            pdfTable.AddCell(cell.Value.ToString());
        }
    }
    TO:
    //Adding DataRow

     foreach (DataGridViewRow row in dataGridView1.Rows)
     {
          foreach (DataGridViewCell cell in row.Cells)
          {
               try
               {
                   pdfTable.AddCell(cell.Value.ToString());
               }
               catch { }
           }
     }

And in new version that I downloaded this must changed:
cell.BackgroundColor = new iTextSharp.text.Color(240, 240, 240);

to:
cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);

Answer:    u button name btn_PDF_DOWNLOAD_Click(.)

        {
          if (dataGridView1.Rows.Count > 0)
          {
              SaveFileDialog save = new SaveFileDialog();
              save.Filter = "PDF (*.pdf)|*.pdf";
              save.FileName = "Envanter.pdf";
              bool ErrorMessage = false;
              if (save.ShowDialog() == DialogResult.OK)
              {
                  if (File.Exists(save.FileName))
                  {
                      try
                      {
                          File.Delete(save.FileName);
                      }
                      catch (Exception ex)
                      {

                          ErrorMessage = true;
                          MessageBox.Show("Diskteki Veriler Yazılamıyor!"+ex.Message);
                      }
                  }
                  if (!ErrorMessage)
                  {
                      try
                      {
                          PdfPTable pTable = new PdfPTable(dataGridView1.Columns.Count);
                          pTable.DefaultCell.Padding = 2;
                          pTable.WidthPercentage = 100;
                          pTable.HorizontalAlignment = Element.ALIGN_LEFT;

                          foreach (DataGridViewColumn col in dataGridView1.Columns)
                          {
                              PdfPCell pCell = new PdfPCell(new Phrase(col.HeaderText));
                              pTable.AddCell(pCell);
                          }
                          foreach (DataGridViewRow viewRow in dataGridView1.Rows)
                          {
                              foreach (DataGridViewCell dcell in viewRow.Cells)
                              {
                                  pTable.AddCell(dcell.Value.ToString());
                              }
                          }

                          using (FileStream fileStream=new FileStream(save.FileName,FileMode.Create))
                          {
                              Document document = new Document(PageSize.A4,12f,20f,20f,12f);
                              document.Open();
                              document.Add(pTable);
                              document.Close();
                              fileStream.Close();
                          }
                          MessageBox.Show("İşlem Başarıyla Gerçekleştirildi","Bilgi");

                      }
                      catch (Exception ex)
                      {

                          MessageBox.Show("Veri Dışa Aktarılırken Bir Hata Meydana Geldi!"+ex.Message);
                      }
                  }
              }
          }
          else
          {
              MessageBox.Show("Kayıt Bulunamadı.","Bilgi");

          }

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Regular expression with repetitive pattern

Question: I need a regular expression to match
%foo(%bar) or %foo.
I'm using this code now:
String code = "%foo(%bar)";
code.matches("%+[\w&&[^_]][\w0-9]+[\w0-9&&[^_]]");

but it works only in the second case.
Edit: My regular expression must check if the variable contain numbers and letters and if it start with _ or end with _. I don't want a match with _%foo or %foo_ or _%foo_.
Comment: Please update the question will all the conditions then, otherwise it is a guessing game
Comment: `%foo` and `%bar` are literals or placeholders?
Comment: they are just literals
Comment: Does `%[\w]+(\(%[\w]+\))?` work for you?
Comment: @Tunaki Too simple, I need to check if they contain word carachters numbers and it doesn't start/end with _
Comment: @Tunaki I wrote my current regular expression for this reason (!)
Comment: @greywolf82 Yes, but as you say, yours do not work, so we cannot trust it
Comment: @ÁlvaroGutiérrez Ok updated
Answer: A correct Java regular expression would be
Pattern pat = Pattern.compile("%\\w+(?:\\(%\\w+\\))?");

No underscores in first or last place:
Pattern pat = Pattern.compile("%[\\w&&[^_]]\\w*[\\w&&[^_]]" +
                                  "(?:\\(%[\\w&&[^_]]\\w*[\\w&&[^_]]\\))?");

This pattern requires at least two characters in the name. If a single non-underscore should be accepted, the second and third part can be made optional:
    Pattern pat = Pattern.compile("%[\\w&&[^_]](?:\\w*[\\w&&[^_]])?" +
                                  "(?:\\(%[\\w&&[^_]](?:\\w*[\\w&&[^_]])?\\))?");

Comment: @greywolf Lost a comment due to lousy connection, now added to the answer.
Answer: Supposing that %foo and %bar are words that begin with a % sign, the regex would be:
%\w+(\(%\w+\))?

Comment: are you kidding me? :D
Comment: Too simple, I need to check if they contain word carachters numbers and it doesn't start/end with
Comment: \w already matches numbers and letters. I don't understand what "it doesn't start/end with" mean
Comment: I don't want a match with _%foo or %foo_ or _%foo_
Comment: I'm sorry I mean the character "_"


List of hosts in Varnish

Question: I'm running a VPS with multiple different websites, and Varnish in front for caching.
However, some websites should not be cached.
Instead of making individual rules for each website, I would like to make a general "DON'T CACHE" list, which is linked to some rules. Possible?
In the following, I've sketched what I would like: a list of websites (ACL syntax) in the VCL configuration which should not be cached.
list cache_blacklist {
 "domain1.com";
 "domain2.com";
}

sub vcl_recv {
  if (req.http.host ~ cache_blacklist) {
    return(pass);
  }
}

sub vcl_fetch {
  if (req.http.host ~ cache_blacklist) {
    return(hit_for_pass);
  }
}

Comment: Nice question, I was thinking of the exact same thing, I thought of some kind of array option, but the list is much better. What's wrong with the code you gave here? Why doesn't it work?
Comment: The list would need to be explicitly specified as 'acl', instead of 'list', but anyway I'm not sure varnish allows you to compare anything but against the client's IP address with an ACL anyway, so this wouldn't work even if the syntax was correct.
Comment: Thanks for your replies. "list"s doesn't exist in Varnish, so it throws a syntax error. I tried like JamesHannah suggested, to use `acl cache_blacklist {}` however, ACL will only match with `client.id` - not `req.http.host`.
Answer: First thing : you don't need to set a vcl_fetch rule if the condition depends on the request. Everything will be handled in vcl_recv.
vcl_fetch rules are only needed when condition depends on the server response.
HTTP Host being in the request...your vcl_fetch rule is actually useless.
Now that you don't need to tell "which domains should not be cached" twice, just use a single condition in vcl_recv like this :
sub vcl_recv {
    if (req.http.host == "domain1.com" ||
        req.http.host == "domain2.com") {
        return(pass);
    }
}

Note that you can also use regexp...not sure about which is the best...
Comment: Yes this is the way to go

List of hosts in Varnish


Parameter not recognized by Spring Data ElasticsearchCrudRepository

Question: I have a @Document "Project" class with the following variables:
<code>    @Document(indexName = "project-index")
    public class Project {
    ...
        @JsonProperty("import_id")
        private Long importId;

        private String title;
   ...
    //getters and setters
    }
</code>
My JSON is like the following
<code>    {
       "_id" : ObjectId("5269fd92e4b0c74e42976c91"),
    ...
        "import_id" : NumberLong(1),
         "title" : "Something",
    ...
    }
</code>
And my @Repository class is like:
<code>    @Repository
    public interface ProjectRepository extends ElasticsearchCrudRepository<Project, String>{
        Page<Project> findByImportId(Long importId, Pageable page);
        Page<Project> findByTitleLike(String title, Pageable page);
    }
</code>
The problem is that findByImportId is not getting any data, while findByTitleLike is working fine and letting me fetch data, I tried with different configurations, but seems that SpringData is not resolving that the field that has to search by import_id, even when it has @JsonProperty configured. Moreover, I tried to change the variable name to import_id (also the getter and setter) but in such case, when I tried to use findByImport_Id, findByImport_id, findByImport__Id or findByImport__id get an error at runtime.
Any idea how can I map a db variable with an underscore with a java variable that later could be recognized by ElasticsearchCrudRepository?
Thanks
Comment: I know this is an old post, but I am stuck with the same problem. Did you find any solution?
Answer: from the Spring Docs:

If your property names contain underscores (e.g. first_name) you can escape the underscore in the method name with a second underscore. For a first_name property the query method would have to be named findByFirst__name(…).

So it seems the correct would be findByImport__id
Comment: This isn't working for me as of spring-data-elasticsearch 1.2.0.RELEASE.


How to find the integral that generates $X$ number in Maple 17?

Question: By a challenge of my calculus' professor, we have to find a integral that generates a $8$ digit number, such as $12345678$.
Since there is an infinite number of integrals that could result in a $8$ digit number, is there a way to do it in Maple, in order to list some of the integrals that could do it?
Comment: use literally any known definite integral at all and scale properly by multiplying through the terms?
Comment: @RobBland: I think that is an answer, not a comment. Maybe add an example like $12345678\int_0^1 dx$
Comment: $\int_0^{100}x^3\,dx$
Comment: $\frac19\int_1^{10}(x^8-1)dx$
Answer: As mentioned in the comment by Rob Bland, you can use any known integral.
My integral of choice would be $$\int_0^{12345678} 1dx=12345678$$
Answer: To close this out: an example of an integral that produces the number $N$ is
$$
\int_0^1 N ~ dx = \left. Nx \right|_0^1 = N\cdot1 - N \cdot 0 = N.
$$
Answer: $11! = \int_0^\infty x^{11}e^{-x}\ dx$.
Anyway, since as you say there are infinitely many, come up with your own!


Entity Framework Delete Entity without its Dependency

Question: While I am trying to delete my entity I am getting following error in my function;

A relationship from the 'ProjectWebsiteTag_ProjectUser' AssociationSet is
  in the 'Deleted' state.
      Given multiplicity constraints, a corresponding 'ProjectWebsiteTag_ProjectUser_Target' must also in the 'Deleted' state.

Here is my code to delete;
public bool Delete(int id)
        {
            try
            {
                using (ProjectDataContext context = new ProjectDataContext())
                {

                    ProjectWebsiteTag websiteTag = context.WebsiteTags.FirstOrDefault(p => p.WebsiteTagId == id);
                    context.WebsiteTags.Remove(websiteTag);
                    int saveChanges = context.SaveChanges();
                    return saveChanges > 0;
                }
            }
            catch (DbEntityValidationException e)
            {
                FormattedDbEntityValidationException newException = new FormattedDbEntityValidationException(e);
                throw newException;
            }
        }

Here is my data class;
public class ProjectWebsiteTag
    {
        public int WebsiteTagId { get; set; }
        public ProjectUser ProjectUser { get; set; }
        public ProjectWebsite ProjectWebsite { get; set; }
    }

My Config Class;
 public ProjectWebsiteTagConfiguration()
        {
            ToTable("ProjectWebsiteTags");
            HasKey(p => p.WebsiteTagId);
            HasRequired(p => p.ProjectUser).WithRequiredDependent().WillCascadeOnDelete(false);
            HasRequired(p => p.ProjectWebsite).WithRequiredDependent().WillCascadeOnDelete(false);
        }

It looks like it is trying to delete User record, but I do not want that.
I just want to delete "ProjectWebsiteTag" and that's it.
What I am missing here?
Comment: It doesn't seem to be a case of cascade deleting, it's trying to ADD a user with null values in non-nullable fields
Comment: @Rob Why it would even do that? I am not even intending to pull user entity from context.
Answer: It isn't trying to delete the ProjectUser. It's trying to insert it. ProjectWebsiteTagConfiguration() is saying that the ProjectWebsiteTags table has a ProjectUser foreign key in it. When you call
ProjectWebsiteTag websiteTag = context.WebsiteTags.FirstOrDefault(p => p.WebsiteTagId == id)

websiteTag has a ProjectUser with an empty string for its UserId property. So either the record in the ProjectWebsiteTags table has an empty string for the foreign key, or EF is newing a ProjectUser (with an empty UserId) when you get from the context. Either way, EF isn't aware of the existence of a ProjectUser with an empty string id, so when you call SaveChanges() it tries to add it. It can't because the UserId field is required and empty.
Comment: You're right. I was initializing User object inside ProjectWebsiteTag  constructor. I removed that initialization. Meanwhile, I am getting different error now. I updated the question. Thanks for the hint.
Answer: I had to fix my problem by adding one-to-many relationship configuration in my User class.
It comes to a resolution of I need to add relationship hint on both sides of Configuration declarations.
public class ProjectUserConfiguration : EntityTypeConfiguration<ProjectUser>
    {
        public ProjectUserConfiguration()
        {
            ToTable("ProjectUsers");
            HasKey(p => p.UserId);
            HasMany(p=>p.ProjectWebsiteTags).WithRequired(q=>q.ProjectUser).WillCascadeOnDelete(false);
        }
    }


Kentico Cloud Swift SDK not returning items

Question: I'm testing out the Kentico Cloud Swift SDK to return some 'article' content types (I have created two of them and they are published).
I am using the Boilerplate code as described here:
The result I get is : [Kentico Cloud] Getting items action has succeeded. Received nil items.
My code:
let client = DeliveryClient.init(projectId: <project id>, previewApiKey: <preview key>, secureApiKey: <secure key>, enableDebugLogging: true)

func getArticles(){

    // Note: Using "items" as custom query returns all content items,
    // but to map them to a single model, a filter is needed.
    let customQuery = "items?system.type=article"

    // More about strongly-typed models https://github.com/Kentico/cloud-sdk-swift#using-strongly-typed-models
    client.getItems(modelType: Article.self, customQuery: customQuery) { (isSuccess, itemsResponse, error) in
        if isSuccess {

    // We get here and itemsResponse != nil but items == nil

            if let articles = itemsResponse?.items {
                for article in articles {

                }
            }
        } else {
            if let error = error {
                print(error)
            }
        }
    }
}

I believe this error message would appear before ObjectMapper is triggered to convert the JSON into Article objects. I could be wrong though.
Anyone have any ideas?
UPDATE
Interestingly, if I request a single article object like so ...
client.getItem(modelType: Article.self, itemName: <codename>) { (isSuccess, itemResponse, error) in
            if isSuccess {

                if let article = itemResponse?.item {
                    // Use your item here
                }
            } else {
                if let error = error {
                    print(error)
                }
            }
        }

... then it works. I get the Article object. It's just asking for all of the articles that fails.
Answer: I'm going to investigate the issue later today, however, from your description, it might be caused by the Delivery API item readiness delay - the project was not fully synced with the delivery API yet. After the publishing/unpublishing item or creating/generating the project, there might be a small delay in processing messages by Delivery API which could cause unavailability of item. This delay might be variable - from my experience, it may vary from a couple of seconds to 2-3 minutes. Nevertheless, I'm going to check it just to be sure. I'll keep you updated.
Edit: I'm pretty sure the project was not synced and processed on the Delivery API at the time you were requested the items. The API returned 200, which caused isSuccess in the callback to be true, however, there might have been none or just a subset of items available - I've reproduced this behavior (screenshot below), although it's by design (the content/messages in Event Hub must be processed asynchronously).
I've also suggested the improvement for Kentico Cloud's documentation to mention/explain the possible delay caused by processing events queue messages from Event Hubs.

Just to be sure - could you try it again with your getArticles custom query?
Edit2: Back to your question about the ObjectMapper. This is not an error just a debug message, however, there shouldn't be probably nil but 0 (zero) in the debug message. This message came from:
    private func sendGetItemsRequest<T>(url: String, completionHandler: @escaping (Bool, ItemsResponse<T>?, Error?) -> ()) where T: Mappable {
    sessionManager.request(url, headers: self.headers).responseObject { (response: DataResponse<ItemsResponse<T>>) in

        switch response.result {
        case .success:
            if let value = response.result.value {
                let deliveryItems = value
                if self.isDebugLoggingEnabled {
                    print("[Kentico Cloud] Getting items action has succeeded. Received \(String(describing: deliveryItems.items?.count)) items.")
                }
                completionHandler(true, deliveryItems, nil)
            }
        case .failure(let error):
            if self.isDebugLoggingEnabled {
                print("[Kentico Cloud] Getting items action has failed. Check requested URL: \(url)")
            }
            completionHandler(false, nil, error)
        }
    }
}

Comment: I'm almost sure it's just a coincidence - I'm not familiar with any internal process that could condition getting all items vs getting just one item.  However, if you experience any suspicious behavior in the future, let me know. End of all - it's software and there might be some glitch.
Comment: My code works consistently now: [Kentico Cloud] Getting items action has succeeded. Received Optional(2) items.
Comment: The delay in processing the project or the items would have been substantial though, I was trying the call for a long time, but it only started working AFTER I requested the single item.
Answer: Ok. This is very weird. After checking the API by requesting an individual item (see the update in the post above), and getting a result (woot). It now seems the original code (unchanged) now works.
I'm wondering if it takes a while for the data to propagate and be available in the API?
Who knows. Weird.


Proper unicode support

Question: Right now I have a first gen windows phone, with 7.8 installed [Omnia 7]. It does not have proper unicode support [I'll be precise, it does not show malayalam characters, on facebook for instance]. I looked around if WP8 supports this and it seems like it doesn't.
My question is, does WP8 have proper unicode rendering? If not throughout the OS, AT THE LEAST on the browser?
Answer: http://answers.microsoft.com/en-us/winphone/forum/wp8-wpfeatures/malayalam-unicode-support-in-windows-phone-8/4d144e4f-eea4-430b-b26d-945e2d98df00
Sorry, Malayalam is not presently supported.
I did find this, though: http://malayalam4mobile.hafees.com/

Proper unicode support


Problem emptying a collection, it is not saved EasyAdmin

Question: For an entity with multiple properties, I have a form that shows one of those properties which is a collection.
I have this form with EasyAdmin, I can add and remove items from the collection, the problem is that I cannot remove all of them the changes are not saved or even if there is only one item left, if I delete it, it is not saved.
Solution I have found
The error I have when deleting offers, was that when trying to remove all they were not deleted on the database, it seems that when the entire body of the empty POST does not execute anything on the database, because if you put the offers in the Bike form along with all properties, if you let them be removed.
Therefore, the solution I take is to add an extra field as hidden, so that when the post is sent without any discount, it will not be empty.
Entity Bike:
class Bike{
    // More properties

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Bike\Offer", mappedBy="bike", orphanRemoval=true, cascade={"persist"})
     */
    private $priceOffers;

    public function __construct()
    {
        $this->priceOffers = new ArrayCollection();
    }

    // Adding, removing items and getter methods
}

Entity Offer:
class Offer{
    // More properties

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Bike", inversedBy="priceOffers")
     */
    private $bike;

    // getter and setter methods
}

Entity in EasyAdmin:
bike_offers:
    class: App\Entity\Bike
    role: ROLE_MANAGER
    form:
        fields:
            - property: 'priceOffers'
              type: 'collection'
              css_class: 'offers-collection'
              type_options:
                entry_type: App\Form\Bike\OfferType
                by_reference: false
                label: false

Answer: You need to add the allow_delete option and set to true.
type_options:
  allow_delete: true

https://symfonycasts.com/screencast/easyadminbundle/collection-type
Comment: This has not worked for me, the docs says: allow_delete: (optional, default true) a boolean value indicating if uploaded files can be deleted directly in the edit/new form;


Inverse of matrix - definition

Question: Usually the inverse of a square $n \times  n$ matrix $A$ is defined as a matrix $A'$ such that:
$A \cdot A' = A' \cdot A = E$
where $E$ is the identity matrix.
From this definition they prove uniqueness but using significantly the fact that $A'$ is both right and left inverse.
But what if... we define right and left inverse matrices separately. Can we then prove that:
(1) the right inverse is unique (when it exists)
(2) the left inverse is unique (when it exists)
(3) the right inverse equals the left one
I mean the usual definition seems too strong to me. Why is the inverse introduced this way? Is it because if the inverse is introduced the way I mention, these three statements cannot be proven?
Comment: Related question: https://math.stackexchange.com/q/3852/40119
Comment: It's a little important to say what your matrices are *over*. Presumably, a field (the reals? the rationals? the complex numbers? other?) Over more general rings, weird things can happen.
Comment: @littleO I looked at this answer and I think I understand it well: https://math.stackexchange.com/q/3800863 So... basically we explicitly show (construct) that matrix C and then it follows that the right inverse equals C and the left one also equals C. Correct? So... it means one can prove (1), (2), (3) if the two concepts of left and right inverse are introduced separately, is that right? I think my book does the same later on in the text. It just doesn't mention that these equalities there are called Laplace expansions. Good to know they are called that way.
Comment: @ArturoMagidin My question was basic. The matrices are over some field yes, e.g. over the reals. On a side note, what weird things? Which might influence the answer, I guess?
Comment: @peter.petrov: over general rings, you could have matrices that are not square, but are invertible (e.g., a $1\times 2$ matrix $A$ and a $2\times 1$ matrix $B$ with $BA$ the $2\times 2$ identity and $AB$ the $1\times 1$ identity), which is impossible over a field. And you could have square matrices that have inverses on one side but not the other; this also cannot happen over a field (or more generally, over a domain). In any case, the "accepted" answer has a serious gap.
Comment: @ArturoMagidin Aha... So in some way even though unwillingly my question does have some deeper meaning. I get it, thanks. Yeah, I was feeling like the definition I read was a bit too strong.
Comment: It has well-known answers in general rings (away from matrices). See my answer. In general rings, it is standard to define "left-invertible" and "left inverse", "right invertible" and "right inverse", and "invertible" and "two-sided inverse", followed by a proof that if an element is  left- and right-invertible then it is invertible and its left and right inverses coincide. In fact, it can be done at the level of monoids, not even rings.
Comment: @ArturoMagidin I will read it in some depth definitely. Thank you.
Comment: (I edited and added something to the previous comment before you commented...)
Comment: @Right... Thanks. Yes, that's how I felt the theory should have been developed... even over a field like the reals. This definition that I read was just not minimalistic enough, that was my feeling.
Answer: Given $n \times n$ matrices $A$ and $B$ for which holds $AB = I$ where $I$ is the $n \times n$ identity matrix. Now we will try to solve
$BX = I$
for an unknown $n \times n$ matrix $X$. We (left-)multiply both sides by $A$ to get
$ABX = AI$
which gives us
$IX = A$
so $X = A$ (because $IX = X$) and therefore $BA = I$. So we just showed $AB = I$ implies
$AB = BA = I$.
So as you can see it is not necessary to introduce a second definition for the inverse because it will lead to the same. Instead of $B$ we write $A^{-1}$.
Existence of a solution to $BX = I$ is because it can be shown $B$ is a bijective mapping ($x \mapsto Bx$) from $\mathbb{R}^{n}$ to $\mathbb{R}^{n}$.
Comment: I told you. You want to prove $BA=I$. You denote $X=BA$. Then you show that $B=XB$ (this is fine, this is correct). But from this last equality you cannot conclude that $X=I$.
Comment: There are non-commutative rings with elements $A$, $B$ such that $AB=I$ but $BA \ne I$ - see [here](https://math.stackexchange.com/questions/2731164) for example. So you should ask yourself why does your proof not apply in that case?
Comment: You cannot cancel matrix $B$ like this from both sides of the equality. For matrices if we have that $AB=A$ this does not imply $B=I$ (or $A=0$ where $0$ is the zero matrix). Never mind, leave it, I am OK now, I got it.
Comment: As far as I can tell, you have shown the following: We assume that $AB=I$. If $BX=I$ has a solution, then $X=A$. (But we still need to show that $BX$ has a solution.) I'd guess adding this clarification - instead of deleting the answer - would be completely sufficient. But if you still think that it is really needed to delete your answer, you have to ask @peter.petrov to unaccept it first.
Comment: Does this proof really work? Because it looks very simple and obvious if indeed correct.
Comment: I think this really works... Thanks a lot. Not sure why this proof is not mentioned more often.
Comment: I worked through your argument one more time but... But this only proves that if X exists such that BX=I then X=A. It does not prove that this X really exists (given that AB=I). I think the explicit proof is better - by just showing explicitly what $A^{-1}$ really is (that matrix with the cofactors). Never mind, I get it all now.
Comment: You have that $AB=I$, you are trying to prove that $BA=I$ There's no way apart from constructing explicitly the $A^{-1}$ matrix and then showing that it's both left and right inverse (as done here: https://math.stackexchange.com/a/3800863/116591) I am accepting your answer anyway, thanks for the help.
Comment: But that's the thing: yes, $X=I$ is a solution but you are not sure if $X=I$ i.e. $X=I$ is not implied. And since $X$ denotes $BA$ you are not sure if $BA=I$. You see the flaw?
Comment: No... you are missing the point, there may be more than one X such that $B=XB$. Hence it does not follow that $X=I$. Write your whole proof in full and you will see the flaw.
Comment: No, you didn't show $X=I$. You have a flaw there believe it or not.
Comment: @Elmex80s Let me delete my entire question :) Again... thanks for the help!
Comment: @peter.petrov  You cannot delete a question that has an upvoted answer, or has been accepted.  And Elmex80s, do not vandalize your own post.
Comment: See update. ___
Answer: The proposed, accepted answer, has a bug. I mean, the conclusion $(AB=I)\Rightarrow (BA=I)$ is true for $n\times n$ matrices, but the proof is wrong.
Suppose that $AB=I$.
IF there exists $X$ so that $BX=I$ -- which you don't know --
THEN you can conclude that $ABX=AI$, whence $X=A$.
But may be $X$ does not exist. In fact the proposed proof never used the fact that the matrices are square $n\times n$, which is crucial.
Example. Suppose $A=\begin{pmatrix}1&0&0\\0&1&0\end{pmatrix}$ and $B=A^t=\begin{pmatrix}1&0\\ 0&1\\ 0&0\end{pmatrix}$
Then $AB=I$, more precisely $AB=I_2$ the identity $2\times 2$.
IF it would exist $X$ so that $BX=I$, more precisely $BX=I_3$ the identidy $3\times 3$, then one could conclude that $X=A$. BUT in fact $BA=\begin{pmatrix}1&0&0\\ 0&1&0\\ 0&0&0\end{pmatrix}$
It is still true, for $n\times n$ matrices, that $AB=I$ if and only if $BA=I$, but this fact has not a two-lines proof. (See for instance this question).
Note: the above example can be adapted to "square" matrices of infinite size. That is to say, endomorphisms of infinite dimensional vector spaces that have a left inverse need not to have a right inverse.
Finally, to give a complete answer to the original question, observe that any matrix $C=\begin{pmatrix}1&0\\ 0&1\\ x&y\end{pmatrix}$ is a right-inverse of $A$. (And so $C^t$ is a left inverse of $B$). Which shows that right and left inverses are not unique outside the realm of $n\times n$ matrices.
So yes, the fact that for $n \times n$ matrices a right inverese is also a left inverse is crucial.
Comment: "but this fact has not a two-lines proof" Yeah, exactly my point. I get it much better now.
Comment: I saw the question and the answer you were referring to. I even have a comment below that answer. That answer is what made me reread the proof from Elmex80s, and made me suspect there's some flaw in it. Thanks for your answer, it had a few interesting points.
Answer: So... square matrices over a field are special: one can prove that if a square matrix has a left inverse, then it also has a right inverse. And once you know that, it is easy to show that the left and right inverse must be equal. This holds in general for groups/rings: if $x$ is an element, and there exist $a,b$ such that $ax=1$ and $xb=1$, then $a=b$:
$$a = a1 = a(xb) = (ax)b = 1b = b.$$
(Use capital letters and the identity for matrices).
Now, if $A$ is a square matrix over a field, and there exists a matrix $B$ such that $AB=I$, then interpret $A$ and $B$ as linear transformations. Then $AB$ is bijective, hence $A$ is surjective; but that means that $A$ is full rank, hence by the Dimension Theorem has trivial nullity, hence $A$ is also injective. Since $A$ is therefore a bijection, it has a left inverse $C$ (which is also linear, and thus corresponds to a matrix), and thus $A$ has a two-sided inverse.
Similarly, if $A$ has a left inverse $C$ with $CA=I$, then $A$ is one-to-one, hence full rank and so surjective, so it has a right inverse and the argument proceeds as before.
In arbitrary rings you can have elements that have a left inverse but no right inverse; in such cases, you will have multiple left inverses but no right inverse. For if $x$ is an element such that there exists $a$ with $ax=1$, but $xb\neq 1$ for all $b$, then $xa\neq 1$, so $xa-1\neq 0$. Then $(xa-1)x = xax-x = x-x = 0$, so then $(a+xa-1)x = ax+(xa-1)x = 1$, but $a+xa-1\neq a$. Thus, $x$ has at least two left inverses. A symmetric argument shows that if $x$ has a right inverse but no left inverse, then it has at least two right inverses.
And yes, it is possible to have rings in which some elements have left inverses but no right inverses. Consider the vector space $\mathbb{R}[x]$ of all polynomials with coefficients in $\mathbb{R}$, and the ring of all linear transformations from $\mathbb{R}$ to itself. The linear transformation $T(p(x)) = xp(x)$ is one-to-one but not onto, so it has left inverse but no right inverse. In fact, it has infinitely many left inverses. Similarly, the linear transformation $T(p(x)) = p'(x)$ (the derivative) is onto, but not one-to-one, so it has a right inverse (in fact, infinitely many), but no left inverse.
Comment: @Elmex80s: What you did was find *necessary* conditions for a solution to exist; *if* a solution exists, then `blah`. If all steps were reversible, then the necessary condition you find at the end is also sufficient. But if not all steps are reversible, then you are in trouble. In your solution, the step from $BX=I$ to $ABX=AI$ is not reversible in general (you need $A$ to be left-cancellable, and you do not know that in general), so you cannot guarantee that your necessary condition is also sufficient.
Comment: @Elmex80s: An analogue would be to try to solve $x^2=-1$ in the reals, by first squaring to get $x^4=1$, then solving this to get $x=1$ and $x=-1$. *If* a real solution existed, then it would be $1$ or $-1$; but the step from $x^2=-1$ to $x^4=1$ cannot be reversed, so the necessary condition is not sufficient.
Comment: I updated my answer. Still somehow a bit surprised. I am always used to 'crawl' my way to a solution by valid algebraic manipulation and never had to worry about the existence of a solution. In fact the only reason I am convinced there was a flaw in my proof was because of the counterexample with the infinite vector space. How does this work for differential equations? Can you just go for a numerical solution without knowing anything about existence?
Comment: Thanks. So when steps are reversible existence of the solution follows from the answer, example $2 + x = 5$. When not I have to be much more cautious? Strange I do not know this, I got my degrees from respectable universities.
Comment: @Elmex80s: Surely you've encountered equations where solving them produces "extraneous solutions", or in differential equations you get equations where you have to "manually" find special solutions (usually constant solutions), which you excluded when you did cancellation, division, squaring, or the like. You've seen the phenomenon, you just never had it highlighted.

Inverse of matrix - definition


Botão não chama função corretamente

Question: from tkinter import *

class Application:

      def __init__(self, master=None):
          self.inicio = Frame(master)
          self.inicio.pack()
          self.msg = Label(self.inicio, text="Deseja exprimentar a versao input?")
          self.msg["font"] = ("Calibri", "9", "italic")
          self.msg.pack ()
          self.sim = Button(self.inicio)
          self.sim["text"] = "sim"
          self.sim["font"] = ("Calibri", "9")
          self.sim["width"] = 10
          self.sim.bind("<Button-1>", self.Verificar)
          self.sim.pack ()
          self.nao = Button(self.inicio)
          self.nao["text"] = "nao"
          self.nao["font"] = ("Calibri", "9")
          self.nao["width"] = 10
          self.nao.bind("<Button-2>", self.Verificar)
          self.nao.pack ()

      def Verificar(self, event):
          if self.msg["text"] == "Deseja exprimentar a versao input?":
              self.msg["text"] = "Bem vindo a versao de input"

          else:
              self.msg['text']='Deseja exprimentar a versao input?'

root = Tk()

Application(root)

root.mainloop()

Alguém me explica como faço para quando carregar no não aparecer a mensagem 'Bem vindo a versão output'?
Comment: Bom, você tá criando o `Label` no construtor com essa frase (quer dizer, com "input" nela), então é natural que ele apareça desde já. Vc pode colocar outro texto (vazio `""`, talvez) no label de início, por exemplo.
Comment: Eu queria que quando carregasse no não que a frase mude para bem vindo a versão output e n estou a conseguir so aparece quando carrego a segunda vez no sim
Answer: Neste trecho:
self.nao.bind("<Button-2>", self.Verificar)

<Button-2> se refere ao botão do meio do mouse (experimente o seu programa como está, clicando com o botão do meio).
Sem mexer muito no seu programa, eu adicionaria uma nova função:
  def Verificar(self, event): # removi o else dessa
          self.msg["text"] = "Bem vindo a versao de input"
  def Verificar2(self, event): # função nova
          self.msg["text"] = "Bem vindo a versao de output"

E mudaria o código do botão nao para <Button-1> também:
self.nao.bind("<Button-1>", self.Verificar2)

Isso deve fazer o que você quer, usando os botões corretos... :)
Comment: muito obrigado :) resolvido agora sim posso prosseguir no meu projeto
Comment: :D Quando puder, @GhostCode, marque a resposta como 'aceita', clicando na marca de verificação do lado esquerdo do texto!
Comment: já agora sabe me explicar como faço para quando carregar sim apareça uma tabela para inserir valores já fiz a estrutura toda da tabela ect... mas n consigo fazer com que  abra a tabela n sei com fazer a ligação entre a primeira parte e a segunda . tenho de realizar um ciclo de for? ou um if ?
Comment: @GhostCode Sugiro que você abra uma pergunta sobre isso, e inclua o seu código! Eu juro que te diria se soubesse :(
Comment: muito obrigada na mesma já actualizei uma perguntar anterior sobre o programa que estava a fazer vou ver se alguém me consegue ajudar :)
Comment: @GhostCode Vou dar uma olhada! Acho muito legal que você já esteja partindo para um programa com GUI (interface gráfica) mas sugiro que você tente fazê-lo em `console` primeiro (pesquise por programa de console), e depois, com um programa básico funcionando desta maneira, tente implementar um GUI para ele.
Comment: obrigado pelo concelho e ajuda mas tem de ser mesmo aqui porque depois de conseguir concluir  vou ter de apresentar numa aula .:)

Botão não chama função corretamente


Prove that any subset of six elements of $S=\left\{1,2,...,9 \right\}$ must contain at least two elements whose sum is 10.

Question:
Prove that any subset of six elements of $S=\left\{1,2,...,9 \right\}$ must contain
  at least two elements whose sum is 10.

I thought of using the pigeonhole principle, but I can't think of how to write this proof, I can only think of particular cases.
Let's say I have the subset $A\subset S$, $A=\left\{1,2,3,4,5,6 \right\}$, so there's $6+4=10$, and $5+2+1$ and blah blah blah...
I can't think of a way to "generalize" this... Any ideas?
Comment: Possible duplicate of [Let $S=\{3,4,5,6,7,8,9,10,11,12\}$. Suppose 6 integers are chosen from S. Must there be 2 integers whose sum is 15?](https://math.stackexchange.com/questions/1456444/let-s-3-4-5-6-7-8-9-10-11-12-suppose-6-integers-are-chosen-from-s-must-t) – same  problem, same solution, only with slightly  different numbers.
Answer: Make a partition $$\{1,9\}, \{2,8\},\{3,7\},\{4,6\}\{5\}$$ So we have 5 sets(houses) and 6 numbers (pigeons)...
Perhaps this:
If we have set with first $2n-1$ elements than every set with $n$ elements have a pair such that their sum is $2n$


Change Bootstrap class depending of component state in React

Question: I have a react component called NavBar. It gets a variable from another component (App.js) which specifies if the page is in dark mode or not. The variable is called "pageMode". I want to change the class of the navBar from navbar-light to navbar-dark depending of the value of the "pageMode" var.
Here´s the code
import React from 'react';

class NavBar extends React.Component{

render(){

if(this.props.pageMode === "dark"){
    //Here I want to do something to render the component using navbar-dark class
}
else{
    //Render using navbar-light class
}

return
    Inicio
    <button className="navbar-toggler" type="button" data-toggle="collapse" data-
     target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-
    expanded="false" aria-label="Toggle navigation">

    </button>

            Proyectos

            Sobre mi

}
}

export default NavBar;

In the render return state the class between [] is the one that i want to be changed depending of the variable value.
Thanks for reading!
Answer: import React from 'react';

class NavBar extends React.Component{

render(){

const themeClass = {
  dark: '[navbar-dark]',
  light: '[navbar-light]'
}[this.props.pageMode]

return <nav className={`navbar navbar-expand-lg ${themeClass} bg-light`}>
    Inicio
    <button className="navbar-toggler" type="button" data-toggle="collapse" data-
     target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-
    expanded="false" aria-label="Toggle navigation">

    </button>

            Proyectos

            Sobre mi

}
}


Calculus word problem( multivariable)

Question: A manufacturer sells three types of fertilizers, which are mixtures of three products A, B and C.
The fertilizer of the type I contains, by unit: $10$ kg of A, $30$ kg of B and $60$ kg of C
that of type II: $20$ kg of A, $30$ kg of B and $50$ kg of C
that of type III: $50$ kg of A and $50$ kg of C.
There are currently in stock $2000$ kg of A, $900$ kg of B and $3100$ kg of C. How many units of each type of fertilizer does the manufacturer have to produce if they want to dispose of all the raw materials in stock?
Answer: Hint
Just name $x_1$, $x_2$ and $x_3$ the quantities of product $I$, $II$ and $III$ which will be made. Now, what do they contain ?
Concerning $A$, you have $$10 x_1+20 x_2 +50 x_3=2000$$  Do just the same for $B$ and $C$. So you have three equations for three unknowns and you have to solve it.
I am sure that you can take from here.
Answer: Hint:
It is a system of linear equation  with
$n_1$ = No of units of Fertilizer Type I
$n_2$ = No of units of Fertilizer Type II
$n_3$ = No of units of Fertilizer Type III
Linear system of equations:
$$10n_1+20n_2+50n_3 = 2000$$
$$30n_1+30n_2 = 900$$
$$60n_1+50n_2+50n_3 = 3100$$
Solve it using Matrix Algebra:
The solution is $n_1$ = 10, $n_2$=20, $n_3$ = 30
We are living in a sophisticated world, $$Matrix(N) = MatrixA^{-1} MatrixB$$
Just to help you further to start using Excel
Here is a set up, Good Luck

Calculus word problem( multivariable)


Multiset/Set/List initiation and use in pseudocode

Question: I'm writing a paper and I've come across interesting problem. In my algorithm, I create a list of 0's (example [0,0,0,0]), where the number of 0's is given by parameter "x". Later I want to update these values using argmin to get the smallest member of this set/list and assign it new value. The problem is how to succinctly describe the creation of such set/list in pseudocode, i.e., mathematical notation.
From what I know, I can't use set, since there are duplicate elements. List have nonstandard notation of add operation and they look weird and there is no notation like "Set-builder" for sets to make the creation of starting list of zeroes in one line. Multi-sets are not very distinguishable from actual sets in notation, which makes it bit confusing for the reader, not mentioning that "Set-builder" notation does not contain what I need to describe it anyway.
I just can't figure out a good way how to deal with this problem.
Comment: You say "pseudocode, i.e., mathematical notation", but pseudocode has different conventions and options from the mathematical notation in the vast majority of math papers that do not use pseudocode. 1. Can you confirm that you want pseudocode rather than a non-pseudocode mathematical presentation? 2. It's unclear if the order of the numbers in your list matters to you, or what you do when multiple entries attain the lowest value.
Comment: @MarkS. I'm sorry I was unclear, I want pseudocode. The order of numbers does not matter to me, however I use argmin in my code to extract the reference to element of minimal value. When I think about it I didn't really think about cases where multiple elements have the minimal value - if argmin is still returning one element or a "subset".
Answer: So my current solution to this problem is as follows:
$MultisetOfZeroes \gets \{0\} \rightarrow x$
I'm not sure if it is correct however if I understood this answer correctly it should be applicable like that.


Gaussian Elimination: 4 equations, 8 unknowns

Question: I need to find the solution set of all b=(b1,b2,b3,b4) element R^4 for this:

I know how Gaussian elimination works, but how do I find all possible solutions of all the b's?
Comment: Leave the right hand side as shown, in $b_1, b_2, b_3, b_4$. Start to do Gaussian elimination, and find the conditions where the $b$'s are not in contradiction.
Answer: Look at the matrix $A$:
$$A = \begin{pmatrix} 1 & -4 & 5 & 1 \\ 1 &-2 & 3 & 1\\ 7 & -11 & 18 & 7 \\ -2 & 3 & -5 &-2 \end{pmatrix}.$$
Notice how the first and last columns are the same? This means that the matrix is singular; in other words, its rank is less than its dimension. In fact, if you perform Gaussian elimination, you will find that its rank is 2 (try it!).
What does this mean?
Well, consider $A$ as a linear transformation. Since its rank is 2, and its dimension is 4, then the dimension of its null space is also 2. That means that when you apply this linear transformation to vectors in $\mathbb{R}^4$, your result will either be zero, or it will lie in a 2-dimensional subspace of $\mathbb{R}^4$. This means that $b$ is either a vector of zeros, or it lies in this subspace. Your task is to find a basis for this subspace, and then $b$ is any linear combination of those basis vectors. Since the subspace is 2-dimensional, you should find two linearly independent vectors in $\mathbb{R}^4$ forming the basis.
Comment: but I don't know the b's. The task reads that I need to find out the solution set of all b=(b1,b2,b3,b4)
Comment: Maybe type out the problem fully. As you have described it, it doesn't make for a very interesting problem.
Comment: Ah, I see why they're asking now. I will edit my answer.
Comment: I have. Full:
Determine the Set S of all b=(b1,b2,b3,b4) element R^4 for which the real system of linear equations above has solutions.
Comment: @user3071205 See my edit, hopefully that makes sense!
Comment: OK. So a basis for the subspace would be B={(1,0,1,1),(0,1,-1,0)}, wouldn't it? From here, how do I go about finding out the set of b1,b3,b3,b4?
Comment: Every vector in a subspace can be written as a linear combination of its basis vectors.


Uma query com custo pior pode ser uma query com melhor desempenho?

Question: Contexto
Aqui na empresa temos uma query muito complexa que engloba várias regras de negócio, para apresentação em um WorkFlow e por enquanto estou avaliando ela no SQLServer.
A performance desta query estava ruim e com o crescimento das tabelas, os DBA nos alertaram a reavaliar a query pois ela está ficando muito custosa para o banco.
Quando comecei a query tinha um custo [Estimated SubTreeCost = 19.891], a partir daí comecei a avaliar e remover alguns campos opcionais, left joins desnecessários, subselects da projeção e o custo aumentou ao invés de diminuir [Estimated SubTreeCost = 20.232]
Ao executar a query reduzida, tive o resultado em 23s  e da query original (com custo menor) 1min18s
Pergunta
Não sou muito experiente com avaliação de planos de execução de queries e daí veio uma dúvida, o custo é baseado na quantidade de dados retornados? no tempo de execução? no custo para o banco?
Pode a query com custo maior ser melhor que a original com custo menor?

Obs: Não posso compartilhar a query por se tratar de dados sigilosos e a query é bem complexa e seria díficil tentar criar uma query fake semelhante
Comment: "Há algumas suposições falsas comuns sobre o custo estimado de execução. Em especial, as pessoas costumam pressupor que o custo estimado de execução é um bom indicador de quanto tempo a consulta leva para ser executada e que essa estimativa permite diferenciar planos bons de planos ruins. Mas isso não é verdade.": http://technet.microsoft.com/pt-br/magazine/2007.11.sqlquery.aspx O artigo é bem elucidativo. A parte recortada é só um chamariz :-)
Answer: O custo é apenas uma estimativa... Pessoalmente não ligo muito a esse custo mas sim ao tempo de execução. Para mim o mais importante é devolver a informação o mais rápido possível. Todavia, há um custo ao qual dou atenção quando pretendo diminuir o tempo de execução, que é o "Estimated Operator Cost" dos joins e dos indexes. Diminuindo o custo destes operadores tem um impacto quase sempre directo na diminuição do tempo de execução.
Espero ter ajudado.
Answer: O Estimated SubTreeCost é individual e existe para cada operador criado no plano de execução, então o aumento na estimativa deste operador em específico, não significa uma query mais pesada, mas somente um aumento no consumo da substree deste índice em específico. Pode ser, por exemplo, que a remoção das partes opcionais aumente a quantidade de dados obtidas por essa subtree, mas de um modo geral, diminua o custo total da query para o banco.
Se possível, sempre rode a query, marcando para incluir o plano de dados atual (query -> Include Actual Execution Plan). A estimativa, muitas vezes não condiz com o que o SQL realmente utilizará.


Eu queria saber como posso resolver o problema de instalar a biblioteca dataprep em python, já que está retorando um erro e não sei o que fazer

Question:
O erro que a imagem retorna

The conflict is caused by:
dataprep 0.3.0 depends on bottleneck<2.0 and >=1.3
dataprep 0.2.15 depends on bottleneck<2.0 and >=1.3
dataprep 0.2.14 depends on pandas<1.1 and >=1.0
dataprep 0.2.13.post2 depends on pandas<1.1 and >=1.0
dataprep 0.2.13.post1 depends on pandas<1.1 and >=1.0
dataprep 0.2.13 depends on pandas<1.1 and >=1.0
dataprep 0.2.12 depends on pandas<1.1 and >=1.0
dataprep 0.2.11 depends on pandas<1.1 and >=1.0
dataprep 0.2.10 depends on pandas<1.1 and >=1.0
dataprep 0.2.9 depends on pandas<1.1 and >=1.0
dataprep 0.2.8 depends on pandas<1.1 and >=1.0
dataprep 0.2.7 depends on pandas<1.1 and >=1.0
dataprep 0.2.6 depends on pandas<1.1 and >=1.0
dataprep 0.2.5 depends on pandas<1.1 and >=1.0
dataprep 0.2.4 depends on pandas<1.1 and >=1.0
dataprep 0.2.3 depends on pandas<1.1 and >=1.0
dataprep 0.2.2 depends on pandas<1.1 and >=1.0
dataprep 0.2.1 depends on scipy<1.4 and >=1.3
dataprep 0.2.0 depends on scipy<1.4 and >=1.3
dataprep 0.1.0 depends on scipy<1.4 and >=1.3
To fix this you could try to:

loosen the range of package versions you've specified
remove package versions to allow pip attempt to solve the dependency conflict

este é o que o terminal retorna
Comment: Já verificou a versão do módulo *bottleneck* instalado no sistema?
Comment: Como eu consigo verficar isso ??
Comment: tenta `pip list --outdated` para listar os módulos desatualizados do sistema ou `pip show bottleneck` para ver apenas as informações do módulo *bottleneck*.
Comment: Consegui ver todos os pacotes que tenho. O bottleneck não ta instalado ainda e quando eu tento instalar ele sepado dá esse erro ai. Na real que o que nao ta instalando é justamente isso
Comment: Ai tem diferença, e informação é importante . O erro gerado pela tentativa de instalação do [bottleneck](https://pypi.org/project/Bottleneck/) tem de ser diferente da informação de erro gerada pela instalação do *dataprep*.
Comment: Consegui resolver aqui, Obrigado pela atenção @AugustoVasques, era o C++ que estava numa versão muito antiga e a biblioteca usa ele por baixo dos panos kkkkkk
Answer: Tenta instalar usando esses comandos que fazem a instalação direta. Eles podem responder de uma outra forma.
<code>pip --trusted-host pypi.python.org --trusted-host pypi.org install --trusted-host files.pythonhosted.org msedge-selenium-tools dataprep
</code>
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: Tentei instalar usando esse comando que me passou mas retornar o mesmo erro


Abrir WebCam e capturar imagem com C# em ASP.NET WebForms

Question: tudo bem? Estou desenvolvendo um sistema de cadastro de alunos e preciso abrir a webcam do computador para tirar uma foto do aluno e vincular no seu cadastro, gostaria de saber como é possível realizar essa ação utilizando C# em ASP.NET WebForm.
Desde já, muito obrigado!
Comment: Conseguiu avançar?
Comment: Infelizmente não meu amigo, ele apenas abre como um input type="file" normal, eu precisava de uma solução que abrisse a webcam utilizando qualquer meio que envolvesse ASP.NET ou Javascript, já consegui porém realizar a abertura da WebCam, porém ainda estou tendo dificuldades em capturar a imagem, mas estou no caminho, de qualquer maneira agradeço ao amigo pela boa disposição de ajudar. Muito obrigado!
Answer: Você pode simplesmente usar um input file com o atributo capture, se o dispositivo estiver disponível e o acesso for liberado pelo usuário a captura será feito por ela, caso contrário irá abrir o diálogo para seleção do arquivo nos diretórios locais
<input type="file" accept="image/*" capture>


$\frac{\log(x)}{1-x}$ is increasing

Question: How can I show that the function $h(x):= \frac{\log(x)}{1-x}$ is increasing on $\mathbb{R}_{>0}$? The derivative of $h$ is $h'(x)= \frac{x\log(x)-x+1}{x(1-x)^2}$ but I don't see why $h'(x)$ is always non-negative.
Answer: It is enough to show that $x\log(x)-x+1\geq0$ for all $x>0$. Define $g(x)=x\log(x)-x$. Then,
$$g^\prime(x)=\log(x)$$
So, for $x\geq1$, we have $g^\prime(x)\geq0$ and so $g$ is increasing on $[1,\infty)$. Hence, for $x\geq 1$, we have $g(x)\geq g(1)=-1$.
On the other hand, for $0< x\leq 1$, note that $g^\prime(x)\leq 0$ so $g$ is decreasing. Hence, $g(x)\geq g(1)=-1$ for all $0<x\leq 1$.
To conclude, we have that for all $x>0$ that $g(x)\geq -1$ or $x\log(x)-x+1\geq0$.

Note. The function $h(x)$ is not defined at $x=1$ right away, but you can continuously extend it by $h(1)=1$ and likewise $h^\prime(1)=0$. The answer above assumes that.
Hope this helps. :)
Comment: In other words: $g$ is *convex* and therefore $g(x) \ge g(1) + (x-1)g'(1) = -1$.
Answer: Using the well known inequality $\log(x) \ge 1-1/x$ we get that
$$
 x \log(x) - x  + 1 \ge x \left( 1-\frac 1x \right) - x + 1 = 0
$$
for all $x > 0$. This proves that $h'(x) \ge 0$, i.e. that $h$ is increasing.
More precisely, $h'(x) > 0$ except for $x=1$, so that $h$ is strictly increasing.

Another solution:
$$
 -h(x) =  \frac{\log(x)}{x-1} = \frac{1}{x-1} \int_1^x \frac{dt}{t}
= \int_0^1  \frac{ds}{1+s(x-1)}
$$
with the substitution $t = 1 + s(x-1)$. The last integral
is decreasing in $x$ because the integrand is decreasing in $x$ for every $s$.

$\frac{\log(x)}{1-x}$ is increasing


Why is the third triad dominant?

Question: I'm working through "Guide to the Practical Study of Harmony" by Tchaikovsky and I had a question about this section on triads (he's working with a C Major scale):

The whole mass of major and minor triads may be grouped into three sets of two triads each:
  One, the tonic group viz: the triads on the 1st and the 6th degrees.
  Two, the dominant group viz: the triads on the 5th and the 3rd degrees.
  Three, the subdominant group viz: the triads on the 4th and 2nd degrees.

Now, I get why the 1st and 6th triad are in the tonic group. I also get why the 5th triad is in the dominant group and why the 4th triad is in the subdominant group. But, I'm having a hard time understanding why the 3rd triad is dominant and the 2nd triad is subdominant.
I'm not sure how I'd categorize them, and I suppose they have to placed somewhere, but I'm not sure why they're being placed here.
I Googled around some and found some conflicting information on Open Music Theory which has muddied the water further:

If you are already comfortable with Roman numerals, you can generally think of I, III, and VI as tonic, II and IV as subdominant, and V and VII as dominant. (Though, as you will see below, there is more to it than that.)

I suppose I'm just looking for some clarity here. It's important that I understand why Tchaikovsky is placing the 3rd and 2nd triad where he is as I keep plowing through the book. Thanks for the help!
Comment: The only thing I can think of is that, if you're creating a group of minor triads, that, in that case, the 3rd triad would take the same place that the 5th triad does in a grouping of major triads. I'm not sure that this is right, though, and I don't know how to reconcile that with the Open Music Theory entry.
Comment: Not an answer, just a comment, but in a sense, vi is the relative minor of I; ii is the relative minor of IV; and iii is the relative minor of V.
Answer: The chord built on the sixth degree of the major scale is closely related to the I chord, and similarly the chord built on the second degree is closely related to the IV chord, and the chord built on the third degree is closely related to the V chord. The I, IV, and V chords have tonic, subdominant, and dominant functions, respectively, and the vi, ii, and iii chords (sometimes called parallel chords) are sometimes called tonic-parallel, subdominant-parallel, and dominant-parallel, respectively.
In the key of C Major, the I chord contains C-E-G, and the vi chord contains C-E-A; that is, the vi chord can be formed by raising the 5th a whole step. Since the vi chord shares the root and the third of the I chord, it can function as a tonic chord. The fifth of the I chord is relatively unimportant, so you might think of the vi chord as a I6 chord. There are no other triads in the key that share the root and third of the tonic chord.
The same considerations can be applied to the ii and iii chords. In the key of C Major, the ii chord contains D-F-A, and the IV chord contains F-A-C; these share the root and third of the IV chord, so the ii chord can function as a subdominant chord. The iii chord contains E-G-B, and the dominant V chord contains G-B-D; these share the root and third of the V chord, so the iii chord can function as a dominant chord.
Comment: I thought the parallel chord of C maj was Cm, parallel of F maj was Fm, and parallel of G maj. was Gm. *Relative* might be a more appropriate term, as the relative of C is Am., relative of F is Dm., and relative of G is Em.
Comment: @Tim -- in this usage _parallel chord_ and _relative chord_ have the same meaning; the terms come from Riemannian theory. There is a link in my answer to a Wikipedia page about this. But I think the bottom line is that the **I** chord and the **iii** chord are the only two chords that share the root and 3rd of the tonic.
Comment: I=CEG, iii=EGB. Sharing three and five of the tonic? The only one sharing the root of the tonic is IV. I find it strange that the term parallel can be used here, regardless of who came up with a theory. It just sounds confusing - to me. When terms already exist, and have specific, different meanings, where's the mileage in making them both mean the same?
Comment: @Tim -- sorry, it's late and my brain is shutting down. I meant the **I** chord and the **vi** chord both share the root and third of the tonic chord, as I wrote in the answer above.
Comment: @Tim -- I don't see the terminology as confusing; it connects the **I** chord to the **vi** chord, the **IV** chord to the **ii** chord, and the **V** chord to the **iii** chord with a name that underscores their relatedness. There are loads of overlapping terms in music anyway; I think that these date from the late 1800's. The Wikipedia page suggests that the "relative" and "parallel" conflation has to do with translation from the original German.
Comment: Exactly. Relatedness sums it up. Relative. Parallels just don't ever meet, let alone have relations! It seems to be confused by translation, something I'll check on later. Just that in most other people's (apart from Riemann's) world, the two terms are absolute, and often used, with *no* confusion. He seems to have introduced some, or perhaps it's just his native language. Thanks.
Comment: My last comment! Yes, the German for 'relative key' is 'paralleltonart'. Confusion reigns! However, that spawns the questions - if the *parallel* chord of C is Am, what's the relative chord? If the *relative* key of C is Am, what's the parallel? Might this be confusing to a beginner, if it's confounded me..?
Comment: @Tim if beginners want to get confused with Riemannian theory, that's their problem (or their teacher's problem if they have one). The Tchaik theory book is historically significant as the first ever textbook on Western music theory published in Russia, but from contemporary accounts Tchaik regarded teaching theory as a boring duty, having accepted a friend's offer of the post of Prof of Music Theory at the newly opened Moscow Conservatory mainly for the salary and the prestige of the title "Professor" than for anything else.
Comment: @alephzero -- note that OP never mentioned Riemannian theory; I only used the names _dominant-parallel_, etc. because those names connect the **iii** chord to the **V** chord, etc., then mentioned Riemann in a comment when Tim wondered about the terminology. Since it wouldn't change the important part of the answer, maybe I should have left this part out if it causes confusion, though it didn't seem to for the OP.
Comment: @Tim -- I have edited to reduce references to the unsavory terms and hopefully increase clarity ;)
Comment: @DavidBowling - It probably would not cause confusion to the OP, as he's maybe never encountered terms such as that previously. ( One can't get confused with what one isn't cognisant of). OP to respond?
Comment: @alephzero - really don't think *anyone* 'wants' to get confused with anything. Sometimes it's thrust upon us! Being the 'first ever' doesn't give a lot of credence if it's not concrete enough... Who was the first to state the flatness of Earth..?
Comment: I am an absolute music theory noob, but what resonates with me in this answer is how well the parallel chords can work as substitution. Case in point is "Can't Help Falling In Love" by Elvis Presley which at least in one arrangement goes like I-iii-vi, IV-I-V. I've tried I-V-I IV-I-V instead, (as well as I-V-I ii-vi-V) and they all work perfectly well.
Answer:
Why is the third triad dominant?

It is not. The third triad is the mediant. The triad on the fifth degree is the dominant.
The selected answer is misleading about the substitute nature of the mediant triad. Apparently the answer take a Riemannian view without pointing out the ambiguous nature of the chord. The mediant chord shares two tones with the dominant chord, but it also shares two tones with the tonic. There is no clear way to simply say the mediant chord substitutes one or the other chords.
This definition from the Harvard Dictionary of Music summarizes the point well...

It should be understood that such substitutions lead toward ambiguous tonality. That is not a problem per se, but cadences won't have their proper function if chords are substituted. V iii, iii I, etc. won't work as perfect cadences.
Comment: I did not take a Riemannian point of view, and we did discuss this in the comment thread under my answer. I specifically took the point of view that the **iii** chord can (not must) function as a dominant because it contains the root and third of the **V** chord. I only mentioned _dominant-parallel_ as an existing term (which happens to come from Riemannian Theory) that describes this relationship, providing a link for anyone who would like to read more about that.
Comment: My point is to make clear the _ambiguity_.
Comment: I agree that there is some ambiguity, as there is likely to be with substitutions, but the **iii** chord contains the root and third of the **V** chord, yet contains  only the third and fifth of the **I** chord. This would seem to make it less likely that the **iii** would find itself in the role of the tonic.
Comment: ...and if we return to the Harvard Dictionary article we see that kind of isolated determination is a problem. The substitute character of either tonic or dominant isn't about those chord tone comparisons, but _about the mediant chord's use in the surrounding harmonic context_. Basically, it's problematic to simply say `iii` subs for `V`
Comment: Probably the best example I can think of now is a deceptive progression like `V4/2 iii`, if the `iii` was indeed simply a sub for `V` that kind of deceptive progression wouldn't be sensible. In that harmonic context `iii` clearly isn't acting as a dominant.
Comment: Of course, context is always important, however, I never said that **iii** simply is a sub for **V**, or that **iii** will always function as a dominant. The article you cite says: "The _chief_ substitute for each of the three principal triads is its relative minor; thus... III for V...." This is what was suggested in my last comment ("_less likely_ that the **iii** would find itself in the role of the tonic.") As I said, I agree that there is some ambiguity, and good of you to point this out.
Comment: After the introductory stuff you concluded "so the iii chord can function as a dominant chord" with no mention of possible tonic substitution and the ambiguity, nor mention of the importance of context. The problem is using such an answer as the basic *to close duplicate questions*.
Comment: Yes, I said _can_, not _must_ or _always_. That is correct, and the duplicate question was "are there cases where the mediant chord has a dominant function." The answer is yes, and I don't see any way in which this question is not a duplicate of that one. Also, it is not the _answer_ which is the basis of the closure, but the _question_. Others are free to post additional answers here, as you have.

Why is the third triad dominant?