text:
Q: Aggregate over batches of records I would like to aggregate stream analytics records in batches of n records each with the following conditions:

*

*each record can only be in a single batch.

*each batch contains at most n records.

*when the nth record of a batch arrives (or a timeout occurs), the window is closed and the query is evaluated.

I have not found a way to achieve this with windowing functions (since they are time-based, not count-based). Also functions like CollectTOP would not work, since it is evaluated for each record, not for each batch.

A: As mentioned in the comments, Azure Stream Analytics doesn't have a concept of event count.
To be able to regroup events per batch of certain size, the first step is to rank them (CollectTop). ASA, like any stream processor, will need a time window to define that rank.
This doesn't match the requirement, also clarified in the comments. Sorry but it looks like ASA is not a solution here.
If you could tolerate a time window - meaning to tolerate the delay (records are output at the end of the window) and to tolerate incomplete batches (most time windows won't have a multiple of n events) - then this could be partially achieved via a multi step query.
With this input file in input, and this query:
WITH Ranking AS (
    SELECT
        System.Timestamp() as ts,
        COLLECTTOP(1000000) OVER (ORDER BY EntryTime, TollId) as c
    FROM [entry] AS e TIMESTAMP BY EntryTime
    GROUP BY TumblingWindow(minute,5)
),
Unfolding AS (
    SELECT
        System.Timestamp() AS windowEnd,
        FLOOR((d.ArrayValue.rank-1) /3.0) as batch3,
        d.ArrayValue.rank,
        d.ArrayValue.value.*
    FROM Ranking AS r
    CROSS APPLY GetElements(r.c) AS d
),
Batching AS (
    SELECT
        System.Timestamp() as ts,
        Collect() as batch
    FROM Unfolding
    GROUP BY System.Timestamp, batch3

)
SELECT * FROM Batching

We will get:
{"ts":"2014-09-10T12:05:00.0000000Z","batch":[{"windowEnd":"2014-09-10T12:05:00.0000000Z","batch3":0.0,"rank":1,"EntryTime":"2014-09-10T12:01:00.0000000Z","TollId":1,"LicensePlate":"JNB 7001","State":"NY","Make":"Honda","Model":"CRV","VehicleType":1,"VehicleWeight":0,"Toll":7,"Tag":null},{"windowEnd":"2014-09-10T12:05:00.0000000Z","batch3":0.0,"rank":2,"EntryTime":"2014-09-10T12:02:00.0000000Z","TollId":1,"LicensePlate":"YXZ 1001","State":"NY","Make":"Toyota","Model":"Camry","VehicleType":1,"VehicleWeight":0,"Toll":4,"Tag":123456789},{"windowEnd":"2014-09-10T12:05:00.0000000Z","batch3":0.0,"rank":3,"EntryTime":"2014-09-10T12:02:00.0000000Z","TollId":3,"LicensePlate":"ABC 1004","State":"CT","Make":"Ford","Model":"Taurus","VehicleType":1,"VehicleWeight":0,"Toll":5,"Tag":456789123}]}
{"ts":"2014-09-10T12:05:00.0000000Z","batch":[{"windowEnd":"2014-09-10T12:05:00.0000000Z","batch3":1.0,"rank":4,"EntryTime":"2014-09-10T12:03:00.0000000Z","TollId":1,"LicensePlate":"BNJ 1007","State":"NY","Make":"Honda","Model":"CRV","VehicleType":1,"VehicleWeight":0,"Toll":5,"Tag":789123456},{"windowEnd":"2014-09-10T12:05:00.0000000Z","batch3":1.0,"rank":5,"EntryTime":"2014-09-10T12:03:00.0000000Z","TollId":2,"LicensePlate":"XYZ 1003","State":"CT","Make":"Toyota","Model":"Corolla","VehicleType":1,"VehicleWeight":0,"Toll":4,"Tag":null},{"windowEnd":"2014-09-10T12:05:00.0000000Z","batch3":1.0,"rank":6,"EntryTime":"2014-09-10T12:05:00.0000000Z","TollId":2,"LicensePlate":"CDE 1007","State":"NJ","Make":"Toyota","Model":"4x4","VehicleType":1,"VehicleWeight":0,"Toll":6,"Tag":321987654}]}
{"ts":"2014-09-10T12:10:00.0000000Z","batch":[{"windowEnd":"2014-09-10T12:10:00.0000000Z","batch3":0.0,"rank":1,"EntryTime":"2014-09-10T12:06:00.0000000Z","TollId":2,"LicensePlate":"BAC 1005","State":"NY","Make":"Toyota","Model":"Camry","VehicleType":1,"VehicleWeight":0,"Toll":5.5,"Tag":567891234},{"windowEnd":"2014-09-10T12:10:00.0000000Z","batch3":0.0,"rank":2,"EntryTime":"2014-09-10T12:07:00.0000000Z","TollId":1,"LicensePlate":"ZYX 1002","State":"NY","Make":"Honda","Model":"Accord","VehicleType":1,"VehicleWeight":0,"Toll":6,"Tag":234567891},{"windowEnd":"2014-09-10T12:10:00.0000000Z","batch3":0.0,"rank":3,"EntryTime":"2014-09-10T12:07:00.0000000Z","TollId":2,"LicensePlate":"ZXY 1001","State":"PA","Make":"Toyota","Model":"Camry","VehicleType":1,"VehicleWeight":0,"Toll":4,"Tag":987654321}]}
{"ts":"2014-09-10T12:10:00.0000000Z","batch":[{"windowEnd":"2014-09-10T12:10:00.0000000Z","batch3":1.0,"rank":4,"EntryTime":"2014-09-10T12:08:00.0000000Z","TollId":3,"LicensePlate":"CBA 1008","State":"PA","Make":"Ford","Model":"Mustang","VehicleType":1,"VehicleWeight":0,"Toll":4.5,"Tag":891234567},{"windowEnd":"2014-09-10T12:10:00.0000000Z","batch3":1.0,"rank":5,"EntryTime":"2014-09-10T12:09:00.0000000Z","TollId":2,"LicensePlate":"CDB 1003","State":"PA","Make":"Volvo","Model":"C30","VehicleType":1,"VehicleWeight":0,"Toll":5,"Tag":765432198},{"windowEnd":"2014-09-10T12:10:00.0000000Z","batch3":1.0,"rank":5,"EntryTime":"2014-09-10T12:09:00.0000000Z","TollId":2,"LicensePlate":"DCB 1004","State":"NY","Make":"Volvo","Model":"S80","VehicleType":1,"VehicleWeight":0,"Toll":5.5,"Tag":654321987}]}
{"ts":"2014-09-10T12:10:00.0000000Z","batch":[{"windowEnd":"2014-09-10T12:10:00.0000000Z","batch3":2.0,"rank":7,"EntryTime":"2014-09-10T12:09:00.0000000Z","TollId":3,"LicensePlate":"YZX 1009","State":"NY","Make":"Volvo","Model":"V70","VehicleType":1,"VehicleWeight":0,"Toll":4.5,"Tag":912345678},{"windowEnd":"2014-09-10T12:10:00.0000000Z","batch3":2.0,"rank":8,"EntryTime":"2014-09-10T12:10:00.0000000Z","TollId":1,"LicensePlate":"CBD 1005","State":"NY","Make":"Toyota","Model":"Camry","VehicleType":1,"VehicleWeight":0,"Toll":4,"Tag":543219876},{"windowEnd":"2014-09-10T12:10:00.0000000Z","batch3":2.0,"rank":9,"EntryTime":"2014-09-10T12:10:00.0000000Z","TollId":3,"LicensePlate":"BCD 1002","State":"NY","Make":"Toyota","Model":"Rav4","VehicleType":1,"VehicleWeight":0,"Toll":5.5,"Tag":876543219}]}
{"ts":"2014-09-10T12:15:00.0000000Z","batch":[{"windowEnd":"2014-09-10T12:15:00.0000000Z","batch3":0.0,"rank":1,"EntryTime":"2014-09-10T12:11:00.0000000Z","TollId":1,"LicensePlate":"NJB 1006","State":"CT","Make":"Ford","Model":"Focus","VehicleType":1,"VehicleWeight":0,"Toll":4.5,"Tag":678912345},{"windowEnd":"2014-09-10T12:15:00.0000000Z","batch3":0.0,"rank":2,"EntryTime":"2014-09-10T12:12:00.0000000Z","TollId":3,"LicensePlate":"PAC 1209","State":"NJ","Make":"Chevy","Model":"Malibu","VehicleType":1,"VehicleWeight":0,"Toll":6,"Tag":219876543},{"windowEnd":"2014-09-10T12:15:00.0000000Z","batch3":0.0,"rank":3,"EntryTime":"2014-09-10T12:15:00.0000000Z","TollId":2,"LicensePlate":"BAC 1005","State":"PA","Make":"Peterbilt","Model":"389","VehicleType":2,"VehicleWeight":2.675,"Toll":15.5,"Tag":567891234}]}
{"ts":"2014-09-10T12:15:00.0000000Z","batch":[{"windowEnd":"2014-09-10T12:15:00.0000000Z","batch3":1.0,"rank":4,"EntryTime":"2014-09-10T12:15:00.0000000Z","TollId":3,"LicensePlate":"EDC 3109","State":"NJ","Make":"Ford","Model":"Focus","VehicleType":1,"VehicleWeight":0,"Toll":4,"Tag":198765432}]}
{"ts":"2014-09-10T12:20:00.0000000Z","batch":[{"windowEnd":"2014-09-10T12:20:00.0000000Z","batch3":0.0,"rank":1,"EntryTime":"2014-09-10T12:18:00.0000000Z","TollId":2,"LicensePlate":"DEC 1008","State":"NY","Make":"Toyota","Model":"Corolla","VehicleType":1,"VehicleWeight":0,"Toll":4,"Tag":null},{"windowEnd":"2014-09-10T12:20:00.0000000Z","batch3":0.0,"rank":2,"EntryTime":"2014-09-10T12:20:00.0000000Z","TollId":1,"LicensePlate":"DBC 1006","State":"NY","Make":"Honda","Model":"Civic","VehicleType":1,"VehicleWeight":0,"Toll":5,"Tag":432198765},{"windowEnd":"2014-09-10T12:20:00.0000000Z","batch3":0.0,"rank":3,"EntryTime":"2014-09-10T12:20:00.0000000Z","TollId":2,"LicensePlate":"APC 2019","State":"NJ","Make":"Honda","Model":"Civic","VehicleType":1,"VehicleWeight":0,"Toll":4,"Tag":345678912}]}
{"ts":"2014-09-10T12:25:00.0000000Z","batch":[{"windowEnd":"2014-09-10T12:25:00.0000000Z","batch3":0.0,"rank":1,"EntryTime":"2014-09-10T12:22:00.0000000Z","TollId":1,"LicensePlate":"EDC 1019","State":"NJ","Make":"Honda","Model":"Accord","VehicleType":1,"VehicleWeight":0,"Toll":4,"Tag":null}]}

Which guarantee that each batch won't have more than N=3 events here. But we enforce that guarantee on a 5 minutes window. When there's less records in a time window, we will get a batch with less than N records.


text:
Q: How to check google analytics api parameters from google analytics interface I am using google analytics api to get data. I am getting data but I want to verify two parameters those are always 0 in a particular date range. I am getting ['ga:transactions'] and ['ga:goalCompletionsAll'] . These two parameters are always zero in google analytics api response.
So I just want to know is there any way I can check these two parameters from google analytics web interface against some particular date range?

A: You could test it using a Custom report on the website:

Link to the custom report above, just import it it will show with your data.
The report is just Goal Completions and transactions by Date

redpajama_set_name: RedPajamaStackExchange


text:
Q: CECIL IsGenericInstance not returns correct value for out put parameter I have below method with nullable parameters in which 2nd one is out too
public static void MyMethod(Nullable<System.Int32> i_ReportID, out Nullable<System.Int32> i_MenuID)
        {
            i_MenuID = 0;
        }

I tried to identify the parameter as a GenericInstance by
(methodDefinition.Parameters[0] as ParameterReference).ParameterType.IsGenericInstance
For 1st parameter and it's returns true.
(methodDefinition.Parameters[1] as ParameterReference).ParameterType.IsGenericInstance
For 2nd parameter and it's returns false. Why?

A: It should be used with ByReferenceType like below
(parameter.ParameterType as ByReferenceType).ElementType.IsGenericInstance
Afterwards I am getting correct IsGenericInstance value


text:
Q: Does spark cache rdds automatically? I'm submitting a spark job (spark-submit).
Problem
I'm loading an rdd by reading avro files from HDFS.
Then I filter the rdd & count it (job-1).
Then I filter it again using a different criteria and count it (job-2).

*

*In the logs I see that the FileInputFormat is reading 60 files the first time.  But it doesn't read any files the second time.

*Also when I do rdd.toDebugString I do not see the parent rdd being cached.

Details
Here is the code:
JavaRdd<Record> records = loadAllRecords();
JavaRDD<Record> type1Recs = records.filter(selectType1());
JavaRDD<Record> type2Recs = records.filter(selectType2());
log.info(type1Recs.count());
log.info(type2Recs.count());

When I look at the rdd debug info for the first count:
  .....
  .....
  |   MapPartitionsRDD[2] at filter at xxxx.java:61 []
  |   NewHadoopRDD[0] at newAPIHadoopRDD at xxxxx.java:64 []

When I look at the rdd debug info for the second count:
  .....
  .....
  |   MapPartitionsRDD[5] at filter at EventRepo.java:61 []
  |   NewHadoopRDD[0] at newAPIHadoopRDD at xxxxx.java:64 []

If I were catching NewHadoopRDD would have some catching info associated to it in the debug string...
However, I do realize that in both instances the RDD is referred to as NewHadoopRDD[0].  What is the [0] mean in this context is that the id?  I think of RDD has a handle so I'm not sure the what the significance of the reusing the same handle would be?
When I do the first count I see in the logs:
FileInputFormat: Total input paths to process : 60

But I do not see a similar log for the second count.  Shouldn't the records Rdd be loaded all over again?
Finally the second count is faster than the first which leads me to believe the data is in memory...

A:
Does spark cache rdds automatically?

Sometimes, yes. The RDDs are cached automatically in cases of a shuffle.
You might have observed "skipped stages" in the spark Web UI, for example.
See: https://spark.apache.org/docs/1.5.0/programming-guide.html#shuffle-operations
In the other cases, you will need to call rdd.cache or its variants.

A: For this line, FileInputFormat: Total input paths to process : 60, it belongs to RDD's metadata. This one outputs in NewHadoopRDD.getPartitions. It's lazy but only runs once. You can say that RDD's metadata is cached. But the data of this RDD (the data in the files) is not cached.


text:
Q: Unable to open Excel file after sending it via python pandas I am sending an email with excel file as an attachment.
Everything is fine, but when I try to open excel file from email, I got an error:

I am not very familiar with python, what can be the problem here?
Code below:
import pandas as pd
import numpy as np
import pyodbc

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

fromaddr = "FromEmail"
toaddr = "ToEmail"

# instance of MIMEMultipart
msg = MIMEMultipart()

# storing the senders email address
msg['From'] = fromaddr

# storing the receivers email address
msg['To'] = toaddr

# storing the subject
msg['Subject'] = "Sending Attachement"

# string to store the body of the mail
body = "Hello, this is a test email!"

# attach the body with the msg instance
msg.attach(MIMEText(body, 'plain'))

# open the file to be sent
filename = "AZ.xlsx"
attachment = open('C:\\Users\\Folder\\AZ.xlsx',encoding='utf-8',errors='ignore')

# instance of MIMEBase and named as p
p = MIMEBase('application', 'octet-stream')

# To change the payload into encoded form
p.set_payload((attachment).read())

# encode into base64
encoders.encode_base64(p)

p.add_header('Content-Disposition', "attachment; filename= %s" % filename)

# attach the instance 'p' to instance 'msg'
msg.attach(p)

# creates SMTP session
s = smtplib.SMTP('10.10.10.10: 25')

# start TLS for security
s.starttls()

# Authentication
#s.login(fromaddr, "password")

# Converts the Multipart msg into a string
text = msg.as_string()

# sending the mail
s.sendmail(fromaddr, toaddr, text)

# terminating the session
s.quit()


text:
Q: Confusion about the extern keyword and multiple source files I am trying to fully understand how extern works, so I created 3 files, two of them are source files and the last is a header file. This is what is contained in each of them:
testingfile1.c
#include <stdio.h>
#include "testingheader.h"
int main() {
    change();
    int my_extern;
    printf("\n%d", my_extern);
    return 0;

}

testingfile2.c:
#include <stdio.h>
#include "testingheader.h"
void change() {
    int my_extern;

    my_extern = 15;
    printf("%d", my_extern);
}

testingheader.h:
#if !defined(TESTINGHEADER_H)
#define TESTINGHEADER_H

#include <stdio.h>
extern int my_extern;
void change();

#endif

The output of this program is: 15 0. However, I thought that since my_extern is an extern int, if you were to change to the value in one source file, it's value would be changed in all of the other source files. Is this not how extern works, or am I doing something wrong in the code itself?

A: In both cases remove int my_extern; where you have it, because those become local variables which happen to have the same name my_extern.
extern int my_extern; just means there's an int called my_extern "out there somewhere".  So you'd have to declare int my_extern somewhere at file scope, for example like this:
int my_extern = 0;

void change() {
    my_extern = 15;
    printf("%d", my_extern);
}

A: In testingfile2.c, the my_extern variable is local to the function and you are not seeing the global my_extern that the extern command is referencing.  Of course, you don't have a global my_extern, so that is another problem.  You would get a linker error if you actually tried to reference the global my_extern that the extern command is referencing.

A: The issue is you're re-declaring int my_extern; inside your functions.  Therefore, C treats that as a separate variable from the global my_extern.
The statement extern int my_extern; is a declaration that a global int called my_extern will be declared somewhere.  You haven't done that.  Instead, you've created local my_extern variables.


text:
Q: Inherit a template class with an inner class and access the inner class within the inherited class I have a template class "BinaryHeap" which also declares a public class "Item" within itself.
Now I want to extend the BinaryHeap with a hash for element lookup and therefore inherited it. I called it "HashedBinaryHeap", which should use the same Item class like BinaryHeap does.
The stub looks like this:
template<class T>
class BinaryHeap {
public:
    class Item {...};
    ...
    void appendItem(const Item & item);
    ...
};

template<class T>
class HashedBinaryHeap : public BinaryHeap<T> {
public:
    ...
    void appendItem(const Item & item);
    ...
};

The problem now is, when I try to access the Item class within HashedBinaryHeap like I do in the appendItem() method, I get some compiler errors.
When I write it like above or with the <T>:
void appendItem(const Item & item);
void appendItem(const Item<T> & item);

I get:
ISO C++ forbids declaration of 'Item' with no type

When I do one of:
void appendItem(const HashedBinaryHeap::Item & item);
void appendItem(const HashedBinaryHeap<T>::Item & item);

I get:
expected unqualified-id before '&' token

So how can I 'access' the class Item within HashedBinaryHeap? What am I misunderstanding?
(Maybe this isn't something template class related problem, but I know template classes are confusing a lot of C++ beginners, and I still don't dare calling myself something else... Please get me out. :))
Thanks in advance!

