text:
Q: Firebase Cloud Firestore - Accessing a collection from a reference High level: In Cloud Firestore, I have two collections. fl_content and fl_files. Within fl_content, I am trying to access fl_files.
Detailed: In fl_content, each document has a field called imageUpload. This is an array of Firebase Document References. (a path to fl_files that I need to access.)
Here's my query for fl_content, in which I am accessing imageUpload reference:
let docRef = Firestore.firestore().collection("fl_content").document(item.id)
docRef.getDocument { (document, error) in
    if let document = document, document.exists {
       let property = document.get("imageUpload")
       print("PROPERTY \(property!)")
    }
}

This prints the following to the console:
PROPERTY Optional(<__NSArrayM 0x60000281d530>(
<FIRDocumentReference: 0x600002826220>
)
)

With this array of Document References, I need to get to fl_files.
This is the part I am having trouble with.
Attempts:
Within the if let statement, I tried accessing fl_files by casting property as a DocumentReference.
    let docRef = Firestore.firestore().collection("fl_content").document(item.id)
     docRef.getDocument { (document, error) in
         if let document = document, document.exists {
            let property = document.get("imageUpload") as? DocumentReference
            print("PROPERTY \(property!)")
            let test = Firestore.firestore().collection("fl_files").document(property)
         }
     }

Cannot convert value of type 'DocumentReference?' to expected argument type 'String'

    let docRef = Firestore.firestore().collection("fl_content").document(item.id)
     docRef.getDocument { (document, error) in
         if let document = document, document.exists {
            let property = document.get("imageUpload") as! DocumentReference
            let test = Firestore.firestore().collection("fl_files").document(property[0].documentID)
            print("TEST \(test)")
         }
     }

Value of type 'DocumentReference' has no subscripts

    let docRef = Firestore.firestore().collection("fl_content").document(item.id)
     docRef.getDocument { (document, error) in
         if let document = document, document.exists {
            let property = document.get("imageUpload") as! DocumentReference
            let test = Firestore.firestore().collection("fl_files").document(property.documentID)
            print("TEST \(test)")
         }
     }

Could not cast value of type '__NSArrayM' (0x7fff87c50980) to 'FIRDocumentReference' (0x10f6d87a8).
  2020-02-05 12:55:09.225374-0500 Database 1[87636:7766359] Could not cast value of type '__NSArrayM' (0x7fff87c50980) to 'FIRDocumentReference' (0x10f6d87a8).

Getting closer!
    let docRef = Firestore.firestore().collection("fl_content").document(item.id)

    docRef.getDocument(completion: { document, error in
        if let err = error {
            print(err.localizedDescription)
            return
        }
        let imageUpload = document?["imageUpload"] as? NSArray ?? [""]
        print("First Object \(imageUpload.firstObject!)")

    })

This prints: First Object <FIRDocumentReference: 0x600001a4f0c0>

Here are two screenshots to help illustrate what the Firestore database looks like..

Ultimately, I need to get to the file field within fl_files. How do I access this from the imageUpload DocumentReference?

A: Finally got it, thanks to the help of @Jay and @Emil Gi.
The "A-HA" moment came from Emil Gi's comment: All I can say is that if you successfully get element of DocumentReference type, then it must have an id property, which you can extract and query collection by document id.
    let imageUploadReference = item.imageUpload.first as? DocumentReference
    let docRef = Firestore.firestore().collection("fl_files").document(imageUploadReference!.documentID)
    docRef.getDocument(completion: { document, error in
        if let err = error {
            print(err.localizedDescription)
            return
        }
        let fileNameField = document?.get("file") as! String

        print("File name from fl_files \(fileNameField)")

    })

Once I finally had access to the corresponding "file", it was very simple to download the full URL of the image to the imageView.
I appreciate all of your help!!!

A: Here's some sample code that shows how to read and print out any of the fields values and also how to read the imageUpload field (an array) and print out the first element's value.
I've included both ways to read data from a document because I believe it answers both parts of the question: how to get the array field imageUpload and then access the first element within that array and how to get the value of the file field within fl_files.
Assuming this points to the correct document:
let docRef = Firestore.firestore().collection("fl_content").document(item.id)

this code will read two fields from the document being pointed to: imageUpload (an array) and fl_id (a String)
docRef.getDocument(completion: { document, error in
    if let err = error {
        print(err.localizedDescription)
        return
    }

    print( document!.data() ) //for testing to see if we are getting the fields

    //how to read an array and access it's elements
    let imageUploadArray = document?["imageUpload"] as? Array ?? [""]
    if let url = imageUploadArray.first {
        print(url)
    }

    //this is also valid for reading the imageUpload field array
    //let anArray = document?.get("imageUpload") as? Array ?? [""]
    //if let url = anArray {
    //    print(url)
    //}

    //how to read a single field, like file within fl_files
    let someId = document?.get("fl_id") as! String //example of reading a field
    print(someId)

})

Edit:
It appears the objects stored in the imageUpload array are references not strings. As an example of how to access them... here's the code
let refArray = document?.get("imageUpload") as? [DocumentReference] ?? []
for docRef in refArray {
   print(docRef.path) //prints the path to the document at this ref
}


text:
Q: Intervals: How can I make sure there is just one row with a null value in a timstamp column in table? I have a table with a column which contains a 'valid until' Date and I want to make sure that this can only be set to null in a single row within the table. Is there an easy way to do this?
My table looks like this (postgres):
CREATE TABLE 123.myTable(
some_id integer NOT NULL,
valid_from timestamp without time zone NOT NULL DEFAULT now(),
valid_until timestamp without time zone,
someString character varying)

some_id and valid_from is my PK. I want nobody to enter a line with a null value in column valid_until if there is already a line with null for this PK.
Thank you

A: In PostgreSQL, you have two basic approaches.

*

*Use 'infinity' instead of null.  Then your unique constraint works as expected.  Or if you cannot do that:

*CREATE UNIQUE INDEX null_valid_from ON mytable(someid) where valid_until IS NULL
I have used both approaches.  I find usually the first approach is cleaner and it allows you to use range types and exclude constraints in newer versions of PostgreSQL better (to ensure no two time ranges overlap based on a given given someid), bt the second approach often is useful where the first cannot be done.

A: Depending on the database, you can't have null in a primary key (I don't know about all databases, but in sql server you can't).   The easiest way around this I can think of is to set the date time to the minimum value, and then add a unique constraint on it, or set it to be the primary key.
I suppose another way would be to set up a trigger to check the other values in the table to see if another entry is null, and if there is one, don't allow the insert.

A: As Kevin said in his answer, you can set up a database trigger to stop someone from inserting more than one row where the valid until date is NULL.
The SQL statement that checks for this condition is:
SELECT COUNT(*)
FROM TABLE
WHERE valid until IS NULL;

If the count is not equal to 1, then your table has a problem.
The process that adds a row to this table has to perform the following:

*

*Find the row where the valid until value is NULL

*Update the valid until value to the current date, or some other meaningful date

*Insert the new row with the valid until value set to NULL

A: I'm assuming you are Storing Effective-dated-records and are also using a valid from date.
If so, You could use CRUD stored procedures to enforce this compliance. E.G the insert closes off any null valid dates before inserting a new record with a null valid date.
You probably need other stored procedure validation to avoid overlapping records and to allow deleting and editing records. It may be more efficient (in terms of where clauses / faster queries) to use a date far in the future rather than using null.

A: I know only Oracle in sufficient detail, but the same might work in other databases:

*

*create another column which always contains a fixed value (say '0') include this column in your unique key.

*Don't use NULL but a specific very high or low value. I many cases this is actually easier to use then a NULL value

*Make a function based unique key on a function converting the date including the null value to some other value (e.g. a string representation for dates and 'x' for null)

*make a materialized view which gets updated on every change on your main table and put a constraint on that view.
select count(*) cnt from table where valid_until is NULL
might work as the select statement. And a check constraint limiting the cnt value to the values 0 and 1

A: I would suggest inserting to that table through an SP and putting your constraint in there, as triggers are quite hidden and will likely be forgotten about. If that's not an option, the following trigger will work:
CREATE TABLE dbo.TESTTRIGGER
(
    YourDate Date NULL
)

    CREATE TRIGGER DupNullDates
ON dbo.TESTTRIGGER
FOR INSERT, UPDATE
AS
DECLARE @nullCount int
SELECT @nullCount = (SELECT COUNT(*) FROM TESTTRIGGER WHERE YourDate IS NULL)
IF(@NullCount > 1)
BEGIN
    RAISERROR('Cannot have Multiple Nulls', 16, 1)
    ROLLBACK TRAN
END

GO

A: Well if you use MS SQL you can just add a unique Index on that column. That will allow only one NULL. I guess that if you use other RDBMS, this will still function.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use conditional statement and return value for a function in R? I have to create a function as: ans(x) which returns the value 2*abs(x), if x is
negative, and the value x otherwise. What command could i use?
Thanks

A: ans <- function(x){
  ifelse(x < 0, 2*abs(x), x)
}

will do.
> ans(2)
[1] 2

> ans(-2)
[1] 4

Explanation:
We can use the built-in base R function ifelse(). The logic is pretty simple:
ifelse(condition, output if condition is TRUE, output if condition is FALSE)
Therefore, ifelse(x < 0, 2*abs(x), x) will do the following:

*

*evaluate whether value x is negative (<0)

*if TRUE, return 2*abs(x)

*if FALSE, return x
The advantage of ifelse() over traditional if() is the vectorization. if() can only handle a single value, ifelse() will evaluate any vector given as input.
Comparison:
ans_if <- function(x){
  if(x < 0){2*abs(x)}else{x}
}

This is the same function, using a traditional if() structure. Giving a single value as input will result in the same output for both functions:
> ans(-2)
[1] 4
> ans_if(-2)
[1] 4

But if you want to input multiple values, let's say
test <- c(-1, -2, 3, -4)

the ifelse() variant will evaluate every element of the vector and generate the correct output as a vector of the same length:
> ans(test)
[1] 2 4 3 8

