text:
Q: I'm trying to get the output from my model,but got 4 tensor.I dont know anything about these tensors I'm trying to get the output from my model,but got 4 tensor.I dont know anything about these tensors
i use the model to detect face.
Here is my model
enter image description here
The model's input is frame of Webcam ,Here is the output
enter image description here
here are my code
      const img = tf.browser.fromPixels(video)
      let resized = img;
      if (img.shape[0] !== 640 || img.shape[1] !== 640) {
        const alignCorners = true;
        resized = tf.image.resizeBilinear(
          img, [640, 640], alignCorners,
        );
      }

      //
      const batched = resized.reshape([-1, 640, 640, 3]);

      // console.log(batched)
      const obj = await net.executeAsync(batched);
      console.log(obj);

A: To get the tensor data, you can use the dataSync method  which is the synchronous version of data


text:
Q: Prove that if all geodesics of a surface $S$ are planar curves, then $S$ is contained in a plane or a sphere I know that if $\alpha$ is geodesic and its curvature is never zero, and it's plane, then it's a line of curvature (i.e. the tangent is a principal direction). I can prove this using Frenet.
I want to show first that all points are umbilical, because then I know how to prove that the curvature is constant, so the surface must be in a plane, a pshere, or the pseudosphere (but it can't be the pseudosphere because of reasons).
Given a point in the surface, and a direction, there exists one and only one geodesic in that direction. If the curvature is never zero, the direction is principal. If I can do this with all points and all directions, all points are umbilical.
But...it can happen that the curvature of the geodesic is zero and I don't know what to do in that case. Can you help me?

A: HINT: Suppose the geodesic has $\kappa(P) = 0$ for some $P$. Then $P$ must be a planar point, a parabolic point, or a hyperbolic point of the surface. In the latter two cases, you get $\kappa_n\ne 0$ for all but one or two directions, and you're done. Now what if $P$ is a planar point?
Now it's a set-theoretic argument. You need to assume the surface is connected, of course.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Динамическое добавление фрагмента Подскажите почему введено некорректно? Во многих примерах именно так показывается работа с динамическим управление фрагментов.
Закрашивается androidx.fragment.app.FragmentTransaction
public class TranslateActivity extends AppCompatActivity {
    EnglishFragment EnglishFrag;
    FragmentTransaction ft;
    JapaniseFragment JapFrag;
    ChineseFragment ChinaFrag;
    RussianFragment RussFrag;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_translate);

    FragmentManager fragmentManager = getFragmentManager();
    //ошибка на строчке ниже
    FragmentTransaction ft = fragmentManager.beginTransaction();

    EnglishFragment EnglishFrag = new EnglishFragment();
    ft.add(R.id.Tranlation, EnglishFrag, "fragment1");
    ft.commit();
}

}


text:
Q: Only update the value given and ignore other values in dynamodb Hi I am writing a lambda function that will update the DynamoDb using boto3. In this code employee_id is auto-generated but you have to provide last_name or first_name. I am doing it with  if-else. If the attribute tends to increase so does the checks. I can't keep on going with if condition. How can I tackle this what changes should I make
import boto3
import json

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Employee')

def lambda_handler(event, context):

    employee_id = event['employee_id']

    if 'first_name' in event and 'last_name' not in event:

        first_name = event['first_name']
        UpdateExpression = 'SET first_name = :val1'
        ExpressionAttributeValues = {':val1': first_name }

    elif 'last_name' in event and 'first_name' not in event:

        last_name = event['last_name']
        UpdateExpression = 'SET last_name = :val1'
        ExpressionAttributeValues = {':val1': last_name}

    elif 'first_name' in event and 'last_name' in event:

        last_name = event['last_name']
        first_name= event['first_name']
        UpdateExpression = 'SET last_name = :val1, first_name = :val2'
        ExpressionAttributeValues = {
                ':val1': last_name,
                ':val2': first_name
            }

    else:
        raise ValueError("first_name and last_name not given")

    update = table.update_item(
        Key={
            'employee_id': employee_id
        },
        ConditionExpression= 'attribute_exists(employee_id)',
        UpdateExpression=UpdateExpression,
        ExpressionAttributeValues=ExpressionAttributeValues
    )

The code that I came up with but is not working
import boto3
import json
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Employee')

def lambda_handler(event, context):
    employee_id = event['employee_id']
    last_name= event['last_name']
    first_name= event['first_name']
    column = [first_name,last_name]
    for i in range(0,len(column):
       query = 'SET {} = :val1,:val2'.format(column[i])
       response = table.update_item(
           Key={
            'employee_id': employee_id
            },
            ConditionExpression= 'attribute_exists(employee_id)',
            UpdateExpression = query,
            ExpressionAttributeValues={
                ':val1': first_name,
                ':val2': last_name
            },
            ReturnValues="UPDATED_NEW"
        )

A: You should look at storing the update expression and expression values separately, then passing the complete set into the Lambda function.
This would also allow you to validate against each parameter (perhaps breaking this into a validate function to avoid excessive size of function). This way you support both required and optional parameters, then at the end validate that the update expression has valid parameters.
Perhaps something like the below?
import boto3
import json

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Employee')

def lambda_handler(event, context):

    update_expression_values = []
    expression_attribute_values = {}

    if 'employee_id' in event:
        employee_id = event['employee_id']
    else:
        raise ValueError("employee_id not given")

    if 'first_name' in event:
        update_expression_values.append('first_name = :val_first_name')
        expression_attribute_values[':val_first_name'] = event['first_name']

    if 'last_name' in event:

        update_expression_values.append('last_name = :val_last_name')
        expression_attribute_values[':val_last_name'] = event['last_name']

    if len(update_expression_values) < 1:
        raise ValueError("first_name and last_name not given")

    seperator = ','

    update = table.update_item(
        Key={
            'employee_id': employee_id
        },
        ConditionExpression= 'attribute_exists(employee_id)',
        UpdateExpression='SET ' + seperator.join(update_expression_values),
        ExpressionAttributeValues=expression_attribute_values
    )

This could be broken down further to reuse the logic through a function that can perform these checks such as the below.
import boto3
import json

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Employee')

update_expression_values = []
expression_attribute_values = {}

def lambda_handler(event, context):
    global update_expression_values
    global expression_attribute_values

    update_expression_values = []
    expression_attribute_values = {}

    if 'employee_id' in event:
        employee_id = event['employee_id']
    else:
        raise ValueError("employee_id not given")

    process_event_key(event, 'first_name')
    process_event_key(event, 'last_name')
    process_event_key(event, 'new_value')

    if len(update_expression_values) < 1:
        raise ValueError("first_name and last_name not given")

    seperator = ','

    update = table.update_item(
        Key={
            'employee_id': employee_id
        },
        ConditionExpression= 'attribute_exists(employee_id)',
        UpdateExpression='SET ' + seperator.join(update_expression_values),
        ExpressionAttributeValues=expression_attribute_values
    )

def process_event_key(event, key):
    global update_expression_values
    global expression_attribute_values

    if key in event:
        update_expression_values.append(key + ' = :val_' + key)
        expression_attribute_values[':val_' + key] = event[key]

Test Event
{
  "new_value": "test",
  "employee_id": "value2",
  "last_name": "value3",
  "first_name": "value4"
}


text:
Q: Retain XML version when file is saved in SQL Server database using Python My Python code pulls locally stored XML file and saves it in a SQL Server database. However, I see that file stored in database is missing the initial XML version statement:
<?xml version="1.0" encoding="utf-8"?>

In order to retain the initial XML version statement, I came across lxml documentation which states to add parameter xml_declaration=True. Using this parameter, I can see the XML version printed in python console. But, when I try to use the same parameter to store it in the database, I get an error:

Type: bytes cannot be serialized exception

Can anyone please help me resolve this exception?
Python code:
    print("Connecting..")
    # Establish a connection between Python and SQL Server
    conn = pyodbc.connect('Driver={SQL Server};'
                          'Server=TestServer;'
                          'Database=test;'
                          'Trusted_Connection=yes;')
    print("DB Connected..")

    # Open the workbook and define the worksheet
    path = 'C:\\Arelle-master\\arelle\\plugin\\TestPlugin\\TestExcel.xlsx'
    book = xlrd.open_workbook(path)
    print("Excel Loaded into xlrd..")

    # Get XML File
    XMLFilePath = open('C:\\TestPlugin\\HelloWorld.xml')
    x = etree.parse(XMLFilePath)
    print(etree.tostring(x, pretty_print=True, xml_declaration=True)) # Shows correct version of XML file in console.

    CreateTable = """
    create table test.dbo.StoreInfo
    (
     col1 varchar(100),
     col2 varchar(100),
     col3 varchar(100),
     col4 varchar(100),
     MyXML XML

    )
    """

    # execute create table
    cursor = conn.cursor()
    try:
         cursor.execute(CreateTable)
         conn.commit()
    except pyodbc.ProgrammingError:
        pass
    print("Table Created..")

    InsertQuery = """
    INSERT INTO test.dbo.StoreInfo (
        col1,
        col2,
        col3,
        col4,
        XBRLFile
    ) VALUES (?, ?, ?, ?, ?)"""

    # Grab existing row count in the database for validation later
    # cursor.execute("SELECT count(*) FROM test.dbo.StoreInfo")
    # before_import = cursor.fetchone()

    for r in range(1, sheet.nrows):
        col1 = sheet.cell(r, 0).value
        col2 = sheet.cell(r, 1).value
        col3 = sheet.cell(r, 2).value
        col4 = sheet.cell(r, 3).value
        col5 = etree.tostring(etree.tostring(x, xml_declaration=True))  # Code throws exception at this line.

        # Assign values from each row
        values = (col1,col2,col3,col4,col5)

        # Execute SQL Insert Query
        cursor.execute(InsertQuery, values)

Exception:
col5 = etree.tostring(etree.tostring(x, xml_declaration=True))
File "src\lxml\etree.pyx", line 3391, in lxml.etree.tostring

TypeError: Type 'bytes' cannot be serialized.

Any idea how to resolve this error?

A: MS SQL Server XML data type doesn't preserve XML declaration prolog. It is stripped out.
If you do need to have it for any reason you would need to change data type to NVARCHAR(MAX).
The XML data type is internally stored as UTF-16 encoding. Even more precise, SQL Server is using varbinary(max) data type
internally, but the content itself is UTF-16 encoded text.


text:
Q: Crouton with custom view: onClickListener not called I have an issue with crouton:
customView = LayoutInflater.from(context).inflate(viewId, null);
if (customView != null) {
    TextView title = (TextView) customView.findViewById(R.id.crouton_title);
    if (title != null) {
        title.setText(titleString);
    }
    TextView message = (TextView) customView.findViewById(R.id.crouton_message);
    if (message != null) {
        message.setText(messageString);
    }
}

final Crouton crouton = Crouton.make((Activity) context, customView);
crouton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Crouton.hide(crouton);
    }
});

If I provide a customView to the make method, the onClickListener is never called. If I use the makeText, it works. Am I doing something wrong?