A: Ok, solved it!
void appendItem(const typename HashedBinaryHeap<T>::Item & item);

This did the trick - I didn't know about typename...


text:
Q: Deleting from a Linked List I am writing a program to be a dictionary. In the program you can add and delete words, and print the current and deleted words. My problem is in my delete method, apparently it is deleting words properly but it is not making a linked list storing those deleted word to then print them. Therefore, it only prints the last word i deleted instead of all the words i've deleted. Here is the method:
public void delete(String b)
{
    WordMeaningNode current = this.list;
    WordMeaningNode previous = null;
    WordMeaningNode temp;

    //While list is empty, return.
    if (this.list == null)
    {
        return;
    }

    // While it is not empty..
    while (current != null)
    {
        if (current.word.getWord().equalsIgnoreCase(b))
        {
            if (current == this.list)
            {

                this.list = this.list.next;
            }
            else
            {

                previous.next = current.next;
            }

            temp = current;
            del = temp;
            current.next = null;
            return;
        }

        previous = current;
        current = current.next;
    }
}

Can anybody see where my mistake is?

A: I am not sure what del is, but assuming it is a node in your deleted words linked list, all your doing is assigning the deleted word to del in del = temp. If you want to add it onto the del linked list you have to create a new node and add it on for example...
WordMeaningNode newDelNode;
newDelNode = temp;
del.next = temp;

something like that... I'm not entirely sure because it is a little difficult to read your code.


text:
Q: Matplotlib pyqt Navigation toolbar change background color of "figure options" I implemented the matplotlib plots and navigation toolbar in pyqt4 GUI.
How do I change the background color of "Figure options" in the toolbar?

In the above picture with a gray background, everything looks good. The same "Figure options" with a dark background looks like the figure below

How do I change the background color of the "Figure options?"
The navigation toolbar is implemented in the following way
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar

self.figure = Figure(figsize=(6,7))
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)

A: I figured it out.
The simple solution is to add self.toolbar.setStyleSheet("background-color:Gray;")