whereas the if() variant will throw a warning
> ans_if(test)
[1] 2 4 6 8
Warning message:
In if (x < 0) { :
  the condition has length > 1 and only the first element will be used

and return the wrong output, as only the first value was used for evaluation (-1) and the operation over the whole vector was based on this evaluation.


text:
Q: Spring Boot - logging configuration from JBoss I'd like to know if there is a way to configure Spring Boot logging using JBoss standalone.xml or domain.xml configuration. For now I ended up with two empty files log4j.properties and log4j-file.properties under org\springframework\boot\logging\log4j package in mvn resources in WAR file and it looks like now my logging configuration in domain.xml works because I've overriden default spring-boot log4j configuration.
But there must be a better way to do this instead of this stupid hack. Keep in mind that I don't want to provide external log4j properties file and set it for one of the property in application.properties but I want to use jboss logging system configuration.
EDIT
Strange thing but when I updated Spring Boot to version 1.4.0 then JBoss intercepts the logs and log them only to the file and I don't have logs on the stdout anymore even without custom log4j configuration.


text:
Q: How to open a Popup in Leaflet as Hover and not on Click I want to open the popup in Angular Leaflet as a hover and not on click.
I have a markers array initialized and an overlay of a layer on top of the base layer.
I am trying to create a layer where buses and bus stops belong to each other. So each layer belongs to the same type in the overlays.
I am using the code
markers = [];
markers.push(
{ layer : layername,
          lat : latitude,
          lng : longitude,
          message: busNames(data),
   icon :{....}
 }
 });

I have another push marker set on the same layer which builds busStop data.
Now how do I display the popups when mouse is moved over them as hover instead of showing them on click
P.S - I am new to coding and hence please help me with proceeding further.

A: For each marker you are creating you have to listen to 'mouseover' and 'mouseout' events.
You open the popup when 'mouseover' is sent, close it when 'mouseout' is sent.
    var marker = L.marker([51.5, -0.09]).addTo(map);
    var tooltipPopup;

    marker.on('mouseover', function(e) {
    tooltipPopup = L.popup({ offset: L.point(0, -50)});
            tooltipPopup.setContent("Hello");
            tooltipPopup.setLatLng(e.target.getLatLng());
            tooltipPopup.openOn(map);

    });

    marker.on('mouseout', function(e) {
        map.closePopup(tooltipPopup);
    });

Here is an example

A: First, you have to include  'leafletData' to your controller, after that add 'mouseover' and 'mouseout' events to your Marker.
angular
.module('myapp')
.controller("EventsController", [ '$scope', 'leafletData', function($scope, leafletData) {

  $scope.$on('leafletDirectiveMarker.mouseover', function(event, args){
    console.log('I am over!');
    var popup = L.popup({ offset: L.point(0, -28)})
                .setLatLng([args.model.lat, args.model.lng])
                .setContent(args.model.message)
    leafletData.getMap().then(function(map) {
      popup.openOn(map);
    });
  });

  $scope.$on('leafletDirectiveMarker.mouseout', function(event){
    leafletData.getMap().then(function(map) {
      map.closePopup();
    });
  });
}]);


text:
Q: Using Anaconda for a parent image for Docker? I'm trying to slightly modify the Docker tutorial to use this as a parent image in my Dockerfile. This runs into one small problem, which is that the following statement:
FROM continuumio:anaconda3

doesn't work.
I get
Sending build context to Docker daemon  71.17kB
Step 1/7 : FROM continuumio:anaconda3
Get https://registry-1.docker.io/v2/: net/http: request canceled while     waiting for connection (Client.Timeout exceeded while awaiting headers)

when I use the
docker build

command.


text:
Q: How do I implement custom rendering logic in dust.js? I'm using dust.js to render a list of variable names that are sometimes long and contain underscores like:
SUM_COUNT_LABOR_COUNTRIES_SMS_PAST
The browser doesn't wrap on underscores so it can get ugly. I'd like my dust template to add a zero-width space after each underscore so the browser can wrap it. This definitely belongs in the template layer and not with the model, but I can't figure out how to properly achieve this with dust.js and it's otherwise very good principle of separating presentation from logic.
Do I create a "helper" function? Where do I put the helper function?
How do I call it from the template?

A: there are many ways in dust to approach this. what i think you're looking for is to probably define a dust filter. you can extend dust.filters to add your own filter. dust.filters looks like this in the source:
dust.filters = {
  h: function(value) { return dust.escapeHtml(value); },
  j: function(value) { return dust.escapeJs(value); },
  u: encodeURI,
  uc: encodeURIComponent,
  js: function(value) { if (!JSON) { return value; } return JSON.stringify(value); },
  jp: function(value) { if (!JSON) { return value; } return JSON.parse(value); }
};

so what you want to do is add another key-value to it that filters your variable. e.g. if you use underscore:
_.extend(dust.filters, {zws: function(value){ your code here}})

then you can call it in your dust template like so:
the variable is: {variable|zws}

hope this helps.


text:
Q: Cast exception in child class I have two classes ClassA and CLassB. ClassA is an abstract class. ClassB derives from ClassA. I have one DTO named ParentDTO.
public class ParentDTO
{
    public int UserId { get; set; }
}

public abstract class ClassA
{
    public abstract void CreateUser(ParentDTO dto);
}

public class ClassB : ClassA
{
    public override void CreateUser(ParentDTO dto)
    {
        Console.WriteLine("You are in class ClassB");
    }
}

Now I have one DTO(MyDTO), which derives from ParentDTO.
public class MyDTO: ParentDTO
{
    public int MyID { get; set; }
}

I have extended ClassB further:
public class ClassC : ClassB
{
    public override void CreateUser(ParentDTO dto)
    {
        var mydto = (MyDTO) dto;// This throws cast exception
        mydto.MyID=222;
    }
}

I am using the above code as :
    ClassC c = new ClassC();
    ParentDTO dto=new ParentDTO();
    c.CreateUser(dto);

Can someone please tell me how to cast DTO above in CreateUser method of ClassC. I want to use mydto.MyID in my code. I know I am doing something like casting Animal to Lion instead of Lion to Animal. But is there any way to use child DTO ID? Can someone please tell me what am I doing wrong?

A: you are just using the interface architecture in wrong way. Add get, set to ParentDTO class.

A: You can't cast a parent type variable to a child type unless it was initialized as the child type (or another type derived from the child type).
ClassC c = new ClassC();
ParentDTO dto = new MyDTO();
c.CreateUser(dto);

A: You created an instance of class ParentDTO. Casting it to MyDTO correctly yields this exception as the instance is really of type ParentDTO and not of type MyDTO.
The object instance you have there doesn't have a property with name MyID, it simply doesn't exist, so there is no way to get that - non-existing - value.
Maybe you should describe what you are trying to achieve.

A:
Can someone please tell me how to cast DTO above in CreateUser method of ClassC

No way. You created object of base type using base type in declaration. You cannot just cast it to derived type, it's illegal.
Use
ParentDTO dto=new MyDto();
Read this

A: The other answers are correct, but the reason for this behavior would be clearer with a better understanding of the difference between "static type" and "run-time type", which they do not discuss.  Static type is the type of a variable in your C# code, while run-time type is the type of an actual object in memory.
We all know that static type and run-time type may differ.  Consider:
class A { }
class B : A { }

A a = new B();

The variable a refers to an instance of type B.  The static type of the variable is A, but the run-time type of the object is B.
We can also think of a as holding a reference of type A that refers to an instance of type B.  This is allowed if and only if type B is derived from (or equal to) type A.
The following, therefore, is not allowed:
B b = new A();

Here, you are attempting to assign a reference to an instance of type A (run-time type) to a variable of (static) type B.  A is not derived from or equal to B, so the assignment is not allowed.  Similarly, the following assignments are not allowed:
string s = new object();
MyDTO dto = new ParentDTO();

The cast operator complicates things somewhat, but the underlying issue is the same: you are attempting to set a reference to point to an object whose run-time type is not derived from or equal to the static type of the reference:
A a1 = new A();
B b1 = new B();

A a2 = (A)b1;  // fine, because B is derived from A
B b2 = (B)a1;  // not allowed, because A is not derived from B.

Again, this might make more sense if we substitute object for A and string for B:
object a1 = new object();
string b1 = "Hello, World!";

object a2 = (object)b1;  // a2 now points to the string "Hello, World!";
string b2 = (string)a1;  // cast fails: the string variable can't point to an instance of `object`

Similarly, with your types:
ParentDTO a1 = new ParentDTO();
MyDTO     b1 = new MyDTO();

ParentDTO a2 = (ParentDTO)b1;  // works
MyDTO     b2 = (MyDTO)a1;;     // doesn't


text:
Q: Superpixel segmentation in R I would like to run a segmentation for the large image using the library(SuperpixelImageSegmentation). However, when I run, it has an Error

"Error in interface_superpixels(input_image, method, superpixel, compactness,  :
std::bad_alloc"

This is my script
library(SuperpixelImageSegmentation)
library(OpenImageR)
library(sp)
library(raster)
library(rgdal)
library(rgeos)
path = 'C:/Data/image1019.png'
r=raster(path)
im=as.matrix(r)
res_slic = superpixels(input_image = im,
                       method = "slic",
                       superpixel = 200,
                       compactness = 20,
                       return_slic_data = TRUE,
                       return_labels = TRUE,
                       write_slic = "",
                       verbose = TRUE)

Could you please help me to fix it?


text:
Q: EF4 code first fluent mapping does not work with inherited properties? Did anyone ever tried mapping an inherited property? Because I would be glad to hear that just works and that I am making a mistake somewhere, as I am getting the following error:
"The property 'UserName' is not a declared property on type 'Advertiser'. Verify that the property has not been explicitly excluded from the model by using the Ignore method or NotMappedAttribute data annotation. Make sure that it is a valid primitive property. "
My model looks like this:
abstract class Entity { public int Id {get; set; }}
abstract class User : Entity { public string UserName {get; set;} }
sealed class Advertiser : User { }

My AdvertisementConfiguration class looks like this:
class AdvertiserConfiguration : EntityTypeConfiguration<Advertiser>
{
   public AdvertiserConfiguration()
   {
      // the following line indirectly causes an InvalidOperationException:
      Property( x => x.UserName ).HasMaxLength(50);
   }
}

If I change the Advertiser class so that it does not inherit from User (and pull the UserName property down) then everything works just fine.

A: You can (and in this case must) define a mapping for an abstract type:
class UserConfiguration : EntityTypeConfiguration<User>
{
    public UserConfiguration()
    {
        Property( x => x.UserName ).HasMaxLength(50);
    }
}

And then add it to the model builder configurations of course:
modelBuilder.Configurations.Add(new UserConfiguration());

User is an entity - abstract, but still an entity with all mapping options.


text:
Q: Why am I getting an uncaught type error when using map in React JS jsx? I'm creating a component for selecting an input based on available options in my courses object.
I'm currently getting this error:
Uncaught TypeError: Cannot read property 'map' of undefined
Here is my code:
const SelectInput = ({name, label, onChange, defaultOption, value, error, options}) => {
    return (

            {label}

                {/* Note, value is set here rather than on the option - docs*/}
                <select name={name} value={value} onChange={onChange} className="form-control">
                <option value="">{defaultOption}</option>
                {options.map((option) => {
                    return <option key={option.value} value={option.value}>{option.text}</option>;
                })}
                </select>
                {error &&
{error}
}

    );
};

Anyone knows the reason?

