Get Authorization Bearer from Webbrowser to WebRequest

Question: I login with Webbrowser control on a website.
Webbrowser contains Authorization:

Bearer Vw1Ta8yPpKV6N2bUOdyy....

in header.
Could I somehow get its information from control? I checked cookie with "GetCookieContainer()" but couldn't find any Authorization fields.
Comment: Technically the web browser doesn't have headers, its requests do. That then leads to the question: does the site store this information in local storage, session storage, or, and I'm assuming it's a SPA site, does it just store it in memory?
Comment: @john When I open this site on IE in debug mode. I see than Authorization stored in local storage, may be webbrowser use the same behavior, but I don't know how it is can help me.
Answer: I found the next solution, make injection on javascript into a page.
After this you can to use _Bearer_Access_token  to make any request to you website.
<code>    string _Bearer_Access_token = "";
    HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
    HtmlElement scriptEl_ = webBrowser1.Document.CreateElement("script");
    IHTMLScriptElement element = (IHTMLScriptElement)scriptEl_.DomElement;
    element.text = @"function GetBearer()
                    {

                        var parent = document.getElementsByTagName('head')[0];
                        var aTag = document.createElement('a');
                        for ( var i = 0, len = localStorage.length; i < len; ++i ) {
                          aTag.innerHTML += localStorage.getItem( localStorage.key( i ) );
                        }
                        parent.appendChild(aTag);

                    }";

    head.AppendChild(scriptEl_);
    webBrowser1.Document.InvokeScript("GetBearer");

    HtmlElement head2 = webBrowser1.Document.GetElementsByTagName("head")[0];
    HtmlElement scriptEl2_ = webBrowser1.Document.GetElementsByTagName("a")[0];

    if (scriptEl2_.InnerText.IndexOf('{') > 0)
    {
        string LocalVariables_ = scriptEl2_.InnerText.Substring(scriptEl2_.InnerText.IndexOf('{'));
        LocalVariables_ = LocalVariables_.Replace("}{", "}@@@BTWOBJ@@@{");
        string[] ObjectArr_ = LocalVariables_.Split(new string[] { "@@@BTWOBJ@@@" }, StringSplitOptions.RemoveEmptyEntries);

        for (int i_ = 0; i_ < ObjectArr_.Length; i_++)
        {
            JToken token_ = JObject.Parse(ObjectArr_[i_]);
            token_ = token_.SelectToken("access_token");
            if (token_ != null)
            {
                _Bearer_Access_token = token_.Value<string>();
                if (_Bearer_Access_token.Length > 0)
                {
                    break;
                }
            }
        }
    }
</code>


AutoEncoder Resulting In (61,61,3) instead of (64,64,3)

Question: I am trying to build a convolutional autoencoder. Here is my architecture.

def MainEncoder():
    inp = Input(shape=(64,64,3))
    x = Conv2D(256,2)(inp)
    x = MaxPool2D()(x)
    x = Conv2D(128,2)(x)
    x = Flatten()(x)
    encoded = Dense(100,activation="relu")(x)

    encoder= Model(inp,encoded)
    return encoder

def Decoder():
    enc = Input(shape=(100,))
    y = Dense(128)(enc)
    y = Dense(768)(y)
    y= Reshape((16,16,3))(y)
    y= Conv2DTranspose(128,(1,1),(2,2),padding='same')(y)
    y= Conv2DTranspose(128,(1,1),(2,2),padding='same')(y)
    decoded1 = Conv2D(3,1,padding="same")(y)
    decoder = Model(enc,decoded1)
    return decoder
encoder= MainEncoder()

decoderA = Decoder()
decoderB = Decoder()

print(encoder.summary())
print(decoderA.summary())
print(decoderB.summary())
input()
#decoder=  Model(encoded_input,decoded1)
#print(decoder.summary())
Inp = Input(shape=(64,64,3))
Inp2 = Input(shape=(64,64,3))
AutoEncoder1 = Model(Inp,decoderA(encoder(Inp)))
AutoEncoder2 = Model(Inp2,decoderB(encoder(Inp2)))
AutoEncoder1.summary()
AutoEncoder2.summary()
print(ot[0].shape)
input()
AutoEncoder1.compile(optimizer='adam',loss='mse')
AutoEncoder2.compile(optimizer='adam',loss='mse')
AutoEncoder1.fit(ot,ot,16,100)
AutoEncoder2.fit(kt,kt,16,100)
encoder.save(path+'encoder')
decoderA.save(path+'obama')
decoderB.save(path+'kimmel')

The outputs of all models and shapes of all images are 64,64,3 according to the summary. However whenever I try to add the accuracy metric or just test out the auto encoder it always results in and image of size 61,61,3. I don't really know how to fix this. Any help would be appreciated.
Here is the test code

from numpy.core.shape_base import block
import tensorflow as tf

from tensorflow.keras.layers import *
from tensorflow.keras.models import *
import pickle
import numpy as np
import matplotlib.pyplot as plt
path = 'youtube_stuff2/'
ot = pickle.load(open(path+'oi.pickle','rb'))
kt = pickle.load(open(path+'ki.pickle','rb'))
ot = ot/255.0
kt = kt/255.0
encoder = load_model(path+'encoder')
obama = load_model(path+"obama")
kimmel = load_model(path+"kimmel")
print(ot[0].shape)
ott = np.array([ot[0]])
print(ott.shape)
thing = encoder.predict(ott)
image = obama.predict(thing)
print(image.shape)
#plt.imshow(ott[0])
plt.imshow(image[0])
plt.show()

The variable image has shape (61,61,3)
Comment: Can you show us the code you use to pass input into your... thing, and where you receive the output?
Comment: @CaptainTrojan No Problem. I edited the code. Hopefully this is what you asked for.
Comment: Is `ott.shape == (...,  64, 64, 3)`? I cannot reproduce the issue.
Answer: When using Convolution, you need to be aware that pixels on the edge of the image will not be kept.
If you want them to be of similar shapes, you can add the keyword "padding" and set its value to "same" when defining your Conv2D.
Here's what it's probably going to look like :
def MainEncoder():
    inp = Input(shape=(64,64,3))
    x = Conv2D(256,2, padding="same")(inp)
    x = MaxPool2D()(x)
    x = Conv2D(128,2, padding="same")(x)
    x = Flatten()(x)
    encoded = Dense(100,activation="relu")(x)

    encoder= Model(inp,encoded)
    return encoder

This padding will create what is effectively a black border on the outside of your image when the convolution is going through.
I hope I was useful
Comment: Try running your code again after clearing out the files you wrote to. I was able to run it on a np.zeros((1,64,64,3)) and the shape of the output was correctly 1,64,64,3. `AutoEncoder1(np.zeros((1,64,64,3)))`
Comment: @Yaoshiang. Thanks. I was using .predict() instead of calling it like that.


How to turn View into Bitmap including the view behind it?

Question: I have a layout which has an ImageView and then a LinearLayout which contains TextViews on top of that, so what this looks like on the screen is an image with text on top of it.
Layout is like this.
<RelativeLayout>
 <ImageView>
    <LinearLayout>

    </LinearLayout>
 </ImageView>
</RelativeLayout>

I am able to get the Linear layout as a Bitmap using this code, but the bitmap does not contain the background image, it is just black background. I want it to be the layout along with the image that is behind it.
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.myLinearLayout);

Bitmap imageToShare = loadBitmapFromView(linearLayout );

public static Bitmap loadBitmapFromView(View view) {
    Bitmap b = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    view.layout(0, 0, view.getWidth(), view.getHeight());
    view.draw(c);
    return b;
}

Answer: Well I seem to have worked around the issue by putting another Relative layout which contains both the ImageView and LinearLayout in it. Then I generate the bitmap from this RelativeLayout instead of the LinearLayout.


Advice to un-stick a bathroom sink waste plug which is stuck down please

Question: My bathroom sink (handbasin) has a pop-up waste, similar to the one shown here:
However it has become STUCK in the down position, totally blocking the sink. A picture is here:
This means I can not use my bathroom sink. There is nowhere to grip it.
Short of drilling it out - what advice would you suggest?
Comment: Should be able to undo the whole drain from below, no drilling necessary.
Comment: A bit of confusion here about terminology (which will determine which answer is correct). When it was working properly, what would you actually do to open/close the drain?
Comment: maybe you are not pressing it down hard enough to release it... otherwise, try using a small suction cup to pull it up or to unscrew it ... small suction cups are used for hanging decorations on glass
Answer: I would disassemble the trap below the drain, and if necessary remove the tailpiece, and push it up with something like a screwdriver
Answer: I have had just that happen to me. This is what I did: Spray around the edges with WD-40. Let it sit for 5-10 min. then press it hard and release multiple times. When it finally pops up unscrew the pop-up from the sink drain and WD-40 the spring and shaft. When you screw it back in don't screw it down so far that it is recessed as far as it is now.
If none of that works you have no choice but to dissemble the drain.
Comment: If I recollect correctly, WD-40 will eventually evaporate away. A follow-up oil or grease suitable for a drain applied to the moving parts might be good.
Answer: Thank you to everyone who answered this!
I ultimately solved it myself with the help of the following video:
https://youtu.be/ZWlq_fWRrzI
I used a rubber glove to give me enough traction on the thumb to unscrew the cap - which was then raised flush with the surrounding metal.
I then used dental floss to slowly and carefully catch the waste cap - which I was then able to lift out.
The brass pin below (onto which the cap screwed) was stuck down tight, and needed some WD40 and a pair of pliers to fix.
Anyway - thank you to all the suggestions here :)
Answer: It worked, I sprayed WD40 on it and waited 10 minutes.Then I used a large plastic nail and gently tapped it with a hammer then pressed firmly and the plug came up. I then unscrewed the plug and gave the thread a brush with a nail brush and sprayed with WD40. I lost my husband a few years ago and try to fix problems myself if possible so thank you for your guidance
Comment: Please don't add "thank you" as an answer. Once you have sufficient [reputation](https://diy.stackexchange.com/help/whats-reputation), you will be able to [vote up questions and answers](https://diy.stackexchange.com/help/privileges/vote-up) that you found helpful. - [From Review](/review/late-answers/162849)
Comment: That answer has already been given.
Answer: There are silicone suction cups that would fit on this drain that can allow a very stong upward pull. Stick this suction cup onto the plug, push down forcefully and pull up forcefully.
I would keep one of these handy if you have this type of drain plug. A couple of years ago I installed one of these pop-up drain plugs in a bathroom lavatory in my house, but we have have no trouble with it. I don't have a silicone suction cup right now, but I now have that on my list.


Determining linear independence in $\mathbb{R}^3$