text:
Q: Model Pandas Data Frame column as List of Category I would like to reduce the memory output of my Pandas dataframe.
I am parsing a Json where some of the columns are multi-valued list of categories, such as :
querySelectedBrands":["b1","b2","b3"]
This is automatically inferred as an 'object' column, but ideally is a List of Category.
Whenever I have a column which is single valued categorical, it is quite simple to make the conversion :
interactions[col] = interactions[col].astype('category')

But what about a column I want to set type as a List of category ?
Later on I will encode this column transforming it in a series of Boolean columns, so I am not sure if the initial memory benefit of transforming in a list of 'category' is going to be beneficial.
Thanks !

A: No, this isn't possible
Using a Pandas series to hold lists is inadvisable because it will always be of dtype object and represent pointers to arbitrary types. As such, operations on such a series will not be vectorisable and will have a memory overhead attached.
An alternative
If you have a set number of items in each list, you can split your series of lists into multiple series, see Pandas split column of lists into multiple columns. Then make each series a categorical:
for col in ['col1', 'col2', 'col3']:
    df[col] = df[col].astype('category')


text:
Q: Ansible variable override default in another role I'm unsure how to override variables between roles in Ansible.
To simplify the setup a little, I have two roles applied to the same host. The first role defines a variable in its default/main.yml:
do_some_task: yes

And looks for that variable in its tasks:
- name: Some Task
  when: do_some_task

The second role overrides that in its vars/main.yml, which is supposed to take precedence over the defaults:
do_some_task: no

However, the task is still being run, indicating that the variable wasn't overridden. It seems that the override is scoped to the tasks of the second role. I tested that by adding a debug task to both roles:
- name: Test some task
  debug: "msg='do_some_task = {{ do_some_task }}'"

This confirms that the first role sees a different value of the variable than the second.
TASK: [role1 | Test some task]
ok: [myhost] => {
    "msg": "do_some_task = True"
}

...

TASK: [role2 | Test some task]
ok: [myhost] => {
    "msg": "do_some_task = False"
}

The common answer to this appears to be to set the variables in the inventory or the host vars. However this isn't particularly DRY: if you have many hosts in different inventories, you'd have to set the same variables in lots of places.
So is there some way of overriding a variable from another role?

A: If you use Ansible >= 2.2, you maybe able to use include_roles:
  - name: Pass variables to role
    include_role:
    name: role1
    vars:
       do_some_task: "{{ role2_do_some_task }}"

You can also use dependencies of roles for Anslbie >= 1.3. Write the role2/meta/main.yml like:
  ---
  dependencies:
  - { role: role1, do_some_task: yes }

If you want neither, given that you don't want to put the variable definition in playbook, the only sensible place to define them is in inventory.
You can define the ones that need to overwrite the role1 default in the same group:
  [overwrite_do_some_task]
  host1
  host3

  [overwrite_do_some_task:vars]
  do_some_task=yes

If you don't give the variable value before running role1, then the expected behavior is, use the role default, which is what OP observed.
Note: It is more readable to prefix role variables. i.e. use role1_do_some_task instead of do_some_task. Doing so, you are less likely to confuse yourself. See Ansible Best Practices: The Essentials.

A: If you want to wrap a role with another role then you can override the inner role's variable by specifically passing variables from the outer role.
So as per your example you would have an inner role task of:
- name: Some Task
  when: do_some_task

This inner role would have a variable set like this:
do_some_task: true

And then you can override the inner role when you are calling your outer role in a playbook like this:
- name: outer-role
  hosts: outer-role-nodes
  roles:
    -   role: outer-role
    - { role: inner role,
        do_some_task: "{{ do_some_task }}" }

This should take the do_some_task variable from the outer role and override the inner role's do_some_task.

A: TLDR : to be able to inherit defaults/ config, you have to separate it into other roles and include it where it's going to be used
One way to apparently work around this is to create a separate role which will hold the defaults, and then import/include it in your main role. The roles you create with the default configurations can import each other as a way of "inheriting" configuration from defaults, and then the main role would load the top-most configuration role and take all the configs as expected..
For example, in my case I want to have a templating system which has a "stacked" level of configuration.. all of them inheriting from a base set of config in defaults, and not vars, otherwise you can't override it from inventory.
these are the roles:

*

*template-base

*template-config-standard

*template-config-performance

-> Template-base has the whole logic for deploying templates based on the selected configuration.. this has some logic to include the selected config role on the tasks files
-> template-config-standard has the standard set of config defined in defaults/main.yml, and nothing else
-> template-config-performance has some additional tweaking on the defaults/main.yml file, but does not repeat anything from template-config-standard, and instead simply uses it on "import_role" on the tasks/main.yml file.. probably dependencies still work
In a bit more examplified way:
role template-base:
- files/ (contains all the template files)
- tasks/
|---- main.yml (contains the code below)

# Includes the template configuration based on the selected template
- include_role:
    name: "template-config-{{ selected_template}}"
    public: true # Important so that configs are exposed here

- ** Does templating work **

role template-config-std:
- defaults/
|---- main.yml (contains a bunch of configuration)

role template-config-perf:
- defaults/
|---- main.yml (contains just a few config items, overriding stuff from the role above)
- tasks/
|---- main.yml (contains below code)

#Simply includes the standard configuration.. all this does is take defaults in the defaults/main.yml file from the below role
- import_role:
    name: template-config-std

The approach above seems to work just fine, respecting the desired inheritage of variables and precedence. It looks like you cannot have the role that will use the variables competing with the roles that contain the default variables, unfortunately, because it will always win.. but in any case the example above seems okay :).. if you need to add more things other than just configuration to the supporting roles, you have to create a kind of mechanism on the main role, but hopefully nothing very complex..
Good luck and have a good one!
PS: one of the most important aspects of this approach is that we keep the default/ precedence on the configuration, meaning the inventory can override it if needed!


text:
Q: How do I know if a AWS Server instance has license SQL Server Standard or SQL Server Web? I'm looking my AWS billing and this doubt has come up. How do I know if a specific instance is running SQL Server 2008-R2 Standard or SQL Server Web? (using the AWS Console or SQL Server Management Studio)
The Management Studio About shows the following:
Microsoft SQL Server Management Studio 10.50.2806.0
Microsoft Analysis Services Client Tools 10.50.2806.0
Microsoft Data Access Components (MDAC) 6.1.7601.17514
Microsoft MSXML 3.0 6.0
Microsoft Internet Explorer 9.0.8112.16421
Microsoft .NET Framework 2.0.50727.5456
Operating System 6.1.7601
Looking for version 10.50.2806.0, I've saw that it may be related for both licenses (link), so I don't know how to distinguish them.

A: Run SELECT @@VERSION; in a query window, with results to text. You will see something like this (minor details will vary) in the Messages pane:
Microsoft SQL Server 2014 - 12.0.2402.0 (X64)
    Aug 13 2014 11:36:34
    Copyright (c) Microsoft Corporation
    Developer Edition (64-bit) on Windows NT 6.4 <X64> (Build 9841: )
----^^^^^^^^^ edition will be here

Help > About in Management Studio is just about the client tools, so may not even reflect the same version as the server, never mind that Management Studio no longer has any edition differentiations.

A: You can run SELECT SERVERPROPERTY('edition') in a query window.
Your output will be something like: Standard Edition (64-bit) or Web Edition (64-bit).
More info: MSDN.


text:
Q: Is it possible to get the original UUID1 from a timestamp? Say, for example, I generate a time based UUID with the following program.
import uuid
uuid = uuid.uuid1()
print uuid
print uuid.time

I get the following:
47702997-155d-11ea-92d3-6030d48747ec
137946228962896279

Can I get back the original UUID, that is 47702997-155d-11ea-92d3-6030d48747ec, if I know the timestamp (137946228962896279)?
I am reading about UUID version 1 and found a few programs that "kind" of tries to reverses it, but, every time, I am getting a different UUID.
The part that is always changing are the timestamp part (last 4 digits of the first block - 47702997) and the clock_sequence (92d3).
If it is possible to get back the original UUID, what would I need?
Any help/direction is greatly appreciated.
I also made a post in Security Stackexchange but later realized that this question should have been posted here.
The more I look into it, I can see that this is not at all possible since the timestamp does not contain information on the clock_sequence unless I am wrong, in which case, please correct me.

A: A UUIDv1 contains two main pieces: a temporally unique part (aka timestamp) and a spatially unique part. By design, the two are completely independent, so if you throw one of the pieces away, there is no way to recover it later from the other one.
More generally, notice how the entire UUID is 32 hexadecimal digits, or 128 bits of information, but the timestamp is 18 decimal digits, or only about 60 bits of information. Even without knowing much about UUIDs you could guess that some of the bits are redundant or fixed (and a few are fixed, or at least guessable), but over half of them? Not likely, which means this translation is not reversible.


text:
Q: XAMLParseException driving me CRAZY! THIS XAMLParseException IS DRIVING ME CRAZY!! I am using .NET 3.5 in Visual Studio 1020 This is my xaml:
<Window x:Class="WinformsHost.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Advanced Notepad" Height="350" Width="525" Loaded="Window_Loaded">
<DockPanel>
    <Menu DockPanel.Dock="Top">

        <MenuItem Header="File">
            <MenuItem Header="_New" />
            <MenuItem Header="_Open..." />
            <MenuItem Header="_Save" />
            <MenuItem Header="S_ave As..." />
            <Separator />
            <MenuItem Header="Page Setup" />
            <MenuItem Header="Print" />
            <Separator />
            <MenuItem Header="Exit" />
        </MenuItem>

        <MenuItem Header="Edit">
            <MenuItem Header="Undo" />
            <MenuItem Header="Redo" />
            <Separator />
            <MenuItem Header="Cut" />
            <MenuItem Header="Copy" />
            <MenuItem Header="Paste" />
            <MenuItem Header="Delete"  />
            <Separator />
            <MenuItem Header="Time/Date" />
            <Separator />
            <MenuItem Header="Preferences" />
        </MenuItem>

        <MenuItem Header="Format">
            <MenuItem Header="Word Wrap" IsCheckable="True" />
            <MenuItem Header="Font..." />
        </MenuItem>

        <MenuItem Header="View">
            <MenuItem Header="Status Bar" IsCheckable="True" />
        </MenuItem>

        <MenuItem Header="Language">
            <RadioButton x:Name="rbtCmake" Checked="rbtCmake_Checked" Content="Cmake" />
            <RadioButton x:Name="rbtCSharp" Content="C#" />
            <RadioButton x:Name="rbtHTML" Content="HTML" />
            <RadioButton x:Name="rbtPython" Content="Python" />
            <Separator />
            <RadioButton x:Name="rbtText" IsChecked="True" Content="Text" />
        </MenuItem>

        <MenuItem Header="Help">
            <MenuItem Header="View Help" />
            <Separator />
            <MenuItem Header="About Notepad" />
        </MenuItem>

    </Menu>
    <StatusBar x:Name="stbStatus" DockPanel.Dock="Bottom" Visibility="Collapsed">
        <TextBlock x:Name="txtStatus" Text="Status" />
    </StatusBar>