A: You expect that options are an array but you provide undefined options prop, so there is no map method for undefined
Provide not undefined options or try this:
const SelectInput = ({name, label, onChange, defaultOption, value, error, options = []}) => {
  ...
}


text:
Q: Itext7 modify table width In java itext5 there is function table.setWidths() hence we can modify column widths on fly.
In itext7 table.setWidths() is not there and  new Table(colwidths) have to pass in constructor this is fixed and cannot modyify on fly.Please let me know the procedure to modify table widths like itext5.
Itext5
Table table = new Table(3);
float[] widths=new float[3.0,4.0,5.0];
table.setWidths(widths);

what is the above code itext7?


text:
Q: Prove the existence of a largest integer less than or equal to a rational number Prove that there is a largest integer $n$ such that $n \le x$ for any fixed rational $x$.
What about any fixed real number $x$?

A: The answer to your question depends on the set of facts you take for granted. In terms of elementary number theory I would argue as follows: Let $x=p/q$ with $q>0$. Then the $q$ consecutive numbers $p-q+1$, $p-q+2$, $\ldots$, $p$ form a complete residue system mod$\thinspace q$, so there is exactly one among them, say $r$, that is divisible by $q$. It follows that $n:=r/q$ is the largest integer $≤x$.

A: (Sorry to post this as an answer, but I can't comment yet). Do you mean that given a fixed rational number $x$, the set $\lbrace n: n\leq x, n \in \mathbb Z\rbrace$ has a maximum? (Hint: Use the well-ordering principle)

A: First, as a clarification pointed out by Dactyl, you probably want a proof of:
For any rational (or real) $x$, there is a largest integer $n$ such that $n \leq x$.
The reversal of words makes the claim false because it says that there is a fixed largest integer $n$ less than or equal to arbitrarily large $x$.
Also for Dactyl's hint, you have to be careful when $x$ is negative because the well-ordering principle is for Natural numbers.  Specifically, not every nonempty subset of the integers has a smallest element (e.g., the integers themselves have no least element).  However, every nonempty subset of the integers that has a lower bound has a least element, and you can prove this by induction on the absolute value of an integral lower bound.
Of course, $n$ is typically used to denote a Natural number so maybe you're restricting yourself to nonnegative $x$ anyway.

Edit (in response to request for different proof):
Consider $\{n \in \mathbb{N}| |x| < n\}$.  The Archimedean property tells us that for any Real number, we can find a Natural number that's larger so this set is non-empty.  Then by the well-ordering of the Natural numbers, there exists a least element in this set, call it $n_0$.  If $x \geq 0$, verify that $n_0 - 1$ is the desired integer, and if $x < 0$, verify that that $1 - n_0$ is the one you want if $x$ is an integer and $-n_0$ otherwise.

A: Since the problem is tagged "real analysis", I'd just use the supremum of the set $\{ n \in \mathbf{Z} : n \le x \}$. Of course, you need to prove that this set is not empty and that the supremum is actually a maximum.


text:
Q: Typescript: Object is possibly 'undefined' I'm curious as to why I would be getting a Typescript warning below.
There error appears on this line: a[k].toString().toLowerCase()
However I have the check if (a && a[k]) which should ensure that in the next line, a and a[k] cannot be undefined?
// Return coins that match text search by currency symbol or name.
export const findAsset = (txt: string, assets: IAsset[] | null[]) => {
  // assets will exist here...
  if (assets) {
    // Typescript error here...
    const checkText = (k: string, a: IAsset | null) => {
      if (a && a[k]) {
        return (textMatch(txt.toLowerCase(), a[k].toString().toLowerCase()) ? a : null);
      }
    }
    const curriedCheckText = R.curry(checkText);
    const byName = R.map(curriedCheckText('name'), assets);
    const bySymbol = R.map(curriedCheckText('currency'), assets);
    const matchNames = R.reject(R.isNil, byName);
    const matchSymbols = R.reject(R.isNil, bySymbol);
    const combinedSearch = (matchNames.concat(matchSymbols));
    return R.uniq(combinedSearch);
  }
  else {
    return [];
  }
};

This is the shape of the IAsset interface
export interface IAsset {
  [key: string]: string | number | undefined | boolean;
  availableSupply?: string;
  currency: string;
  exchange: string;
  exchange_base?: string;
  marketCap: number;
  name: string;
  percentage?: number;
  price: number;
  position?: number;
  value?: number;
  inWatchlist?: boolean;
}

tsconfig
{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
    "lib": [
      "dom",
      "es2015",
      "es2016",
      "es2017",
    ], /* Specify library files to be included in the compilation. */,
    "allowJs": true,                       /* Allow javascript files to be compiled. */
    "checkJs": true,                       /* Report errors in .js files. */
    "jsx": "react",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "removeComments": true,                /* Do not emit comments to output. */
    "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    "resolveJsonModule": true,
    "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true /* Enable all strict type-checking options. */,
    "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
    "strictNullChecks": true /* Enable strict null checks. */,
    "strictFunctionTypes": true /* Enable strict checking of function types. */,
    "strictBindCallApply": true /* Enable strict 'bind', 'call', and 'apply' methods on functions. */,
    "strictPropertyInitialization": true /* Enable strict checking of property initialization in classes. */,
    "noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */,
    "alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */,

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
  },
  "include": [
    "components/**/*",
    "pages/**/*",
  ],
  "exclude": [
    "node_modules",
    "styles",
    "_document.tsx"
  ]
}

A: Not sure if this is 100% applicable to your question, ever since TypeScript 3.7 is released, the use of optional chaining (? operator) is definitely another relevant solution to be explored. You may install the latest stable version of TypeScript:
npm install typescript

As such, checkText can be simplified by using the optional chaining operator.
const checkText = (k: string, a: IAsset | null) => {
  return (textMatch(txt.toLowerCase(), a?.[k].toString().toLowerCase()) ? a : null);
}

A: There are two ways to that I can think of to get rid of the error.
The first way I can think of is to use a fallback with the || operator, which would turn this:
a[k].toString().toLowerCase()

Into this, so if the value is falsy, then use an empty string.
(a[k] || '').toString().toLowerCase()
// Or with optional chaining
a[k]?.toString().toLowerCase() || ''

Note: Use ?? to catch only undefined and null values instead of falsy values.
The other way is to save the value to a variable and check the new variable. Which then makes this
if (a && a[k]) {
  return textMatch(txt.toLowerCase(), a[k].toString().toLowerCase()) ? a : null;
}

Become this:
let v = a ? a[k] : null
if (v) {
  return textMatch(txt.toLowerCase(), v.toString().toLowerCase()) ? a : null;
}

A: Supress the error in VUE templates
If you understood the error and want to know how to handle it in VUE templates: simply put a condition in the parent element

Hallo {{user.firstName}}

A: Typescript doesn't keep type information about values at specific array indices. For example, this is an error:
function test(a: (number | string)[]) {
    if (typeof a[3] === "number") {
        const num: number = a[3];
    }
}

To get something that can have type information, you could put a[k] into some other variable like this:
const checkText = (k: string, a: IAsset | null) => {
if (a) {
  const atK = a[k];
  if (atK) {
    return (textMatch(txt.toLowerCase(), atK.toString().toLowerCase()) ? a : null);
  }
}

or you could cast it, because you know more about the types than the type system:
const checkText = (k: string, a: IAsset | null) => {
  if (a && a[k]) {
    return (textMatch(txt.toLowerCase(), (a[k] as string | number | true).toString().toLowerCase()) ? a : null);
  }
}

or you could avoid having to worry about undefineds by using string interpolation:
const checkText = (k: string, a: IAsset | null) => {
  if (a && a[k]) {
    return (textMatch(txt.toLowerCase(), `${a[k]}`.toLowerCase()) ? a : null);
  }
}

Ideally the type system would take care of these things, but I'm sure there's some reason why this kind of type information isn't available in general.

A: In Angular, i put ngIF and solved the problem for me.

  <input
    [(ngModel)]="user.firstName"
    placeholder="Placeholder"
    id="first_name"
    type="text"
    class="validate"
  />
  First Name

A: You can use ! so that the error "Object is possibly 'undefined'" no longer occurs. a[k]!.toString().toLowerCase()
<ng-container *ngIf="comment.children && comment.children!.length > 0">
    // your code here
</ng-container>


text:
Q: Were medals awarded after the destruction of the second Death Star? In Star Wars: Episode IV: A New Hope, medals are awarded to the people who destroyed the original Death Star.  In Star Wars: Episode VI: Return of the Jedi, another Death Star is destroyed.
Were medals awarded again, off-screen?

A: SOME medals were definitely awarded.

*

*Star Wars Insider #160 had a story in its "Exclusive fiction" section called "Blade Squadron: Zero Hour".
In it, it mentioned that all B-Wing pilots got Medal of Bravery.

The ceremony on the flight deck was short and to the point... before proceeding to award the B-Wing pilots who had survived the battle of Endor their Medals of Bravery.

*Aftermath mentions medals to Y-Wing pilots too:

Since she joined the fight, she has had two moments when she wept. The first was only months earlier, after the battle over Endor had concluded; after she and her Y-wing (and her laser-crisped astromech) emerged from the labyrinth of half-constructed passages inside the second Death Star—just escaping in a plume of flame as the whole thing began to implode and then explode behind her, the shock waves causing her little fighter to tumble end-over-end until she almost passed out. That night, she sat alone in a changing room on the star cruiser Home One, and sitting there half in and half out of her jumpsuit, she wept. Like a baby without its mother. Hard, racking sobs hit her like crashing waves until she was curled up on the floor, feeling gutted. A day later, she got her medal. She smiled, turned toward the applause of the crowd. She didn't show them how stripped-down and scraped-clean she really felt.

*I saw mentions of posthumous medal to Arvel Crynyd (A-Wing pilot who flew into SSD's bridge). But couldn't find canon source for that.
Basically, what this tells me is that everyone pretty much got a medal, we simply don't have one single Yavin-like ceremony, because:

*

*The Rebellion got too big, physically/logistically, to fit into a large hall

*They were too busy rushing to organize the next steps of the war - both "Aftermath" and Insider's story allude to that pretty strongly. Unlike EU with its Yawn at Bakura, New Disney canon basically doesn't STOP the war at Endor, it STARTS it for realz.


text:
Q: Is there a way to make a dropdownlist inside a TabBar in Flutter? I'm trying to add a DropDownList inside a TabBar items so the user can select the dropdown item before the tabbarwiew changes the widget. I tried to make this, but it changes the TabBarView widget before showing the DropDownList items:
tabs: [
          const Tab(
            text: 'Home',
          ),
          const Tab(
            text: 'About us',
          ),
          DropdownButton(
            value: selectedValue,
            items: menuItems, onChanged: (String? value) {
              print(value);
            },
          ),

If it's not possible can you suggest an alternative, please?

A: Yes, it is possible to have DropdownButton as Tab.
tabs: takes list of widget and DropdownButton is a widget, you can simply use it.
 String? selectedValue;

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      initialIndex: 1,
      length: 4,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('TabBar Widget'),
          bottom: TabBar(
            tabs: <Widget>[
              Tab(
                icon: Icon(Icons.cloud_outlined),
              ),
              Tab(
                icon: Icon(Icons.beach_access_sharp),
              ),
              Tab(
                icon: Icon(Icons.brightness_5_sharp),
              ),
              DropdownButton<String?>(
                value: selectedValue,
                onChanged: (value) {
                  setState(() {
                    selectedValue = value;
                  });
                  print("value");
                },
                items: ["A", "B", "C"]
                    .map(
                      (e) => DropdownMenuItem(
                        child: Text(e),
                        value: e,
                      ),
                    )
                    .toList(),
              ),
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            Center(
              child: Text("It's cloudy here"),
            ),
            Center(
              child: Text("It's rainy here"),
            ),
            Center(
              child: Text("It's sunny here"),
            ),
            Center(
              child: Text("TabBar here ${selectedValue ?? "select 1st"}"),
            ),
          ],
        ),
      ),
    );
  }


