text:
Q: undefined, how you work? Just a simple question :)
if I have :
var user = {'name': 'Fred'};

So
console.log(user.name); // Fred
console.log(user.age); // undefined

But
console.log(test); // ReferenceError: test is not defined

I don't understand why because for me it's the same as
console.log(window.test); // undefined

In my project, i try to check if a global variable exist but I have a referenceError... I don't really understand why the followinf code doesn't work...
if (TestGlobal) // ReferenceError: TestGlobal is not defined
   console.log(' allo 1 ');

if (typeof(TestGlobal ) !== 'undefined') // Ok
   console.log(' allo 1 ');

A: …and a simple answer:

*

*Property references always evaluate to their value or the undefined value if the key does not exist, as long as the base value is not undefined (then a TypeError would be thrown).

*Variables throw ReferenceErrors if not defined before, unless they are used with the  typeof keyword (where they just evaluate to "undefined").


text:
Q: Keyboard appears twice when UITextField becomes first responder after custom segue performed So the problem is: when I push a button on a source view the custom segue performed.
Here is the code (pretty standard):
class FirstCustomSugue: UIStoryboardSegue {
override func perform() {

    let initalView = self.source.view as UIView?
    let destinationView = self.destination.view as UIView?

    let screenHeight = UIScreen.main.bounds.size.height
    let screenWidth = UIScreen.main.bounds.size.width

    initalView?.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
    destinationView?.frame = CGRect(x: screenWidth, y: 0, width: screenWidth, height: screenHeight)

    let appWindow = UIApplication.shared.keyWindow
    appWindow?.insertSubview(destinationView!, aboveSubview: initalView!)

    UIView.animate(withDuration: 0.4, animations: {
        // Left/Right
        initalView?.frame = (initalView?.frame.offsetBy(dx: -screenWidth, dy: 0))!
        destinationView?.frame = (destinationView?.frame.offsetBy(dx: -screenWidth, dy: 0))!
    }) { (Bool) in
        self.source.present(self.destination, animated: false, completion: nil)
    }
}

}
I call myTextField.becomeFirstResponder() in viewDidiAppear (call to super is included).
When I set a simulator's «Slow animations» On I can clearly see that keyboard first appears alongside the animation and after animation is complete it reappears.
I included the example а the segue because when I switch to the standard segues there is no such problem. If you need any other code example I will update a post.
Using custom segues because I am not using navigationController for views I transition between and default modal segues are not an option.
My guess is that viewDidAppear is called twice, because even when I set myTextField.isUserInteractionEnabled = false and myTextField.isEnabled = false in viewWillAppear or viewDidLoad (before or after the super in both methods) and then setting those to true in viewDidAppear right after call to super the result is the same.
TNX in advance!

A: Changed segue's perform to the following:
    let sourceViewController = self.source
    let destinationViewController = self.destination

    let transition = CATransition()

    transition.duration = 0.5
    transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    transition.type = kCATransitionMoveIn
    transition.subtype = kCATransitionFromRight

    let appWindow = UIApplication.shared.keyWindow
    appWindow?.layer.add(transition, forKey: kCATransition)

    sourceViewController.present(destinationViewController, animated: false, completion: nil)ere

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django forms: How to simply include all attributes in the associated model I am working through how to use Django's forms (https://docs.djangoproject.com/en/1.11/topics/forms/#more-on-fields) and I can't see a way to generate a form structure that is based on a defined Model. In Symfony, I remember I was able to get my form to automatically include all parameters of myModel (for example) even if any new attributes were later added to the model.
For example:
class myModel(models.Model):
    name = models.CharField(max_length=50)
    created=models.DateTimeField(null=False)
    modified=models.DateTimeField(null=True)
    myParameter= models.IntegerField(default=None)
    // ... plus many more parameters

Rather than having to manually type corresponding rows into my class myModelForm(forms.Form):, I'm looking/hoping for a 'catch all'.

A: from django.forms import ModelForm

class myModelForm(ModelForm):
    class Meta:
        model = myModel
        fields = '__all__'

More details selecting-the-fields-to-use


text:
Q: Apache Beam: Wait for AvroIO write step is done before start ImportTransform Dataflow template I'm using apache beam to create a pipeline where basically reads an InputFile, Convert to Avro, write the AvroFile to a bucket and then Import these avro files to Spanner using Dataflow template
The problem that I'm facing is that the last step (Import the Avro files to the Database) is starting before the previous (write Avro Files to the bucket) is done.
I tried to add the Wait.on function but that only works if returns a PCollection, but when I write the files to avro it returns PDone.
Example of the Code:
// Step 1: Read Files
PCollection<String> lines = pipeline.apply("Reading Input Data exported from Cassandra",TextIO.read().from(options.getInputFile()));

// Step 2: Convert to Avro
lines .apply("Write Item Avro File",AvroIO.writeGenericRecords(spannerItemAvroSchema).to(options.getOutput()).withSuffix(".avro"));

// Step 3: Import to the DataBase

pipeline.apply( new ImportTransform(
                spannerConfig,
                options.getInputDir(),
                options.getWaitForIndexes(),
                options.getWaitForForeignKeys(),
                options.getEarlyIndexCreateFlag()));

Again, the problem is because step 3 starts before Step 2 is done
any ideas?

A: This is a flaw in the API, see, e.g. a recent discussion on this on the beam dev list. The only solutions for now are to either fork AvroIO to return a PCollection or run two pipelines sequentially.


text:
Q: Sendgrid to stop changing plain text links? How to tell sendgrid to stop decorating plain text URLs?
Using sendgrid SDK for Python, if that matters.
sendgrid.SendGridClient(username, pwd)
mail = sendgrid.Mail()
mail.set_html(html_message)
mail.set_text(text_message_with_urls)  # <-- urls are here
...
sendgrid_client.send(mail)

For HTML-side this already has an answer:
Is it possible to exclude links from tracking
Tracking still needed for HTML parts of mails.

A: I contacted support and they informed me that I could use Clicktrack SMTP filter with the X-SMTPAPI header.
There are two filter options, one is the enable and disable the click-tracking setting and the other for enabling or disabling click-tracking links in the Plain-Text portion of the message.
The Sendgrid Python client has helper class ClickTracking to control these settings:
import json
import os

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import *

sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
from_email = Email("team@example.com")
to_email = To("test@example.com")
subject = "Sending with ClickTracking plain text disabled"
content = Content(MimeType.text, "Test URL: https://www.google.com")
message = Mail(from_email, to_email, subject, content)

tracking_settings = TrackingSettings()
tracking_settings.click_tracking = ClickTracking(enable=True, enable_text=False)
message.tracking_settings = tracking_settings

response = sendgrid_client.send(message=message)
print(response.status_code)