</DockPanel>
</Window>

Then again it might be my code? Here is the exception:
System.Windows.Markup.XamlParseException was unhandled
  Message=Cannot create instance of 'MainWindow' defined in assembly 'Notepad, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Exception has been thrown by the target of an invocation.  Error in markup file 'MainWindow.xaml' Line 1 Position 9.
  Source=PresentationFramework
  LineNumber=1
  LinePosition=9
  StackTrace:
       at System.Windows.Markup.XamlParseException.ThrowException(String message, Exception innerException, Int32 lineNumber, Int32 linePosition, Uri baseUri, XamlObjectIds currentXamlObjectIds, XamlObjectIds contextXamlObjectIds, Type objectType)
       at System.Windows.Markup.XamlParseException.ThrowException(ParserContext parserContext, Int32 lineNumber, Int32 linePosition, String message, Exception innerException)
       at System.Windows.Markup.BamlRecordReader.ThrowExceptionWithLine(String message, Exception innerException)
       at System.Windows.Markup.BamlRecordReader.CreateInstanceFromType(Type type, Int16 typeId, Boolean throwOnFail)
       at System.Windows.Markup.BamlRecordReader.GetElementAndFlags(BamlElementStartRecord bamlElementStartRecord, Object& element, ReaderFlags& flags, Type& delayCreatedType, Int16& delayCreatedTypeId)
       at System.Windows.Markup.BamlRecordReader.BaseReadElementStartRecord(BamlElementStartRecord bamlElementRecord)
       at System.Windows.Markup.BamlRecordReader.ReadElementStartRecord(BamlElementStartRecord bamlElementRecord)
       at System.Windows.Markup.BamlRecordReader.ReadRecord(BamlRecord bamlRecord)
       at System.Windows.Markup.BamlRecordReader.Read(Boolean singleRecord)
       at System.Windows.Markup.TreeBuilderBamlTranslator.ParseFragment()
       at System.Windows.Markup.TreeBuilder.Parse()
       at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
       at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
       at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
       at System.Windows.Application.DoStartup()
       at System.Windows.Application.<.ctor>b__0(Object unused)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
       at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
       at System.Windows.Threading.DispatcherOperation.InvokeImpl()
       at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
       at System.Threading.ExecutionContext.runTryCode(Object userData)
       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.ProcessQueue()
       at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
       at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
       at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run(Window window)
       at System.Windows.Application.Run()
       at WinformsHost.App.Main() in C:\Users\Mohit\Documents\Visual Studio 2010\Projects\Notepad\Notepad\obj\x86\Debug\App.g.cs:line 0
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.Reflection.TargetInvocationException
       Message=Exception has been thrown by the target of an invocation.
       Source=mscorlib
       StackTrace:
            at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
            at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
            at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
            at System.Activator.CreateInstance(Type type, Boolean nonPublic)
            at System.Windows.Markup.BamlRecordReader.CreateInstanceFromType(Type type, Int16 typeId, Boolean throwOnFail)
       InnerException: NLog.Config.NLogConfigurationException
            Message=Exception occured when loading configuration from 'C:\Users\Mohit\Documents\Visual Studio 2010\Projects\Notepad\Notepad\bin\Debug\NLog.config'
            Source=NLog
            StackTrace:
                 at NLog.Config.XmlLoggingConfiguration..ctor(String fileName, Boolean ignoreErrors)
                 at NLog.Config.XmlLoggingConfiguration..ctor(String fileName)
                 at NLog.LogFactory.get_Configuration()
                 at NLog.LogFactory.GetLogger(LoggerCacheKey cacheKey)
                 at NLog.LogFactory.GetLogger(String name)
                 at NLog.LogManager.GetCurrentClassLogger()
                 at WinformsHost.MainWindow..ctor() in C:\Users\Mohit\Documents\Visual Studio 2010\Projects\Notepad\Notepad\MainWindow.xaml.cs:line 15
            InnerException: NLog.Config.NLogConfigurationException
                 Message=Target console not found.
                 Source=NLog
                 StackTrace:
                      at NLog.Config.XmlLoggingConfiguration.ConfigureRulesFromElement(LoggingConfiguration config, LoggingRuleCollection rules, XmlElement element)
                      at NLog.Config.XmlLoggingConfiguration.ConfigureFromXmlElement(XmlElement configElement, String baseDirectory)
                      at NLog.Config.XmlLoggingConfiguration.ConfigureFromFile(String fileName)
                      at NLog.Config.XmlLoggingConfiguration..ctor(String fileName, Boolean ignoreErrors)
                 InnerException:

A: I don't think this is really a XamlParseException: I think it's a TargetInvocationException which has gotten wrapped in a XamlParseException.  Take a look at the ultimate inner exception:

NLog.Config.NLogConfigurationException
  Message=Exception occured when loading
  configuration from
  'C:\Users\Mohit\Documents\Visual
  Studio
  2010\Projects\Notepad\Notepad\bin\Debug\NLog.config'

It looks like you have a borked configuration file, possibly due to invalid XML or possibly for some more specific reason.
When you get a mysterious XamlParseException, it's always worth checking the InnerException for a TargetInvocationException (and drilling in from there if there is one).  Yes, it is very confusing and misleading!

A: I know that this is an old question but hopefully this will help someone.
I had a property of the main window that was a Business Object... so when the window initialized, the Business Object attempted to initialize... great, but the Data access layer had not been setup, therefore it threw an error...
So c# called that an XML parse error because it happened so early... really it was thrown in code.

A: Solved the same issue by including the referenced dll and config files in the same folder as the exe file. Trying to run the exe alone will cause a windows level exception.


text:
Q: SQL join based on select as column name So in one table I can use a replace and charindex to extract a specific ID that relates to a PK in another table, I want to then join the data from the other table based on the trimmed value, how can I do this?
select top 100 *, Replace(Left(LogValue,Charindex(';', LogValue) - 1) ,'RtaId=', '') as TaskID, PrmRoutingTask.*
  from SytLog
       inner join  PrmRoutingTask on RtaId = TaskID
 where LogTableName like '%Routing%' and LogValue like '%RtaAniId=397%'
 order by 5 desc;

The problem I get is that the temp column name I create (TaskID) is not working in the inner join where in fact the results of TaskID have the reference to the RtaId in the RoutingTask table.

A: Assuming LogValue belongs to the first table you can use the column named TaskID if you produce a subquery as a table expression of the main query.
For example you can produce the column in the table expression a by doing:
select top 100
  a.*,
  PrmRoutingTask.*

from (
  select *,
    Replace(Left(LogValue,Charindex(';', LogValue) - 1) ,'RtaId=', '') as TaskID
  from SytLog
) a

inner join PrmRoutingTask on PrmRoutingTask.RtaId = a.TaskID

where LogTableName like '%Routing%'
  and LogValue like '%RtaAniId=397%'

order by 5 desc


text:
Q: Implicit differentiation "in terms of $x$ and $y$". I dont get it when it means "to find $dy/dx$ in terms of $x$ and $y$" what does it mean?
Solve the following problem and write your answer and solutions on bond paper.
1) Use implicit differentiation to find $dy/dx$ in terms of $x$ and $y$.
a) $2x^3=2y^2+5$
b) $1=3x+2x^2y^2$
c)$x^2=(4x^2y^3+1)^2$
2) Use implicit differentiation to find second derivative in terms of $x$ and $y$.
$4y^2+2=3x^2$

A: We need to express the derivative of the functions in terms of both $x$ and $y$ (in our answers), rather than just $x$. This is how it works:
$$a) 2x^3 = 2y^2+5$$
$$\frac{d}{dx} 2x^3 = \frac{d}{dx}2y^2 + \frac{d}{dx}5$$
$$6x = \frac{d}{dx}2y^2+0 \implies 6x = \frac{d}{dx}2y^2$$
Here, we need to use the Chain Rule to simplify $\frac{d}{dx}2y^2$. $$\frac{du}{dx} = \frac{du}{dy}\cdot\frac{dy}{dx}$$
$$\frac{d}{dx}2y^2 = \frac{d}{dy}2y^2\cdot\frac{dy}{dx}$$
$$\frac{d}{dx}2y^2 = 4y\cdot\frac{dy}{dx}$$
Now, we can continue.
$$6x = 4y\cdot\frac{dy}{dx}$$
$$\frac{dy}{dx} = \frac{6x}{4y} \implies \frac{dy}{dx} = \frac{3x}{2y}$$
We used the derivatives of both sides in order to differentiate implicitly. As you can see, it is expressed in terms of both x and y, just as the question asked. Repeating this process for the other questions will lead to the answer.
$$b) 1= 3x+2x^2y^2$$
$$\frac{d}{dx}1 = \frac{d}{dx}3x+\frac{d}{dx}2x^2y^2$$
$$0 = 3+\frac{d}{dx}2x^2y^2$$
$$-3 = \frac{d}{dx}2x^2y^2$$
To find $\frac{d}{dx}2x^2y^2$, use the Product Rule.
$$\frac{d}{dx}2x^2y^2 = (\frac{d}{dx}2x^2)\cdot y^2+(\frac{d}{dx}y^2)\cdot 2x^2 \implies \frac{d}{dx}2x^2y^2 = 4xy^2+2x^2\cdot 2y\cdot \frac{dy}{dx}$$
$$\frac{d}{dx}2x^2y^2 = 4xy^2+4x^2y\cdot\frac{dy}{dx}$$ Back to the question, we can quickly reach the answer.
$$-3 = 4x^2y+4xy^2\cdot\frac{dy}{dx} \implies -3-4x^2y = 4xy^2\cdot\frac{dy}{dx} \implies \frac{dy}{dx} = \frac{-3-4x^2y}{4xy^2} = -\frac{3+4x^2y}{4xy^2}$$
$$c) x^2 = (4x^{2}y^{3}+1)^2$$
$$\frac{d}{dx}x^2 = \frac{d}{dx}(4x^{2}y^{3}+1)^2$$
$$2x = \frac{d}{dx}(4x^{2}y^{3}+1)^2$$
Now, $\frac{d}{dx}(4x^{2}y^{3}+1)^2$ should be calculated.
Using the Chain Rule, $$\frac{dy}{dx} = \frac{dy}{du}\cdot\frac{du}{dx}$$
$$y = x^2 = (4x^{2}y^{3}+1)^2$$ $$u = (4x^{2}y^{3}+1)$$
$$\frac{d}{dx}(4x^{2}y^{3}+1)^2 = 2(4x^{2}y^{3}+1)\cdot\frac{d}{dx}(4x^{2}y^{3}+1)$$
$$\frac{d}{dx}(4x^{2}y^{3}+1)^2 = 2(4x^{2}y^{3}+1)\cdot (8xy^3+12x^{2}y^{2})\cdot\frac{dy}{dx}$$
Back to the question.
$$2x = 2(4x^{2}y^{3}+1)\cdot (8xy^3+12x^{2}y^{2})\cdot\frac{dy}{dx}$$
$$\implies \frac{dy}{dx} = \frac{2x}{2(4x^{2}y^{3}+1)\cdot (8xy^3+12x^{2}y^{2})}$$ $$\implies \frac{dy}{dx} = \frac{x}{(4x^{2}y^{3}+1)\cdot (8xy^3+12x^{2}y^{2})}$$
For question 2, the process is repeated twice with substitution at the end.
$$2) 4y^2+2 = 3x^2$$
$$\frac{d}{dx}4y^2+\frac{d}{dx}2 = \frac{d}{dx}3x^2$$
$$\frac{d}{dx}4y^2 + 0 = 6x \implies \frac{d}{dx}4y^2 = 6x$$
Using the Chain Rule, we get $$8y\cdot\frac{dy}{dx} = 6x \implies \frac{dy}{dx} = \frac{6x}{8y} = \frac{3x}{4y}$$
But the question wanted the double derivative, so the process repeats.
$$\frac{dy}{dx}\frac{3x}{4y} = \frac{\frac{d}{dx}(3x)\cdot 4y -\frac{d}{dx}(4y)\cdot 3x}{(4y)^2}$$ $$\frac{d}{dx}\frac{3x}{4y} = \frac{12y-12x\cdot\frac{dy}{dx}}{16y^2}$$
Now, plug in $\frac{3x}{4y}$ for $\frac{dy}{dx}$. $$\frac{d}{dx}\frac{3x}{4y} = \frac{12y-12x\cdot\frac{3x}{4y}}{16y^2}$$
Simplify the right side and you'll get this.
$$\frac{d}{dx}\frac{3x}{4y} = \frac{12y^2-9x^2}{16y^3}$$
Therefore, this is the second derivative. $$\frac{d^2y}{dx^2} = \frac{12y^2-9x^2}{16y^3}$$