text:
Q: Same maximum entropy and measures As the author Christian Robert asks about reference measures that are absolutely continuous to one another, and from what I can gather this just means they have the same null set? But would that not be true for any continuous distribution? Since from what I can gather, Lebesgue is zero over points, non zero over intervals or such. Similar to continuous distributions which are zero at any given point.
Some people pointed out that not all distributions have this , for example the cantor distribution, because it does not have a density.
So the author pointed out, it is really about having a density not just a distribution.
I am trying to work through some of the examples and problems. One talks about that if we have absolutely continuous measures, then we can construct example where corresponds maximum entropy distributions are the same.
So this leads me to think, that the reference measure does not uniquely determine the maximum distribution? Ie, if they are absolutely continuous, then it may be ( or will be?), the same. And I am wondering why this would be true.
I get the formula, but wouldn't they normalise differently? How would it end up being the same distribution?
An example given is Lebesgue measure and standard normal. Since standard normal has a density, I think this is an example of absolute continuity. I am thinking they may give the same when the two measure have no distance between them? with known expected value and variance as constraints, we could find the Lagrange multipliers. But we will still have $\frac{1}{\sqrt{2\pi}}exp(\frac{-\theta^{2}}{2})$ But since its a density, wont it simply integrate to 1 as well
with the normal, so even if both can be normalised I have trouble seeing how it gives the same max entropy. That is, I am wanting to see how different reference priors can lead to the same max entropy.
More my thoughts:
So, for a standard normal reference prior, since we know mean and variance I assume we could write it as
$\pi^{*}(\theta)$ $\alpha$ $\exp(\lambda_{1}\theta+\lambda_{2}\theta^{2})\exp(\frac{-\theta^{2}}{2})$
Which I guess has the same form with a factor, would it still give the same normal though?
$\exp(\lambda_{1}\theta+(\lambda_{2}-\frac{1}{2})\theta^{2})$
And as seen previously , for Lebesgue measure with known mean and variance,
$\pi^{*}(\theta)$ $\alpha$ $\exp(\lambda_{1}\theta+\lambda_{2}\theta^{2})$
So both are normalise, but I have trouble seeing how they will correspond to same distribution. The second one is a normal with mean 0 and variance $\sigma^{2}$ unless the factor in the first just would change the Lagrange, and leave with same normal

A: The point I am making in my book and in the previous question is not original but worth repeating. For a dominating measure $\text{d}\mu$, the maximum entropy prior is defined as maximising$$\int_\mathcal{X}\log p(x) \text{d}\mu(x)$$in the density $p$ under a set of constraints$$\mathbb{E}_p[g_k(X)]=\int_\mathcal{X} g_k(x) p(x) \text{d}\mu(x)=\omega_k\qquad k=1,\ldots,K$$including$$\int_\mathcal{X} p(x) \text{d}\mu(x)=1$$
If there is such a probability distribution, then it is given by
$$p(x) = \exp\{\lambda_1 g_1(x)+\cdots+\lambda_K g_K(x)\}\Big/
\int_\mathcal{X} \exp\{\lambda_1 g_1(x)+\cdots+\lambda_K g_K(x)\} \text{d}\mu(x)$$whose notation is simplified into
$$p(x) \propto \exp\{\lambda_1 g_1(x)+\cdots+\lambda_K g_K(x)\}$$
to avoid dragging the denominator into every equation.
This being a density against $\text{d}\mu$, changing the measure changes the resulting density and the resulting distribution. Except in your example where you unfortunately chose to move from the measure $\text{d}\mu$ to the measure $e^{-x^2/2}\text{d}\mu$ and a constraint involving $g_2(x)=x^2$: in this case the maximum entropy prior distribution is the same for both measures. Indeed, they both have the same dominating measure $\text{d}\mu$ and the same defining equations:
\begin{align*}
p_1(x)\text{d}\mu &\propto\exp\{\lambda_1 x+\lambda_2 x^2\}\text{d}\mu\\
p_2(x)e^{-x²/2}\text{d}\mu &\propto\exp\{\lambda_1^\prime x+\lambda_2^\prime x^2\}e^{-x²/2}\text{d}\mu\\
&=\exp\{\lambda_1^\prime x+(\lambda_2^\prime -1/2)x^2\}\text{d}\mu\\
\end{align*}
Hence$$\lambda_1=\lambda_1^\prime\qquad\lambda_2=\lambda_2^\prime -1/2$$and the probability distributions are the same distributions even though $p_1(\cdot)\ne p_2(\cdot)$.
If, for this example of the first two moments [meaning $g_1(x)=x$ and $g_2(x)=x^2$], I choose instead to replace the Lebesgue measure $\text{d}x$ with the new measure $|x|^{-1/2}\text{d}x$, which is absolutely continuous wrt the Lebesgue measure, the corresponding maximum entropy prior distributions will differ since their density wrt the Lebesgue measure will be
\begin{align*}
p_1(x)\text{d}\mu &\propto\exp\{\lambda_1 x+\lambda_2 x^2\}\text{d}\mu\\
p_2(x)|x|^{-1/2}\text{d}\mu &\propto\exp\{\lambda_1^\prime x+\lambda_2^\prime x^2\}|x|^{-1/2}\text{d}\mu\\
\end{align*}
For $\omega_1=0$ and $\omega_2=1$, the first solution $p_1(\cdot)$ is the density of the standard Normal distribution, while the second one satisfies
$$\int_{-\infty}^\infty \frac{x}{\sqrt{|x|}} \exp\{\lambda_1'x+\lambda_2'x^2\}\text{d}x=0$$
which is achieved when taking $\lambda_1'=0$ and implies that
$$p_2(x)\propto \exp\{ \lambda_2^\prime x^2\}|x|^{-1/2}$$The normalising constant is thus given by
$$\int_{-\infty}^\infty \exp\{ \lambda_2^\prime x^2\}|x|^{-1/2}\text{d}x
\overbrace{=}^{y=x^2}2\int_0^\infty \exp\{ \lambda_2^\prime y\}|y|^{-1/4}\underbrace{y^{-1/2}\text{d}y/2}_\text{Jacobian}=\Gamma(1/4)(-\lambda_2^\prime)^{-1/4}$$
The second parameter is determined by the constraint
$$\int_{-\infty}^\infty x^2 \exp\{ \lambda_2^\prime x^2\}|x|^{-1/2}\text{d}x =1 \times \Gamma(1/4)(-\lambda_2^\prime)^{-1/4}$$
or $$2\int_0^\infty \exp\{ \lambda_2^\prime y\}|y|^{1+1/4-1}\text{d}y/2= \Gamma(5/4)(-\lambda_2^\prime)^{-5/4}=
\Gamma(1/4)(-\lambda_2^\prime)^{-1/4}$$which simplifies as
$$\frac{1}{4}(-\lambda_2^\prime)^{-1}=1\quad\text{i.e.}\quad\lambda_2=-1/4$$
These two distributions share the same first two moments but are clearly not identical distributions
$$p_1(x)=\dfrac{\exp\{-x^2/2\}}{\sqrt{2\pi}}\qquad p_2(x)=\dfrac{\exp\{-x^2/4\}}{\Gamma(1/4)(1/4)^{-1/4}}$$


text:
Q: How to multiply a row of an array by the value stored in the corresponding row of a vector? I have the following setup:
a = np.asarray([[1, 2, 3], [4, 5, 6]])
s = np.asarray([1, 2])

I would like to multiply a[0] * s[0] and a[1] * s[1] to get
[[1, 2, 3],
 [8, 10, 12]]

How can I do this easily? And if possible, I would like to avoid a reshape.

A: a * s[:, np.newaxis]

Broadcasting goes through the shapes in the opposite direction from what you want, so we stick another axis in there. (This is very similar to a reshape.)


text:
Q: Loop for offset and limit in a request I need some help to make a loop to execute my request in api.
I have a request that is only permited requests with a limit and offset, but the request show only data every 100.
I set manually the limit to 100 and offset to 0, but i'll automate this request, so i need automate this too.
I need that the variable offset and limit sum 100 in the value and do the same request, but the variables changed.
Ex:
First request: offset = 0, limit = 100, Second request: offset = 100, limit = 200, Third request: offset = 200, limit = 300, Fourty request: offset = 300, limit = 400...
When the offset is 3000 i need to stop.
I use this variables in url_no = ...
$offset = 0; // Começa do registro 'x';
$limit = 100; // Vai até o registro 'x';

//Var URI:
    $url_no = "https://".$account['baseuri']."/messaging_history/api/account/".$account['id']."/conversations/search?offset=".$offset."&limit=".$limit;

A: i think this should do it :
$limit = 100;

For($i=0 ; $i < sizeof($request) ; $i++){
$offset=$limit - 100;
$limit += 100;
echo $offset,$limit
}

Results:
0,100 100,200 200,300 ,...

A: To make it right, i did this:
$request = 3000;

For($i=0 ;  $offset < $request ; $i++){
$limit = 100;
$offset = $limit*$i;
echo "<pre>";
echo $offset . " " .  $limit;
echo "</pre>";
}

And my result was:


text:
Q: Cannot cast a generic type to list in C# I am trying to do a simple test, in which I pass in two generic objects to a test function, see if they can be cast to List<S>, and further, check if the counts of the lists are equal.
The following code works:
private static void Test<T> (T obj1, T obj2) {
    if (typeof(T).IsGenericType) {
        var genericTypeParam1 = typeof(T).GetGenericArguments().First();
        Console.WriteLine(genericTypeParam1);

        // LINE MARKER 1
        // var obj1AsList = (obj1 as IEnumerable<genericTypeParam1>);
    }
}