A flask-mail example setting the `X-SMTPAPI' header with clicktrack filter:
from flask_mail import Mail
from flask_mail import Message

mail = Mail(app)
subject = "Sending with clicktrack plain text disabled"
body = "Test URL: https://www.google.com"
headers = {"X-SMTPAPI": json.dumps({
  "filters" : {
    "clicktrack" : {
      "settings" : {
        "enable" : 1,
        "enable_text" : False
      }
    }
  }
})}
message = Message(subject=subject, body=body, extra_headers=headers)
mail.send(message)

A: You can disable click tracking in settings: Disable clicktracting in sendgrid
This feature is there to track clicks as the name says. By default sendgrid also adds An invisible image is being appended to HTML emails to track if they have been opened.


text:
Q: Error putting S3 notification configuration When I try to create a aws_s3_bucket_notification I get this terrerform exception: aws_s3_bucket_notification.input_notification: Error putting S3 notification configuration: InvalidArgument: Unable to validate the following destination configurations
    status code: 400, request id: 4E17F794B9BC67C9, host id: QmeEFS+T1cvr1xFEMmAlqBKxzX1Fg+qOpwJFXDl4sR1hVcHa4swLN87BiPI8BToGuNQ3oYD0pYk= As for as I can tell I have followed the specs outlined in the terraform docs here: https://www.terraform.io/docs/providers/aws/r/s3_bucket_notification.html
Has anyone else had this problem before?
resource "aws_sqs_queue" "sqs_queue" {
  name = "${var.env}-${var.subenv}-${var.appname}"
  delay_seconds = 5
  max_message_size = 262144
  message_retention_seconds = 86400
  receive_wait_time_seconds = 10
  visibility_timeout_seconds = 90
  redrive_policy = "{\"deadLetterTargetArn\":\"${aws_sqs_queue.sqs_dlq.arn}\",\"maxReceiveCount\":${var.sqs_max_receive_count}}"

  policy = <<POLICY
  {
    "Version": "2012-10-17",
    "Statement": [
      {
        "Effect": "Allow",
        "Principal": "*",
        "Action": "sqs:SendMessage",
        "Resource": "arn:aws:sqs:*:*:s3-event-notification-queue",
        "Condition": {
          "ArnEquals": { "aws:SourceArn": "${aws_s3_bucket.input.arn}" }
        }
      }
    ]
  }
  POLICY
}

resource "aws_s3_bucket" "input" {
  bucket = "${var.env}-${var.subenv}-${var.appname}-input"
}

resource "aws_s3_bucket_notification" "input_notification" {
    depends_on = [
        "aws_s3_bucket.input",
        "aws_sqs_queue.sqs_queue"
  ]

  bucket = "${aws_s3_bucket.input.id}"

  queue {
    queue_arn     = "${aws_sqs_queue.sqs_queue.arn}"
    events        = ["s3:ObjectCreated:*"]
    filter_suffix = ".gz"
  }
}

A: The SQS policy was wrong, it should look like this:
resource "aws_sqs_queue" "sqs_queue" {
  name = "${var.env}-${var.subenv}-${var.appname}"
  delay_seconds = 5
  max_message_size = 262144
  message_retention_seconds = 86400
  receive_wait_time_seconds = 10
  visibility_timeout_seconds = 90
  redrive_policy = "{\"deadLetterTargetArn\":\"${aws_sqs_queue.sqs_dlq.arn}\",\"maxReceiveCount\":${var.sqs_max_receive_count}}"

  policy = <<POLICY
  {
    "Version": "2012-10-17",
    "Statement": [
      {
        "Effect": "Allow",
        "Principal": "*",
        "Action": "sqs:SendMessage",
        "Resource": "arn:aws:sqs:*:*:${var.env}-${var.subenv}-${var.appname}",
        "Condition": {
          "ArnEquals": { "aws:SourceArn": "${aws_s3_bucket.input.arn}" }
        }
      }
    ]
  }
  POLICY
}


text:
Q: Continuous/discontinuous decomposition of local martingales Continuing from my previous question Decomposition of semimartingales,
In his answer, George Lowther mentioned that if $X$ is a local martingale, then $X^d$ and $X^c$ in its decomposition
$X_t - X_0 = X_t^d + X_t^c$
(where $X^c$ is the continuous local martingale part of $X$ and $X^d$ is the purely discontinuous semimartingale part) are in some sense orthogonal to each other.
Q1: In what sense? Can we say $X^d$ and $X^c$ are independent of each other?
Q2: What about the special case where
(1) $X^c$ is locally square integrable with respect to the filtration generated by a standard Brownian motion $W$ and, hence, can be written
$X_t^c - X_0^c = \int_0^t \! H_u \, \mathrm{d}W_u,$
where $H$ is predictable, and
(2) $X_t^d \equiv \sum_{0\leq u\leq t}\Delta X_u.$
Can we say anything about the independence between $H$, $W$, or $X^d$?

A: Q1: The orthogonality term introduced in this context is just a definition, i.e. two local martingales $M$ and $N$ are said to be orthogonal if $MN$ is a local martingale. I guess the term comes from the fact that if $M,N\in\mathcal{H}^2$ ($\mathcal{H}^2$ being the set of square integrable martingales) then $M$ and $N$ are orthogonal in this sense if and only if for every stopping time $\tau$, $M^\tau$ and $N-N_0$ is orthogonal in $\mathcal{H}^2$ (seeing $\mathcal{H}^2$ as a Hilbert space with inner product $(M,N)=E[M_\infty N_\infty]$).
As to whether $X^d$ and $X^c$ are independent, I'm pretty sure that this isn't the case. One can show that if $M,N\in\mathcal{H}^2$ then $M$ and $N$ are orthogonal if and only if $\langle M,N\rangle=0$, where $\langle M,N\rangle$ denotes the predictable quadratic covariation/sharp-bracket process. But $\langle M,N\rangle =0$ does not imply $M$ and $N$ being independent.


text:
Q: What is wrong in this proof of existence of the improper integral $\int_{y=1}^{\infty}\frac{\sin y}{y^2}dy$ So I want to prove whether the improper integral in title exists or not. Now existence of $\int_{y=1}^{\infty}\frac{\sin y}{y^2}dy  $ is as good as existence of the limit $\lim_{N\to \infty}\int_{y=1}^{N}\frac{\sin y}{y^2}dy$. We have,  $|\int_{y=1}^{N}\frac{\sin y}{y^2}dy|\le1-1/N \; \;\forall N\gt 1$
Therefore,$ \int_{y=1}^{N}\frac{\sin y}{y^2}dy$ is bounded and hence the integral in title converges.
But as per the solution, this integral diverges. Can you please help? Thanks a lot in advance.

A: Your solution would be correct if you were integrating a non-negative function. But you have only proved that $n\mapsto\int_1^n\frac{\sin y}{y^2}\,\mathrm dy$ is bounded, not that it converges. However, the integral converges. I would prove that it converges absolutely:$$\int_1^\infty\left|\frac{\sin y}{y^2}\right|\,\mathrm dy\leqslant\int_1^\infty\frac1{y^2}\,\mathrm dy=1.$$


text:
Q: Silverlight DataPager - Split Into 3X3? I have a ListBox bound to an observable collection.
I also have a data pager bound to the itemsource of the list box.
I currently have the data pager set to only show up to 3 rows.
How would I go about changing the style ListBox style (or something else) such that I could have a 3X3 display?  For example, the first three items in my observable collection would be displayed on the first row of the list box, horizontally next to each other, then the next row would contain the next three items in the observable collection?
Any info would be greatly appreciated.
Thanks.
Chris

A: It sounds like you want to use an ItemsControl with a WrapPanel (from the Silverlight Toolkit) in the ItemsPanelTemplate.
    <ItemsControl xmlns:controls="clr-namespace:Microsoft.Windows.Controls;assembly=Microsoft.Windows.Controls">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <controls:WrapPanel/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>

Here's a short tutorial about the WrapPanel: http://blogs.silverlight.net/blogs/justinangel/archive/2008/11/05/silverlight-toolkit-wrappanel.aspx


text:
Q: Pass object to directives without watching them Generally we use the = to make two-way data binding when creating directives, for example:
app.module('main')
    .directive('dirTest'[function(){
        return {
            scope:{
                data:'='
            }
        }
    }])

Then we can use
<dir-test data="xx.data"></dir-test>

To pass the xx.data object to the directive, but it seems that this will make angular watch this expression.
This may be a waste of time once I do not care the change of the data or the data can hardly change.
Which means I need a one-way one-time data passwed to the directive, is this possible?

I ask this question because when I open the Batarang console, I found the regularinterceptedexpression cost too long and watch a lot of watchers. I think the page may run fast if I can remove some unused watchers.
I know there is a one-way from dom to directives by using @, however it seems that it just support string.

A: In angularjs if you create a directive with scope '@' then it will be Text bindings,which means you will be able to get the value of expression but making changes to it won't reflect back to the html page.so i believe if you create the directive in with scope @ then it will do a job for you.
app.module('main')
    .directive('dirTest'[function(){
        return {
            scope:{
                data:'@'
            }
        }
    }]

)
<dir-test data={{xx.data}}></dir-test>

A: It is possible, however you will need to eval data attribute and clone object yourself. The scope of this evaluation is going to be scope.$parent because this is the scope where the data comes from. If your directive doesn't need isolated scope (so you don't use scope config in the directive) then the attribute should be evaluated in the scope:
.directive('dirTest', [function() {
    return {
        scope: {
            something: '=' // something that might need two-way binding
        },
        link: function(scope, element, attrs) {
            scope.data = angular.copy(scope.$parent.$eval(attrs.data));
        }
    }
}]);

Demo: http://plnkr.co/edit/nDzqWaVH9QkluFJknOfy?p=preview

A: You can use Angular's one-time binding:
<dir-test data="::xx.data"></dir-test>

Note that it is available in Angular 1.3+. have a look at this article for more details: http://blog.thoughtram.io/angularjs/2014/10/14/exploring-angular-1.3-one-time-bindings.html


text:
Q: Unity3D debug magically removes NullReferenceException? A friend of mine, which in a programmer too, has got stuck in some really weird stuff... I can't really explain it, because this code:
try {
   result = chunks.Find (delegate(float[] fa2) {
//                                            Debug.Log("fa2: " + fa2);
//                                            Debug.Log("fa: " + fa);
       return fa2[0] == fa[0] && fa2[1] == fa[1] && fa2[2] == fa[2];
   });
}
catch (Exception e) {
   Debug.LogError("result1: " + e);
}

Returns
result1: System.NullReferenceException: Object reference not set to an instance of an object
 at March+<BuildLand>c__AnonStorey0.<>m__3 (System.Single[] fa2) [0x00009] in C:\Users\Roy\Documents\March\Assets\Scripts\March.cs:262
 at System.Collections.Generic.List`1[System.Single[]].GetIndex (Int32 startIndex, Int32 count, System.Predicate`1 match) [0x00000] in <filename unknown>:0
 at System.Collections.Generic.List`1[System.Single[]].Find (System.Predicate`1 match) [0x00000] in <filename unknown>:0
 at March.BuildLand () [0x0012c] in C:\Users\Roy\Documents\March\Assets\Scripts\March.cs:257

But if you uncomment the debug lines, it works.
Can anyone clarify this, please? Thanks for your help!

A: It looks like your code is getting a null reference exception, by using the try-catch statement your telling your program to ignore the error and continue running.
The catch statement catches the error and allows you to handle the error however you see fit. In your case, your error handling is just writing the error to the log.
By commenting out the Debug statement your not handling your error at all. Your essentially completely ignoring that block of code if and when an error occurs. Sometimes the program can "appear" to still run properly if that block of code doesn't have any dependencies.
However you should track down your null reference exception and resolve it or face the wrath of unintended consequences.


text:
Q: PreparedStatement and DateTime I am trying to use DateTime from the Joda library and I realized that PreparedStatements doesn't support DateTime. What can I do instead? I can set TimeStamp but that's not really what I want. Is there a workaround or do I have to use TimeStamp? In my MySQL database I have also chosen DateTime as the type.
      DatabaseConnection dbConnect = new DatabaseConnection();
      PreparedStatement query =dbConnect.getConnect().prepareStatement(sql);

      query.setInt(1, c.getMemberId());
      query.setDateTime(2, c.getStartDate());
      query.setDateTime(3, c.getEndDate());

A: setDate(java.sql.Date) seems like what you're looking for:
 query.setDate(2, new java.sql.Date(c.getStartDate().getMillis());

A: In your PreparedStatement, call the toDate() method on your DateTime objects.
If you are not interested in times, you might as well change your database columns to DATE.


text:
Q: MsysGit gets differend look&feel depending on, how it is called When I start msysgit (C:\msysgit\msysgit\msys.bat) from its directory, it has an other visual settings, as when I start it over a shortcut in the Quick Launch.

Why? How can I change it?

A: Right click the Quick Launch shortcut and select Properties. You should be able to adjust visual styles like Font, Layout, Colors from there.
If you directly run msys.bat it will use whatever defaults your cmd is set to.


text:
Q: How to backup and access iOS Safari's reading list? I have an iPhone, with iOS 7. In Safari, I have a lot of pages saved in the reading list.
How can I backup the reading list to a computer and then access it ?
On a PC, I have a backup of my iPhone. I have explored the backup with iBackup Viewer, free version, on Windows. I have managed to access the open tabs of Safari. But I don't find the reading list.

A: Assuming you have your backup under $backup_dir, the reading list is stored in the sqlite database file $backup_dir/Library/Safari/Bookmarks.db, under the table bookmarks.
This table also contains favourites, which can be distinguished from reading list bookmarks by the fact they have no value for the column extra_attributes. Therefore, we can use the following query:
select url,title
from bookmarks
where url not like '' and extra_attributes not like '';

To import these in browsers, we can transform the entries into Netscape Bookmark File Format. You can use, for example, the following AWK script:
#!/usr/bin/awk -f

BEGIN { print \
    "<!DOCTYPE NETSCAPE-Bookmark-file-1>\n" \
    "\n" \
    "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">\n" \
    "<TITLE>Bookmarks</TITLE>\n" \
    "
Bookmarks
\n" \
    "

"
}
/^[[:space:]]*$/ { next }
{
    split($0, parts, "|")
    url = parts[1]
    title = separator = ""
    for (i=2; i in parts; i++) {
        title = title separator parts[i]
        separator = "|"
    }
    print "
" title ""
}
END { print "

" }

In sum, you can do all this with the following bash "one-liner":
echo "
select url,title
from bookmarks
where url not like '' and extra_attributes not like '';
" | \
sqlite "$backup_dir"/Library/Safari/Bookmarks.db | \
./"$awk_script" > bookmarks.html


text:
Q: Why didn't Doctor Strange wind back the clock way before Thanos got any of the Infinity Stones? Why didn't Doctor Strange wind back the clock way before Thanos got any of the Infinity Stones?

A: Because it was not a winning scenario. In Avengers: Infinity War we see Doctor Strange look into the future to see outcomes of the possible conflicts and saying they only win one. Considering the amount of possibilities he looks at it is highly likely at least one involved rewinding time.

Doctor Strange: [panting] I went forward in time to view alternate futures. To see all the possible outcomes of the coming conflict.
Peter Quill: How many did you see?
Doctor Strange: 14,000,605.
Tony Stark: How many did we win?
[Strange stares intently at Tony for a moment]
Strange: [pause] One.
Avengers: Infinity War

At the end of the film Strange then comments to Tony the following:

Doctor Strange: [calmly turns to Stark] Tony, there was no other way.
Avengers: Infinity War

Adding both of these together we see that the outcome at the end of Infinity War was the only solution Strange saw for beating Thanos.
It's also not known how much power Doctor Strange can harness from the Time Stone and so it isn't known if he could wind time back for the entire universe.


text:
Q: Is liquibase support kerberos authentication with oracle database connection? Is liquibase support kerberos authentication with oracle database connection?
We are using liquibase node package with version 1.0.1.
If kerberos authentication support with liquibase then please provide details how to use it with oracle database connection.

A: I don't believe Liquibase supports Kerberos authentication.
There's even a Jira ticket to Include kerberos authentication in Liquibase, but it's still open and there was no activity yet.
UPDATE (Nov 2021)
Looks like the situation has changed and liquibase now do support kerberos.
Check out Connecting to an Oracle Database with Liquibase via Kerberos and Active Directory article


text:
Q: Windows 8 remote desktop I got a workstation here in a private network running Windows 8 Pro. This computer is used to test new features or Metro applications. The users connect via remote desktop and that works pretty fine so far.
My problem is now, that if a user is already connected to the workstation, he will be kicked off if another user connects. In older versions there was an option that the current user gets a message to accept or decline.
After hours of searching I couldn't find a solution for Windows 8. How do I solve this problem, or isn't it possible anymore?

A: Windows 8 does not offer multiple RDP sessions out of the box. In older OS'es you could buy more Terminal Services (TS) Client Access Licenses (CALs) and Windows Server 2003 had two by default.
There is however a way to set up multiple RDP connections which I found in an answer to Super User question How do I enable terminal services on Windows 8?.


text:
Q: Vlookup using wildcards in indexed column I know how to use a wildcard with Vlookup on the reference value, but what about on the matched column index?
I know you can do for instance VLOOKUP("*Hello*",A4:G4,2,FALSE)
However, what if you wanted to match a cell that is "Hello", with another one that is "Why, Hello there!" (so the opposite i suppose)
My data is set in a way where a macro is going to ask if A4 in workbook 1 matches C2:C25000 in workbook 2 to return the corresponding value in D back to workbook 1. The thought is that when A4 in workbook 1 says Its DHS Here, that I could input a value such as DHS in column C in workbook 2 and have it say its a match.
Is this possible?

A: The key is to bild the lookup value by concatenating *'s, like this
=VLOOKUP("*"&A4&"*",'[workbook 2.xlsx]Sheet1'!$C$2:$D$25000,2,0)

(adjust sheet name to suit)

A: Since you are already planning on using a macro, what is the possibility of using an add-on? From my understanding, you are looking for fuzzy lookup. Excel created an add-on to accomplish this task found here.

A: I've run into this problem many time.  You need put the wildcard phrase in a different cell.
Cell B1 has this in the cell:  *Hello*
Your new formula:  VLOOKUP(B1,A4:G4,2,FALSE)
It should work now.

A: My understanding is that the "lookup value" could be "Why, Hello There!" or "DHS Here" and you want that to match respectively with "Hello" and "DHS" in the lookup range.
Given that then for a formula approach try the following:
=LOOKUP(2^15,SEARCH(C2:C25000,A4)/(C2:C25000<>""),D2:D25000)
Where A4 is the lookup value, insert workbook/worksheet references as required.
That will find the last "match" in C2:C25000, for first match you can use
=INDEX(D2:D25000,MATCH(1,INDEX(ISNUMBER(SEARCH(C2:C25000,A4))*(C2:C25000<>""),0),0))
Note: either of those could match partial "words" so if A4 is "Rat catcher" that might match with "cat" or "catch" as well as "rat" - you can add in spaces to force the match to be with whole words only, e.g. first formula can be addapted to:
=LOOKUP(2^15,SEARCH(" "&C2:C25000&" "," "&A4&" ")/(C2:C25000<>""),D2:D25000)
although that assumes all words separated by spaces with no punctuation.....


text:
Q: How do I call this method that registers device I do not know how to replace "method" with the following app delegate method.
viewcontroller
[(AppDelegate *)[[UIApplication sharedApplication] delegate] method];

appdelegate
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
    TUPushHelper * helper = [[TUPushHelper alloc] initWithTokenData:devToken];
    [helper registerDevice];
}

A: You do not need to call it programmatically. The delegate receives this message after the registerForRemoteNotificationTypes: method of UIApplication is invoked and there is no error in the registration process. didFailToRegisterForRemoteNotificationsWithError: will be called otherwise.
To register your device for remote push notifications you have to do this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
...
}

Edit:
Check Apple Guide for APNS here
also check out this tutorial


text:
Q: Creating a IEqualityComparer> I'm using xUnit and it doesn't have a way to determine if 2 IEnumerable<T> are equal if T is custom type.
I've tried using LINQ SequenceEqual but again as the instances of T are different this returns false;
Here is a basic test with a non-working IEqualityComparer
    [Fact]
    public void FactMethodName()
    {
        var one = new[] { new KeywordSchedule() { Id = 1 } };
        var two = new[] { new KeywordSchedule() { Id = 1 } };

        Assert.Equal(one, two, new KeywordScheduleComparer());
    }

public class KeywordScheduleComparer : IEqualityComparer<IEnumerable<KeywordSchedule>>
{
    public bool Equals(IEnumerable<KeywordSchedule> x, IEnumerable<KeywordSchedule> y)
    {
        return Object.ReferenceEquals(x, y) || (x != null && y != null && x.SequenceEqual(y));
    }

    public int GetHashCode(IEnumerable<KeywordSchedule> obj)
    {
        if (obj == null)
            return 0;

        return unchecked(obj.Select(e => e.GetHashCode()).Aggregate(0, (a, b) => a + b));  // BAD
    }
}

I'm using this in an integration test, so I insert data from a IEnumerable into a DB at the start, then call my SUT to retrieve data from DB and compare.
If you can help me get a collection comparison working I'd appreciate it!

A: I just verified that this works fine with xUnit.net 1.9.2:
public class MyClass
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class MyClassComparer : IEqualityComparer<MyClass>
{
    public bool Equals(MyClass x, MyClass y)
    {
        return x.ID == y.ID;
    }

    public int GetHashCode(MyClass obj)
    {
        return obj.ID.GetHashCode();
    }
}

public class ExampleTest
{
    [Fact]
    public void TestForEquality()
    {
        var obj1 = new MyClass { ID = 42, Name = "Brad" };
        var obj2 = new MyClass { ID = 42, Name = "Joe" };

        Assert.Equal(new[] { obj1 }, new[] { obj2 }, new MyClassComparer());
    }
}

So I'm not 100% clear why you need the extra comparer. Just the single comparer should be sufficient.

A: Well, your implementation is pending. You implemented custom comparer for IEnumerable<KeywordSchedule> but forgot to implement the same for KeywordSchedule.
x.SequenceEqual Still uses Comparer<T>.Default so it goes for reference comaprison and hence result is false.
public class KScheduleComparer : IEqualityComparer<KeywordSchedule>
{
    public bool Equals(KeywordSchedule x, KeywordSchedule y)
    {
        return x.Id == y.Id;
    }

    public int GetHashCode(KeywordSchedule obj)
    {
        return obj.GetHashCode();
    }
}

Then modify your Equals method in KeywordScheduleComparer class as below
public class KeywordScheduleComparer : IEqualityComparer<IEnumerable<KeywordSchedule>>
{
    public bool Equals(IEnumerable<KeywordSchedule> x, IEnumerable<KeywordSchedule> y)
    {
        return Object.ReferenceEquals(x, y) || (x != null && y != null && x.SequenceEqual(y, new KScheduleComparer()));
    }

    public int GetHashCode(IEnumerable<KeywordSchedule> obj)
    {
        if (obj == null)
            return 0;

        return unchecked(obj.Select(e => e.GetHashCode()).Aggregate(0, (a, b) => a + b));  // BAD
    }
}

A: You could do this more elegantly using FluentAssertions library. It has plenty assertion methods for collections.
public class MyClass
{
    public int ID { get; set; }
    public string Name { get; set; }

    protected bool Equals(MyClass other)
    {
        return ID == other.ID;
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != GetType()) return false;
        return Equals((MyClass) obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return (ID*397) ^ (Name != null ? Name.GetHashCode() : 0);
        }
    }
}

public class ExampleTest
{
    [Fact]
    public void TestForEquality()
    {
        var obj1 = new MyClass { ID = 42, Name = "Rock" };
        var obj2 = new MyClass { ID = 42, Name = "Paper" };
        var obj3 = new MyClass { ID = 42, Name = "Scissors" };
        var obj4 = new MyClass { ID = 42, Name = "Lizard" };

        var list1 = new List<MyClass> {obj1, obj2};
        list1.Should().BeEquivalentTo(obj3, obj4);
    }
}


text:
Q: How to replace identical consecutive values from a 1D array efficiently Surprisingly, after a fair bit of research, I did not find any post sparking a good idea to solve this simple problem.
I have a 1D numpy array of shape (n, ) which is mostly zeros with a few other positive values.
D = np.zeros(10)
D[2] = 1
D[5] = 4
D[7] = 3

Out: array([0., 0., 1., 0., 0., 4., 0., 3., 0., 0.])

However, sometimes, one of the values (which is a trigger at the given sample) might be repeated during the next (or few next samples).
D = np.zeros(10)
D[2] = 1
D[3] = 1
D[5] = 4
D[7] = 3

Out: array([0., 0., 1., 1., 0., 4., 0., 3., 0., 0.])

In this case, I want to process the array to replace the identical consecutive values by 0; in this case, to replace the second 1 by 0.
In: array([0., 0., 1., 1., 0., 4., 0., 3., 0., 0.])
Out: array([0., 0., 1., 0., 0., 4., 0., 3., 0., 0.])

For one additional complexity level, I would like to define a tolerance, and if every element right after a value x>0 is close enough to x, then they get replaced by 0.
In: array([0., 0., 1., 0.98, 1.01, 4., 0., 3., 3.1, 0.]), tolerance = 0.05
Out: array([0., 0., 1., 0., 0., 4., 0., 3., 3.1, 0.])

This is fairly easy to do by looping on the array with either a while or a for loop. However, as this is for an online application, I was looking for a vectorized solution in numpy. If anyone has any suggestion, any function I could look at to do this as efficiently as possible, please comment!

A: Try using np.diff() like so:
D[np.where(np.diff(D)==0)] = 0

Edit: Including OP's solution to include tolerance and prepend:
D[np.where(np.diff(D, prepend=[0])<=tolerance)] = 0

Edit 2: @obchardon's excellent suggestion to remove the unnecessary np.where:
D[abs(np.diff(D, prepend=[0]))<=tolerance] = 0


text:
Q: Cannot construct instance of `{dataclass}, problem: Should never call `set()` on setterless property "authors" is my collection in MongoDB.
my schema
authors = [
{

name: "Author1",
books: [

{title:"Book1"},
{title:"Book2"}

]
}
]

I'm trying to append the books array by adding another book object (book3). Before that, I have to check whether there exists an object already in the author's name. So I have the findOneByAuthorname function.
My issue is that every time I try to call the findOneByAuthorname function. I get an error
  - Unhandled: POST - /v1/api/addBooks. Exception class com.fasterxml.jackson.databind.exc.ValueInstantiationException:  Cannot construct instance of `com.sample.models.schema.Author`, problem: Should never call `set()` on setterless property ('books')

I'm using postman for the post request and passing a JSON object {title: "book3"}.
My code :
    @kotlinx.serialization.Serializable
    data class Author ( val name: String , val books : MutableList<Bookitem>)
    @kotlinx.serialization.Serializable
    data class Bookitem (val title :String)

    private var collection : CoroutineCollection<Author> = MongoConfig.getDatabase().getCollection("authors")

    suspend fun findOneByAuthorname(Name:String) : Author {
    collection.findOne(Author::name eq Name)
}
    suspend fun addBooks(Name:String,book:Bookitem) : Bookitem?{

    collection.findOneandUpdate(Author::name eq  Name, ,push(Author::books ,Bookitem(book)))
}

I have added the relevant details ( or that I feel are relevant here). Find function works if I disregard the books dataclass completely. If any more details is required, kindly mention in the comments and I'll add. Any help is appreciated.

A: I solved this by changing the variable type of books: MutableList<Bookitem> from var to val. Since objects are added this is the way to declare it.
Still, I'm not able to understand what the error message means.


text:
Q: TSQL Merge Insert With Duplicate   I have a table that has duplicate email address, I need to insert just one of them into a temp a temp table along with two other fields. there are many example here but I can get any of them work,
I ended up looking into MERGE I get the same results. All the record are getting inserted I'm at a lost. I tried many different samples but it always insert all the records. I went back to make sure the email address are really dupes and they are.. Below is were I'm at now..
MERGE #EmailTable2 AS Target
USING (SELECT EMAIL, NAME, JOB_TITLE FROM b2b_cmas_list$ WHERE EMAIL IS NOT NULL) AS Source
ON (Target.EMAIL = Source.EMAIL)
 WHEN NOT MATCHED BY TARGET THEN
    INSERT (EMAIL, NAME, JOB_TITLE)
    VALUES (Source.EMAIL, Source.NAME, Source.JOB_TITLE)

OUTPUT $action, inserted.*, deleted.*;

so any help in getting this correct would be helpful.

A: This it not working because SQL doesn't know, which of the two rows containing the same e-mail you want to choose. I mean: if EMAIL is the same, which of pair (NAME and JOB_TITLE) are important and which can be discarded?
Some hints:

*

*If it doesn't matter which item is chosen simply group by EMAIL selecting MAX(NAME) and MAX(JOB_TITLE), i.e.
select EMAIL, max(NAME), max(JOB_TITLE) from b2b_cmas_list$ group by EMAIL
Be warned however that this can mangle NAME-JOB_TITLE pairs (as max is selected).

*Try using ROW_NUMBER() OVER() to arbitrarilly select 1st row in each group.

*Use a CURSOR to iterate over rows and skip duplicates.

*Use .NET CLR aggregate to i.e. concat names and job titles for same e-mail.
And a little note to your MERGE statement. This is not working as expected, because SQL checks all rows at once, and not row-by-row. So it is not that if one e-mail. ie. "a@a.com" is inserted, then another won't. It only matters if "a@a.com" is in the table at the beginning of the statement.


text:
Q: Finding the limit of $\lim_{n \to \infty} \frac{n^3}{(3n)!^\frac{1}{n}}$ How can one find this limit:
$$\lim_{n \to \infty} \frac{n^3}{(3n)!^\frac{1}{n}}$$
Hospitals is out of the question, in this case, because n! is not a differentiable function.

A: Consider the power series
$$
\sum_{n=0}^\infty a_nz^n,\qquad\mbox{where}\quad a_n:=\frac{n^{3n}}{(3n)!},
$$
and let $R$ be the radius of convergence. Then
$$
\frac{1}{R}=\lim_{n\to\infty}\frac{a_{n+1}}{a_n}=\lim_{n\to\infty}\sqrt[n]{a_n}=\lim_{n\to\infty}\frac{n^3}{(3n)!^\frac{1}{n}}.
$$
Now, the first limit it easy to calculate. We have
$$
\frac{a_{n+1}}{a_n}=\frac{(n+1)^{3n+3}(3n)!}{(3n+3)!n^{3n}}=\left(1+\frac{1}{n}\right)^{3n}\cdot\frac{(n+1)^3}{(3n+1)(3n+2)(3n+3)},
$$
and the first factor tends to $e^3$ and the second to $\frac{1}{27}$ as $n\to\infty$, what leads to
$$
\lim_{n\to\infty}\frac{n^3}{(3n)!^\frac{1}{n}}=\frac{e^3}{27}.
$$

A: $$\lim_{n \to \infty} \frac{n^3}{(3n)!^\frac{1}{n}}$$
$$=exp[\frac{3n\ln(3)-\ln(3n)-\ln(3n-1)-\cdots-\ln(1)}{n}]$$
$$=exp[\frac{-1}{n}\left(\sum\limits_{i=1}^{n} \ln(\frac{i}{n})\right)]$$
$$=exp[-\int\limits_{0}^{3}ln(x)\,dx]=exp[-3\ln(3)+\int\limits_{0}^{ln(3)}e^{x}\, dx]$$
$$=exp[-3\ln(3)+3]=\frac{e^{3}}{27}$$

A: $A=\lim_{n\to\infty}\frac{n^3}{(3n)!^{1/n}}$ is the cube of $B=\lim_{n\to\infty}\frac{n}{(3n)!^{1/3n}}$, which is a third of $C=\lim_{n\to\infty}\frac{3n}{(3n)!^{1/3n}}$, which is equal to $D=\lim_{n\to\infty}\frac n{n!^{1/n}}$ if the latter exists.
The logarithm of the latter is $E=\lim_{n\to\infty}\log n-\frac1n\Sigma_{i=1}^n\log i$.
Now the derivative of $x\log x-x$ is $\log x$, so $n\log n-n+1=\int_1^n\log x\ge\int_1^n\log\lfloor x\rfloor=\Sigma_{i=1}^{n-1}\log i$, and similarly $n\log n-n+1=\int_1^n\log x\le\int_1^n\log\lceil x\rceil=\Sigma_{i=1}^n\log i$.
Thus $n\log n-n+1\le\Sigma_{i=1}^n\log i\le(n+1)\log n-n+1$, so
$1-\frac1n-\frac{\log n}n\le\log n-\frac1n\Sigma_{i=1}^n\log i\le 1-\frac 1n$.
This shows that $E=1$. Since $E$ was defined as $\log D$, $C$ was equal to $D$, $B$ was a third of $C$ and $A$ was the cube of $B$, it follows that $A=\frac{e^3}{27}$.


text:
Q: SQL INSERT INTO VALUES I have 2 tables :
TableUser

UserID
Name
FirstName

1
CAMERON
James

2
CONNOR
John

3
CONNOR
Sarah

TableTarget

UserID
TargetName
TargetLocation

2
Someone...
Someplace...

2
Someone...
Someplace...

4
Someone...
Someplace...

3
Someone...
Someplace...

2
Someone...
Someplace...

And I have a CSV file to fulfil my TargetTable. I thought it would be easy by formating my CSV to make a SQL command like
INSERT INTO
TableTarget (UserID,TargetName,TargetLocation)
VALUES
(2,'Someone...','Someplace...'),
(2,'Someone...','Someplace...'),
(3,'Someone...','Someplace...')

But I don't have the UserID in my CSV file, I have the Name and FirstName:
Name;FirstName;TargetName;TargetLocation

And I don't know how to do. Worst, among my hundred users, sometimes they have the same Name.
I would be glad to have some help!
Thanks!

A: Load the CSV table into a staging table.  Then load the final result using a join:
insert into targettable (UserID, UserID TargetName  TargetLocation, TargetLocation)
    select u.userid, tts.TargetName, tts.TargetLocation
    from targettable_staging tts join
         tableuser u
         on u.name = tts.name and u.firstname = tts.firstname;

You might want another step where you load unknown users into the user table.  And the whole time you'll keep your fingers crossed that users have unique names.


text:
Q: Align 2 lines horizontally starting from a dash symbol , with the first previous one without subscript and the second previous one with subscript I try to align horizontally 2 lines after 2 words, the first one not containing a subscript in text (see below with "WL") and the second one with a subscript (see GC_{sp}).
I used for this multiple attempts like \hphantom or "\," but none of them is working. As you can see, there is a little shift between the 2 first left dash '-' symbols.

I want the first left dash '-' symbol on the first line to be at the same place than the second line from an horizontal alignement point of view, i.e to be slightly shifted to the right.
Here the code snippet :
fisher_1.name = '\\parbox{9in}{ $ \\mathrm{WL\\hphantom{ } - Opt. Flat. No \gamma -} \\mathrm{FoM=47.05} $ }'
fisher_2.name = '\\parbox{9in}{ $ \\mathrm{GC_{sp} - Opt. Flat. No \gamma -} \\mathrm{FoM=60.49} $ }

If someone could have the trick to solve this issue...
EDIT1 :
the fisher_1.name and fisher_2.name are injected into the following structure from the library cosmicfish :
fisher_list = fpa.CosmicFish_FisherAnalysis(
    fisher_list=[
        fisher_1,
        fisher_2,
    ],
)

I recall that I would like the first '-' symbol to be at the same horizontal place from an horizontal alignement point of view, which implies a perfect alignement from the first dash '-' symbol up to the end of string ( 47.05 and 60.49.
The last solution :
fisher_1.name = '\\parbox{9in}{$\\mathrm{WL}$\\hphantom{$\\mathrm{_{sp}}$} - FoM=47.05}'
fisher_2.name = '\\parbox{9in}{$\\mathrm{GC_{sp}}$ - FoM=60.49}'

doesn't work. I can't compensate the gap provocated by subscript _{sp}
EDIT 2: The only solution that works is basically :
fisher_1.name = 'WL   - Opt. Flat. No gamma - FoM=47.05'
fisher_2.name = 'GCsp - Opt. Flat. No gamma - FoM=60.49'

which gives :
With the other solutions suggested, I have compilation errors since I
define fisher_1.name and fisher_2.name in a Python code with the library [cosmicfish][3].
If I want the greek symbol \gamma, this basic solution doesn't work anymore :
fisher_1.name = 'WL   - Opt. Flat. No $\gamma$ - FoM=47.05'
fisher_2.name = 'GCsp - Opt. Flat. No $\gamma$ - FoM=60.49'

the same for :
fisher_1.name = 'WL   - Opt. Flat. No $\\gamma$ - FoM=47.05'
fisher_2.name = 'GCsp - Opt. Flat. No $\\gamma$ - FoM=60.49'

I am disapointed that it doesn't work with all your solutions. I don't know what to do...
EDIT 3: I try to restart from the beginning with this example implemented in my Python code :
fisher_1.name = '\\parbox{\\widthof{$\\mathrm{GC_{sp}}$}}{$\\mathrm{WL}$}  $\\mathrm{-\\ Opt.\\ Flat.\\ No\\ \\gamma - FoM=47.05} $'
fisher_2.name = '\\parbox{\\widthof{$\\mathrm{GC_{sp}}$}}{$\\mathrm{GC_{sp}}$}  $\\mathrm{-\\ Opt.\\ Flat.\\ No\\ \\gamma - FoM=60.49} $'

At the execution of Python code, I get the following errors :
TITLE - name of file : \parbox{\widthof{$\mathrm{GC_{sp}}$}}{$\mathrm{WL}$}  $\mathrm{-\ Opt.\ Flat.\ No\ \gamma - FoM=47.05} $
Traceback (most recent call last):
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/texmanager.py", line 254, in _run_checked_subprocess
    stderr=subprocess.STDOUT)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/subprocess.py", line 411, in check_output
    **kwargs).stdout
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/subprocess.py", line 512, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['latex', '-interaction=nonstopmode', '--halt-on-error', '/Users/fab/.matplotlib/tex.cache/e8dd1b2348d85fb40145a12d56a0f625.tex']' returned non-zero exit status 1.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "main_synthesis.py", line 904, in <module>
    plot_tri(fisher_plotter)
  File "main_synthesis.py", line 206, in plot_tri
    set_triplot_dimensions( self, num_col=len(params_temp), num_rows=len(params_temp), **kwargs )
  File "main_synthesis.py", line 673, in set_triplot_dimensions
    dimensions  = self.get_dimensions_plot_obj()
  File "cosmicfish-pyplots-py3/cosmicfish_pylib/fisher_plot.py", line 778, in get_dimensions_plot_obj
    self.figure.canvas.draw()
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py", line 406, in draw
    self.figure.draw(self.renderer)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/artist.py", line 74, in draw_wrapper
    result = draw(artist, renderer, *args, **kwargs)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/artist.py", line 51, in draw_wrapper
    return draw(artist, renderer, *args, **kwargs)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/figure.py", line 2791, in draw
    renderer, self, artists, self.suppressComposite)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/image.py", line 132, in _draw_list_compositing_images
    a.draw(renderer)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/artist.py", line 51, in draw_wrapper
    return draw(artist, renderer, *args, **kwargs)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/legend.py", line 609, in draw
    bbox = self._legend_box.get_window_extent(renderer)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/offsetbox.py", line 352, in get_window_extent
    w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/offsetbox.py", line 439, in get_extent_offsets
    for c in self.get_visible_children()]
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/offsetbox.py", line 439, in <listcomp>
    for c in self.get_visible_children()]
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/offsetbox.py", line 347, in get_extent
    w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/offsetbox.py", line 475, in get_extent_offsets
    for c in self.get_visible_children()]
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/offsetbox.py", line 475, in <listcomp>
    for c in self.get_visible_children()]
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/offsetbox.py", line 347, in get_extent
    w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/offsetbox.py", line 439, in get_extent_offsets
    for c in self.get_visible_children()]
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/offsetbox.py", line 439, in <listcomp>
    for c in self.get_visible_children()]
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/offsetbox.py", line 347, in get_extent
    w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/offsetbox.py", line 475, in get_extent_offsets
    for c in self.get_visible_children()]
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/offsetbox.py", line 475, in <listcomp>
    for c in self.get_visible_children()]
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/offsetbox.py", line 823, in get_extent
    bbox, info, yd = self._text._get_layout(renderer)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/text.py", line 315, in _get_layout
    clean_line, self._fontproperties, ismath=ismath)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py", line 230, in get_text_width_height_descent
    s, fontsize, renderer=self)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/texmanager.py", line 399, in get_text_width_height_descent
    dvifile = self.make_dvi(tex, fontsize)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/texmanager.py", line 293, in make_dvi
    texfile], tex, cwd=tmpdir)
  File "/opt/intel/oneapi/intelpython/latest/lib/python3.7/site-packages/matplotlib/texmanager.py", line 267, in _run_checked_subprocess
    exc=exc.output.decode('utf-8'))) from exc