A: Adding an OnClickListener to a custom view is not yet supported.
The easiest way to handle click events within a custom view Crouton is to add the OnClickListener directly to your custom view.


text:
Q: Customer login not working after Data migrated from Magento 1.5.1.0 to 2.3.1 I recently migrated customers from Magento 1.5.1.0 to 2.3.1 then my magento 1 customers are not able to login getting error like:
Error : The account sign-in was incorrect or your account is disabled temporarily.Please wait and try again later

sometime bellow error also
 Error : 'Invalid login or password.'

I tried to upgrade customer has using command but also getting error like
php -f bin/magento customer:hash:upgrade
Error :Notice: Undefined index: 0:1 in /var/www/html/vendor/magento/framework/Encryption/Encryptor.php on line 198

anyone have idea how to fixed this ?

A: after lots of debugging finally, I got issue actually website_id is null in customer_entity table so while Magento tries to authenticate customer it throws an exception "No such Entity..." so customer login not working and it shows an error. so I just assign website id and issue fixed .

A: I found the command called
customer:hash:upgrade I think this will help you.
If you have many many customers if might be good to run the command with
-d memory_limit=-1
So, the command would be like:
php bin/magento customer:hash:upgrade
or the version with unlimited memory
php -d memory_limit=-1 bin/magento customer:hash:upgrade
I hope that will help


text:
Q: Is eq the correct selector to get the first element of a jquery list? It gives me an error I try to get the first .myClass element of my page.
To do that, I use $(".myClass:eq(0)"); This is working perfectly but gives me the following console error:
"Warning: Pseudo-class or pseudo-element "eq" unknown." (Traduced from french)
Is that error normal? Is there a way to avoid it? Which syntax do you use to select first elements? I also tried $(".myClass:first"); but the problem is then the same with first.
Thank you in advance for your help
David

A: Your code is fine and correct. I'm wondering which jQuery version you are using and on what browser you are testing.
$(".myClass").first()

which is a shortcut for
$(".myClass").eq(0)

might solve your trouble. .first() will not use sizzle to query elements, but uses array slice to reduce the set of matched elements.

A: you are getting this warning because eq() is not a valid css selector...
you are getting the same with :first because the :first pseudo-class is equivalent to :eq(0)..
and jQuery catches this warning, and then do the thing it needs to do with it...
just same with this :hidden


text:
Q: Possible to display timezone in OS X menu bar? Since I have trouble keeping my standard/DST straight in my head, I'd like to see the 3-letter timezone abbreviation with the date/time on my menu bar in OS X.
I tried customizing the short time format in the Language & Region settings, but that did not change what shows on the menu bar.
Any other settings that I can tweak to get what I'm looking for? Any free/inexpensive app to do it?

A: iStat Menus will do this.  It's NOT free ($16) but it's a great menu-bar add-on (it does tons of other things, not just time!).  I've been a happy user for years.


text:
Q: Creating Table in Oracle, SQL ORA-00907: missing right parenthesis
I can't figure out what is going wrong with my dataypes and/or commas. Any help would be awesome. Thank you!
CREATE TABLE RIDERS
(RIDER_ID VARCHAR2(4) CONSTRAINT RIDERS_RIDER_ID_PK PRIMARY KEY,
FIRSTRIDER VARCHAR2(20) CONSTRAINT RIDERS_FIRSTRIDER_NN NOT NULL,
LASTRIDER VARCHAR2(20) CONSTRAINT RIDERS_LASTRIDER_NN NOT NULL,
ADDRESS VARCHAR2(25),
CITY VARCHAR2(15),
STATE CHAR(2),
ZIP VARCHAR2(15),
PHONE VARCHAR2(25)
DATEJOINED DATE,
AGENT_ID VARCHAR2(4) CONSTRAINT RIDERS_AGENT_ID_FK REFERENCES AGENTS(AGENT_ID),
TEAM_ID VARCHAR2(4) CONSTRAINT RIDERS_TEAM_ID_FK REFERENCES TEAMS(TEAM_ID));

A: PHONE VARCHAR2(25)

There's your missing comma.

A: You miss a comma after PHONE:
CREATE TABLE RIDERS
(RIDER_ID VARCHAR2(4) CONSTRAINT RIDERS_RIDER_ID_PK PRIMARY KEY,
FIRSTRIDER VARCHAR2(20) CONSTRAINT RIDERS_FIRSTRIDER_NN NOT NULL,
LASTRIDER VARCHAR2(20) CONSTRAINT RIDERS_LASTRIDER_NN NOT NULL,
ADDRESS VARCHAR2(25),
CITY VARCHAR2(15),
STATE CHAR(2),
ZIP VARCHAR2(15),
PHONE VARCHAR2(25),
DATEJOINED DATE,
AGENT_ID VARCHAR2(4) CONSTRAINT RIDERS_AGENT_ID_FK REFERENCES     AGENTS(AGENT_ID),
TEAM_ID VARCHAR2(4) CONSTRAINT RIDERS_TEAM_ID_FK REFERENCES TEAMS(TEAM_ID));


text:
Q: How to connect a client to multiple server sockets? I'm using spring-integration to connect a client to a server socket using the following components:
DirectChannel
TcpConnectionFactoryFactoryBean
TcpOutboundGateway
@MessagingGateway

Problem: the TcpConnectionFactoryFactoryBean is tied to a specific socket port. I'd like to connect the client to multiple server sockets.
How could I achieve this? Is that possible at all?

A: A TCP connection is bound to following parameters:

*

*Source address

*Source port

*Remote address

*Remote port

I think it's not intended to offer the possibilty to create one to many connections via one socket since this would be against the TCP definition.
Wiki-Article for TCP
So the solution would be to create multiple sockets, each holding one connection to a different server.

A: Correct. You need a separate connection factory for each server/port.
There's not currently any mechanism in Spring Integration to dynamically select a TCP host/port for each message.
Such a mechanism would probably need to cache connections to avoid having to open a new socket for each request. Feel free to open a new feature JIRA issue and we'll consider it for a future release.


text:
Q: I'm getting "Uncaught (in promise) TypeError: Cannot read property 'data' of undefined" error in axios patch api I am trying to update an array of objects using an Axios/Node.js API.  I have successfully created the array, but when I try to pass in through an axios patch request, I am getting the "Cannot read property 'data' of undefined".  Anyone know what I might be doing wrong?
My axios function is below:
export const updateTrans = async (transArr) => {
try {
const res = await axios({
  method: 'PATCH',
  url: `http://127.0.0.1:7000/api/v1/property/${id}`,
  data: {
      "transactions": transArr  }
});

if (res.data.status === 'success') {
  showAlert('success', 'Data updated successfully!');

}
 } catch (err) {
console.log(err.response.data.message );

showAlert('error', err.response.data.message);
}
};

I have tried to stringify "transArr" as well, but still no luck.

A: The problem is that you're accessing err.response.data without checking if err.response exists. err.response is only present if the request was made and there was a response. If, for example, a CORS error or some network error occurred (or some other error inside the try block), it will not be present.
Just check that err.response exists before using it.
try {
  // ...
} catch (err) {
  console.log(err, err.response && err.response.data);

  if (err.response && err.response.data) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    showAlert("error", err.response.data.message);
    return;
  }

  showAlert("error", err.message);
}


text:
Q: I have used react-router for my single-page-application. why my page is getting refreshed after navigating to another page? I am new to React-redux, I am using react-router to make my application SINGLE PAGE APP. Routing is working fine but page is getting refreshed. Means when I navigate from one page to another there is a page refresh.  I have worked on angular application. I did not see page refresh in angular based app.  Is it correct behavior of react-router (page refresh on navigation)?

A: Try their examples, those are easy to understand. No, it doesn't reload.
You can use <Link> or you can set the URL with history push, there are many options.
Simple Example

A: You must be using anchor tags in your reactjs code. You need to use  tag instead  tag.
So use  import {Link} from react-router and then in places where you have anchor tag replace it with Link tag.
For example:-
click here

Change above to
<Link to="example.com">click here</Link>


text:
Q: $2n+1$ numbered balls in box in arithmetic progression
We have $2n+1$ numbered balls in a box. Three balls are chosen randomly and simultaneously. Find the probability that the numbers are in arithmetic progression.

My attempt to solve it:
I have defined $$S=\{\{x_1,x_2,x_3\} | x_1,x_2,x_3 \in \{1,...,2n+1\}, x_1 \not = x_2 \not = x_3\}. $$ Then, I have defined the mass function $p: S \rightarrow [0,1] $ so that for $ \overline x \in S$, $p(\overline x)=k=\frac{1}{Card(S)}$.
Correction: $Card(S)=\binom{2n+1}{3}$.

Note: $Card()$ means cardinal.

In consequence, $\forall A \in \mathcal{P}(A)=\sum_{\overline x \in A} k =...=\frac{Card(A)}{Card(S)}.$
Now, we define $A_d=\{\{x_1,x_2,x_3\}\in S | x_2=x_1+d, x_3=x_2+d\}$ for $d>0$. Thus, the probability of the numbers being in arithmetic progression would be $ P(\cup_{d=1}^{2n+1} A_d)$. However, I am having trouble delimitating the range of $d$ so that $A\subseteq S$ and calculating the intersection between different '$A_d$'s.

I feel like there should be an easier way to calculate the probability but I really can't come up with it. Any help would be appreciated.
Thank you!

