Question about sigma-algebra generated by a random variable

Question: I saw this example in Richard Durrett's book:

Example 5.1.4. To continue making connection with definitions of
  conditional expectation from undergraduate probability, suppose $X$
  and $Y$ have joint density $f (x, y)$, i.e.,
  $$ P ((X, Y ) ∈ B) = \int_B f (x, y) \, dx \, dy $$
  for $B ∈ R^2$ and suppose for simplicity
  that $f (x, y) \, dx > 0$ for all y. We claim that in this case, if
  $E|g(X)| < \infty$ then $E(g(X)\mid Y ) = h(Y )$, where
  $$ h(y) = \left. \int g(x)f (x, y) \, dx \right/ \int f (x, y) \, dx. $$

My question is, why we have $h(Y) \in \sigma(Y)$.  The book states it as something trivial, but I failed to see why this is true.
Answer: Because it's a function of $Y$.
$$
\{\omega : h(Y(\omega)) \in A\} = \{ \omega : Y(\omega) \in\text{something measurable} \}.
$$
(This assumes $h$ is measurable.  We know $Y$ is measurable since it's a random variable.)
That does it.
We have
$$
\text{something} = \{ y\in \mathbb R : h(y)\in A \}.
$$
Later addendum: From comments, my impression of what the question is about is evolving . . . . .
So let's see: What does the measure-theoretic definition of $\mathbb E(W\mid Y)$ say, when $W$ and $Y$ are random variables?
The conditional expectation should be a $\sigma(Y)$-measurable random variable $V$ such that for every $\sigma(Y)$-measurable set $B$,
$$
\int_B W\,dP = \int_B V\,dP.
$$
(The r.v. $W$ itself is not generally $\sigma(Y)$-measurable; otherwise there'd be no point in having such a definition.)  So a question is: How do we know such a random variable exists, and that there is essentially only one (i.e. only one up to equalitiy-almost-everywhere)?  The answer is that that follows from the Radon–Nikodym theorem, thus: Observe that
$$
Q(B) = \int_B W\,dP \tag{1}
$$
is a measure on $\sigma(Y)$ that is absolutely continuous with respect to the restriction of the measure $P$ to $\sigma(Y)$.  So there is a Radon–Nikodym derivative $V=dQ/dP$, i.e. a $\sigma(Y)$-measurable function $V$ such that for all $B\in\sigma(Y)$,
$$
Q(B) = \int_B V \, dP.
$$
(The equality $(1)$ looks as if it's saying $W$ is the desired Radon–Nikodym derivative, but again, that doesn't work since $W$ is not generally $\sigma(Y)$-measurable; otherwise there'd be no point in doing this.)
So the answer is that this comes from the Radon–Nikodym theorem.
Later still . . . .  The other $\sigma$-algebras, besides those of the form $\sigma(Y)$ for some random variable $Y$, that I've seen this done with are tail $\sigma$-algebras.  For a sequence $X_1,X_2,X_3,\ldots$ of random variables, a tail event is any event whose occurrence or non-occurrence is determined by the whole sequence $X_1,X_2,X_3,\ldots$ but whose occurrence or non-occurrence is unchanged by altering the values of any finite set of terms in that sequence.  An example is the even that $\lim_{n\to\infty}X_n>1/2$.  The tail $\sigma$-algebra is the set of all tail events.
Comment: I understand we just need $h$ to be measurable. I can't see how to prove this from its definition.
Comment: OK, I hope my later addendum to the answer gets at what you were wondering about.
Comment: Hey, thanks for explaining how to prove the existence of the conditional expectation with Radon–Nikodym theorem.


LAMP stack installation. Accidental deletion of ports.conf

Question: I have Ubuntu 12.04 and tried to install Apache/PHP/MySQL with the
default LAMP stack using tasksel.
Everything went well until I was going to edit the /etc/apache2/ports.conf file according to the ApacheMySQLPHP guide. I unintentionally deleted the contents of the document because I had not first changed the file's permissions.
Now, I cannot figure out how to restore the file to its original state.
I tried reinstalling the programs, but it had no effect, as Apache is still installed and running.
Comment: [This should be set as the default content](http://paste.ubuntu.com/5878968/) for the latest version. You can try creating the file again.
Answer: In general, I'd use the apt-file command (needs to be installed) to search for /etc/apache2/ports.conf: apt-file search ports.conf. This will provide a list of packages, one being apache2.2-common. So now you know which package provides the file you're looking to replace. Then you can either reinstall that package or download it and look at its content manually.
There might be better ways to accomplish it, but in general, this approach would always lead you in the right direction, at the very least.
Comment: Thank you for the help! I have the problem fixed now... whew. :)


Voltage between shower faucet and drain

Question: Is it normal to have voltage between shower faucet and drain?
I measured 2 volts between shower faucet and drain when water heater is off, and 11-12 volts when it is on?
Comment: I have to ask...what prompted you to make this measurement?
Comment: Nigth before, I felt stinging electricity when I touch shower faucet with my finger. Even though, the skin of part finger is slightly damaged, I decided to make a measurement.
Comment: What kind of water heater is this, and where (bathroom vs. other side of the house, etc.) is it installed?
Comment: It is electric water heater and it is in other part of the house, other room. @manassehkatz-Moving2Codidact
Comment: How did you measure? Just a voltmeter would read floating voltage, which is meaningless. 2 or 12 volts would also not leave any visible damage to your skin
Comment: I use regular multimeter. I set multimeter to ~200 V, put red lead on shower faucet and black lead on top of drain. I had damage on my skin previously. It isn't from stinging electricity, I forgot mention.
Comment: Ah, so you had an open wound of some sort and felt the tingle of electricity in the previously open wound. That may be somewhat more sensitive an area that "normal" undamaged skin.
Comment: can you take your multi meter and switch it to current, then measure as before? If it's a milliamp or so, it's nothing to worry about.
Comment: I called electrician. The problem is solved! Neutral wire had fault in junction box on poles. Not only I had problem my neighbour had problem to (when he turn oven the fuse pops up). This was in my rented flat so I didn't know what and how is ground made. Because the flat has no separate ground wire, the ground was connected to neutral and beacuse wire had fault in junction box on poles we had problem.
Comment: Now, voltage  between shower faucet and drain is under 1 (V) even water heater is on. Before, the worst case was when I measured 44(V).
Answer: No, this is not normal and dangerous. I suggest that you hire an electrician or least favorable option (ground is like crazy science to regular person and there are a lot of gotcha ya), do your own research. It looks like there is insufficient grounding and your heater or some other appliance has a ground fault. All of the electrical circuits and appliances must be grounded and all metallic piping must be bonded.
Comment: Wouldn't you consider asking here at least part of "do your own research"?
Answer: Damaged skin reduces your body's natural resistance so you felt the shock.
This low voltage can be generated in many ways and at that low of a voltage is not dangerous.
the National electric code article 411 low voltage lighting: think swimming pools hot tubs where this lighting is normally used allows 15 volts ac where wet contact is likely.
I regularly bond the hot water pipe to the cold water pipe if metallic many jurisdictions require this as the NEC if likely to become energized it shall be bonded to the grounding electrode system.
Another possibility is an imbalanced electrical system. A heavy imbalance can cause a voltage to be present on the neutral & grounding system that a well balanced system will not have.
No one likes getting shocked so taking steps to eliminate the cause (other than broken skin) like making sure the water piping is grounded both hot and cold. Getting the home balanced L1 to L2 I have seen 50 amp imbalances cause much higher neutral voltages and once the system was balanced no voltage on the grounded or grounding conductors (moving breakers to even out loading for each leg.)
The good thing is this is not considered hazardous but I would be at least adding additional grounding to eliminate it.
Comment: Not sure why the down vote other than that those that don't know code values.

Voltage between shower faucet and drain


How to find the Lihzahrd temple in Terraria?

Question: I have been looking all over my jungle in Terraria and I can't seem to find the Lihzahrd temple anywhere. Does anyone have any tips on how to find it?
Answer: The Jungle Temple is randomly generated somewhere within the Underground Jungle biome. There is not specific ways for finding it.
Note that it can generate on the very edge of the underground jungle, so make sure you have explored the entire jungle to its edges.
If you are still having no luck, you could download a map viewer to pinpoint the location of your temple.
Comment: The Jungle Temple is ruffly the same depth so you dont need to digg all the way down to the underworld


Javascript popup different size in different browsers?

Question: How come this pop-up gets a size other than what I have specified, when testing it in IE6 and FireFox 3.6? Firefox displays it correctly but IE6 is smaller for some reason. (620x530 instead) How can I fix it?

Comment: I think that in one of those browsers title is not calculated in height... but I am not sure in which one
Comment: IE6 includes the status/title/toolbar in its height.
How can I circumvent this - make it the same size in as many browsers as possible?
Answer: window.open('/sitecollectiondocuments/myPage.htm','welcome','width=630,height=590').resizeTo(630, 590)


How to clear a textbox in view after calling popToViewController

Question: I have a view (viewControllerA) that has a textbox. The user populates it and clicks Next. After completing a few steps, they're done/submit all data and I want to pop them back to viewControllerA, but when I do, the textbox is still populated. I don't want to clear on viewWillAppear because I want to use the built-in back button functionality. How can I clear that textbox only after popToViewController?
[rootController popToViewController:rootController.transferScanPartView animated:YES];

Comment: Not sure how you pop to / back to the relevant controller but normally those calls have a completion block. Why not put it there or show how you `pop them back to vcA`?
Comment: code added. maybe there's a better way for me to utilize popToViewController?
Comment: Hi - what iOS version are you targeting?
Comment: currently iOS 9.0
Comment: Ok - I do something similar using a dismissBlock ... I'll post a bit of code as an answer.
Answer: There are a variety of ways in which you can do this. What I post below is my second attempt, which I think is simplest here. Have a block in your vc, something like
@property (nonatomic,strong) void ( ^ appearBlock )();

and then use that to do whatever you want next time the view appears. The first time this will be nil and will not execute, then when you call the code you posted also do something like
__weak myVc * weakSelf = self;
self.appearBlock = ^ { weakSelf.edit.text = nil; };
// Code you posted, where you present your popover
[rootController popToViewController...

and in your viewWillAppear
- ( void ) viewWillAppear ...
{
  [super viewWillAppear...

  if ( self.appearBlock )
  {
    // Execute block
    self.appearBlock();

    // Ensure we never call it again
    self.appearBlock = nil;
  }

  .. rest of view will appear ..
}

EDIT
The trouble here is that, depending on the iOS you use and how you present the vc, a number of things are called or not called when the view is presented or dismissed.
Depending on that you may have to move the call to the appearBlock to different places. The popover delegate can be used but I don't think iOS 9 supports that, then for popovers you also have the  beingPresented / beingDismissed messages.


tensorflow lite on arduino nano 33 ble: Didn't find op for builtin opcode 'SHAPE' version '1'

Question: I used Tensorflow lite 2.1.0-ALPHA-PRECOMPILED for arduino nano 33 ble with headers.
Model Definition
model = tf.keras.Sequential()
model.add(layers.Dense(16,activation='relu', input_shape=(seq_len,12,1)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(1, activation='sigmoid'))

Model Summary
Model: "sequential_1"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 dense_4 (Dense)             (None, 100, 12, 16)       32

 dense_5 (Dense)             (None, 100, 12, 16)       272

 dense_6 (Dense)             (None, 100, 12, 1)        17

 flatten_1 (Flatten)         (None, 1200)              0

 dense_7 (Dense)             (None, 1)                 1201

=================================================================
Total params: 1,522
Trainable params: 1,522
Non-trainable params: 0
_________________________________________________________________

and I converted to tflite
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]

tflite_model = converter.convert()

open('saved_model/ver4.tflite','wb').write(tflite_model)

and I included in arduino
static tflite::MicroMutableOpResolver<2> micro_op_resolver;  // NOLINT
micro_op_resolver.AddBuiltin(tflite::BuiltinOperator_FULLY_CONNECTED,
                              tflite::ops::micro::Register_FULLY_CONNECTED());
micro_op_resolver.AddBuiltin(tflite::BuiltinOperator_RESHAPE,
                              tflite::ops::micro::Register_RESHAPE());

in this case i get a error:
Didn't find op for builtin opcode 'SHAPE' version '1'

Failed to get registration from op code SHAPE

Failed starting model allocation.

I tried to include
micro_op_resolver.AddBuiltin(tflite::BuiltinOperator_SHAPE,
                              tflite::ops::micro::Register_SHAPE());

but got error message
Compilation error: 'Register_SHAPE' is not a member of 'tflite::ops::micro'

and I also tried
static tflite::AllOpsResolver resolver;

but didn't work either.
Didn't find op for builtin opcode 'SHAPE' version '1'

Failed to get registration from op code SHAPE

Failed starting model allocation.

like this
Answer: this happens when there is a version mismatch between the tensorflow version you are using and the tflite micro inference engine. I'm not sure exactly which version of tensorflow lite for microcontrollers you are using, but it sounds out of date.


Compilation fails when using super in string concatination

Question: I have the following class, which doesn't compile:
public class C {
    public String toString() {
        return "Test " + super;
    }
}

It gives the the compilation error Syntax error on token "super", invalid Expression.
Does anyone know, why this compiler error occurs? The intended effect would be "Test " + super.toString(), which is compiling fine, but why does the example above fail to compile? Shouldn't the normal Java rules for String concatinations apply here?
Even more surprising that the following code compiles fine:
public String toString2() {
    return "Test " + this;
}

So why does thiswork in string concatination while super doesn't?
I'm using openjdk 11.0.3 2019-04-16, just in case it matters (which I doubt).
Answer: The super keyword in Java is not an object reference and thus you receive some errors in your code!
It's not a good practice to doing that so, Because super is a keyword to discover the parent class. So you can't print using that keyword!
According to Java spec :

The forms using the keyword super are valid only in an instance
  method, instance initializer, or constructor, or in the initializer of
  an instance variable of a class. If they appear anywhere else, a
  compile-time error occurs.
Comment: As far as I know, it is an object reference to `this` being casted into the parent class type.

I'm also not sure how the paragraph you quoted answers my question, as I am using super in an instance method.
Comment: super is not a normal object, this can be used on its own. super cannot.
Answer: super usages:

The statement super() is used to call the parent constructor and
can be invoked only from the child's constructor. It also must be
the first statement in the child's constructor.
super.instance_variable
super.instance_method

Eg:
class Animal {
    String name;
    Animal() { }

    String myName() {
        return name;
    }
}

class Dog extends Animal {

    Dog() {
        super();
    }

    public String toString() {
        return "Test " + super.myName() + super.name;
    }
}

There is no standalone usage for just super. The this refers to the current object and can be invoked on its own.
Comment: I'm not talking about `super()` in a constructor call, but about using `"Test " + super` in a method call. I cannot use `this` in my example because it would lead to infinite recursion.
Comment: There is no usage for *just* super.
Comment: @DorianGray you have two answers by now explaining to you that using super isn't possible like that. The real question is: what is your toString method supposed to do?!
Comment: Well, it would be supposed to be equivalent to `"Test " + super.toString()` in the exaple above.
Answer: Simple: "super" can't be used in that way.
That keyword can be used to either call a super constructor or to reference a super method/field. But it can't stand "all by its own".
As there is no "super" object. You can use "this" to reference the "this" object, but as there is no "standalone" super object. So the language does not allow you to use "super" the way you can use "this".
Comment: Well, it isn't a standalone object, but from what I've learned, it is merely equivalent to a cast of `this` to the parent class type, which forces the compiler to call the parent class method.
Comment: @DorianGray I suggest you revisit that topic. Either your source is wrong or you are misreading it.
Comment: Well, from 15.11.2. Accessing Superclass Members using super

    The form super.Identifier refers to the field named Identifier of the current object, but with the current object viewed as an instance of the superclass of the current class.

I thought, "viewed as" is pretty much the same as "casted into"..

Also, Further below it states in the example: : Within class T3, the expression super.x is treated as if it were: ((T2)this).x
Answer: The keyword super by itself is not a valid Java expression.  The summary of the answer is that super simply isn't used that way in Java.
The following types of expressions are the Java grammar productions including super, none of which present super by itself:

Field Access Expressions

super . Identifier This form accesses superclass members.

TypeName . super . Identifier This form accesses superclass members of the enclosing class.

Method Invocation Expressions

super . Identifier ( [ArgumentList] ) This form calls a superclass method.

TypeName . super . Identifier ( [ArgumentList] ) This form calls either a superinterface method, or a superclass method in an enclosing class, depending on whether TypeName is a class name or an interface name.

Method Reference Expressions

super :: Identifier

TypeName . super :: [TypeArguments] Identifier

By contrast, this by itself is an expression, because it is allowed by itself to form a primary expression.  The keyword super by itself is not in this list of productions or in the sub-productions.  Think of a "primary" as the basic building block of an expression.

Primary:
   PrimaryNoNewArray
   ArrayCreationExpression
PrimaryNoNewArray:
   Literal
   ClassLiteral
   this
   TypeName . this
   ( Expression )
   ClassInstanceCreationExpression
   FieldAccess
   ArrayAccess
   MethodInvocation
   MethodReference

The keyword this works in an expression because it's a Primary, which can participate in bigger, more complicated expressions involving operators such as +.
To summarize, super is only involved in larger productions to refer to specific ways of accessing the superclass.  The keyword this, while it can be involved in larger productions, is allowed by itself as a primary expression, which allows it to participate in more complicated expressions using operators.


Interior, closure, boundary of countable complement topology

Question: I've been set the following question

I started by trying to work out the interior, but I couldn't get any further. I'm using the definition that the interior of a set $A$  w.r.t. a topological space $X$ is the set of all $x\in X$ such that there exists a open $U$ such that $x\in U\subset A$. Clearly the interior of $A$ is always contained in $A$, so I'm trying to find which $U\subset A$ are open, and then points that are contained by the union of these open sets contained in $A$ form the interior. How do I know whether there will be an open set $U$ contained in $A$? I'm completely lost! Thanks for any replies.
Answer: There must be a typo in the question. It should read:

$Int(A)=\begin{cases}
A, &\text{ if $X\setminus A$ is at most countable}\\
\varnothing, &\text{ if $X\setminus A$ is uncountable}&
\end{cases}
$

Actually this is dual to the closure $\overline A$, since the interior of $A$ is the complement of the closure of $X\setminus A$.
To find the conditions under which $A$ has an interior, just assume that there exists an open non-empty set $U$ which is a subset of $A$. Then $X\setminus U$ is at most countable, and so is $X\setminus A$. But what does this mean for the openness of $A$ itself?
Comment: Oh so then $A$ is open and as $A\subseteq A$ every point $x\in A$ is in the interior?
Comment: Yes, that's right. So we can say that if $A$ has a non-empty interior, then $A$ is itself open. Note that sometimes is more convenient to use the characterisation of $Int (A)$ as the union of all open sets contained in $A$, that is the largest open subset of $A$.


Do I Really Need A Swap Partition?

Question: I am about to format and manually partition my hard drive for Ubuntu for the first time. I have 16GB of RAM. I am wondering if I should even allocate a swap partition? Should I just make a root partition and a home partition?
Comment: Duplicates http://askubuntu.com/questions/291378/do-we-still-need-swap-partitions-on-desktop http://askubuntu.com/questions/398258/do-i-need-a-swap-partition
Answer: Honestly, you can just make a root partition and you would be fine. But if you hibernate your computer, you will need the swap space. Also if you do not have a lot of ram, it will be useful to have swap space.
Read this:
https://www.linux.com/news/software/applications/8208-all-about-linux-swap-space
Comment: I currently have the default install and it made 3 partitions. One Fat32 (512MB), 200 gig ex4 for /, and 16gig for swap space. It says that the small 512MB partition is a mount point of /boot/eft, and the flag is boot. Do I need one of those too?
Comment: What is the fat32 for?
Comment: Dno, it's just there when I clicked to install Ubuntu

Do I Really Need A Swap Partition?


How to Setup particular Programs in Windows7 Administrator access to Non-Admin User

Question: I have team of developers in my company, and i have windows7 installed with UAC on all the machines, now the Dotnetnuke Compiled Template require Administrator access to create, because they are linked with IIS, so everytime they want to work on DNN Modules, they calls me to input the Credentials, and if they by-mistake close the VS, they again my Credentials, is there a way to run only Particular Application with Administrator on Standard User Accounts.
Answer: No, it's not possible.
It is even more complicated if your users are not in Administrators group. In this case the admin access token is not stripped from their security token, they never had it in the first place.
To start an elevated process, users must provide administrator privileges if they are not member of Administrators group. If they are, then a simple confirmation is shown.


trying to set arabic sentence in word using Apache poi?

Question: i'am trying to generate a word document using apache poi api, and i want to set an arabic sentence into the word, but the words didn't stay on the order !!! for instead of "شهادة بالملك" i get بالملك شهادة
public class word {

    public static void main (String [] args) {
    XWPFDocument docx = new XWPFDocument();

    try {

    XWPFParagraph tmpParagraph = docx.createParagraph();
    XWPFRun tmpRun = tmpParagraph.createRun();
    tmpRun.setText("شهادة بالملك");
    tmpRun.setFontSize(18);
    tmpRun.setFontFamily("Calibri (Corps)");
    tmpRun.setBold(true);
    tmpRun.setColor("003894");
    tmpParagraph.setAlignment(ParagraphAlignment.LEFT);
    tmpRun.setUnderline(UnderlinePatterns.SINGLE);
    tmpParagraph.setSpacingAfter(300);

    FileOutputStream fos = new FileOutputStream("Word2.docx");
    docx.write(fos);
    fos.close();
    }
    catch (Exception e ) {
        e.printStackTrace();
    }
    }
}

Comment: Your words are exactly the same...
Comment: I edit my question it was just a mistake
Comment: Arabic is right to left instead of left to right.  Does XWPFDocument know that the writing direction is changed?
Comment: just cant fing any command doing what you had proposed....(tmpRun(reverse(word)))
Comment: mm sorry I meant that you can implement a `reverse` method by yourself and then `tmpRun.setText(reverse("شهادة بالملك"))`. It is not a nice solution but that's a possible fix in case you don't find anything else
Comment: NO, how can i tell him to write from right to left ?!!
Comment: It is not even sure that such a feature has been implemented... Programs or libraries cannot be adapted to every languages in the world.
Comment: i'am sure that apache poi can support this, and i should just change the direction right to left as Andersen said i just should find the command doing this !
Comment: possible duplicate of [Right to Left (RTL) text in XWPFDocument (Apache POI)](http://stackoverflow.com/questions/11171777/right-to-left-rtl-text-in-xwpfdocument-apache-poi)
Comment: AbstractWordView can not be resolved as type !!!!!
Answer: this is the answer :
public class word {

    public enum TextOrientation {
          LTR,
          RTL
       }

    public static void main (String [] args) {

    XWPFDocument docx = new XWPFDocument();

    try {

    XWPFParagraph tmpParagraph = docx.createParagraph();
    XWPFRun tmpRun = tmpParagraph.createRun();
    tmpRun.setText("شهادة بالملك");
    tmpRun.setFontSize(18);
    tmpRun.setFontFamily("Calibri (Corps)");
    tmpRun.setBold(true);
    tmpRun.setColor("003894");
    tmpParagraph.setAlignment(ParagraphAlignment.CENTER);
    tmpRun.setUnderline(UnderlinePatterns.SINGLE);
    tmpParagraph.setSpacingAfter(300);
    setOrientation(tmpParagraph, TextOrientation.RTL);

    FileOutputStream fos = new FileOutputStream("Word2.docx");
    docx.write(fos);
    fos.close();
    }
    catch (Exception e ) {
        e.printStackTrace();
    }
    }

    private static void setOrientation(XWPFParagraph par, TextOrientation orientation) {
          if ( par.getCTP().getPPr()==null ) {
              par.getCTP().addNewPPr();
          }
          if ( par.getCTP().getPPr().getBidi()==null ) {
             par.getCTP().getPPr().addNewBidi();
          }
          par.getCTP().getPPr().getBidi().setVal(orientation==TextOrientation.RTL?STOnOff.ON:STOnOff.OFF);
       }
}


In MongoDB how to use "$expr" with an array?

Question: Let's say I have the below document:
{
 MyField1: 'A',
 MyArray: [
  {
   MyArrayField1: 'C';
  },
  {
   MyArrayField1: 'A';
  }
 ]
}

How can I select all documents in MyArray an object with MyArrayField1 = MyField1?
I tried

db.find({$expr: {$eq: ["$MyArray.MyArrayField1",
  "$MyField1"]}})

even

db.find({$expr: {$eq: ["$MyArray.MyArrayField1",
  "A"]}})

but it's not working :(
Answer: You can use $in operator
db.col.find({
    $expr: {
        $in: [ "$MyField1", "$MyArray.MyArrayField1" ]
    }
})

In this case MyArray.MyArrayField1 will represent an array of two values A and C
Comment: {
        $lookup:{
            from: "dealer",
            let: { codes: "$dealer_codes_exist" },
            pipeline: [
                {
                    $match:{
                        $expr:{
                            $and:[
                                { $nin: [ "$code",  "$$codes" ] },
                            ]
                        }
                    }
                },
                { $project: { code: 1, _id: 0, name: 1 } }
            ],
            as: "dealers"
        }
    }
Comment: @AbdulMoiz can you open a separate question and link it here? Thanks


change a static method for a functional component. I have been making class to functional but I have never done a static method yet

Question: here is what the static method looks like, I want to change the class component to a functional component but functional components don't support it. I am still learning, any advice will be appreciated
static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.security.validToken) {
     setTimeout(() => {
        const product_type = localStorage.getItem("types");
        if (product_type === "imp") {
          nextProps.history.push("/imported");
        } else if (product_type === "branded") {
          nextProps.history.push("/brands");
        } else if (product_type === "imp,branded" || product_type === "branded,imp") {
          nextProps.history.push("/imported-brands");
        } else if (product_type === "local") {
          nextProps.history.push("/local");
        }
      }, 1000);
    }

Comment: If you fully transition to functional component, then simply defining the given function should work
Comment: static functions are similar to normal functions except for they can be invoked by className directly and used for utility. Have a read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static .

Coming to your question, you have to check the code where it is being called
Comment: static is a class concept, I don't think it will be possible when you switch to functional components. Is there any specific reason that you want the function to be static ?
Comment: @Kaneki21  I don't know the purpose, it was written by the previous dev. I have not covered this in my course yet. I am breaking the code and understanding it.
Comment: @Kaneki21 is there any specific time when this gets called in a component's lifecycle because I don't see it being called anywhere
Answer: Would be easier if you could share the whole component, or at least how/where you plan to manage your functional component's state. As said on this anwser:

This has a number of ways that it can be done, but the best way is situational.

Let's see how we could create a ProductsRouter functional component.
import React from 'react'
import { useHistory } from 'react-router'

export const ProductsRouter = ({ security }) => {
  // our page state
  const [productType, setProductType] = React.useState('')
  // history object instance
  const history = useHistory()
  // our routing effect
  React.useEffect(() => {
    // if not authenticated, do nothing
    if (!security.validToken) return
    // update our state
    setProductType(localStorage.getItem('types'))
    // timeout function
    const timer = setTimeout(() => {
      if (productType === 'imp') {
        history.push('/imported')
      } else if (productType === 'branded') {
        history.push('/brands')
      } else if (productType === 'imp,branded' || productType === 'branded,imp') {
        history.push('/imported-brands')
      } else if (productType === 'local') {
        history.push('/local')
      }
    }, 1000)
    return () => clearTimeout(timer)
  }, [])

  return
{JSON.stringify({ history }, null, 2)}

}

We could use a map to keep our code tidy and flexible. If there's no particular reason to have a 1000ms timeout, we could also call push instantly, as long as we have a validToken.
const typesMap = new Map([
  ['imp', '/imported'],
  ['branded', '/brands'],
  ['imp,branded', '/imported-brands'],
  ['branded,imp', '/imported-brands'],
  ['local', '/local'],
])

export const ProductsRouter = ({ security }) => {
  const history = useHistory()
  React.useEffect(() => {
    if (!security.validToken) return
    history.push(typesMap.get(localStorage.getItem('types')))
    return () => {}
  }, [security.validToken])
  return
{JSON.stringify({ history }, null, 2)}

}

Hope that helps! Cheers
Comment: how do we write refactor it if the condition returns two values as if it's 'imp', make it 'imported' and 'branded'? @Moa
Comment: We can use an array with both values. As in ['imp', ['/branded', '/imported']]. We can't redirect to two endpoints simultaneously, though. Is that what you mean?
Comment: I have to send values to a splice method with a few if else conditions as (0,1) (1,1) if it's imported meaning two set of values so I tried ['imp', (0,1), (1,1) but it returns 1 and now I tried it with the array and it gives me an array like so [1, 1] @Moa
Comment: Have you tried this ['imp', [[0,1], [1,1]]]? It's hard to help without knowing what you're actually trying to achieve. Maybe create a new question with more info and paste the link here so I can have a look and try to help you more efficiently?
Comment: I tried all types of brackets and braces. However, you can have a look on what I am trying to achieve (goal: best practices) - the way you have done for if else conditions https://stackoverflow.com/questions/73618768/trying-to-refactor-and-make-use-of-the-map-object @Moa


assign values to variable names in Matlab

Question: Is there a way to assign values to variable names which are both supplied by the user?
I thought of something along these lines:
function varargout=my_fun(varargin)

for i=1:2:nargin
eval('varargin{i}=varargin{i+1}')
end

>> my_fun('a',1,'b',2)

>> a

1

>> b

2

but it doesn't work.
Answer: You could do this using assignin, but I strongly recommend not to use such solution. It violates the common expectations of a variable scope. Besides this, assignin and eval are two of the best option to confuse the matlab editor, which results in many useless recommendations and warnings.
If you really need such a solution:
assignin('caller',varargin{i},varargin{i+1}) to assign to the caller work space.
Comment: Thanks a lot! That works great! I'll be careful in using it though :)


cannot properly mock Notification API

Question: I have the following in my setupTests.ts:
globalThis.Notification =  ({
    requestPermission: jest.fn(),
    permission: "granted",
} as unknown) as jest.Mocked<typeof Notification>

However, I keep getting this error in my jest test in a react project:
TypeError: Notification is not a constructor

  21 | export function showNotification(title: string, notificationText: string) {
  22 |     if (Notification.permission === "granted") {
> 23 |         const notification = new Notification(title, {  // params});

How to fix it to mock Notification API properly?
Comment: Is that surprising? Your test double of Notification is an object with one method and a string property, which _isn't_ a constructor.
Answer: I was facing a similar problem. I used the following method to mock the Notification. Visual studio code kept complaining about the way I was mocking the object, but the test still ran perfectly.
I was able to add a mock function for close, which I could test later using expect.
    const mockClose = jest.fn();

    global.Notification = jest.fn().mockImplementation(
      () =>
        (({
          close: mockClose,
        } as unknown) as Notification)
    );

    functionInCode(data); <--- Calls new Notification

    expect(global.Notification).toBeCalledTimes(1);
    expect(mockClose).toBeCalledTimes(1);

cannot properly mock Notification API


Change Proxy Settings In Ubuntu

Question: I want to use the Ubuntu Software Center to install software, but I cannot download them.
How can I give my proxy settings in Ubuntu terminal (just like we use cmd in Windows to choose IE proxy settings)?
Answer: You can easily change the proxy settings for your user, or for the entire system, within the Network config under System Settings. This uses the GUI and is quick and helpful, but not very advanced. If you have particular requirements or special settings/circumstances, this may not do everything you need.

Open System Settings
Choose Network
In the left hand menu, choose Network Proxy
Enter your proxy settings. If you want to apply them system wide, press that button.
Close the window, or presss All Settings to leave this interface.

You should be all set. You may have to logout and login again for changes to take affect. In unusual circumstances, you may have to reboot your system, but that is highly unlikely for a Linux system.
Comment: That's not a terminal solution, but a good one.
Answer: proxy setting from terminal in ubuntu:
Open the terminal and run the following commands:
For a HTTP proxy, simply run the following command in a terminal
export http_proxy='http://proxy_username:password@proxy_ip:port'

For a HTTPs and FTP
export https_proxy='https://proxy_username:password@proxy_ip:port'
export ftp_proxy='ftp://proxy_username:password@proxy_ip:port'

If there is no username and password required for your proxy then simply remove the username and password section.
export https_proxy='https://proxy_ip:port'

These settings are saved into  /etc/apt/apt.conf file .So you can directly add these variables using text editor .First open the apt.conf file
sudo gedit /etc/apt/apt.conf

then enter the username,password,proxy_ip and port in given format
Acquire::http::proxy "http://proxy_username:password@proxy_ip:port";
Acquire::https::proxy "https://proxy_username:password@proxy_ip:port";
Acquire::ftp::proxy "ftp://proxy_username:password@proxy_ip:port";

Comment: I can't find /etc/apt/apt.conf file. Is there any alternative to this file ?
Comment: I also want to try the first solution using export, but my username is "domainname\firman" how should I write the syntax ? Thank You
Answer: Add
http_proxy='http://proxy_username:password@proxy_ip:port'
https_proxy='https://proxy_username:password@proxy_ip:port'
ftp_proxy='ftp://proxy_username:password@proxy_ip:port'

to /etc/environment to load them automatically at login (or system start - I might look that up if it matters).

Change Proxy Settings In Ubuntu


CSS font-weight property is either bold or light

Question: I'm facing a weird issue with font-weight property on a button element
When I set font-weight to 400, it works just fine.
However, if I try to set it to 300 or 500, nothing changes.
It only becomes bold if I do font-weight: 600, which isn't even imported!
Using !important doesn't help either
I have also checked that the style isn't overwritten.
I'm using Inter font family, and React library
My index.html (inside the public folder):
<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="icon" href="favicon.ico?v=2" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Apple notes (not really)"
    />
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500&display=swap" rel="stylesheet">
    <title>Apple notes</title>

    You need to enable JavaScript to run this app.

JSX where the bug occurred (on button with class add-note):
import React, { useState, useEffect } from "react";

export default function Sidebar() {
    return (

                <button type="button" className="add-note">Add new note</button>

    )
}

CSS:
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: Inter, Arial, Helvetica, sans-serif;
}

.add-note {
  font-size: 1.2rem;
  font-weight: 600;
  color: var(--clr-font-light);
  background-color: var(--clr-accent-light);
  border: none;
  border-radius: 5px;
  padding: 10px;
  width: 100%;
}

.add-note.dark {
  background-color: var(--clr-accent-dark);
  color: var(--clr-font-dark);
}

Comment: It's not picking up the font-family you want in that button. Use your browser devtools inspect facility to see exactly what is being set and you'll find that the browser has cleared font-family setting (which otherwise by default is inherit).
Answer: I think the matter is form elements don't inherit font settings automatically. Try to explicitly set in CSS file: button {font-family: inherit}; and apply desired font-weight on the button class further: .add-note {font-weight: 400};
That is relevant for inputs, textareas as well.


rubber gasket under bathroom sink leak

Question: Need temp.fix, seal until January when I'll replace the whole thing. Replacing gasket might not be possible due to age and state of the whole thing.
Comment: Hello, and welcome to Home Improvement. Use a mess of caulk, and pray? And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to participate here.
Comment: Okay! Thank you. What is " a mess of caulk, and pray"?
Comment: Basically what's described in the answers below (although they don't mention the prayer aspect).
Answer: No great answer for a temp fix. Clean existing seal and surrounding area with a non-abrasive cleaner such as Comet Classic spray-on.  Be sure to remove any loose bits of rubber or other material around damaged seal before applying caulk.

Apply a generous bead of clear GE Silicone all around existing seal. Using a finger and gentle pressure, smooth the bead of caulk, pressing it into any gap or crevice around the seal.
Make certain you have complete coverage of any and all gaps. One you have applied this silicone, you cannot do a second application, as it will not bond. Remove excess with paper towel and allow 60 minutes minimum before checking efficacy. Be certain to used a new, unexpired tube of silicone caulk. Expired caulk will not cure.
Run water, check for leaking. After the caulk has cured, you may want to tape a short length of toweling all the way around the pipe. An old, clean rag will do. Check and replace toweling if it gets wet.
This won't be pretty but it should keep the floor dry until you replace the sink and plumbing in January. Good luck.
Comment: thank you.  So far it is working!
Comment: I did, but my reputation is insufficient.
Comment: Thank you. Testing right now.
Comment: I hope it keeps you going until January.
Comment: Glad it's working. Don't forget to upvote me!
Comment: Here's one for you.
Answer: Seals shrink over time with age. Therefore I would start by using a rench and tightening up the assembly. You might be done after that. If not the amount of water is that small that you just catch the water and do nothing else. Then I would disassemble the drain which is actually not much work and replace the gaskets. I don't believe that silicon is fixing this without disassembly anyway.
There are also replacement kits available for the complete assembly which don't cost much.
Answer: You should be able to slow it down by caulking inside the sink around where the actual drain pipe comes in contact with the sink bowl. that's probably where the water's originating from.
Comment: sorry, sounds like a rocket science to me
Comment: @OohLaLa    In the sink, between the chrome ring and the actual sink material.. That is a bathroom sink, right?
Comment: That is a bathroom sink.
Comment: Place a small bead of caulk around the rim of the chrome drain and sink. Good luck

rubber gasket under bathroom sink leak


RabbitMQ keeps too many queue mirrors after rolling upgrade

Question: We have upgraded our RabbitMQ cluster recently to the latest version with a rolling upgrade (remove one node after the other, upgrade it and then add it back to the cluster with the newer version).
Roughly speaking, we proceeded as follows:
<code># Put host into maintenance mode
rabbitmq-upgrade drain

# Install new rabbitmq version

# Re-join cluster
rabbitmqctl join_cluster rabbit@rabbit01
</code>
Regarding the rolling upgrade, we have deliberately not included all the details here because this process is not the problem. The problem is rather the following: We wanted to make sure that the queue leader replicas are evenly distributed again afterwards. So we did:
<code># Rebalance queues
rabbitmq-queues rebalance "all" --vhost-pattern ".*" --queue-pattern ".*"
</code>
But now we have a situation where some queues have too many mirrors! We are using classic queue mirroring with the following policy:

But the next image shows that some queues have +2 mirrors. Normally this should only state +1.

Of course you could say that this is nothing too bad. But since we use automated checks to make sure that for each queue the correct number of mirors exists, these tests are now failing. We are looking for a way to get RabbitMQ to clean up this situation again, so that only the configured number of mirrors is created and continued.
Answer: It is possible to apply a new policy to the queue, with the same values as the old, but with a higher priority and a different name. When the policy changes, RabbitMQ will apply the correct values and the mirrors that are to much will vanish. In your example the command with rabbitmqctl would look like this:
<code>rabbitmqctl set_policy --vhost customers --priority 1 new-tmp-policy "^ha.sample_queue_" '{"ha-mode": "exactly", "ha-params": 2, "ha-sync-mode": "automatic", "queue-master-locator": "min-masters", "queue-mode": "lazy"}'
</code>
This will change the policy for the sample_queues to "new-tmp-policy" and the mirrors will vanish. Now just delete the "new-tmp-policy" and the old policy will be applied again for the sample_queues.
Comment: Just tested your suggestion and it actually solves my problem. Thanks a lot!


Checking pipe state

Question: I create a named posix pipe, say pipe_out, using
mkfifo $path_tmp/pipe_out

open it in C
out_pipe = fopen(TMP_PATH "/pipe_out", "w");

and write to it using the fprintf command
fprintf(out_pipe,"%s",string);

I guess I could use the return value of fprintf to check how much was written and compare it to the actuall length of the string, to know if the complete string was written to the pipe. Then, if it is (over-)full, I pause somehow and try to write again in an endless loop starting with what was not yet written...
What would this look like in detailed and is there maybe a more advanced way which stalls (pauses) fprintf  automatically when the pipe is full.
Answer: If you want to pro-actively detect when the pipe is full, using fprintf() is not a good idea because it will internally buffer your data.
Even if the pipe fd is not writable anymore, fprintf() will continue to return unless the internal buffer is also full. In that case, it will not return a shortened value but block until it can write/buffer the whole string.
If you want to detect pipe state, you should not use buffered function but:

open() to open fifo/pipe
select() to test is file descriptor is writable
write() to write string (return value must be handled)

Checking pipe state


swift Xcode 6 unwind segue action doesn't fire

Question:
"Done" button of the modally presented controller ("Modal") is bound to an exit action defined in the primary controller ("Main"):
<code>@IBAction func done(segue:UIStoryboardSegue) {}
</code>
"Done" button is not firing!
I have tried the manual segue approach from Unwind Segue in Xcode 6 Beta 4 and bound the "Done" button action to following code in "Modal":
<code>@IBAction func donePressed(sender: AnyObject) {
    performSegueWithIdentifier("unwind", sender: self)
}
</code>
it doesn't work too!
if I remove tab bar controller everything is working fine - is that a bug or a restriction?
P.S.There is an annoying log output I can't get rid of:
<code>2014-08-17 16:14:15.380 SwiftPhotoCards[9113:497540] 17545849:_UIScreenEdgePanRecognizerEdgeSettings.edgeRegionSize=13.000000
</code>
no idea whether it is related to the issue or not but I thought it's worth mentioning it.
Comment: It doesn't work in beta 6 too. I ended changing the type of segue from modal to popover and now it works as it is supposed to.
Comment: Did you try with Xcode 6 beta 6? Did you try with a pure new Swift project? Unwind segues are normally fixed with Xcode 6 beta 5. I was able to set an Unwind segue (`@IBAction func done(segue:UIStoryboardSegue) {}`) in a new Swift Master-Detail application project with Xcode 6 beta 6.
Answer: I've been struggling with what may be the same issue (although I'm using a Split View instead of a Tab Bar) and was able to resolve it by setting the Modal segue to "Presentation: Current Context" instead of "Default" in the Attributes Inspector:

(This is the setting on the Segue arrow that creates "Main" to "Navigation Controller" in your screenshot).
Comment: You sir, are the man. Actually... I partially take that back. Using a tab bar controller it ends up presenting with the tabs on the bottom... ugh apple...
Comment: This isn't limited to Swift.  I am having problems with an unwind segue from a modal segue using regular Obj-C.  The workaround posted by @payton works, but as reported by the previous comment, the tabs show up on the bottom allowing the user to navigate away from a view that is supposed to be modal.


Will the Rotation games stay forever even after new rotation?

Question: Let's say I download Uncharted 3 because it is on this month's rotation, when the month ends and a new rotation begins, will I still be able to play uncharted?
Can I keep a "free rotation" game forever by being a Playstation Plus member?
Comment: You can find the answer you seek [here](http://gaming.stackexchange.com/questions/76543/what-happens-to-free-games-obtained-through-playstation-plus-after-it-expires). Basically: `If you did not download the game when it was in the collection, you will not be able to secure your free download. However, if you downloaded when it was in the collection, but it's no longer on your hard drive, you can visit the PlayStation Store and re-download it anytime, as long as you're a member.` The same also applies to *playing* the game.
Comment: So you can Keep a "rotation" game forever as long as you are a member?
Comment: Yes, and re-download it in case you delete it from your console.
Comment: @Peter do not edit someone's answers, ask in comments, or update your question. And concerning your edit, yes as long as you have "purchesed" or downloaded PS+ game and have not interrupted your PS+ membership it's always available for you (I think that's that I wrote in answer already).
Answer: The @Nolonar comment is somehow different to my expirience, but I'm a member is a Russian segment of PSN, so it could possibly differ.
Basically during the rotation, you must "purchase" the game with a price of 0. If you "purchased" the games it's not necessary to even download them, they will be available "forever" till you are member. The additional requirement, your subscription mustn't be interrupted. If you make a pause in subscription you could lose your free games (but not necessarily will).


Bigquery select distinct values

Question: How to select distinct values in Google Bigquery?
Query:
SELECT DISTINCT cc_info
FROM user
WHERE date = ?

Thanks!
Answer: SELECT cc_info
FROM user
WHERE date = ?
GROUP BY cc_info

Comment: And if this solution stops working as your tables grow larger, you can replace `GROUP BY` with `GROUP EACH BY` to increase the scalability.
Comment: is it possible to do select * from table group by *?
Answer: Simply use group by,
SELECT cc_info
FROM user
WHERE date = ?
GROUP BY cc_info

If you want to COUNT over DISTINCT values you can use,
SELECT COUNT(DISTINCT cc_info)
FROM user
WHERE date = ?

Answer: Try using group by
SELECT cc_info
FROM user
WHERE date = ?
group by cc_info

Answer: For all who have come to find the DISTINCT method in BigQuery, and who needs to use unique field feature for tables having large columns, using GROUP BY as mentioned by tning won't be possible.
As of 2020, BigQuery has DISTINCT modifier. You need to wrap your query as:
SELECT DISTINCT usr.cc_info
FROM (
  SELECT *
  FROM user
  WHERE date = ?
) usr

This could be very handy for people shifting from other SQL products.
Answer: SELECT COUNT(DISTINCT cc_info)
FROM user
WHERE date = ?

is NOT the right query, because DISTINCT is a statistical approximation and is not guaranteed to be exact. See https://cloud.google.com/bigquery/docs/reference/legacy-sql#countdistinct
So better approach is
select EXACT_COUNT_DISTINCT(cc_info) from user where date = ?

Comment: Yes, you are right. Normal distinct uses hyper log log algorithm to count distinct over distributed machines. Depending on your data if some approximation is alright, COUNT provides much better performance compared to EXACT_COUNT_DISTINCT. I really appreciate how complex algorithm runs behind the scene for a simple COUNT DISTINCT statement. https://cloud.google.com/bigquery/docs/reference/legacy-sql#exact_count_distinct
Answer: This is another way to achieve your goal (in case anyone else needs it) which works in the current BigQuery 2020.
SELECT colname FROM table1
UNION DISTINCT
SELECT colname FROM table2
UNION DISTINCT
.
.
.
SELECT colname FROM tableN

My reference was this article.
Answer: At present, BigQuery provides the Distinct Counts view by default under the Table Explorer tab

Bigquery select distinct values


Plist To SQLITE

Question: I'm trying to convert my .plist to SQLITE DB since my app got reject because .plist was too big.
I've been trying few days and still don't know how to convert this. First tried to find some converted but couldn't find any so now I'm trying to convert threw code with enumeration but can't get right result.
Could anyone help me convert this to SQLITE (just need SQL INSERT stuff and relations if needed, since I'm going to use FMDB it will be easy to implement in Xcode):
<code><array>
<dict>
    <key>State</key>
    <string>Alabama</string>
    <key>Area code</key>
    <dict>
        <key>205</key>
        <array>
            <dict>
                <key>City</key>
                <string>Birmingham, AL</string>
                <key>County</key>
                <string>Jefferson</string>
            </dict>
            <dict>
                <key>City</key>
                <string>Birmingham, AL</string>
                <key>County</key>
                <string>Shelby</string>
            </dict>
        </array>
        <key>251</key>
        <array>
            <dict>
                <key>City</key>
                <string>Mobile, AL</string>
                <key>County</key>
                <string>Mobile</string>
            </dict>
            <dict>
                <key>City</key>
                <string>Atmore, AL</string>
                <key>County</key>
                <string>Escambia</string>
            </dict>
        </array>
    </dict>

    <key>Zip code</key>
    <array>
        <dict>
            <key>City</key>
            <string>Wetumpka</string>
            <key>County</key>
            <string>Elmore</string>
            <key>Zip code</key>
            <string>36093</string>
        </dict>
        <dict>
            <key>City</key>
            <string>Winfield</string>
            <key>County</key>
            <string>Fayette</string>
            <key>Zip code</key>
            <string>35594</string>
        </dict>
    </array>
</dict>
</code>

Top array contains dictionary of states (this is just Alabama, all states are included in, but should be enough for example).
Thanks.
Comment: Also To-Core-Data would also be helpful if anyone can help. Thanks
Comment: Do you know anything at all about SQLite?  How did you originally create the XML data?  (As I understand it you want to ship a "canned" SQLite DB, so you probably want to build it on a desktop system.  Might as well start from your original data.)
Answer: You'll want to migrate to Core Data.  Add a model to your project, it's under "Core Data" in the file wizard.
Off-hand it looks like you'll want two entities: State and AreaCode; State would have a toMany relationship with the AreaCode entity.  Once these entities are constructed in the model builder you can export them and Xcode will generate the classes for you.
If you want to migrate your current plist directly; I think the best way is to open the plist as a dictionary; for every State dictionary call initWithEntity: and do the appropriate -[setValue: forKey:] for your properties from the dictionary.  Then once you save the object context everything will be persisted for you.

Plist To SQLITE


Brouwer fixed-point theorem on a function

Question: For $f:\mathbb R^n \rightarrow \mathbb R^n \quad \exists R \gt 0 $ that $f$ is continous on $\bar B_R(0):= \{ x \in \mathbb R^n : \Vert x\Vert_2 \leq R \} \subset \mathbb R^n$ .
Let also $\langle f(x),x \rangle \geq 0 \quad \forall x \in \partial\bar B_R(0)$
Show that it exists a $x^* \in \bar B_R(0) $ so that $f(x^*) = 0$.
I tried to check the function $F:\bar B_R(0) \rightarrow \mathbb R^n , \quad F(x):= -R \frac{f(x)}{\Vert f(x)\Vert_2}$ with the Brouwer fixed-point theorem but didnt get far.
Any help is appreciated thanks.
Answer: Suppose by contradiction that $f(x)\neq0$ for all $x\in \bar{B}_R(0)$. Then your function $F:\bar{B}_R(0)\to\mathbb{R}^n$ is well defined and we have that $|F(x)|=R$ for all $x\in \bar{B}_R(0)$, hence we  can write that $F:\bar{B}_R(0)\to\partial \bar{B}_R(0)\subset\bar{B}_R(0)$. Also $F$ is continuous, so by the Brower fixed point theorem there exists $x_0\in\bar{B}_R(0)$ such that $F(x_0)=x_0$. Moreover $|F(x_0)|=|x_0|=R$ implies that $x_0\in \partial \bar{B}_R(0)$. Now we have:
$$0<R^2=\langle x_0,x_0\rangle=\langle F(x_0),x_0\rangle=-\frac{R}{|f(x_0)|}\langle f(x_0),x_0\rangle\le0,$$
that is a contradiction.
Comment: wow thats smooth thank you alot


How can i downgrade GCC 4.7.2?

Question: i want to downgrade GCC and G++ 4.7.2 to some older versions, 4.0 perhaps. Any assistance? I'm using Lubuntu ATM.
Comment: Why would you want to do that?
Comment: I don't know why BlueBaron might want to do that, but I would do that if I had an important codebase that had been compiled with GCC 4.0 and subject to a lot of testing. On a previous job, I versioned the GCC toolchain. If we checked out a baseline from six months ago, its makefiles would point to the compiler which was used six months ago.
Comment: There are good reasons not to use the latest, shiniest release of GCC, such as that it's a fast moving target with poor QA.
Answer:
You can install 4.4, 4.6, 4.7

<code>sudo apt-get install gcc-4.
gcc-4.4                               gcc-4.6-plugin-dev                    gcc-4.7-locales
gcc-4.4-base                          gcc-4.6-source                        gcc-4.7-multilib
gcc-4.4-doc                           gcc-4.7                               gcc-4.7-multilib-arm-linux-gnueabi
gcc-4.4-locales                       gcc-4.7-aarch64-linux-gnu             gcc-4.7-multilib-arm-linux-gnueabihf
gcc-4.4-multilib                      gcc-4.7-aarch64-linux-gnu-base        gcc-4.7- multilib-powerpc-linux-gnu
gcc-4.4-source                        gcc-4.7-arm-linux-gnueabi             gcc-4.7-plugin-dev
gcc-4.6                               gcc-4.7-arm-linux-gnueabi-base        gcc-4.7-powerpc-linux-gnu
gcc-4.6-base                          gcc-4.7-arm-linux-gnueabihf           gcc-4.7-powerpc-linux-gnu-base
gcc-4.6-doc                           gcc-4.7-arm-linux-gnueabihf-base      gcc-4.7-source
gcc-4.6-locales                       gcc-4.7-base
gcc-4.6-multilib                      gcc-4.7-doc
</code>
You need to install base package for example
<code>  sudo apt-get install gcc-4.4-base
</code>
Comment: Can you get 4.0 this way?
Comment: nope ...only starting from 4.4
Comment: do this sudo apt-get install gcc  then press " Tab " key twice

How can i downgrade GCC 4.7.2?


show another image on mouse over of the default image in category product list in magento

Question: I am developing a magento site. In my category products listing page (catalog/products/list.phtml). I need to implement swap image function on mouse over the default image...( here each product have 2 or more images  and while mouse over the default  image, should be show any of the other image )
I am new to this magento..
Does any one help me ..
Answer: from what i know magento only loads 1 image on the category page by default, the "small_image".
if you want to display any other image you have to create a full instance of the product
$_product = Mage::getModel('catalog/product')->load([product id]);

then loop through the media gallery:
foreach ($_product->getMediaGalleryImages() as $image) {
  // assign the image you want to the product object
  $_product->setImage($image->getFile());
}

once you've done that you can access the new image using
echo $this->helper('catalog/image')->init($_product, 'image')->resize(200, 350);

the above will return the image url of a cached version of the image with 200x350

assign this to a data attribute of your image and use javascript to change the img src on mouseover

you might want to consider preloading all these mouseover images using javascript to give the user the best possible experience


VSCode extension api – file type/extension icons using ThemeIcon

Question: We are building an extension that visualizes some data for workspace files in our view using a class derived from TreeDataProvider. We wonder if there is a way to use file icons contributed by the current File Icons Theme for our custom tree items. Base icon class has a field icon: ThemeIcon which supports product icons. Wonder if something similar exists for referring to file-type icons?
Thanks
Comment: if you use an URI as tree item you get the current file icon
Answer: Seems like using resourceUri and ThemeIcon.File is the way to do it:
this.iconPath = ThemeIcon.File;
this.resourceUri = Uri.parse('_.js');


JPA using eclipselink and java.sql: when connect to DB

Question: I explain better my question since from the title it could be not very clear, but I didn't find a way to summarize the problem in few work. Basically I have a web application whose DB have 5 tables. 3 of these are managed using JPA and eclipselink implementation. The other 2 tables are manager directly with SQL using the package java.sql. When I say "managed" I mean just that query, insertion, deletion and updates are performed in two different way.
Now the problem is that I have to monitor the response time of each call to the DB. In order to do this I have a library that use aspects and at runtime I can monitor the execution time of any code snippet. Now the question is, if I want to monitor the response time of a DB request (let's suppose the DB in remote, so the response time will include also network latency, but actually this is fine), what are in the two distinct case described above the instructions whose execution time has to be considered.
I make an example in order to be more clear.
Suppose tha case of using JPA and execute a DB update. I have the following code:
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
EntityManager em=emf.createEntityManager();
EntityToPersist e=new EntityToPersist();
em.persist(e);

Actually it is correct to suppose that only the em.persist(e) instruction connects and make a request to the DB?
The same for what concern using java.sql:
Connection c=dataSource.getConnection();
Statement statement = c.createStatement();
statement.executeUpdate(stm);
statement.close();
c.close();

In this case it is correct to suppose that only the statement.executeUpdate(stm) connect and make a request to the DB?
If it could be useful to know, actually the remote DBMS is mysql.
I try to search on the web, but it is a particular problem and I'm not sure about what to look for in order to find a solution without reading the JPA or java.sql full specification.
Please if you have any question or if there is something that is not clear from my description, don't hesitate to ask me.
Thank you a lot in advance.
Answer: In JPA (so also in EcliplseLink) you have to differentiate from SELECT queries (that do not need any transaction) and queries that change the data (DELETE, CREATE, UPDATE: all these need a transacion). When you select data, then it is enough the measure the time of Query.getResultList() (and calls alike). For the other operations (EntityManager.persist() or merge() or remove()) there is a mechanism of flushing, which basically forces the queue of queries (or a single query) from the cache to hit the database. The question is when is the EntityManager flushed: usually on transaction commit or when you call EntityManager.flush(). And here again another question: when is the transaction commit: and the answer is: it depends on your connection setup (if autocommit is true or not), but a very correct setup is with autocommit=false and when you begin and commit your transactions in your code.
When working with statement.executeUpdate(stm) it is enough to measure only such calls.
PS: usually you do not connect directly to any database, as that is done by a pool (even if you work with a DataSource), which simply gives you a already established connection, but that again depends on your setup.
PS2: for EclipseLink probably the most correct way would be to take a look in the source code in order to find when the internal flush is made and to measure that part.


ionic 2 SQLite manage callback with Promise

Question: I want to get the callback of a successful SQLite transaction with Ionic 2. I am still currently learning the HTML5 Promise, and it is still a bit confuse. And since I've heavily used jQuery Deferred before, I try to adapt what I used to do with jQuery.
Before Ionic 2, I used the following jQuery pattern to execute my async SQL:
var SqlResult = function(sqlToExecute,bracketValues){
    this.sqlToExecute = sqlToExecute;
    this.bracketValues =bracketValues;
};

SqlResult.prototype.execSqlCustomDeferred = function(){
        var execSqlCustomDeferredRes = $.Deferred();
        var execSqlCustomDeferredResProm = execSqlCustomDeferredRes.promise();

        var sqlToExecuteForTx = this.sqlToExecute;
        var bracketValuesForTx = this.bracketValues;

        DbManagement.db.transaction(function(tx){
            tx.executeSql(sqlToExecuteForTx,bracketValuesForTx,success,error);
            function success(tx,rs){
                    execSqlCustomDeferredRes.resolve(rs);
            }
            function error(tx,error){
                execSqlCustomDeferredRes.reject(error);
            }
        });
        return execSqlCustomDeferredResProm;
};

With that pattern I was getting the async result, with SqlResult.prototype.execSqlCustomDeferred.done(function(res){...}).
Now I struggle to figure out how things should be ordered to use the Promise pattern, I thought of the following but it does not match:
This case would not work because resolve() or reject() don't exist (it doesn't transpile).
private execSqlCustom = (sqlToExecute:string,bracketValues:Array<any>) => {
    let sqlToExecuteForTx:string = sqlToExecute;
    let bracketValueForTx:Array<any> = bracketValues;

    return this.db.transaction(
        function(tx){
            tx.executeSql(sqlToExecuteForTx,bracketValueForTx,success,error);
            function success(tx,rs){
                resolve(rs);
            }
            function error(tx,error){
                console.log('execSqlCustom error ' + error.message);
                reject(error);
            }
        }
    );

This would not work neither because I think I'd lose the context (this) (it  transpiles but at execution it tells me that:

it cannot read db of undefined

):
private execSqlCustom = (sqlToExecute:string,bracketValues:Array<any>) => {
    let sqlToExecuteForTx:string = sqlToExecute;
    let bracketValueForTx:Array<any> = bracketValues;
    return new Promise(function(resolve,reject){
       this.db.transaction(
        function(tx){
            tx.executeSql(sqlToExecuteForTx,bracketValueForTx,resolve,reject);
        }
    );

Does anyone spot what I've been doing wrong?
Answer: I found that it could be added a .bind(this) at the end of a function to carry within that function, the exisiting context (this).
By creating a new Promise() and adding .bind(this) at the end of the function(resolve,reject){} within it, it worked and I can use .then( (...) => {...} on the async result returned.
My function looks like that:
private execSqlCustom = (sqlToExecute:string,bracketValues:Array<any>):Promise<any> => {

    return new Promise(function(resolve,reject){
        this.db.transaction(
        function(tx){
            tx.executeSql(sqlToExecute,bracketValues,success,error);
            function success(tx,rs){
                resolve(rs);
            }
            function error(tx,error){
                console.log('execSqlCustom error ' + error.message);
                reject(error);
            }
        }
        )}.bind(this)
    );
}


Solve for the following: $\frac{\pi}{4}=\frac{e^x-e^{-x}}{2}+\arctan(x+1)$

Question: Question
Solve for the following :
$$\frac{\pi}{4}=\frac{e^x-e^{-x}}{2}+\arctan(x+1)$$
Clearly I would mutliply both sides by 2 but then I would get the following :
$$\frac{\pi}{2}=e^x-e^{-x}+\arctan(x+1)$$
I was wondering how I would simplify from here. Would i convert $\arctan$ into $\frac{\arcsin}{\arccos}?$
preferably done without using hyperbolic trig functions
Comment: Note! $\arctan \neq \frac{\arcsin}{\arccos}$ ! Not necessary for this problem, but it will lead to mistakes in the future. Try evaluating each side for a few different values with a calculator...
Comment: @JohnRawls In general, with these kind of equations you need to use methods that successively find better approximations to the roots of the function. There are different methods (e.g. Newton's Method) but for this case you can clearly see that $0$ is a solution. By taking the first derivative you can see that it always increases, therefore the only solution is $0$. Note: when you encounter equations of this kind, it is a good start to find a possible interval that might contain the zero, then use the Intermediate Value Theorem to prove it. From there you use Newton's Method to find the  root.
Comment: $e^x - e^{-x} = 2\sinh(x)$.
Comment: You have multiplied by 2 and got the same equation. Are you sure there is no typo? If the LHS is $\frac {\pi }{4} $, then $0$ is a solution.
Comment: @rohan indeed it is 0 but i dont know how to arrive at that conclusion. and also i fixed it
Answer: You can guess that $0$ is a solution, and because the derivative of $e^x-e^{-x}+2\arctan(x+1)$ is always positive, we know that $0$ is the only solution.
Answer: Let $f(x)=\frac{e^x-e^{-x}}{2}+\arctan(x+1)$.
Since $f'(x)=\frac{e^x+e^{-x}}{2}+\frac{1}{x^2+2x+2}>0$,
we get that $f$ is an increasing function.
Thus, our equation has one root maximum and since $0$ is a root, we get an answer: $\{0\}$.
I fixed a typo.


Question on Calculating Covariance and Correlation of Payoffs

Question: Suppose you are drawing randomly from three cards: a jack, a queen, and a king.  If you draw a jack it pays off 0 dollars, if you draw a queen it pays off 2 dollars, and if you draw a king it pays off 3 dollars. What are the expected value, variance, and standard deviation of your payoff from this game?
Now suppose you draw twice,  without replacement (i.e.,  for the second draw you are only drawing from the remaining two cards).  The payoffs are the same as above for both draws.  How do you calculate the expected value, variance, and standard deviation of the total payoff from the two draws?
Answer: Let's give me a try.
From my point of view the cards are uniformly distributed. Therefore
$P(X=x)=\frac{1}{3}$
Expected Value is defined as
$\mathbb{E}\left [ X \right ] = \sum_{i=1}^{3}x_{i}p_{i}$.
Plug in the numbers and you will get: 1.66667
By the same way you can compute variance and sdt as well.


What type of material is flexible but not too much, water proof, and can tolerate 80°C temperatures?

Question: The idea is to build an electric pad with an non-coated heating wire (~1.3 Ohm/metter): the pad must be flexible under the bed sheet (like this one) but not too much (to prevent it being crumpled which would damage the heating wire and might create shortcuts that could dangerously increase the heat).
This tuto recommends using a PVC+fiberglass mosquito net, which is a good idea since it is flexible but can't be crumpled and on the same time does support relatively high temperature. But he used a coated wire (these wires are, for mysterious reason, not sold anymore). So it might be dangerous with on non-coated wired since mosquito net are not really waterproof and sweat/moisture might create interesting shortcuts...
Any idea of material(s)/fabric that would meet those criteria:

flexible but not too much.
non conductive (for electricity)
tolerate 80 or 100°C (~180F) heat
doesn't emit toxic particle in contact with heat. (It would be use under bed sheet...)
relatively cheap

ps: I was thinking to use the mosquito net buy insulating those wire using heat-schrink tubing but I'm not sure they could stand the 80°C heat from the wire, and about toxic emissions.
ps2: notice that it's not a safety related question, but a technical one (I'm looking for specific material).
Comment: Electric heated blankets and mattress pads are widely available. They also have the advantage of being UL listed, so you can bet they're less likely to set you on fire while you sleep.
Comment: What is your end goal with this project?
Comment: Vtc as not home improvement
Comment: first they close the question, then 5 years later they wanted to edit the title by removing the  ''and can tolerate 80°C temperatures?'', which would have make it completely off
Answer: The project you linked is for a small heating pad on a chair, and uses insulated wire to prevent electrical shorts.  This is relatively safe (though not as safe as just buying one) mostly because the person using it is awake and alert - if it starts arcing or overheating they will notice.
Building your own to heat the whole bed is a much riskier proposition.  You (and potentially loved ones) will be asleep and may not notice such problems quickly enough.  Using uninsulated wires just makes it that much more dangerous.  If you start a fire, you will probably find your insurance won't pay out after the fire inspector determines the cause to be your jerry rigged heating blanket.
I am all for DIY, especially building my own electronics, but sometimes it is best to leave it to companies that can afford to do a lot of safety testing.
Heating blankets are easily available at many stores, and probably won't cost much more than the parts and material you need to build your own. They are tested for safety and usually include cutoffs to prevent overheating and shut off if more than the expected current is drawn (if a wire shorts inside).
The linked project says it is more durable than a heated blanket because it doesnt have to be cleaned.  But I have had one for years, washed regularly, with no issues.  If that is a big concern put it under a plastic sheet so it never gets dirty.
So just buy one, and use your heating wire for more interesting projects, like foam sculpting or building an awesome fog machine.
Comment: just a feedback: I slept on it during the last 5 years, 7 months per year, I'm still alive...
Comment: @JinSnow One of the issues with things like this is that a 1% failure (or worse, fatality) rate is pretty awful, and yet results in 99% of people saying everything is fine.
Comment: ok, but it's off topic, the question isn't about safety.
Answer: Probably ABS plastic fits the bill. But, as others have noted, this sounds like a terrible and dangerous idea. Don't set yourself on fire.


How to draw a Polyline on google map from other window

Question: I'm trying to draw a Polyline on my map.  The script that draws the Polyline is defined and called from a pop-up window.
        var route = new google.maps.Polyline({
             map: window.parent.map,
             path: result.routeCoordinates,
             geodesic: true,
             strokeColor: '#00FF00',
             strokeOpacity: 1.0,
             strokeWeight: 2
         });

"map" is defined as a global variable and when I'm debugging I actually see that the contents of window.parent.map are correct.
Still this approach gives me the following error:
InvalidValueError: setMap: not an instance of Map
I found other threads about this error but I din't manage to solve my problem based on these.
UPDATE: Here some code that will allow to reproduce the error.
First the main page containing the map:
<!DOCTYPE html>

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

    <title>GMaps</title>

Secondly the popup window (called example2.html):
<!DOCTYPE html>

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

    <title>GMaps</title>

    Draw Polyline

For completeness, relevant tags in the stylesheet are the following:
html{height: 100%}
body{height: 100%; margin: 0; padding: 0}
#map-canvas{height: 100%}

Comment: Please provide a [mcve] that demonstrates the issue.
Comment: @geocodezip I edited the post. Thanks for pointing me to the MCVE page.
Answer: It's not a good idea to load Maps JavaScript API twice. I would suggest removing the load of Maps JavaScript API from your popup page and using window.parent.google.maps.Polyline in your code
<!DOCTYPE html>

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

        <title>GMaps</title>

        Draw Polyline

This approach worked for me.
Comment: Thanks, solved my issue.  I wanted to upvote but unfortunately I haven't got enough reputation.


When should pdf files be tracked in a Git repository and when not

Question: I am developing a LateX package (http://www.openlilylib.org/lilyglyphs) which contains a number of small PDF files. Currently there are only a few dozens of them but as the package and its user base grows there will probably hundreds of them (but unlikely more than 1000).
The PDFs are typically only a few KB in size, but I don't know whether to track them in the Git repository. The files are subject to change at any time, but probably not too often.
Usually one is told not to track binary files which can't be diffed, but I also have read that this doesn't really matter with smaller files and a smaller overall volume. I think in the end the PDFs will sum up to not more than a few MB in total.
The package will be available as a download or through the Git repository which I prefer because using the package quite naturally leads to contributing ...
Currently when cloning the Git repository one has to rebuild the pdfs using Python and the LilyPond notation software so the stakes are rather high - which is why I would like to have the pdfs directly in the repo.
Any thoughts?

EDIT in response to answers/comments:
The pdf files are generated from the sources in the repository, which is why I'm reluctant to track them in Git.
But:

The pdfs are necessary to use the package so the user needs to have them
To generate the pdfs one needs Python as well as LilyPond, and both of them are not necessary to use the package. So I feel it is a too big burden to require someone to install two programs just to install my package.
I don't see a problem requiring someone who decides to clone a Git repo to run an install script, but the software dependencies are maybe too high?
Currently generating the pdfs finishes in reasonable time because there are only a few dozens. But with a growing number of files this time could become inacceptable.

The pdf files change when they are updated/corrected. This won't happen often, and I think this is covered by tracking the source code. But the pdfs will also change whenever there is  a new version of LilyPond available, which may be every two to four weeks. So while the source remains the same the pdfs will change regularely - which is a clear indicator against tracking them with Git.
On the other hand we are talking about (possibly) a few hundred files of a few KB each, so I don't know if it's worth bothering about the issue at all.
Comment: There's no clear answer to that.
Comment: So the pdfs are generated by the source in the repository? Usually you wouldn't want to version build output. It's not so much that they're binary as there are now 2 competing sources of truth in the same repository.
Comment: The pdfs are generated by the repo's source. That's why I'm reluctant to track them. See my edited question for details.
Answer: If the documents don't change, there is no reason to track their changes in git. No revisions, no need for revision control.
But if they do change over time, and someone may need to consult the old document versions for any reason, consider these questions:

Is it impossible or impractical to recreate the old versions of the documents?
Is there any underlying data outside of version control that has changed, or is it still in the same state?
Is the data in the documents tied to source code releases?

If the answers to these questions are yes, then they may be good candidates for version control under git.
Comment: Hm, difficult: The files change over time. But if someone _should_ need older versions he can recreate them from the sources. More details in my edited question.
Answer: The question is: do you want to use git for source code management/tracking/syncing exclusively or do you want to use it for distribution as well? For smallish projects it simplifies things to do it that way, for big projects it bloats the repo.
Comment: i do not think the impact will be too bad. but the good thing about git is, you can easily test it on a throwaway clone how long it takes to add all the files, clone the repo and check them out. i have the feeling that it will be fast.
Comment: I want to use it for distribution as well (although there also will be 'binary' releases), because that's the way to contribute.
I think the project is 'smallish' but I'm still not sure how much impact it would have tracking the pdfs too.
Answer: I know this is an old post but I found it whilst searching so other people might as well.  Here are some options I found
As it has been pointed out, a lot will depend on whether these source files will change over time.
One option you have if they don't change (or change infrequently) would be to keep a copy of them on a server you control or on a Cloud storage option and make your install script download them rather than produce them.
This would probably depend on the user having wget or curl installed but most people do and if they don't, you could always prompt the user to download them manually.
If the PDFs do change with the source frequently, you could look at GIT LFS.  I have never used it myself but have seen it used.


How to store access token and pass to next api call in javascript fetch

Question: I was just wondering if someone could help me figure this out.  My code to get the access token is:
    const inputBody = 'client_id=00000000-0000-0000-0000-000000000001&secret=mySecretPassword';
    const headers = {
      'Content-Type':'application/x-www-form-urlencoded',
    };

    fetch('https://api.replicastudios.com/auth',
    {
      method: 'POST',
      body: inputBody,
      headers: headers
    })
     .then(function(res) {
      return res.json();
    }).then(function(body) {
     console.log(body);
    });

I then need to include the access token received from the first call in order to insert it below.
    const headers = {
    'Authorization':'Bearer {token}'
    };

    fetch('https://api.replicastudios.com/voice',
    {
      method: 'GET',

      headers: headers
        })
    .then(function(res) {
       return res.json();
   }).then(function(body) {
      console.log(body);
    });

What is the best way to save the access token and insert it into the second request?
Comment: suggest the proper tag is `fetch-api`
Comment: Thank you.  I edited the question and corrected the tag.
Answer: Please, and one more time, please don't store users security tokens in session storage, local storage, cookies (by yourself, let browser do it securely for you), etc.
Browsers have pretty awesome way of handling those security sensitive stuff, and those ways are preventing session hijacking through XSS and bunch of other stuff.
Proper way of doing things:
On the frontend you call your login (or in your case) auth route, and from the backend instead of sending your security token in body you need to set it in the secure cookie. One of the common ways to do it with Node+Express is like this:
 res.status(200)
    .cookie('auth_cookie', token, { httpOnly: true, maxAge: 86400 * 1000, sameSite: 'none', secure: true})
    .json({ success: true, message });

This was one example of it, you should learn what all those arguments do here: https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector/Cookies
And on the last part, you dont need to manually include those cookies with each other request after that, if you are using Axios you can just put { withCredentials: true } and it's gonna automatically include those secured tokens in the cookie part of your request. There is a good thread already on that here: Make Axios send cookies in its requests automatically
I understand that this can seem as much work but it will make web safe(er) and it promotes good practices.
Comment: Based on the context of the question, OP doesn't have access to the backend as it's a third party API so he/she is not able to send response cookies
Answer: If your code is in a browser which it seems like it is, you could save the access token to session storage for use in future calls. When the tab is closed, session storage will be cleared.
    const inputBody = 'client_id=00000000-0000-0000-0000-000000000001&secret=mySecretPassword';
const headers = {
  'Content-Type':'application/x-www-form-urlencoded',
};

fetch('https://api.replicastudios.com/auth',
{
  method: 'POST',
  body: inputBody,
  headers: headers
})
 .then(function(res) {
  return res.json();
}).then(function(body) {
 console.log(body);
 // NEW CODE
 // body.access_token is my guess, you might have to change this
 // based on the response
 window.sessionStorage.setItem('access_token', body.access_token)
});

Then you can get the access token using:
window.sessionStorage.getItem('access_token')

Comment: People, don't do this. This is security disaster waiting to happen.
Comment: Thank you all for your answers.  I have a better idea of how it should be done correctly.  Thank you.


Ubuntu/Wayland: Turn off screen via FN keys

Question: On my old laptop, I was able to turn off the screen by pressing FN + BRIGHTNESS DOWN until it reached 0 when I was running Linux Mint. Now, I want to replicate this on Ubuntu 20.04 with Wayland, but I cannot replicate the methods shown in other posts like this and this.

xset dpms force off doesn't work on Wayland,
xrandr doesn't actually turn off the monitor backlight,
Setting screen saver dbus-send shows no effect and also doesn't turn off the screen,
echo 0 > /sys/class/backlight/intel_backlight/brightness works, but is hard to undo and might not work when switching to the NVidia card - and it requires root,
Locking the screen with CTRL + L also turns off the screen immediately, but it often turns itself on just a few minutes later for no obvious reason.

When I use the FN keys that control the brightness, which method is used to set the screen brightness? Wouldn't it be possible to simply modify the key binding in a way that it reduces the brightness to 0 instead of 15 (in my case)? And is it known why the screen turns itself on after a short time after being locked?
Answer: You probably could implement a hack using the tool light, which is available in the standard Ubuntu software repositories. After installing, see "man light" to see how it works. For example, the command light -A 5 will increase brightness with 5 units.
light allows to set a minimum brightness - in your case you would set that to 0.
You could then bind the appropriate commands to your Fn+BrightnessUp/Down keys. For that, disable the default assignment first with the commands:
gsettings set org.gnome.settings-daemon.plugins.media-keys screen-brightness-up-static "['']"
gsettings set org.gnome.settings-daemon.plugins.media-keys screen-brightness-down-static "['']"

Then assign the commands to these keys using "Settings" - "Keyboard Shortcuts", "Custom Shortcuts".
To revert to the default behaviour, change set in the above commands to reset and leave out the last argument.
Comment: `light` apparently doesn't work on my device. Does it work with Wayland? I tried `light -s sysfs/backlight/intel_backlight -A 5` and `light -G` remains at 1.00.
Comment: You will of course need a tool that works on your specific system. It is perhaps wise to edit your question and add information about your hardware, specifically the graphics card.


how to create a hash table using the given classes

Question: I am currently finishing up my computer science assignment and am having trouble with the last bit and am looking for some advice.
Using the following classes:
class CounterLinkedList:
    __n_comparisons__ = 0

    def __init__(self, head=None):
        self.head = head
        self.__n_accesses__ = 0

    def __repr__(self):
        node = self.head
        string = str(node)
        while node.next_node:
            string += " -> " + str(node.next_node)
            node = node.next_node
        string = "[" + string + "]"
        return string

class MyString:
    '''A wrapped string that counts comparisons of itself
   against strings and delegates all other operations to the
   string itself.'''
    def __init__(self, i):
        self.i = i

    def __repr__(self):
        return repr(self.i)

    def __getattr__(self, attr):
        '''All other behaviours use self.i'''
        return self.i.__getattr__(attr)

class CounterNode:
    def __init__(self, word, count=1):
        self.word = MyString(word)
        self.count = count
        self.next_node = None

    def __repr__(self):
        return str(self.word) + ": " + str(self.count)

def _c_mul(a, b):
    """Substitute for c multiply function"""
    return ((int(a) * int(b)) & 0xFFFFFFFF)

def nice_hash(input_string):
    """Takes a string name and returns a hash for the string. This hash value
    will be os independent, unlike the default Python hash function."""
    if input_string is None:
        return 0  # empty
    value = ord(input_string[0]) << 7
    for char in input_string:
        value = _c_mul(1000003, value) ^ ord(char)
    value = value ^ len(input_string)
    if value == -1:
        value = -2
    return value

def hash_word(item, slots):
    return nice_hash(item) % slots

I am required to implement a hash table without using dictionaries and each time you take a word from the list of words you will check if it is in a hash table and increment its count if it is. If it is not then insert its count into the table, using chaining if there is already an object in the hash table slot. Chaining is done with a linked list.
The output of the code if I used the input:
slots = 3
counts, comparisons = word_counter_hash(['list', 'with', 'no', 'repeat', 'words'], slots)
for i in range(slots):
    print(str(i) + ": " + str(counts[i]))
print(comparisons)

Should output:
0: ['words': 1 -> 'no': 1 -> 'list': 1]
1: ['repeat': 1]
2: ['with': 1]
3

My code so far is:
'''test'''
from classes_2 import CounterNode, CounterLinkedList, hash_word

def word_counter_hash(words_list, slots):
    """test"""
    hash_list = [None]*slots
    num_comparisons = 0
    for new_word in words_list:
        if len(words_list) >= 0:
            n = CounterNode(new_word, 1)
            new_list = CounterLinkedList(n)
            hash_value = hash_word(new_word, slots)
            if hash_list[hash_value] == None:
                del hash_list[hash_value]
                hash_list.insert(hash_value, new_list)
            else:
                first_node = new_list.head
                first_node.next_node = CounterNode(words_list[hash_value], 1)
                first_node = (new_list)
                del hash_list[hash_value]
                hash_list.insert(hash_value, new_list)

    return hash_list, num_comparisons

however my output is not the same as it was above:
0: ['words': 1 -> 'list': 1]
1: ['repeat': 1]
2: ['with': 1]
0

I am looking for any advice as to what I could do to get on the right track, and any help would be appreciated.
Comment: This code is a bit long. Is it possible to pare it down a bit or is it all needed?
Comment: @Veedrac, unfortunately the huge Classes code is needed because it puts in the restrictions for the assignment, as well as basis on which we formulate an answer
Comment: It might be needed for the *assignment* but right now we only need to reproduce the bug. Removing things that aren't relevant to that will help.
Comment: @Veedrac sorry about that, I've tried to cut it down as much as I can
Answer: The first thing to note is:
nice_hash("list") % 3
#>>> 0

nice_hash("no") % 3
#>>> 0

nice_hash("words") % 3
#>>> 0

These will all collide on the first box. So let's try and remove all but the first box:
slots = 1
counts, comparisons = word_counter_hash(['a', 'b', 'c'], slots)
print(counts[0])
#>>> ['c': 1 -> 'a': 1]

This reproduces the problem. Good. Now we can replace hash_word:
def hash_word(item, slots):
    return 0

It doesn't matter that it doesn't work well; it reproduces the problem. In fact, we no longer need the function at all, we can just hardcode a hash value of 0.
Bringing these simplifications through, we get:
def word_counter_hash(words_list):
    hash_list = [None]

    for new_word in words_list:
        new_list = CounterLinkedList(CounterNode(new_word, 1))

        if hash_list[0] == None:
            del hash_list[0]
            hash_list.insert(0, new_list)

        else:
            first_node = new_list.head
            first_node.next_node = CounterNode(words_list[0], 1)
            first_node = (new_list)
            del hash_list[0]
            hash_list.insert(0, new_list)

    return hash_list

counts = word_counter_hash(['a', 'b', 'c'])
print(counts[0])
#>>> ['c': 1 -> 'a': 1]

Note that:
del hash_list[idx]
hash_list.insert(idx, X)

Is just a really slow way of doing
hash_list[idx] = X

so we have
def word_counter_hash(words_list):
    hash_list = [None]

    for new_word in words_list:
        new_list = CounterLinkedList(CounterNode(new_word, 1))

        if hash_list[0] == None:
            hash_list[0] = new_list

        else:
            first_node = new_list.head
            first_node.next_node = CounterNode(words_list[0], 1)
            first_node = (new_list)
            hash_list[0] = new_list

    return hash_list

counts = word_counter_hash(['a', 'b', 'c'])
print(counts[0])
#>>> ['c': 1 -> 'a': 1]

This line does nothing:
first_node = (new_list)

and since we never really use fist_node we can rewrite it like:
def word_counter_hash(words_list):
    hash_list = [None]

    for new_word in words_list:
        new_list = CounterLinkedList(CounterNode(new_word, 1))

        if hash_list[0] == None:
            hash_list[0] = new_list

        else:
            new_list.head.next_node = CounterNode(words_list[0], 1)
            hash_list[0] = new_list

    return hash_list

counts = word_counter_hash(['a', 'b', 'c'])
print(counts[0])
#>>> ['c': 1 -> 'a': 1]

Then we can deduplicate the hash_list[0] = new_list line:
def word_counter_hash(words_list):
    hash_list = [None]

    for new_word in words_list:
        new_list = CounterLinkedList(CounterNode(new_word, 1))

        if hash_list[0] != None:
            new_list.head.next_node = CounterNode(words_list[0], 1)

        hash_list[0] = new_list

    return hash_list

counts = word_counter_hash(['a', 'b', 'c'])
print(counts[0])
#>>> ['c': 1 -> 'a': 1]

So we:

Make a new list
If there is already a list, set the second element of new_list to words_list[0] (originally words_list[hash_value])
Set the new list

Now, that second one looks wrong.
So instead you should do something like:

If the node is None, make a new list
If the node is not None, traverse it

If you find something already there, increment its number
If you do not, add the current one as a new node to the end

Like this:
def word_counter_hash(words_list):
    hash_list = [None]

    for new_word in words_list:
        if hash_list[0] == None:
            hash_list[0] = CounterLinkedList(CounterNode(new_word, 1))

        else:
            node = hash_list[0].head

            while True:
                if node.word == new_word:
                    node.count += 1
                    break

                elif not node.next_node:
                    node.next_node = CounterNode(new_word, 1)
                    break

                node = node.next_node

    return hash_list

counts = word_counter_hash(['a', 'b', 'c', 'c', 'a'])
print(counts[0])
#>>> ['a': 2 -> 'b': 1 -> 'c': 2]

I've tried to keep it fairly unimaginitively simple.
I leave it to you to change hash_list[0] to hash_list[hash_value].
Comment: Thank you very much for this very detailed answer! It makes things much easier to understand