RuntimeError: latex was not able to process the following string:
b'$\\\\mathrm{\\\\parbox{\\\\widthof{$\\\\mathrm{GC_{sp}}$}}{$\\\\mathrm{WL}$}\\\\ \\\\ $\\\\mathrm{-\\\\\\\\ Opt.\\\\\\\\ Flat.\\\\\\\\ No\\\\\\\\ \\\\gamma\\\\ -\\\\ FoM=47.05}\\\\ $}$'

Here is the full report generated by latex:
This is pdfTeX, Version 3.14159265-2.6-1.40.21 (TeX Live 2020/MacPorts 2020.54632_1) (preloaded format=latex)
 restricted \write18 enabled.
entering extended mode
(/Users/fab/.matplotlib/tex.cache/e8dd1b2348d85fb40145a12d56a0f625.tex
LaTeX2e <2020-02-02> patch level 5
L3 programming layer <2020-03-06>
(/opt/local/share/texmf-texlive/tex/latex/base/article.cls
Document Class: article 2019/12/20 v1.4l Standard LaTeX document class
(/opt/local/share/texmf-texlive/tex/latex/base/size10.clo))
(/opt/local/share/texmf-texlive/tex/latex/type1cm/type1cm.sty)
(/opt/local/share/texmf-texlive/tex/latex/cm-super/type1ec.sty
(/opt/local/share/texmf-texlive/tex/latex/base/t1cmr.fd))
(/opt/local/share/texmf-texlive/tex/latex/base/inputenc.sty)
(/opt/local/share/texmf-texlive/tex/latex/geometry/geometry.sty
(/opt/local/share/texmf-texlive/tex/latex/graphics/keyval.sty)
(/opt/local/share/texmf-texlive/tex/generic/iftex/ifvtex.sty
(/opt/local/share/texmf-texlive/tex/generic/iftex/iftex.sty)))
(/opt/local/share/texmf-texlive/tex/latex/base/textcomp.sty)
(/opt/local/share/texmf-texlive/tex/latex/l3backend/l3backend-dvips.def)
No file e8dd1b2348d85fb40145a12d56a0f625.aux.
*geometry* driver: auto-detecting
*geometry* detected driver: dvips
! Undefined control sequence.
<argument> \widthof
                    {$\mathrm {GC_{sp}}$}
l.19 ....\\ Flat.\\ No\\ \gamma\ -\ FoM=47.05}\ $}
                                                  $}