A: I will try to follow your notation, as you are almost there.
As you stated, let's write
$$A_d = \{(x_1, x_2, x_3) \in S : x_2 = x_1 + d, x_3 = x_2 + d\}$$
We want to remove the "$\in S$ " restriction, so we replace it with the definition of $S$:
$$A_d = \{(x_1, x_1 + d, x_1 + 2d) : x_1, x_1 + d, x_1 + 2d \in [1, 2n + 1]\}$$
Of course, since $d\geq 1$, we only need the final term in the A.P. to be in the interval:
$$A_d = \{(x_1, x_1 + d, x_1 + 2d) : x_1 \geq 1, x_1 + 2d \leq 2n + 1\}$$
Finally, let's rearrange the final condition:
$$A_d = \{(x_1, x_1 + d, x_1 + 2d) : x_1 \in [1, 2n - 2d + 1]\}$$
From this, clearly we have $|A_d| = 2n - 2d + 1$ (iff it's positive of course). Now since the sets $A_d$ are disjoint, We have
$$|A| = \left|\bigcup_{d=1}^n A_d\right| = \sum_{d=1}^n |A_d| = \sum_{d=1}^n 2n + 1 - 2d = n^2$$
Finally, simply divide by $Card(S)$ to get your answer!


text:
Q: How can I extend a "normal" class with a static class in Python? I'm using Python 3 and I'm trying to rewrite a graphics library that I wrote a while ago. Right now, I have a class called Scene which has three methods in addition to its constructor: logic(self), update(self), and render(self).
logic(self) handles the logic of each Scene. It handles all mouse and keyboard input, and figures out whether a button was clicked, et cetera.
update(self) can be thought of as an abstract method. Its contents are simply raise NotImplementedError. update(self) is called a certain number of times each second, and updates whatever is going on in the program, but does not draw anything on the screen. This is the framerate-independent update. If Pong were to be made with this library, the ball's position would be updated in this method.
render(self) actually updates the screen. This way, the speed of the program is not determined by the framerate.
I like my current implementation of Scene. It's really clean right now, and it seems very intuitive. However, I can't get over how to extend Scene. Suppose I want to make a Scene for a basic GUI like a main menu. I want there to be only one main menu Scene, because I don't think it's a good idea to recreate a whole other Scene every time the main menu will be viewed and used.
I started out by extending Scene with a static class, but quickly realized that it's not really possible to do that. Is the current paradigm just to extend Scene with a normal class, and then recreate and destroy it everytime that the subclass must be used? For example, should I just recreate and destroy a hypothetical MainMenu(Scene) object when viewing and leaving it, respectively?

A: Implement what the GoF refer to as Strategy Pattern, where you dynamically dispatch to appropriate logic based on current state.


text:
Q: Extra default padding problem CSS for Firefox I have that CSS for one of my elements:
background: -moz-linear-gradient(top, #3B3B3B 0%, #FFFFFF 100%);

When I inspect it at Firebug it is like:
-moz-linear-gradient(center top , #3B3B3B 0%, #FFFFFF 100%) repeat scroll 0 0 transparent

When I look  at my page it has some paddings from top left down and bottom. How can I solve it?
PS:
The problem is that. I give that style into a a div as like:
<html>
...
<body>
<div id ="myDiv">
....//That div is just under the body element so includes everything.
</div>
</body>
</html>

At firefox html element is upper than that div element and if I give that style into html element I can not see the result at my div.
It works at Chrome, I get this error at Firefox.

A: Have you removed the margin and padding from your html, body, div elements?
Something like:
html, body{
   padding:0;
   margin:0;
}

#myDiv{
   padding:0;
   margin:0;
   background: -moz-linear-gradient(top, #3B3B3B 0%, #FFFFFF 100%);
   //OTHER STYLES
}


text:
Q: Spark Standalone Mode not working in a cluster My installation of spark is not working correctly in my local cluster. I downloaded spark-1.4.0-bin-hadoop2.6.tgz and untar it in a directory visible to all nodes (these nodes are all accessible by ssh without password). In addition, I edited conf/slaves so that it contains the names of the nodes. Then I issued a sbin/start-all.sh . The Web UI in the master became available and the nodes appeared in the workers sections. However, if a start a pyspark section (connecting to the master using the URL that appeared in the Web UI), and try to run this simple example:
a=sc.parallelize([0,1,2,3],2)
a.collect()

I get this error:
15/07/12 19:52:58 ERROR TaskSetManager: Task 1 in stage 0.0 failed 4 times; aborting job
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/myuser/spark-1.4.0-bin-hadoop2.6/python/pyspark/rdd.py", line 745, in collect
    port = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())
  File "/home/myuser/spark-1.4.0-bin-hadoop2.6/python/lib/py4j-0.8.2.1-src.zip/py4j/java_gateway.py", line 538, in __call__
  File "/home/myuser/spark-1.4.0-bin-hadoop2.6/python/lib/py4j-0.8.2.1-src.zip/py4j/protocol.py", line 300, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 1 in stage 0.0 failed 4 times, most recent failure: Lost task 1.3 in stage 0.0 (TID 6, 172.16.1.1): java.io.InvalidClassException: scala.reflect.ClassTag$$anon$1; local class incompatible: stream classdesc serialVersionUID = -4937928798201944954, local class serialVersionUID = -8102093212602380348
    at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:604)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1601)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1514)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1750)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1964)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1888)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1964)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1888)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
    at org.apache.spark.serializer.JavaDeserializationStream.readObject(JavaSerializer.scala:69)
    at org.apache.spark.serializer.JavaSerializerInstance.deserialize(JavaSerializer.scala:95)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:194)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1266)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1257)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1256)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1256)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:730)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:730)
    at scala.Option.foreach(Option.scala:236)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:730)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1450)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1411)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)

Has anyone experienced this issue? Thanks in advance.

A: It's seems like it type cast exception.
Can you try input as sc.parallelize(List(1,2,3,4,5,6), 2) and re-run

A: Please, check that you use the proper JAVA_HOME.
you should set it before lauching the Spark job.
For example:
export JAVA_HOME=/usr/java/jdk1.7.0_67-cloudera
export PATH=$JAVA_HOME/bin:$JAVA_HOME/jre/bin:$PATH


text:
Q: Nvidia GeForce driver for windows 8.1 not working on windows 10 I have just recently installed Windows 10 and found that Nvidia has not came out with a specific driver for the 465 yet and was told to use the windows 8.1 driver as a workaround for Windows 10 and it still is not working it. I am getting this error in my device manager: Windows has stopped this device because it has reported problems. (Code 43)
Device PCI\VEN_10DE&DEV_06C4&SUBSYS_083910DE&REV_A3\4&2534e90f&0&0010 requires further installation.
Is there anything I can do to make my driver work so I can use my graphics card?

A: nVIDIA relased today a new Windows 10 driver, which supports your Geforce 465 GTX:

Supported products:
  GeForce 400 Series:
  GeForce GTX 465

Download and install this driver.
Download:
32Bit: http://www.nvidia.com/download/driverResults.aspx/86509/en-us
64Bit: http://www.nvidia.com/download/driverResults.aspx/86510/en-us


text:
Q: Aspose slides data labels are overlapping in 'Area Chart' I am using aspose-slides-17.3-jdk16.jar for java. I have created the Area Chart using IChartDataWorkbook. I have used multiple series to plot area chart and following image is the chart output, where the data labels are overlapped.

Is there any way to organize or fit the data labels properly?

A: @Chandra Shekar,
I have observed your requirements and like to mention that you can try using different options label.getDataLabelFormat().setLabelPosition() and label.getDataLabelFormat().setShowLabelAsDataCallout(true) methods on your end to set the individual label positions for chart data points. You can please try using following sample code on your end and may alter this as per your requirements on your end.
public static void TestAreaChart()
{
    Presentation pres = new Presentation();

    IChart chart = pres.getSlides().get_Item(0).getShapes().addChart(ChartType.Area, 50, 50, 500, 400);
    chart.getChartData().getSeries().get_Item(0).getLabels().getDefaultDataLabelFormat().setShowValue(true);
    chart.getChartData().getSeries().get_Item(0).getLabels().getDefaultDataLabelFormat()
                    .setShowLabelAsDataCallout(true);
    chart.getChartData().getSeries().get_Item(0).getLabels().get_Item(2).getDataLabelFormat()
                    .setShowLabelAsDataCallout(true);
    chart.getChartData().getSeries().get_Item(0).getLabels().get_Item(2).getDataLabelFormat()
            .setPosition(LegendDataLabelPosition.OutsideEnd);

    pres.save("C:\\Aspose Data\\AreaChart.pptx", SaveFormat.Pptx);

}

I am working as Support developer/ Evangelist at Aspose.


text:
Q: How call a screen fuction clicking tabbar button. React navigation v5, setOption. React Native i just migrate from react navigation 4 to 5.
With the v4 i did
this.props.navigation.setParams({
      scrollToTop: this._scrollToTop,
    });

inside the Screen and call the function inside my custom MyTabBar like this:
onPress={() => {
              navigation.navigate("HomeStack");
              const navigationInRoute = state.routes[0].routes[0];
              navigationInRoute.params.scrollToTop();
}}

now with the v5 i must use setOption like documentations suggests:
this.props.navigation.setOptions({
      scrollToTop: this._scrollToTop,
    });

the problem is that i dont know how to call the function inside the tabbar.
This is my tabbar:
function MyTabBar({ state, descriptors, navigation }) {
  <View style={styles.FooterContenitor}>
          <TouchableHighlight>...          </TouchableHighlight>
          <TouchableHighlight>...          </TouchableHighlight>
          <TouchableHighlight
            onPress={() => {
                  navigation.navigate("HomeStack");
                  ....how to call scrollToTop???....
            }}>...
         </TouchableHighlight>
  </View>
}

Any help? Thanks
#### UPDATE #########################
this is my structure:
const Tab = createMaterialTopTabNavigator();

export default function App() {
  return (
    <NavigationContainer ref={navigationRef}>
      <Tab.Navigator
        tabBar={props => <MyTabBar {...props} />}
        mode='modal'
        tabBarPosition="bottom"
        swipeEnabled={false}
        lazy={true}
        initialRouteName='HomeStack'//'HomeStack'
      >
        <Tab.Screen name="HomeStack" component={HomeStack}/>
        ...
      </Tab.Navigator>
    </NavigationContainer>
  );
}

A: Try:
this.props.navigation.navigate();

if you are calling a component and use the navigation inside the component you have to pass navigation props to the component.
like
<Component navigation={this.props.navigation} />

then use this.props.navigation.navigate(); inside component

A: I Solved using this inside my component:
this.props.navigation.dangerouslyGetParent().setOptions({
  scrollToTop: this._scrollToTop,
});

and calling the function:
onPress={() => {
    navigation.navigate("HomeStack");
    const indexTab = state.routes[state.index].state ? state.routes[state.index].state.index : null
    if(state.index===0 && (indexTab===0 || !indexTab)){
        const key = state.routes[state.index].key
        descriptors[key].options.scrollToTop()
    }

}}


text:
Q: Sticky tabs in NestedScrollView with ListViews The layout works as desired, except this:
When I scroll on one page, the second page scrolls too. Not as much but enough to obscure the first item.
I could imagine it'd have something to do with the NestedScrollView but I don't know how to go on.

import 'package:flutter/material.dart';