Question: Let $\{\xi_k\}_{k=1}^4$ be a set of vectors in $\mathbb{R}^3$. If $\{\xi_1, \xi_2\}$ and $\{\xi_2, \xi_3, \xi_4\}$ are independent sets, and $\xi_1$ belongs to the span of $\{\xi_2, \xi_4\}$. Show that $\{\xi_k\}_{k=1}^3$ is linearly independent.
Clearly, $\xi_1 = a_1\xi_2 + a_2\xi_4$ where $a_1\neq0$ due to the fact that $\xi_1$ and $\xi_2$ are linearly independent. Hence, $\xi_2 = a_1^{-1}\xi_1-\frac{a_2}{a_1}\xi_4$... How to proceed with the formalization? Because, it is quite clear that $\xi_1$ is linearly independent of $\xi_3$ and we know that $\{\xi_1, \xi_2\}$ is independent as well, so it follows that $\{\xi_k\}_{k=1}^3$ is linearly independent set. Is it rigorous enough?
Thank you!
Comment: I don't think your argument is very clear.  Have you tried using the definition of linear independence?
Answer: Suppose that
$$
\lambda_1\xi_1+\lambda_2\xi_2+\lambda_3\xi_3=0\tag{1}
$$
Writing $\xi_1=\alpha_2\xi_2+\alpha_4\xi_4$ then gives
$$
\lambda_1(\alpha_2\xi_2+\alpha_4\xi_4)+\lambda_2\xi_2+\lambda_3\xi_3=0
$$
Now, rearrange this equation to obtain
$$
(\lambda_1\alpha_2+\lambda_2)\xi_2+\lambda_3\xi_3+\lambda_1\alpha_4\xi_4=0\tag{2}
$$
Equation (2) and the linear independence of $\{\xi_2,\xi_3,\xi_4\}$ imply that $\lambda_3=0$. Equation (1) then implies that
$$
\lambda_1\xi_1+\lambda_2\xi_2=0\tag{3}
$$
Equation (3) and the linear independence of $\{\xi_1,\xi_2\}$ imply that $\lambda_1=\lambda_2=0$.
Hence $\{\xi_1,\xi_2,\xi_3\}$ is linearly independent.
Note that this argument avoids "dividing" by unknown scalars!
Answer:
If $\{v_1,\dots,v_k\}$ is linearly independent in a vector space $V$ and $v\in V$, then $\{v_1,\dots,v_k,v\}$ is linearly independent if and only if $v$ doesn't belong to the span of $\{v_1,\dots,v_k\}$.

One direction is clear: if $v$ belongs to the span of $\{v_1,\dots,v_k\}$, the set $\{v_1,\dots,v_k,v\}$ is linearly dependent. Suppose $v$ doesn't belong to the span of $\{v_1,\dots,v_k\}$ and that
$$
\alpha_1v_1+\dots+\alpha_kv_k+\beta v=0
$$
Then $\beta=0$, otherwise $v$ would be a linear combination of $v_1,\dots,v_k$, against the hypothesis. Therefore $\beta=0$ and, by the linear independence of $\{v_1,\dots,v_k\}$, also $\alpha_1=\dots=\alpha_k=0$.

Thus you need to prove $\xi_3$ doesn't belong to the span of $\{\xi_1,\xi_2\}$. Suppose
$$
\xi_3=a\xi_1+b\xi_2
$$
Since you can write $\xi_1=c\xi_2+d\xi_4$, you get
$$
\xi_3=(ac+b)\xi_2+ad\xi_4
$$
Well, this is not possible, why?
Answer: hint
Start with a linear combination of vectors $1,2,3$ and set it equal to $0$ (vector). Now write vector $1$ as a linear combination of vectors $2$ and $4$. This gives you a linear combination of vectors $2,3$ and $4$ equal to the zero vector. Now use the independence of $2,3,4$ to find the coefficients.


ntpd vs ntpdate: pros and cons

Question: In order to keep the time accurate on a Ubuntu system one can either:

Run the ntpd (network time protocol daemon) which will run all the time and continuously adjust the system time when clocks drift.  or alternatively:
Call ntpdate periodically (e.g. from cron)

Questions:

