text:
Q: How to avoid java.io.StreamCorruptedException? I have a method that writes data from a list to a file, a method that reads data from a file into a list and a method that writes data from a list in a file to the specified number of times. I'm trying to extract data from a file after I use the first method writeFile () everything works fine. I read the data from the file into the list by readFile () method. After that I use my method which writes to the file the number of times I need, everything is fine, it writes multyWrite (). But after that I can not read the data from the file in the readFile () method since I get `
Exception stack trace:
 Exception in thread "main" java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1599)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at ProductService.readFile(ProductService.java:47)
at Main.main(Main.java:21)

I know that I should use objectOutputStream.reset (), but where would it be better to use it?
private String fileName;
    private ProductInterface<FlyingMachine> productService = new ProductInterfaceImpl();
    private ObjectOutputStream objectOutputStream;
    private FileOutputStream fileOutputStream;

    public ProductService(String fileName) throws IOException {
        this.fileName = fileName;
        fileOutputStream = new FileOutputStream(fileName);
        this.objectOutputStream = new ObjectOutputStream(fileOutputStream);
    }

public void writeFile() throws IOException {
        try {
            for (FlyingMachine f : productService.getProductContainer()) {
                objectOutputStream.writeObject(f);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (objectOutputStream != null) {
                objectOutputStream.flush();
                objectOutputStream.close();
                fileOutputStream.close();
            }
        }
    }`

public void readFile() throws IOException {
        ObjectInputStream objectInputStream = null;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(fileName);
            objectInputStream = new ObjectInputStream(fileInputStream);
            while (fileInputStream.available() > 0) {
                FlyingMachine flyingMachine = (FlyingMachine) objectInputStream.readObject();
                productService.getProductContainer().add(flyingMachine);
            }
        } catch (ClassNotFoundException | EOFException e) {
            e.printStackTrace();
        } finally {
            if (objectInputStream != null) {
                objectInputStream.close();
                fileInputStream.close();
            }
        }
    }

public void multyWrite(int number) throws IOException {
        for (int i = 0; i < number; i++) {
            try {
                fileOutputStream = new FileOutputStream(fileName, true);
                objectOutputStream = new ObjectOutputStream(fileOutputStream);
                for (FlyingMachine f : productService.getProductContainer()) {
                    objectOutputStream.writeObject(f);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (objectOutputStream != null) {
                    objectOutputStream.flush();
                    objectOutputStream.close();
                }
            }
        }
    }

A: You create a new ObjectOutputStream in the constructor. In writeFile you use that OOS instance and close it. But in multyWrite you don't use it and instead create new instances.
Now when you call multyWrite without having called writeFile first, that first OOS will still be open, but the OOS you create in multyWrite doesn't know that - thus causing your file to have two OOS headers after another.
And then when you try to read such a file, the ObjectInputStream will find the first header (all is fine) and then unexpectedly find the second header, while it expected a type code. That header starts with 0xAC, hence throwing the exception message "invalid type code: AC".
To fix this, either have multyWrite use the OOS constructed in your constructor, the same way writeFile does, or make sure that that OOS is closed before you create a new one.
It's generally not a good idea to open a stream (of any kind) in a constructor and then rely on external code calling a specific method to close it. Better create streams when you need them and close them directly.


text:
Q: Set env variable inside sudo statement - Linux shell I need to modify an environment variable inside a sudo statement. The sudo statement includes some instructions.
In the example, I set the environment variable VAR1 with the value "ABC".
Then, in the sudo statement (and only here), I need to change that value to "DEF". But the value did not change after I set the value to "DEF". Echo commands return "ABC" as the value of VAR1.
How can I change/set the value of the variable inside the sudo statement?
Here an example of the code I run:
#!/bin/bash
export VAR1="ABC"

sudo -u <user> -i sh -c "
         export VAR1="DEF";
         echo $VAR1;
"

echo $VAR1;

Extra info: I tryed the option -E of sudo, to preserve the environment variable at the moment of sudo invocation (source: https://unix.stackexchange.com/questions/337819/how-to-export-variable-for-use-with-sudo/337820), but the result did not change:
#env VAR1="DEF" sudo -u <user> -E -i sh -c " [...]"

A: Use single quotes to prevent the outer shell from interpolating $VAR1. You need $VAR1 to be passed to the inner shell so it can expand it.
sudo -u <user> -i sh -c '
         export VAR1="DEF"
         echo "$VAR1"
'

It's also a good idea to quote variable expansions to prevent globbing and splitting mishaps: write "$VAR1" instead of $VAR1.
(The semicolons aren't necessary since you have newlines.)

A: Try this
export VAR1="ABC"

sudo -u <user> -i sh -c '
         export VAR1="DEF"
         echo "${VAR1}"
'

echo $VAR1;

as John Kugelman pointed out, you should use ' instead of " to wrap your command to avoid shell vars interpolation. Also, when referencing to VAR inside the command, use "${}" instead of $, this is what did the trick for me

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve the compilation options for octave Is there any simple way to retrieve the compilation options for octave ?
Something similar to python:
import distutils.sysconfig
print(distutils.sysconfig.get_config_var('CONFIG_ARGS'))
>>> '--enable-shared' '--enable-ipv6' '--with-ensurepip=no' <...>

I'm running Ubuntu 16.04

A: octave_config_info () is very chatty. For example the configure options as you asked on my system:
octave:1> octave_config_info().config_opts
ans = '--disable-gui'

EDIT: as carandraug has pointed out "octave_config_info()" has been deprecated for 4.2. You can see a discussion on the maintainers mailinglist here: http://octave.1599824.n4.nabble.com/quot-features-quot-problems-td4675361.html


text:
Q: Reduce latency in Asyncio I have an websocket server up and running fine using FastAPI.
However, when i am using those "await", i am getting some latency issues. At first, i though this had something to do with internet connection, or perhaps my linux server. But it appears to be that asyncio waits for other tasks.
Here is my code:
import asyncio
from pydantic import BaseModel

class UserClientWebSocket(BaseModel):
    id: str
    ws: WebSocket

    class Config:
        arbitrary_types_allowed = True

class ConnectionManager:
    def __init__(self):

        self.active_user_client_connections: List[UserClientWebSocket] = []
        self.collect_user_IDs = []

async def connect_the_user_client(self, websocket: WebSocket, THE_USER_ID):
    await websocket.accept()
    await self.send_message_to_absolutely_everybody(f"User: {THE_USER_ID} connected to server!")
    print("User: {} ".format(THE_USER_ID) + " Connected")
    if THE_USER_ID not in self.collect_user_IDs:
        self.collect_user_IDs.append(THE_USER_ID)
    else:
        await self.send_message_to_absolutely_everybody(f"Somebody connected with the same ID as client: {THE_USER_ID}")
        await self.send_message_to_absolutely_everybody("but Vlori is a nice and kind guy, so he wil not get kicked :)")
        self.collect_user_IDs.append(THE_USER_ID)
    self.active_user_client_connections.append(UserClientWebSocket(ws=websocket, id=THE_USER_ID))
    await self.show_number_of_clients()

async def function_one_send_message_to_absolutely_everybody(self, message: str):
    try:
        await asyncio.sleep(2)
        await asyncio.gather(*(conn.ws.send_text(message) for conn in self.active_webpage_client_connections))
        await asyncio.gather(*(conn.ws.send_text(message) for conn in self.active_user_client_connections))
    except:
        print("waiting")

async def function_two_send_personal_message_to_user(self, message: str, websocket: WebSocket):
    try:
        await websocket.send_text(message)
    except:
        print("waiting for task..")

...
...
...
...
...
and further down is the channel in which client connects:
@app.websocket("/ws/testchannel")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()

    try:
        while True:
            data = await websocket.receive_text()
            print_result = print("Received data: {} ".format(data))

            send_data_back_to_user = await websocket.send_text(f"you sent message: {data}")

    except WebSocketDisconnect as e:
        print("client left chat, error = ", e)

The code as it stands now works perfectly, and the performance is good! However, if i add an async def function under the "send_data_back_to_user" line such as this:
await connection_manager.function_one_send_message_to_absolutely_everybody(data)

Then there is a huge latency! why is that?
I am playing around and tried this:
@app.websocket("/ws/testchannel")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    try:
        while True:
            data = await websocket.receive_text()
            print_result = print("Received data: {} ".format(data))

            send_data_back_to_user = await websocket.send_text(f"you sent message: {data}")   # if i comment this line and the line underneath, and the speed is extremely fast!

            the_asyncio_loop = asyncio.get_event_loop()

            print_data_on_terminal = asyncio.gather(print_result)
            return_data_back_to_user = asyncio.gather(send_data_back_to_user)
            broadcast_msg = asyncio.gather(connection_manager.function_one_send_message_to_absolutely_everybody(data))

            run_all_loops_together = asyncio.gather(print_data_on_terminal, return_data_back_to_user, broadcast_msg)

            results = the_asyncio_loop.run_until_complete(run_all_loops_together)

            print(results)

    except WebSocketDisconnect as e:
        print("client left chat, error = ", e)

but gives me the error:
TypeError: An asyncio.Future, a coroutine or an awaitable is required

could someone help me with this?
thanks.


text:
Q: Using SignedJwtAssertionCredentials on Python Google App Engine Used the code snippet below to edit cells of a spreadsheet on my google drive account. This works when i run the code from my python IDE (Not on google app engine).
import webapp2
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
import json
from httplib2 import Http
from gspread.exceptions import CellNotFound
import os

# folder = os.path.dirname(os.path.realpath(__file__))
# file_path = os.path.join(folder, 'clientkey.json')
json_key = json.load(open('clientkey.json'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
googleClient = gspread.authorize(credentials)

On copying same code to my google app engine project which i am to deploy, it shows the error below.
    Traceback (most recent call last):

  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 240, in Handle

    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())

  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 299, in _LoadHandler

    handler, path, err = LoadObject(self._handler)

  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 85, in LoadObject

    obj = __import__(path[0])

  File "C:\Users\CrowdStar\workspace\AppEngineThinkStudio\DominicProject\main.py", line 3, in <module>

    from oauth2client.client import SignedJwtAssertionCredentials

  File "C:\Users\CrowdStar\workspace\AppEngineThinkStudio\DominicProject\oauth2client\client.py", line 34, in <module>

    import six

ImportError: No module named six

I added the module required, it throw an error saying another module is required. Kept on adding the required modules and it keep on throwing error to add other module. Have added over 8 modules just to make it work and it still saying some modules an not be found even while it works well outside appengine. How do i fix this.

A: I see this is and older question but unanswered and still getting views. This will happen if you only install the client library to your system site-packages like this:
pip install --upgrade google-api-python-client

To vendor the library along with all its required dependencies into your app's directory in one go, so that they will be uploaded along with your application, use the '-t' flag:
pip install google-api-python-client -t /myappdir


text:
Q: Git Pull from a Forked Repository I recently forked a repository.  The repository has been updated and I would like to have the updated version. When I git pull, does it pull from my repository on github? Or will it pull from the forked repository?
From my understand when I fork I have access to 3 versions of the repository.

*

*On my local machine.

*My forked version on my personal github repository

*The repository that I forked from.

So if I git pull from my local machine, will that pull from my personal repository where the project is forked, or will it pull from the project repository where everyone is working from?
**I cloned the repository to my local machine by git clone [https link] (my own forked version).
**I'm in the process of trying to find the rest of the information Wooble requested, thanks for the suggestions! I will try to get that information asap.
Thanks!

A: You will have remotes to both your forked repository and the original repository you forked from. Run git remote -v to see a list of remotes available.
You can choose to pull from the listed remotes:
git pull <remote_name> <branch_name>

Doing a git pull will pull from your default remote, which in your case is your repository not the original one.


text:
Q: Pandas counter as a new column I'm trying to build a dataframe in which I'm gonna build a timeline chart. On the X-axis I'm gonna have the dates and on the Y-axis I'm gonna have the amount if a specific ID.
Here is my attempt:
import pandas as pd
import numpy as np

file = ('test31.csv')

df = pd.read_csv(file)
df = df[['ID', 'Created Date', 'Finished Date']]

df.head()

Output:

ID        Created Date      Finished Date

XY11           2020-07-21          2020-07-23
AA12           2020-07-17          2020-07-28
AA12           2020-07-15          2020-07-20
AA12           2020-07-15          2020-07-23
XY11           2020-07-13          2020-07-22

Now I'm gonna count how many ID's was created one a specific date.
x = df.groupby(['ID', 'Created Date'])['Created Date'].size().to_frame('size1')
print(x)

Output:

ID             Created Date        size1

XY11           2020-07-21          1
XY11           2020-07-13          1

AA12           2020-07-15          2
AA12           2020-07-17          1

What I'm lacking here is the counter column, which should increase as new ID's are created.
After I've managed to do that, I'm gonna subtract the Finished Date counter and build a timeline based on that. Perhaps there is an easier way for this but this is the plan I got at the moment.
Wanted output:

ID             Created Date        size1          counter

XY11           2020-07-21          1              1
XY11           2020-07-13          1              2
XY11           2020-08-14          5              7

AA12           2020-07-15          2              2
AA12           2020-07-17          1              3

EDIT:
I'm probably gonna have to sort by date, but that's a problem for later.
UPDATE:
With some help from the community I now got this:
x = df.groupby(['ID', 'Created Date'])['Created Date'].size().to_frame('size1')
y = df.groupby(['ID', 'Finished Date'])['Finished Date'].count().to_frame('size2')

x['counter1'] = x.groupby('ID').size1.cumsum()
y['counter2'] = y.groupby('ID').size2.cumsum()

print(x)
print(y)

x Output:

ID             Created Date        size1          counter1

XY11           2020-07-21          1              1
XY11           2020-07-13          1              2
XY11           2020-08-14          5              7

AA12           2020-07-15          2              2
AA12           2020-07-17          1              3

y Output

ID             Finished Date       size2          counter2

XY11           2020-07-28          1              1
XY11           2020-09-13          4              5
XY11           2020-08-14          1              6

AA12           2020-10-15          6              6
AA12           2020-11-17          2              8

How can I subtract counter1 with counter2 only where the date matches?

A: Is this what you're looking for?
x['counter'] = x.groupby('ID').size1.cumsum()
print(x)

Output
     ID Created Date  size1  counter
0  XY11   2020-07-21      1        1
1  XY11   2020-07-13      1        2
2  AA12   2020-07-15      2        2
3  AA12   2020-07-17      1        3


text:
Q: First AutoCompleteTextView drop-down menu does not appear I have two AutoCompleteTextView:
AutoCompleteTextView textViewFrom = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextViewFrom);
MyAdapter myAdapter = new MyAdapter(this, android.R.layout.simple_dropdown_item_1line, Direction.FROM);
textViewFrom.setAdapter(myAdapter);

AutoCompleteTextView textViewTo = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextViewTo);
MyAdapter myAdapter2 = new MyAdapter(this, android.R.layout.simple_dropdown_item_1line, Direction.TO);
textViewTo.setAdapter(myAdapter2);

Why do I have a drop down menu is presented only in the second AutoCompleteTextView?
MyAdapter class:
http://pastebin.com/DwxdrTN6


text:
Q: How to make image_tag hyperlink using link_to in Rails, with mouseover? I am placing *image_tag* images within *link_to* elements, as well as trying to do a mouseover image swap. It's all working except for the mouseover, which is not grabbing the alternate image. On a more general note, am I doing hyperlinked images correctly? Sorry, new to Rails. Much appreciated!
<%= link_to (image_tag("#{product.prod_img}.jpg", alt: product.prod_name, class: 'img_prod_thumb', mouseover: "#{product.prod_img}_over.jpg")), "/products/#{product.id}" %>

A: Couple of pointers:

*

*Don't dynamically add img extensions to your code (esp. in the view) unless there is a very good reason to do so(?)

*You can use simple product as the path, instead of a hardcoded url

Here's what I'd do:
>>> move product image name construction to the model, helper, or decorator
# model (for simplicity)

def prod_img_full
  "#{prod_img}.jpg"
end

def prod_img_over
  "#{prod_img}_over.jpg"
end

>>> update and clean up link_to

<%= link_to image_tag(product.prod_img_full,
            alt: product.prod_name,
            class: 'img_prod_thumb',
            mouseover: product.prod_img_over),
            product %>

You could easily move the image_tag to a decorator, which would allow this within your views:
<%= link_to product.hover_image, product %>


text:
Q: Java time in GMT I have a Grails application with the following code:
Date now = Calendar.getInstance().getTime() //Also tried new Date()
println "now: " + now

When I do this, I get now: Thu Aug 18 12:47:09 CDT 2011. I need the date to be in GMT, not local time because I need to store the GMT time in a database. I can use a simpleDateFormat object to print out the time in GMT, but I need to actually store it as GMT.
Question: How do I convert a Date object to a Date object using GMT?

A: This accentuates why Java sucks at time. The previous posts are all close, but we need to be very careful about getting the current time in GMT, and getting the current time in CDT and calling it GMT.
TimeZone reference = TimeZone.getTimeZone("GMT");
Calendar myCal = Calendar.getInstance(reference);

This is the current time in GMT, with a timezone context of GMT.
To convert to a Date object which keeps the zone intact you'll need to call:
TimeZone.setDefault(reference);

This setting will last as long as your current JVM. Now calling get Time should produce the desired result.
myCal.getTime();

A: Well, if you really want time in GMT, you need to get it as GMT (@jpredham is right. Kudos to you! Editing my post to reflect this)
So do the following
//this option uses TimeZone
TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");
TimeZone.setDefault(gmtTimeZone);
Calendar calendar = Calender.getInstance(gmtTimeZone);

Date myDate = calendar.getTime();

A: Try this:
println Calendar.getInstance(TimeZone.getTimeZone('GMT')).format('HH:mm:ss')

Note that when you convert to a date, you lose the timezone information.  When Java/Groovy formats your Date for printing, it automatically formats it for your local timezone.  Don't worry, your date doesn't have a timezone associated with it.  You can add the proper timezone back in when you display it like so:
Date now = Calendar.getInstance(TimeZone.getTimeZone('GMT')).time
def formatter = new java.text.SimpleDateFormat('HH:mm:ss')
formatter.timeZone = TimeZone.getTimeZone('GMT')
println formatter.format(now)

A: Internally a Calendar object stores the time in UTC (the modern name for GMT).  getTimeInMillis() returns a UTC value, and is probably what you want to store.

A: You should try GregorianCalendar#setTimeZone(TimeZone timeZone).

A: Using System.currentTimeMillis() is not only much faster than using Calendar or Date, it always gives you the GMT time. If you want to display this time, you can use SimpleDateFormat, setting the time zone to what ever you want.

A: You are confusing  date-time object with its string representation. All common date-time libraries in Java (java.util.Date, Joda-Time, java.time in Java 8) internally track a fractional number of seconds since the first moment of 1970 in UTC while ignoring leap seconds. So in all three libraries, the date-time is internally always in UTC/GMT.
So your question of how to convert a Date object to a Date object in GMT (UTC) makes no sense.
The two better libraries (Joda-Time and java.time) also track a time zone inside the date-time object. The notoriously troublesome java.util.Date has no time zone assigned yet confusingly applies the JVM's current default time zone when it's toString method is invoked.
For the record, Joda-Time makes short work of this.
DateTime nowUtc = DateTime.now( DateTimeZone.UTC );

Calling that object's toString method generates a string in ISO 8601 format in Zulu (UTC) time.
Search StackOverflow for "Joda" and "formatter" to find many examples of adjusting to other time zones.

A: tl;dr
Instant.now()    // Capture current moment in UTC.
    .toString()  // Generate a String object in standard ISO 8601 format, YYYY-MM-DDTHH:MM:SS.SSSSSSSSSZ.

2018-02-16T23:28:01.101324Z

java.time
The modern approach uses java.time classes. Avoid the troublesome legacy date-time classes entirely.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ;  // Capture the current moment in UTC.

Generate a string in standard ISO 8601 format by calling toString.
String output = instant.toString() ;

If you need more flexibility than Instant provides, such as formatting while generating strings, use OffsetDateTime with the constant ZoneOffset.UTC.
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;  // Capture the current moment in UTC.

To generate strings in non-standard formats, use a DateTimeFormatter.

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, and later

*

*Built-in.

*Part of the standard Java API with a bundled implementation.

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android bundle implementations of the java.time classes.

*For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


text:
Q: When minimax theorem does not hold: counterexample of absence of convexity I know that the conditions to have that
$\min_{y\in Y} \max_{x\in X} f(x,y)=\max_{x\in X} \min_{y\in Y} f(x,y)$
are that $X,Y$ are compact and convex subsets of the product of reals and that $f$ is continuous and quasi-concave on $y$ and quasi-convex on $x$. I am trying to find particular cases in which I violate one of the conditions and get an inequality.
In particular, I am struggling to find $X$ or $Y$ not convex such that for $f: X\times Y \rightarrow R$, continuous, quasi-concave on $y$ and quasi-convex on $x$,
$\min_{y\in Y} \max_{x\in X} f(x,y)\neq \max_{x\in X} \min_{y\in Y} f(x,y)$.
I think my issue is probably related to a misunderstanding of the theorem (I can prove it but cannot check its conclusion).

A: Take a set $X$ with just two points. On $X\times X$ define $f(x,y)=1$ if $x=y$ and $0$ otherwise. This is example where min and max cannot be switched but $f$ is continuous.


text:
Q: X11 Frwarding Error while trying to run a Java Utility with GUI I am trying to run a java utility on a UNIX Server through PuTTY. This JAVA utility launches a GUI. When I run this utility using the following command
./DAVTree.sh

I get the following Error
    Exception in thread "main" java.awt.HeadlessException:
    No X11 DISPLAY variable was set, but this program performed an operation
    which requires it.

    at java.awt.GraphicsEnvironment.checkHeadless(Unknown Source)
    at java.awt.Window.<init>(Unknown Source)
    at java.awt.Frame.<init>(Unknown Source)
    at java.awt.Frame.<init>(Unknown Source)
    at javax.swing.JFrame.<init>(Unknown Source)
    at com.sas.services.webdav.tools.DAVTree.<init>(DAVTree.java:319)
    at com.sas.services.webdav.tools.DAVTree.main(DAVTree.java:944)

I searched on the internet for the problem its something called X11 Forwarding don't know what that is but I followed the suggestions by googling so I created a new session with PuTTY and under
Connection > SSH > X11 checked yes the Enable X11 Forwarding

Now when I run the utility again the error\exception message has changed it now says.
Exception in thread "main" java.lang.InternalError: Can't connect to X11 window

server using 'localhost:10.0' as the value of the DISPLAY variable.

at sun.awt.X11GraphicsEnvironment.initDisplay(Native Method)
at sun.awt.X11GraphicsEnvironment.access$100(Unknown Source)
at sun.awt.X11GraphicsEnvironment$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.awt.X11GraphicsEnvironment.<clinit>(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(Unknown Source)
at java.awt.Window.init(Unknown Source)
at java.awt.Window.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at javax.swing.JFrame.<init>(Unknown Source)
at com.sas.services.webdav.tools.DAVTree.<init>(DAVTree.java:319)
at com.sas.services.webdav.tools.DAVTree.main(DAVTree.java:944)

Now it says that no DISPLAY variables is set. So I try this
export DISPLAY=kcsclm92:7001

kcsclm:7001 would be my server. After this when I run the utility it gives the same error only with the following difference
Exception in thread "main" java.lang.InternalError: Can't connect to X11 window

server using 'kcsclm92:7001' as the value of the DISPLAY variable.

I was already working in blind after this I have nothing more to try. Please help.
p.s. (for those who know SAS)I have SAS deployment on a UNIX server and I am trying to run the DAVTree Utility.

A: You need an X "server" running on your local Windows machine. (Yes, the terminology is confusing). Try http://mobaxterm.mobatek.net/
Note, the correct DISPLAY setting will be created by Putty automatically, so don't change it (localhost:10 sounds about right).


text:
Q: Can I set and get flags on Linux using my Rust application? I am building a rust application, when the application is running, I want to set an OS level flag (an ENV variable) saying.. MY_CUSTOM_APP_RUNNING=true and set it to false when application stops!
Also, My application has 3 different features, I want my application to listen to the flag changes.
For example, if I run export MY_CUSTOM_APP_FEATURE_1=enable, my application should listen to this change.
Are these 2 things possible?
How should I approach to do this?
It would be a cherry on top, if I could do this for all OS!

A: No. Environment variables are scoped to each individual process and cannot be changed externally, meaning your program cannot update its parent's process's variables, nor can the parent update your program's variables after it was launched.
I can conceive of some hacky ideas to get vaguely to what you want, but that wouldn't be helpful. Environment variables are not the mechanism of choice to communicate with a live program. You should opt for pipes/sockets or file-monitoring.


text:
Q: How do I change the Template Layout for the Customer 'My Account' page? This might be very basic...
I need to change the Template Layout for the "My Account" page
It is currently using:
frontend/mypackage/mytheme/template/page/2columns-left.phtml
And I need to change it to:
frontend/mypackage/mytheme/template/page/1column.phtml
I can't see any way to change it... I don't even know which file the template is defined. It might be using the 'default' setting - but I don't know where that is populated. Please help :)

A: It seems you are using a theme. It might have it's own XML to define layouts or not, since i dont know the theme i cant tell you. But the most normal way to do this is to open customer.xml in the layout folder of your theme and  find the path to the My account page (customer_account_index) and change your layout from there.
See this, it is very similar to your question and might help you.


text:
Q: Determinant from matrix of logarithms Is there a way to get the determinant $\text{Det}(M)$ of a matrix $M$ from the matrix of its logarithms, i.e.
$\Bigg(
\begin{smallmatrix}
\log(M_{00}) & \log(M_{01}) & \ldots \\
\log(M_{10}) & \log(M_{11}) &  \\
\vdots
\end{smallmatrix}\Bigg)\ \ \ \ ?
$
Note that I don't mean the actual matrix logarithm; then I could use the second identity in this question.
EDIT: I mean if there is a faster way than exponentiating the elements and computing the determinant from scratch.


text:
Q: How to get all possible combinations of the number if we have divide the number in equal number of groups Suppose we 6 balloons. we only can make the groups as follows:

*

*a group of 3 balloons in each group : total 2 groups

*a group of 2 balloons in each group : total 3 groups

*a group of 1 balloon in each group :  total 6 groups

Suppose we 10 balloons. we only can make the groups as follows:

*

*a group of 5 balloons in each group : total 2 groups

*a group of 2 balloons in each group : total 5 groups

*a group of 1 balloon in each group :  total 10 groups

I am not able to write a C language code for it.

A: With this code, you will be able to display all the divisors of your number :
int main()
{
long int n,i;
cout<<"Enter the number: ";
cin>>n;
cout<<endl<<"Divisors of "<<n<<" are";

for(i=1;i<=n;++i)
{
if(n%i==0)
cout<<" "<<i;
}

return 0;
}


text:
Q: Prove $\{12a+25b:a,b\in\mathbb{Z}\}=\mathbb{Z}$
Prove $\{12a+25b:a,b\in\mathbb{Z}\}=\mathbb{Z}$.

My approach
Proof: Since, the only prime factors of $12$ are $2$, and $3$ and the only prime factors of $25$ are $5$, the $\gcd(12,25)=1$. Thus, by Bezout's lemma, 1=12x+25y for some $x,y\in\mathbb{Z}$. Now, for all $c\in\mathbb{Z}$,
  \begin{align*}
      c(12x+25y)&=1(c)\\
      12(xc)+25(yc)&=c\\
  \end{align*}
    Thus, by closure of the set of integers under integer addition and multiplication,$xc,yc\in\mathbb{Z}$. Thus, $12(xc)+25(yc)=12a+25b=c$ for some $a,b\in\mathbb{Z}$, namely, $a=cx$ and $b=cy$. Therefore,  $12a+25b=\mathbb{Z}$, since $c$ is any integer.
This was wrong but can you help show me why?
The reason it is wrong is because this only shows its a subset  of the integers not equal to them. I don't quite see that but would appreciate a full proof.

A: In general your proof is correct, but there are some minor mistakes. When you want to prove that two sets $A$ and $B$ are the same you have to prove that $A\subseteq B$ and $B\subseteq A$.
Let $X=\{12 a + 25 b : a, b \in \mathbb{Z}\}$. So, if $x\in X$, $x=12a+25b$ for some $a, b\in \mathbb{Z}$, then "by closure of the set of integers under integer addition and multiplication" you have $x\in \mathbb{Z}$, therefore $X\subseteq \mathbb{Z}$. On the other hand, suppose $c\in \mathbb{Z}$, we want to show that $\mathbb{Z}\subseteq X$. In order to do that we have to prove that $c\in X$. Since $12(-2)+25(1)=1$, multiplying by $c$ last equality gives us $c(12(-2)+25(1))=c$, then $12(-2c)+25(c)=c$. So if we put $a=-2c$ and $b=c$ we get $12a+25b=c$ and thus $c\in X$. This proves $\mathbb{Z}\subseteq X$. Hence $X=\{12 a + 25 b : a, b \in \mathbb{Z}\}=\mathbb{Z}$.

A: The core of your proof is fine, except for maybe some trivialities to tie the whole thing together. Given $c \in \mathbb Z$, you show that there are $a, b \in \mathbb Z$ such that $12 a + 25 b = c$. Hence $c \in \{ 12 a + 25 b : a, b \in \mathbb Z \}$, so $\mathbb Z \subseteq \{ 12 a + 25 b : a, b \in \mathbb Z\}$. The reverse inclusion holds trivially, hence both sets are equal.


text:
Q: React-Bootstrap - How to create rows of 4 cards each? how do I set the number of cards per row? I need 4 cards to be in one row of mine.
I have been trying for hours.. can't figure out what i do wrong..
I was getting all sorts of errors when i played around with this.
like this one :
here
my package.json file:

thanks!
:)
import { React } from 'react';
import { Card, Button, CardGroup } from 'react-bootstrap';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';

const MyDishes = props => {
    const { dishes } = props;

    return (
        <CardGroup style={{display: 'flex', flexDirection: 'row'}}>
            {dishes.length > 0 &&
                dishes.map(d => (
                    <Row xs={1} md={2} className="g-4">
                    {Array.from({ length: 4 }).map((_, idx) => (
                    <Col>

                    <Card key={d.id} style={{ width: '100em' }} style={{flex: 1}}>
                        <Card.Img variant="top" src={d.attributes.picture} />
                        <Card.Body>
                            <Card.Title>{d.attributes.name}</Card.Title>
                            <Card.Text>Possibly some text here</Card.Text>
                            <Link to={`/dishes/${d.id}`}>
                                <Button variant="primary">Full Recipe</Button>
                            </Link>
                        </Card.Body>
                    </Card>
                    </Col>
                ))}
                </Row>
        </CardGroup>
    );
};

const mapStateToProps = state => {
    return {
        dishes: state.myDishes
    };
};

export default connect(mapStateToProps)(MyDishes);

i get this error now :

A: *

*To use bootstrap layout system, must use <Container> to wrap <Row> and <Col>

*You don't need custom styles to achieve that you want.
import { React } from 'react';
import { Container, Card, Button, CardGroup } from 'react-bootstrap';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';

const MyDishes = props => {
    const { dishes } = props;

    return (
        <Container>
            {dishes.length > 0 &&
                dishes.map(d => (
                    <Row xs={1} md={2} className="g-4">
                    {Array.from({ length: 4 }).map((_, idx) => (
                    <Col>
                    <Card key={d.id}>
                        <Card.Img variant="top" src={d.attributes.picture} />
                        <Card.Body>
                            <Card.Title>{d.attributes.name}</Card.Title>
                            <Card.Text>Possibly some text here</Card.Text>
                            <Link to={`/dishes/${d.id}`}>
                                <Button variant="primary">Full Recipe</Button>
                            </Link>
                        </Card.Body>
                    </Card>
                    </Col>
                ))}
                </Row>
              ))}
        </Container>
    );
};

const mapStateToProps = state => {
    return {
        dishes: state.myDishes
    };
};

export default connect(mapStateToProps)(MyDishes);


text:
Q: Display special products in every category, showing only products related to that category Is it possible to display special products in every category, showing only products that are related to that category? For example, if category is "Nokia", show specials that are only under Nokia, and do not display other specials.
Same for featured products also.
Is it possible? If possible, can you please explain how to do it so that a beginner can understand it? I'm using OpenCart 1.5.3.1.

A: Alright, here is something to get you started. I am using Opencart 1.5.5.1.
In catalog/controller/module/special.php find this line towards the end:
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/special.tpl')) {

Before, add this code (I hope my comments make it clear enough):
// filter specials by current category code - - - - - - -

/* check wether current page is a category page (i.e. has 'path' var) */
if (isset($this->request->get['path'])) {

    /* get category ID from path (last number) */
    $parts = explode('_', (string)$this->request->get['path']);
    $category_id = (int)array_pop($parts);

    /* loop through products */
    foreach ($this->data['products'] as $k => $item){
        /* check whether this product is assigned to current category */
        $sql = "SELECT * FROM " . DB_PREFIX ."product_to_category WHERE product_id = ". $item['product_id']. " AND category_id = ".$category_id;

        $query = $this->db->query($sql);

        /* if no match found, remove this item */
        if (count($query->rows) == 0){
            unset ($this->data['products'][$k]);
        }

    }
}

// end of filter specials by current category code - - - -

A: Just needed this myself, here's my solution, you need to modify catalog/model/catalog/product.php and catalog/controller/module/special.php. I recommend VQMod to do this:
in product.php replace
$sql = "SELECT DISTINCT ps.product_id, (SELECT AVG(rating) FROM " . DB_PREFIX . "review r1 WHERE r1.product_id = ps.product_id AND r1.status = '1' GROUP BY r1.product_id) AS rating FROM " . DB_PREFIX . "product_special ps LEFT JOIN " . DB_PREFIX . "product p ON (ps.product_id = p.product_id) LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) WHERE p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int)$this->config->get('config_store_id') . "' AND ps.customer_group_id = '" . (int)$customer_group_id . "' AND ((ps.date_start = '0000-00-00' OR ps.date_start < NOW()) AND (ps.date_end = '0000-00-00' OR ps.date_end > NOW())) GROUP BY ps.product_id";

with:
$sql = "SELECT DISTINCT ps.product_id, (SELECT AVG(rating) FROM " . DB_PREFIX . "review r1 WHERE r1.product_id = ps.product_id AND r1.status = '1' GROUP BY r1.product_id) AS rating".(isset($data['category_id']) ? ", (SELECT category_id FROM oc_product_to_category WHERE product_id = ps.product_id AND category_id = '".$data['category_id']."' GROUP BY category_id) as category" : "")." FROM " . DB_PREFIX . "product_special ps LEFT JOIN " . DB_PREFIX . "product p ON (ps.product_id = p.product_id) LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) WHERE p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int)$this->config->get('config_store_id') . "' AND ps.customer_group_id = '" . (int)$customer_group_id . "' AND ((ps.date_start = '0000-00-00' OR ps.date_start < NOW()) AND (ps.date_end = '0000-00-00' OR ps.date_end > NOW())) GROUP BY ps.product_id".(isset($data['category_id']) ? ",category HAVING category='".$data['category_id']."'" : "");

and in special.php: add
if (isset($this->request->get['path'])) {
    $parts = explode('_', (string)$this->request->get['path']);
    $data['category_id'] = (int)array_pop($parts);
}

before
$results = $this->model_catalog_product->getProductSpecials($data);


text:
Q: What is the significance of NCSU's double floating gate FET technology for the future of OS design? this is my first post, and I certainly hope that it's appropriate to the forum - I've been lurking for some time, and I believe that it is, but my apologies if this is not the case.
I presume that most if not all readers here have encountered the story regarding the discovery (popularization?) of "double floating gate FETs" by NCSU, which is being hailed as a potential "universal memory."
http://www.engadget.com/2011/01/23/scientists-build-double-floating-gate-fet-believe-it-could-revo/
I've been slowly digesting a wide range of material related to software development, including OS design (I am, perhaps obviously, strictly amateur), and given that one of the most basic functions that any OS performs is managing the ever-present exchange of data between perpetual storage and volatile memory, it strikes me that if this technology matures and becomes widely available, it would represent such a sea-change in the role of the OS that it would almost necessitate rewriting our operating systems from the ground up to make full use of its potential.  Am I correct in my estimation of the role of the OS, and in the potential ramifications of the new technology?  Or, have I perhaps failed to understand some critical distinction regarding the logical (as opposed to physical) relationships between processor, memory, and storage?

A: Until we know what it'll cost in mass production, it's impossible to say. Unless it can be made cheaply enough to replace hard drives, so you erase the distinction between "main memory" and "long term storage", the impact will be minimal. I'd be surprised to see that happen though.
Even if economics allowed that to happen, I doubt it really would. Some mobile devices already use identical (battery backed RAM) for main memory and long term storage. This would eliminate the battery-backing for the memory, but doesn't seem likely to impact OS design at all. Since (at least most) use the same battery for normal operation and maintaining long-term storage, this would simply mean and extra 10% (or whatever) life from the same battery -- but only if its normal operation required about the same power as normal RAM (which strikes me as unlikely -- most flash draws extra power when writing).


text:
Q: Array length doesn't match index

var index = 0;
var length = ["a", "b", "c", "d", "e"].length;
var interval = setInterval(function() {
 if (index < length) {
  console.log(index);
  console.log(length);
  index++;
 } else {
       clearInterval(interval);
    }
}, 1000);

How do i fix that? So it will clear interval on 5:5 not 4:5

A: You could check the incremented index after an output.
If index is greater or equal to length clear the interval.

var index = 0,
    length = ["a", "b", "c", "d", "e"].length,
    interval = setInterval(function() {
        console.log(index, length);
        if (++index >= length) {
            clearInterval(interval);
        }
    }, 1000);

A: hmmm

var index = 0;
var length = ["a", "b", "c", "d", "e"].length;
var interval = setInterval(function() {
 if (index < length) {
                ++index;
  console.log(index);
  console.log(length);
 } else {
       clearInterval(interval);
    }
}, 1000);

A: lenght give the quantitity. This is 5, but index starts with zero.

var index = 0;
var length = ["a", "b", "c", "d", "e"].length;
var interval = setInterval(function() {
 if (index < length) {
  console.log(index + 1);
  console.log(length);
  index++;
 } else {
       clearInterval(interval);
    }
}, 1000);

A: I guess this is all you need

var index = 0;
var length = ["a", "b", "c", "d", "e"].length;
var interval = setInterval(function() {
 if (index <= length) {
  console.log(index);
  console.log(length);
  index++;
 } else {
       clearInterval(interval);
    }
}, 1000);


text:
Q: App Config file - Ensure Custom Configuration Structure I have a library that reads from a custom section in app.config
Is there a proper way to ensure that when this library is used in a project, it creates the "skeleton" of its custom section if it's not provided?
I want to ensure that whenever this get's used, by whomever, they will be able to understand what they have access to configure without looking inside the library.
EDIT: In order to be more specific, here is an example app config with some explanation of what I'm trying to do
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>

    </configSections>
    <CustomSection SettingOne="My Setting"/>
</configuration>

That is an example of a section I would have created, knowing that SettingOne is a setting that works, and knowing about CustomSection and all of that.  What I would like to do, is have my CustomSection.dll file, when included and used in a project, update a config file to make sure CustomSection is available with some default settings.
The result I would like to be this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>

    </configSections>

    <CustomSection SettingOne="DEFAULT"/>
</configuration>


text:
Q: Deploy a GitHub branch automatically to AWS Elastic Beanstalk Say I have a branch stable on GitHub that I want to automatically deploy to my AWS EB instances when there is a commit.
I have looked at CodePipeline, which is not available in the region I am hosting my instances.
I have also looked at CodeDeploy but this appears to only be for a single instance of EC2 and not for Elastic Beanstalk. Please correct me if I am wrong.
All help is appreciated. I do not want to have to manually deploy every time a commit is made.

A: currently we are using jenkins ci for BDD .and jenkins custom aws-eb plugins automatically deploy your branch to elastic beanstalk. this might be help you and even this is the alternative for codepipeline to.

A: For anyone that stumbles on this, I would like to comment saying this is possible.

*

*You need to create an application on Elastic Beanstalk (This application should be based on the runtime environment of your code for example nodejs for an application built with nodejs, php for a php-application)

*Make sure to select the sample application provided by aws when creating a beanstalk application.

*This spins up an environment that runs that sample application (feel free to configure the environment the way you want)

*Launch the application and then create a new pipeline but be sure to select your source as GitHub in the pipeline (this enables your branch from github to be selected as the source)

*In the Deploy stage of the pipeline, be sure to select Elastic Beanstalk for deployment.

A well detailed explanation can be found here: https://medium.com/@faithfulanere/how-to-create-cicd-using-github-as-source-and-elastic-beanstalk-244319a2a350

A: One solution that you can try is use EB Deployer which automates the EB deployments. Here are some helpful links.
https://www.thoughtworks.com/insights/blog/ebdeployer-automate-your-deployments-aws-elastic-beanstalk
https://github.com/ThoughtWorksStudios/eb_deployer


text:
Q: Responsiver Sidebar Menu I'm quite new to jQuery and I would like to change the following code that it fits my needs:
  $(document).ready(function() {
  var slider_width = $('.pollSlider').width(); //get width automaticly
  $('#pollSlider-button').click(function() {
    if ($(this).css("margin-right") == slider_width + "px") {
      $('.pollSlider,#pollSlider-button').animate({
        "margin-right": '-=' + slider_width
      });
    } else {
      if (!$(this).is(':animated')) //perevent double click to double margin
      {
        $('.pollSlider,#pollSlider-button').animate({
          "margin-right": '+=' + slider_width
        });
      }
    }
  });
});

https://jsfiddle.net/3okensLj/1/
It is working quiet good but a problem appears when I'm resizing the window under 500px:
When I'm clicking onto the button (?) the menu appears. If I close the menu and enlarge the window the menu and the button has disappeared and I've got a problem. How can I avoid this?
I would like to change the code, that it adds a new class to the Menu container acording to the windows size but keeping the functinality of the button.

A: Sorry, I dont know how to fix your code in a better way without using js $(window).resize
add this to your js
 var pollSlider = $("#sidebar");
$(window).resize(function(){
    if ($(window).width() > 500) {
        if (!pollSlider.hasClass("marginFixed")) {
            $("#sidebar").addClass("marginFixed");
        }
    } else {
        if (pollSlider.hasClass("marginFixed")) {
            $("#sidebar").removeClass("marginFixed");
        }
    }
})

and css
.marginFixed {
   margin-right: 0px !important;
}

you use js change your style which is not good and have to use !important to cover this
it can work but its bad code
and there is another way use css do this
use transition
.pollSlider {
    background: #fff none repeat scroll 0 0;
    height: 100%;
    line-height: 20pt;
    position: fixed;
    right: 0;
    top: 0;
    width: 450px;
    margin-right: 0px;
    -webkit-transition: margin-right 1s ease-in;
    transition: margin-right 1s ease-in;
}

.pollSlider.slideAni {
    margin-right: 0px;
}

js
$(document).ready(function () {

  $('#pollSlider-button').click(function () {
      $("#sidebar").toggleClass("slideAni");
 });
});

or use css animate with keyframe
    .pollSlider {
        background: #fff none repeat scroll 0 0;
        height: 100%;
        line-height: 20pt;
        position: fixed;
        right: 0;
        top: 0;
        width: 450px;
        margin-right: 0px;
        -webkit-animation-duration: 1s;
        animation-duration: 1s;
        -webkit-animation-fill-mode: both;
        animation-fill-mode: both;
      }
      .pollSlider.slideAni {
          animation-name: slideAni;
      }
  @-webkit-keyframes slideAni {
      from {
          margin-right: -450px;
      }
      to {
          margin-right: 0px;
      }
  }

  @keyframes slideAni {
      from {
          margin-right: -450px;
      }
      to {
          margin-right: 0px;
      }
  }

js
$(document).ready(function () {

  $('#pollSlider-button').click(function () {
      $("#sidebar").toggleClass("slideAni");
 });
});

but in this way you have to add other animate class to animate slide back, I just give you a way to try(I'm sure it will work)


text:
Q: Slope is independent of coordinates Let $y = m_1 x + b_1$, $y = m_2 x + b_2$ be two lines in $\mathbb R^2$. Then the expression $(m_2 - m_1)/(1 + m_1 m_2)$ is independent of coordinates. I tried to show this but failed:
Pick two points on line one: $p_1 = (0,b_1), p_2 = (1, m_1 + b_1)$. Assume these are the coordinates in an orthonormal basis $e_1', e_2'$. Assume $T = ( \begin{array}{cc} a & c \\ b & d\end{array} )$ is a basis coordinate transformation to an orthonormal basis $e_1, e_2$: $Te_1' = e_1, Te_2' = e_2$.
I computed the points with respect to $e_i$ as:
$p_1 = b_1 Te_2' = (\begin{array}{c} b_1 c \\ b_1 d\end{array})$
$p_2 =  Te_1' + (m_1 + b_1)Te_2'  = (\begin{array}{c} a + (m_1 + b_1)c \\ b + (m_1 + b_1)d\end{array})$
and then $m_1 = \frac{b + m_1 d}{a + m_1 c}$. Similarly for $m_2$.
Then I compute $(m_2 - m_1)/(1 + m_1 m_2) = \frac{[(m_2 -m_1)(ad - bc)][1 + m_1m_2]}{((a+m_1c)(a+m_2c))^2}$
These should be equal. What is my mistake? Thank you for correcting me.

A: The new slopes you computed look OK to me, but it looks as if something strange happened when you plugged them into $\frac{m_2-m_1}{1+m_1m_2}$.  The numerator and denominator of this expression will be unpleasant differences and sums of fractions, but all the fractions here can be put on a common denominator of $(a+m_1c)(a+m_2c)$. So this denominator will completely cancel out, and I don't see why you have its square in the denominator of your last formula.  I suspect you might have multiplied $m_2-m_1$ by $1+m_1m_2$  instead of dividing.
By the way, you could avoid a lot of algebra by remembering that the slope of a (non-vertical) line is the tangent of the angle that the line makes with the $x$-axis.  So, calling the angles $\theta_1$ and $\theta_2$, we have, thanks to a helpful trig identity,
$$
\frac{m_2-m_1}{1+m_1m_2}=\frac{\tan\theta_2-\tan\theta_1}{1+(\tan\theta_1)(\tan\theta_2)}
=\tan(\theta_2-\theta_1),
$$
which is the tangent of the angle between your two lines.  That angle doesn't change when you rotate your coordinate system, so its tangent is also unchanged.

A: EDIT: Sorry I thought you wanted to show that if the lines are perpendicular then $m_1m_2=-1$.
A nice proof of this fact goes as follows. Let $L_1$ and $L_2$ be two lines of slope $m_1$ and $m_2$ and suppose that the lines are perpendicular.
Translate their intersection to the origin and suppose without loss of generality that $m_1>0$ and $m_2<0$ (if one of these are zero rotate the plane through $\alpha$ such that both of the $m_i$ are non-zero). Now consider the points $o(0,0)$, $a(1,0)$, $p(1,m_1x)\in L_1$ and $q(1,m_2x)\in L_2$.
Consider the triangles $\triangle oap$ and $\triangle oaq$. Both are right-angled so we have:
$|op|^2=1+m_1^2$ and $|oq|^2=1+m_2^2$.
Now consider the right-angle triangle $\triangle opq$ and apply Pythagoras (note that $|aq|=-m_2$):
$|pq|^2=|op|^2+|oq|^2$
$\Rightarrow (m_1-m_2)^2=(1+m_1^2)+(1+m_2^2)$
$\Rightarrow m_1^2-2m_1m_2+m_2^2=2+m_1^2+m_2^2$
from whence it follows that $m_1m_2=-1$ $\bullet$


text:
Q: Translation of polygon after rotation I have two functions one that performs a rotation in 2D canvas item (polygon) and another that translate the 'robot'. The move is like this:
.
If a rotation is performed the movement should be like this:
.
Here the functions:
def rotation(self, i):
    if i == '+':
        if self.angle == 360:
            self.angle = 0.0
        self.angle += 1
        delta = radians(1)
    elif i == '-':
        if self.angle == 0:
            self.angle = 360.0
        self.angle -= 1
        delta = -radians(1)
    x0, y0 = self.center[0], self.center[1]
    tmp = list()
    pts = self.polygon
    for i in range(0, len(pts), 2):
        xa, ya = pts[i], pts[i + 1]
        xl, yl = xa - x0, ya - y0
        xll, yll = cos(delta) * xl + sin(delta) * yl, -sin(delta) * xl + cos(delta) * yl
        xr, yr = xll + x0, yll + y0
        tmp.append(xr)
        tmp.append(yr)
    self.polygon = tmp.copy()
    self.arena.coords(self.item_canvas, self.polygon)

def move_polygon(self, x, y, switch=False):
    tmp = self.polygon
    for i in range(0, len(tmp), 2):
        if not switch:
            tmp[i] += cos(radians(self.angle)) * x * 5
            tmp[i + 1] += -sin(radians(self.angle)) * y * 5
        else:
            tmp[i] += -sin(radians(self.angle)) * x * 5
            tmp[i + 1] += cos(radians(self.angle)) * y * 5
        print('x:{} y:{}'.format(cos(radians(self.angle)), -sin(radians(self.angle))))
    self.polygon = tmp.copy()
    self.update_polygon()

def move(self, dir):
    if dir == 'f':
        x, y = cos(radians(self.angle)), sin(radians(self.angle))
        self._move_polygon(x, y)
    if dir == 'b':
        x, y = -cos(radians(self.angle)), -sin(radians(self.angle))
        self._move_polygon(x, y)
    if dir == 'l':
        x, y = -sin(radians(self.angle)), -cos(radians(self.angle))
        self._move_polygon(x, y, True)
    if dir == 'r':
        x, y = sin(radians(self.angle)), cos(radians(self.angle))
        self._move_polygon(x, y, True)

The idea is passing the variation of x and y in function of the angle to the translation function (move_polygon). When the angle is zero the movement is right (only in the 1st and 3th quadrant, with directions reversed...).
I know that I need to add the x and y offset to perform the translation but the relation with the angle, center and the rotated axis is confusing and frustrating. So I need help to understand the math and the right way to perform this task.

A: So robot has own direction self.angle and you want to move robot in this direction, in back direction, and shift it (like strafe in shooter games?) left and right?
In this case you need to change signs in move:
 if dir == 'l':
      x, y = sin(radians(self.angle)), -cos(radians(self.angle))
      self._move_polygon(x, y, True)
 if dir == 'r':
      x, y = -sin(radians(self.angle)), cos(radians(self.angle))

But why do you apply cos and sin factors again inside move_polygon?? It seems you just need to update coordinates with provided shifts (using velocity coefficient) like this:
 tmp[i] += x * 5
 tmp[i+1] += y * 5

Also remove True as switch parameters


text:
Q: get values of all variables in class in Python Say I have a class that has 100 variables in it that each have values. How would I go about getting each of those values without having to know the name of the variable. For example:
class Stuff():
    a = 1
    b = 2
    c = 3
    d = 9.36
    e = "f"
    #and so on...

for i in dir(Stuff):
    print(Stuff.i)    #Does not work but it's what I want to achieve


text:
Q: What are some good resources on doing text-to-speech in .NET? Can anybody help me with Text to Speech Engine in C#

A: Microsoft Speech SDK
http://msdn.microsoft.com/en-us/library/aa920210.aspx
Just for simple t2s, it should be very simple, like
SpVoice objSpeech = new SpVoice();
objSpeech.Speak("Hello world",SpeechVoiceSpeakFlags.SVSFlagsAsync);
objSpeech.WaitUntilDone(Timeout.Infinite);


text:
Q: Create a world that would reset I'm making my first server to play with some friends, and I was wondering:
I have a world called Tuto to train new players to move, fight, eat, hunt... and in the end, a portal for another world. My point would be that everytime a player loads the world Tuto for the firt time, he finds it the way I built it, and not the way the previous persons left it.
Another way to see this is: how can I prevent the server to save the changes made in my Tuto world once the players left it?

A: Well, Minecraft does save changes on the fly, not when player leaves the map. So you need to have some backup and when the world is unloaded, replace old map with your backuped one.
For Spigot/bukkit servers there are some plugin tools (used especially for "automatic mines" or minigames, AFAIK MineResetLite can be example, or WorldEdit with Schematic files, or Map Reset), but for vanilla server/singleplayer you need to use commandblocks and area replacing - for that you have to have two copies of area and replace one by another via commandblock, but that really depends on area size (and expects closed area of course), for bigger ones it can heavily overload or crash the server...
And I really don't know how you deal with multiple players starting at same time? Do they share the area?
If I would want to achieve your needs, I would aim for something like "daily resets", because that would be easier than reset after every player leaves the map (and more server friendly).
That can be achieved by script replacing map files from backuped folder on server restart (that you still do daily, don't you?), however you need to be sure players leave the area or they might get stuck.
With spigot/bukkit you can try to find some plugin for it, there are probably some around.


text:
Q: Google Tag Manager Custom Template Sandboxed Javascript Problem I have created a custom template using  google tag manager,  however I am having some difficulty in getting my sandboxed javascript to work,  I know that the script is injected correctly becuase the following

log('Cotaylitcs: Script loaded successfully.');

outputs to the console.  I'm just not able to call my functions.  I have included the JS code as well.
Custom Template Code (Sandboxed Javascript)
// Enter your template code here.
const log = require('logToConsole');
const injectScript = require('injectScript');
const copyFromWindow = require('copyFromWindow');
const callInWindow = require('callInWindow');
const callLater = require('callLater');
const setInWindow = require('setInWindow');

const key = "testing";
const value = "test2";
const url = 'https://api.deve/cotalytics/cotalytics.js';

// If the script loaded successfully, log a message and signal success
const onSuccess = () => {
  log('Cotaylitcs: Script loaded successfully.');

  const cotalytics = copyFromWindow('cotalytics');
  log(cotalytics);
  callInWindow('cotalytics.addEvent',"testing12" ,{key: value}, "{{DL - cottageCode}}");
  callInWindow('cotalytics.logEvents()');
  data.gtmOnSuccess();
};

// If the script fails to load, log a message and signal failure
const onFailure = () => {
  log('Cotaylitcs: Script load failed.');
  data.gtmOnFailure();
};

injectScript(url, onSuccess, onFailure, 'cotalytics');

My Javascript code that is injected by Sandboxed Js:

let Cotalytics = function(){
    this.init();
};

// Init
Cotalytics.prototype =
{
    init: function () {

        var cotalytics = this;

        // Argument Assignment
        //cotalytics.endpoint           =  'https://localhost:44301/api/events/',
        //cotalytics.async              =  true,
        //cotalytics.debug              = true,
        //cotalytics.events             = {}

        //creat cookie here

        return cotalytics;
    },
      // Add Interaction Object Triggered By Events to Records Array
    addEvent: function (eventType, data, cottageCode, brandid) {
        data = data || {};
        cottageCode = cottageCode || null;

        data.Browser = window.navigator.appVersion;

        var cotalytics  = this;

            // cotalytics Object
            cotalytics.events     = {
                timestamp       : new Date(),
                cottagecode     : cottageCode,
                type            : eventType,
                ipaddress       : "127.0.0.1",
                requesturl      : window.location.href,
                sessionid       : "1234567",
                brandid         : brandid,
                eventData  : Object.keys(data).map(function(key) { return {"key": key, "value": data[key]}})
            };

        // Log Interaction if Debugging

            //cotalytics.logEvents();
            //console.log("Session:\n", interactor.interaction);
            //var data =JSON.stringify(interactor)
           console.log("JSON:\n", JSON.stringify(cotalytics));

        return cotalytics;
    },
     // Gather Additional Data and Send Interaction(s) to Server
     logEvents: function () {

        var cotalytics  = this,
            // Initialize Cross Header Request
            xhr         = new XMLHttpRequest();

        // Post Session Data Serialized as JSON
        xhr.open('POST', 'https://localhost:44301/api/events/', true);

        xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
        var data = JSON.stringify(cotalytics.events);
        xhr.send(data);

        return cotalytics;
        }
};

window.cotalytics = new Cotalytics();

A: Okay, so it looks like you're mostly there, but there are a few things that aren't quite right.

*

*The use of {key: value} in the addEvent call. Whilst the value will be populated with your constant, the key won't be. I'm imagining that these will be dynamic variables, so why don't you have something like:

const kvp= {};
const key = "yourKey";
const value = "yourValue";
kvp[key] = value;

That will create the object with the key you want and not just "key".

*This line here won't work. you can't use container variables in a custom template.

callInWindow('cotalytics.addEvent',"testing12" ,{key: value}, "{{DL - cottageCode}}");
It looks like a dataLayer variable, so why don't you use the copyFromDataLayer API and try this?
const copyFromDataLayer = require('copyFromDataLayer');
const cottageCode = copyFromDataLayer('cottageCode');

*The logEvents callInWindow callInWindow('cotalytics.logEvents()'); doesn't need the brackets, it's just callInWindow('cotalytics.logEvents');.

The final code that I got working was:
const log = require('logToConsole');
const injectScript = require('injectScript');
const callInWindow = require('callInWindow');
const makeTableMap = require('makeTableMap');
const copyFromDataLayer = require('copyFromDataLayer');

const cottageCode = copyFromDataLayer('cottageCode');

//Create the Key Value Pair
const kvp = {};
const key = "testing";
const value = "test2";
kvp[key]=value;

const url = "https://api.deve/cotalytics/cotalytics.js";

// If the script loaded successfully, log a message and signal success
const onSuccess = () => {
  log('Cotaylitcs: Script loaded successfully.');
  callInWindow('cotalytics.addEvent',"testing12" ,kvp,cottageCode);
  callInWindow('cotalytics.logEvents');
  data.gtmOnSuccess();
};

// If the script fails to load, log a message and signal failure
const onFailure = () => {
  log('Cotaylitcs: Script load failed.');
  data.gtmOnFailure();
};

injectScript(url, onSuccess, onFailure, 'cotalytics');

Hopefully that helps, ask if you have any other questions!

A: I've managed to resolve this now.  I am still using the Custom template but I needed to add a new custom HTML tag that injected my .JS script into all pages after doing this my custom template tag worked.


text:
Q: fetching data from external JSON file into an innerHTML table using JQuery I have created an HTML table called players_table consisting of 3 variables(ID, Name, Country)
The table should display the fetched JSON data into its rows. I don't know what's wrong and why it isn't fetching anything. Could you please help me out fix this error and display results into the table?

The console is not showing any errors. However, the entire table cells are showing the word "Undefined".
This is the view from my end.


text:
Q: objdump : file format not recognized I'm encountering these errors when trying to compile a new kernel under Gentoo...
scripts/kconfig/conf  --syncconfig Kconfig
  DESCEND  objtool
  CC      kernel/bounds.s
  CC      arch/x86/kernel/asm-offsets.s
  GEN     scripts/gdb/linux/constants.py
  CALL    scripts/checksyscalls.sh
  CC [M]  arch/x86/kvm/../../../virt/kvm/kvm_main.o
  CC      init/main.o
  CC      kernel/bpf/core.o
  CC      arch/x86/ia32/sys_ia32.o
  CC      arch/x86/kernel/acpi/boot.o
  CC      arch/x86/events/amd/core.o
  CC      certs/system_keyring.o
  CC      arch/x86/entry/vdso/vma.o
  CC      arch/x86/crypto/sha1-mb/sha1_mb.o
objdump: certs/.tmp_system_keyring.o: unable to initialize decompress status for section .debug_info
objdump: certs/.tmp_system_keyring.o: unable to initialize decompress status for section .debug_info
objdump: certs/.tmp_system_keyring.o: file format not recognized
  EXTRACT_CERTS
  AS      certs/system_certificates.o
  AR      certs/built-in.a
objdump: arch/x86/ia32/.tmp_sys_ia32.o: unable to initialize decompress status for section .debug_info
objdump: arch/x86/ia32/.tmp_sys_ia32.o: unable to initialize decompress status for section .debug_info
objdump: arch/x86/ia32/.tmp_sys_ia32.o: file format not recognized
objdump: arch/x86/events/amd/.tmp_core.o: unable to initialize decompress status for section .debug_info
objdump: arch/x86/events/amd/.tmp_core.o: unable to initialize decompress status for section .debug_info
objdump: arch/x86/events/amd/.tmp_core.o: file format not recognized
  CC      arch/x86/ia32/ia32_signal.o
  CC      arch/x86/mm/init.o
  CC      arch/x86/events/amd/uncore.o
objdump: arch/x86/entry/vdso/.tmp_vma.o: unable to initialize decompress status for section .debug_info
objdump: arch/x86/entry/vdso/.tmp_vma.o: unable to initialize decompress status for section .debug_info
objdump: arch/x86/entry/vdso/.tmp_vma.o: file format not recognized
  CC      arch/x86/entry/vdso/vdso32-setup.o
objdump: arch/x86/kernel/acpi/.tmp_boot.o: unable to initialize decompress status for section .debug_info
objdump: arch/x86/kernel/acpi/.tmp_boot.o: unable to initialize decompress status for section .debug_info
objdump: arch/x86/kernel/acpi/.tmp_boot.o: file format not recognized
  CC      arch/x86/kernel/acpi/sleep.o
  AR      arch/x86/crypto/sha1-mb/built-in.a
objdump: init/.tmp_main.o: unable to initialize decompress status for section .debug_info
objdump: init/.tmp_main.o: unable to initialize decompress status for section .debug_info
objdump: init/.tmp_main.o: file format not recognized
...

I've rebuilt binutils (which is the package from which objdump comes from), but that had no effect.
I can compile and install other packages/software without any problem, but this is preventing kernel compilation from completing.

A: According to bug 671650, elfutils-0.175 has problems with alignments.
Switching into linker ld.gold unveiled massive ammount of warnings about section alignments.
Try reverting to elfutils-0.173:
# emerge dev-libs/elfutils-0.173
And then rebuild your kernel.
sys-kernel/gentoo-sources-4.19.3 on my system builds and loads fine with elfutils-0.173.


text:
Q: How to parse this huge XML file with nested elements using lxml the efficient way? I tried parsing this huge XML document using XML minidom. While it worked fine on a sample file, it choked the system when trying to process the real file (about 400 MB).
I tried adapting code (it processes data in a streaming fashion rather than in-memory load at once) from codereview for my xml file, I am having trouble isolating the datasets due to the nested nature of the elements. I worked on simple XML files before but not on a memory intensive task like this.
Is this the right approach?
How do I associate the Inventory and Publisher IDs to each book? That is how I am planning to relate the 2 tables eventually.
Any feedback is much appreciated.
book.xml
<BookDatabase>
    <BookHeader>
        <Name>BookData</Name>
        <BookUniverse>All</BookUniverse>
        <AsOfDate>2010-05-02</AsOfDate>
        <Version>1.1</Version>
    </BookHeader>

    <InventoryBody>
        <Inventory ID="12">
            <PublisherClass ID="34">
                <Publisher>
                    <PublisherDetails>
                        <Name>Microsoft Press</Name>
                        <Type>Tech</Type>
                        <ID>7462</ID>
                    </PublisherDetails>
                </Publisher>
            </PublisherClass>
            <BookList>
                <Listing>
                    <BookListSummary>
                        <Date>2009-01-30</Date>
                    </BookListSummary>
                    <Book>
                        <BookDetail ID="67">
                            <BookName>Code Complete 2</BookName>
                            <Author>Steve McConnell</Author>
                            <Pages>960</Pages>
                            <ISBN>0735619670</ISBN>
                        </BookDetail>
                        <BookDetail ID="78">
                            <BookName>Application Architecture Guide 2</BookName>
                            <Author>Microsoft Team</Author>
                            <Pages>496</Pages>
                            <ISBN>073562710X</ISBN>
                        </BookDetail>
                    </Book>
                </Listing>
            </BookList>
        </Inventory>
        <Inventory ID="64">
            <PublisherClass ID="154">
                <Publisher>
                    <PublisherDetails>
                        <Name>O'Reilly Media</Name>
                        <Type>Tech</Type>
                        <ID>7484</ID>
                    </PublisherDetails>
                </Publisher>
            </PublisherClass>
            <BookList>
                <Listing>
                    <BookListSummary>
                        <Date>2009-03-30</Date>
                    </BookListSummary>
                    <Book>
                        <BookDetail ID="98">
                            <BookName>Head First Design Patterns</BookName>
                            <Author>Kathy Sierra</Author>
                            <Pages>688</Pages>
                            <ISBN>0596007124</ISBN>
                        </BookDetail>
                    </Book>
                </Listing>
            </BookList>
        </Inventory>
    </InventoryBody>
</BookDatabase>

Python Code :
import sys
import os
#import MySQLdb
from lxml import etree

CATEGORIES = set(['BookHeader', 'Inventory', 'PublisherClass', 'PublisherDetails', 'BookDetail'])
SKIP_CATEGORIES = set(['BookHeader'])
DATA_ITEMS = ["Name", "Type", "ID", "BookName", "Author", "Pages", "ISBN"]

def clear_element(element):
    element.clear()
    while element.getprevious() is not None:
        del element.getparent()[0]

def extract_book_elements(context):
    for event, element in context:
         if element.tag in CATEGORIES:
               yield element
               clear_element(element)

def fast_iter2(context):
    for bookCounter, element in enumerate(extract_book_elements(context)):
            books = [book.text for book in element.findall("BookDetail")]
            bookdetail = {
                'element' : element.tag,
                'ID' : element.get('ID')
            }
            for data_item in DATA_ITEMS:
                data = element.find(data_item)
                if data is not None:
                    bookdetail[data_item] = data

            if bookdetail['element'] not in SKIP_CATEGORIES:
                #populate_database(bookdetail, books, cursor)
                print bookdetail, books

            print "========>", bookCounter , "<======="

def main():
        #cursor = connectToDatabase()
        #cursor.execute("""SET NAMES utf8""")

        context = etree.iterparse("book.xml", events=("start", "end"))
        #fast_iter(context, cursor)
        fast_iter2(context)

        #cursor.close()

if __name__ == '__main__':
    main()

Python Output :
$ python lxmletree_book.py
========> 0 <=======
========> 1 <=======
{'ID': '12', 'element': 'Inventory'} []
========> 2 <=======
{'ID': '34', 'element': 'PublisherClass'} []
========> 3 <=======
{'Name': <Element Name at 0x105140af0>, 'Type': <Element Type at 0x105140b40>, 'ID': <Element ID at 0x105140b90>, 'element': 'PublisherDetails'} []
========> 4 <=======
{'ID': None, 'element': 'PublisherDetails'} []
========> 5 <=======
{'ID': None, 'element': 'PublisherClass'} []
========> 6 <=======
{'ISBN': <Element ISBN at 0x105140eb0>, 'Name': <Element Name at 0x105140dc0>, 'Author': <Element Author at 0x105140e10>, 'ID': '67', 'element': 'BookDetail', 'Pages': <Element Pages at 0x105140e60>} []
========> 7 <=======
{'ID': None, 'element': 'BookDetail'} []
========> 8 <=======
{'ISBN': <Element ISBN at 0x1051460a0>, 'Name': <Element Name at 0x105140f50>, 'Author': <Element Author at 0x105140fa0>, 'ID': '78', 'element': 'BookDetail', 'Pages': <Element Pages at 0x105146050>} []
========> 9 <=======
{'ID': None, 'element': 'BookDetail'} []
========> 10 <=======
{'ID': None, 'element': 'Inventory'} []
========> 11 <=======
{'ID': '64', 'element': 'Inventory'} []
========> 12 <=======
{'ID': '154', 'element': 'PublisherClass'} []
========> 13 <=======
{'Name': <Element Name at 0x105146230>, 'Type': <Element Type at 0x105146280>, 'ID': <Element ID at 0x1051462d0>, 'element': 'PublisherDetails'} []
========> 14 <=======
{'ID': None, 'element': 'PublisherDetails'} []
========> 15 <=======
{'ID': None, 'element': 'PublisherClass'} []
========> 16 <=======
{'ISBN': <Element ISBN at 0x1051465f0>, 'Name': <Element Name at 0x105146500>, 'Author': <Element Author at 0x105146550>, 'ID': '98', 'element': 'BookDetail', 'Pages': <Element Pages at 0x1051465a0>} []
========> 17 <=======
{'ID': None, 'element': 'BookDetail'} []
========> 18 <=======
{'ID': None, 'element': 'Inventory'} []
========> 19 <=======

Desired Output (eventually stored in MySQL - for now a List in Python):
Publishers
InventoryID PublisherClassID Name            Type ID
12          34               Microsoft Press Tech 7462
64          154              O'Reilly Media  Tech 7484

Books
PublisherID BookDetailID Name                              Author           Pages ISBN
7462        67           Code Complete 2                   Steve McConnell  960   0735619670
7462        78           Application Architecture Guide 2  Microsoft Team   496   073562710X
7484        98           Head First Design Patterns        Kathy Sierra     688   0596007124

A: You might try something like this:
import MySQLdb
from lxml import etree
import config

def fast_iter(context, func, args=[], kwargs={}):
    # http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
    # Author: Liza Daly
    for event, elem in context:
        func(elem, *args, **kwargs)
        elem.clear()
        while elem.getprevious() is not None:
            del elem.getparent()[0]
    del context

def extract_paper_elements(element,cursor):
    pub={}
    pub['InventoryID']=element.attrib['ID']
    try:
        pub['PublisherClassID']=element.xpath('PublisherClass/@ID')[0]
    except IndexError:
        pub['PublisherClassID']=None
    pub['PublisherClassID']=element.xpath('PublisherClass/@ID')[0]
    for key in ('Name','Type','ID'):
        try:
            pub[key]=element.xpath(
                'PublisherClass/Publisher/PublisherDetails/{k}/text()'.format(k=key))[0]
        except IndexError:
            pub[key]=None
    sql='''INSERT INTO Publishers (InventoryID, PublisherClassID, Name, Type, ID)
           VALUES (%s, %s, %s, %s, %s)
        '''
    args=[pub.get(key) for key in
          ('InventoryID', 'PublisherClassID', 'Name', 'Type', 'ID')]
    print(args)
    # cursor.execute(sql,args)
    for bookdetail in element.xpath('descendant::BookList/Listing/Book/BookDetail'):
        pub['BookDetailID']=bookdetail.attrib['ID']
        for key in ('BookName', 'Author', 'Pages', 'ISBN'):
            try:
                pub[key]=bookdetail.xpath('{k}/text()'.format(k=key))[0]
            except IndexError:
                pub[key]=None
        sql='''INSERT INTO Books
               (PublisherID, BookDetailID, Name, Author, Pages, ISBN)
               VALUES (%s, %s, %s, %s, %s, %s)
            '''
        args=[pub.get(key) for key in
              ('ID', 'BookDetailID', 'BookName', 'Author', 'Pages', 'ISBN')]
        # cursor.execute(sql,args)
        print(args)

def main():
    context = etree.iterparse("book.xml", events=("end",), tag='Inventory')
    connection=MySQLdb.connect(
        host=config.HOST,user=config.USER,
        passwd=config.PASS,db=config.MYDB)
    cursor=connection.cursor()

    fast_iter(context,extract_paper_elements,args=(cursor,))

    cursor.close()
    connection.commit()
    connection.close()

if __name__ == '__main__':
    main()

*

*Don't use fast_iter2. The original fast_iter separates the
useful utility from the specific processing function
(extract_paper_elements). fast_iter2 mixes the two together
leaving you with no repeatable code.

*If you set the tag parameter in etree.iterparse("book.xml",
events=("end",), tag='Inventory') then your processing function
extract_paper_elements will only see Inventory elements.

*Given an Inventory element you can use the xpath method to burrow
down and scrape the desired data.

*args and kwargs parameters were added to fast_iter so cursor
can be passed to extract_paper_elements.

A: So if you want something quick and dirty you need to simply remember the last publisher parsed and assign it to each bookdetail until the next PublisherDetails is found. Add something like this to your fast_iter2 function after you extract the bookdetail:
        if bookdetail['element'] == "PublisherDetails" and bookdetail['ID'] is not None:
            CurrentPublisher = bookdetail
        if bookdetail['element'] == "BookDetail":
            bookdetail['PublisherID'] = CurrentPublisher['ID'].text


text:
Q: What is the difference between different ways of Custom event handling in JavaScript? I came across the below posts about custom event handling in JavaScript. From these articles, there are two ways (at least) of handling/firing custom events:

*

*Using DOM methods (createEvent, dispatchEvent)

*

*How do I create a custom event class in Javascript?

*http://the.unwashedmeme.com/blog/2004/10/04/custom-javascript-events/

*Custom code

*

*http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/

*http://www.geekdaily.net/2008/04/02/javascript-defining-and-using-custom-events/
But what is the recommended way of handling (firing & subscribing) custom events?
[Edit] The context for this question is not using any libraries like jQuery, YUI,... but just plain JavaScript
[Edit 2] There seems to be a subtle differences, at least with the error handling.
Dean Edwards ( http://dean.edwards.name/weblog/2009/03/callbacks-vs-events/ ) is recommending the former way for custom event handling. Can we say this a difference?

A: What your describing is the difference between

*

*A custom event based message passing system

*manually firing DOM events.

The former is a way to use events for message passing. An example would be creating an EventEmitter
The latter is simply a way to use the browsers build in DOM event system manually. This is basically using the DOM 3 Event API which natively exists in (competent / modern) browsers.
So the question is simply what do you want to do? Fire DOM events or use events for message passing?
Benchmark showing DOM 3 custom events is 98% slower
The DOM appears to have a huge overhead. It does so because it supports event propagation and bubbling. It does because it supports binding events to a DOMElement.
If you do not need any of the features of DOM3 events then use a pub/sub library of choice.
[Edit 2]
That's all about error handling, how you do error handling is upto you. If you know your event emitter is synchronous then that's intended behaviour. Either do your own error handling or use setTimeout to make it asynchronous.
Be wary that if you've made it asynchronous you "lose" the guarantee that the event handlers have done their logic after the emit/trigger/dispatch call returns. This requires a completely different high level design then the assumption that event emitters are synchronous. This is not a choice to make lightly

A: There are pros and cons to each. Use what suits you.
The most obvious "con" to using the DOM methods is that they're tied to browser-based deployments and involve the DOM in things even if it doesn't really make sense (e.g., the messaging isn't related to DOM objects), whereas a standard Observer-style implementation can be used in any environment, not just web browsers, and with any generic object you like.
The most obvious "con" to doing your own Observer implementation is that you've done your own Observer implementation, rather than reusing something already present (tested, debugged, optimised, etc.) in the environment.

A: Many libraries already provide a way to deal with events, and I would recommend on just using an existing library. If you use the DOM, you are assuming that the browser provides the necessary support, whereas if you use a custom mechanism, you might be sacrificing speed for the custom implementation. If you rely on an existing library, the library can choose the appropriate tradeoffs.
For example, Closure provides EventTarget which has an interface simliar to that of the DOM mechanism, but which does not depend on the browser to provide native support for it.


text:
Q: INNER JOIN запрос в Sequelize Как выполнить этот запрос в Sequelize?
SELECT features.name
FROM typeFeatures
INNER JOIN features ON featuresId = features.id

Models:
const Feature = sequelize.define('feature', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    name: { type: DataTypes.STRING, allowNull: false }
});

const TypeFeature = sequelize.define('typeFeature', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }
});

Т.е. чтобы вместо:
{
    "id": 1,
    "featureId": 1
}

Получить это:
{
    "id": 1,
    "feature.name": "TestName"
}

A: Как минимум добавить ассоциацию между моделями:
TypeFeature.belongsTo(Feature, { foreignKey: 'featuresId' })

А потом сделать запрос TypeFeature и включить заассоциированную модель
Feature (см. запросы с ассоциациями):
const typefeature = await TypeFeature.findByPk(1, {
  include: [{
    model: Feature,
    attributes: ['name']
  }]
})

Тогда в typefeature будет:
{
    "id": 1,
    "feature": {
      "name": "TestName"
    }
}

Если прям надо без вложенного объекта просто на уровне полей основной модели получить name, то так:
const typefeature = await TypeFeature.findByPk(1, {
  attributes: ['id', [['feature', 'name'], 'feature.name']],
  include: [{
    model: Feature,
    attributes: []
  }]
})


text:
Q: ola-hallengren cleanup will not remove AOAG old DB backups if server fails over ola-hallengren cleanup will not remove AOAG old DB backups if server fails over
anyone else experience this?

A: It will clean up only on active server or where the backup is taken from. You should put a custom job to do cleanup on the passive nodes.
This is what I have done in my environment :

*

*scan entire NFS for backups that are older than X-days and which have been backed up to tape (Archive bit is set).

*Use powershell to find and delete old backups - full, diff and tlogs. Note that scanning a large NFS for many files will take some time, so use robocopy with /L to fast list and then delete files.

Technically, Ola's backup solution should only care of the primary or the server that is taking the backups. Removing old files should be handled by a custom job.


text:
Q: jQuery load needs to wait for target scripts I'm using jQuery.load to get contents of another page on the same domain.
What I need it to do is to wait for the target page to fully load cause the content I want is loaded using ajax on the target page.
I can't figure out how to do that, so therefore I'm asking here.
Anyone who can help me?
$('.getjson').load('URL .cso-wspn-cont.cso-tile-view.static ul');

The content in the UL is inserted with ajax so my jQuery.load gets an empty UL.

A: You can try with ,
$(window).bind("load",function(){
     $('.getjson').load('URL .cso-wspn-cont.cso-tile-view.static ul');
}

Or instead of wondow you can give selector of parent div of the div you are using
 :) :)


text:
Q: Implementing drawer (Offcanvas) in react I am trying to implement Drawer (Offcanvas) component in react, so here the requirement is, there will be one Drawer whose component will change dynamically, consider something like bootstrap modal, you have one modal but you can trigger that modal from anywhere from the page just write data-toggle="modal" data-target="#modalid", but implementing this in react requires communicating between 2 root components & setting drawers component data from the triggering component or button. I have seen people added trigger & modal in same component & than passing state.toggle flag like below:
render() {
    return (
      <div>
        <Button color="danger" onClick={this.toggle}>{this.props.buttonLabel}</Button>
        <Drawer isOpen={this.state.drawer} toggle={this.toggle} className={this.props.className}>
          <DrawerBody>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
          </DrawerBody>
        </Drawer>
      </div>
    );
  }

But in my case, there is no relationship between components, this component <Button color="danger" onClick={this.toggle}>{this.props.buttonLabel}</Button> will be added in multiple places & there is no coupling between Drawer & Button. So how I can achieve this without using any state management like Redux or Flux or anything else


text:
Q: Java Connection Pool Shut Down I am running Apache HTTP POST Request in Java and start getting the following error whenever I exceed ~ 1300 requests, I need to make a lot more requests ~40k what can I do to rectify the same?
java.lang.IllegalStateException: Connection pool shut down
    at org.apache.http.util.Asserts.check(Asserts.java:34)
    at org.apache.http.pool.AbstractConnPool.lease(AbstractConnPool.java:184)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.requestConnection(PoolingHttpClientConnectionManager.java:251)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:175)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
    at io.searchbox.client.http.JestHttpClient.execute(JestHttpClient.java:48)
    at code.niki.elasticSearchBase.Location.LocationAPI.writeBulkLocation(LocationAPI.java:116)
    at sun.reflect.GeneratedMethodAccessor28.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)

A: It was definitely a bug caused by a LoadBalancingPolicy instance being shared across the two clusters.
Please refer to the link here.


text:
Q: fetch first 2 words along with symbols I am trying to fetch the first 2 words from a sting, the first word Animal and second word is (Cat) my current code does fetch it but the () brackets gets ignore I want to fetch exactly like on string Animal (Cat).
echo implode(' ', array_slice(str_word_count($_POST['str'], 2), 0, 5));

A: You can use array_slice to get the first two words and then use implode to join them:
<?php
  $str = "Animal (Cat) is a domestic pet";
  echo implode(" ", array_slice(explode(" ", $str), 0, 2));

I get the output as:
Animal (Cat)

Here's a sandbox: https://sandbox.onlinephpfunctions.com/c/a2c44

A: It's much easier.  Just tokenize on a space twice:
echo strtok($_POST['str'], ' ') . ' ' . strtok(' ');


text:
Q: Validating SSN,Email and Phone number in Postgres Could anyone help me on how to perform validation on SSN, Email, phone through a stored procedure in Postgresql?
Thanks.

A: A stored procedure doesn't look like the right solution.  Use a domain with a check constraint using pattern matching.  There is an example on the CREATE DOMAIN reference page.  For email address checking, consider http://wiki.postgresql.org/wiki/Email_address_parsing.


text:
Q: c# Show Windows Form So, I'm struggling a little bit here. I am writing a windows console application in C# and have just made a login form for the application called frmLogin.
I tried using the MS documented method of;
Form f = new Form();
f.ShowDialog();

but this obviously loads/displays a blank form and not the form I defined in the form designer.
In my main application, I want to be able to show the login form programmatically, but when I try to use;
frmLogin.ShowDialog();

it tells me that "An object reference is required for the non-static field, method or property 'System.Windows.Forms.Form.ShowDialog()'
In the old days, I could show a form by simply using the above snippet of code. So, obviously something has changed since the last time I wrote a windows console app.
Can someone show me the error of my ways?

A: The problem is that with the code snippet you took from Microsoft, you were just building the base Type. You need to build your form. So instead of new Form, you build a new frmLogin:
var f = new frmLogin();
f.ShowDialog();

A: If this doesn't solve your problem, I will delete my answer but, I am assuming that you aren't instantiating your form:
Form2 frmLogin = new Form2();
frmLogin.ShowDialog();

This works just fine for me.  Although personally, I would simply use the .Show() method:
Form2 frmLogin = new Form2();
frmLogin.Show();

A: This creates a new instance of type Form:
Form f = new Form();

Which, of course, is a blank form.  It would appear that your type is called frmLogin.  Normally this sounds like a variable name and not a class name, but the error you're getting here tells me that it's a class:
frmLogin.ShowDialog();

Given that, then the quickest way to solve your problem would be to create an instance of your form and show it:
frmLogin login = new frmLogin();
login.ShowDialog();

However, in keeping with naming standards and conventions (to help prevent future confusion and problems), I highly recommend renaming the form itself to something like:
LoginForm

Then you can use something like frmLogin as the variable name, which is a much more common approach:
LoginForm frmLogin = new LoginForm();
frmLogin.ShowDialog();

A: Create the object of the FORM you are trying to open
for instance "frmStudent"
Method 1:
frmStudent obj = new frmStudent();
obj.Show();

Method 2:
It will open the form , but you can't move to another form until you close it.
frmStudent obj = new frmStudent();
obj.ShowDialog();


text:
Q: Can I shrink 25 GB Lenovo parition my laptop came with? I have just bought a new lenovo yoga 720, with a 256 GB ssd. However, the main partition only has 212.23 GB of space allocated. There is a 25 GB partition called "Lenovo" which has about 1.5 GB of drivers in it. I would like to keep these drivers so that my stylus works, so I don't want to completely reinstall Windows.
Would it be a reasonable idea to shrink the Lenovo partition? I would leave some extra space in case there are updates, but it currently has 23 GB of unused space which is 10% of my laptop's total storage.
I plan on eventually dual booting, so I would use the space for the linux distro.
I'm using a Lenovo yoga 720 13", Windows 10.

A: If you have a recovery disk that came with the computer, you can resize the partition as the drivers should be restored when you run the disk.
Alternatively, you can either copy the drivers to a USB drive or external hard disk, or to somewhere in the C: partition. You could also download them from the Lenovo website.

A: You can shrink the program in third party partitioning tools like minitool partition wizard free edition or easeus partition master, as long as this partition is showing up as NTFS in the program.


text:
Q: In Artillery. How do I log ETIMEDOUT? I have a test that gets an ETIMEDOUT error.  I want to know which URL is giving the timeout.  I have the following hook already
function logIfError(requestParams, response, context, ee, next) {
  if (response.statusCode !== 200 && response.statusCode !== 204) {
      console.error("%i %s", response.statusCode, response.url);
      if (response.statusCode >= 500) {
          console.log(response.headers['X-Trace-Id'])
      }
      if (response.statusCode >= 400) {
          console.log(response.rawBody.toString())
      }
  }
  next();
}

I added to my scenario
scenarios:
  - name: My Scenario
    afterResponse: logIfError

But I can't see any messages when it times out.  There's a note in https://github.com/artilleryio/artillery/issues/437#issuecomment-371801777 that indicates an onError but it is not documented anywhere.
I tried to add it in like this
scenarios:
  - name: My Scenario
    afterResponse: logIfError
    onError: myOnErrorHandler

With my implementation as
function myOnErrorHandler(err, requestParams, context, events, callback) {
  console.log("ERR", err);
  return callback();
}

But again no output

A: I add the following processor
function trapError(requestParams, context, ee, next) {
  if (!requestParams.hooks) {
    requestParams.hooks = {};
  }
  if (!requestParams.hooks.beforeError) {
    requestParams.hooks.beforeError = [];
  }
  requestParams.hooks.beforeError.push((error) => {
    if (error.name !== "HTTPError") {
      console.error(requestParams.url, error.name);
    }
    return error;
  });
  next();
}

And register it as follows
scenarios:
  - name: My Scenario
    beforeRequest: trapError

What this does is exploits the fact that it is using got which provides a beforeError hook