A: It means that in your answer you are required to have only x and y as independent variables*, and not $y'$ or $\frac{dy}{dx}$ or anything else.
As far as I understand, with the first derivative it can't be done other way, since you don't introduce any other variables into the equation, like here, from your example:
$$
2x^2=2y^2+5 \to 4x = 4yy' \to y' = \frac{x}{y}
$$
Here the answer contains only x and y, which means exactly "in terms of x and y".
When one needs the second derivative, this is where you can have another variable, namely the first derivative. So you are required not to use it in your final answer, which usually means to substitute it with the first derivative equation (which contains only x and y)
From your question: Use implicit differentiation to find second derivative in terms of x and y:
$$
4y^2+2=3x^2 \\
8yy' = 6x \\
4yy' = 3x \\
y' = \frac{3x}{4y}
$$
this is the first derivative.
The second one is:
$$
4yy' = 3x \\
4y'y' + 4yy''=3 \\
4yy'' = 3 - 4(y')^2\\
y'' = \frac{3 - 4(y')^2}{4y}
$$
This is the second derivative, but it's not "in terms of x and y" since it contains $y'$ as an independent variable. You just need to substitute it with the value from $y' = \frac{3x}{4y}$, that is:
$$
y'' = \frac{3 - 4(\frac{3x}{4y})^2}{4y}\\
y'' = \frac{3}{4y} - \frac{9x^2}{16y^3}\\
$$
Here the equation contains only x and y as independent variables, which means it is in terms of x and y.

* and independent variable is one, which can be freely substituted for any allowed value, unlike the dependent one, which must be calculated from values of the independent variables.


text:
Q: Capture output of process synchronously (i.e. "when it happens") I am trying to start a process and capture the output, have come a far way, but am not quite at the solution I'd want.
Specifically, I am trying to reset the IIS on my development machine from a small utility application that I am writing. I have come to the conclusion, by experimenting, that the safe way to do this is by running iisreset.exe in a child process.
If you run iisreset.exe on a command prompt, you get feedback during the process. Running iisreset takes several seconds, and several lines of feedback is generated, with pauses in between.
I'd like to capture this feedback and present it in my Windows Forms application (in a ListBox), and I have succeeded with that. My remaining concern is that I dont get it until the child process finishes. I'd like to get the output from the child process, line by line, immediately when the lines are created.
I have tried to do my homework, reading/testing things from e.g. these:

*

*How to spawn a process and capture its STDOUT in .NET?

*Capturing console output from a .NET application (C#)

*http://www.aspcode.net/ProcessStart-and-redirect-standard-output.aspx
and several more with similar content. Most (all?) get the output asynchronously (e.g. with Process.ReadToEnd()). I want the output synchonously, which acording to the MSDN documentation involves establishing an event handler etc and I've tried that. It works, but the event handler does not get called until the process exits. I get the output from iisreset.exe, but not until it has finished.
To rule out the possibility that this has something to do with iisreset.exe in particular, I wrote a small console application that generates some output, pausing in between:
namespace OutputGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine("OutputGenerator starting and pausing for 10 seconds..");
            System.Threading.Thread.Sleep(10000);
            System.Console.WriteLine("Pausing for another 10 seconds..");
            System.Threading.Thread.Sleep(10000);
            System.Console.WriteLine("Exiting!");
        }
    }
}

Testing with this it turns out that I get captured data diretly when I want. So, to some extent it seems that the way iisreset.exe outputs the data come into play here.
Here is the code of the program (a Windows Forms application) that does the capture:
using System;
using System.Windows.Forms;
using System.Diagnostics;

namespace OutputCapturer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            // Running this will show all output after the process has exited
            //String path = @"C:\Windows\system32\iisreset.exe";

            // Running this will show all output "when it happens"
            String path = @"C:\OutputGenerator.exe";

            var p = new Process();
            p.StartInfo.FileName = path;
            p.StartInfo.UseShellExecute = false;  // ShellExecute = true not allowed when output is redirected..
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.CreateNoWindow = true;
            p.OutputDataReceived += OutputDataReceived;
            p.Start();
            p.BeginOutputReadLine();
        }

        private delegate void OutputDataToTextboxDelegate(String s);

        void OutputDataToTextbox(String s)
        {
            tbxOutput.Text += s + Environment.NewLine;
            tbxOutput.Refresh();
        }

        private void OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (e.Data != null && e.Data.ToString() != "")
            {
                // Must run the update of the textbox in the same thread that created it..
                tbxOutput.Invoke(
                    new OutputDataToTextboxDelegate(OutputDataToTextbox),
                    DateTime.Now.ToString() + ": " + e.Data.ToString()
                );
            }
        }
    }
}

Thinking it was an EOL-encoding problem (the output of iisreset.exe apearing as one line to my app)), I ran a debug session. Nope. The event handler for StandardOutput gets called several times (one time for each output line from iisreset.exe), buth these calls come in one burst after the process exits.
I would LOVE if I could get the output from iisreset.exe "when it happens" so that I can show it as a progress indication.
I've seen one other thread with the same/similar problem,  Asynchronous capture from a process output not working properly , but w/o a solution.
I'm sort of stumped.

A: To do autoflushing of printfs / stdouts
C equivalent of autoflush (flush stdout after each write)?
This saved my ass...

A: It seems that sixlettervariables is correct, and that this has something to do with iisreset.exe isn't flushing it's buffers for each line. (I still wonder what makes it work on a plain command line - i.e. what does cmd.exe do?)
Anyhow.. I tried what apacay suggested, and wrote this:
private void btnRun_Click(object sender, EventArgs e)
{
    // Running this will show the output after the process has finished
    //String path = @"C:\Windows\system32\iisreset.exe";

    // Running this will show all output "when it happens"
    String path = @"C:\OutputGenerator.exe";

    var p = new Process();
    p.StartInfo.FileName = path;
    p.StartInfo.UseShellExecute = false;  // ShellExecute = true not allowed when output is redirected..
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.CreateNoWindow = true;
    p.Start();

    StreamReader sr = p.StandardOutput;
    while (!sr.EndOfStream)
    {
        String s = sr.ReadLine();
        if (s != "")
        {
            tbxOutput.Text += DateTime.Now.ToString() + ": " + s + Environment.NewLine;
        }
        tbxOutput.Refresh();
    }
}

Notice that I am timestamping when I get each line. For my OutputGenerator I get this:
2011-07-06 17:49:11: OutputGenerator starting and pausing for 10 seconds..
2011-07-06 17:49:21: Pausing for another 10 seconds..
2011-07-06 17:49:31: Exiting!

And for iisreset.exe I get this:
 2011-07-06 17:57:11: Attempting stop...
 2011-07-06 17:57:11: Internet services successfully stopped
 2011-07-06 17:57:11: Attempting start...
 2011-07-06 17:57:11: Internet services successfully restarted

Running iisreset.exe on the command line, those lines come with pauses in between, over a span of perhaps 10 seconds.
The case seems more or less closed now. Not that I am all that satisfied, but I'm at roads end it seems. I'll reluctantly live with it..
To summarise: In the general case, it is quite possible to capture output synchronously with when it is generated. This thread presents code for two ways to do that - by establishing an event handler, and by "polling" the stream. In my specific case there is something with how iisreset.exe generates output that prevents this.
Thanks to those who participated and contributed!

A: Well.... you could kick it old-school. Output can be redirected to the input of another program using old-school DOS commands (foo.exe | bar.exe). Write a program that reads from standard in, and you'll get it every time the stream flushes.
Edit
You could also redirect the ouput to a named pipe and read from that. That would also be "as it happens".

A: I've had that problem and had to solve it when my logs where too long to read in a single readtoend.
This is what I've done to solve it. It's been doing Ok so far.
            myProcess.StartInfo.FileName = path;
            myProcess.StartInfo.Arguments = args;
            myProcess.StartInfo.UseShellExecute = false;
            myProcess.StartInfo.ErrorDialog = false;
            myProcess.StartInfo.CreateNoWindow = true;
            myProcess.StartInfo.RedirectStandardError = true;
            myProcess.StartInfo.RedirectStandardInput = (stdIn != null);
            myProcess.StartInfo.RedirectStandardOutput = true;
            myProcess.Start();

            int index;
            OpenLogFile(myLog);                      //LOGGGGGGGGGGGGG

            if (myProcess.StartInfo.RedirectStandardInput)
            {
                StreamWriter sw = myProcess.StandardInput;
                sw.Write(stdIn + Convert.ToChar(26));
            }

            StreamReader sr = myProcess.StandardOutput;
            /*stdOut = new ArrayLi
            */
            while (!sr.EndOfStream)
            {                                           //LOGGGGGGGGGGGGG
                Log(sr.ReadLine(), true);
            }