What are the pros and cons of each of these two methods?
Which different scenarios call for picking one over the other?
Answer: ntpdate is deprecated as of September 2012; apparently ntpd now has the ability to do one-time updates if needed, and ntpdate is based on "long-neglected" ntpd code. (News to me, since my system has ntpdate but not ntpd! I'll be fixing that presently; thanks for asking this question.)
As for the difference between continuous versus periodic updates, I think the trade-offs there are what you would expect; continuous adjustments maintain better accuracy over time, which can be important for databases and MailDir (see same link). But of course this would require slightly more network traffic (presumably negligible for exchanging simple timestamps) as well as an always-online network connection, slight consumption of RAM and CPU, etc. But all these downsides are tiny in a modern computing environment; overall I doubt there are good reasons to substitute cron for ntpd.
Comment: Thanks so much for the answer. I had no idea that ntpdate has been deprecated.  It has been working well for me for years.
Answer: As far as I understand the Linux System Administrators Guides NTP chapter, "continuous updates" doesn't mean that ntpd constantly queries its servers (like once a second), but that the time corrections do not introduce discontinuities.
Instead of just setting the correct time, ntpd will run your computers clock slightly slower or faster until it reaches the correct time (assuming the error is not too big). This avoids problems with software running havoc because of gaps in time or negative durations -- most programmers won't expect a process to finish before it started and thereby giving a negative duration...
Furthermore, the manual states that ntpd also learns and compensates the drift of your computers clock (at least the constant part).
The Network Time Protocol Project has a nice FAQ (http://www.ntp.org/ntpfaq/) explaining NTP and how it keeps the time.

ntpd vs ntpdate: pros and cons


How can I run a cursor tree in Eiffel?

Question: I need a cursor tree and I found CURSOR_TREE and RECURSIVE_CURSOR_TREE classes in EiffelStudio but they are deferred and I don't know how to implement them. Isn'it strange?
Answer: Source code of some classes implementing CURSOR_TREE is available in your installation in .../library/base/elks/structures/cursor_tree. Unfortunately, the classes (as they were implemented) are incompatible with void safety. You can try copying the following classes to your project and compile:
library/base/elks/structures/cursor_tree/compact_cursor_tree.e
library/base/elks/structures/cursor_tree/linked_cursor_tree.e
library/base/elks/structures/cursor_tree/two_way_cursor_tree.e
library/base/elks/structures/cursors/compact_tree_cursor.e
library/base/elks/structures/cursors/linked_cursor_tree_cursor.e
library/base/elks/structures/cursors/two_way_cursor_tree_cursor.e

The process would involve several changes:

your project void safety capability should be set to none (and the project should be recompiled from scratch);
depending on the version of the compiler you may need to fix some validity errors in the library classes (e.g., remove put_right from redefine clauses);
implementations of the feature new_cursor have to be provided, a quick-and-dirty fix could be a dummy stub:
new_cursor: ITERATION_CURSOR [G]
    do
        Result := (create {SPECIAL [G]}.make_empty (0)).new_cursor
    end

After that you should be able to use effective classes COMPACT_CURSOR_TREE, LINKED_CURSOR_TREE and TWO_WAY_CURSOR_TREE.
I would suggest collaborating with Eiffel Software if you plan to use the classes in a void-safe project because the implementation and the interface requires substantial changes to make the code void-safe.
Comment: I will work on them trying to get something useful, but this lack is very strange. ps - RECURSIVE_CURSOR_TREE is deferred too.
Comment: @B3nTek Indeed, I meant `linked_cursor_tree.e`. Thanks for the correction.
Comment: @B3nTek I would start with `LINKED_CURSOR_TREE` version to get the feeling what's wrong with the implementation and how it could be fixed. As soon as you have some ideas about that, constructive collaboration with Eiffel Software should be possible.

How can I run a cursor tree in Eiffel?


Wiring two motion sensors from separate locations to control a bank of lights in between both?

Question: I want to turn on a bank of lights running along a deck between two entryways. The power switch is inside one doorway and feeds the circuit to the outside.  How do I wire the two motion sensors so either will trigger the lights to come on?
Answer: Wire nut together the motion sensors so that they are in parallel and will then so provide a path to the light if either is switched on.
Here is a wiring diagram (minus the grounds that must be pulled along):

Blacks are hot, red are travelers, and the gray are your neutrals.
Answer: They will have to be wired in parallel so either switch can turn on the lights.
The lights will stay on as long as the switch with the longest delay if they are both triggered.
A layout diagram would be helpful to determine how to wire it.
Comment: This doesn't answer the question, and feels more like a comment.
Comment: The first sentence is the technical answer to the OPs question. The rest is advisory.


balancing stats for equality

Question: Not sure if this is the right forum, please comment on the correct one. OK:
I am creating a game where the user inputs stats and attack values, and I want the ai to match its ability (so they are about equal) for example,
  "Health":  1000,
  "Shield blockage percent":  90%
MOVE#1
      "Damage":   100,
      "Accuracy": 100%
MOVE#2
      "Damage":   1000,
      "Accuracy": 10%

So if you use the shield, it will block 50 percent of the foe's damage
Accuracy for MOVE#2, only 1/10 will hit. How do I calculate an equal foe, just replicate the stats? Any way to do it without replicating the stats?
MORE NOTES
The optimal game would last 7 moves and would be very close
Shielding counts as a move, and is a constant 90% for all people.
An optimal game is one that would be won or lost by 1-2 turns.
Comment: What tags as well? sorry!!!
Comment: Could you describe in more detail how the game works? Is using the shield a move? And you have to be clear about what you mean by equal foe. Do they play randomly? Do they play well as if the know their opponent's moves from the start? Do they play well but have to observe the opponent's moves? Do you have a metric in mind for "playing well"? Etc.
Answer: The first thing you need to do is figure out a constant dpt, or damage per turn. calculated by doing damage/(accuracy as a decimal). Each person would have 3 moves that have the same dpt:
high risk | EG 1000 dmg, 10% acc.
med risk | EG 200 dmg, 50% acc.
low risk | EG 100 dmg, 100% acc.

dpt = 100 (must be constant)
computer stats are dpt * 7 = health and health/7 = dpt
health = 700
dpt = 143 [1000/7(rounded up)]

calculate moves,
high risk | EG 1430 dmg, 10% acc.
med risk | EG 286 dmg, 50% acc.
low risk | EG 143 dmg, 100% acc.

complete

balancing stats for equality


JavaScript Standard Library for V8

Question: In my application, I allow users to write plugins using JavaScript. I embed V8 for that purpose. The problem is that developers can't use things like HTTP, Sockets, Streams, Timers, Threading, Crypotography, Unit tests, et cetra.
I searched Stack Overflow and I found node.js. The problem with it is that you can actually create HTTP servers, and start processes and more things that I do not want to allow. In addition, node.js has its own environment (<code>./node script.js</code>) and you can't embed it. And it doesn't support Windows - I need it to be fully cross platform. If those problems can be solved, it will be awesome :) But I'm open to other frameworks too.
Any ideas?
Thank you!
Answer: There is CommonJS, which defines a "standard" and a few implementations available of that standard - one of which is node.js.
But from what I can see, it's still fairly immature and there aren't many "complete" implementations.
Answer: In the end, I built my own library.
Comment: cool.. Any of that is open source? I am starting on similar project and would be great to look at that. Also is there any standard library docs for v8 available?

JavaScript Standard Library for V8


How to add bootstrap buttons column to DevExtreme DataGrid (Angular)?

Question: I want to add a bootstrap buttons to DataGrid. These buttons will act as download button for each row. I have the following codes for datagrid:
<dx-data-grid id="pmschedule-dataGrid" [hoverStateEnabled]="true" [dataSource]="ds"
            [showBorders]="true" [allowColumnResizing]="true" (onSelectionChanged)="onDataGridSelectionChanged($event)">
            <dxo-paging [pageSize]="50" [pageIndex]="0"></dxo-paging>
            <dxo-pager [showPageSizeSelector]="true" [allowedPageSizes]="[50, 100, 200]" [showNavigationButtons]="true"
                [showInfo]="true">
            </dxo-pager>
            <dxo-filter-row [visible]="true"></dxo-filter-row>
            <dxo-selection selectAllMode="page" [showCheckBoxesMode]="checkBoxesMode" mode="multiple"></dxo-selection>
             .
             .
             .
             .
            <dxi-column type="buttons" caption="Download Link">
                <button class="btn btn-primary">Download</button>
            </dxi-column>
        </dx-data-grid>

When I run the app, There is a column named Download Link but there are no buttons.
I studied documents from DevExtreme but I couldn't find any information to add a command column for downloading (Adding bootstrap buttons).
Is there any solution?
Answer: You will need to change code little bit. sharing you the docs link where they had rendered the image in each row similarly you have to write your button.
check this out.
https://js.devexpress.com/Demos/WidgetsGallery/Demo/DataGrid/ColumnTemplate/Angular/Light/
something on this line
<dx-data-grid
  id="gridContainer"
  [dataSource]="employees"
  keyExpr="ID"
  [showBorders]="true"
>
  <dxi-column
    dataField="Picture"
    [width]="100"
    [allowFiltering]="false"
    [allowSorting]="false"
    cellTemplate="cellTemplate"
  ></dxi-column>
  <dxi-column dataField="Prefix" [width]="70" caption="Title"></dxi-column>
  <dxi-column dataField="FirstName"></dxi-column>
  <dxi-column dataField="LastName"></dxi-column>
  <dxi-column dataField="Position"></dxi-column>
  <dxi-column dataField="BirthDate" dataType="date"></dxi-column>
  <dxi-column dataField="HireDate" dataType="date"></dxi-column>

    <button>
      my button
    </button>

</dx-data-grid>


Error while drawing a clock using turtle module

Question: My code:
import turtle
wn =turtle.Screen()
te=turtle.Turtle()
te.shape("turtle")
te.left(90)
for i in range(12):
  te.penup(100)
  te.right(30)
wn.mainloop()

The output: Type error occurred in terminal. Please help. I am beginner in Tkinter graphics.
Comment: `penup` takes no arguments.
Answer: Note that, penup does not take any arguments. So, I do not know what you are trying to do, but your code may be corrected as in the example below:
#!/usr/bin/python3
import turtle
wn=turtle.Screen()
te=turtle.Turtle()
te.shape("turtle")
te.penup()
te.setpos((0,250))
te.pendown()
te.right(-15)
for i in range(12):
  te.right(30)
  te.forward(100)
wn.mainloop()


How to Map Triggers For Run Away in Final Fantasy 7?

Question: I'm using a gamepad for FF7 on PC and no matter what I've tried, I can't map the triggers on my gamepad to Page Up and Page Down so I can run away! Any thoughts on how to remedy this?
Comment: Are you using any mapping software? Personally I find running a PSX game in ePSXe to be much better than playing its PC port precisely because i don't have to deal with ancient software's bugs.
Comment: Yeah, Xpadder should work.
Comment: I am not using any mapping software. I've seen people recommend Xpadder, worth a shot?
Comment: @kotekzot - There is a modern version of this port, though, and the PC version of FF7 is unique anyway in that it fixed a bunch of localization errors from the PSX version.
Comment: I also recommend XPadder. Its well worth the money and you should never have problems mapping controllers again.
Answer: Maybe you can use JoyToKey for solve this problem. This program is used for mapping the keys into joypad buttons.
Answer: FF7 PC has native gamepad support for PlayStation style controllers(DS1, PS pad, ETC.).  My sister has had very little trouble mapping several of these onto the game in fact it sees these automatically.  I haven't messed with the Xbox 360 controller for windows but I've had trouble mapping my dual shock clone onto TF2(Still don't have this right).
The main thing I've heard is the with the official drivers the triggers on a 360 controller don't seem to function.  You could try these and see if it makes a difference.  Also Xpadder works great with certain games...
Answer: If you have an xbox 360 controller that you are using, I have found this guide on Steam to be the best solution:
Xbox 360 Controller Fix
It does however require that you are using the English Steam version of FF7.
Comment: Please don't post just a link; if the link target disappears or is moved, your answer is useless. Please summarize the important parts.


Ubuntu 22.04.1 LTS - Not able to adjust brightness

Question: Since the update to Ubuntu 22.04.1 LTS I am not able to adjust the brightness of my screens anymore.

I was using the Brightness Controller before, but it doesn't work
anymore.

I have no brightness switch on the system menu

I already tried using xrandr:
xrandr | grep " connected" | cut -f1 -d " "

Gives me back:
XWAYLAND0 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 530mm x 300mm
XWAYLAND1 connected 1920x1080+1920+0 (normal left inverted right x axis y axis) 530mm x 300mm

And after that:
xrandr --output XWAYLAND0 --brightness 0.5
But there is no visible change at all.
Comment: To be clear: most OSes don't allow adjusting brightness except for laptops; regular monitors can have brightness adjusted using buttons. `xrandr` adjust brightness using a "hack" that adjusts gamma for all channels equally, which looks like a less-bright screen. The tool I linked above aims to replicate this, but only works when you don't already have gamma adjustments (like nightshift) running.
Comment: xrandr won't work because you're using Wayland. To confirm: you updated from 20.04? 20.04 defaulted to xorg for displays; 22.04 defaults to Wayland.
Comment: Yes right. There is no way to change brightness in wayland?
Comment: can you not change the brightness in the monitors themselves? or is one a laptop screen?
Comment: it's already almost on lowest level. and I use dual-boot so brightness controller was an easy way to adjust for ubuntu. I can manage it directly on the screen in the future. But I wonder why some basic option like this is not part of ubuntu anymore.
Comment: if you absolutely require this feature, you can switch back to xorg instead of wayland. Or look at [this xrandr replacement for wayland](https://github.com/maxwellainatchi/gnome-randr-rust/tree/adjust-brightness) which has an experimental branch that enables adjusting brightness
Comment: also look at this tool https://github.com/zb3/gnome-gamma-tool
Comment: My eyes are thanking you very much for your help. The gnome-gamma tool provides what I need. I will test it a bit and also have a look at the xrandr replacement.
Answer: Finally found a way to reduce brightness using ddcutil based on the wiki here.
Mine complained first that it can't get a valid response !!! Unable to get capabilities for monitor on Display_Handle
However the getvcp and setvcp commands worked!
Answer: hope I am not late to suggest on this issue!
I am also facing same problem ever since I cleaned my laptop (Ubuntu 22.04.2) panel port by disassembling the laptop. I am pretty sure this is a software problem, not hardware (at least in my case). ANyway, I happen to know a cure of this problem for Ub-22.04.1.

In Terminal:: sudo gedit /etc/modprobe.d/framework-als-blacklist.conf
A blank gedit doc opens, write this command in here and save it:: blacklist hid-sensor-hub
After closing the gedit, return to Terminal and type:: sudo update-initramfs -u
In Terminal after this command execution:: sudo reboot .

This will most probably cure the problem, however if it dosen't please let us know! Additionaly, in the case you dont have gedit text editor preinstalled, you will face an error message in Terminal, there follow this step to install gedit and then execute the above mentioned steps:: sudo apt  install gedit .
Comment: Unless you had this issue before you messed with the hardware. I suggest it is a hardware issue.
Comment: It would be nice to explain what these commands actually are, and what they actually do. Otherwise I'm hesitant to just go ahead and run them in ignorance.
Answer:
Open the Software & Updates application window.
Select the Additional Drivers tab.
Choose any proprietary NVIDIA driver or one from your respective vendor. The higher the driver number, the more recent the version.

This is likely to improve your computer's performance compared to using x.org's drivers and may solve the brightness issue.
Comment: This is a sleazy way of choosing the proprietary NVIDIA driver. It's better to let Ubuntu choose the most compatible proprietary NVIDIA driver automatically.
Comment: @karel `ubuntu-drivers devices` shows recommended drivers. Then you can proceed manually if needed.
Answer: What's the graphic driver you are using? Search "Additional Driver" in ubuntu and change the driver if it's using the default x.org driver.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Proof for parallelogram law of vector addition

Question: The Statement of Parallelogram law of vector addition is,

If two vectors are considered to be the adjacent sides of a parallelogram, then the resultant of two vectors is given by the vector that is a diagonal passing through the point of contact of two vectors.

But how do we justify that the resultant is along the diagonal? Is it based on experimental evidence, or is it something that can be proved?
I know, the question might sound pretty obvious, but I'm new to this stuff. :)
Comment: Vectors are a purely mathematical construct.  You seem to be asking about the superposition principle, which is the physical fact that forces add like vectors. Don't get it backwards! You seem to be implying that vectors add like they do because of the superposition principle, but it's the other way around: we represent forces with vectors *because* addition of forces is just like addition of vectors. In any case, I think you should make your question clearer, because apparently no one understood what you were asking.
Comment: Two things. One, this is a mathematical question, so experimental evidence is not really a proof. Second, how do you define vector addition?
Comment: Three things. First, you din't get me. Secondly, derivation of formula relating the two vectors and resultant can be derived from mathematics. Thirdly, vector addition is a definition based on experiments performed in real life. Vector addition is not a definition, it's a law. It's the generalization on the basis of which we can cloude that, when two particles are tied by two ropes making an angle theta w.r.t. to one another, the particle moves along the diagonal. Now, why the particle has to move along the diagonal, not any other direction? U got me now?
Comment: Yes exactly! How are we representing forces with vectors because addition of forces is just like addition of vectors? How can we justify that?
Comment: This question then seems to mean "Why is the superposition principle valid for vectors (positions, velocities, forces)?" The mathematical proof should just be geometry.
Answer: First, an important remark. Vectors are mathematical objects, just like numbers, matrices, tensors, groups, manifolds, etc. These things are a part of physics because they happen to be a good model for the physical world, but they are not a part of it. Vectors are not something that exists in physical reality, whatever that might be. So let's separate the math and the physics.
You can define a vector as an ordered tuple of real numbers, or as an arrow in space; it doesn't make any difference because the definitions are equivalent. In the case of an ordered tuple of numbers, addition is defined component wise. If you define a vector as an arrow, then addition is defined either with the parallelogram or the triangle law. These notions of addition can be shown to be equivalent, but I don't think that's the point of your question.
On the other hand, we find that a good way to model the way things move is with forces. Suppose you're floating in empty space near a star. You will feel the force of gravity pulling you towards the star. We can model this force as a vector, where the magnitude and direction of the vector correspond to those of the force, and you can use your knowledge of this force (so far there's only one) to calculate your movement using Newton's law.
Now suppose the star magically disappears and is replaced by a different one, maybe with a different mass and a little bit to the side. Now the force (and its associated vector) points to the new star, and you can again use Newton's law. But what if both stars are present? So far all we know is that it's convenient to represent a force by a vector, but we have no idea what to do when there are various forces. It is found experimentally that when there are multiple forces acting on you, it's exactly as if there were a single force, whose vector is given by the vector sum of the individual forces' vectors.
Although this sounds obvious, it is a nontrivial statement. A priori, who says that multiple forces acting at once are equivalent to a single force? It happens to be true, and that is the reason we say that forces are vectors.
Of course, I've used forces as an example, but the superposition principle also applies to velocities, positions, electromagnetic fields, etc. Because it is found experimentally that the superposition principle is valid, we use vectors to model all those things.
Answer: Addition of Vectors basically found their origin from the Triangular Law of Vector Addition

The triangle law of vectors basically is a process that allows one to take two vectors, draw them proportional to each other, connect them head to tail, then draw the resultant vector as a result of the third side that is missing.

The Parallelogram law is just a furthermore explanation of Triangular law,

If two vectors are considered to be the adjacent sides of a Parallelogram, then the resultant of two vectors is given by the vector which is a diagonal passing through the point of contact of two vectors.

The proof for the resultant vector in Parallelogram addition is as follows,
Consider a parallelogram $OABC$ as shown in the figure,

Let $P \;\&\; Q$ be two adjacent sides of parallelogram, and $R$ be the resultant vector obtained by addition of vectors $P \;\&\; Q$,
Now, drop a perpendicular from $C$ on $OA$ so that they meet at $A$.
From right angled triangle $\Delta OCD \;,\; OC^2=OD^2+DC^2$
$$[OD=OA+AD]$$
$$R^2=(OA+AD)^2+DC^2$$
$$R^2=OA^2+AD^2+2OA.AD+DC^2$$
From $\Delta$ADC, $AC^2=AD^2+DC^2$
and also $\cos\theta= \frac{AD}{AC}$
And hence $R^2= OA^2+AC^2+2 OA.AC \cos\theta$
And substituting A and B $$R^2=A^2+B^2+2 A.B \cos\theta$$
Comment: You din't get my question. It was quite obvious anyways. :P I meant, you used the ||gm law to solve this, right? How'd you justify that? In fact, you got the ||gm law as a corollary of Triangle law. How would you justify the triangle law? In fact, if you prove triangle law in this manner, it would be a matter of circular reasoning. I am asking the absolute reason for validity of triangle law.
Comment: Go read Euclid's elements.  If that doesn't answer your question, then you're expecting too much.
Comment: @AnubhabDas The fundamental reason that we treat physical quantity as obeying the mathematical properties of vectors is *that doing so generates correct predictions*. That's true of all science all the time. "Proofs" are a mathematicians tool; scientists use empirical tests.
Comment: @dmckee I guess, that does answer my question.
Answer: Let $\mathbf{a}\;,\; \mathbf{b}$ be two vectors & let these constitute the sides of a parallelogram such that they are co-initial from one of the vertices of a parallelogram. So, considering assumption that the law be true(this is what we'll judge now whether by taking the assumption for the validity of the law, we can prove something which is earlier ascertained by elementary geometry), the two diagonals are $\mathbf{a + b}\;,\;\mathbf{b -a}$. Sum of the squares of the diagonals is $\left| \mathbf{a + b} \right|^2 + \left| \mathbf{b - a} \right|^2$. Now, from Euclidean Geometry, we get from Parallelogram law which states that,

The sum of the squares of the lengths of the four sides of a parallelogram equals the sum of the squares of the lengths of the two diagonals.$^1$

So, the sum of the squares of the diagonals i.e. $\left| \mathbf{a + b} \right|^2 + \left| \mathbf{b - a} \right|^2 $ must be equal to the sum of the squares of the sides $2(|\mathbf{a}|^2 + |\mathbf{b}|^2)$.
This can be proved by inner product or for this case dot product.
$$\begin{align}  \left| \mathbf{a + b} \right|^2 + \left| \mathbf{b - a} \right|^2 = (\mathbf{a + b}) \cdot (\mathbf{a + b}) + (\mathbf{b - a}) \cdot (\mathbf{b - a}) \end{align} \implies  \left| \mathbf{a + b} \right|^2 + \left| \mathbf{b - a} \right|^2  = 2\mathbf{a}\cdot \mathbf{a} +2\mathbf{b}\cdot \mathbf{b} =2(|\mathbf{a}|^2 + |\mathbf{b}|^2)$$ which makes our assumption that the law is true  absolutely true.

$^1$ Courtsey: Wikipedia-Parallelogram law; If you want to deduce the parallelogram law in elementary geometry, then check Is the parallelogram law a theorem or an axiom?.
Comment: "If the law wasn't valid, then our assumption which would be incorrect then, would bring us to such a conclusion which would be incorrect. So, proving that the assumption of the validity of the law brings forth to a correct conclusion means our assumption is correct." That is entirely wrong.
Comment: Yeah, I got your point. But, I've one major confusion. U assumed a statement to be true and then by manipulation, you reached a more general statement which is true, thus making your assumption true. Is this valid?
Comment: @Anubhab Das:   Which assumption are you talking of?
Comment: At first, you assumed ||gm law to be true right?
Comment: @Anubhab Das: See what I've done: I've assumed the law to be valid & if the assumption is true that the law is valid, then it must come to the same conclusion, that has been proved in other way i.e. by using elementary geometry. If the law wasn't valid, then our assumption which would be incorrect then, would bring us to such a conclusion which would be incorrect. So, proving that the assumption of the validity of the law brings forth  to a correct conclusion means our assumption is correct.
Comment: Yeah, I got your point. :) Thanks! Actually it's tough to visualize physical quantities as lengths and how laws of geometry holds for them, as well too!
Comment: @Anubhab Das: Feel free to ask, if you've any problem. I've removed your downvote since the question was good. Many students of your age would cram it but would never ask how it came. So, good luck :)
Comment: Perhaps anyone can help me in this. https://math.stackexchange.com/q/3082098/474166
Comment: You basically proved the statement "*if* the law is true *then* the sum of the squares $\cdots$ of the two diagonals". You cannot conclude the truth value of the assumption from this.
Answer: If you hold a mirror to the two vectors, you get a mirror image of both. Turn the mirror image upside down, and the resultant vector of the upside down mirror image is the same magnitude as the original.  Combine the upside-down mirror image with the original and you have a parallelogram.  This is a proof of magnitude, only.
Comment: That's just one of the case. How'd you generalize for all directional physical quantities?
Answer: This was already answered, but I figured I'd break it down into more intermediate steps for those who, like me, want to see all of the work.
First, note that:
$||\vec{x}|| = \sqrt{x_1^2 + ... + x_n^2}$
$||\vec{x}||^2 = x_1^2 + ... + x_n^2 = \vec{x} \cdot \vec{x}$
Now, let $\vec{a}$ and $\vec{b}$ be two vectors of size $n$ (i.e., they are both $\in R^n $.
Substituting symbolically using $\vec{a} + \vec{b} = \vec{x}$ in the above, we find that:
$||\vec{a} + \vec{b}||^2 = (\vec{a}+\vec{b})\cdot(\vec{a}+\vec{b}) = \vec{a}\cdot\vec{a} + \vec{a}\cdot \vec{b} + \vec{b}\cdot\vec{a} + \vec{b}\cdot \vec{b} = ||\vec{a}||^2 + 2(\vec{a}\cdot\vec{b}) + ||\vec{b}||^2$
Repeat these steps using the same reasoning, this time for $\vec{a} - \vec{b}$, and you'll find that the $2(\vec{a}\cdot\vec{b})$ term will disappear, while the other terms will double.


Journey planning

Question:
If you have the full bus schedule for a country, how can you find out the maximum number of people that can be carried between between two specified stops in 1 day?

I assume a bus schedule gives you the full list of leaving and arriving times for every bus stop and also the capacity of each bus.   You are given the start and end stop in the question.
You could determine a sequence of buses that gives the shortest time to the destination and fill up all the buses that leave from the start going along this path and then when each bus arrives at a stop, just transfer as many passengers as possible to the next bus that is leaving.  There is no reason why this should have maximal capacity however.
What is the fastest this problem can be solved?  For example, suppose that for M cities I'm given a total of N records; route record Rᵢ contains a number Kᵢ, a capacity Cᵢ, and lists of Kᵢ city numbers, Kᵢ arrival times, and Kᵢ departure times. (The first arrival time and the last departure time in  Rᵢ are irrelevant.)  Can a breadth-first search program solve the question in O(M*N) time?
Comment: This is obviously not a duplicate of the other question.  It's a max-flow variant of a shortest path problem.
Comment: Do you have a programming question?
Comment: It's not a duplicate. The question are quite different. The other question talks about the maximum distance you can travel between *any* two nodes and this question is about the maximum *capacity* between two *specified* nodes. I don't expect the solutions to be similar either.
Comment: Fair enough, we do however still need a programming question
Comment: @felix: What data do we have about the passengers?
Comment: Are the "Maximum Capacity" ratings for buses strictly adhered to in the country for which you have a bus schedule? Just sayin.... 'cuz there are some countries where I do *not* want to ride the buses...
Comment: Where are you finding these questions?
Comment: @SaviourSelf I love buses :)  (I actually just think they are interesting algorithmic problems whose solutions I would like to implement.)
Comment: well, please correct me if I'm wrong. If I know the bus schedule then what I've to do except simulate this schedule? Just simulating the schedule will give me the number of people carried from stoppage A to stoppage B and that result will be unique.
Comment: @MuhammedHedayet From a given stop there may be buses to lots of places. You have to choose how many passengers to put on each bus.
Comment: I don't understand why this question has been closed when it has been established it is not a duplicate.
Comment: I doubt that the general question has a precise solution.  One can obviously make a number of educated guesses, and/or simulate it in a number of ways.
Answer: This isn't a weird puzzle; it's an algorithms question. One way to solve this is to make a directed graph with a node for every (location, arrival time) and (location, departure time). Each arrival node has an infinite capacity arc to all departures at the same location that aren't earlier. Each departure node has an arc to each of the appropriate arrival nodes (per the bus schedule), weighted with the capacity of the bus. Then you can use your favorite algorithm to find the maximum flow from your source to your sink.
Your source node should be an arrival node at time zero at your start location, your sink node should be a departure node at the ending time at your ending location.
Comment: You could do a first pass to prune useless nodes from the graph. E.g., time-weight the graph and use Dijkstra from the source and sink, deleting any nodes where the source+sink time > 24 hours. That may or may not be useful, depending on what your graph looks like.
Comment: The complexity is horrible but maybe that's as good as it gets.

Journey planning


copy file from one path to another with a 'variable folder name' in the path - batch file

Question: I got a problem in copying a file from one path to another path with a 'variable folder name' in the path
The following code works fine if the folder name doesnot have a space in it.(hear Folder1 is the variable folder name)
CODE:
<code>@echo off&setlocal enabledelayedexpansion

SET inpu="Folder1"
::SET /p fil=enter file name:

for /f "delims=" %%x in ('dir "C:\Users\kumark3\Desktop\"%inpu% /ad /b') do (
set /a userslen+=1
set "usersarray!userslen!=C:\Users\kumark3\Desktop\%inpu%\%%x"
)

for /l %%x in (1,1,%userslen%) do (

xcopy "!usersarray%%x!\geth\gr.txt" "C:\Users\kumark3\Desktop\Folder2" /c /h /r /y /i

)
</code>
But if the folder name has a space, the code is not working
for eg if the 2nd line in the code is like
SET inpu="Folder 1"
Please give me a solution for this problem
Answer: Almost done, change quotes positions in
<code>set "inpu=Folder 1"
</code>
and
<code>'dir "C:\Users\kumark3\Desktop\%inpu%" /ad /b'
</code>
EDITED - To answer to comments
<code>@echo off
    setlocal enableextensions enabledelayedexpansion

    set "inpu=Folder 1"
    set "where=C:\Users\kumark3\Desktop"

    for /f "tokens=*" %%x in ('dir /ad /b "%where%\%inpu%" /ad /b') do (
        set /a "userslen+=1"
        set "usersarray!userslen!=%where%\%inpu%\%%x"
    )

    set users

    for /l %%x in (1,1,%userslen%) do (
        xcopy /c /h /r /y /i "!usersarray%%x!\geth\gr.txt" "%where%\Folder2"
    )
</code>
Comment: Still not getting the answer

Invalid number of parameters is the error am getting
Comment: @user3173444, see updated answer. Where are you getting your invalid number of parametes?


How can I fill an object matrix

Question: I have an object matrix, and I have to fill it with string. How can I do this? Let me explain well, I have declared a matrix of objects of fixed size, now I have to fill it through for loops, how can I access the cells of the matrix. I put the code of matrix down. Sorry but is in Italian. Giorno = day, ore = Hour
tabMedie = new JTable();
tabMedie.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
tabMedie.setFont(new Font("Times New Roman", Font.PLAIN, 10));
tabMedie.setModel(new DefaultTableModel(
    new Object[][] {
        {"Orari", "Giorno 1", "Giorno 2", "Giorno 3", "Giorno 4", "Giorno 5", "Giorno 6", "Giorno 7"},
        {"1", "", "", "", "", "", "", ""},
        {"2", "", "", "", "", "", "", ""},
        {"3", "", "", "", "", "", "", ""},
        {"4", "", "", "", "", "", "", ""},
        {"5", "", "", "", "", "", "", ""},
        {"6", "", "", "", "", "", "", ""},
        {"7", "", "", "", "", "", "", ""},
        {"8", "", "", "", "", "", "", ""},
        {"9", "", "", "", "", "", "", ""},
        {"10", "", "", "", "", "", "", ""},
        {"11", "", "", "", "", "", "", ""},
        {"12", "", "", "", "", "", "", ""},
        {"13", "", "", "", "", "", "", ""},
        {"14", "", "", "", "", "", "", ""},
        {"15", "", "", "", "", "", "", ""},
        {"16", "", "", "", "", "", "", ""},
        {"17", "", "", "", "", "", "", ""},
        {"18", "", "", "", "", "", "", ""},
        {"19", "", "", "", "", "", "", ""},
        {"20", "", "", "", "", "", "", ""},
        {"21", "", "", "", "", "", "", ""},
        {"22", "", "", "", "", "", "", ""},
        {"23", "", "", "", "", "", "", ""},
        {"24", "", "", "", "", "", "", ""},
    },
    new String[] {
        "Ore", "Giorno 1", "Giorno 2", "Giorno 3", "Giorno 4", "Giorno 5", "Giorno 6", "Giorno 7"
    }
) {
    Class[] columnTypes = new Class[] {
        String.class, String.class, String.class, String.class, String.class, String.class, String.class, String.class
    };
    public Class getColumnClass(int columnIndex) {
        return columnTypes[columnIndex];
    }
    boolean[] columnEditables = new boolean[] {
        true, false, false, false, true, true, true, true
    };
    public boolean isCellEditable(int row, int column) {
        return columnEditables[column];
    }
});
tabMedie.getColumnModel().getColumn(0).setResizable(false);
tabMedie.getColumnModel().getColumn(1).setResizable(false);
tabMedie.getColumnModel().getColumn(2).setResizable(false);
tabMedie.getColumnModel().getColumn(3).setResizable(false);
tabMedie.getColumnModel().getColumn(4).setResizable(false);
tabMedie.getColumnModel().getColumn(5).setResizable(false);
tabMedie.getColumnModel().getColumn(6).setResizable(false);
tabMedie.getColumnModel().getColumn(7).setResizable(false);
tabMedie.setBounds(503, 36, 662, 401);
frmTemperature.getContentPane().add(tabMedie);

Answer: First, store the "matrix" (actually a two-dimensional array) in a variable:
String[][] texts = { { "Ora", "Giorno 1", … }, … };

And then, you can use it in a for loop:
for (int x = 1; x < 8; x++) {
    for (int y = 1; y < texts.length; y++) {
        texts[y][x] = "Your Text Here";
    }
}

And finally, you can pass it to the method as an argument:
new DefaultTableModel(texts, new String[] { … }) { … };

How can I fill an object matrix


Unable to mount NTFS Partition after resizing - "Failed to read last sector"

Question: I had only 15 GB space for Linux, but I wanted to have more, so I just resized one of my NTFS partitions using GParted. But after resizing I am not able to open the partition neither in Ubuntu 10.10 nor in Windows 7.
I get this error message:
Error mounting: mount exited with exit code 12: Failed to read last sector (395458824): Invalid argument
HINTS: Either the volume is a RAID/LDM but it wasn't setup yet,
   or it was not setup correctly (e.g. by not using mdadm --build ...),
   or a wrong device is tried to be mounted,
   or the partition table is corrupt (partition is smaller than NTFS),
   or the NTFS boot sector is corrupt (NTFS size is not valid).
Failed to mount '/dev/sda5': Invalid argument
The device '/dev/sda5' doesn't seem to have a valid NTFS.
Maybe the wrong device is used? Or the whole disk instead of a
partition (e.g. /dev/sda, not /dev/sda1)? Or the other way around?

Answer: This might do it:
sudo ntfsfix /dev/sdxy
change xy in the above to reflect the partition in question, e.g.:
sudo ntfsfix /dev/sdb1

Example output:
ubuntu@ubuntu:~$ sudo ntfsfix /dev/sdb1
Mounting volume... OK
Processing of $MFT and $MFTMirr completed successfully.
Checking the alternate boot sector... FIXED
NTFS volume version is 3.1.
NTFS partition /dev/sdb1 was processed successfully.

Comment: @dgbutterworth I'm not sure if this the right way to make edits. Why not create an additional answer? It's okay if you it's essentially the same as this answer but does improve the whys and hows. You can access your edit if you click on [edit(1)](http://askubuntu.com/review/suggested-edits/338175) below the answer.
Comment: scratch that, it was just formatting....
Answer: Boot from windows installation CD and use recovery console to fix that.
Comment: Thanx for reply but I don't know How to use recovery console.
any help


the false value not working? for checked/unchecked checkbox

Question: please click to view imagePHP CODE: this the code getting the value from database and use it to checked/unchecked checkbox.
<?php

$value = FALSE;

foreach ($LOCKPERIOD as $lp)
    if ($lpg->pay_code == $lp->pay_code) {
        if ($lp->generate_payslip == 1) {
            $value = TRUE;
        } else {
            $value = FALSE;
        }
    }
?>
<input type="checkbox" id="checkbox" checked="<?php echo $value; ?>" >

Comment: Instead of `checked` type `` and it should work.
Comment: What has this to do with JavaScript? It looks like you're using the boolean as a value of an input, remove/add `checked` attribute according to `$value`, if you need to control the input checking.
Comment: sorry this is php code only not a javascript.
Comment: After i remove the checked attribute the checked on checkbox remove all how about the value= 1?
Comment: What are you trying to output? The string 'true' or 'false'? Because you've assigned a boolean to $value. You could assign the strings 'true' and 'false' instead, or use `value=""`. I'd also note that whether the checkbox is checked or not is nothing to do with the "value", and you might actually want something more like `>`
Comment: sir  Daren Chandisingh please click the enter image desription here after the code i posted. thankyou. in this picture you can see my  problem
Comment: and here is my last codes.
pay_code == $lp->pay_code){
                                if($lp->deduct_add_adjustment == 1){
                                    $value = TRUE;
                                }else{
                                  $value = FALSE;
                                }
                          }
                          ?>