No pages of output.
Transcript written on e8dd1b2348d85fb40145a12d56a0f625.log.

EDIT 4: A partial solution is done :
    fisher_1.name = '\\parbox{9in}{\\rlap{$\\mathrm{WL}$}\\hphantom{$\\mathrm{GC_{sp}}$} - FoM=47.05}'
    fisher_2.name = '\\parbox{9in}{$\\mathrm{GC_{sp}}$ - FoM=60.49}'

As you can see, and for a reason I ignore, the "WL" string is pushed to the top, I don't why. The font for strings "FoM=47.05" and "FoM=60.49" is also weird.
So, we are near to a solution since the alignement regarding first dash '-' is respected.
SOLUTION : has been found by Heiko Theiße :
these 2 lines did the trick :
   fisher_1.name = '\\rlap{$\\mathrm{WL}$\\hphantom{\\mathrm{GC_{sp}}} - FoM=47.05'
   fisher_2.name = 'GC_{sp} - FoM=60.49'

which produces :
Regards

A: Use \hphantom{\mathrm{GC_{sp}}}\llap{$\mathrm{WL}$} in the first row and GC_{sp} in the second. The \hphantom produces a space that is as wide as GC_{sp}, and the \llap typesets $\mathrm{WL}$ into that space, right-aligned.
Using \rlap{$\mathrm{WL}$}\hphantom{\mathrm{GC_{sp}}} in the first row instead will make it left-aligned.
Addendum: The following works:
fisher_1.name = '\\rlap{$\\mathrm{WL}$}\\hphantom{\\mathrm{GC_{sp}}} - FoM=47.05'
fisher_2.name = 'GC_{sp} - FoM=60.49'