Here's OpenLogFile
    private void OpenLogFile(string fileName)
    {
            if (file == StreamWriter.Null)
            {
                file = new StreamWriter(fileName, true);
                file.AutoFlush = true;
            }
    }

Of course that Log is a function that does something elsewhere. But the solution to you question lies here:
        while (!sr.EndOfStream)
        {                                           //LOGGGGGGGGGGGGG
            Log(sr.ReadLine(), true);
        }

while stream reader is still reading, you can be writing it down as the log comes out.

A: Well, I tried a helper class that I know works: http://csharptest.net/browse/src/Library/Processes/ProcessRunner.cs
ProcessRunner runner = new ProcessRunner("iisreset.exe");
runner.OutputReceived += OutputDataReceived;
runner.Start("/RESTART", "/STATUS");

However, this still doesn't solve the problem with this specific executable.  It seems that iisreset was written in such a way that this is not possible.  Even running the following from the command line:
iisreset.exe /RESTART /STATUS > temp.txt

Still nothing is written to the text file 'temp.txt' until after all services have been restarted.
As for your example code, I would recommend reading a post I wrote some time ago:  How to use System.Diagnostics.Process correctly.  Specifically you are not reading the std::err stream or redirecting and closing the std::in stream.  This can cause very undesirable results in your program.  You can look at the example wrapper class linked above for how to do it with the output events, or if you want to directly read the streams you need to use two of your own threads.
    static void Main()
    {
        ProcessStartInfo psi = new ProcessStartInfo(@"C:\Windows\system32\iisreset.exe", "/RESTART /STATUS");
        psi.CreateNoWindow = true;
        psi.UseShellExecute = false;
        psi.RedirectStandardError = true;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardInput = true;

        ManualResetEvent output_complete = new ManualResetEvent(false);
        ManualResetEvent error_complete = new ManualResetEvent(false);

        Process p = Process.Start(psi);
        new ReadOutput(p.StandardOutput, output_complete);
        new ReadOutput(p.StandardError, error_complete);
        p.StandardInput.Close();

        p.WaitForExit();
        output_complete.WaitOne();
        error_complete.WaitOne();
    }

    private class ReadOutput
    {
        private StreamReader _reader;
        private ManualResetEvent _complete;

        public ReadOutput(StreamReader reader, ManualResetEvent complete)
        {
            _reader = reader;
            _complete = complete;
            Thread t = new Thread(new ThreadStart(ReadAll));
            t.Start();
        }

        void ReadAll()
        {
            int ch;
            while(-1 != (ch = _reader.Read()))
            {
                Console.Write((char) ch);
            }
            _complete.Set();
        }
    }

I wrote this just to see if anything was coming through.  Still got nothing until the end, so I think your just SOL on getting asynchronous output from iisreset.

A: For my specific situation, the solution is what Mr Moses suggested in a comment above, i.e. run iisreset /stop followed by iisreset /start.
I need a proper answer, rather than a comment, in order to mark it as my "accepted answer", so this answer is more of administrativa than a new contribution. The cred should go to Mr Moses.. :-)


text:
Q: How to do to see my AdMob Ads? i tryed ALL CODES FROM ALL THE WORLD and i got 2 things: 1) errors or 2)Don´t see ads..
This is my Manifest:

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.adview.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
<activity android:name="com.google.ads.AdActivity"
          android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
   </application>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
</manifest>

UPDATED!!!!
**This is my NEW Layout:**
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads= "http://schemas.android.com/apk/lib/com.google.ads"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/layout"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="@string/hello_world" />

<com.google.ads.AdView android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    ads:adUnitId="xxxxxxxx" i put my editor id here..
    ads:loadAdOnCreate="true"
    ads:adSize="BANNER"/>

</RelativeLayout>

And...
This is my class (i dont put anything because i did it in layout)
package com.example.adview;

import android.os.Bundle;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import android.app.Activity;
import android.view.Menu;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

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

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

I put the GoogleAdMobAdsSdk-6.4.1 (The latest version) in libs AND in Project>RightClick>Properties>JavaBuildPath>AddExternalJARs>GoogleAdMobAdsSdk-6.4.1

A: in main activity layout.xml have you added this
xmlns:ads= "http://schemas.android.com/apk/lib/com.google.ads"

for example
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads= "http://schemas.android.com/apk/lib/com.google.ads"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

and you have to add tihs line to your ad code
ads:loadAdOnCreate="true"

A: You either need to add this to your AdView
ads:loadAdOnCreate="true"