Comment: in your db, is `1` stored as an `int` or as a `string(varchar)` ?
Comment: i stored it as int
Comment: where did i paste that code sir Jirka? can you edit my codes sir?
Comment: @JirkaPicek Or better: ``.
Comment: @Nemuel It must be placed instead of this piece of your code: ``.
Answer: Please follow following steps, i have edited your code.
<?php
$value = FALSE;
foreach ($LOCKPERIOD as $lp){
if ($lpg->pay_code == $lp->pay_code) {
    if ($lp->generate_payslip == 1) {
        $value = TRUE;
    } else {
        $value = FALSE;
    }
  }
<input type="checkbox" id="checkbox" <?php echo ($value==TRUE)? 'checked':'';?> >
}
?>

It will work. Kindly try it.


How to prove this interesting inequality: $\frac{5x+3y+z}{5z+3y+x}+\frac{5y+3z+x}{5x+3z+y}+\frac{5z+3x+y}{5y+3x+z}\ge 3$?

Question: Here is my question:

Prove that if $x,y,z>0$ then $$\frac{5x+3y+z}{5z+3y+x}+\frac{5y+3z+x}{5x+3z+y}+\frac{5z+3x+y}{5y+3x+z}\ge 3$$

Here is my attempt:

Let us assume $x>y>z$:
  \begin{align*}