main(){
  runApp(new MaterialApp(
    home: new MyHomePage(),
  ));
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new DefaultTabController(
      length: 2,
      child: new Scaffold(
        body: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[
              new SliverAppBar(
                title: const Text('Tabs and scrolling'),
                forceElevated: innerBoxIsScrolled,
                pinned: true,
                floating: true,
                bottom: new TabBar(
                  tabs: <Tab>[
                    new Tab(text: 'Page 1'),
                    new Tab(text: 'Page 2'),
                  ],
                ),
              ),
            ];
          },
          body: new TabBarView(
            children: <Widget>[
              _list(),
              _list(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _list(){
    return ListView.builder(
      padding: EdgeInsets.zero,
      itemCount: 250,
      itemBuilder: (context, index){
        return Container(
          color: Colors.grey[200].withOpacity((index % 2).toDouble()),
          child: ListTile(
            title: Text(index.toString()),
          ),
        );
      }
    );
  }
}

A: To be able to keep the two ListViews to scroll without affecting each other they need to have defined controllers.
To have the ListViews maintain their scroll position between tab switching you need to have them in a Widget with AutomaticKeepAliveClientMixin.
Here's an example of what you can do instead of your _list method. Defined a Stateful Widget that returns your lists using both controllers and the AutomaticKeepAliveClientMixin:
class ItemList extends StatefulWidget {
  @override
  _ItemListState createState() => _ItemListState();
}

class _ItemListState extends State<ItemList> with AutomaticKeepAliveClientMixin{
  ScrollController _scrollController = ScrollController();
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ListView.builder(
      controller: _scrollController,
      padding: EdgeInsets.zero,
      itemCount: 250,
      itemBuilder: (context, index){
        return Container(
          color: Colors.grey[200].withOpacity((index % 2).toDouble()),
          child: ListTile(
            title: Text(index.toString()),
          ),
        );
      }
    );
  }

  @override
  bool get wantKeepAlive => true;
}

You can just call it normally like any other widget inside your TabBarView:
TabBarView(
  children: <Widget>[
    ItemList(),
    ItemList(),
  ],
),


text:
Q: How to test Django REST Framework Login Protected API using postman? I need to test REST API using postman. API is build using Django REST Framework. Only login user can get access to API. I am not able to find how I can send login credentials using postman. Thanks in advance.
class ApiMemberGroupNameList(views.APIView):
    permission_classes = (
        permissions.IsAuthenticated,
        RequiredOrgPermission,
        RequiredOrgStaffMemberPermission)

    def get(self, request, **kwargs):
        pk = kwargs.get('pk')
        hash = kwargs.get('hash')
        member_obj = get_object_or_404(Member.objects.filter(org__hash=hash, pk=pk))
        return Response(GroupListSerializer(member_obj.groups.all(), many=True).data)

A: If you want to use Basic Authentification to test Django REST API, it must be allowed in Django REST Framework settings:
'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
...

A: You can use Basic Auth in POSTMAN. Refer to this screenshot:

You could change the HTTP Methods, URLs, Data Payload(under Body tab) etc in the POSTMAN console
UPDATE-1
After your comments, I tried to recreated the problem.What I did was:

*

*created a view
 from rest_framework.views import APIView
 from rest_framework.permissions import IsAuthenticated
 from rest_framework.response import Response

 class MySampleView(APIView):
     permission_classes = (IsAuthenticated,)

     def get(self, request):
         return Response(data={"status": True})

*Added to urls.py
 urlpatterns = [
     url(r'^mysampleview/$', MySampleView.as_view())
 ]

And my POSTMAN response are below:
Authorization Screenshot
Header Screenshot
My conclusion
You may enter wrong credentials, or something else. I would suggest you open a new POSTMAN tab and repeat the procedure, also try to login Django admin using the same credential which is already used in POSTMAN.


text:
Q: Better way to do a Bruteforce on strings? I have come up with a pretty efficient method of bruteforcing a string in C#. (Yes, it could be used as a password cracker/generator)
Basically it works like this (this example is using a 5 character length string with only lowercase letters):

*

*Create an array that is 5 indices in length.

*Start a loop that will increment the array similarly to the way a numeral system increments it's place value (1 0 0 0 0, or 1 1 0 0 0).
Yes, I do it backwards. I work from Left to Right, not like our decimal system which works from Right to Left.

*Transform those numbers(or place values) into actual characters. This is done by using those numbers to point to an index in an array that holds all the target characters.

The code for this example is below.
using System;
using System.Text;

public class Program
{
    public static void Main(string[] args)
    {
        NumeralSystem sys = new NumeralSystem(9, new Range(0, Helpers.Chars.Length - 1));
        sys.PrintStrings();

        Console.ReadKey(true);
    }
}

public class NumeralSystem
{
    private int _Length;
    private Range _Range;

    public int Length
    {
        get
        {
            return _Length;
        }
    }

    public Range Range
    {
        get
        {
            return _Range;
        }
    }

    public NumeralSystem(int length, Range range)
    {
        _Length = length;
        _Range = range;
    }

    public NumeralSystem(int length, int min, int max)
    {
        _Length = length;
        _Range = new Range(min, max);
    }

    public void PrintStrings()
    {
        int num = this.Range.Max;
        int[] arr = new int[this.Length];
        for (int c = 0; c < arr.Length; c++) arr[c] = this.Range.Min;
        while (true)
        {
            arr[0]++;
            if (arr[0] > this.Range.Max)
            {
                for (int i = 1; i < arr.Length; i++)
                {
                    if (arr[i - 1] > this.Range.Max)
                    {
                        arr[i - 1] = this.Range.Min;
                        arr[i]++;
                    }
                }
            }

            int num2 = arr[0];
            for (int i = 1; i < arr.Length; i++) num2 += arr[i];

            //PrintArray(arr);
            Console.WriteLine(Helpers.ArrayToString(arr));

            if (num2 == this.Range.Max * arr.Length) break;
        }
    }

    private void PrintArray(int[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            if (i == arr.Length - 1)
            {
                Console.WriteLine(arr[i]);
            }
            else
            {
                Console.Write(arr[i] + ", ");
            }
        }
    }
}

public class Helpers
{
    public static char[] Chars = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
    public static string ArrayToString(int[] arr)
    {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < arr.Length; i++)
        {
            if (arr[i] >= 0)
            {
                builder.Append(Helpers.Chars[arr[i]]);
            }
            else
            {
                throw new Exception();
            }
        }
        return builder.ToString();
    }
}

public class Range
{
    private int _Max, _Min;

    public int Max
    {
        get
        {
            return _Max;
        }
    }

    public int Min
    {
        get
        {
            return _Min;
        }
    }

    public Range(int min, int max)
    {
        _Max = max;
        _Min = min;
    }
}

So is there any faster method to bruteforce a string than this? When I say "brute force a string", I mean find all possible combinations of the string, given the length, and possible characters.
Thanks for your help in advance.


text:
Q: C# save a file from a HTTP Response Im trying to download and save a file from a HttpWebResponse but im having problems saving the file (other than Text Files) properly.
I think its something to do with this part:
byte[] byteArray = Encoding.UTF8.GetBytes(http.Response.Content);
MemoryStream stream = new MemoryStream(byteArray);

Text Files work fine with the above code but when I try to save the Content to an Image file it gets corrupted.
How do i write this 'string' data to an image file (and other binary files)
Forgot to mention, This is .NET CP 3.5 and I have a wrapper class around the HttpWebResponse class to add OAuth etc.

A: Use WebClient.DownloadFile.  You can do it manually (something like this), but WebClient is the best bet for simple downloads.

A: The problem is you're interpreting the binary data as text, even if it isn't - as soon as you start treating the content as a string instead of bytes, you're in trouble. You haven't given the details of your wrapper class, but I'm assuming your Content property is returning a string - you won't be able to use that. If your wrapper class doesn't let you get at the raw data from the web response, you'll need to modify it.
If you're using .NET 4, you can use the new CopyTo method:
using (Stream output = File.OpenWrite("file.dat"))
using (Stream input = http.Response.GetResponseStream())
{
    input.CopyTo(output);
}

If you're not using .NET 4, you have to do the copying manually:
using (Stream output = File.OpenWrite("file.dat"))
using (Stream input = http.Response.GetResponseStream())
{
    byte[] buffer = new byte[8192];
    int bytesRead;
    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, bytesRead);
    }
}

A: Simplest way I found is:

*

*Use ReadAsByteArrayAsync to get the data.

*List item
File.WriteAllBytes to save the file.

No need to loop through anything.  Example in context below:
[TestClass]
public class HttpTests
{
    [TestMethod]
    public void TestMethod1()
    {
        var jsObject = (dynamic)new JObject();
        jsObject.html =  "samplehtml.html";
        jsObject.format = "jpeg";
        const string url = "https://mywebservice.com/api";

        var result =   GetResponse(url, jsObject).GetAwaiter().GetResult();
        File.WriteAllBytes($@"c:\temp\httpresult.{jsObject.format}", result);
    }

    static async Task<byte[]> GetResponse(string uri, dynamic jsObj)
    {
        var httpClient = new HttpClient();
        var load = jsObj.ToString();
        var content = new StringContent(load, Encoding.UTF8, "application/json");
        var response = await httpClient.PostAsync(uri, content);
        return await response.Content.ReadAsByteArrayAsync();
    }
}


text:
Q: Responsive dashboard on css grid I have a question. Does anyone have a css-grid template for an responsive dashboard. With the ability to hide the sidebar on large screens, but leave only the icons and the departing sidebar on a small screen. Without anything superfluous. Thank you all.

A: I believe you are looking for some CSS frameworks.

With the ability to hide the sidebar on large screens, but leave only the icons and the departing sidebar on a small screen.

This should be implemented manually and I don't think frameworks might even provide it.

list of some CSS frameworks that might help you:

*

*BootStrap

*Bulma

*Tailwind CSS

*Materialize

*Spectre

*Milligram

*Water.css

*Windi CSS

*Mobi.css

A: Naive UI is a great library that has components like these.
https://www.naiveui.com/en-US/os-theme


text:
Q: tikz text width causes error What am I doing wrong to have this error in my thesis report ?
The error:
./Chapter1.tex:666: Package pgfkeys Error: I do not know the key '/tikz/width',
 to which you passed '12cm', and I am going to ignore it. Perhaps you misspelle
d it.

See the pgfkeys package documentation for explanation.
Type  H <return>  for immediate help.
 ...

l.666 ...t=5cm,node distance=5cm,fit=(A1)(B1)(C1)]
                                                  (container){};
?

The source code:
\begin{figure}[H]
\centering
\begin{tikzpicture}[above]
\node[b,text width=3cm,below=3cm, node distance=2cm]at (6,7)(but){Mise à jour "But"};
\node[b,text width=3cm,below=3cm, node distance=2cm]at (-2,-8)(commande){Commande};
\node[b,text width=3cm,below=3cm, node distance=2cm]at (6,-8)(mise){Exécution des requêtes  et la mise à jour};
\path [l] (but.west) -| (-2,2.2);