or you need to programmatically load your add from your Activity (I'd suggest in the onCreate).
final AdView adView = findViewById(R.id.adView);
adView.load(new AdRequest());

A: <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/ad_layout"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">
    </LinearLayout>

    ... Other View

</LinearLayout>

LinearLayout ad_layout = (LinearLayout) findViewById(R.id.ad_layout);
ad_layout.setOrientation( LinearLayout.VERTICAL );

mAdView = new AdView(this);
mAdView.setAdSize(AdSize.BANNER);
mAdView.setAdUnitId( UNIT_ID );

AdRequest.Builder adRequest = new AdRequest.Builder();
adRequest.addTestDevice( AdRequest.DEVICE_ID_EMULATOR );
adRequest.addTestDevice( "3204995868e01153" );
adRequest.addTestDevice( "b9ceca537aaddee2" );

ad_layout.addView( mAdView );

mAdView.loadAd( adRequest.build() );


text:
Q: Firebase functions - Using async/await with once() function I am fairly new to typescript and I have managed so far with it but I found a weird error/bug that I cannot figure out with async/await.
I have the following code snippet and my problem is that the 'await' clause doesn't work with the .once() function.
async function testFunction(deviceID:string){
    const returnObject:{name:string, description:string, tokens:string[]}[] = [];

    const deviceRef = admin.database().ref('deviceInfo/').orderByChild('id').equalTo(deviceID);

    await deviceRef.once('value', async (payload) => {
        const pushObject:{name:string, description:string, tokens:string[]} = {name:"", description:"", tokens:[]};
        if(payload.exists()){
            const devices = payload.val();
            const keys = Object.keys(devices);

            for(const key of keys){
                pushObject.name = devices[key].name;
                pushObject.description = devices[key].description;
                pushObject.tokens = await getTokens(key);
                returnObject.push(pushObject);

            }
            console.log("Return Object 1:", returnObject);
            return returnObject;

        }
        else{
            return null;
        }

    })
    console.log("Return Object 2:", returnObject);
    return returnObject;
}

This function always returns {name:" ", description: " ", tokens:[]} even though I have 'await' at the start of my deviceRef.once() function.
Also both console.logs print, "Return Object 1" prints the correct object with all the data retrieved from the DB but "Return Object 2" prints an empty array. So it is clear that the await is not waiting for the once() function to complete, I'm just not sure why this is?
Any help or advice would be appreciated

A: When using once(), you choose one of two options:

*

*Use the returned promise to get the data from the query.

*Pass a callback function as the second argument to get the data from the query.

If you're going to use async/await, I'd go with option 1.  Right now it looks like you're using a combination of 1 and 2.  Don't bother passing a callback function to once() if you're going to use the promise it returns.  That kinda defeats the purpose of using async/await.
const payload = await deviceRef.once('value')
if (payload.exists()) { ... }


text:
Q: How to create php pagination based on amount of MySQL results in an iframe without page refresh? I am trying to create some pagination and I'm not sure the best way to go about it. Currently the query is being run in a class file and then the results are printed out in an iframe. The pagination is to be based on the number of results, which is currently over 10 thousand, so the results take a few seconds to load in the iframe. It's currently using the JQuery datatables plug-in. I know datatables has pagination, but someone, at some point disabled it, and for all intents and purposes, I can't use it. So I need to come up with an alternative.
I thought I was smart by running a count on the results, and then storing that count in a session variable and then base the pagination on that, limiting it to 999 results per page, but since the storing of the variable and the query running happens at the same time, the page needs to reload for any pagination to show up and I don't want to have to reload the query. (Sorry for the run-on/long sentence there)
Short version: I need a way to asynchronously run the query, get the count, and have the pagination show up at the same time, and I just don't know how to go about it. I'm not super familiar with the ins and outs of JQuery and AJAX, but is that where my solution lies? I can show code if I need to, but I need more guidance than syntactic help.
Thanks

A: You can generate a json with the "count" of registers, after that you can divide the result by the amount of register per page, for instance you have 20 registers in table 'contacts' and you want to see 5 per page, you can divide 20/5, it gave you like result 4, this will be the amount of pages; then you will use 'limit' and 'offset' in sql defining how many registers do you want with limit and from where the search should start with offset.

A: So, I haven't run this to check syntax, but it should be good. This one query when used in PHP in conjunction with your AJAX call this should return everything you need as well as handle the pagination, this will also return the number of pages when using the defined results per page variable.
$resultsPerPage = (isset($_GET['resultsPerPage'] ? $_GET['resultsPerPage'] : 20);
$currentPage = (isset($_GET['page'] ? $_GET['page'] : 1);
$sql = "SELECT *, (COUNT(ID)/". $resultsPerPage .") AS pages FROM table OFFSET ". (($currentPage - 1) * $resultsPerPage) ." LIMIT ". $resultsPerPage;

I think this is what you were looking for? all that's left other than this is formatting and implementation.
Note actual SQL commands omitted because I don't know what engine or method you are using.

A: The datatables pagination is not something that should be disabled in this case, you should reenable it, and focus on whats really the issue: you have 10,000 rows, you should look at implementing a server side solution of datatables rather than client side, it says specifically that 10,000 is the magic number to make it viable


text:
Q: Cinema 4d export to Illustrator with texture I need little help with exporting from Cinema 4d to illustrator. The idea is I want to use body paint in c4d and then I want to export to Illustrator the model with my body paint work (not just grey model). Is it possible? The Idea is I create 3d model for my game but this models must be with precise dimensions. In Cinema 4d have measurement in centimeters, meters etc without pixels. Any ideas?
Thanks in advance

A: I'm very confused about what exactly you're trying to do.
You want to render a model inside C4D and texture, then use it inside Illustrator as an asset/sprite?
That's totally possible you just need to render the model with alpha.
And yes Cinema4d has measurement system:
Go to Edit -> User Preferences -> Units


text:
Q: When I upgrade a buildbot master do I have to upgrade all the slaves? I want to use the gitpoller in buildbot however I don't want to upgrade all the slaves.
Can I get away with upgrading the master to 0.8.3 leave the slaves on 0.7.x?

A: Buildbot has fairly good backwards and forwards compatibility between server and slave version. We try to keep backwards compatibility at least back to 0.7.12 (although we don't have tests set up to guarantee this). I suspect even older version will mostly just work, even with version 0.8.5, which is the most recent version.
To give you an idea on the rate of change, there have been about 330 changes to the slave and 2000 changes to the slave, since the code was split (sometime between 0.7.12 and 0.8.0).
One benefit to newer slaves, is that a bunch of commands have been added to the slave to allow a lot of the logic (particularly of source steps) to be moved to the master.
If you are upgrading, I'd suggest using 0.8.5 (with 1fed964da6b1c15e409dacb6ce0c9585e3669f3c if you use irc force builds).


text:
Q: Не устанавливаются библиотеки в venv через pip через файл requirements.txt При попытке установки через pip install -r requirements.txt
Терминал выдает ошибку:
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://pypi.org/simple/smart-json-log-formatter/


text:
Q: uploading a file using servlet
Possible Duplicate:
How to upload files in JSP/Servlet?
File Uploading with Servlets?

I am using Glassfish. How can i upload a file/image/song using a servlet ? After the user clicks the upload button in the form the servlet should handle that data and should copy it at a defined location on server.
Will the method be different if do this on some other server such as Tomcat ?


text:
Q: Finding last Occurence of String in C I want to compare a String in another String like "ther" in "motherfathersister" and the result would be either null ( no match ) or the remaining characters after the last occurence ( in this example) "thersister".
I have changed the implemantation of strstr from string.h but the result is everytime the same.
Where i have made a mistake?
Thanks
char *stRstr(char *s, char *m)
{
    char *last=NULL;
    size_t n = strlen(m);
    while(*s)
    {
        if(!memcmp(s++,m,n))
        {
            last=s-1;
        }
    }
    return last;
}

A: Thanks Guys
I found my mistake...
i didnt't called my function "stRstr" but "strstr"... And this function is already implemented...
Thanks for your help, without your feedback, in terms of that my functions returns the right result, i would have been lost...

A: As mentioned in the comments, your code will access s beyond its bounds (consider what memcmp does when s points to the last non-'\0'-character). So I'd get rid of the memcmp-usage and I'd scan the string from backwards.
In analogy to strstr, which quickly scans the string looking for a single-character match and compares then the rest, see the following code that does exactly the same in a backwards manner.
Hope it helps.
const char *stRstr(const char *s, const char *m)
{
    const char* ptr = s + strlen(s);
    size_t mlen = strlen(m);
    while (ptr-- != s) {  // until ptr reaches the beginning of s
        if (*ptr==*m) {   // single character match (first characters of s and m)?
            if (strncmp(ptr,m,mlen)==0)  // check the remainder
                return ptr;
        }
    }
    return NULL;
}

void printLast(const char* s) {
    if (s)
        printf("last: %s\n", s);
    else
        printf("string not found.\n");
}
int main() {

    const char* s = "this is the first, this is the last";
    const char* m = "this";

    const char* last = stRstr(s, m);
    printLast(last);

    last = stRstr(s, "not contained");
    printLast(last);

}

A: Your function should work (the problem is elsewhere) but it has some issues:

*

*using memcmp() is incorrect as it may access s beyond its last element. you should use strncmp() instead or add a test on the lengths.

*the posted code would not find the last occurrence of the empty substring and return NULL, where it should return a pointer to the trailing null byte.

*for consistency, you should call it strrstr() or my_strrstr().
Here is a faster and safer version:
char *my_strrstr(const char *s, const char *m) {
    char *last = NULL;
    size_t n = strlen(m);

    while ((s = strchr(s, *m)) != NULL) {
        if (!strncmp(s, m, n))
            last = (char *)s;
        if (*s++ == '\0')
            break;
    }
    return last;
}


text:
Q: Current transformers, voltage output vs current output I'm designing a energy monitoring system that is using split-core clamp current sensors to measure multiple high power lines(40+ lines at 300A each) in a MCB room of a building. I'm currently sourcing the current transformers and noticed that there are typically two types of outputs, voltage and current. I understand the only difference is that the voltage output has a burden resistor built-in the CT. My question is if there are any pros and cons in using one of it in terms of interference or accuracy?
The standard voltage output option seems to be either 333mV or 1V and the standard current output option seems to range from 30mA to 5A. Since most microcontrollers operate at 5V or 3.3V, is there a downside to increasing the burden the resistor, so that the output voltage increases making it easier to measure?
Lastly, if I were to use a 10 channel single-ended ADC on MCUs, and some resistors and capacitors to increase the voltage swing to be above 0V, will I face any significant inaccuracy or interference issues when connecting many CTs to the same MCU?
Any help or advice will be much appreciated thank you.


text:
Q: Syntax Error (Missing operator) in query expression '[ProductName] = Product1' when opening a form from a search report I am building a simple database and I want to have a report open when a result from a search report is clicked on.
The VBA code is as follows:
Private Sub Product_name_Click()

DoCmd.OpenReport "Product Table", acViewReport, , "[ProductName]= " & Me![ProductName]

DoCmd.Close acReport, "KeywordSearchReport", acSaveNo

End Sub

I get the error message in the title. It is correctly getting the value for Me![ProductName] and [ProductName] is a field in the underlying table. I have more or less this same code for opening a report after submitting a form and it works fine.


text:
Q: How do I prevent new programmers pushing `console.log` to Bitbucket? I want to prevent new programmers pushing code containing console.log to Bitbucket using pipelines. How I'll do it?

A: Assuming that it is not too important to prevent the push, but that it's enough to make sure that the build fails if console.log() encountered, you could implement a script step which greps the codebase. I'm doing something like this myself with Bb Pipelines, both with console.log and debugger.
The basic approach for that looks something like this:
foundfiles=$(fgrep -rli "console.log" --include='*.js' $BITBUCKET_CLONE_DIR/path/to/files)
result="$?"
if [ "$result" = "0" ]
then
    echo "Found in $foundfiles"
    exit 1
fi

A Bash script including code such as the above could then be run by your pipeline and will fail if console.log is found.


text:
Q: Rails Routing - :action => 'new' returns error "No route matches {:action=>"show"... in the same controller I am writing the code for a model called "ExternalDatabase".
The model file has no code in it outside of the class declaration. I have added view pages for index, new, show, and _form .html.erb.
config/routes.rb contains the line resources :external_databases. The model contains no nested resources at this time. There are other models declared within this application, though none of them interact with this model at the moment and they are all tested and are functional and closed prior to declaring resources :external_databases.
I have a link from within the index view to new_external_database_path, which behaves exactly like {:action => "new", :controller => "external_database"} if I am following correctly.
This should theoretically load application/external_databases/new which will render _form.html.erb. The first line of _form is <%= form_for(@external_database) do |f| %>
The problem as stated in the post title occurs when using the link to /new. The url application/external_databases/new has the following error:
No route matches {:action=>"show", :controller=>"external_databases"}
When I created a data member using rails console, it was displayed properly by index and show. The same _form file is used by the edit method, and successfully edits the console-created data member. Destroy also functions.
...So why isn't it recognizing the new method?
My controller code for this model:
    class ExternalDatabasesController < ApplicationController

     def index
      @external_databases = ExternalDatabase.all

      respond_to do |format|
       format.html # index.html.erb
       format.json { render :json => @external_databases }
      end
     end

     # POST /external_databases
     # POST /external_databases.json

     def new
      @external_database = ExternalDatabase.new

      respond_to do |format|
       format.html # new.html.erb
       format.json { render :json => @external_database }
      end
     end

     def show
      @external_database = ExternalDatabase.find(params[:id])

      respond_to do |format|
       format.html # show.html.erb
       format.json {render :json => @external_database }
      end
     end

     def create
      @external_database = ExternalDatabase.new(params[:external_database])

      respond_to do |format|
       if @external_database.save
        format.html {redirect_to @external_database, :notice => "New External Database         Profile was created successfully!"}
        format.json {render :json => @external_database, :status => :created, :location => @external_database}
       else
        format.html {render :action => "new"}
        format.json { render :json => @external_database.errors, :status =>         :unprocessable_entity }
       end
      end
     end

     #GET /external_databases/1/edit
     def edit
      @external_database = ExternalDatabase.find(params[:id])
     end

     # PUT /external_databases/1
     # PUT /external_databases/1.json
     def update
      @external_database = ExternalDatabase.find(params[:id])

      respond_to do |format|
       if @external_database.update_attributes(params[:external_database])
        format.html {redirect_to @external_database, :notice => "External Database         Profile was updated successfully!" }
        format.json {head :ok}
       else
        format.html { redner :action => "edit" }
        format.json {render :json => @external_database.errors, :status =>         :unprocessable_entity }
       end
      end
     end

     # DELETE /external_databases/1
     # DELETE /external_databases/1.json
     def destroy
      @external_database = ExternalDatabase.find(params[:id])
      @external_database.destroy

      respond_to do |format|
       format.html { redirect_to external_databases_rul }
       format.json { head :ok }
      end
     end

    end

Update: Added routes.rb and Views code
My routes.rb file:
    App::Application.routes.draw do

      resources :type_as do
         resources :type_bs
         end

      resources :type_bs do
        resources :type_as
        resources :type_cs
        end

      resources :type_cs do
       resources :type_bs
       end

      resources :external_databases

      root :to => "home#index"

    end

Views:
external_databases_form
    <%= form_for(@external_database) do |f| %>

      <%= f.label :name %>

      <%= f.text_field :name %>

      <%= f.label :description %>

      <%= f.text_field :description %>

      <%= f.label :url %>

      <%= f.text_field :url %>

       <%= f.submit %>

    <% end %>

index.html.erb

<%= notice %>

External Databases

      Database Name

     <% @external_databases.each do |exdb| %>

       <%= exdb.name %>
       <%= truncate(exdb.description) %>
       <%= link_to 'Show', exdb %>

       <%= link_to 'Visit', exdb.url, :target => "_blank" %>
       <%= link_to 'Edit', edit_external_database_path(exdb)%>
       <%= link_to 'Destroy', exdb, :confirm => 'Are you sure?', :method => :delete %>

     <% end %>

    <%= link_to 'New External Database Profile', { :action => "new", :controller => "external_databases" }%> |
    <%= link_to 'Home', root_path %>

new.html.erb

Creating a new External Database Profile

    <%= render 'form' %>

    <%= link_to 'Back', external_database_path %>

show.html.erb

<%= notice %>

      External Database Name
      Database ID

      <%= @external_database.name %>
      <%= @external_database.id %>

      URL

      <%= @external_database.url %>
      <%= link_to 'Visit External Database', @external_database.url %>

Description

     <!% @external_database.description.split.scan(/.{,60}/).each do |line| %>
      <!%= line %>

     <!% end %>

    <%= link_to 'Back to External Database Index', external_databases_path %> |
    <%= link_to 'Edit', edit_external_database_path(@external_database) %> |
    <%= link_to 'Destroy', :confirm => 'Are you sure?', :method => :delete %>

A: You have a typo in your new.html.erb file in your 'back' link. It should be:
external_databases_path

You can compare it with your own back link in show.html.erb above.
Fixed: new.html.erb

Creating a new External Database Profile

<%= render 'form' %>

<%= link_to 'Back', external_databases_path %>

A: I had a similar issue to this. Followed the instructions here with no luck. At the base of my form_for code for submit I had the 'create new' and 'delete' buttons. Turns out my create new was generating an error because of a dodgy delete button :/. Anyway, I can at least comment that out to get the new button working and then focus on debugging the delete button instead.
  = f.submit "Submit", class: "btn btn-large btn-primary"
  = link_to 'Create New', new_matrix_header_path, class: 'btn btn-primary'
  -#= link_to 'Delete', matrix_header_path(@matrix_header), method: :delete, data: { confirm: 'Are you sure?'}, class: 'btn btn-danger'

I looked through the stack and found it beginning the error around line 13 of my view which was the line with my delete button.
Started GET "/matrix_headers/new" for 127.0.0.1 at 2014-10-28 21:08:48 +1000
Processing by MatrixHeadersController#new as HTML
  User Load (0.2ms)  SELECT  `users`.* FROM `users`  WHERE `users`.`id` = 1  ORDER BY `users`.`id` ASC LIMIT 1
  Rendered shared/_error_messages.html.erb (0.4ms)
  Rendered matrix_headers/_form.html.haml (21.0ms)
  Rendered matrix_headers/new.html.haml within layouts/application (22.6ms)
Completed 500 Internal Server Error in 36ms

ActionController::UrlGenerationError - No route matches {:action=>"show", :controller=>"matrix_headers", :format=>nil, :id=>#<MatrixHeader id: nil>} missing required keys: [:id]:
  actionpack (4.1.1) lib/action_dispatch/journey/formatter.rb:39:in `generate'
  actionpack (4.1.1) lib/action_dispatch/routing/route_set.rb:597:in `generate'
  actionpack (4.1.1) lib/action_dispatch/routing/route_set.rb:627:in `generate'
  actionpack (4.1.1) lib/action_dispatch/routing/route_set.rb:663:in `url_for'
  actionpack (4.1.1) lib/action_dispatch/routing/url_for.rb:155:in `url_for'
  actionview (4.1.1) lib/action_view/routing_url_for.rb:83:in `url_for'
  actionpack (4.1.1) lib/action_dispatch/routing/route_set.rb:228:in `call'
  actionpack (4.1.1) lib/action_dispatch/routing/route_set.rb:179:in `call'
  actionpack (4.1.1) lib/action_dispatch/routing/route_set.rb:268:in `block (2 levels) in define_url_helper'
   () media/jay/DATA/rails_projects/my_app/app/views/matrix_headers/_form.html.haml:13:in `block in _app_views_matrix_headers__form_html_haml__2669648707298145379_8667520'

By commenting out the delete button it now routes through to new correctly without going to the No route matches {:action=>"show" error.


text:
Q: Sketch the complex function: $z\overline{z}+(1+2i)z+(1-2i)+1=0$ Tried sketching the complex function: $z\overline{z}+(1+2i)z+(1-2i)+1=0$
I first simplified it by converting $z=x+yi$
I got: $(x+yi)(x-yi)+(1+2i)(x+yi)+(1-2i)+1=0$
Which gave me this implicit function: $$(x^2+y^2+x-2y+2)+(2x+y-2)i=0$$
This is where I got confused as I don't know how to go further and sketch this function.
Could it be that there's a typo in the question or is there something I'm missing?

A: You have $(x^2 +y^2 +x−2y+2)+(2x+y−2)i=0 $ so this complex number is identically zero, meaning that both real and imaginary parts must be zero.
However, looking at the real part, you have$$x^2 +y^2 +x−2y+2=0$$ $$\Rightarrow(x+\frac 12)^2+(y-1)^2=-2+1+\frac 14<0,$$ so there are no real $x$ and $y$ satisfying this equation and hence no locus.

A: Already you have obtained that $$Z=(x^2+y^2+x-2y+2)+(2x+y-2)i=0$$
Note that $$x^2+y^2+x-2y+2=(x+\frac12)^2+(y-1)^2+\frac34\gt0.$$ Hence $\Re( Z)\gt 0$ and $Z\not=0.$
Therefore, there are no such complex numbers.


text:
Q: How to use immutable objects to replace observer pattern I was happy when O.o was announced but turns out it's not in the woodwork anymore. One of the advised replacement libraries explains it on its github page as such:

Web development evolved in the direction of functional programming and immutable objects, so that's where we all should look at.

Although I've been hearing about immutable data structures recently I still don't know how I'm supposed to use them to replace the functionality of the observer pattern.

A: Immutable data structures do not exactly replace the functionality of the observer pattern, they merely make it redundant. Immutability simply means "unable to change", so whereas the observer pattern tells you when objects change, using immutable objects means that they will never be able to change (if you do need to add or remove values, then you would create a new immutable object), so you don't need to worry about handling change events any more. You can use Immutable.js to get immutable Maps or Lists or Stacks or other complex data structures (and you may want to read The case for Immutability on that page). Or you can use plain javascript (the Object.freeze function introduced in ES5.1) to make object literals immutable:
var o = { a: 99 };
Object.freeze(o); // make o immutable
o.a = 100; // a still equals 99, this assignment silently fails because o is immutable

A: I think you misunderstood the message of that.
Immutable data and observers (reactive programming) are a great pairing. It's just that Object.observe in particular becomes redundant - if Object doesn't change, what exactly are you trying to observe here?
The library you linked to is a compatibility patch for browsers that don't (yet) support the ECMA standard for Object.observe. Since the standard retracted the interface, this is no longer valid. That doesn't mean someone can't keep this as a library - it just means it's no longer a compatibility patch. That's all that's meant by the comment, IMO.
Change and its detection in Javascript frameworks is a pretty good read on the topic. The last point, Om, basically talks about a reactive approach over immutable data, with plenty of links for deeper study. Of course, I still recommend reading the whole article - it nicely outlines how the state change approach changed over the years, and as such, gives you the details you want - what were the problems with our old approaches that are solved by the new (50 year old :P) paradigm. Note that only the state itself is immutable - you can switch states just fine and that's the thing you're observing.


text:
Q: Tensorflow Lite tf.assign() equivalent Is there an equivalent operation for the tf.assign() operation in TFlite?
In case it helps: I use this operation to hold the RNN cell states in variables as I process a sequence iteratively at inference time. Another use case for this is storing CNN layer outputs in a fifo queue, similar to fast-wavenet implementation.


text:
Q: Rcpp error through RExcel I have a problem in using Rcpp from Rexcel.
(especially, sourceCpp() function)
I'm running a 64-bit Windows 10 platform.
I installed R ver 3.3.1 and RExcel.
I also installed Rtools by Rtools34.exe.
I can use RExcel properly if I don't use sourceCpp().
Hoewver, when I use sourceCpp() function, I have an error.
From Rexcel, I execute the command
library(Rcpp)

and this step, there is no error.
Next, I put the following command
sourceCpp("C:/Users/ChrisCCCCC/Desktop/ChrisCCCCC/program/samplecode.cpp")

and Run code.Then, the error message
Error in command:
sourceCpp("C:/Users/ChrisCCCCC/Desktop/ChrisCCCCC/program/samplecode.cpp")

  'C:/Program' not found
attr(,class)
[1] try-error

Is anyone else know the reason of this error?
Of course I set the path for Rtools.
and I can run the code
sourceCpp("C:/Users/ChrisCCCCC/Desktop/ChrisCCCCC/program/samplecode.cpp")

with no error from normal RGui and RStudio.
Why sourceCpp() causes an error through RExcel while there is no error through normal RGui?
Can anyone help me, please?


text:
Q: How to declare two dimensional arrays using pointers? Hello there I am having trouble declaring two dimensional arrays using pointers. I am new to C.
int main(){

    int x = 0;
    int y = 0;

    int *xdim;
    int *ydim;

    printf("Enter x:\n");
    scanf("%d", &x);
    printf("Enter y:\n");
    scanf("%d", &y);

    xdim = &x;
    ydim = &y;

    char sq[xdim][ydim];

    return 0;
}

I want the two dimentionial array char sq to hold the values inputed by the user. I get error non-integer type *int. I am also new to pointers.

A: Using VLAs (which are allowed in C99, or as an extension to many compilers), all you need to do is:
int xdim, ydim;
scanf("%d %d", &xdim, &ydim);

char vla_array[xdim][ydim];

As you can see, there is no need for pointers.

The 2nd option is to use "ordinary" arrays. You need to declare an array with big enough size, and use only a part of it:
#DEFINE X_MAX_DIM 100
#DEFINE Y_MAX_DIM 100

char vla_array[X_MAX_DIM][Y_MAX_DIM];

int xdim, ydim;
scanf("%d %d", &xdim, &ydim);
// check xdim and ydim are acceptable sizes

// from now on you use up to `xdim x ydim` of your array, even if
// it was declared as `100x100`

You can use this only when you know in advance the maximum allowed dimensions of your array.

The 3rd option is to use dynamic allocation. This is the only option if the array is very big. However this is an advanced topic, so you will not deal with this right now.

A: int** ptr = NULL;
ptr = new int*[val];

for(int i=0; i < val; i++)
{
    ptr[i] = new int[val];
}

above code allocates 2d array of val*val

A: change char sq[xdim][ydim]; to char sq[*xdim][*ydim];, else you pass the location of the value rather than the value itself.
But it is unnecessary to use pointers in this case, you could just use x and y.

A: In the code you sowed the error occured because in this declaration
char sq[xdim][ydim];

there are used pointers  xdim and ydim instead of integers. You could write
char sq[*xdim][*ydim];

Though there is no need to use pointers such a way.
If your compiler supports Variable Length Arrays then you can for example just write
int main( void )
{
    size_t m = 0;
    size_t n = 0;

    printf("Enter x:\n");
    scanf("%zu", &m);
    printf("Enter y:\n");
    scanf("%zu", &n);

    if ( !m || !n ) return 1;

    char sq[m][n];

    //...

    return 0;
}

Otherwise you have to allocate arrays dynamically. For example
#include <stdlib.h>

int main( void )
{
    size_t m = 0;
    size_t n = 0;

    printf("Enter x:\n");
    scanf("%zu", &m);
    printf("Enter y:\n");
    scanf("%zu", &n);

    if ( !m || !n ) return 1;

    char **sq = malloc( m * sizeof( char * ) );

    for ( size_t i = 0; i < m; i++ ) sq[i] = malloc( n * sizeof( char ) );

    //...

    for ( size_t i = 0; i < m; i++ ) free( sq[i] );
    free( sq );

    return 0;
}

A: I believe if i understand what you're asking this should work.
Using a single pointer within a 2D array;
#include <stdio.h>
#include <stdlib.h>
int x = 0, y = 0;
char *arr = (char *)malloc(x * y * sizeof(int));