4x+x+z &> 4z+x+z\\
5x+z &> x+5z\\
5x+3y+z &> x+3y+5z\\
\frac{5x+3y+z}{x+3y+5z} &> 1
\end{align*}

The question is given by my high school teacher as a challenge questions in my class.
I want to understand what is the difference between a cyclic inequality and symmetric inequality. Why $\frac{5x+3y+z}{5z+3y+x}+\frac{5y+3z+x}{5x+3z+y}+\frac{5z+3x+y}{5y+3x+z}\ge 3$ is not a symmetric inequality?
Comment: you can assume x>y>z, and try to attack it
Comment: @Vivek how? can you please show me?
Comment: Why is this inequality interesting?
Comment: How did you arrive at this equation ? Did you try to multiply with all the denominators ?
Comment: @Peter I tried, but it is not helping.
Answer: It's $$\sum_{cyc}\left(\frac{5x+3y+z}{x+3y+5z}-1\right)\geq0$$ or
$$\sum_{cyc}\frac{x-z}{x+3y+5z}\geq0$$ or
$$\sum_{cyc}(x-z)(y+3z+5x)(z+3x+5y)\geq0$$ or  $$\sum_{cyc}(x-z)(15x^2+5y^2+3z^2+28xy+14xz+16yz)\geq0$$ or $$\sum_{cyc}(15x^3+5x^2z+3x^2y+28x^2y+14x^2z+16xyz-$$
$$-15x^2z-5x^2y-3x^3-28xyz-14x^2y-16x^2z)\geq0$$ or
$$12\sum_{cyc}(x^3+x^2y-x^2z-xyz)\geq0,$$ which is true by Rearrangement and AM-GM.
Also, we can use C-S.
Indeed,
$$\sum_{cyc}\frac{5x+3y+z}{x+3y+5z}=\sum_{cyc}\frac{(5x+3y+z)^2}{(x+3y+5z)(5x+3y+z)}\geq$$
$$\geq\frac{\left(\sum\limits_{cyc}(5x+3y+z)\right)^2}{\sum\limits_{cyc}(x+3y+5z)(5x+3y+z)}\geq3,$$
where the last inequality it's just $$\sum_{cyc}(x-y)^2\geq0.$$
The inequality is named symmetric if it does not depend on all permutations of variables.
For example, the inequality $$a+b+c\geq3$$ is symmetric because for all permutations of $a$, $b$ and $c$ we obtain the same inequality:
$$a+b+c\geq3;$$
$$a+c+b\geq3;$$
$$b+a+c\geq3;$$
$$b+c+a\geq3;$$
$$c+a+b\geq3$$ and
$$c+b+a\geq3.$$
Easy to see that they are the same.
The inequality is named cyclic if it does not depend on all cyclic permutations of variables.
For example, the following inequality is cyclic.
$$a^2b+b^2c+c^2a\geq3.$$
Cyclic permutations ($a\rightarrow b\rightarrow c\rightarrow a$) give:
$$a^2b+b^2c+c^2a\geq3;$$
$$b^2c+c^2a+a^2b\geq3$$ and $$c^2a+a^2b+b^2c\geq3.$$
Easy to see that they are the same.
By the way, the last inequality is not symmetric because we can not say that it does not depend on all permutations of our variables.
For example, take the permutation $(a,b,c)\rightarrow(a,c,b)$.
By this permutation we get from $$a^2b+b^2c+c^2a\geq3$$ the following:
$$a^2c+c^2b+b^2a\geq3,$$ which is something another.
Comment: @MichaelRozenberg what should be $\sum_{sym}\left(\frac{5x+3y+z}{x+3y+5z}\right)\geq3$ should be written as?
Comment: It's exactly your inequality. I added something in my post. See now.
Comment: @MichaelRozenberg I got it... Thanks for your answer!!! There is a typing mistake in your answer, I don't have edit privilege so I can't correct it... Instead of $a+b+a\geq3$ it should be $c+b+a\geq3$ and instead of "inequality named cyclic/symmetric" it should be "inequality is named cyclic/symmetric"
Comment: My English is very bad. I fixed. :)
Comment: @MichaelRozenberg as you said this inequality is symmetric, so can I use the technique "If both sides of an inequality are symmetric functions then there is no loss of generality in assuming $x>y>z$" ? Then I can add the three different inequalities $\frac{5x+3y+z}{x+3y+5z}> 1$ to get my resulting inequality.
Comment: I think you understood right about assuming $x\geq y\geq z$ in the symmetric inequality. The inequality $\frac{5x+3y+z}{x+3y+5z}>1$ is wrong. You can't add nothing. You need to prove the given  inequality only.
Comment: @MichaelRozenberg why is it wrong? Thanks for being patient with me
Comment: Try $x=y\rightarrow0^+$. You can't assume that $x\geq y\geq z$ because the starting inequality is not symmetric. By the way, you can assume that $z=\min\{x,y,z\}$.
Comment: see this https://imgur.com/a/sBAIp here they are adding three different inequalities to prove the required question
Comment: I saw. It's a symmetric inequality. You see the adding of three true inequalities. In your trying you add three  inequalities and not all of them are true because you can not assume that $x\geq y\geq z$.
Comment: you just said that the inequality is symmetric, now you are saying that the starting inequality is not symmetric? "It's exactly your inequality" $\sum_{sym}\left(\frac{5x+3y+z}{x+3y+5z}\right)\geq3$
Comment: ok... I will try to understand
Comment: Sorry, I did not see "sym". I thought that it's "cyc".  If so it's symmetric of course. I said all time about your starting inequality.
Comment: which one is my starting inequality that you were saying about?
Comment: You can not assume that $x>y>z$. Thus, there all is wrong.