static void Main(string[] args) {
    Test(Enumerable.Range(0, 5).ToList(), Enumerable.Range(0, 5).ToList());
    Console.ReadLine();
}

But if I uncomment the line marked with LINE MARKER 1, I get the following error:
The type or namespace name 'genericTypeParam1' could not be found (are you missing a using directive or an assembly reference?)

I do not know beforehand that Test will receive Lists.  But my intention is to first check if obj1 and obj2 can be taken as lists, and then to compare
var obj1AsList = obj1 as List<genericTypeParam1>;
var obj2AsList = obj2 as List<genericTypeParam1>;
var flag = (obj1AsList != null) && (obj2AsList != null) && (obj1AsList.Count() == obj2AsList.Count());

Thanks in advance for your help.

A:
I am trying to do a simple test, in which I pass in two objects to a test function, see if they can be cast to List<S>, and further, check if the counts of the lists are equal.

The correct way to do that is:
static bool Test<T>(object obj1, object obj2)
{
    List<T> list1 = obj1 as List<T>;
    List<T> list2 = obj2 as List<T>;
    return list1 != null && list2 != null && list1.Count == list2.Count;
}
...
bool result = Test<int>(Enumerable.Range(0, 5).ToList(), Enumerable.Range(0, 5).ToList());

This takes two objects and a type, and returns true if the objects are equally-sized lists of that type.

A: Type provided as generic type parameter has to be known at compile time. You're trying to pass Type typed variable instead, and that's why you're getting compile type error.
You can make the fact, that only List<T> instances can be passed as method parameters check by compiler during compilation time:
private static void Test<T>(List<T> obj1, List<T> obj2)
{
    var flag = obj1 != null && obj2 != null && obj1.Count == obj2.Count;
}

If you want that test to be done during runtime you should use solution provided by Eric.

A: If the true goal is to ensure that both items can be cast to some generic list type, then just as-cast the objects into the non-generic IList interface. Then you can compare the count:
private static bool Test<T>(T obj1, T obj2)
{
    if (typeof(T).IsGenericType)
    {
        var obj1List = obj1 as System.Collections.IList;
        var obj2List = obj2 as System.Collections.IList;

        if (obj1List != null && obj2List != null && obj1List.Count == obj2List.Count)
            return true;
    }
    return false;
}

If you really want to use reflection it you might make something like this work:
if (typeof(T).IsGenericType) {
        var genericTypeParam1 = typeof(T).GetGenericArguments().First();
        Console.WriteLine(genericTypeParam1);

        // LINE MARKER 1
        // var obj1AsList = (obj1 as IEnumerable<genericTypeParam1>);
        var genericListType = typeof(IEnumerable<>).MakeGenericType(genericTypeParam1);

        Convert.ChangeType(obj1,genericListType);
    }


text:
Q: how can i validate the date for my reservation? I made a reservation form, and I need a date validation.
If the date is less than the current date, it should show an alert message saying "Please select a higher date" the stay on the page to change the date. But there is problem in my alert: when I choose a higher date, it still shows the alert message.
Here is my code:
<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="tcal.css" />
<link rel="stylesheet" type="text/css" href="style.css" />
<link href="bootstrap/css/bootstrap.css" rel="stylesheet"/>

<?php
session_start();
$message=''; //error message
$reserve=@$_POST['reserve'];
$dayCount = date("d");
$year = date("Y");
$month = date("m");
$currentDate = $year.'-'.$month.'-'.$dayCount;

if ($reserve <= $currentDate){
  ?>

  <?php
  }

 ?>

<form action="all.php" method="post" onsubmit="return myFunction()">

<fieldset>
<legend>Contact Details</legend>

<input type="text" name="name" class="txt" placeholder="Full Name:" />

<input type="text" name="address" class="txt" placeholder="Address:" />

<input type="text" name="contact" class="txt" placeholder="Contact Number:" />

<input type="text" name="email" class="txt" placeholder="Email Address:" />

</fieldset>

<fieldset>
<legend>Reservation Details</legend>

        Date

        <input name="reserve" type="text" class="tcal txt-reg" id="fgh"/>

<select class="txt-reg" name="users" onchange="showUser(this.value)">
<option >Select a time:</option>
<option value="1">DayTime</option>
<option value="2">NightTime</option>
<option value="3">OverNight</option>
</select>

Person info will be listed here.

<select class="txt-reg" name="Cot" onchange="showCottage(this.value)">
<option >Select a cottage:</option>
<option value="4">Cottage1</option>
<option value="5">Cottage2</option>
<option value="6">Cottage3</option>
<option value="7">Cottage4</option>
<option value="8">Cottage5</option>
<option value="9">Cottage6</option>

<option value="10">Cottage7</option>
<option value="11">Cottage8</option>
<option value="12">Cottage9</option>
<option value="13">Cottage10</option>
<option value="14">Cottage11</option>
<option value="15">Cottage12</option>

<option value="16">Cottage14</option>
<option value="17">Cottage15</option>
<option value="18">Cottage16</option>
<option value="19">Cottage17</option>
<option value="20">Cottage18</option>
<option value="21">Cottage19</option>

<option value="22">Cottage20</option>
<option value="23">Cottage21</option>
<option value="24">Cottage22</option>
<option value="25">Cottage23</option>
<option value="26">Cottage24</option>
<option value="27">Cottage25</option>

<option value="28">Cottage26</option>
<option value="29">Cottage27</option>
<option value="30">Cottage28</option>
<option value="31">Cottage29</option>
<option value="32">Cottage30</option>
<option value="33">Cottage31</option>

<option value="34">Cottage32</option>
<option value="35">Cottage33</option>
<option value="36">Cottage34</option>
<option value="37">Cottage35</option>
<option value="38">Cottage36</option>
<option value="39">Cottage37</option>

<option value="40">Cottage38</option>
<option value="41">Cottage39</option>
<option value="42">Cottage40</option>
<option value="43">Cottage41</option>
</select>

Price of cottage will show here.

Adult's Head Count :

<input type="text" class="txt-reg" name="headcount1" value="0" />

Children's Head Count :

<input type="text" class="txt-reg" name="headcount2" value="0" />

<input type="submit" value="Calculate Discount" />

</fieldset>

</form>

A: Use strtotime() function like below:
if (strtotime($reserve) <= strtotime($currentDate))

instead of
if ($reserve <= $currentDate)

A: Your Javascript myFunction() is between 2 blocks of PHP and not inside PHP. Then it loads unconditionnaly.
You have to structure your code differently. onsubmit="return myFunction()" could become onsubmit=<?php comparison and if needed echo "alert('...')" else echo "#"?>
Double quotes for PHP and simple quotes for Javascript to avoid an error in interpretation.
Of course if you want to use PHP. You can also compare the dates in Javascript.

A: I am suggest you to add jquery.js,bootstrap.js and bootstrap date picker file and add following code. you don't need to validate for past date it will disable.

var date = new Date(); date.setDate(date.getDate()-1);
$('.txt-reg').datepicker({
      startDate: date });


text:
Q: Google Data Studio: Connect to multiple schemas in multi-tenant postgres DB I have a multi-tenant database in postgres. So, I have one schema per customer and each schema has a fixed set of tables.
When I connect to the DB using Google Data Studio(GDS), I only see the table names without their associated schema.
How do I connect to tables belonging to one or more schemas?
Also, what do I do if my tables have more than 700k rows, as GDS has a limit on number of rows that can be queried right?

A: You'll have to use the "Custom Query" option instead of the basic table selection if you need anything more complex.
Regarding the row limit. I wasn't aware of the limit, but if that is true I'd suggest using the Custom Query to pre-group your rows in the query into whatever makes sense...days...months...etc to bring the row count down.
Data Studio will likely choke on anywhere near that many rows and make for a horrible user experience. Let Postgres do as much of the heavy lifting as you can.

A: Answering only: "what do I do if my tables have more than 700k rows, as GDS has a limit on number of rows that can be queried right?"
Not exactly. The limit is on the number of rows returned, not the amount of rows queried. And that matters since Data Studio will almost always push down queries to connectors.
Here's an example: Lets say you have a purchase table in a PostgreSQL db with 1M+ rows where each record is a purchase event. You add this table as a data source in your report and add a bar chart that shows average purchase by customer type. Let's say you have 12 customer types. Data Studio will then push down the GROUP BY clause to the PostgreSQL db. Thus, your result will have only 12 rows of data instead of 1M+. In most chart types, Data Studio will aggregate or page the results thus issuing a query statement that limits the number of rows returned.
You will only run into the limit if you end up creating a scenario where Data Studio cannot issue an aggregation or paging over the query results or if the aggregated results cross the row limit.


text:
Q: ESLint activate option to notify "Object is possibly null" For some reason, my .eslintrc.json has some option, or has a lack of some option to catch the warning

Object is possibly 'null'

What I need to change to eslint notify my about this warning?
IMPORTANT this is on my unit tests, so adding strictNullChecks does not work for my project, that why I asked if eslint has an option for that.
{
  "settings": {
    "react": {
      "version": "latest"
    }
  },
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": ["eslint:recommended", "plugin:react/recommended", "plugin:@typescript-eslint/recommended", "prettier"],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 12,
    "sourceType": "module"
  },
  "plugins": ["react", "@typescript-eslint"],
  "rules": {
    "@typescript-eslint/no-inferrable-types": "off"
  },
  "ignorePatterns": ["dist/*"]
}

My tsconfig.json
{
  "exclude": ["lib/**/*.spec.tsx", "lib/**/*.stories.tsx", "lib/**/*.styles.tsx", "settings/**/*", "dist/**/*"],
  "compilerOptions": {
    "skipLibCheck": true,
    "target": "es5",
    "lib": ["es5", "dom"],
    "jsx": "react",
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "outDir": "dist",
    "rootDirs": ["lib"],
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strictNullChecks": true
  }
}

A: In your tsconfig.json file under "compilerOptions", you want to set "strictNullChecks" to "true":
{
    "compilerOptions": {
        "strictNullChecks": true,
    }
}

That will make typescript warn you when a value is possibly null.  I don't think you can make eslint do it for you.

A: ESLint cannot lint or warn about types only typescript can do it.
You want to have 2 tsconfig.json fles, tsconfig.test.json and tsconfig.json
The tsconfig.json should be like:
{
    ...
    "compilerOptions": {
        "strictNullChecks": true,
    }
}

and the tsconfig.test.json should be like:
{
    "extends": "./tsconfig.json",
    ...
    "compilerOptions": {
        "strictNullChecks": false,
    }
}