The challenge is that cosmicfish compiles the rows separately (one LaTeX run per row), therefore \halign or a table package cannot be used.

A:
A parbox is used only for the first "word". Its width is set to a fixed length or calculated from the longest using the calc package.
The first option is better. You don't need additional packages and it's easy to define a
\newlength{<width to fit the longest first word used>}{\mywidth}
and then always apply \parbox{\mywidth}{<first word>}.
No additional compilations are required.
\documentclass{article}

\usepackage{calc} % \widthof{..}

\begin{document}

    \textbf{Original}\medskip

    \parbox{9in}{ $ \mathrm{WL\hphantom{ } - Opt. Flat. No \gamma -} \mathrm{FoM=47.05} $ }

    \parbox{9in}{ $ \mathrm{GC_{sp} - Opt. Flat. No \gamma -} \mathrm{FoM=60.49} $ }

    \bigskip
    \textbf{A fixed length}\medskip

    \parbox{5ex}{$\mathrm{WL}$}  $\mathrm{-\ Opt.\ Flat.\ No\ \gamma - FoM=47.05} $

    \parbox{5ex}{$\mathrm{GC_{sp}}$}   $\mathrm{-\ Opt.\ Flat.\ No\ \gamma - FoM=60.49} $

    \bigskip
    \textbf{Using calc}\medskip

    \parbox{\widthof{$\mathrm{GC_{sp}}$}}{$\mathrm{WL}$}  $\mathrm{-\ Opt.\ Flat.\ No\ \gamma - FoM=47.05} $

    \parbox{\widthof{$\mathrm{GC_{sp}}$}}{$\mathrm{GC_{sp}}$}  $\mathrm{-\ Opt.\ Flat.\ No\ \gamma - FoM=60.49} $

\end{document}

A: You can leave the calculation of widths up to LaTeX via eqparbox's \eqmakebox[<tag>][<align>]{<stuff>}. It puts <stuff> inside a box of maximum width across all <tag>s with the option of individual <align>ment as well (left, right or center). It requires two compilations with any change in the width of the widest element.

\documentclass{article}

\usepackage{eqparbox}

\setlength{\parindent}{0pt}% Just for this example

\begin{document}

\eqmakebox[LHS][l]{WL} -- Opt.\ Flat.\ No $\gamma$ - FoM = 47.05

\eqmakebox[LHS][l]{GC\textsubscript{sp}} -- Opt.\ Flat.\ No $\gamma$ - FoM = 60.49

\end{document}


text:
Q: Continuation of "I just can not understand DR 712" This is basically a continuation of my prior question about DR 712. Let me first explain why I'm insisting in looking at something that could be considered old, as the C++11 Standard, but my problem is that the section [basic.def.odr] is already difficult to understand in C++11, and I want to cover this completely before I delve into the same section in the current draft, which in my opinion, is even more complicated.
The answer to my prior question by Austing Hastings was great, but I still have one little point that is not clear in [basic.def.odr]/2 in C++11. Consider this little and very simple example:
const int i = 1;
int main()
{
    int j = i;
}

From [basic.def.odr]/2 in C++11 i is not odr-used in int j = i; as i is an object that satisfies the requirement for appearing in a constant expression and the lvalue-to-rvalue conversion is immediately applied to i. That doesn't make much sense to me, as i is clealy being used in the declaration int j = i;, as can be seen in the slightly modified code shown here, where I forced the variable i not to be optimized out of the compiled code.
Of course, there must be something wrong in my reasoning above, for I don't believe C++11 could be wrong in such a simple example. Again, what am I missing now???

A: I am trying to translate my understanding of standardese "used" and "one definition rule used" to something more intuitive here.  Terms other than "used" and "ODR-used" are not intended as standard-defined terms below.

Something being ODR-used basically means "we need it to have an identity".  This usually means someone is taking a reference or pointer to it.
If you only need the value of something, this doesn't always make it ODR-used.  The value of a compile-time constant does not require identity.
In C++, identity basically means "it must actually have storage somewhere".
The standard doesn't say "it is ODR used if we need it to have an identity", because then different compilers will have different rules to determine if they need the identity.  As an example, if an operation is inlined and the reference elided, does that mean it no longer needs an identity?
So the standard describes what ODR-used means, and distinguishes it from the value being used.
int j = i;

this doesn't need the identity of i.  It just needs its value.  const int i = 1; has a value that cannnot (under defined behavior) change.
int const* pj = &i;