Why does this algorithm convert decimal to hexadecimal numbers?

Question: I can't quite seem to figure out how does such algorithm work...
Code:
#include <stdio.h>

int main(void){

int number = 0;

while(number < 16){

  if(number < 10){
    printf("decimal: \t%d\n", number);
    printf("hexadec.: \t%c\n", number  + '0');
  }else{
    printf("decimal: \t%d\n", number);
    printf("hexadec.: \t%c\n", number  - 10 + 'A');
  }

  printf("\n");
  number++;
  }

  return 1;
}

Output:
decimal:    0
hexadec.:   0

decimal:    1
hexadec.:   1

decimal:    2
hexadec.:   2

decimal:    3
hexadec.:   3

decimal:    4
hexadec.:   4

decimal:    5
hexadec.:   5

decimal:    6
hexadec.:   6

decimal:    7
hexadec.:   7

decimal:    8
hexadec.:   8

decimal:    9
hexadec.:   9

decimal:    10
hexadec.:   A

decimal:    11
hexadec.:   B

decimal:    12
hexadec.:   C

decimal:    13
hexadec.:   D

decimal:    14
hexadec.:   E

decimal:    15
hexadec.:   F

It prints out exactly what I want but I don't understand the process behind it. If I am not mistaken integer + 'character' converts the number to a character by the ascii table.
Let's say we have number 11, then 11 - 10 = 1 which is 49 in ascii, A is 65 in ascii. So how does 49 + 65 = 66.
I am sure this thinking is completely wrong, I just wanted to show you what I think it does in the background.
Comment: It relies on a character set where the symbols A through F occur sequentially. Which doesn't have to be the case, but is on virtually all systems you're likely to encounter.
Comment: With ASCII and compatible encodings, 11 - 10 + 'A' (65) is 66, or 'B'.
Answer: When you change
printf("hexadec.: \t%c\n", number  - 10 + 'A');

to this:
printf("hexadec.: \t%c\n", number  - 9 + 'A');

the first letter you get when 'number' is over 10 is 'B'.
Thats because you count up the Letters from the current value of 'number'.
so when number has the Value 12 you subtract it with 10 and you have the value 2 stored in number
'A' + 2 = 'C'.
you just count up the letters.


How can I pass pipe's filtered data into another function on click event in angular?

Question: I have simple one note list in which each note's background color is randomly pick by pipe and set using style.backgroundColor
Html  :

And My pipe is like this :  (return random color from provided array)
transform(arr: Array<string>, ...args: unknown[]): string {
   return arr[Math.floor(Math.random() * arr.length)];
}

what I want to do that, when Pipe return any value from Array, That is set in background of note div that's fine. But when user click on that note, I want to pass that color into function
want some thing like this :

when user click on that note, that note's background color should be display on next page so I want that pipe's returned color in function.
I don't know weather it is possible or not in angular. If anyone knows about it then please answer here.  I really need it. Please help me.
After research about it. I found this : Angular 2 store piped value in variable
I can store filtered value into main list of note and then reuse it again. But it's weird and not feasible Solution.
Can I generate variable inside html and then direct pass into another function without use of TS ?
Comment: Can I generate variable inside html and then direct pass into another function without use of TS ? No you can't
Comment: i would suggest to isolate the computation part of the transform function in a .ts file. SO you can use it both for the pipe and for any other reason (inside the 'openNote' function in your use case)
Comment: Not sure if it works but you can try. What if you use 'as' after the pipe? Something like this: (backgroundColors | colorChooser) as color
Comment: Is there any other method through which I can pass pipe's result into another function ?
Comment: Thanks For Help Brother. Let me try that one.
Comment: I would cut out logic from pipe and create some utility function and then import it the pipe and in the component class
Comment: Thanks a Lot Buddy, Yaah that can be possible @Yuriy, But I don't want to use TS.
I found one Solution. Let me post here.
Comment: @ JackyShows, Thanks for Reply Man , `as` is not working. I tried that one.
Answer: Yeey, I found Answer After lot's of searching and I made my custom logic for it.
We can pass that result into ng-template and then we can use it in multiple places inside ng-template
Here's how I got it worked :

        <ng-container *ngTemplateOutlet="noteTemplate;context: {color: backgroundColors | colorChooser}">
        </ng-container>
        <ng-template #noteTemplate let-color="color">

                ...

        </ng-template>

I have create one template and then pass filtered value into it and then use it at multiple places.


How safely bring lamp wire into house?

Question: I'm considering replacing an outdoor lighting fixture with an LED motion-sensitive fixture, but I'm not sure how to safely do the wiring.
The location is protected (under a porch) but still needs to be weatherproof. Here's the existing fixture and mount:

The obvious replacement would be another lamp that included its own box cover, so that its wiring would be covered and protected. But, the fixture I like doesn't include such a cover:

You can see it's meant to be screwed into the wall, but doesn't cover anything. The power cable ends with bare wires which are meant to be wire-nutted to the supply wiring, probably inside a junction box. But, how do I get the wire safely into the junction box while keeping things weatherproof?
One option would be to replace the lamp's power cable with one ending in a grounded plug, and install a weatherproof outlet box. But that's ugly and complex.
Are there weatherproof junction box covers that include provisions for sealed entry of cables?
Answer: Those cheap Chinese lights need to be thought out better. There is no one stock part to simply mount them to a proper box. You'll need to make something up on your own. Some of the ones I've seen at the supply house have been put together with a plate from the manufacturer with a rubber sealed connector already installed.
You'll need to mount the bracket to a gasketed weatherproof blank place, then knock out or drill a hole for a rubber cord connector of the proper size to pass the cord through the metal plate.
If you do not have the light yet my strong recommendation would be to find one that is already set up to mount to a box properly.

How safely bring lamp wire into house?


Android: custom a menu create

Question: I don't know which type of this menu. can anyone help me.

I want to create menu like this screen. When i click the button then pop-up the menu like this. I don't know how to achieve this. i do not know what type of this menu. and can it run on android 2.2?
Comment: Hi There Create Custom Dialog and set the x and y positions (means set Attributes).so you can achive that one
Comment: yaa its right but what about when user click at the left button. then its open at center position.
Comment: you can also use PopUpWindow  developer.android.com/reference/android/widget/PopupWindow.html
Comment: @Gautam Vasoya it's nice and also user-friendly..user can easily do deletion or cancel operation rapidly...:)
Comment: @GautamVasoya you can set the positions of dialog where that should come set x and y positions of that dialog then it should come at that button.
Answer: Current popup menu called QuickAction Dialog in Android. you can customize it According to you need. see following good tutorial for creating QuickAction View in Android:
How to Create QuickAction Dialog in Android
Quick Actions Android
Answer: This is Quick Action 3d. Checkout source and example from here :)
Answer: This is not exactly a custom dialog. But, yes it is still a customized view. And it is more or less called Quick Action Dialog in android. I would suggest you to follow the tutorials below for generating an exactly same popover (or even better) with Android. Check the screenshot also.

http://www.londatiga.net/it/how-to-create-quickaction-dialog-in-android/
https://github.com/lorensiuswlt/NewQuickAction3D

Reference

Android: custom a menu create


Why is $f:\mathbb{R} \rightarrow [-1,1]$ , $x$ mapped to $\sin(x)$, surjective?

Question: I'm a little confused with the $x$ mapped to $\sin(x)$ and the $[-1,1]$.
Comment: Because ... for every $-1 \le y \le 1$ there is a $\theta$ so that $\sin \theta = y$?  I don't understand what you are asking.
Comment: I edited your tags; this has nothing to do with "discrete geometry".
Answer: Note that $f: \mathbb{R} \rightarrow [-1,1]$ defines by $x \mapsto \sin(x)$ means that $f$ is the function taking a real number $x$ to the number $\sin(x)$ whose value lies in the interval $[-1,1]$.
The intermediate value theorem states that if a continuous function, $f$, with an interval, $[a, b]$, as its domain, takes values $f(a)$ and $f(b)$ at each end of the interval, then it also takes any value between $f(a)$ and $f(b)$ at some point within the interval.
If you can convince yourself that $\sin(x)$ is continuous on $\mathbb{R}$, than you just need to take $a := \frac{\pi}{2}$ and $b := \frac{3\pi}{2}$. You can check that $f(a) = 1$ and $f(b) = -1$.
Answer: Perhaps a review of the geometric definition of the sine function would help. As is done in the picture linked, I'll use $\theta$ as the input angle ($x$ is used for a different purpose, as the first coordinate in the Cartesian plane).
From the picture linked above, if you draw a line segment $\overline{\mathcal{O} P}$ with one endpoint at the origin $\mathcal{O} = (0,0)$ and opposite endpoint at $P = (x,y)$ on the unit circle, and if $\theta$ is equal to the signed angle from the positive $x$-axis to this line segment, then $\sin(\theta)=y$.
From the picture linked, you can see that any $y$-coordinate between $-1$ and $+1$ can be obtained in this way from some appropriate choice of $\theta$: draw the horizontal line $L$ with that $y$-coordinate, take $P$ to be the point where $L$ intersects the right half of the unit circle, and take $\theta$ to be the signed angle from the positive $x$-axis to the segment $\overline{\mathcal{O} P}$.
In other words, for each $y \in [-1,+1]$ there exists $\theta$ such that $\sin(\theta)=y$, which proves surjectivity.


Bottom content cutoff using overflow: auto; and jscrollpane

Question: Because of a rotated content area, textoverflow, and a -webkit issue about the scroll bar not showing properly I've decided to use jscrollpane.  For initial issue:  Original Issue question to Sitepoint.
To prevent all that extra css code to create my own scrollbar for -webkit browsers I decided to use jscrollpane.  It works accept for one major issue:  The bottom several lines of text remain invisible!  Please see:  overflow:  auto; with jscrollpane, but cutting off bottom text.  How do I make it scrollable enabling all of the content to be visible?
Any help is appreciated.
PChuprina
Comment: I have the same problem in webkit browsers. Have you determined a solution?
Answer: jScrollPane has some options for solving this:

autoReinitialise:true

(adds processing overhead.. use only if necessary)
http://jscrollpane.kelvinluck.com/auto_reinitialise.html