This way the script null check will not be checked during test run.

A: The problem was on the line:
"exclude": ["lib/**/*.spec.tsx", ...

Because of that, the tests are being ignored.


text:
Q: How to fuse batteries connected in series? Is it possible to wire each battery in a series to the next using a fuse wire, so that the individual batterie's max power output is not exceeded?
here is an illustration, suppose each battery had a maximum safe output of 60w, would it be possible to use 60w fuse wire in the place of the blue lines?

A: The question contains some errors but I will try to answer what I think you are really asking.  You're talking about fuses (fuse wire) so clearly you are interested in trying to protect the circuit.
When batteries are connected in series, the same current flows through all batteries.  So you need a single fuse to protect them all.
Actually fuses are often used to protect the cable, and so fuses should be set to a lower rating than the current the cable can carry.
If you really are talking about resistors and putting them in series with the batteries: then standard formulae apply: power W = I.I.R  (I squared R).  V = I.R , W = V.I and all the other permutations of these formulae.
So you have to ensure that the power dissipated by the resistor does not exceed the maximum power rating for that resistor. If it does, the resistor will become excessively hot and burn out.
The voltage you know, the maximum current you know or you can calculate, and so you can calculate the power dissipated by the resistor.
You don't need fuse wire in each position. Fuse wire - of the correct rating - in one position is enough.
Let's spend a moment talking about fuse wire. Fuse wire is specified in Amps, as to how much current it can handle before it breaks.  Fuse wire is not specified in W - watts.
Watts = volts x current. And the voltage doesn't matter, because it's an electrical conductor (made of metal), the voltage at any point along the fuse wire is the same (that's not entirely true, but good enough for discussion here).
So you're only interested in current when talking about fuse wire, which is measured in amps.

A: For series-connected batteries, you need only one fuse in series.
For parallel/series connected batteries (like in the Tesla), each group of series-connected batteries needs its own fuse.
Note that there are some conceptual issues with the question:

*

*Fuses are not rated in W, but in A (although a fuse will also have a maximum voltage rating).

*Batteries may have a maximum rated output current, which may be the 15A to which you refer, but it is rare to see the specification in W (maximum current times cell voltage).

*A common parameter is the Ahr rating which is (simplistically) a measure of the current capacity of a battery expressed as a nominal current draw (A) multiplied by the time in hours that the battery can deliver it (hr). You can convert this to energy (J) by multiplying by the voltage (and converting hr to s).

EDIT: The OP just added a diagram showing a different battery connection (from the Tesla?) which shows an extreme form of serial/parallel connection. Banks of individual cells are connected in parallel, and these banks are then connected in series. With this arrangement, you do indeed need a fuse on every battery. The advantage is that a failed battery (fuse) will remove only one battery from the pack and not (too much) affect the voltage/current characteristics of the overall pack. The first diagram does, however, show several cells in series - in this case only one fuse is required.
A WARNING: Connecting large numbers of lithium cells in series/parallel can achieve life-threatening voltages, and very high currents capable of doing serious damage to electronics and wires. High risk of fire too. Take care!


text:
Q: HTML only- create a popup window from image I have a very simple HTML web page that has one large image on it with several text boxes (drawn in the image) that I would like to have a user click on and a popup window open up with more text. Currently, I'm using hotspots and the behaviors tag in Dreamweaver to call a pop-up window for each box on the image.
Q1 - How do I hide the scrollbars on the popup window in HTML?
Q2 - Is there a better way to do this with little coding like a modal popup? I have lots of these popups with different text in each I will need.
Thank you in advance!

A: To hide the scroll bar there is some CSS you can use, attached below. And for making popups, I have never tried hotspot and behavior tag however I just created one a few days ago using position absolute and using display none and block. Basically, you have to create the whole design of your popup anywhere in the code and you then set it to display: none, and whatever click you have for it to pop up, you add a little javascript function to it which will change the properties of that popup to display: block or anything else that you are using.
::-webkit-scrollbar {
    width: 0;  /* Remove scrollbar space */
    background: transparent;  /* Optional: just make scrollbar invisible */
}


text:
Q: C++ Windows Form Application accessing another form on button click I have created Windows Form Application with C++ in Visual Studio 2010. I have created two forms (Form1, Form2). I added button to Form1. Now I want on button click go to Form2 (hide Form1).
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

             }

What is the right way to do this?
I've tried this:
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
                 Form2->ShowDialog();
             }

But that gives me this error while building:
error C2065: 'Form2' : undeclared identifier
error C2227: left of '->ShowDialog' must point to class/struct/union/generic type
1>          type is ''unknown-type''

A: I forgot to include in "Form1.h":
#include "Form2.h"

Then in Form1.h:
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
                 Form2 ^ form2 = gcnew Form2;
                 form2->Show();
             }


text:
Q: Weird bug in program that "turns off" certain objects after they are used I'm trying to create a "text based game" in a window, using fonts and makeshift buttons. Everything works fine, but when there are multiple buttons on the screen and only one is pressed, the others' collisions carry over to the next screen and mess everything up. While doing debugging, I noticed that pressing the button on the next screen briefly works, but then goes to the 2nd button from the first screen, ex. I press the first button, button on second screen works, but bugs out by triggering the second button on the first screen. Here's the code:
import pygame, sys
from pygame.locals import *

pygame.init()

window = pygame.display.set_mode((640, 480))

starting = 0
choiceNum = 0
isReady = False
isReady2 = False

#old debug tool - hasBeenClicked = False

fList = []

FONTtitle = pygame.font.SysFont('arial black', 20)
FONT = pygame.font.SysFont('arial black', 15)

YELLOW = (255, 255, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 40)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

class StoryFont():
    def __init__(self, FONT, string, x, y, window):
        self.FONT = FONT
        self.string = string
        self.x = x
        self.y = y
        self.window = window
        self.fSFont = 0

    def create(self):
        self.fSFont = self.FONT.render(self.string, False, WHITE)
        self.fSFontr = self.fSFont.get_rect()
        self.fSFontr.center = (self.x,self.y)

    def blit(self):
        self.window.blit(self.fSFont, self.fSFontr)

class Button():
    def __init__(self, FONT, string, x1, y1, x2, y2, fontx, fonty, choiceNum, window):
        self.FONT = FONT
        self.string = string
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
        self.fontx = fontx
        self.fonty = fonty
        self.choiceNum = choiceNum
        self.hasBeenClicked = False
        self.window = window
        self.fSFont = 0

    def create(self):
        self.fSFont = self.FONT.render(self.string, False, WHITE)
        self.fSFontr = self.fSFont.get_rect()
        self.fSFontr.center = (self.fontx, self.fonty)
        self.window.blit(self.fSFont, self.fSFontr)

        if self.hasBeenClicked == False:
            if pos[1] >= self.fonty - 17.5 and pos[1] <= self.fonty + 17.5 and pos[0] >= self.fontx - 47.5 and pos[0] <= self.fontx + 47.5:
                pygame.draw.rect(window, BLUE, ((self.x1, self.y1), (self.x2, self.y2)), 0)
                window.blit(self.fSFont, self.fSFontr)

                if pygame.mouse.get_pressed()[0] == True:
                    global starting
                    self.hasBeenClicked = True
                    starting = self.choiceNum
                    isReady2 = False
                    window.fill(BLACK)
                    return starting

            else:
                global isReady2
                isReady2 = False

def blitMenu(FONTtitle):
    pygame.display.set_caption("Text Game")
    fTITLE = StoryFont(FONTtitle, "Text Game", 320, 100, window)
    fTITLE.create()

    fBUTTON = Button(FONTtitle, "Start", 285, 285, 70, 30, 320, 300, 1, window)

    def blitMenuDraw():

        window.fill(BLACK)
        fTITLE.blit()
        fBUTTON.create()
    blitMenuDraw()

def choice1(FONT):
    fSTORY = StoryFont(FONT, "You are Mr. Stetkiewicz, a seventh grade science teacher.", 320, 50, window)
    fSTORY.create()

    fSTORY2 = StoryFont(FONT, "One day, when coming into your class room to teach about the", 320, 70, window)
    fSTORY2.create()

    fSTORY3 = StoryFont(FONT, "behavior of convection, you notice that no one is there.", 320, 90, window)
    fSTORY3.create()

    fSTORY4 = StoryFont(FONT, "Everything seems cold and somewhat dark.", 320, 140, window)
    fSTORY4.create()

    fSTORY5 = StoryFont(FONT, "Eventually you realize that there is a lack of thermal energy,", 320, 190, window)
    fSTORY5.create()

    fSTORY6 = StoryFont(FONT, "as if it has been stolen. Infuriated, you grab your trusty frying pan", 320, 210, window)
    fSTORY6.create()

    fSTORY7 = StoryFont(FONT, "engraved with '212 degree boiling point', and set out on your journey", 320, 230, window)
    fSTORY7.create()

    fSTORY8 = StoryFont(FONT, "to restore thermal energy to the school.", 320, 250, window)
    fSTORY8.create()

    fSTORY9 = StoryFont(FONT, "Good Luck!", 320, 300, window)
    fSTORY9.create()

    fBUTTON2 = Button(FONT, "Continue", 270, 385, 100, 30, 320, 400, 2, window)

    def choice1Draw():

        window.fill(BLACK)
        fSTORY.blit()
        fSTORY2.blit()
        fSTORY3.blit()
        fSTORY4.blit()
        fSTORY5.blit()
        fSTORY6.blit()
        fSTORY7.blit()
        fSTORY8.blit()
        fSTORY9.blit()
        fBUTTON2.create()

    choice1Draw()

def choice2(FONT):

    fSTORY = StoryFont(FONT, "You have just exited the doorway to your classroom.", 320, 170, window)
    fSTORY.create()

    fSTORY2 = StoryFont(FONT, "What would you like to do?", 320, 230, window)
    fSTORY2.create()

    fBUTTON3 = Button(FONT, "1.Check Inventory", 240, 300, 160, 25, 320, 310, 3, window)

    fBUTTON4 = Button(FONT, "2.Look left down the hallway.", 190, 330, 260, 25, 320, 345, 4, window)

    fBUTTON5 = Button(FONT, "3.Look right down the hallway.", 185, 365, 265, 25, 320, 380, 5, window)

    global fList
    fList = [fSTORY, fSTORY2, fBUTTON3, fBUTTON4, fBUTTON5]

    if fBUTTON3.hasBeenClicked == True:
        fBUTTON4.hasBeenClicked = True
        fBUTTON5.hasBeenClicked = True

    if fBUTTON4.hasBeenClicked == True:
        fBUTTON3.hasBeenClicked = True
        fBUTTON5.hasBeenClicked = True

    if fBUTTON5.hasBeenClicked == True:
        fBUTTON3.hasBeenClicked = True
        fBUTTON4.hasBeenClicked = True

    print(str(fBUTTON3.hasBeenClicked) + "button 3")
    print(str(fBUTTON4.hasBeenClicked) + "button 4")
    print(str(fBUTTON5.hasBeenClicked) + "button 5")

    choice2Draw(fList, window)