this does need an identity.  Two different pointers to i must agree on the location of i under the standard.
void foo( const int& x ) {
  int j = x;
}
foo(i);

This also needs an identity for i.  We take a reference to i.  Even though the only thing we do is just that reference its value, the (short, theoretical) existence of that reference means it had an identity.
const int a = 3; const int b = 4;
int i = (a<2)?a:b;

the defect there was that this required a and b to have identity (they where ODR-used), because the the interaction of ? with the used-rules.  The defect was saying "we should fix this".
Link to DR 712
And after that resolution, only the value of a and b are required by that expression, not their identity, so they don't need to have storage.
We care if something has storage because things requiring storage have to have a unique point of definition.  They cannot exist purely in a header file, basically.
Note that with inline variables in C++17 we may care less about this; under the as-if rule, the inline storage location created can be erased from existence if nobody actually pays attention to the identity.  As functions taking const& can "accidentally" force identity requirements on things intended to be value-only tokens, this is a nice relaxing of the rules.


text:
Q: How to exit from a function Sometimes when I use this function, it does not detect the edges of an image, that is because I would like to know how to exit the function, in case it does not find any contour, with an if loop for example.
def sort_contours(cnts,reverse = False):
    i = 0
    boundingBoxes = [cv2.boundingRect(c) for c in cnts]
    #if cnts==0:
      #quit()
    (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
                                        key=lambda b: b[1][i], reverse=reverse))
    return cnts

With this output in failure case:
      7     (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
----> 8                                         key=lambda b: b[1][i], reverse=reverse))
      9     return cnts
     10

ValueError: not enough values to unpack (expected 2, got 0)

Before I made this
#if cnts==0:
  #quit()

Which does not work, any ideas?


text:
Q: RNN in TensorFlow realtime implementation I want to implement a RNN in TensorFlow to track the position of a few objects. I want a realtime implementation so I would give the network a datapoint at the time. The examples I have seen in TensorFlow the input is always a sequence of datapoints at different times.. How can I input only one datapoint at the time?

A: As the Tensorflow documentation,
https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn

*

*You can specify the initial state as an input for the RNN network,

*Also, Tensorflow RNN networks output the final state.

Therefore, you can give the input as the shape of [batchsize, 1, inputsize] (don't forget the initial state ;) and will receive an output with the following shape [batchsize, 1, outputsize] and the final state.
Then you can input the final state of the previous execution as the initial state to the next execution.
This will allow you to create a RNN that can run in real-time ;)


text:
Q: Is this the reason why IEquatable was introduced? Is main reason why IEquatable<T> interface was introduced because it allows you to do the same as the System.Object.Equals method but without having to perform casts?
thank you

A: To make it type safe, I would think. Equals() takes an object as parameter and hence you will not see an error if you pass in an object of wrong type until you run it.

A: One reason is so that you can require a class be equatable with a desired type, without necessarily being that type. E.g.
public void MyClass<T> where T : IEquatable<Foo>
{
    private static readonly Foo SpecialFoo = Foo.SpecialFoo;

    public void MyMethodThatProcessesTs(T theT)
    {
        if (theT.Equals(SpecialFoo))
        {
            // process theT.
        }
    }
}

A: In addition to what @Bala R says, it also avoids boxing when doing custom equality checking between structs.


text:
Q: Chrome not honoring border radius on children I'm having a bit of trouble getting Chrome to honor the border radius on child elements.
Here's the setup:

if the wrapper is a positioned element (e.g. position: relative) and has a border-radius, then the border radius will not be applied to the img content.
it doesn't have to be an image, either.  any content that fills the background.
Here's a reduced example page that shows off the problem.  View in Safari, Mobile Safari, Firefox, or IE and the corners of the image will be clipped to the round corner.  Viewed in Chrome the image overflows the corner (despite the overflow:hidden css) and looks ugly.
Have a look:
https://dl.dropbox.com/u/433436/no-rounding/index.html
The question:
Is there some workaround for this that's not too insane?  Does anyone know why this affects one WebKit based browser and not others?  Perhaps this is coming to update in Chrome soon?

A: You need to remove the position: relative
If your really need position relative then you can double wrap your element:
HTML:

CSS:
.outer {
    position: relative;
}
.wrapper {
    width: 100px;
    height: 100px;
    overflow: hidden;
    border: 3px solid red;
    border-radius: 20px;
}
.inside {
    width: 100px;
    height: 100px;
    background-color: #333;
}

http://jsfiddle.net/eprRj/
See these related questions:

*

*Forcing child to obey parent's curved borders in CSS

*CSS Border radius not trimming image on Webkit

*How to make CSS3 rounded corners hide overflow in Chrome/Opera

A: Try giving the child elements a border-radius of half of that given to the parent element.
From this answer: https://stackoverflow.com/a/5421789/187954

A: Just add in

    .wrapper:first-child{
    border-radius:20px;
    }

You will have to adjust the radius though depending on your border thickness and take this off the child.
I would also add in prefixes for the older supporting browsers -moz- etc..

A: Adding display: block; or  display: inline-block; to the parent element could solve it.


text:
Q: Removing items from array and DOM simultaneously I have a large array of items which I am removing one by one within a setInterval.
var randomInt = function(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
};