\node[text width=6cm]at (0,2)(A0){Planificateur};
\node[c,text width=3cm]at (-4,1)(A){Fonctions de planification};
\node[c,text width=3cm,below=1cm] at (-4,1) (B){Gestionnaire "état/ressource"};
\node[c,text width=3cm] at (0,1)(C){Modélisation déclarative};
\node[c,text width=3cm,below=1cm] at (0,1)(D){Mise à jour "Etat/Activité"};
\node[c,text width=3cm,below=3cm]at (-2,1)(E){Envoi d'activité};
%%line 666 %%% \node[c,text width=12cm,minimum height=6cm,node distance=3cm,fit=(A)(B)(C)(D)(E)](container){ };
\vspace{2cm}
\node[text width=8cm]at (6,-2)(A01){ };
\node[c,text width=6cm, node distance=5cm]at (6,-2)(A1){Base de données "plan d'activité"};
\node[c,text width=6cm, node distance=5cm] at (6,-3) (B1){Synchronisation "Planificateur/B.D"};
\node[c,text width=6cm, node distance=5cm] at (6,-4)(C1){Exec "activité D.B"};
%%%\node[c,text width=3cm,below=1cm] at (8,-3)(D1){Mise à jour "Etat/Activité"};
%%%\node[c,text width=3cm,below=3cm]at (6,-3)(E1){Envoi d'activité};
\node[c,width=12cm,minimum height=5cm,node distance=5cm,fit=(A1)(B1)(C1)](container){};
\node[text width=6cm, node distance=2cm]at (0,-5)(A02){Exécutif TDL};
\node[c,text width=3cm,node distance=2cm]at (-4,-6)(A2){Modélisation procédurale};
\node[c,text width=3cm,below=1cm,node distance=2cm] at (-4,-6) (B2){Synchronisation des tâches};
\node[c,text width=3cm, node distance=2cm] at (0,-6)(C2){Mise à jour des tâches};
\node[c,text width=3cm,below=1cm, node distance=2cm] at (0,-6)(D2){Exception/Surv.. d'état};
\node[c,text width=3cm,below=3cm, node distance=2cm]at (-2,-6)(E2){Envoi d'activité};
\node[c,width=12cm,minimum height=6cm,node distance=4cm,fit=(A2)(B2)(C2)(D2)(E2)](container){};

\path [l] (E.south) -| (-2,-4.75);
\path [l] (1.75,1) -- (2,1);
\path [l] (2,1) |- (A1.west);
\path [l] (A1.west) -| (2,1);
\path[l](2,-4)|-(C2.east);
\path[l](2,-4)|-(2.75,-4);
\path[l](D.east)-|(2,-4);
\path[l] (E2.south)--(commande);
\path[l] (D2.east)-|(mise.north);
\path[l] (mise.north)|-(D2.east);
\path[l] (-6.5,1)|-(commande.west);
\path[l] (-6.5,1)|-(A.west);
%\draw[densely dashed] (-4,-12) -- (6,-12) node {c.fonctionnelle.};
\end{tikzpicture}
\caption{Architecture \ac{CLARAty}.}
\label{Architectureclaraty}
\end{figure}


text:
Q: Printing current time in different time zones in C I'm trying to print in the console the current time in my local timezone (-0600), then printing the time at the +0100 timezone. Currently I'm using gmtime, and adding 1 to the tm_hour section.
However when using strftime, it still prints the: "... +0000".
How can I print it properly? How can I change my effective time zone, for instance?

A: On macOS Sierra 10.12.2 with GCC 6.3.0, the following code works:
#include "posixver.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#ifndef lint

extern const char jlss_id_settz_c[];
const char jlss_id_settz_c[] = "@(#)$Id: settz.c,v 1.2 2017/01/23 07:06:21 jleffler Exp $";
#endif

static void time_convert(time_t t0, char const *tz_value)
{
    char old_tz[64] = "-none-";
    char *tz = getenv("TZ");
    if (tz != 0)
        strcpy(old_tz, tz);
    setenv("TZ", tz_value, 1);
    tzset();
    char new_tz[64];
    strcpy(new_tz, getenv("TZ"));
    char buffer[64];
    struct tm *lt = localtime(&t0);
    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", lt);
    if (strcmp(old_tz, "-none-") == 0)
        unsetenv("TZ");
    else
        setenv("TZ", old_tz, 1);
    tzset();
    printf("%ld = %s (TZ=%s)\n", (long)t0, buffer, new_tz);
}

int main(void)
{
    time_t t0 = time(0);
    char *tz = getenv("TZ");
    if (tz != 0)
        time_convert(t0, tz);
    time_convert(t0, "UTC0");
    time_convert(t0, "IST-5:30");
    time_convert(t0, "EST5");
    time_convert(t0, "EST5EDT");
    time_convert(t0, "PST8");
    time_convert(t0, "PST8PDT");
}

By default, TZ is not set in the environment — those ungainly tests for getenv("TZ") returning NULL are necessary to handle that.  When run, the output is:
$ ./settz
1485155290 = 2017-01-23 07:08:10 (TZ=UTC0)
1485155290 = 2017-01-23 12:38:10 (TZ=IST-5:30)
1485155290 = 2017-01-23 02:08:10 (TZ=EST5)
1485155290 = 2017-01-23 02:08:10 (TZ=EST5EDT)
1485155290 = 2017-01-22 23:08:10 (TZ=PST8)
1485155290 = 2017-01-22 23:08:10 (TZ=PST8PDT)
$

With the environment set so TZ=US/Alaska, the output is:
$ TZ=US/Alaska ./settz
1485155395 = 2017-01-22 22:09:55 (TZ=US/Alaska)
1485155395 = 2017-01-23 07:09:55 (TZ=UTC0)
1485155395 = 2017-01-23 12:39:55 (TZ=IST-5:30)
1485155395 = 2017-01-23 02:09:55 (TZ=EST5)
1485155395 = 2017-01-23 02:09:55 (TZ=EST5EDT)
1485155395 = 2017-01-22 23:09:55 (TZ=PST8)
1485155395 = 2017-01-22 23:09:55 (TZ=PST8PDT)
$

This is ugly as a technique; it is also not fast.  However, on some platforms, it does in fact work.


text:
Q: React reuses components instead of creating new so that I have to rely on componentWillReceiveProps to load fresh data I have a problem with ReactJS as when in parent component's state that stores child components (as thumbnails) the child components stored as array of components are constructed once and have componentDidMount called once. Once I 'reimport' data and create new child components based on new data from backend API (for example upon new sorting mode activated) the components do not call componentDidMount and i have to rely on componentWillReceiveProps method to import for example a link to the picture to be displayed on a thumbnail (it seems like react reuses components). If for example the the data in child components is being imported slowly it shows and old photo because remembers previous iteration done in own componentDidMount done after creation.
How can i force react to always create new child components from the scratch and thanks to that achieve having componentDidMount called to include data import from backend and avoid relying on componentWillReceiveProps call?
Here is the pseudocode where parent component ComponentManager imports person data from backend and creates thumbnails based on retrieved JSON. Thenafter it can upodate thumbnails after user changes sorting order:
class ComponentManager extends Component {

constructor(props) {
    super(props);
    this.state = {
        personsThumbnails : undefined
    }
}

componentDidMount() {
    // Import person ids and create SinglePersonThumbnail(s) child components as the state personsThumbnails
    importPersonsIds();
}

importPersonsIds(sortingMode) {
// Importing persons data from backend API and created thumbnails stored in personsThumbnails state
...
}

render() {
    return(

        <button onClick={()=>{this.importPersonsIds("SORT_BY_AGE")}}>Sort by age</button>
        <button onClick={()=>{this.importPersonsIds("SORT_BY_NAME)}}>Sort by name</button>

            {this.state.personsThumbnails}

    );
}
}

class SinglePersonThumbnail extends Component {

constructor(props) {
    super(props);
    this.state = {
        photoUrl : undefined,
        personsName : undefined
    }
}
componentDidMount() {
// Called when component is created
    this.importDataAndPhotoForPerson(this.props.id);
}

componentWillReceiveProps(nextProps) {
// Called always when ComponentManager changes the order of thumbnails upon other sorting mode triggered
    this.importDataAndPhotoForPerson(this.props.id);
}

importDataAndPhotoForPerson(id) {
    // Imports name of the person and link to photo stored in state
}

render() {
    return(
        // Display image by link and person's name based on photoUrl and personsName states!
    );
}
}

A: you can use componentDidUpdate() and can see the documentation from official site.
componentWillReceiveProps is outdated and not recommended. A better idea will be to store the data from backend in some context/redux. This will cause the child components to re-render with updated data.


text:
Q: BlueZ hci_* API to make the host discoverable Environment:

*

*Linux

*BlueZ Bluetooth stack

*C API

*No usage of the dbus interface

I must say that the HCI BlueZ C API ( hci_lib.h ) is poorly documented, having that said, Is there a C hci_* API controlling the host discover-able state? something similar to "hci_write_simple_pairing_mode" enabling control of discoverability?

A: The following hci command makes the adapter discoverable
   hciconfig hci0 piscan
Following is the corresponding code from hciconfig
if (!strcmp(opt, "pscan"))
    dr.dev_opt = SCAN_PAGE;
else if (!strcmp(opt, "piscan"))
     dr.dev_opt = SCAN_PAGE | SCAN_INQUIRY;
if (ioctl(ctl, HCISETSCAN, (unsigned long) &dr) < 0) {

Here ctl is what is got from:
 if ((ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)) < 0)

A: Solution can be found at hciconfig.c in specific at 'cmd_scan' implementation ( having opt = "piscan" ), derivation of that follows
    HRESULT BluZbridge::SetDiscoverable(IN BOOL bVisible) {
        if (0 == m_fdHCI)
            return HRESULT_FROM_WIN32(ERROR_NOT_READY);
        hci_dev_req req = { DEFAULT_HCI_ADAPTER_ID, ((TRUE == bVisible) ? (SCAN_PAGE | SCAN_INQUIRY) : SCAN_DISABLED) };
        if (ioctl(m_fdHCI, HCISETSCAN, (unsigned long)&req) < 0) {
            perror("Can't set scan mode on hci0");
            return HRESULT_GET_ERRNO();
        }
        return S_OK;
    }


text:
Q: Accessibility of a session in a view I have created a Zend session in a view:
$user = Tools::getUserByLoginAndPassword($form);

if ($user instanceof Membre)
{
  $sessionUser = new Zend_Session_Namespace('user');
  $sessionUser->data = $user;

  $this->_redirect('/adresse');
}

I have tested $sessionUser->data, it contains the right data.
But i need to get this session in another view, and there, it's not working anymore...
for instance
<?php var_dump($sessionUser->data->prenom); ?>

displays "NULL"
it worked fine in the previous view but not in this one.
I have placed my Zend_Session::start();
in the init() function of my controller...
thanks in advance for your help

A: If you want to use your session in another view, you have to instantiate it again. So if you use the following code you should be able to access your data:
<?php
    $session = new Zend_Session_Namespace('user');
    Zend_Debug::dump($session->data);
?>


text:
Q: Cannot find element in Window object in Chrome, but works in IE I have the following javascript for a multiselect dropdown list with checkboxes which works just fine in IE:
function checkAll(textId, checkId, hiddenId) {
var checkBox1 = document.getElementById(checkId);
var textElement = document.getElementById(textId);
var hiddenElement = document.getElementById(hiddenId);
    if (checkBox1.checked) {
        for (var item in window[textId]) {
            if (typeof window[textId][item] != "function") {
                var checkBox = document.getElementById(item);
                if (window[textId][item].text != "Not Supported")
                try
                {
                    checkBox.checked = true;
                    }
                    catch (exception)
                    {
                    }
                if (window[textId][item].text != "Select/De-select All" && window[textId][item].text != "Not Supported")
                    textElement.value += window[textId][item].text + ", ";
                    hiddenElement.value += window[textId][item].value + "|";
            }
        }
        }
     else if (!checkBox1.checked) {
            for (var item in window[textId]) {
                if (typeof window[textId][item] != "function") {
                    var checkBox = document.getElementById(item);
                    checkBox.checked = false;
                    textElement.value = "";
                    hiddenElement.value = 0;
                }
            }
        }
}

However, in Chrome it does not work. The problem is that this line
for (var item in window[textId])

assigns to the var item the actual checkbox id
ctl00_MainContent_TabContainer1_TabPanel1_Multiselect1_ctl01

in IE. However, in Chrome, this assigns to item something called "webkitEntries," which is not what I am looking for. btw textID here is the ID of the parent control
ctl00_MainContent_TabContainer1_TabPanel1_Multiselect1_TextControl

Does anyone know how to get the checkbox id for each in Chrome? Thanks and apologies for any lack of clarity -- I`m pretty new to js


text:
Q: help free inode but no space with weird percentage i'm kindof a newbie at this , but when i list the disk usage with df command  ,i get that the percentage of inodes used is 1 percent (%iused = 1%)but the 99% of the filesystem is used ( only 1 percent is free : used : 99% ) How is that possible and what does that mean
thank you

A: This probably means that you have many big files on this filesystem. Or at initialization the (probably default) ratio of inode per bytes was not the optimum value.
Having "too many" inodes is not a problem per se, the problem is often more when you have too little of them (you can have a lot of space free on your disk but if you do not have any inode free you will not be able to store anything new).
Things also depend on which filesytem you use: ext3, ext4, xfs, reiserfs, btrfs, etc. Have a look at the mkefs specific to your filesystem for explanations on inode usage.


text:
Q: Trying to write to a file, getting FileNotFoundException (Read-only file system) So basically I have a program that utilizes Robotium to run tests on an android device, and all the tests work great. Certain tests also have timestamps, and I want to save those timestamps to a file so I can use them elsewhere, so I wrote a simple method.
public static void saveTimestamps(Timestamp ts) throws IOException {
    FileWriter fw = new FileWriter(
        "C:\\Users\\brendonn\\workspace\\TestProject\\timestamps.txt");
    fw.write(ts.toString());
    fw.close();
}

But for every test that uses this method I get
java.io.FileNotFoundException: /timestamps.txt (Read-only file system)
And I'm not sure where to go from here. I'm not trying to write to the phone, I'm just writing a text file to my computer. I can do the exact same thing in other classes on this computer and it works.

A: As near as I can see from a quick look at the Robotium home page, this tool runs ON the target system! If that's correct, your method is trying to write to something on the Android device, where the path doesn't exist.
Note that the front page of the Robotium project talks about a future feature of running the tests from the PC.
You could try saving the timings to a file on the target device (the app would need permission to write somewhere), or you could perhaps send the data out as log messages and capture the log output on your PC.


text:
Q: QueryDSL - Sum where a join is involed Given the following classes:
class User {
    @OneToMany
    Set<Transaction> transactions
}

class Transaction {
     BigDecimal money;
}

I'm stumped how to perform an aggregate, as the functions don't appear to be available on a the following query:
QUser $user = QUser.user;
QTransaction $transaction = QTransaction.transaction;
query().from($user)
    .innerJoint($user.transactions, $transaction)
    .where($user.eq(myUser))
    // Now what?

As a bonus -- is this possible if the money is persisted as a Joda Money type, rather than as a BigDecimal?
(I'm using UserType's Joda Money support to facilitate persistence)

A: Something like this should work
QUser $user = QUser.user;
QTransaction $transaction = QTransaction.transaction;
query().from($user)
    .innerJoin($user.transactions, $transaction) //inner join clause
    .where($user.eq(myUser))
    .singleResult($transaction.money.sum());

Querydsl doesn't have (yet) direct support for Joda Money, so using Joda Money the sum() method won't be available directly.


text:
Q: ListItem onClick issue I have a listview and in each of listitems I am adding a checkbox, two textviews and imageview. What I want is to have a click action on listitem and a separate click action on imageview as well (which lies in the listitem).
I used the following code for itemclick event :
lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                long arg3) {
            CustomizeDialog customizeDialog = new CustomizeDialog(desserts.this);            // Used to show a dialog
            customizeDialog.show();
            // TODO Auto-generated method stub

        }

    });

Also on clicking item checkbox is checked. So, two things are happening (checkbox is checked and dialog appears), which is true according to functionality. I want that when user clicks the listitem checkbox is checked or unchecked and no dialog should appear, and when user click imageview on same listitem,only a dialog is shown above and no checkbox is checked or unchecked.
How can I achieve that? Please help.
Stone

A: you need to use an Adapter and set your listeners for your checkbox and dialog in the getView() of this adapter.
see: http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
Update textView from an item in a custom listView Android

A: set the listener into the getView()
like for example:-
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_layout, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.image1 = (ImageView) view.findViewById(R.id.image1);
viewHolder.image1.setOnClickListener(new OnClickListener(){
        @Override
        public voic onClick(View v){
             // do something here
        }
});
viewHolder.text1 = (TextView) view.findViewById(R.id.text1);
viewHolder.checkBox = (CheckBox) view.findViewById(R.id.checkbox);
viewHolder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
     @Override
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // do something
     }
});
view.setTag(viewHolder);


text:
Q: How can I programmatically add text as if it was copied to be pasted? I would like to write a ruby program preferably, that can take a string object and write it's contents to the clipboard in windows to be pasted.
Easiest test case, a command that can be run globally like cat, but instead of stdout it writes to the clipboard, for things like ssh keys.

A: You can try this gem.
I haven't personally tested.
Here is the page of the project that implements the gem.

A: I've never used IronRuby, but I think this would also work if running that interpreter (untested):
include System::Windows::Forms
Clipboard.SetText 'foo'


text:
Q: Stubbing a mock's method with Sinon.js I'm having trouble using a mock to replace a dependency of my class when testing, using Sinon.js and Buster.js.
I'm testing class B, which has a dependency on class A. I use Sinon.js to create a mock object of class A, and pass it into an instance of class B. In my test I call the doSomething method of object B, which then calls the getData method of object A. (Though the getData method is actually on A's prototype, not A itself).
But when I run the test I get the error:
TypeError: a.getData is not a function

If I try and stub the getData method of A's prototype, then I get the error:
TypeError: Attempted to wrap getData which is already stubbed

The error occurs on the line where I'm setting mock_A.expects('getData').
This is the classes and test I'm running:
function A(){};
A.prototype = {
    "getData" : function(oDataToGet, cb) {
        var aData = ['someData'];
        cb(aData);
    }
}
function B() {
    var a;
    this.setA = function(oA){
        a = oA;
    };
    this.doSomething = function(oObj){
        a.getData({}, function(aData){if(!aData){throw new Error('No data');} oObj.data = aData[0];});
    }
}

var oB, assert = buster.referee.assert;
buster.testCase('myTest', {
    "setUp" : function()
    {
        oB = new B();
    },
    "test_Mock" : function()
    {
        var mock_A = sinon.mock(new A());
            oB.setA(mock_A);
    //        sinon.stub(A.prototype, 'getData').callsArgWith(1, ['hi']);
        mock_A.expects('getData')
            .withArgs({})
            .once();
        var oTestObj = {};
        oB.doSomething(oTestObj)
        mock_A.verify();
    }
});

Edit 2016-03-16 to add:
A workaround is to use a stubbed instance rather than a mock, and then set the method you need to check to an expectation:
var stubbed_A = sinon.createStubInstance(A);
stubbed_A.getData = sinon.expectation.create('getData')
    .withArgs({})
    .once();
oB.setA(stubbed_A);
var oTestObj = {};
oB.doSomething(oTestObj);
stubbed_A.getData.verify();

A: There is a difference between sinonJS and other mocking frameworks (like Mockito, jMock etc.) that creates this misunderstanding. In most mocking frameworks, you create the mocked dependency and inject it in the object-to-be-tested (SUT), as you did:
var mock_A = sinon.mock(new A());
oB.setA(mock_A);

However, in sinonJS, you have to inject the original object and use the generated mock object to assign expectations over the original one. So, if you change the previous 2 lines with the following, your test works as expected:
var a = new A();
var mock_A = sinon.mock(a);
oB.setA(a);

Stubs are more appropriate, when we want to control the behaviour of a dependency of the object we are testing. Mocks are more appropriate, when we want to ensure that a specific event will happen on the dependency of the object we are testing (via expectations). So, in this case, a mock object would be more suitable than a stub, as in your first attempt.


text:
Q: Grabbing Facebook life events Ive been looking for a way to pull recent life events for friends from the graph API but I've ran into a blocker for locations.
I know you can query friends for their location. But is it possible to find previous location history (or just history in general, if someone was given a promotion at work so they change their role?).
Excuse the lack of code as I'm posting from my mobile.
What I have for locations is:
->api('/me/friends?fields=name,location);
Which works fine for current location.
Any tips would be great. Thanks.

A: So it turns out the best way to do this is to use FQL against the "stream" table. From here we can add WHERE clauses to do exactly what I'm after. The hardest part is the lack of documentation provided by Facebook on a specific field. "Type".
https://developers.facebook.com/docs/reference/api/user/
https://developers.facebook.com/docs/reference/fql/stream/
Permissions required: "read_stream"
Doing the initial query "SELECT post_id, actor_id, target_id, message FROM stream WHERE filter_key in (SELECT filter_key FROM stream_filter WHERE uid=me() AND type='newsfeed') AND is_hidden = 0" gives you a wide list of updates within your news stream.
So by changing a few things on my test account I was able to find the "type"'s that matched the activity changes on a users account.

*

*Work update - 305

*Education update - 305

Work and Education are grouped.

*

*Relationship status - 62

*Changed locations - 282

So say if we wanted to be specific and look for one activity we can change the "type" to be equal to the id's mentioned above.
$query = "SELECT post_id, actor_id, target_id, message, created_time, description, description_tags, type, place FROM stream WHERE type = '62' filter_key in (SELECT filter_key FROM stream_filter WHERE uid=me())";
$response = $this->facebook->api('/fql?q=' . urlencode($query));

The response will look something like this:
'data' => array(
        (int) 0 => array(
            'post_id' => '100035395_38758242', //I've changed this post id to be random
            'actor_id' => (int) 4242, //I've changed this actor_id to be random
            'target_id' => null,
            'message' => '',
            'created_time' => (int) 1347601178,
            'description' => 'Joe Smith updated his work and education on his timeline.',
            'description_tags' => array(
                (int) 0 => array(
                    (int) 0 => array(
                        'id' => (int) 4242, //I've changed this id to be random
                        'name' => 'Joe Smith',
                        'offset' => (int) 0,
                        'length' => (int) 8,
                        'type' => 'user'
                    )
                )
            ),
            'type' => (int) 305, //<--- Note the type id
            'place' => null
        ),
);

Now we need to be aware that Education and Work history can be combined, and potentially other types can be as well. We can from here query the "post_id" directly to get more information related to it.
$post = $this->facebook->api('/100035395_38758242');

The response of this could be something like:
array(
    'id' => '100035395_38758242',
    'from' => array(
        'name' => 'Joe Smith',
        'id' => '4242'
    ),
    'story' => 'Joe Smith added Harvid University of America to his timeline.',
    'story_tags' => array(
        (int) 0 => array(
            (int) 0 => array(
                'id' => '4242',
                'name' => 'Joe Smith',
                'offset' => (int) 0,
                'length' => (int) 8,
                'type' => 'user'
            )
        )
    ),
    'actions' => array(
        (int) 0 => array(
            'name' => 'Comment',
            'link' => 'http://www.facebook.com/3535/posts/345345' //Changed
        ),
        (int) 1 => array(
            'name' => 'Like',
            'link' => 'http://www.facebook.com/345345/posts/34534' //Changed
        )
    ),
    'type' => 'link',
    'created_time' => '2012-09-14T05:39:38+0000',
    'updated_time' => '2012-09-14T05:39:38+0000',
    'comments' => array(
        'count' => (int) 0
    )
)

The alternative could be to also query the user id directly and pull fields relevant to the "type". I.e. 'work' or 'education'.
$friend = $this->facebook->api('/242?fields=work,name,education,id');

NOTE: If you require data from X Weeks or Months ago you should use the "created_time" within your queries to Facebook, otherwise you're limited to: 30 days or 50 posts per query.


text:
Q: GCM Push Notifications not getting recieved on Lollipop devices Ok,
I'm developing an android app which is enabled with GCM for Push Notifications.
I was having trouble getting push notifications on any device (lollipop / pre-lollipop) when on college wifi. I researched about it and found that the port 5228, 5229, 5230 on my college's firewall (Cyberroam) were closed. So the administrator opened them and now I am receiving push notifications, but only on pre-lollipop devices. Lollipop & Post-lollipop devices still aren't receiving push notifications.
No problem occurs when i use the app on cellular data or on private wifi (at my place).
I'm not able to understand why this is happening.
NOTE: Interesting thing is that all MI devices are receiving push irrespective of their Android version.
Can someone explain what might be happening and solution to this problem.
Thanks.

A: I found out that the Cyberroam was blocking all requests from the GTalk service. That is why push notifications were not getting through. It is resolved now.
Thanks


text:
Q: Still combating multidimensional arrays I've put forward two issues with multidimension array before, I'm really appreciated those who had helped me with it. Now there's still a not fixed bug in my codes like the one showed below:
#include "Algorithm.h"

template<int size>
void strassen_matrix_multiplication(int (*A)[size], int (*B)[size], int (*C)[size]){
  int n = size / 2;

  int A11[n][n];
  int P1[n][n];
  int S1[n][n];
  strassen_matrix_multiplication(S1, A11, P1);
}

Now I got a compilation error int line 5 said that:

no matching call to function 'strassen_matrix_multiplication'

So how can I fix it? I've modified my codes sevaral times but in vain. Thanks for any help.

A: There was quite a few issues with your code, one of them being infinite recursion because you didn't catch the base case where size is 1 or 0.
I have created some template specializations to resolve this infinite recursion.
Then passing your 2D arrays,  you have to pass them as 2D arrays, because a 2D array int[N][N] is not convertible to an array of pointers int*[].
Below is the code and it compiles with only a few warnings as regards unused parameters.
#include<iostream>

// Header file

#include <fstream>
#include <ostream>
#include <string>

template<int size> struct strassen
{
static void strassen_matrix_multiplication(int A[size][size], int B[size][size], int C[size][size]){
  const int n = size / 2; //make this a compile time constant

  int A11[n][n] = {};
  int P1[n][n] = {};
  int S1[n][n] = {};
  strassen<n>::strassen_matrix_multiplication(S1, A11, P1);
}
};

template<> struct strassen<1>  {
static void strassen_matrix_multiplication(int A[1][1], int B[1][1], int C[1][1]){}
};

template<> struct strassen<0>  {
static void strassen_matrix_multiplication(){}
};

int main()
{
    int arr[3][3];
    strassen<3>::strassen_matrix_multiplication(arr, arr, arr);
}


text:
Q: webpack configuration webpack-dev-server does not compile files on the fly I have following webpack configuration file.
const path = require('path');
const webpack = require('webpack');

module.exports = {
output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'scripts.min.js'
},

resolve: {
    root: [
        path.resolve('./src'),
        path.resolve('./node_modules')
    ]
},

entry: './src/app.js',

module: {
    loaders: [
        {
            test: /\.js$/,
            loader: 'babel'
        }
    ]
},

devServer: {
    // compress: true,
    inline: true,
    stats: 'errors-only'
},

plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({ 'mangle': false, sourcemap: false })
]

};
The problem is that when I run webpack-dev-server command, it does run the server but when I make changes to any js file they are not compiled on the fly. So I had to stop the server and run webpack and then run webpack-dev-server command to make things work.
How can I make webpack-dev-server work so that when watches for all js, css, scss files and compile those fly?

A: If you are working with an IDE, you have to disable "safe write".

Note that many editors support "safe write" feature and have it enabled by default, which makes dev server unable to watch files correctly. "Safe write" means changes are not written directly to original file but to temporary one instead, which is renamed and replaces original file when save operation is completed successfully. This behaviour causes file watcher to lose the track because the original file is removed. In order to prevent this issue, you have to disable "safe write" feature in your editor.

http://webpack.github.io/docs/webpack-dev-server.html#hot-mode


text:
Q: Find the minimum distance of some bad binary code Let $M$ be a $n \times n$ matrix over the finite field of two elements that satisfies the following property$\colon$ the total number of 1's in each row coincides with one in each column. In other words, there is a number $N$ such that

*

*The number of non-zero elements in each row of $M$ is $N$.

*The number of non-zero elements in each column of $M$ is $N$.
Moreover, the matrix $M$ is such that the sum of some two distinct rows of $M$ is a row of $M$ also.
I hope there are non-trivial answers to the following questions.
Question 1. Which additional properties the matrix $M$ may has?
Question 2. Let $C$ be the binary code obtained as the right kernel of $M$. What can one say about the weight enumerator of $C$? In particular, what are the best bounds on the minimum distance of the code $C$ can be obtained?
I believe that, for example, the algebraic graph theory can be applied to the last question. Unfortunately, I am not a specialist in this theory (as well as in error-correcting codes).
More precisely, the rank of $M$ is less or equal to $q-1$ and $n=\frac{q^2-q}{2}$, $N=\frac{q^2-1}{4}$ where $q$ is an odd prime power.
UPD 1. For example, if $q=5$, then we obtain the following matrix$\colon$
$\left(\begin{array}{rrrrrrrrrr}
0 & 1 & 1 & 1 & 1 & 1 & 0 & 1 & 0 & 0 \\
1 & 0 & 1 & 0 & 1 & 1 & 0 & 0 & 1 & 1 \\
1 & 0 & 1 & 1 & 0 & 0 & 1 & 1 & 1 & 0 \\
0 & 1 & 0 & 0 & 0 & 1 & 1 & 1 & 1 & 1 \\
1 & 1 & 0 & 1 & 0 & 0 & 0 & 1 & 1 & 1 \\
1 & 1 & 0 & 0 & 1 & 1 & 1 & 0 & 1 & 0 \\
0 & 0 & 1 & 1 & 1 & 0 & 1 & 0 & 1 & 1 \\
0 & 0 & 0 & 1 & 1 & 1 & 1 & 1 & 0 & 1 \\
1 & 1 & 1 & 0 & 1 & 0 & 1 & 1 & 0 & 0 \\
1 & 1 & 1 & 1 & 0 & 1 & 0 & 0 & 0 & 1
\end{array}\right)$

A: Unfortunately, the nice property that every distinct pair of rows yields another row by mod 2 vector addition has been withdrawn.  However, it may be possible to regard M as having maximal subsets of rows where this property holds, and still say something useful about M.
The comment above regarding Hadamard matrices goes as follows: since every row has the same number N of ones, and since the sum of two rows A and B is also a row, the number N of ones is even, and the number of columns which have ones in both A and B is N/2, half the number of columns which have ones in either row A or row B.
Suppose we have a small collection F of rows of M that generates by mod 2 addition a slightly larger collection of rows G, such that G is a subset of rows of M, and such that the sum of any two rows of G also has N ones (even though the result may be not a row of M and thus outside of G). Suppose further we can adjust the length of the rows of G so that each row has as many zeros as it has ones, without giving up any of the ones already present in G.
Now, copy each row in G into a new set H, but for every zero replace it by -1, and let each row in H have N ones and the same number of occurrences of -1, by resizing if needed.  Now every two distinct rows have dot product 0, and are part of a Hadamard matrix.  If the closure property had held for M, the rows of H would be one coordinate longer, and with the addition of a row of all ones, would have formed a Hadamard matrix.
This suggests that the actual M is composed of fragments of a Hadamard matrix, somehow shortened and glued together.  Since we do not know how large F or G is, it becomes challenging to say much more.  However, if the matrix (Edit M when considered over the real numbers and not over the two element field, thank you Gerry Myerson) is of full rank (contrary to claims in the post), it may be possible to say something about the size of the determinant of M.
Gerhard "Imagines A Spectrum Of Possibilities" Paseman, 2017.01.24.


text:
Q: Is there a standard way to read "30+"? I have just come across the following sentence:

Our team has cataloged 30+ [design patterns] across various areas of the framework so far.

I have often seen the pattern "number + plus sign" to refer to an unknown quantity above the given number. When I read that sentence I usually "translate" the expression as "more than 30", so I would read:

Our team has cataloged more than 30 design patterns across various areas of the framework so far.

But now I'm curious. Do you usually read the sentence like that, or read it like "30 plus" or "above 30" or in some other way? Is there a common, standard way to read the "number + plus sign" construction when you find it in sentences? Or is that construction discouraged? (Example: it may be unfriendly for sight-impaired people trying to use text-to-speech software.)

A: "30+" is the non-alphabetic equivalent of the written phrase "thirty-plus", which is said just as it looks. Some examples of the written phrase:

The class sizes were thirty-plus (as opposed to fifteen to twenty at Abbey Hall) . . . .
  —Ben Elton, Meltdown, 2009
It was thirty-plus years ago but it was still fresh in his mind since the media continually reminded the public that the last cup victory was thirty-plus years ago.
  —Rick Ferguson, The Ghosts in Maple Leaf Gardens, 1998, 2013
My Quest to be a Single Dad: Thirty-Plus Years Trying to Adopt
  —title of 2009 book by Garry White
There were thirty-plus people dining with us for Christmas dinner.
  —Sara McDaniel H. Kemp, From Dawn to Dusk, 2013

The exact meaning is intentionally a bit fuzzy, but seems to be an ellipsis for "thirty plus [some amount]" where the amount is often greater than zero and less than ten (so "30+" equates to "somewhere between 31 and 39, inclusive") but can also be zero at the low end and/or any number at the high end (i.e. "30+" is "at least thirty"). Examples of this latter usage are easiest to see when looking at known minimums, such as the US drinking age:

[F]ans typically have to be twenty-one plus in the United States to get into the venues where bands play . . . .
  — David Buckingham, Youth, Identity, and Digital Media, 2008 (snippet view)
It was a twenty-one-plus show, which worried us, but we drew one hundred and sixty people . . . .
  —Jon Ginoli, My Life in Pansy Division, 2009

In both these examples, "twenty-one-plus" clearly includes individuals who are currently twenty-one-years-old, as well as thirty-, forty-, or hundred-year-olds. Many other similar examples of "X-plus" being used for "X and up" can be easily found, as in movie rating ages. And just for fun, here's a similar usage on StackOverflow:

As currently written, this will insert a hyphen between the first two groups of four in any eight-digit-plus number.
jonrsharpe's answer to https://stackoverflow.com/q/28396120

A: Signs for Sums A story of the 4 basic math sign.  world wide words

"There be other 2 signes in often use of which the first is made thus
  + and betokeneth more: the other is thus made - and betokeneth lesse".

Above from 1557 English. Amazing!
My sense is to read " thirty plus" if written 30+, to read "thirty or so"  or "thirty plus or minus" if written 30+/-.  There are a number of other variations. There are no standards.  And i do not sense that is is discouraged but in the most formal use of English.


text:
Q: How to remove existing Linux system on a hard drive, turn it into a normal disk, but keep some user files? I just shucked a WD MyCloud for its hard drive. There are already around 5TB data on it. After ssh into the disk, I found there is a Linux system on there, which is not surpise since it was designed to server as a NAS.
I could copy all my 5TB data to another hard drive and format it. But that will take some time. So I wonder is there a way I could do, to convert this disk to a normal disk, without moving existing data on it. By normal, I mean when you connect it to another computer, it will just show as a disk with folders and files on it.
Thank you!

A:
So I wonder is there a way I could do, to convert this disk to a
normal disk, without moving existing data on it.

Installing Linux makes your disk bookable by installing boot-loader and linux system files are stored pretty much like a normal disk holding files. So nothing to convert ; All you can do is - remove boot-loader files {simply delete boot folder} and EFI entry (assuming UEFI) {how-do-i-remove-ubuntu-in-the-bios-boot-menu-uefi}.
You can simply delete Linux-related system files manually . Keep the home directory if you want your personal data.

By normal, I mean when you connect it to another computer, it will
just show as a disk with folders and files on it.

Your disk will appear as a normal disk {with files and folders} on Linux OS. But you will not be able to access them in Win due to unsupported file system. To overcome you can simply install ext4/ext3/btrfs or other needed win drivers for win to access them {tools-to-see-ext2-ext3-ext4-btrfs-jfs-xfs-filesystems-under-windows}.

A: No. It would seem the disk is using an ext or other "non windows" filesystem, and you cant convert filesystems in place (at least not to fat or ntfs).
Its probably best to copy, format and copy back, but depending on the filesystem and block layer config you might be able to shrink the filesystem slightly , create a new VFAT system at the end of it and put some tools to read a Linux fileststem from Windows on it.  A horrible hacky cludge though.


text:
Q: How to create/simulate two audio lines/devices? I have searched around the internet for answers; however, I was not successful in locating an answer. What is the best method of simulating two audio devices using Pulse Audio/ALSA/something else? Thank you.
Edit: For further clarification, I need these audio devices for input and output into Teamspeak 3. This setup will allow me to create a music bot of sorts when I play audio into the line that is the input of teamspeak. This setup is easily achieved through Virtual Audio Cable on Windows. Thank you.

A: Using alsa, you can add in ~/.asoundrc
pcm.simulatedAudio {
  type file
  slave {
    pcm null
  }
  format "raw"
   file " | /path/to/script"
}

This will run the script sending the audio data in to stdin (if you dont want the audio you can pipe it in to /dev/null).


text:
Q: How to send/receive windows messages between VB6 and c#? I am not a good programmer of C#, thus I need a small piece of code to send and receive messages between a C# and VB6 program, I have tried many examples from web but not succeeded due complexity of topic to me, your help is appreciated.
Thanks in Advance.

A: You did not provide alot details therefor i could think of quite a few solutions. Probably the  2 best are:

*

*MSMQ: Read
http://jwbs-blog.blogspot.de/2009/06/using-msmq-to-communicate-between-net.html

*Named Piped: More Infos http://support.microsoft.com/kb/177696/en-us
Hope this gives you some direction.

A: Well I was looking for some code sample rather tips or reference as I had mentioned in my question. Anyway, I have managed it by extending following project
here
and now I can pass strings message between both VB6 and C# applications.
Thanks to All for Time and Suggestions.


text:
Q: Figuring out my grades lol I have 6 HW assignments If my assignments are worth 25% of my grade and each assignment is worth 50 pts. And out of that 25 percent what would that 25 percent change too if I got a zero on one of the 6 assignments.

A: Since each homework assignment is worth the same number of points, each one is worth $\frac{1}{6}\times 25\% = 4.166...\%$ of your grade. So if you remove one of the six assignments, the rest make up $\frac{5}{6}\times 25\% = 20.833...\%$ of your grade.


text:
Q: Eval doesn't work on Firefox As simple as the title says.
I have a bunch of scripts that work over some javascript code and should execute that code when pressing a button.
I use the eval function to do that and it works fine on:

*

*GOOGLE CHROME

*SAFARI

*OPERA

*INTERNET EXPLORER (?!?)

Surprisingly this doesn't work on Firefox and if I open the console here is the error I get:
[12:17:58.447] ReferenceError: undefinedundefinedundefinedundefinedundefined is not defined
Any idea on how to make it work even on FF?
EDIT.
here's the code I use. so much to work on!
function exec_code() {
   var code= document.getElementById("code").innerText;
   eval (code);
}

A: Firefox doesn't support the non-standard innerText property.
You can establish this by testing the value of code before you pass it to exec. It will be undefined.
Use something else to get your data.


text:
Q: Updating column in mysql database using HTML input button I have a MySQL table for storing users with columns for exercises (ex1 & ex2) that should go from 0 - 10 depending on which question a user has completed. For example, if a user has completed question 4 in exercise one ex1 would say 4. I have the rest of the site set up so that a user can't move access ex2 unless ex1 is 10.
this is a shortened example of my users table:

id | firstname | ex1 | ex2
---------------------------
 1 |  example  |  0  |  0

My questions use a form using JQuery to check a users answer and uses bootbox to give information to the user such as why they haven't completed the question correctly.
{% block main %}

Put the corresponding digit next to the French word.
We've completed the first one for you.

            <form id="uanswer" method="get">

                    <input type="text" id="answer1" name="answer1" placeholder="*" style="text-align: center; width: 30px;">
                    trois

                    <input type="text" id="answer2" name="answer2" placeholder="*" style="text-align: center; width: 30px;">
                    six

                    <input type="text" id="answer3" name="answer3" value="1" placeholder="*" style="text-align: center; width: 30px;">
                    un

                    <input type="text" id="answer4" name="answer4" placeholder="*" style="text-align: center; width: 30px;">
                    deux

                    <input type="text" id="answer5" name="answer5" placeholder="*" style="text-align: center; width: 30px;">
                    neuf

                    <input type="text" id="answer6" name="answer6" placeholder="*" style="text-align: center; width: 30px;">
                    cinq

                    <input type="text" id="answer7" name="answer7" placeholder="*" style="text-align: center; width: 30px;">
                    dix

                    <input type="text" id="answer8" name="answer8" placeholder="*" style="text-align: center; width: 30px;">
                    quatre

                    <input type="text" id="answer9" name="answer9" placeholder="*" style="text-align: center; width: 30px;">
                    huit

                    <input type="text" id="answer10" name="answer10" placeholder="*" style="text-align: center; width: 30px;">
                    sept

            <input type="button" value="Check My Answer" id="useranswer" class="btn btn-large btn-info">
            </form>

{% endblock main %}

the JQuery works as it's meant to however I need the database to update if the user gets the correct answer. However, I'm unsure how to go about this.
EDIT
this is my PHP file that is auto generated with my code I have modified.
<?php
/**
 * A class that contains code to handle any requests for
/french_tutorial_one_question_two
 */
/**
 * Support // or /home/french_tutorial_one_question_two
 */
    class french_tutorial_one_question_two extends \Framework\Siteaction
    {
/**
 * Handle french_tutorial_one_question_two operations /
 *
 * @param object    $context    The context object for the site
 *
 * @return string   A template name
 */
        public function handle($context)
        {
            $fd = $context->formdata();
            if ($fd->haspost('useranswer') and ($context->hasstudent())) {
                $u = \R::findOne('user', 'id=?', [$fd->post('useranswer')]);
                $u->ex1 = '1';
                \R::store($u);
                return 'french_tutorial_one_question_two.twig';
            } else {
                return 'error/403.twig';
            }
        }
    }
?>

this is the exact same code I used in a previous project and it worked perfectly however it won't work now


text:
Q: Bound Method - Python class Iloilo():
     def Population(self):
        population = 946146
        return population

class Palawan():
    def Population(self):
        population = 1104585
        return population

Iloilo = Iloilo()
Palawan = Palawan()

print(Iloilo.Population)
print(Palawan.Population)

I am trying to print its value but I'm getting an error saying:
bound method
My question is, how can I compare both method results?

A: You need to do:
ilolio_instance = Iloilo()
palawan_instance = Palawan()
print(ilolio_instance.Population())
print(palawan_instance.Population())

A: Use below code
class Iloilo():
    def Population(self):
        population = 946146
        return population

class Palawan():
    def Population(self):
        population = 1104585
        return population

a= Iloilo()
b=Palawan()
print(a.Population(),b.Population())


text:
Q: Instantiate an object without having it appear on startup I want to instantiate a sphere every time I press a button, in order to instantiate it must be cloned from an object I already created example: 'sphere1, so it will instantiate sphere1(clone)
I do not want sphere1 though to appear when I start the game. How can hide sphere 1?

A: You can do this 2 ways:
1). You can create a prefab of the object that you want to instantiate. This can be done by dragging the object in the scene into your assets folder, it will make an item that has a blue square for an icon and the objects name. This new item can be put in your script just like that of the gameobject sphere1 in the scene, but it will not be loaded in your scene unless you instantiate one.
2). You can also use your current method, however the sphere1 that is currently in your game scene you need to turn it to inactive. (The top checkbox by the name of the object in the inspector)
Now in your code, you need to use:
//Creates the object in the scene, ',,,,' is other parameters.
GameObject obj  = Instantiate(Sphere1Prefab,,,,);
//Changes the newly created object to active in the scene.
obj.SetActive(true);

Either of these should give you the desired effect.


text:
Q: How to set celery result backend key before task function runs? I'm using multiple databases in my django project(redis, postgresql). In celery, I'm running a task function with the countdown parameter set to a week which put the results in redis result backend. Then i'm trying to save the redis key in postresql table. If I set the redis key before task function runs, I can access the redis record later. So, Is there a way to do that? (Sorry for my English)

A: Can you try this
result = add.apply_async(countdown=time_in_seconds)
result.id #give you task id.

You can save it now to your postgres.


text:
Q: Show that f(x) = 2a + 3b is continuous where a and b are constants Need help with a question in my book. How do I prove this is continuous.
question -
Show that f(x) = 2a + 3b is continuous where a and b are constants

A: The definition you learned is Definition in terms of limits of functions:
If $f(x)=2a+3b=k$ we have $\lim_{h\to0}|f(x)-f(x+h)|=\lim_{h\to0}|k-k|=\lim_{h\to0}0=0$ and done

A: $f(x+h)=f (x)=2a+3b $.  Thus  $lim_{h\to 0}\lvert f (x+h)-f (x)\rvert =lim_{h\to 0}\lvert 2a+3b-(2a+3b)\rvert =lim_{h\to 0} \lvert 0 \rvert =0$.