def choice2Draw(fList, window):
    window.fill(BLACK)
    fList[0].blit()
    fList[1].blit()
    fList[2].create()
    fList[3].create()
    fList[4].create()

    global isReady2

def choice3(FONT):
    #print("HI")

    fSTORY = StoryFont(FONT, "You are currently holding a frying pan and a pencil in your hands.", 320, 200, window)
    fSTORY.create()

    fSTORY2 = StoryFont(FONT, "You are also wearing glasses, and your work clothes.", 320, 220, window)
    fSTORY2.create()

    fBUTTON = Button(FONT, "Back", 190, 330, 260, 25, 320, 345, 2, window)

    def choice3Draw():
        window.fill(BLACK)
        fSTORY.blit()
        fSTORY2.blit()
        fBUTTON.create()

        global isReady2

    choice3Draw()

def choice4(FONT):
    print("in choice 4")

def choice5(FONT):
    print("in choice 5")

while True:
    pos = pygame.mouse.get_pos()
    if starting == 0:
        blitMenu(FONTtitle)
        print(str(starting))

    if starting == 1:
        choice1(FONT)
        print(str(starting))

    if starting == 2:
        choice2(FONT)
        print(str(starting))

    if starting == 2.5:
        choice2Draw(fList, window)
        print(str(starting))

    if starting == 3:
        choice3(FONT)
        print(str(starting))

    if starting == 4:
        choice4(FONT)
        print(str(starting))

    if starting == 5:
        choice5(FONT)
        print(str(starting))

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()

The problem stems from the stuff in choice 2:
def choice2(FONT):

    fSTORY = StoryFont(FONT, "You have just exited the doorway to your classroom.", 320, 170, window)
    fSTORY.create()

    fSTORY2 = StoryFont(FONT, "What would you like to do?", 320, 230, window)
    fSTORY2.create()

    fBUTTON3 = Button(FONT, "1.Check Inventory", 240, 300, 160, 25, 320, 310, 3, window)

    fBUTTON4 = Button(FONT, "2.Look left down the hallway.", 190, 330, 260, 25, 320, 345, 4, window)

    fBUTTON5 = Button(FONT, "3.Look right down the hallway.", 185, 365, 265, 25, 320, 380, 5, window)

    global fList
    fList = [fSTORY, fSTORY2, fBUTTON3, fBUTTON4, fBUTTON5]

    if fBUTTON3.hasBeenClicked == True:
        fBUTTON4.hasBeenClicked = True
        fBUTTON5.hasBeenClicked = True

    if fBUTTON4.hasBeenClicked == True:
        fBUTTON3.hasBeenClicked = True
        fBUTTON5.hasBeenClicked = True

    if fBUTTON5.hasBeenClicked == True:
        fBUTTON3.hasBeenClicked = True
        fBUTTON4.hasBeenClicked = True

    print(str(fBUTTON3.hasBeenClicked) + "button 3")
    print(str(fBUTTON4.hasBeenClicked) + "button 4")
    print(str(fBUTTON5.hasBeenClicked) + "button 5")

    choice2Draw(fList, window)

def choice2Draw(fList, window):
    window.fill(BLACK)
    fList[0].blit()
    fList[1].blit()
    fList[2].create()
    fList[3].create()
    fList[4].create()

    global isReady2

And while debugging, I found this: (solitary numbers are the choice number)
3
3
3
3
3
True inside button class
2
False button 3
False button 4
False button 5
True inside button class
4
in choice 4
4
in choice 4
4
in choice 4
4
in choice 4
4
in choice 4
4
in choice 4

I'm not really sure why it's behaving this way, or why in this IDLE shell the program went back to choice 2 like expected, but then reverted to the second button declaration in choice 2. It's like everything before fBUTTON4 is disabled. Please, try to run the program yourself and see if you encounter the same error. Help is appreciated!

A: I have reviewed your code and I understand what is happening. The main issue is actually happening in the create function of the Button class.
You have some buttons that are is roughly the same position when they get rendered on the screen. An example of this is the continue button in choice1 and the 3.Look right down the hallway in choice2.
When I click the top of the continue button in choice1, the screen goes to choice2 and thinks I am clicking the 3.Look right down the hallway button in choic2. That will immediately take me to choice5.
What we need to do is make sure that a user releases the mouse button in between clicks.
To do this I have added 6 lines to your program. At the top of the file I added a new variable under the isReady2 variable:
isReady2 = False
hasBeenReleased = not pygame.mouse.get_pressed()[0]

That will check if the player has the mouse button held down or it is released when they start the game.
Next, I added code so they have to release the mouse button before they can click again. I am pasting the code that you already have and then pasting my solution.
if self.hasBeenClicked == False:
        if pos[1] >= self.fonty - 17.5 and pos[1] <= self.fonty + 17.5 and pos[0] >= self.fontx - 47.5 and pos[0] <= self.fontx + 47.5:
            pygame.draw.rect(window, BLUE, ((self.x1, self.y1), (self.x2, self.y2)), 0)
            window.blit(self.fSFont, self.fSFontr)

            if pygame.mouse.get_pressed()[0] == True:
                global starting
                self.hasBeenClicked = True
                starting = self.choiceNum
                isReady2 = False
                window.fill(BLACK)
                return starting

Here is my fix:
if self.hasBeenClicked == False:
    if pos[1] >= self.fonty - 17.5 and pos[1] <= self.fonty + 17.5 and pos[0] >= self.fontx - 47.5 and pos[0] <= self.fontx + 47.5:
        pygame.draw.rect(window, BLUE, ((self.x1, self.y1), (self.x2, self.y2)), 0)
        window.blit(self.fSFont, self.fSFontr)

        global hasBeenReleased
        if hasBeenReleased and pygame.mouse.get_pressed()[0] == True:
            hasBeenReleased = False
            global starting
            self.hasBeenClicked = True
            starting = self.choiceNum
            isReady2 = False
            window.fill(BLACK)
            return starting
        elif not hasBeenReleased:
            hasBeenReleased = not pygame.mouse.get_pressed()[0]

The code checks if the button has been released previously. If it has been released then we can check if it is currently being clicked. If it is being clicked then we hasBeenReleased = False to let us know they did actually click.
The section that lets them click again is:
elif not hasBeenReleased:
    hasBeenReleased = not pygame.mouse.get_pressed()[0]

If we check if they recently clicked and then set the value equal to if they have released the button or if they are still holding it down.
Using this code I was able to go back and forth between choice 2 and 3.


text:
Q: Django Sessions via Memcache: Cannot find session key manually I recently migrated from database backed sessions to sessions stored via memcached using pylibmc.
Here is my CACHES, SESSION_CACHE_ALIAS & SESSION_ENGINE in my settings.py
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
        'LOCATION': ['127.0.0.1:11211'],
    }
}

SESSION_CACHE_ALIAS = 'default'

SESSION_ENGINE = "django.contrib.sessions.backends.cache"

Everything is working fine behind the scenes and I can see that it is using the new caching system. Running the get_stats() method from pylibmc shows me the number of current items in the cache and I can see that it has gone up by 1.
The issue is I'm unable to grab the session manually using pylibmc.
Upon inspecting the request session data in views.py:
def my_view(request):
    if request.user.is_authenticated():

        print request.session.session_key
        # the above prints something like this: "1ay2kcv7axb3nu5fwnwoyf85wkwsttz9"

        print request.session.cache_key
        # the above prints something like this: "django.contrib.sessions.cache1ay2kcv7axb3nu5fwnwoyf85wkwsttz9"

        return HttpResponse(status=200)
    else:
        return HttpResponse(status=401)

I noticed that when printing cache_key, it prints with the default KEY_PREFIX whereas for session_key it didn't. Take a look at the comments in the code to see what I mean.
So I figured, "Ok great, one of these key names should work. Let me try grabbing the session data manually just for educational purposes":
import pylibmc

mc = pylibmc.Client(['127.0.0.1:11211'])

# Let's try key "1ay2kcv7axb3nu5fwnwoyf85wkwsttz9"

mc.get("1ay2kcv7axb3nu5fwnwoyf85wkwsttz9")

Hmm nothing happens, no key exists by that name. Ok no worries, let's try the cache_key then, that should definitely work right?
mc.get("django.contrib.sessions.cache1ay2kcv7axb3nu5fwnwoyf85wkwsttz9")

What? How am I still getting nothing back? As I test I decide to set and get a random key value to see if it works and it does. I run get_stats() again just to make sure that the key does exist. I also test the web app to see if indeed my session is working and it does. So this leads me to conclude that there is a different naming scheme that I'm unaware of.
If so, what is the correct naming scheme?

A: Yes, the cache key used internally by Django is, in general, different to the key sent to the cache backend (in this case pylibmc / memcached). Let us call these two keys the django cache key and the final cache key respectively.
The django cache key given by request.session.cache_key is for use with Django's low-level cache API, e.g.:
>>> from django.core.cache import cache
>>> cache.get(request.session.cache_key)
{'_auth_user_hash': '1ay2kcv7axb3nu5fwnwoyf85wkwsttz9', '_auth_user_id': u'1', '_auth_user_backend': u'django.contrib.auth.backends.ModelBackend'}

The final cache key on the other hand, is a composition of the key prefix, the django cache key, and the cache version number. The make_key function (from Django docs) below demonstrates how these three values are composed to generate this key:
def make_key(key, key_prefix, version):
    return ':'.join([key_prefix, str(version), key])

By default, key_prefix is the empty string and version is 1.
Finally, by inspecting make_key we find that the correct final cache key to pass to mc.get is
:1:django.contrib.sessions.cache1ay2kcv7axb3nu5fwnwoyf85wkwsttz9

which has the form <KEY_PREFIX>:<VERSION>:<KEY>.
Note: the final cache key can be changed by defining KEY_FUNCTION in the cache settings.


text:
Q: MS Excel pivot table - expand column in a new sheet i wonder if this is possible at all or is there any way of expanding pivot table column in a new sheet.
here is what pivot i've got:

so you see it's grouped by customer.
the question is - can i expand/open each customer in a new sheet (as if you do when double clicking values)

A: Yes. Double click the Grand Total row (for the Customer). If you don't have such then under PivotTable Options, Totals & Filters check Show grand totals for columns.

A: Figured this out:

*

*move Customers to filter (top left box)

*then select a customer

*double click on total values
this will open all sales ONLY for selected customer