var showItems = function() {
    $.each(items, function(key, val) {
        $('.list').append('
'+val+'
');
    });
};

var interval = setInterval(function() {
    var id = randomInt(0, items.length);
    items.splice(id, 1);
    $('#i'+id).remove();
    if (items.length < 10) {clearInterval(interval);}
}, 200);

The problem arises when the list starts to become shorter. Let's say items starts with 500 entries. Once items.length equals 200, the ids within the DOM stay the same. This results in items being deleted from the array while not from the DOM.
Another method I've thought of is delete items[id], but then there's the problem of sparse removal when an item has already been deleted. Once the defined item count reaches ~20, it takes an exceptionally long time for anything more to happen.
The solution I can think of is to redraw the DOM at every delete but that sounds awful and the results (both aesthetic and computational) would be ugly!

A: Instead of using IDs for your DIVs, do something like this:

First DIV

Second DIV

  ...

Instead of $('#i'+id).remove(); do $('.list > .item').eq(id).remove();


text:
Q: Some kind of IF condition in INSERT I have next tables:
   table1               table2
id. value position    id   state
                       1.  false

What I need is to insert data in to table1 if state from table2 is true.
Something like:
INSERT INTO table1(value, position)
VALUES('someVal', 3)
IF table2.id = 1 AND table2.state = true

A: Do you want exists?
INSERT INTO table1(value, position)
    SELECT v.value, v.position
    FROM (VALUES('someVal', 3)) v(value, position)
    WHERE EXISTS (SELECT 1 FROM TABLE2 t2 WHERE t2.id = 1 AND t2.state = true);

A: You can select only item where table2.State = true before inserting
If you have your data comming from another table it would look like this
INSERT INTO table1(value, position)
SELECT ValueId, Value
FROM TableValue
INNER JOIN Table2
ON TableValue.ValueID = Table2.ID
WHERE table2.state = true


text:
Q: How to override fillOval function in Java? The issue I am having is that I want to fill an oval, but I am using floats as my 'x' and 'y' values. Here is what I have:
@Override
public void paintComponent(Graphics g)
{
.
.
.
for(Coordinates cord : tempVertices)
{
    g.fillOval(cord.x,cord.y,DIAMETER,DIAMETER);
}
// DIAMETER = 10

// Coordinate Class is just a variable with an 'x' and 'y' value stored in floats
// Floats range from 0 to 1, so type casting won't work...

// tempVertices is just an ArrayList with Coordinates values

I am using NetBeans IDE 7.2 and I don't know how to override the fillOval method, and I cannot use an import from : import org.newdawn.slick.*; (It wouldn't recognize it). Is there a better Graphics option or easier way to achieve this simple fillOval?

A: You may be looking for the fill() method of Graphics2D, which accepts any Shape:
g.fill(new Ellipse2D.Float(cord.x, cord.y, DIAMETER, DIAMETER));

You'll also want to explore any supported java.awt.RenderingHints.


text:
Q: How to simulate the different types of missing data How do you create a missingness mechanism (MAR, MCAR, NMAR)? Can you generate it directly or do you do it by a model?

A: Rubin defined three types of missing data:

*

*Missing Completely at Random (MCAR)
MCAR occurs when there is a simple probability that data will be missing, and that probability is unrelated to anything else in your study.  For example, a patient can miss a follow up visit because there is an accident on the highway and they simply can't get to the visit.

*Missing at Random (MAR)
MAR happens when the missingness is related to information in your study, but all the relevant information to predict missingness is in the existing dataset.  An example might be a weight loss study in which people drop out if their trajectory is that they are gaining weight.  If you can estimate that trajectory for each person before anyone drops out, and see that those whose slope is positive subsequently drop out, you could take that as MAR.

*Not Missing at Random (NMAR)
NMAR is like MAR in that the missingness is related to what is happening in your study, but differs in that the data that are related to the missingness is included in the data that are missing.  For instance, if you are studying a treatment for vertigo / 'woozy-ness', but anytime a patient is really woozy, they don't show up for the follow-up visit.  Thus, all the high values are missing, and they are missing because they are high!
In other words, the types of missingness specify the mechanism that generates the missingness itself, so if you understand how the mechanism works, you simply write code to replicate it.  For example, if you want 7% of your data missing completely at random, draw a number from a uniform distribution for every value in your dataset, and if it is <.07, replace the value with NA.  For missing at random, simulate a logistic regression data generating process that outputs a probability of each value being missing (i.e., being replaced with NA) using information that will continue to be non-missing in your dataset.  (For an example of simulating a logistic regression data generating process, see my answer here: Logistic regression simulation in order to show that intercept is biased when Y=1 is rare.)  You can generate missingness not at random using a similar logistic regression data generating process, where the probability of missingness is a function of the y-value itself (i.e., the value that will potentially be replaced by NA).
Here is an example:
##### generic data setup:
set.seed(977) # this makes the simulation exactly reproducible
ni     = 100  # 100 people
nj     =  10  # 10 week study
id     = rep(1:ni, each=nj)
cond   = rep(c("control", "diet"), each=nj*(ni/2))
base   = round(rep(rnorm(ni, mean=250, sd=10), each=nj))
week   = rep(1:nj, times=ni)
y      = round(base + rnorm(ni*nj, mean=0, sd=1))

# MCAR
prop.m = .07  # 7% missingness
mcar   = runif(ni*nj, min=0, max=1)
y.mcar = ifelse(mcar<prop.m, NA, y)  # unrelated to anything
View(cbind(id, week, cond, base, y, y.mcar))

# MAR
y.mar = matrix(y, ncol=nj, nrow=ni, byrow=TRUE)
for(i in 1:ni){
  for(j in 4:nj){
    dif1 = y.mar[i,j-2]-y.mar[i,j-3]
    dif2 = y.mar[i,j-1]-y.mar[i,j-2]
    if(dif1>0 & dif2>0){  # if weight goes up twice, drops out
      y.mar[i,j:nj] = NA;  break
    }
  }
}
y.mar = as.vector(t(y.mar))
View(cbind(id, week, cond, base, y, y.mar))

# NMAR
sort.y = sort(y, decreasing=TRUE)
nmar   = sort.y[ceiling(prop.m*length(y))]
y.nmar = ifelse(y>nmar, NA, y)  # doesn't show up when heavier
View(cbind(id, week, cond, base, y, y.nmar))


text:
Q: Using regex for switch-statement in Java void menu() {
    print();
    Scanner input = new Scanner( System.in );
    while(true) {
        String s = input.next();
        switch (s) {
        case "m": print(); continue;
        case "s": stat(); break;
        case "[A-Z]{1}[a-z]{2}\\d{1,}": filminfo( s ); break;
        case "Jur1": filminfo(s); break; //For debugging - this worked fine
        case "q": ; return;
        }
    }
}

It seems like either my regex is off or that I am not using it right in the case-statement. What I want is a string that: Begins with exactly one uppercase letter and is followed by exactly two lowercase letters, which are followed by at least one digit.
I've checked out the regex API and tried the three variants (greedy, reluctant and possessive quantifiers) without knowing their proper use. Also checked the methods for String without finding a method that seemed pertinent to my needs.

A: I don't think you can use regex in switch cases.

The String in the switch expression is compared with the expressions
  associated with each case label as if the String.equals method were
  being used.

See http://download.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html for more info.

A: You can't use a regex as a switch case.  (Think about it: how would Java know whether you wanted to match the string "[A-Z]{1}[a-z]{2}\\d{1,}" or the regex?)
What you could do, in this case, is try to match the regex in your default case.
    switch (s) {
        case "m": print(); continue;
        case "s": stat(); break;
        case "q": return;
        default:
            if (s.matches("[A-Z]{1}[a-z]{2}\\d{1,}")) {
                filminfo( s );
            }
            break;
    }

(BTW, this will only work with Java 7 and later.  There's no switching on strings prior to that.)


text:
Q: Quantum mechanics, commuting operators. If two operators $A$ and $B$ commute then any eigenvector of $A$ is an eigenvector of $B$?
I know that if that happens there is a basis in which the eigenvectors of $A$ and $B$ are equal, but I don't know if that can be generalized to any basis.

A: Not necessarily. Counterexample: Be $A$ the $2\times 2$ unit matrix, $B$ any  $2\times 2$ diagonal matrix with two different entries in the diagonal, and $v=\begin{pmatrix}1\\1\end{pmatrix}$.
Then $v$ is an eigenvector of $A$ (since every vector is an eigenvector of the identity matrix), but $v$ is not an eigenvector of $B$.
However, if $v$ is an eigenvector of $A$ with non-degenerate eigenvalue $\alpha$, then $v$ is also an eigenvalue of $B$.
Proof: We have
$$ABv = BAv = B\alpha v = \alpha Bv.$$
Therefore $Bv$ is also an eigenvector of $A$ with the same eigenvalue. But since we assumed that the eigenvalue is non-degenerate, $Bv$ must be a multiple of $v$, that is, $v$ is an eigenvector of $B$.

A: Take $J=\begin{bmatrix}0 & 1 \\ 0 & 0 \end{bmatrix}$. Then $I,J$ commute.
Any basis forms a basis of eigenvectors for $I$, but at most one element of any basis can be an eigenvector for $J$.
(See https://math.stackexchange.com/a/6261/27978 for relevant comments.)


text:
Q: Can't dismiss a popover normally after it presents a page sheet with isModalInPresentation set to true We have a view controller (A) presented as a popover. When it presents a view controller (B) as a page sheet, we are setting isModalInPresentation to true on B to prevent the swipe down gesture from dismissing it. But setting that to true also results in it being changed to true on view controller A. So after the page sheet is dismissed (with dismiss(animated: true, completion: nil)), the popover can't be dismissed by tapping outside of its bounds.
We tried setting isModalInPresentation back to false on B before it is dismised (in its viewWillDisappear(_:)), and while that changes isModalInPresentation back to false on A, A still cannot be dismissed by tapping outside of its bounds.

A: This appears to be fixed when building with Xcode 11.1 to an iOS 13.1 simulator (the popover is dismissed when tapping outside its bounds, and we don't need to set isModalInPresentation back to false when dismissing B).


text:
Q: Consider nonzero $A_{2\times 2}$ such that $A^2 = \vec{0}$. Prove or disprove that dim$($ker$(A)) = 2$ I'm having a couple of difficulties with this problem. The first comes with finding an $A$ such that $A^2 = \vec{0}$. In the case of a $2 \times 2 $ matrix, it seems simple enough to try a few combinations until one works, but what if $A$ had been say, $5 \times 5$? Is there any simple method to determine $A$ given some $A^x = \vec{y}$ for scalars $x$ and vector $y$, or is this just a particular case?
My second confusion is with what dim$($ker$(A))$ precisely means. To my understanding dim$(\mathbb{R^n})$ is equal to the number of vectors in a basis for $\mathbb{R^n}$. So how do we make sense of the number of vectors in a basis for ker$(A)$? If ker$(A) = \vec{0}$, is dim$($ker$(A)) = 0$, since $\vec{0}$ is not linearly independent?

A: You are right that if $ker(A)=\vec 0$ then $dim(ker(A))=0$
Here it is rather the opposite: $dim(ker(A))=2$ means that $ker(A)=\mathbb R^2$, so for all $x$, $Ax=0$, meaning $A=0$. The question can be reformulated: "is there a nonzero $2\times 2$ matrice $A$ such that $A^2=0$ ?"
Hint: the answer is yes, try to find such a matrice.


text:
Q: python socket gives wrong udp port status of remote server [user@testserver~]$ sudo nmap -v -Pn -sU -p 152 10.146.25.44

Starting Nmap 5.51 ( http://nmap.org ) at 2022-09-12 16:32 GMT

Initiating UDP Scan at 16:32

Scanning remoteserver.example.com (10.146.25.44) [1 port]

Completed UDP Scan at 16:32, 0.05s elapsed (1 total ports)

Nmap scan report for remoteserver.example.com (10.146.25.44)

Host is up (0.029s latency).

PORT    STATE  SERVICE

152/udp closed bftp

#!/usr/bin/python #(i am running below code as root)

from socket import *

udp_scan=socket(AF_INET,SOCK_DGRAM)

udp_scan.connect_ex(('10.146.25.44',152))

0   ------------------> this is reported open where as nmap shows udp port 152 is closed
I do not have access to remote server. When checked the remote servers port status, socket modules gives wrong result

A: Connecting a UDP socket just means that the destination address is set on the socket. There is no actual communication with the remote system going on, contrary to TCP. Thus that the connections succeeds does not allow any conclusion about the remote systems being reachable, ports being open or that the remote system even exists.
Instead one actually needs to send data to the system. The first send will succeed since it returns after putting the data in the local socket buffer, i.e. before actually transmitting the data to the system. Once the packet gets transmitted it might reach the target or might lost somewhere in the middle. Only if the target or some middlebox in between actively reacts to the packet, then a conclusion about the peer can be done. Specifically

*

*if there is an answer somebody is actively replying to the packet

*if there is an ICMP unreachable somebody is actively rejecting the packet

*if no response happens either the packet got lost, got dropped by a firewall or similar or got actually successfully read by the remote server but without responding


text:
Q: in dojo, not able to send multiple files using FileInput and iFrame I am sending a multipart request using FileInput and iframe
var _newForm;
        if(dojo.isIE < 9 || (dojo.isIE && dojo.isQuirks)){
            // just to reiterate, IE is a steaming pile of code.
            _newForm = document.createElement('<form enctype="multipart/form-data" method="post">');
            _newForm.encoding = "multipart/form-data";

        }else{
            // this is how all other sane browsers do it
            _newForm = document.createElement('form');
            _newForm.setAttribute("enctype","multipart/form-data");
        }
        _newForm.appendChild(foo.fileInput);
        console.log("FP is "+foo.fileInput);
        dojo.body().appendChild(_newForm);

        var o = dojo.io.iframe.send({
            url: foo.url,
            form: _newForm,
            load: uploadComplete,
            error: onBeforeSend
        });

I am facing issue that, I can send only one successful request. For second I need to refresh the page. Please let me know, what I need to do for sending multiple files.

A: I am using dojo 1.6 and had a very similar problem that I resolved with the following method:
dojo.io.iframe._currentDfd = null; //insert this line
dojo.io.iframe.send
({...

*verified in Chrome Version 25.0.1364.152 m
Source: http://mail.dojotoolkit.org/pipermail/dojo-interest/2012-May/066109.html


text:
Q: Shallow Rendering Jest Testing with Material UI withStyles Component I am writing a test for a component that is wrapped in a withStyles() from Material UI using Jest. I need to test the children elements, but my wrapper is undefined.
I've seen another post similar to writing tests with withStyles(), but the undefined error still persists.
Test File:
import { shallow } from 'enzyme';

import { TempComponent } from '../../../../src/components/helpers/temp';

describe('temp', () => {
  let wrapper;

  const renderComponent = () => shallow(<TempComponent />);

  beforeEach(() => {
    wrapper = renderComponent();
  });

  it('render correctly', () => {
    expect(wrapper.type()).toEqual('div');
  });
});

Component:
import React from 'react';
import { withStyles } from '@material-ui/core/styles';

const TempComponent = () => <button>Click Me!</button>;

export default withStyles({})(TempComponent);

I get this error for my test:
Invariant Violation: ReactShallowRenderer render(): Shallow rendering works only with custom components, but the provided element type was undefined.
I am wanting the wrapper component to behave the same way as a wrapper without the withStyles() component. Any help would be appreciated!
Note: I am not doing snapchat testing with jest

A: This appears to be the issue and solution:
https://github.com/mui-org/material-ui/issues/9266#issuecomment-349447137

The issue isn't about the children elements but with the intermediary
  element, it's creating. The shallow() API of enzyme only render one
  level depth. Any higher-order component is going to obfuscate the
  children. You have different workarounds. I would encourage you to
  refer to the enzyme documentation. Still, here they are:

*

*use mount()

*use .dive()

*use our createShallow() public API

*use our internal until() helper


text:
Q: You are getting tired, you should find a parking place to rest When doing long trips, you will eventually start getting 'tired' in game. This is shown to you by a message that takes up your GPS space saying "You are getting tired. You shold find a parking place to rest".
I have noticed that the screen will occasionally start blacking out but I have always rested before it got too bad.
Once this message starts showing, how long can you keep driving until you fall asleep?
Do you actually fall asleep at all?

A: At first you will begin audibly yawning. Once this phase passes the screen will begin getting darker and the word dozing will appear in the middle of the screen every now and again.
The yawning will get increasingly more frequent.
The text will change to "You are tired! You should find somewhere to park and rest!".
The dozing screens will get longer the longer you stay awake
You don't seem to actually fall asleep (I drove 300 miles while tired)

A: Shortly after you've passed the time when the game says it's time for rest (F6 menu) it will begin charging you 150 euro every few minutes until you sleep.  Not a big deal if you have an empire, but if you're still getting established it's worth knowing.
The only time you should drive while tired is when taking a rest break would cause you to deliver your cargo late.

A: If I am within 2-3 hours of my destination, there's no way I'm pulling over for 8 hours because the game tells me I'm tired.  I'll rest when I'm dead.
Anyway, usually the 150 euro penalties start rolling in right when you hit your destination anyway.  Bang out that parking job extra quick and you usually only get a single one.  I haven't fallen asleep at all yet.


text:
Q: xfs quota not reliable I have enabled quotas on an xfs-partition. But it seems to be broken:
$ echo asdf >/disk/l/data/avi/foo
-su: /disk/l/data/avi/foo: Disk quota exceeded

$ quota -f /disk/l
Disk quotas for user avi (uid x):
 Filesystem  blocks   quota   limit   grace   files   quota   limit   grace
 /dev/md0 1801035344  3000000000 4000000000           38063       0       0

Any ideas why?
Edit:
grpquotas explained the problem for some users, but I still have users quota issues for other users.
$ touch a
touch: cannot touch `a': Disk quota exceeded
$ quota -f .
Disk quotas for user s (uid 2267):
 Filesystem  blocks   quota   limit   grace   files   quota   limit   grace
   /dev/md0  293812  1000000000 2000000000               8       0       0
$ mount
/dev/md0 on /disk/l type xfs (rw,usrquota,grpquota)
# xfs_quota -x -c report |grep -v -- '------'
User quota on /disk/l (/dev/md0)
                           Blocks
User ID          Used       Soft       Hard    Warn/Grace

Group quota on /disk/l (/dev/md0)
                           Blocks
Group ID         Used       Soft       Hard    Warn/Grace
[... i.e. no groups or users over their soft limit ...]

A: It's possible that you need to use xfs_quota(8) for XFS filesystems.
Alternatively, the -F xfs option may be necessary to quota, if format autodetection isn't deducing it correctly.
If neither of these are useful, can you indicate how you enabled quotas, and how you mounted this filesystem?

A: The problem was group quotas. The user quota was not exceeded, but the group quota was.


text:
Q: Angular HTTP GET not hitting Express Route My Angular HTTP GET Request indside clearNotifications() in notification.service.ts not hitting Express Route routes/notifications.js. I am calling clearNotifications() from a component called app.component.ts. I am using Angular 7+
routes/notifications.js
const router = require('express').Router();

//Additional modules
// const db = require('../config/database');
// const notificationModel = require('../models/notifications');

//Test connection
// db.authenticate().then(() => {
//     console.log('Connection has been established successfully.');
// }).catch(err => {
//     console.error('Unable to connect to the database:', err);
// });

//Clear all notifications
router.get('/clear', (req, res, next) => {
    console.log('clear');
    // notificationModel.destroy({});
});

module.exports = router;
notification.service.ts
import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class NotificationService {

  uri = 'http://localhost:5000';
  private socket = io(this.uri);

  constructor(private http: HttpClient) { }

  getNotification() {
    let observable = new Observable<{ string: String, number: String }>(observer => {
      this.socket.on('notification', (data) => {
        observer.next(data);
      });
      // return () => { this.socket.disconnect(); }
    })
    return observable;
  }

  clearNotifications() {
    return this.http.get(`${this.uri}/notifications/clear`);
  }
}

app.component.ts
import { Component } from '@angular/core';
import { NotificationService } from './notification.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [NotificationService]
})
export class AppComponent {
  title = 'client';

  string: String;
  number: String;
  notificationArray: Array<{ string: String, number: String }> = [];

  constructor(private notificationService: NotificationService) {
    this.notificationService.getNotification().subscribe(data => {
      this.notificationArray.push(data);
    });
  }

  clearNotifications() {
    this.notificationArray = [];
    this.notificationService.clearNotifications();
  }
}

A: You should be doing this: Check the basic routing on express
var express = require('express');
var app = express();

app.get('/clear', (req, res) => {
    console.log('clear');

 res.send(success);
// notificationModel.destroy({});
});

Also make sure to subscribe to the service method from your component. If you do not subscribe the observables won't execute.
Where are you calling clearNotifications from?
subscribe to clearNotifications in component and this will work:
 this.notificationService.clearNotifications().subscribe( (data) => { ..})

As a publisher, you create an Observable instance that defines a subscriber function. This is the function that is executed when a consumer calls the subscribe() method. The subscriber function defines how to obtain or generate values or messages to be published

A: In angular, http request returns observable, so you need to subscribe. If there aren't any subscriber to the observable, it wont be executed. Try
    clearNotifications() {
    return this.http.get(`${this.uri}/notifications/clear`)
               .subscribe(data => //your callback function,
                          error => // your error handler,
                          complete => // any after completion task);
  }


text:
Q: How to show keyboard on PopupWindow? I am using PopupWindow class and on PopupWindow I have one EditText, my problem is that when PopupWindow is visible and I click on EditText at that time the soft keyboard is not visible and I am not able to enter Input. Can anybody tell me how to solve this problem?

A: Took quite a bit to figure out, but here you go:
While creating the popup, I had to set the textbox (Edittext) to force opening the soft keyboard when receiving focus.
 txtBox.setOnFocusChangeListener(new OnFocusChangeListener() {

        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus == true){
                InputMethodManager inputMgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
                inputMgr.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);

            }
        }
    });
    txtBox.requestFocus();

A: Add this code
popupWindow.setFocusable(true);

A: This worked for me.
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(final View v, final boolean hasFocus) {
            if (hasFocus && editText.isEnabled() && editText.isFocusable()) {
                editText.post(new Runnable() {
                    @Override
                    public void run() {
                        final InputMethodManager imm =(InputMethodManager)getBaseContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(editText,InputMethodManager.SHOW_IMPLICIT);
                    }
                });
            }
        }
    });

A: When you create a new PopupWindow, use another constructor method, you must set the focusable = true; only the view could be focusable, the soft keyboard will show .
public PopupWindow(View contentView, int width, int height, boolean focusable) {}

The Default focusable is 'false'


text:
Q: How to sorting the gridview when i click the header text on gridview in asp.net I have developed an asp.net application that has a Gridview control. I want it to sort when I click on the Gridview header text in asp.net. Entity framework is used to bind the gridview.
protected void grdmortgagesaver_Sorting(object sender, GridViewSortEventArgs e)
{
    string sortExpression = e.SortExpression;

    if (GridViewSortDirection == SortDirection.Ascending)
    {
        GridViewSortDirection = SortDirection.Descending;
        SortGridView(sortExpression, DESCENDING);
    }
    else
    {
        GridViewSortDirection = SortDirection.Ascending;
        SortGridView(sortExpression, ASCENDING);
    }

}

private void SortGridView(string sortExpression, string direction)
{

 //  You can cache the DataTable for improving performance
     var databind = from i in mortgageentites.Clients orderby i.LastName select i;
    if (databind.Count() > 0)
    {
        grdmortgagesaver.DataSource = databind.ToList();
        grdmortgagesaver.DataBind();
        DataTable dt = clients;
        if (dt != null)
        {
            // DataTable dt = ds.Tables[0];
            DataView dv = new DataView(dt);
            dv.Sort = sortExpression + direction;
            grdmortgagesaver.DataSource = dv;
            grdmortgagesaver.DataBind();
        }
    }
}

A: If you are using a standard ASP.NET System.Web.UI.WebControls.GridView, you can simply "Enable Sorting", in the properties pane by setting "AllowSorting" to true or via the "pop-out" on the top right of the control by checking "Enable Sorting"

A: add AllowSorting="true" in your gridview control and
protected void grd_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression == hdfSortExp.Value)
        {
            if (hdfUpDown.Value == "1")
                hdfUpDown.Value = "0";
            else
                hdfUpDown.Value = "1";
        }
        else //New Column clicked so the default sort direction will be incorporated
            hdfUpDown.Value = "0";

        hdfSortExp.Value = e.SortExpression; //Update the sort column
        BindGrid(hdfSortExp.Value, this.CBool(hdfUpDown.Value));
    }

in your c# code
public void BindGrid(string sortBy, bool inAsc)
    {
        grd.DataSource = WManager.GetAdminTags(txtSearch.Text.Trim(), sortBy, inAsc);
        grd.DataBind();
    }

A: First in your Page in the GridView Declaration Tag add the property AllowSorting="true" and in the Gridview_SortCommand try the Following code as guidence
try {
    if (SortType == false) {
        SortView.Sort = e.SortExpression + " ASC";
        //dviewGeneral.Sort = e.SortExpression & " ASC"
        Session.Item("SortOrder") = SortView.Sort.ToString;
        SortType = true;
    } else {
        SortView.Sort = e.SortExpression + " DESC";
        Session.Item("SortOrder") = SortView.Sort.ToString;
        //dviewGeneral.Sort = e.SortExpression & " DESC"
        SortType = false;
    }
    CMSgrid.SelectedIndex = -1;
    CMSgrid.CurrentPageIndex = 0;
    SortBind();
} catch (Exception ex) {
    UserMsgBox(ex.ToString());
}


text:
Q: VBA Find and replace part of file path I'm having difficulty writing VBA to find and replace part of a file path. I need to isolate the filename without the file extension (i.e. replace everything including and to the left of the last \ and the .flac for the example below)
The type find and replace involves file paths that look like --

C:\Users\myname\Desktop\PhoneCallFolder1\123456789_20140101120101.flac
  C:\Users\othername\Desktop\PhoneCallFolder2\123456789_19990101120101.flac

and the result should look like --

20140101120101
  19990101120101

Thanks for your help. My existing code is below:
Columns("A:A").Select
Selection.Replace What:= _
    "C:\Users\myname\Desktop\PhoneCallFolder1\" _
    , Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:= _
    False, SearchFormat:=False, ReplaceFormat:=False

Selection.Replace What:= _
    ".flac" _
    , Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:= _
    False, SearchFormat:=False, ReplaceFormat:=False

A: You can use a wild card to replace any path, like this
With Columns("A:A")
    .Replace What:= _
      "*\", _
      Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, _
      MatchCase:= False, SearchFormat:=False, ReplaceFormat:=False

    .Replace What:= _
      ".*", _
      Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, _
      MatchCase:= False, SearchFormat:=False, ReplaceFormat:=False
End With

A: The easiest way to do this, since you're always getting a 14 characters string, positionned 5 characters from the end, is the following. You could do it with a formula that would look like this.
For cell A1:
=LEFT(RIGHT(A1, 19), 14)

Then streth this formula all the way down.
I'll elaborate a vba way of doing this.
VBA :
lastRow = Cells(Rows.Count, 1).End(xlUp).Row 'this only finds the last row
For x = 1 To lastRow 'This loops through all the rows
    Cells(x, 1) = Left(Right(Cells(x, 1), 19), 14)
Next

A: If you need to handle your replacements one at a time you could use a couple functions like the following:
Function FileNameParse(strFile as String)
' Return a file name from a full path
FileNameParse = Left(strFile, InStrRev(strFile, "\") - 1)
End Function

Function FilePathParse(strFile as String)
' Return a directory from a full path
FilePathParse = Right(strFile, Len(strFile) - InStrRev(strFile, "\"))
End Sub


text:
Q: Do I have to use signoutRedirectCallback in oidc-client.js? In my application for authentication I'm using IdentityServer + Angular with oidc-client.js.
When I want to logout from application then following code is run:
signout(): void {
  this.manager.signoutRedirect();
}

and to handle logout from other tabs
this.manager.events.addUserSignedOut(() => {
  this.manager.removeUser().then(() => {
    this.user = null;
    this.authNavStatusSource.next(false);
    this.router.navigate(["logout"]);
  });
});

Everything works fine, but I noticed that oidc-client provides also method signoutRedirectCallback which I don't have in my code.
From documentation:

signoutRedirect: Returns promise to trigger a redirect of the current window to the end session endpoint.
signoutRedirectCallback: Returns promise to process response from the end session endpoint.

Well it says nothing to me, still don't get it. What is this for? Do I really need this? In what case it might be useful?