reinitialise()

(manually update pane size)
http://jscrollpane.kelvinluck.com/dynamic_content.html
Answer: Welcome to stackoverflow!
This looks like a simple problem of timing. You are/something is altering the content of the scroll pane after the jsScrollPane() function has run.
First try simply including it in a $(document).ready() function. If that doesn't work go through your functions and check to see if any javascript is altering the size of that container and add jsScrollPane() as a callback.
Pretty sure the first will work for you though :)
Comment: hmm, interesting. If you open up your site in chrome, hit ctrl+shift+j, go to console, type in `$('#resume').jScrollPane();` and hit enter it should display the correct scroll. You have a script.js file - can you not add your initialisation code here? Final option - it could be because of your images loading. If adding to `$(document).ready(function(){})` in script.js doesn't work try creating a new function `$(window).load(function(){$('#resume').jScrollPane();})`
Comment: Hi @Inrbob,
Unfortunately your fix didn't work.  Not sure whether I implemented the $(document).ready() function.  The code to implement jscrollpane is:

$(function(){
$('#resume').jScrollPane();
});

Also there doesn't seem to be any other functions altering the size of the container.  The only other javascript is for Google analytics.  Any more help would definately be appreciated and a learning experience.  Thanks.  PChuprina
Comment: I think Inrbob is right, but I've found some weird behaviour of jScrollPane. I had the same issue. My images had padding property set to 6px, which was no calculated in overall height of enclosing div. jScrollPane initializator just ignored that property of an image and enclosing div was shorter than expected by (2x6px)12px.


Output to the console window

Question: Trivial question, but how do I go about outputting the results into the console window. Don't know how to pass that data type to main. I have the code as follows:
namespace Node
    {
        class Program
        {
            public static int appLayer(int humData)
            {
                int tempData1 = 55;
                int tempData2 = 60;
                int tempData3 = 58;
                int tempData4 = 58;
                int [] tempData = new int[] {tempData1, tempData2, tempData3, tempData4};

                Dictionary<int, int> count = new Dictionary<int, int>();
                foreach (int a in tempData)
                {
                    if (count.ContainsKey(a))
                        count[a] = count[a] + 1;
                    else
                        count[a] = 1;
                }
                int result = int.MinValue;
                int max = int.MaxValue;
                foreach (int key in count.Keys)
                {
                    if (count[key] > max)
                    {
                        max = count[key];
                        result = key;
                    }
                }
                return result;
            }
            static void Main(string[] args)
            {
                Console.WriteLine("The mode is: " + result);
            }
        }

Thank you
Answer: static void Main(string[] args)
{
   int result = appLayer();
   Console.WriteLine("The mode is: " + result);
}

OR
static void Main(string[] args)
{
   Console.WriteLine("The mode is: " + appLayer());
}

The prototype of appLayer should be
public static int appLayer()

because the humData parameter is not used.
Answer: You have to call the method inside your main and add a Console.Read() or Console.ReadLine()
        static void Main(string[] args)
        {
            var result = appLayer(0); // 0 is the parameter value for humData which is not used so you can remove it...
            Console.WriteLine("The mode is: " + result);
            Console.ReadLine(); // Add this to the end to have a pause on the console app
        }

Comment: I get it now. Thanks for a quick and clear explanation.

Output to the console window


Overlap When Painting Stripes: Can I Sand?

Question: I'm painting a three-stripe pattern across the length of my wall, and I had a question about whether I could sand down the overlapping areas.
The stripe consists of a 21" green stripe with two 3" stripes (white and dark grey) bordering it. It goes green--white--dark grey from bottom to top. The walls are a light grey/taupe color. We painted the top and bottom of the wall light grey, and then we measured and painted a swath of white. Next we will paint the grey and green and ta da, the white becomes a stripe.
So to my question. When we painted the white, you could see the buildup under it when you look closely. It's not super obvious, but my OCD had taken over. Before I paint the other stripes, can I tape them off and sand down the areas that will be painted? I just want to whittle down the paint a little so it looks cleaner.
Answer: Sure, no problem there as long as you get what you want. Or, you can very lightly & precisely cut or score it along a straight-edge with a razor blade & peel it off. Or, even very carefully paint white over any bleeding fissures.
Comment: Good ideas. For all of them, make sure you experiment to get the technique down. With sanding in particular, the grit of the paper will affect the final texture and gloss of the paint in the sanded area, and if you're using a glossy paint it could come out looking dull.


Specifying implementation at deploy time in grails

Question: This issue specifically stems from specifying an XMLOutputFactory implementation in a grails app, but I was looking for a more generic grails way to do this. So here goes.
In our grails app, we use the XMLOutputFactory to build XMLWriters that render out documents. Now the XMLOutputFactory implementation that we were looking for is present in the Sun's implementation of this class which is com.sun.xml.internal.stream.XMLOutputFactoryImpl.
So to use this, we added it as a system property in Glassfish, which we use as our app server and that works as we expect it be. Which leads me to my question(s), how would we have this mapping within the Grails app such that we don't need to update a server property for this.
Initially I thought it should be just adding it to the Config.groovy, but I don't think system properties are the same as grails config properties.
The second option was to call these at command time with the -D param. And that works, but I was looking for a more elegant solution to this.
Therefore, is there a "grails" way to do this? And if so, would those properties persist once deployed into the container? Or is updating the container properties the sole way to get around this.
I hope this makes sense :).
Thanks
Answer: If this configuration changes for deployments Config.groovy is a good place to put it, because you can externalize it, so in your server environment you can replace the value of the config.
Config.groovy
application.xmlFactory=...

grails.config.locations = [classpath:external-config.groovy]

external-config.groovy
application.xmlFactory=com.sun.xml.internal.stream.XMLOutputFactoryImpl

Comment: So I had tried this. But it seems like grails attaches this to the config properties, instead of java system properties that can be accessed using System.getProperty(...). I am thinking that the classloader doesn't quite look at grails config properties for something like this?


Are there locations in a residence where a non tamper resistant receptacle can still be used?

Question: Assume for a second that my jurisdiction has adopted 2011 NEC code as legally binding without significant amendment. This code requires (406.11) that 120V 15/20A outlets in all areas defined in NEC 210.52 must be tamper-resistant, and that existing grandfathered outlets are only grandfathered until replaced; any replacement must be TR. Exceptions are:

Outlets more than 5.5' off the ground (only common one I can think of is the one for a garage door opener)
Outlets designed to be used by a major appliance which normally blocks access to the receptacle (mostly in the kitchen; fridge/stove/oven/dishwasher)
Outlets built in to light fixtures or lumieres (and so replacing them would involve replacing the entire light fixture which may be expensive or impossible)