text:
Q: std::atomic segmentation fault on WSL Ubuntu 20.04 LTS with GCC 9.x Based on this question, I extended std::mutex so that I can check if the mutex is already locked by the current thread:
class mutex : public std::mutex
{
  public:
    void lock()
    {
      std::mutex::lock();
      lock_holder_ = std::this_thread::get_id();
    }

    void unlock()
    {
      lock_holder_ = std::thread::id();
      std::mutex::unlock();
    }

    [[nodiscard]] bool locked_by_caller() const
    {
      return lock_holder_ == std::this_thread::get_id();
    }

    private:
      std::atomic<std::thread::id> lock_holder_;
};

On Linux with GCC 9.x (via WSL on Windows 10, using Ubuntu 20.04 LTS), there is a segmentation fault thrown in the locked_by_caller() function. When using Valgrind I get the following output:
==2120== Memcheck, a memory error detector
==2120== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2120== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==2120== Command: ./WSL-GCC-Debug/eventbus/eventbus.tests
==2120==
==2120== error calling PR_SET_PTRACER, vgdb might block
Running main() from /mnt/d/repositories/eventbus/eventbus-src/out/build/WSL-GCC-Debug/_deps/googletest-src/googletest/src/gtest_main.cc
[==========] Running 4 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 3 tests from EventBusTestFixture
[ RUN      ] EventBusTestFixture.LambdaRegistrationAndDeregistration
Lambda 3 take by copy.
Lambda 1
Lambda 3 take by copy.
Lambda 1
Lambda 3 take by copy.
Lambda 3 take by copy.
[       OK ] EventBusTestFixture.LambdaRegistrationAndDeregistration (83 ms)
[ RUN      ] EventBusTestFixture.RegisterWhileDispatching
Loop 0 Handler count: 2
==2120== Invalid read of size 8
==2120==    at 0x11C036: std::atomic<std::thread::id>::load(std::memory_order) const (atomic:254)
==2120==    by 0x11AE5A: std::atomic<std::thread::id>::operator std::thread::id() const (atomic:207)
==2120==    by 0x11A22E: dp::event_bus::mutex::locked_by_caller() const (event_bus.hpp:153)

And gdb outputs the following:
Program received signal SIGSEGV, Segmentation fault.
std::atomic<std::thread::id>::load (this=0x2a, __m=std::memory_order_seq_cst) at /usr/include/c++/9/atomic:254
254     __atomic_load(std::__addressof(_M_i), __ptr, int(__m));
Segmentation fault

I noticed the invalid read of size 8 and after doing research I found that this was a bug (also on Stackoverflow) in an older version of GCC but was fixed in 5.x. Is this still an alignment problem because I'm using std::thread::id in an std::atomic? Are there any work around to this issue?
Full code (for context) is on my Github.


text:
Q: Getting input objects in Cocoa...What's better style? I have a factory-type class that creates its products based on the traits of another object.  This means that I need a reference to the input object somewhere.  I am planning to either:
A) Define the input object as a property and set it in a custom init method.  So the factory's owner calls "initWithObject:", then calls "createProduct".
B) Define the factory's creation methods so that they take in the input object as an argument. So the factory's owner inits normally and then calls "createProductWithObject:".
All else equal, is one of these methods preferable to the other from an overall design standpoint?  Method A makes things simpler for me since I don't have to make every method accept an input, but I'd like to be sure that I'm not overlooking anything.
Thanks!

A: I think it completely depends on how you intend to use your factory class.  If this were a pizza factory, you might want to use option A in a scenario where the style of all pizzas (the products) depends on the initial value.
PizzaFactory *factory = [[PizzaFactory alloc] initWithStyle:NewYorkStylePizza];

On the other hand, the individual pizzas can depend on something that other pizzas from the same factory don't.
Pizza *meatLovers = [factory createPizzaWithToppings:toppings];

In this case, both options are being used.  You'll just need to decide what makes the most sense for your needs.

A: I base my choice of which to do on whether the class must have a value for a property, or can go without it.
Borrowing Cory Kilger's idea of food-based examples, let's consider a Hamburger class. The instance must have a bun and a patty:
Patty *patty = [BeefPatty patty];
Bun *bun = [WhiteBun bun];
Hamburger *burger = [Hamburger burgerWithSinglePatty:patty bun:bun];
//Instantiation without convenience factory method
Hamburger *burger = [[[Hamburger alloc] initWithSinglePatty:patty bun:bun] autorelease];

But can have any number of toppings:
[burger addToppingsObject:[LeafLettuce lettuce]];
[burger addToppingsObject:[TomatoSlice sliceWithThickness:1.0 /*cm*/]];
[burger addToppingsObject:[CheddarCheese slice]];

Or none at all:
//No toppings—just meat in a bun.

A steak doesn't have any required elements, so you would instantiate it with no arguments:
Steak *steak = [NewYorkSteak steak];
//Instantiation without convenience factory method
Steak *steak = [[[NewYorkSteak alloc] init] autorelease];

But you could add values for optional elements if you want to:
steak.sauce = [userSelectedSauce sauceInAmount:2.0 /*ml*/];


text:
Q: State solid hard disk upgrade Wha type of connector are mounted on SSD? I'm searching for a new notebook and I'm stuck on this choice.
Could I buy a notebook with a classic HDD and then, upgrade it with a SSD?

A: Both SSD and HDD hard drives use standard SATA connectors, so yes if you can remove the hard drive from a notebook then you could easily put an SSD back in its place.

A:
What type of connector are mounted on SSD?

Almost all current drives, both rotating and solid state, use a SATA connector. There are a few exceptions, e.g. with SAS drives, fibrechannel drives or PCI-e based cards which act as a drive, but almost all notebook drives should be SATA.  SATA is backwards compatible, so you can use any SATA drive to replace another SATA drive.

Image source: Wikipedia
That only leaves the form factor. Obviously a 3½ drive is not going to fit in a notebook, so make sure you select a 2½ inch drive. That is the normal size for laptop drives and for almost all SSDs. Next check the thickness of the drive. That is also almost always the same (9.5mm), but making sure that you do not have an ultra-thin drive before trying to replace it with a normal thickness SSD would not hurt.

Could I buy a notebook with a classic HDD and then, upgrade it with a SSD?

In almost all cases: Yes.


text:
Q: How can I avoid getting out of space in LXD operations? I installed LXD 4.10 in an Ununtu 18.04 machine using the snap:
sudo install lxd

LXD is installed in /var/span/lxd. Since a small disk is mounted in /var, I get out of no free space for some operations. Creating storage pools out of /var does not solve the problem because I still have problems with commands as lxc export or lxc publish. These commands create files in the directories:
/var/snap/lxd/common/lxd/backups/instances
/var/snap/lxd/common/lxd/images

When images and backups are too big, the /var disk gets out of space.
What is the best practice to avoid getting out of space? My restriction is that I cannot mount another disk in /var.


text:
Q: How to assign a relationship in Ember Data when it doesn't have an ID yet? I have a new team member, which belongs in a team but the member doesn't have an ID yet because the record hasn't been send to the server yet how do I tell the team that the member belongs in the team and let it appear in the team list before sending the team member to the server and assigning a unique ID to the member.

A: I think ember is geared towards saving the record to the back end, and then on the success callback creating your relationship and save it again. This ensures that ember-data remains a slave to the backend, ensuring data integrity.
You could look at creating an ID in ember, but this certainly sounds like here be dragons as you would need to purge your ember-data store and and get the real records and ID's from the server.
This process could be simplified by placing a flag on your model to say that it has a generated ID, but as I said here be dragons.
The safest option is to either just establish relationships once a record has been saved to the back end, or if offline is a real concern, you could use something like Ember Pouch to keep a synced local copy of your datastore, this will make the whole issue of resolving ID's a little more consistent.
Finally you could look into some sort of localStorage man in the middle to sync with your db, it has been discussed in this SO question.


text:
Q: Pandas - why does it throw ValueError? Would anyone know why is Pandas throwing the ValueError and how to fix it? I just want to calculate the difference in "Value" column while grouping by "CurveName" and "Tenor"
Example

A: you need to add .agg() method with arguments to groupby object to be able to apply diff and other functions to it. Otherwise it is not clear how exactly you want to aggregate your data. See help and examples on groupby/agg method.
here is a simple example:
df = pd.DataFrame()
df['a'] = np.random.randint(0, 4, 100)
df['b'] = np.random.randint(10, 99, 100)
df2 = df.groupby('a').agg('mean')
df2['d'] = df2.b.diff(-1)
df2

           b          d
a
0  56.000000  22.500000
1  33.500000 -25.900000
2  59.400000   9.288889
3  50.111111        NaN

'mean' is aggregation function. Could be other like 'max', 'std' or even a custom function. Start here


text:
Q: Dynamically changing the data displayed using ajax I have a problem with manipulating data from ajax and jQuery.
I am using jQuery to display html code and insert it into the div element "#kontener"
$.ajax({
    url: "qa.php",
    type: "POST",
    datatype: "html",
    contentType: "application/x-www-form-urlencoded; charset=iso-8859-2",
    data: {
        indeks: tekst, q: question},
    success: function (result) {
        jQuery("#kontener").html(result);
    },
});

Here is sample html

<input type="radio" name="answer" value="1">q1

<input type="radio" name="answer" value="2">q2

<input type="radio" name="answer" value="3">q3

<input type="radio" name="answer" value="4">q4

Question - can I use jQuery to select the radio button after clicking on the tr element?
Unfortunately this doesn't work :(
$("tr").click(function () {
   $(this).find('input:radio').attr('checked', true);
});

A: Try this
$(this).find('input:radio').prop('checked', true);

I recommend giving each radio a unique ID

A: I was able to get this to work:
$("#q tr").click(function() {
    $(this).find("input[type=radio]").prop("checked", true);
});

This worked, as well:
$("#q").on( "click", "tr", function() {
    $(this).find("input[type=radio]").prop("checked", true);
});

A: Use setAttribute function.
$("tr").click(function () {
    $(this).find('input:radio')[0].setAttribute('checked', true)
});


text:
Q: Where like queries on multidimensional arrays in php Suppose I have a php array like this:
$shop = array( array("name"=>"Tom", "level"=> 1.25 ),
               array("name"=>"Mike","level"=> 0.75 ),
               array("name"=>"John","level"=> 1.15 )
             );

I want to filter this array similar to filtering a mysql table with where conditions. Supposedly I want every array where level is higher than 1. I could iterate through and check with if statements. Are there any php solutions to this?

A: array_filter is what you are looking for:
$results= array_filter($shop, function($item) { return $item['level'] > 1; });

print_r($results);

Output:
Array
(
    [0] => Array
    (
        [name] => Tom
        [level] => 1.25
    )

    [2] => Array
    (
        [name] => John
        [level] => 1.15
    )
)