210.52 covers pretty much any outlet in an interior space of a residential building, including attached garages. It doesn't specifically cover closets but the NEC doesn't treat closets any differently than the interior space containing the closet. It also doesn't (AFAIK) cover attic spaces that haven't been finished. I don't have a basement so don't worry about that.
All that being said, is there any outlet in my house, besides the one for the fridge (ex 2), stove (ditto) and garage door opener (ex 1 - on the ceiling), that wouldn't be required to be TR if/when I replace it?
This also begs the (somewhat argumentative) question of why standard (non-TR) outlets are still sold to "amateur" electricians. At least in my area, they are only code-compliant in commercial spaces that aren't healthcare, child care or hotel spaces (ask the next 100 people who buy an outlet where they plan to install it, and 99 will say "in my home"), and in VERY LIMITED circumstances in residential, where a TR outlet would also be just fine. I'm not sure exactly how the store would be expected to tell who would install it in a compliant way, but it seems disingenuous for a store to sell 10-packs of outlets that would be illegal to install without at least having the POS system throw up a flag at checkout (like they already do for age-restricted items like glues/paints/solvents).
Comment: It's not the responsibility of the store to enforce codes, that's the Electrical Inspectors job (which is likely unionized, so he'd file a grievance if the stores did his job).
Comment: @KeithS Save yourself some cash and pick up some [Outlet Plugs](http://www.toysrus.com/product/index.jsp?productId=12011319). NEC only requires tamper resistant receptacles in new installs and when receptacles are replaced.  We all grew up with open receptacles, and most of us made it.
Comment: If the vast majority of the outlets are required to be TR, why worry about which ones don't need to be? Just install them everywhere and be done with it.
Comment: No safety device has ever been invented that can match the vigilant parent.
Comment: -1 :   I am downvoting because your question is literally its own answer.   Why not just remove all the preamble and answer the question yourself?
Comment: @tester101: Funny. But actually, there are a lot of laws regarding possession of certain items, which retail stores are expected to help enforce at point of sale. Alcohol, ciggs, VOC products which can be inhaled, firearms and firearm-like devices such as pellet and paintball guns, etc etc. However, that wasn't the main question.
Comment: @Steven: That's a pretty big retrofit in my case. Theoretically I agree, but I don't have long until my daughter is going to start crawling, so I'm working in three phases; ones that need replacing before she can move around on her own (and we let her do so in certain living areas), ones that need replacing before she has the run of the house, and ones that aren't going to be a concern because she can't possibly reach them before we can teach her the danger.
Comment: This question really identifies that third category; if it's not required by NEC it's because it's extremely unlikely for a preschooler to get to them, or simply impractical to replace them.
Comment: My niece is two, and can remove most outlet plugs in nothing flat. And conversely there are child-safe plugs in her parents' house which even the parents can't get back out. Yes, I'm probably being overcautious, but my daughter is incredibly cute so you'll just have to forgive me.
Comment: I applaud better safety regulations, but I recently installed many outlets in my unfinished basement and It just didnt make sense to put in TR ones there.
Comment: I was just looking at another related question last night.  It doesn't appear the tamper resistant outlets are worth the cost and hassle.  They don't seem to have a significant impact on child safety.  Maybe the home improvement stores are thinking with their head?
Answer: While Article 406.11 Tamper-Resistant Receptacles in Dwelling Units. existed in NEC 2008, it was revised as Article 406.12 Tamper-Resistant Receptacles in Dwelling Units. in NEC 2011. And it says Tamper-Resistant Receptacles are required in all areas listed in Article 210.52

National Electrical Code 2011
ARTICLE 210 Branch Circuits
210.52 Dwelling Unit Receptacle Outlets.
(A) General Provisions.

kitchen
family room
dining room
living room
parlor
library
den
sunroom
bedroom
recreation room
or similar room or area of dwelling units

(B) Small Appliances
(C) Countertops
(D) Bathrooms
(E) Outdoor Outlets
(F) Laundry Areas
(G) Basements and Garages
(H) Hallways

With the following exceptions.

Ex.: Receptacles in the following locations aren't required to be tamper-resistant:
(1) Receptacles located more than 5½ ft above the floor.
(2) Receptacles that are part of a luminaire or appliance.
(3) A receptacle located within dedicated space for an appliance that in normal use isn't easily moved from one place to another.
(4) Nongrounding receptacles used for replacements as permitted in 406.4(D)(2)(a).
Comment: @shirlockhomes No link. my source is not online. It'll cost you $90.00. [NFPA 70 :National Electrical Code](http://www.nfpa.org/catalog/product.asp?pid=7011SB&icid=B484)
Comment: @keshlam just new, permitted work. Unless some type of other laws/codes require you to bring things up to current code.
Comment: This answer doesn't really tell me anything I didn't already know as of when I wrote the OP. I think I can add two more outlets to my list; the ones for the washer and dryer, as they are located behind said appliances which definitely qualify as "not easily moved". I have no non-grounded plugs; the house was built in the late 70s so 110v outlets had to be grounded. So, I think by this answer that you agree that every plug in a typical SFD that isn't for the fridge, stove, GDO, or W/D must be at least TR, and outdoor/wet areas must be WR.
Comment: Tester, Can you send me the link you use for NEC???  thanks
Comment: Follow-up Q. Does an attic space that isn't finished as living space count as "outdoor"? If finished, it's definitely a living space and so outlets must be TR, but if not, it doesn't really fall into any other listed area that would require TR, unless it's considered outdoor space.
Comment: @KeithS not outdoor (unless you don't have a roof, or only have 3 walls). If it has a floor (not just joists) and a non-movable staircase leading to it, I might call it living space. Maybe "Storage or Equipment Spaces."
Comment: Some of it is floored in plywood. They're all "crawl spaces", and none have a built-in ladder or staircase.
Comment: Then I'd call it Storage, in which case the only requirement would be one lighting outlet (*outlet* not receptacle) controlled by a switch at the normal point of entry. Since this area is not covered in 210.52, receptacles are not required in this area and so tamper resistant receptacles are not required either.
Comment: Thanks. BTW, there IS a copy of the 2011 NEC available for free. http://www.nfpa.org/aboutthecodes/AboutTheCodes.asp?DocNum=70&cookie_test=1 You have to sign into their site (it's free to register), and the online version has some severe limitations (single-page scrolling, no search, save or print), but it's there.
Comment: So, looks like an outlet behind a wall mounted TV would fall into exception 3. Reason being that there is a recessed black non-TR outlet I'd like to install behind my TV
Comment: @Tester101: One thing I'm not clear on: does this section demand replacing existing outlets in those locations (including GFCI?) or is it just new work?
Comment: @keshlam existing work is generally grandfathered in (check codes in your jurisdiction) _unless_ it constitutes a safety hazard. My house built a few decades ago has many violations of modern building and electrical code, but is in no danger of falling over or bursting into flames. For example: certain configurations of knob and tube wiring might be considered a hazard because it can burn your house down, while non-TR outlets probably would not.
Answer: The TR rule applies whether you get a permit or not.  I install TR in every receptacle location. They cost about 60 cents more than the baby killer open outlets. IMO open outlets should not be sold anywhere.
Comment: While your _opinion_ is valid, it's irrelevant when it comes to what the code says and what's legal. In _my_ opinion, most posted speed limits are far too low, but that won't matter if a cop pulls me over. If you'd care to [edit] this into an answer to the question asked, please do so, otherwise, it will likely be deleted soon. If you'll spend a moment taking the [tour], you'll understand why.
Comment: If you're concerned about the safety of babies in your house, you'd be better to install combination afi/gfi breakers for all your receptacle and lighting circuits.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask).


Tunneling & Bypass proxy

Question: are there any software for ubuntu to tunneling/bypass proxy (HTTP/S, SOCK4/5). Like "Proxifier" on windows ?
Comment: You could try the easy to use GUI tool [GrrProxy](https://github.com/Cadogan/GrrProxy)
Answer: If you want to use putty as a dynamic proxy to go across the firewall, just select "Dynamic" and type any available source port you wish(ie. 9050), then press "Add". Things get done :D
Go to your system proxy setting(ONLY configure in your browser if you want it to be the browser's proxy) , only set the socks v5 proxy as 127.0.0.1:yourport (ie. 127.0.0.1:9050)

Wanna use it to break the firewall in Browsers, then continue reading the information as below otherwise that's all.
If you are using firefox, type about:config in the address bar, then search "remote_dns", set the value to True
If you are using chrome, just install the "Proxy SwitchySharp" extention, remote dns resolve is used by default.
Have fun with your newly setup proxy and have fun bypassing the firewall between your PC and your target hosts.
Comment: actually, it's very simple to setup a dymanic proxy in linux with a single line command `ssh -D your_proxy_port -p your_remote_ssh_port username@remote_host_name`
Answer: Yes, the ever-popular PuTTY (http://www.chiark.greenend.org.uk/~sgtatham/putty/) is available through the repositories.
To install it run:
sudo apt-get install putty

To set up tunneling it is quite easy.
Open PuTTY
Enter the IP address of the server you want to tunnel to (where 255.255.255.255 is in the image)

After entering the IP address, click on the 'Tunnels' tab under SSH.
Now enter the port you want the connections to go over on the source port and set your localhost at that specified port as the destination and click 'Add'

Tunneling & Bypass proxy


MacOS Desktops for Ubuntu

Question: Anyone who knows of MacOS-like desktop window manager that runs on Ubuntu?
Having left Win2k around 2000 for SuSE, dropping SUSE for OSX in 2010, and now dropping MacOS (Software and Desktop) for Ubuntu 18.04.1 LTS, I've come to like the minimalism of the MacOS-Desktop, but hating its HPFS/APFS Filesystem and BSD environment. I work a lot with CentOS Servers, but would switch all Office Workstations to a future oriented OS like Ubuntu LTS. The Unity Desktop was quite OK for me, but would like to have a MacOS-Like Work environment. I looked at ZorinOS, but it does not support any MacBookPro's atm. QUBES just reboots during the installation and re-installs.
The aim is an Ubuntu Host with a MacOS-Like Desktop equvalent to ZorinOS's strategy (but stable and running on MacBookPro's) and running Whonix WS & GW on some, and a plain Office WS on others.
Regards
Answer: This will get you a similar appearance, however as far as running Mac programs I don't think there is such an animal.
https://www.noobslab.com/2018/08/macbuntu-1804-transformation-pack-ready.html

MacOS Desktops for Ubuntu


Evaluating $\lim _{x\to \infty }\tan\left(x^2\sin\frac{\pi }{4x^2}\right)$ without L'hopital's rule

Question: How do I solve this without using L'hopital's rule?
$$\lim _{x\to \infty }\left(\tan\left(x^2\sin\left(\frac{\pi }{4x^2}\right)\right)\right)$$
Problem
EDIT:
My progress so far:
$$\lim _{x\to \infty }\left(\tan\left(x^2\sin\left(\frac{\pi }{4x^2}\right)\right)\right)$$
$$=\lim _{x\to \infty }\left(\tan\left(\frac{\sin\left(\frac{\pi }{4x^2}\right)}{\frac{1}{x^2}}\right)\right)$$
$$=\lim _{x\to \infty }\left(\tan\left(\frac{\pi}{4}*\frac{\sin\left(\frac{\pi }{4x^2}\right)}{\frac{\pi}{4x^2}}\right)\right)$$
Now I know $\frac{\sin\left(x\right)}{x} = 1$ but I don't know how to take the above expression to that form.
Comment: Hi there! I'm more than happy to give you a hand, but I want to (1) avoid writing a solution that contains "redundant" details (e.g. repeating a part of the solution process you've already made progress on and/or clearly understand), and (2) avoid revealing the answer to a homework problem unless I know you've put some effort into solving it. Could you be kind enough to show how you've attempted to attack the problem?
Comment: Hints: change of variable $t:=\dfrac{\pi}{4x^2}$ and continuity of the tangent.
Comment: @AlannRosas I have made my edits to my original post to show my progress. I appreciate that you are not blindly handing out solutions and allowing the OPs to actually work on their problems. This was my first time posting on math.stackexchange.com so I didn't know how to go about it. From now on, I'll ask questions along with my progress so far.
Comment: @AlannRosas, hey, nice approach! this is different from the usual copy paste of rep-w users
Comment: Write down the Taylor series and take the limit as x goes to infinity.
Comment: @MSha Taylor series is a overkill for someone who has just started out with limits, we all should try to answer in a way which is understandable for the OP according to their current knowledge.
Answer: Hint:
$\lim _{x\to 0} \frac{\sin x}{x}=1$ then if $x\to\infty\ $ means $\frac{1}{x}\to0$. So basically $\lim _{x\to \infty} \frac{\sin\left(\frac{1}{x}\right)}{\frac{1}{x}}$ is also equal to $1$
Answer: You've already taken care of one important bit, namely rewriting
$$\tan\left(x^2\sin\frac{\pi}{4x^2}\right)$$
as
$$\tan\left(\frac{\pi}{4}\cdot\frac{\sin\frac{\pi}{4x^2}}{\frac{\pi}{4x^2}}\right)$$
As you noted, $\lim_{x\to 0}\frac{\sin(x)}{x}=1$, so we should make use of this somehow. We can achieve this goal by making use of another important observation, namely that
$$\lim_{x\to\infty}\frac{\pi}{4x^2}=\frac{\pi}{4}\lim_{x\to\infty}\frac{1}{x^2}=\frac{\pi}{4}\cdot 0=0$$
Knowing this, I hope it makes sense that we should have
$$\lim_{x\to\infty}\frac{\sin\left(\frac{\pi}{4x^2}\right)}{\frac{\pi}{4x^2}}=1$$
After all, as $x$ gets bigger and bigger, $\frac{\pi}{4x^2}$ gets closer and closer to $0$, and $\sin(y)/y$ gets closer and closer to $1$ as its argument gets smaller and smaller, namely $y=\frac{\pi}{4x^2}$.
Alright, so we know that
$$\lim_{x\to\infty}\frac{\sin\left(\frac{\pi}{4x^2}\right)}{\frac{\pi}{4x^2}}=1$$
and thus, by the constant multiple rule for limits
$$\lim_{x\to\infty}\left(\frac{\pi}{4}\cdot\frac{\sin\left(\frac{\pi}{4x^2}\right)}{\frac{\pi}{4x^2}}\right)=\frac{\pi}{4}$$
But the tangent function $\tan$ is continuous near $\pi/4$, so
$$\lim_{x\to\infty}\tan\left(\frac{\pi}{4}\cdot\frac{\sin\left(\frac{\pi}{4x^2}\right)}{\frac{\pi}{4x^2}}\right)=\tan\left(\lim_{x\to\infty}\left(\frac{\pi}{4}\cdot\frac{\sin\left(\frac{\pi}{4x^2}\right)}{\frac{\pi}{4x^2}}\right)\right)=\tan\left(\frac{\pi}{4}\right)=1$$
We conclude that the original limit is
$$\lim_{x\to\infty}\tan\left(x^2\sin\frac{\pi}{4x^2}\right)=1$$
Comment: $\tan$ is not continuous in $\mathbb{R}$. It's just that $x^{2}\sin(\frac{\pi}{4x^{2}})$ takes values within $(-\frac{\pi}{4},\frac{\pi}{4})$ within which tan is continuous . You should edit that.
Comment: @Mr.GandalfSauron you're right! I have fixed that part of the proof :)


How to set the Referer of HttpRequest in windows store app?

Question: I want to download some images from a website, but it must send the request with 'referer'.
the code like this:
<code> HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imgUrl);
 CookieContainer cc = new CookieContainer();
 request.CookieContainer = cc;
 request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5";
 request.Referer = "http://www.xxxxx.com/xxx/xxx/list_78542.html";
 request.CookieContainer = cc;
 HttpWebResponse myResponse = (HttpWebResponse)request.GetResponse();
 using (Stream stream = myResponse.GetResponseStream())
 ...
</code>
however, when i want to do it in windows store apps, it has not the property 'Referer' in WebRequest, I try to use this(as below) to set the 'UserAgent' and 'Referer'
<code>    request.Headers["UserAgent"] = UserAgent;
    request.Headers["Referer"] = Referer;
</code>
but it raise an error "The 'Referer' header must be modified using the appropriate property or method."
What should i do, help me, please?
Thanks.
Answer: Try to use Windows.Web.Http namespace instead of System.Net as described here https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn440594.aspx
Answer: Very simple:
myHttpWebRequest.Referer="http://www.microsoft.com";
Comment: This answer does not solve the issue for Windows Store apps or universal portable class libraries for that matter. It only solves the problem for regular C# applications.