text:
Q: Moodle SQL - tabela de registro respostas de um questionário por aluno Faaaaala galera!
No moodle, no banco de dados, em uma atividade quiz, onde encontro a tabela de registro de respostas dadas por alunos em um determinado questionário?
Eu estou fazendo assim, onde no campo lastname, é onde coloco um código para escola e no campo institution uso para colocar nome da escola, está correto o raciocínio lógico? rsrs:
SELECT
     SUBSTRING(u.`department`,2,5) AS Turma,
     u.`firstname` AS Aluno,
     u.`lastname` AS Siem,
     u.`institution` AS Escola,
     i.`itemname` AS Simulado,
     g.`finalgrade` AS Nota,

(select count(u.`firstname`)

from  `mdl_grade_items` i INNER JOIN `mdl_grade_grades` g ON i.`id` = g.`itemid` INNER JOIN `mdl_user` u ON g.`userid` = u.`id`

  where itemid = 6  and courseid = 2  and lastname = 213 AND finalgrade != "NULL") totalAlunos,

(select avg(finalgrade)

from  `mdl_grade_items` i INNER JOIN `mdl_grade_grades` g ON i.`id` = g.`itemid` INNER JOIN `mdl_user` u ON g.`userid` = u.`id`

  where itemid = 6  and courseid = 2  and lastname = 213 and department = ".5anoA") notaTurmaA,

(select avg(finalgrade)

from  `mdl_grade_items` i INNER JOIN `mdl_grade_grades` g ON i.`id` = g.`itemid` INNER JOIN `mdl_user` u ON g.`userid` = u.`id`

  where itemid = 6  and courseid = 2  and lastname = 213 and department = ".5anoB") notaTurmaB,

(select avg(finalgrade)

from  `mdl_grade_items` i INNER JOIN `mdl_grade_grades` g ON i.`id` = g.`itemid` INNER JOIN `mdl_user` u ON g.`userid` = u.`id`

  where itemid = 6  and courseid = 2  and lastname = 213) as NotaGeralEscola

FROM
     `mdl_grade_items` i INNER JOIN `mdl_grade_grades` g ON i.`id` = g.`itemid`
     INNER JOIN `mdl_user` u ON g.`userid` = u.`id`

WHERE
     i.courseid = 2  AND itemtype = "mod"  AND itemmodule = "quiz"  AND finalgrade != "NULL"  AND g.`itemid` = 6

ORDER BY
     u.`department` ASC, finalgrade desc

A: Acho que você consegue algo, com uma consulta similar a esta, adapte ela de acordo com o que você precisa:
SELECT DISTINCT q.id, q.name, q.questiontext,  qw.id, qw.answer,qa.id, qa.rightanswer as resposta_aluno
FROM mdl_quiz_attempts qt
INNER JOIN mdl_question_attempts qa ON qt.uniqueid=qa.questionusageid
INNER JOIN mdl_question_answers qw ON qa.questionid=qw.question
INNER JOIN mdl_question q on q.id = qa.questionid
WHERE qt.id=? // ID DA TENTATIVA, NA TABELA quiz_attempts
ORDER BY qw.id ASC;


text:
Q: Migrate Odoo CRM DB from V6 to V8 My boss give me a task to migrate a OpenERP V6 DB that have CRM installed on it and have CRM data to migrate it to V8 without any loss of the data
I need to know how to implement something like that or how to move the data and update the database from v6 to v8
update 1 :
i tried to use openupgrade ,, i have downloade migrate.py and run command
python migrate.py --config=[openerp-server.conf] --database=[kamel] --run-migrations=7.0 but i alawys got an error
No user found in configuration

and here is my openerp-server.conf:
[options]
; This is the password that allows database operations:
admin_passwd = admin
db_host = localhost
db_port = 5432
db_user = odoo
db_password = odoo
addons_path = /Users/mostafa/Documents/odoo-develop/odoo8/addons,/Users/mostafa/Documents/odoo-develop/net2do_work,/Users/mostafa/Documents/odoo-develop/more_net2do,/Users/mostafa/Documents/odoo-develop/freelance_work,/Users/mostafa/Documents/odoo-develop/custom_addons
pg_path= /usr/local/bin

A: Check this stackoverflow link.There are many ways on how to do this.But I am not sure whether this solution works for you but u  can just try out

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does thread synchronization mean thread safety? Thread synchronization or serialization, strictly defined, is the application of particular mechanisms to ensure that two concurrently-executing threads or processes do not execute specific portions of a program at the same time. (From wikipedia).
So if an object implements thread synchronization, does it mean that it's thread safe?

A: Thread synchronization is a method for achieving thread safety.  Thread safety just means that a program can run multiple threads at the same time without any chance of the threads corrupting each other's state.
It's possible to have thread safety without thread synchronization in some cases, though -- for example, if two threads both read from the same data structure but no thread ever modifies the data structure, that program can be thread safe without any thread synchronization required.  There are also some lockless data structures that are designed to be useable by multiple threads without synchronization.

So if an object implements thread synchronization, does it mean that
  [it has] thread safety?

If the synchronization was done correctly, yes.  It's very easy to do it incorrectly (or incompletely) if you're not careful, in which case even with the synchronization the program might still occasionally crash or give incorrect output due to lack of thread safety.

A: Yes. Thread synchronization means Thread safety. If 2 tickets are there and 3 customers are there. Then, if I have to declare a method for randomly choosing which threads will get the tickets must be a a synchronized method.Please take a look at this example which is very easy to understand.
        public class ThreadSynchronization {
            public static void main(String[] args) {
                Ticketbooking tb = new Ticketbooking();
                Thread t1 = new Thread(tb);
                Thread t2 = new Thread(tb);
                Thread t3 = new Thread(tb);
                t1.start();
                t2.start();
                t3.start();
            }

        }

        class Ticketbooking implements Runnable {
            int tickets = 3;

            @Override
            public void run() {
                System.out.println("waiting => " + Thread.currentThread().getName());
                m1();

            }

            private synchronized void m1() {
                if (tickets > 0) {
                    System.out.println("booking for => " + Thread.currentThread().getName());
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    tickets--;
                    System.out.println("Booked for => " + Thread.currentThread().getName());
                    System.out.println("tickets now => " + tickets);

                } // if
                else {
                    System.out.println("ticket not booked for => " + Thread.currentThread().getName());
                } // else

            }
        }// end1
    /*
    The output will be :
    waiting => Thread-0
    waiting => Thread-1
    waiting => Thread-2
    booking for => Thread-0
    Booked for => Thread-0
    tickets now => 1
    booking for => Thread-2
    Booked for => Thread-2
    tickets now => 0
    ticket not booked for => Thread-1
*/

This can also be solved using Executors.newFixedThreadPool().Here is the solution :
public class Test13 {
    public static void main(String[] args) {
        Ticketbooking1 tb1 = new Ticketbooking1();

        ExecutorService service = Executors.newFixedThreadPool(3);

        for (int i = 0; i < 3; i++) {
            service.execute(tb1);
        }
        service.shutdown();

    }
}

class Ticketbooking1 implements Runnable {
    int tickets = 2;

    @Override
    public void run() {
        System.out.println("waiting => " + Thread.currentThread().getName());
        m1();

    }

    private synchronized void m1() {
        if (tickets > 0) {
            System.out.println("booking for => " + Thread.currentThread().getName());
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            tickets--;
            System.out.println("Booked for => " + Thread.currentThread().getName());
            System.out.println("tickets now => " + tickets);

        } // if
        else {
            System.out.println("ticket not booked for => " + Thread.currentThread().getName());
        } // else
    }

}// end1

/*  The output :
 * waiting => pool-1-thread-1
waiting => pool-1-thread-3
waiting => pool-1-thread-2
booking for => pool-1-thread-1
Booked for => pool-1-thread-1
tickets now => 1
booking for => pool-1-thread-2
Booked for => pool-1-thread-2
tickets now => 0
ticket not booked for => pool-1-thread-3

 */

Synchronization is not required if we use Executors.newSingleThreadExecutor(). Here I have not made method m1 as synchronized .
public class Test13 {
    public static void main(String[] args) {
        Ticketbooking1 tb1 = new Ticketbooking1();

        ExecutorService service = Executors.newSingleThreadExecutor();
        service.execute(tb1);
        service.execute(tb1);
        service.execute(tb1);
        service.shutdown();

    }
}

class Ticketbooking1 implements Runnable {
    int tickets = 2;

    @Override
    public void run() {
        System.out.println("waiting => " + Thread.currentThread().getName());
        m1();

    }

    private void m1() {
        if (tickets > 0) {
            System.out.println("booking for => " + Thread.currentThread().getName());
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            tickets--;
            System.out.println("Booked for => " + Thread.currentThread().getName());
            System.out.println("tickets now => " + tickets);

        } // if
        else {
            System.out.println("ticket not booked for => " + Thread.currentThread().getName());
        } // else
    }

}// end1

/*  the output :
 * waiting => pool-1-thread-1
booking for => pool-1-thread-1
Booked for => pool-1-thread-1
tickets now => 1
waiting => pool-1-thread-1
booking for => pool-1-thread-1
Booked for => pool-1-thread-1
tickets now => 0
waiting => pool-1-thread-1
ticket not booked for => pool-1-thread-1

 *
 *
 * */


text:
Q: Why are request cookie poperties null or incorrect on ASP.NET postback? I'm debugging the HttpContext.Current.Request.Cookie values in an ASP.NET web application, and finding the only property correctly populated is the Value. The Domain and Path are null, and the Expires value is set to DateTime.Min.

A: Those values are not available in the Request.Cookies collecton.  They are only used when you are "setting" the value.  You can verify this with a network trace.  In the request headers, the client browser only sends the name/value pairs in the "Cookie" header.


text:
Q: Hue/Hive user root is not allowed to impersonate Hue Situation:
I have set up Hive, Hue and Hadoop in different Docker Containers. In the same Docker network. I created a Container for each 1 Hadoop Namenode, 2 Datanodes,1 Hue instance, 1 Hive Server and a Postgres Metastore. I was able to configure a hue proxy user in the hdfs-site.xml of the namenode and can browse the filesystem via webhdfs. For Hive however I get the error within Hue:
Failed to open new session: java.lang.RuntimeException:
org.apache.hadoop.ipc.RemoteException
(org.apache.hadoop.security.authorize.AuthorizationException):
User: root is not allowed to impersonate hue

I am able to create Hive tables in Hive or write to them from within Sparkjobs for example.
What I've tried so far:
I've tried adding properties like

*

*hive.server2.proxy.user = hue

*hive.server2.enable.impersonation=true

*hadoop.proxyuser.hue.hosts=*

*hive.server2.authentication=NONE

in different configuration files like:

*

*core-site.xml in hdfs-namenode configuration folder

*core-site.xml in hive-hadoop folder

*hdfs-site.xml in both

*hive-site.xml in hive-conf folder

Most of this was suggested in similar questions but it does not seem up to-date anymore. For some properties Hive says: Property unknown
What I need clarification on:

*

*What is the right file to add the configuration to ?

*What is the right property to add ?

*Do I have to add some configuration to hue regarding the metastore ?

Additional Information:
 - Hive Version: 2.3.1
 - Hive Hadoop Version: 2.7.4
 - Hadoop Cluster Version: 2.7.2 (I think version difference should not be the problem here ?!)
Hue Version: 4 (gethue/hue:latest form docker-hub)

*

*The full error log here

*Hive configuration here

*HDFS-site configuration here

A: Okay I found a solution that works:
Add the following properties to the hadoop namenodes and datanodes core-site.xml:
<property>
  <name>hadoop.proxyuser.root.groups</name>
  <value>*</value>
</property>
<property>
  <name>hadoop.proxyuser.root.hosts</name>
  <value>*</value>
</property>

Furthermore you need to set the path to Hive config if Hive is running on another machine/container in the hue .ini file and copy the hive-config folder to your hue container/machine.
Note that in the Hue docs the configuration for WebHdfs is done in the hdfs-site.xml and the hive configuration is done in hive-site.xml

A: I also encountered the same problem as you. The difference is that I built a Hadoop Ecological Cluster locally. When I wanted to integrate my HDFS file system with hue, I encountered this problem. My idea is that my Hadoop belongs to the root user. When I installed hue, I added hue users, so I need to change the permissions of my hue, Let my hue access Hadoop. In fact, this is just like the mutual access between folders. My Hadoop belongs to the highest level of root, but my hue is not, so the idea is very clear. I hope I can help you


text:
Q: Is this partition algorithm correct? I've been looking at the partition function in the book "Cracking the Coding Interview" (5e, page 119). I've copied it below:
int partition(int arr[], int left, int right){
    int pivot = arr[(left + right) /2 ]; // Pick pivot point
    while (left <= right) {
        // Find element on left that should be on right
        while (arr[left] < pivot) left++;
        // Find the element on right that should be on left
        while (arr[right] > pivot) right--;
        // Swap elements, and move left and right indicies
        if (left <= right) {
            swap(arr, left, right); // swaps elements
            left++;
            right--;
        }
    }
    return left;
}

Given this array:
1 2 3 4 5 6 3

This is how the partition worked out for me in steps

*

*4 is the pivot value. left = 0, right = 6

*left = 3, right = 6. Swap.
1 2 3 3 5 6 4

*left = 4, right = 4. Exit
However, the array I ended up with:
1 2 3 3 5 6 4

Is not partitioned around 4. Have I followed the steps incorrectly or is the algorithm incorrect? I've double checked my reproduction of the algorithm and I've copied it correctly.
Also, I'm not positive why partition is returning left, is it returning the pivot?
I understand the Wikipedia implementation of partition and quicksort, but I'm trying to wrap my head around what's going on here.

A: The goal of the partition is to break the array into two segments.  The first segment contains elements [1,2,3,3].  All of these values are less than or equal to four.  The second segment contains elements [5,6,4].  All of these values are greater than or equal to four.
The partition function returns where the second segment begins.  In this case it starts at index 4.

A: The goal of partition algorithm is to simply take some collection of elements (for example, you work with "arrays") and then partitioning (or splitting!) this collection around the pivot into two parts — left part and right part.
There should be some "rule" regarding the elements on the left of pivot and on the right of the pivot.
For example, all elements on the left will be smaller than the chosen pivot and all the elements on the right will be greater than the pivot.
You may also see the Implementation in the following video:
https://www.youtube.com/watch?v=MLpH7mpwOxQ
Hope that helps!


text:
Q: Does iText provide mechanism for overlapping margins? I've been trying to organize sections with multiple margins, but they ofter overlap with other margins:

*

*HEADER / SECTION / CONTENT

*HEADER / CONTENT / SECTION

*CONTENT / SECTION / CONTENT

*SECTION / SUBSECTION

Each of those has different set of margins; HEADER has to have margins, no matter if it's followed by CONTENT or SECTION and SECTION should also have some margins to separate it from CONTENT.
This results with case where HEADER's margin and SECTION's margins are overlapping, creating double-sized margin.
Is there any margin mechanism in iText that can result with taking Max(margin1,margin2) instead of Sum(margin1,margin2)?

A: Using HEADER margin/padding bottom (I don't remember which one we've been always using until now) along with 'spacingBefore' for Section Paragraphs worked just fine.


text:
Q: how to make div border wrap around text, but still be block?
I am making a chat application with angular and bootstrap for practice.
Trying to make div border wrap around the text like the iPhone message bubbles,
inline-block didn't seem to work.
relevant code:

Chat with {{activeFriend.name}}

          {{message.from}}
          {{message.message}}

        <form ng-submit='sendMessage(messageText)' name='messageForm'>
          <input type='text' name='message' ng-model='messageText' required/>
          <input ng-disabled='!messageForm.$valid' type='submit' value='send'/>
        </form>

CSS:
.messages {
  border: 1px solid black;
  border-radius: 15px;
  /*display: inline-block;*/
}

.message-right {
  text-align: right;
}

.message-left {
  text-align: left;
}

A: You have to float the containing divs left and right, and then clear each one.
HTML:

Chat with {{ activeFriend.name }}

Message from 1

Message 1

Message from 2

Message 2

        <form ng-submit='sendMessage(messageText)' name='messageForm'>
            <input type='text' name='message' ng-model='messageText' required/>
            <input ng-disabled='!messageForm.$valid' type='submit' value='send'/>
        </form>

CSS:
.messages {
    border: 1px solid black;
    border-radius: 15px;
    display: inline-block;
}

.message-right {
    clear: both;
    float: right;
}

.message-left {
    clear: both;
    float: left;
}

.sendMessage {
    clear: both;
}

.col-md-4 {
    width: 33%;
}

Demo: https://jsfiddle.net/jcmorris/m2a3Lrxv/1/

A: Nevermind, i figured it out, i had to put the inline-block on the spans inside the div instead of the div itself

A: HTML

Chat with {{activeFriend.name}}

              {{message.from}}
              {{message.message}}

          <form ng-submit='sendMessage(messageText)' name='messageForm'>
            <input type='text' name='message' ng-model='messageText' required/>
            <input ng-disabled='!messageForm.$valid' type='submit' value='send'/>
          </form>

CSS
/* Represents row (block you wanted) */
.message-wrap {
  margin-bottom: 10px;
}

/* Represents message */
.message {
  border: 1px solid black;
  border-radius: 15px;
  display: inline-block;
}

.message-right {
  text-align: right;
}

.message-left {
  text-align: left;
}


text:
Q: How to bind model to formbuilder using reactive forms in angular8 i have used reactive forms in my application and binding to html using formcontrolName. But now instead of declaring the properties inside the formbuilder, i need to call a model and assign that model to the formbuilder and use it in html.
I been through many links but didnt find anywhere how to work based on my requirement.
HTML:

          Agent Code *
          <input type="text" formControlName="agentCode" class="form-control">

TS:
 this.userInfoForm = this.FB.group({
        Id: 0,
        agentCode: this.agentCode,
        userName: [''],
        firstName: [''],
        middleName: '',
        lastName: [''],
        department: [''],
      });
      this.userInfoForm.controls['agentCode'].disable();

model.ts:
export class UserFormDetails {
   Id: number;
   agentCode: number;
   userName: string;
   firstName: string;
   middleName: string;
   lastName: string;
   department: string;
}

DEMO

A: based on the comments, it sounds like you want a dynamic form based on a model... there is no "out of the box" solution to do this. You can write your own form model:
interface MyFormModelField {
  initial?: {
    value: any,
    disabled: boolean
  },
  controlOptions?: AbstractControlOptions
  // anything you find useful really?
}

export type MyFormModel<T> = Record<keyof T, MyFormModelField>

then implement it like so:
const USER_FORM_MODEL: MyFormModel<UserFormDetails> = {
    Id: { },
    agentCode: {
        initial: {
          value: '',
          disabled: true
        },
        controlOptions: {
          validators: Validators.required
        }
    },
    userName: { },
    firstName: { },
    middleName: { },
    lastName: { },
    department: { },
}

then you could write a service for producing form groups based on an instance of the form model...
@Injectable({providedIn: 'root'})
export class MyFormBuilder {
  constructor(private: fb) { }

  buildForm<T>(formModel: MyFormModel<T>) {
    const fg = Object.keys(formModel).reduce((grp, k) => {
      const fld = formModel[k];
      return Object.assign(grp, {
        [k]: [fld.initial || '', fld.controlOptions]
      })
    }, {});
    return this.fb.group(fg);
  }
}

now, anytime you make changes to the UserFormDetails interface, typescript will yell at you to update the corresponding form model with the field information... and while updates won't flow "automatically" from a model update, you at least have some type safety in your forms. I'd personally stop here.
This next part isn't perfect, and I'm not a fan of it, but if you really want the next step to have it be more or less automatic from the class definition, you could write a function to build a default form model from a class, like this:
function buildDefaultFormModel<T>(model: new () => T) {
  return Object.keys(new model()).reduce((form, k) => {
      return Object.assign(form, {[k]: {}})
  }, {} as MyFormModel<T>)
}

this requires 2 things, 1, the class your building a form for MUST have a default specified for each field, fields without defaults wont't be included. (This introduces a hidden dependency on fields having default values, which is why I don't like this method, however, you CAN configure ts to yell at you if you write a class that has properties without defaults or constructor assignments):
class UserFormDetails {
   Id: number = 0;
   agentCode: number = 0;
   userName: string = '';
   firstName: string = '';
   middleName: string = '';
   lastName: string = '';
   department: string = '';
}

2, the object constructor must take no parameters. but TS will yell at you if you try to misuse it in this case.
the function could be used like this:
const USER_FORM_MODEL: MyFormModel<UserFormDetails> = {
  ...buildDefaultFormModel(UserFormDetails),
  ...{
    agentCode: {
      initial: {
        value: '',
        disabled: true
      },
      controlOptions: {
        validators: Validators.required
      }
    },
  }
}

this way you can use default fields, and also provide an override for specific fields.
finally, you could also leverage this form model to build a template, but that's a bigger task.
here's a blitz with this all implemented (and I went ahead and cleaned up the controller code): https://stackblitz.com/edit/github-ck3u8u-qtnasc?file=src%2Fapp%2Fuser-table%2Fuser-table.validators.ts

A: You have to use patchValue to bind you model in the FormGroup form control.
this.userInfoForm = this.FB.group({
        Id: 0,
        agentCode: this.agentCode,
        userName: [''],
        firstName: [''],
        middleName: '',
        lastName: [''],
        department: [''],
      });

this is correct.
When you get UserFormDetails object you have to pass it to form you have to do :
 this.userInfoForm.patchValue({
   'Id': UserFormDetails.id
    ...
})

and when you had to pass the form controls value to object:
 this.UserFormDetail.id = this.userInfoForm.get('Id').value

etc...

A: I think this might be the solution you are looking for:
private initUserForm() {
   // mapping the object into the form model
   this.userInfoForm = this.FB.group({ ...this.userDetails });

   // if you want to add validators or disable buttons...
   this.userInfoForm.controls.agentCode.setValidators(Validators.required); // adding validations
   this.userInfoForm.controls.agentCode.disable();
   // console.log(this.userInfoForm.controls);
}

This way covers your need of "binding" which is not a real binding as the framework doesn't allow such thing, but it allows you to map from the object model/values to create the reactive form model.

See how after adding an extraField, the forms pick up that control and its value:


text:
Q: UnboundLocalError: local variable 'Control_Type' referenced before assignment Dear Stackflow community!
I know this question comes like weekly but I could not find the right solution to my problem.
I am trying to write a function the read a raw file.
The code looks like this:
def read_raw(file_name):
   f = open(file_name, 'r')
   lines = f.readlines()
   header = lines[9].rstrip().split('\t')
   dicts = {}

   for x,y in enumerate(header):
       if y == 'FeatureNum'
           num_id = x
       elif y == 'ProbeName':
           probe_name = x
       elif y == 'gProcessedSignal':
           signal = x
       elif y == 'ControlType':
           Control_Type = x

   for l in lines[10:]:
       l = l.rstrip().split('\t')
       if l[control_type] == '0':
           dicts[l[num_id]] = {'FeatureNum': l[num_id],\
                               'ProbeName': l[probe_name],\
                               'gProcessedSignal': l[signal]}
   df = pd.DataFrame.from_dict(dicts)
   df['Signal'].astype(float)
   return df

I think you can imagine how the raw looks like and what I want to take out from it!
Now the thing is, I want to can call all the files from my directory, call out the function and put it all into a list, something like this:
path = os.getcwd()
os.chdir(path)
all_files = glob.glob(os.path.join(path, '*.txt'))

array_list = []
for files in all_files:
    arrays = read_raw(files)
    array_list.append(arrays)

And then I got This:
if l[Control_Type] == '0':
UnboundLocalError: local variable 'Control_Type' referenced before assignment

Is there a way to fix this problem? I also tried to put global for control_type before the dictionary but it also did not work.
I would preferably have it without global though since I've read that it could messed with your function though.
Thank you in advance and wish you a lovely evening here in Austria.

A: Are you sure about the spelling? 'C' not 'c'? and 'T' not 't'? in Control_Type.
Because in the code I could see control_type and in the error I could see Control_Type.


text:
Q: Create SPA in Nuxt.js I have a navigation bar (and maybe a footer), which should be visible on every nested page. So basically just the content changes. In Vue.js I would just use <router-view> as placeholder for the dynamic content and <router-link> to switch this content.
Now in Nuxt.js I have the following dir structure.
pages/
--| calendar/
-----| index.vue
--| people/
-----| index.vue
--| index.vue

And my navigation bar consists of two <nuxt-link> e.g. <nuxt-link :to="/calendar"> (some content) </nuxt-link>. So if I click on this link, the navigation bar disappears and only the content in /pages/calendar/index.vue is displayed.
Sorry, I am new to nuxt, but I thought it would be possible to create a SPA like in Vue.js. I even  changed the mode from universal to spa and also used the Vue.js approache like explained above, without success.

A: You can extend the main layout by adding a layouts/default.vue file. It will be used for all pages that don't have a layout specified. Make sure to add the  component when creating a layout to actually include the page component.
Something like this:
<template>

My blog navigation bar here

    <Nuxt />

My footer is here

</template>

if you need use it in a sub-child route, you can use inside your pages/index.vue the NUXT-CHILD to get sub-child-nested-page...
<template>

FIXED BANNER

      <nuxt-child />

FIXED LIST OF ITEMS

</template>


text:
Q: Fatal error: Class 'Mage_Framework_Helper_Data' not found in app/Mage.php When creating User Roles I encountered a "Fatal error: Class 'Mage_Framework_Helper_Data' not found in /var/www/latest/app/Mage.php on line 547" when I clicked on create user roles.
Please I need your help on how to solve this issue.
Thanks.

A: I found out the solution to my problem. I renamed the file in app/code/local/Megnor/Framework/etc/adminhtml.xml to admin.xml and it works now. This thread on magentocommerce helped me out http://www.magentocommerce.com/boards/viewthread/354259/.
Thanks.

A: adminhtml.xml or system.xml could contain such line(s)
<xmlnode translate="title" module="module">
...
</xmlnode>

Magento passes the module argument to the Mage::helper() factory method.
Mage::helper('module');

Factory method looking for the class prefix to use in the node global/helpers/module/class. If helper part of config is missing, magento tries to load one from core codepool by prefixing the class id with mage_ and appending _helper.
As a result class prefix = mage_module_helper and it resolves to mage_module_helper_data. And autoloader tries to load Mage/Module/Helper/Data.php


text:
Q: AngularJS, strange behavior, entering if statement even the expression is not true I want to do some action in my controller when the view is loaded. In my controller, I have the following code:
$scope.$on('$viewContentLoaded', function () {
//Here your view content is fully loaded !!
   if ($scope.hasErrors === true) {
     showError('Error message');
     $scope.errorMessage = 'error';
   }
});

Firstly, this event fires multiple times. I suppose it is due to angular digest cycle? But, the strange thing is, when I debug js in my Firefox, it comes to the logical expression and even when
$scope.hasErrors = false

it stops on the line
$scope.errorMessage = 'error';

Is this issue due to Firefox, or something else?

A: You don't have anything wrong in you code.
It has something to do with Firefox. It highlights that line, but it's not executing it.
There are some issues posted on the internet about step debugging in Firefox.
For example THIS and THIS


text:
Q: Why Android Location Service is not running? I want to update my location on server using service but i am not getting why my service is not running. here is code:
package com.example.friendlocation;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;

public class UpdateLocationService extends Service {

String url = "http://coders-hub.com/googlemap/new/location.php";
JSONParser jsonParser = new JSONParser();
String id;

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {

    if(intent==null || intent.getAction()==null)
        return START_NOT_STICKY;

    Toast.makeText(getApplicationContext(), "In onCreate()!", Toast.LENGTH_SHORT).show();

    SharedPreferences sp=getSharedPreferences("location", Activity.MODE_PRIVATE);
    id=sp.getString("id", null);
    if(id!=null)
    {
        Toast.makeText(getApplicationContext(), "In id!", Toast.LENGTH_SHORT).show();
         LocationManager lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
         Criteria c=new Criteria();
         String provider=lm.getBestProvider(c, false);
         lm.requestLocationUpdates(provider, 0, 0, new LocationListener() {

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onLocationChanged(Location location) {
                // TODO Auto-generated method stub
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("id", id));
                params.add(new BasicNameValuePair("lat", location.getLatitude()+""));
                params.add(new BasicNameValuePair("longi", location.getLongitude()+""));
                JSONObject json=jsonParser.makeHttpRequest(url,"POST", params);
                Toast.makeText(getApplicationContext(), "In onLocationChanged()!", Toast.LENGTH_SHORT).show();
                try {
                    int success = json.getInt("success");
                    if (success == 1)
                        Toast.makeText(getApplicationContext(), "Updated in Service!", Toast.LENGTH_SHORT).show();
                    else
                        Toast.makeText(getApplicationContext(), "Not updated in Service!", Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    //e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Error in JsonException Service!", Toast.LENGTH_SHORT).show();
                }

            }
        });
     }

    return START_NOT_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

 @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
   }

 }

I added permissions in AndroidManifast.xml file and declare Service like this:
<service android:name="com.example.friendlocation.UpdateLocationService">
    </service>

And calling it from listener class:
Intent i=new Intent(context, UpdateLocationService.class);
context.startService(i);

But service is not starting.


text:
Q: Android Navigation bar appearing when in full screen In my application, I have set it up in the XML so it is in full screen using
 android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

Now this works fine when the app opens, however if while using the app, I use the home button to back out of the app, and then open it again, when it opens, a black navigation bar will appear for a second or two before disappearing. This does not occur if I exit the app using the back button, just the home button.
Does anyone know why this happens? I have tried doing it from code instead using
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    //Remove notification bar
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

However, what this does is removes the title bar, but the black bar is there at the top, just nothing is in it.
I.e. this bar

I tried combining the code, by putting the full screen line of code in the XML and also adding the code I showed above into the app, but same thing happens. If I back out of the app with home button and enter it again, that black bar will appear for two seconds temporarily pushing the app and its contents down before righting itself again.
How do I go about fixing this? I have been trying loads of different solutions, but nothing seems to work.
Thanks in advance

A: Seems to a bug with Android OS. Only way to fix it is go to device, settings animation, and disable animations.

A: try to remove animation by setting->brightness->animation
set no animation there


text:
Q: single bit manipulation is it possible to get just one bit of an int in C and then flip it without reading the entire int and writing it back to memory?
context:
trying to avoid too many locks/unlocks in pthread.

A: You can not read a single bit from the memory, actually you can not force CPU to read only a single byte. It is always reading a full cache line, which could have different sizes for different CPUs.
But from the language point of view you can use bit fields http://publications.gbdirect.co.uk/c_book/chapter6/bitfields.html

A: As far as I know, the lowest unit of operation is the byte. Maybe you can split the int into bytes and read the required byte from the word and change only that one.

A: No. Why would it, even if you could read one bit from memory you'll still need locking to make sure it's safe.

A: Either use the smallest type that can be addressed atomically (char is fine on any sane architecture, but some RISC junk cannot atomically operate on individual bytes) and accept that you'll be wasting some space, use a lock, or use the right atomic primitives (in asm, gcc builtins, or C1x _Atomic types) for atomic arithmetic on individual bits.

A: Here is how ya do it 50x faster than grandpa mutex (we did tests on this sort of thing).  Use gcc atomic operations. You could also use linux atomic operations if your release included them.
typedef union _foo {
  struct {
    unsigned int a:1,
                 b:6,
                 q:2;
  } Data;
  unsigned int n32;
} TFoo;

TFoo _GlobalFoo;

SomeFuncThatChangesFoo_A(int fNewA)
{
TFoo Old, New;

  while(1) {
    // get a copy of the current state
    Old.n32 = _GlobalFoo.n32;
    New.n32 = Old.n32;
    New.Data.a = fNewA;
    // compare and swap is the atomic operation.
    // if _GlobalFoo hasn't changed since we copied it to "Old", then change _GlobalFoo to "New".
    // __sync_bool_compare_and_swap works on basic types (8 bit, 16 bit, 32 bit, 64 bit, 128 bit
    // depending upon architecture), which is why there is a union overlaying the 32 bit n32 over
    // the actual data that the program uses, Data.
    if (__sync_bool_compare_and_swap(_GlobalFoo.n32, Old.n32, New.n32))
      break; // successfully changed
    // if we get here, the global was changed by another thread, so we just loop back, get the new value
    // and try again.
  } // concurrency loop
}

Astute threaders might think that the line "Old.n32 = _GlobalFoo.n32;" could copy garbage in a race if the compiler chose a non-atomic way to perform the copy.  However, __sync_bool_compare_and_swap would just fail because of the a bad copy of the current state, so there would be no harm done.
cheers.

A: This might be possible, but only in a non-portable, non-standard way and only if your platform supports it.  Some ARM CPUs (Cortex-M3 and M4 for example) implement 'bit-banding' that provides bit level addressing to regions of address space.
But in general, the smallest unit for reading/writing (or equivalently, the smallest addressable unit) is a char.


text:
Q: Reverse engineer assembler which probably encrypts code? I use an IDE with integrated assembler to write code for microcontrollers of a company which also produces the IDE and assembler I just mentioned.
Because the development kit with hardware in-circuit programmer is quite expensive I would like to reverse engineer their way of assembling the written source-code into the file format which is later transferred to the controller via the programming device.
So basically what I did was writing a very basic assembly program (like this):
mov a, 0x01

and changed very little of it (like this):
mov a, 0x02

then I took a look at the generated files in binary format. What I expected was not even close to what was actually happening:
Not only a single byte changed (what I was hoping for) but 2000 bytes of a total of 2300 changed!
The methods which would be possible to do this are either encryption or compression, or maybe both combined.
Is it possible to decrypt or decompress the files even though I have no idea what algorithm they are using?

A: Do not assume the most complex answer to your questions; instead, always look for the simplest explanation of what you see. Why going all the way to encrypting and stuff when vendor's low market share and lack of documentation do almost as good job in keeping secrets? Adding encryption (and decryption in hardware!) will cost the vendor (a lot of) money.
It may simply be the case that the two instructions you used are very different, and also that your tools calculated difference incorrectly.
mov a, 0x1 may be encoded as inc a, which might be, let's imagine, one byte long, and mov a, 0x2 may be representable as a two byte machine instruction. After that all the subsequent bytes will be offset to one position in files being compared, and, if your comparison tools cannot accommodate for that, they will report a huge difference.
In general, it is possible to reverse things. It will be very time consuming, an undertaking proportionally big to the size of instruction set and to number of features the binary format you are studying.
Essentially, you want reconstruct the layout of a binary format, and machine encoding scheme. Providing minimally different inputs and looking at outputs is a correct first thing to do; but you cannot make conclusions just after a single experiment. It is simply not enough data collected.
If you are really decided to jump into this, I recommend you to start from studying papers, tools and approaches used by people for solving similar cases. Hackme tutorials, papers on reversing etc. Be prepared that it will take you a least several months before you could get first results. It is fun, but not always a well-paid activity.


text:
Q: How to store HTML emoji v3.0 code in PostgreSQL? I would like to store a couple of country flags into my PostgreSQL database. But when my website's view file fetches the flag data the source output looks like this text <td>&#127482;&#127480;</td> and not the flag Emoji.
INSERT INTO mytable (country, flag) VALUES ('United States', '🇺🇸');

I tried to create the flag column with these Data Types:

*

*VARCHAR(150)

*TEXT

But the web browser's source output doesn't seem to give me the visual Emoji. I DuckDuckGo some websites and PostgreSQL docs, and read some other threads on this issue. But I can't grasp their answers and understand how to implement this.
Help please.
It works when I hard code the Emojis directly into my HTML files but not when I save it to Postgres and fetches it with EJS.
https://www.quackit.com/character_sets/emoji/emoji_v3.0/emoji_icons_flags.cfm
https://www.w3schools.com/charsets/ref_emoji.asp

A: Hi @BjarniRagnarsson you are correct I just took a look at Tags chapter and tried it out.
https://ejs.co/
Before = Incorrect,
<%= your_variable %>
After = Correct,
<%- your_variable %>
But it seems I only get the visual Emoji as intended on Firefox not in Chrome. Guess I have to resort to using image files for my flags in order to display it correctly on all web browsers.


text:
Q: Running Multiple Users Simultaneously from one Script in LoadRunner LoadRunner Version: 11.52
Build: 4391
Protocol: TruClient Ajax
So I am trying to run a load runner script I have written, with multiple users simultaneously.    The Script works something like this(Over simplification):

*

*User logs into system

*Script/User does something in system

*Script/User logs out

My issue is with step 1 of this process because I need to run the same test for each user but simultaneously.  Short of writing the same test multiple times with different users for each test hard coded in, is there a way where I could have the LR Controller read in user names from a file (or parameterize it somehow) such that it runs each test with a different user?  Thanks!

A:
is there a way where I could have the LR Controller read in user names from a file

See training material or product documentation.   Parameterization: Unique, Block size.   As you are new to the tool be aware that this is a tool that mandates a large set of foundation skills to be successful, plus a period of training and internship.  It looks like your managers have thrown you to the proverbial wolves.  Expect to lose limbs in gruesome incidents.
Users do not operate to a "clock tick."  Concurrent, operating on different pages and on different schedules within the same window of time?  Yes.  Simultaneous to the point of coordinated clicks on the same pages at the same time?  No. See the book, "Chaos, Making a new science" by James Gleick regarding some interesting insights on user behavior that will forever impact your performance testing efforts  -- I have a dog eared copy from college that I re-read once every five years for new insights based upon my experiences.

A: Not really in any meaningful and effective way, no.
This is primarily for usability reasons (why have something called a 'virtual user' when you can do something like this in the script) but of course that usability aspect has the extra feature of protecting HP's licensing.  HP bills primarily based on number of vusers purchased.  If a perf engineer could simply and easily make their one vuser run as multiple vusers, that would defeat the purpose of darn near everything in their billing structure.
There are a myriad of shortcuts and half-measures you could take but I don't think you'll find too many folks who will instruct you on such methods because it treads pretty near going against the terms of service and a lot of people who have built their careers around HP Loadrunner (like me) won't support such things.  I know this isn't what you're advocating, but just fyi.
With that being said you can use the cheap (now free?) license HP provides for 25 vusers.  If that's not enough you'd probably want to consider going with a jmeter type product where the price is right.
I'm not sure if this is what you're looking for but this is how I read your question.  Stack Overflow isn't too great around getting clarification on questions, but I'd ask why you need such methods.  If it's truly to simulate more than your allotted number of vusers that's not something HP supports.  If you need to run business processes, but not necessarily simultaneously you can create a longer script.
EDIT: Engrish


text:
Q: How to display subtitles with an flv file in a web page? I've created subtitles for a video in mp4 format, that i would like to put online, as an FLV file.
Is it possible to have the subtitles played along with the flv file without integrating them into the video images, so keeping them in srt format ?

A: I found a way, using JW flv player :

*

*convert your .srt file to an xml file (php code below)

*then add a variable "captions" pointing to your xml file:

s0.addVariable("captions","path/to/subtitles.xml");
live example here

// script to convert multi-line srt caption files to new-format (02-05-08) tt XML caption files
$use_cdata_tags = true;
$debug_output = true;

// the directory to write the new files in
// it must exist, be writeable, and be outside of the directory that is being scanned
$new_directory = '../temp/';

/////////////////////////////////// no user configuration below this \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

// get filename or scan directory if it's a directory
$filename = (isset($_GET["filename"])) ? strval($_GET["filename"]) : "./";

// read each file into an array
$it = new RecursiveDirectoryIterator("$filename");

foreach(new RecursiveIteratorIterator($it) as $file)
{

// debug('Filename', $file); exit;
// debug('Ext', substr(strtolower($file), (strlen($file) - 4), 4));// exit;

// debug - only use test file
// if($file == '.\multi-line_test_file.srt')

  // check for .srt extension
  if(substr(strtolower($file), (strlen($file) - 4), 4) == '.srt')
  {
    $ttxml     = '';
    $full_line = '';

    if($file_array = file($file))
    {
      // write tt , head, and div elements for the new file
     $ttxml .= "";
      $ttxml .= "\n";
      $ttxml .= "  \n";
      $ttxml .= "  \n";
      $ttxml .= "  \n";
      $ttxml .= "    \n";

      foreach($file_array as $line)
      {
        $line = rtrim($line);

// debug('Line', $line);

        // get begin and end
        //                00  :  00  :  32  ,   000   -->   00  :  00  :  37  ,   000
        if(preg_match('/(\d\d):(\d\d):(\d\d),(\d\d\d) --> (\d\d):(\d\d):(\d\d),(\d\d\d)/', $line, $match))
        {
          $begin = $match[1] . ":" . $match[2] . ":" . $match[3] . "." . $match[4];
          $end   = $match[5] . ":" . $match[6] . ":" . $match[7] . "." . $match[8];
          $full_line = '';
        }
        // if the next line is not blank, get the text
        elseif($line != '')
        {
          if($full_line != '')
          {
            $full_line .= '' . $line;
          }
          else
          {
            $full_line .= $line;
          }
        }

        // if the next line is blank, write the paragraph
        if($line == '')
        {
          // write new paragraph
          //                 Nothing is going on.
          if($use_cdata_tags)
          {
            $ttxml .= "      \n";
          }
          else
          {
            $ttxml .= "      " . $full_line . "\n";
          }

// debug('Text', $line);
// debug('ttxml', $ttxml); exit;

          $full_line = '';
        }
      }

// write ending tags
$ttxml .= " \n";
$ttxml .= " \n";
$ttxml .= "\n";

      // write new file
      $new_file = $new_directory . substr($file, 0, (strlen($file) - 4)) . '.xml';
      $fh = fopen($new_file, 'w') or die('Can\'t open: ' . $new_file);
      fwrite($fh, $ttxml) or die('Can\'t write to: ' . $new_file);
      fclose($fh);
    }
  }
}

function debug($title, $value)
{
  global $debug_output;

  if ($debug_output)
  {
    print "";
    if (is_array($value))
    {
      print $title . ":\n";
      print_r($value);
    }
    else
    {
      print $title . ": " . $value;
    }
    print "\n";
  }
}

?>


text:
Q: Bootstrap4 - 2 columns: left scroll, right fixed map Using Bootstrap4 to create a two column layout, the left column should scroll (currently it's not) and the right column should not scroll (currently it does as shown by the scroll bar in the image). The map should always be the height of the window (referred to as the "viewport" in Bootstrap, I think). FYI, the contents of the left column grows with time as the server pushes more hosts into it:

HTML:

list of hosts (should scroll)

google map (should NOT scroll)

CSS:
.col-md-2 {
    border-right: 1px solid black;
    min-height: 100vh;
    overflow-y: scroll;
    padding: 0;
}

Thanks

A: Here's an example that uses a fixed sidebar: https://jsfiddle.net/Lbn21js8/1/
I added an id selector to the sidebar, and a background color:

list of hosts (should scroll)

google map (should NOT scroll)

With this CSS:
#sidebar {
  border-right: 1px solid black;
  overflow-y: scroll;
  padding: 0;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
}

The linked jsFiddle appends a new paragraph to the sidebar every 1.5 seconds, so if you wait long enough you'll see the sidebar's scrollbar become active/scrollable.
With this, as long as you constrain the map section to never be bigger than the viewport, you won't see a scrollbar for the page.

A: I used this CSS and it worked for me:
CSS:
#map {
    margin-left:20%;
    position:fixed;
}

This will allow the left column col-md-2 to be scrollable and prevent the right column col-md-10 from scrolling.  By adding margin-left:20%;, the right column won't overlap the content on the left.


text:
Q: MOSS 2007 - list permission I have configured my list so that users can only read and edit items they have created.
I now need to configure this list so that a particular group of users can edit and read all items on this list. I know users with the 'Manage Lists' permission would be able to do this.
My question is can this be configured to be even more granular to apply a permission that works like the  'Manage Lists' permission but only for a particular list, rather than all lists?
Many Thanks,
Nav

A: Cant you do this:

*

*Create a permission set which has manage lists (do not assign any groups to this)

*Create a group for the list itself - do not assign any permissions to the group

*Add people to the group

*navigate to the list

*add the group to the groups allowed access to the list

*modify the group permissions on only this list to include the permission set you created in step 1 (which has manage lists permission).


text:
Q: Silverlight data binding breaks when there is no debugger attached Ok, a bit of a strange one - and it's probably something simple as I'm pretty new to Silverlight!
I have an object with the following property:-
private int targetID = NULL_TARGET_VALUE;
    [Display(Name="Target", Order=1)]
    [Required]
    public int TargetID
    {
        get
        {
            return targetID;
        }
        set
        {
            if (this.targetID != value)
            {
                this.ValidateProperty("TargetID", value);

                this.targetID = value;

                this.RaisePropertyChanged("TargetID");
            }
        }
    }

This object is created using the DataForm from the toolkit. I use the AutoGeneratingField event to change the item to a combo box drop down with the code below:
if (e.PropertyName == "TargetID")
        {
            ComboBox target = new ComboBox() { DisplayMemberPath = "Title", SelectedValuePath = "ItemID" };
            target.ItemsSource = TaskManager.Manager.GanttItemSource;
            var selectedItem = TaskManager.Manager.GanttItemSource.FirstOrDefault(p => p.ItemID == ParentTargetID);
            target.SelectedItem = selectedItem;
            e.Field.ReplaceTextBox(target, ComboBox.SelectedValueProperty, binding => binding.Converter = new TargetNullValueConverter());
            break;
        }

This does result in a drop down as I would expect. On my save button event I have this code:
if (registerForm.ValidateItem())
        {
            this.task.Save();
        }

If the debugger is attached to the silverlight project this works great. If it's not then ValidateItem returns false as it thinks I have added an invalid target ("Input is not in a correct format" is the exact validation error I get).
Any ideas really appreciated! (BTW Just to confirm this happens in both release and debug build modes, simply attaching or removing a debugger causes this to occur)

A: Dammit, the issues was down to this line in the autogeneratingfield event:-
e.Field.ReplaceTextBox(target, ComboBox.SelectedValueProperty, binding => binding.Converter = new TargetNullValueConverter());

This allows it to work
                            e.Field.ReplaceTextBox(target, ComboBox.SelectedValueProperty);

Which makes sense because I'm dealing with ints not objects. Still don't know why it works with the debugger attached however!


text:
Q: How to run a shell command inside AWK that takes AWK variables as the input? My package manager has a option --dry-run or -n that shows what packages will be installed when I do a update -u.
It outputs in the following format <pkgver> <action> <arch> <repository> <installedsize> <downloadsize>,
~ $ xbps-install -un | head -n 5
MesaLib-devel-20.1.4_1 update x86_64 https://alpha.de.repo.voidlinux.org/current 148212 35909
amdvlk-2020.Q3.2_1 update x86_64 https://alpha.de.repo.voidlinux.org/current 53003388 17077076
audacious-4.0.5_1 configure x86_64 https://alpha.de.repo.voidlinux.org/current 2016807 578996
libwavpack-5.3.0_1 configure x86_64 https://alpha.de.repo.voidlinux.org/current 174280 86184
libfluidsynth-2.1.3_1 configure x86_64 https://alpha.de.repo.voidlinux.org/current 448560 216298

I want to know only two things, the packages that are bigger than a MiB. The download size is in column 5, so, I did the following to get in human readable format, filter through grep and pretty print.
~ $ xbps-install -un | numfmt --field=5 --to=si | grep -P '\d+M' | awk '{printf("%30s%7s\n",$1,$5);}' | head -n 5
        amdvlk-2020.Q3.2_1    54M
         audacious-4.0.5_1   2.1M
 audacious-plugins-4.0.5_1   6.2M
           openvdb-7.0.0_1   9.2M
          alembic-1.7.13_1   3.0M

This works great. I want to make it shorter. I know has awk (mine is gawk) has a inbuilt PCRE, so I can get rid of grep. But when I try this, I get nothing.
   ~ $ xbps-install -un | numfmt --field=5 --to=si | awk '$5==/\d+M/ {printf("%30s%7s\n",$1,$5);}'

But awk throws me an error saying,
   awk: cmd. line:1: warning: regexp escape sequence `\d' is not a known regexp operator

I thought gawk supported PCRE, but apparently it doesn't. So, I replace \d+ with [0..9]+. I get no error, but no output. Please help fix the error. Is there a way to run a command inside AWK? Something like this
   ~ $ xbps-install -un | awk '$5>1024 { print $1 `numfmt --to=si $5`; }

Is this even possible? Even in Perl/PHP?
EDIT: I'm sorry I asked the question in a wrong way. My main question was if there is a way to expand shell commands in AWK with AWK variables. For example, in bash shell commands can be expanded as below,
   ~ $ file `which python`
   ~ $ file $(which python)
   ~ $ file (which python)       # in fish

Similarly, I want to numfmt a awk variable, $5 like numfmt --to=iec $5. So, I was wondering if I can do something like
   ~ $ xbps-install -un | awk '$5>1024 { print $1 `numfmt --to=si $5`; }

A: Your awk just needs to be written as below. And \d is a PCRE digit pattern which is not/never supported in GNU Awk. Pipe the output of numfmt to below
awk '$5 ~ /M$/{ printf("%30s%7s\n", $1, $5) }'

which means, match those columns in $5 whose last character ends with an M which would be the converted SI units in MB
The pattern below is wrong, because the == brings in literal string "equality" check in Awk, which you have intermingled with an incorrect PCRE construct.
awk '$5==/\d+M/'

Also the range expressions need to be written as [0-9] and not [0..9].

For the updated question, for which OP wants to use numfmt inside awk, for which I don't see a reason as they can very well pipe the output of numfmt to awk.
If you want to run the numfmt command inside awk, you can use the getline function in awk
awk '$5 > 1024 { cmd = "numfmt --to=si " $5; print $1, ((cmd | getline res)>0)? res : $5; close(cmd) }'

This approach is not needed as your original cmd | numfmt | awk approach is very well valid.


text:
Q: creating a bcd squarer using verilog Basically, I am using a lookup table to output in bcd the square of a single digit bcd.
The problem that I have is that it is not outputting the correct answer.
For example: the result I get for the square of these number are:
1 = 1
2 = 4
4 = 10
5 = 19
10 = 64
as you can see I have to separate MBCD and LBCD and then concatenate them.
Here is my code:
module bcdsquarer(input[3:0]bcdin, output[7:4]Mbcd, output[3:0]Lbcd);
parameter msb = 16;
parameter lsb = 8;
reg [lsb-1:0]ROM[0:msb-1];
integer i;
initial
    begin
    for(i=0; i<16; i = i+1)
        begin
            ROM[i] = i**2;
        end
    end
    assign {Mbcd,Lbcd} = ROM[bcdin];
endmodule

do anyone see where I made a mistake at?
edit:
Okay, So know I have to convert from binary to bcd. I have a code that converts, but how do I implement it with my bcdsquarer?
here is my code
module B2BCD(B,hundreds,tens,ones);
    input [7:0] B;
    output [3:0] hundreds;
    output [3:0] tens;
    output [3:0] ones;
    integer x;
    reg [3:0] hundreds, tens, ones;
    always @(B)
    begin
        x=B;
       hundreds=0; tens=0; ones = 0;
       if(x>99)begin hundreds =hundreds +1; x =x-100; end
       if(x>99)begin hundreds =hundreds +1; x =x-100; end
       repeat(9)
       begin
       if(x>9)begin tens = tens +1; x =x-10; end
       end

       ones =x;
    end
endmodule

I tried implementing it like this: (I just get x for my results now)
module bcdsquarer(bcdin,Mbcd,Lbcd,tens,ones);
parameter msb = 16;
parameter lsb = 8;

input[3:0]bcdin;

output[7:4]Mbcd;
output[3:0]Lbcd;

output [3:0] tens;
output [3:0] ones;

integer x;
reg[3:0] tens;
reg[3:0] ones;
    always @(bcdin)
    begin
        x=bcdin;
       tens=0; ones = 0;
       begin
       if(x>9)begin tens = tens +1; x =x-10; end
       end

       ones =x;
    end

assign Mbcd = tens;
assign Lbcd = ones;

reg [lsb-1:0]ROM[0:msb-1];
integer i;
initial
    begin
    for(i=0; i<16; i = i+1)
        begin
            ROM[i] = i**2;
        end
    end
    assign {Mbcd,Lbcd} = ROM[bcdin];
endmodule

A: Basically Verilog operations are done in binary not BCD. So if you do something like i**2 the result will be in binary. Splitting the nibbles doesn't convert binary to BCD.
You have two options. Either:

*

*Continue and implement a binary to BCD conversion - you could do this as a function, which because it is used in an initial block shouldn't infer any hardware assuming it is something the synthesizer can calculate. Or

*Compute all the values before hand, and simply initialise the LUT you have designed with the precomputed values. This is by far the easiest way, and to be honest likely (or so I've found) the usual way of doing it.
In the latter option you can do this several ways. One is to use something like Excel to compute a table of values and initialise the LUT from that - e.g. by reading the values in turn from a file (Verilog has macros for this like $readmem).
Alternatively if you are feeling adventurous, you can create a script (e.g. TCL) which creates the values and generates either the a Verilog file containing the code for the whole LUT including initialation, or creates a memory initialisation file which you can load into your LUT. This option is not really useful for this particular example, but great for more complex ones, perhaps save it for once you've gained more experience.

A: This is a code that is similar that I used for single digits squared (0-9).
module squarer(
input [3:0] B,
output [7:0] SQ
);

localparam NL=16;
localparam Nb=8;
reg [Nb-1:0]ROM [0:NL-1];
integer i;
initial
begin

ROM[0]=8'b0000_0000;
ROM[1]=8'b0000_0001;
ROM[2]=8'b0000_0100;
ROM[3]=8'b0000_1001;
ROM[4]=8'b0001_0110;
ROM[5]=8'b0010_0101;
ROM[6]=8'b0011_0110;
ROM[7]=8'b0100_1001;
ROM[8]=8'b0110_0100;
ROM[9]=8'b1000_0001;

end
assign SQ=ROM[B];
endmodule

The simulation code was:
module testsq;
reg [3:0] B;
wire [7:0] SQ;

squarer uut (
    .B(B),
    .SQ(SQ)
);

initial begin
B = 0;

#10  B = 0;
#10  B = 1;
#10  B = 2;
#10  B = 3;
#10  B = 4;
#10  B = 5;
#10  B = 6;
#10  B = 7;
#10  B = 8;
#10  B = 9;

#10 $finish;
end

endmodule

This gave the correct values for 0-9, 0=00, 1=01, 2=04, 3=09, 4=16, 5=25... 9=81.
Hope this helps, not sure if it exactly answers the question.


text:
Q: Same form to open with different content So I'm building a simple windows tool to display different embeded videos and some tips as technical support for a specific department on my company. The thing is that I have in line more than 50 videos I want to display and I do not want to create a form for each one of them. The idea is to have 2 forms, one where I have the list of videos and by clicking on the desired tutorial it opens a new form where the video would run. So I'm basically looking for a way of getting one form that displays different contents depending on the selected video. Is it possible? this is how i'm doing it now for 1 video:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim MyHTMLCode As String = "<object width=" & C() & "420" & C() & " height=" & C() & "315" & C() & " src=" & C() & "//www.youtube.com/embed/W7W8VjKIBUY" & C() & " frameborder=" & C() & "0" & C() & " allowfullscreen></object>"
    Me.WebBrowser1.DocumentText = MyHTMLCode
    Me.WebBrowser1.Update()

End Sub
Private Function C() As Object
    Return Convert.ToChar(34)

End Function

Any help welcome.
Regards

A: Add a Constructor to your Form to receive the URL:
    Dim f1 As New Form1("www.youtube.com/embed/W7W8VjKIBUY")
    f1.Show()

In Form1:
Public Class Form1

    Private _URL As String

    Public Sub New(ByVal URL As String)
        Me.InitializeComponent()
        Me._URL = URL
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim MyHTMLCode As String = "<object width=" & C() & "420" & C() & " height=" & C() & "315" & C() & " src=" & C() & "//" & Me._URL & C() & " frameborder=" & C() & "0" & C() & " allowfullscreen></object>"
        Me.WebBrowser1.DocumentText = MyHTMLCode
        Me.WebBrowser1.Update()
    End Sub

    Private Function C() As Object
        Return Convert.ToChar(34)
    End Function

End Class

A: I've sorted out my problem in a simple way by adding an action to each button/list item to navigate on webbrowser plugin. Works wonders! Thank you all for your time. See my code below:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim form As New Form2
    form.Show()
    form.WebBrowser1.Navigate("http://www.youtube.com/embed/VeWYQPxzNZo")
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim form As New Form2
    form.Show()
    form.WebBrowser1.Navigate("http://www.youtube.com/embed/ghqVadag1-8")
End Sub


text:
Q: jtag debugging on avr with avr-gdb and ddd I try to debug with jtag on an AVR 8 bit microcontroller.

avarice --jtag /dev/ttyUSB0 :4444
ddd lcd --debugger avr-gdb

in the session I do:

target remote localhost:4444
break main

Breakpoint 1 at 0x244: file lcd_test.cpp, line 254.

cont

Now the target stops and pc is correct:
But if I look at assembly code window, I have an offset of 0x800000 and the wrong content:
Dump of assembler code from 0x800244 to 0x800344:

0x00800244:  ldd     r1, Y+16        ; 0x10
0x00800246:  std     Z+8, r0 ; 0x08
0x00800248:  sbc     r8, r16
0x0080024a:  xch     Z, r16
0x0080024c:  .word   0x0018  ; ????
0x0080024e:  eor     r1, r0

In native avr-gdb with layoit asm everything looks fine.
Any idea how to get the correct output from assembly window in DDD in connection with avr-gdb?

A: This is an very old bug in gdb! It was reported already in 2011. The bug report contains a patch which can be applied to current gdb version 9.1 and works as expected!
Also ddd must be patched with:
diff -ur ddd-3.3.12/ddd/GDBAgent.C ddd-3.3.12_patched/ddd/GDBAgent.C
--- ddd-3.3.12/ddd/GDBAgent.C   2009-02-11 18:25:06.000000000 +0100
+++ ddd-3.3.12_patched/ddd/GDBAgent.C   2014-05-20 09:49:46.147850710 +0200
@@ -3200,7 +3200,8 @@
   {
     string end_( end );
     normalize_address(end_);
-   cmd += ' ';
+    cmd += ',';
+    cmd += ' ';
cmd += end_;
 }
 return cmd;

After the changes ddd with avr-gdb works.


text:
Q: Constructing Twilio Flow with opt in text message at the end of call We are trying to have a phone flow where the customer calls in and in the end they receive a text message asking for their name, which they respond to, and then receive a response asking another follow-up question. An example below:

*

*call

*Us: (SMS) Thanks for participating! What is your name for our website?

*Them: (SMS) John Smith

*Us: (SMS) Thanks John Smith!Would you like to be    notified when it is
online?

*Them: (SMS) Yes

*Us: (SMS)Take care!

We have structured this by having a Send & Wait widget which sends the initial message for the name and another one for the notification message.
We disabled the concurrent callers feature such that the user is kept in the same session, but this creates other issues. In order to try and solve these issues, we have written code that terminates executions for completed calls. But this code appears to be too large to run for the Twilio call handle POST link.
We were wondering what advice you might have for constructing a flow like the one described above and how we could best accomplish that considering what different options we've done.
Thanks!

A: So during the voice phone call portion, are you receiving verbal opt-in to send the party follow-up SMS Messages?
One option is to use the Studio HTTP Request Widget or Run Function Widget to start another Studio flow focused on the SMS portion via the REST API Trigger. You can send the relevant information into this new execution using the parameters key, https://support.twilio.com/hc/en-us/articles/360007778153-Trigger-a-Twilio-Studio-Flow-Execution-via-the-REST-API.
You should do a lookup on the number they call in from, to make sure it is a mobile device capable of supporting SMS to offer this option.
Not sure I understand the issue you encountered, ...this code appears to be too large to run for the Twilio call handle POST link...
Also for Studio Voice flows, always set the statusCallback URL and the Primary Handler Fails URL to the Studio Webhook URL found under the trigger widget of your flow, as called out here, to mitigate stuck executions.
Configuring Your Twilio Number for Studio


text:
Q: Is converting floating point number to integer defined behavior today have found that VS2010 do not support round function in C++ projects. Info about that function have found here. Also noticed that there also no trunc function.
So have tried some stuff and noticed some behavior that may help in such situation.

float a = 2.999;
int b = (int)a;   //gives 2

float a = -2.999;
int b = (int)a;   //gives -2

This works as truncation so I could use that, however I don't want to use code which leads to undefined behavior. So would like to ask if this is defined or undefined behavior.
EDIT: I'm not asking about C++11 as I'm using VS2008.

A: It is clearly defined in

4.9 Floating-integral conversions [conv.fpint]
1 A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion trun- cates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type. [ Note: If the destination type is bool, see 4.12. — end note ]

A: It's not undefined behavior.

C++11 §4.9 Floating-integral conversions [conv.fpint]
An rvalue of a floating point type can be converted to an rvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type. [ Note: If the destination type is bool, see 4.12. —end note ]


text:
Q: Exploding column in GeoPandas I have a shp with a column NOM_CONCAT and I can not explode it to have a unique information,
Each time, I have the same error message and I can't find solutions.
#TypeError: explode() takes 1 positional argument but 2 were given

SHAPEFILE
Code:
import pandas as pd
import numpy as np
import time
import datetime
import sys
import geopandas as gpd

gdf = gpd.read_file('RSF_Fiche_Canalisation-power_shp_ME_Position-04012021.shp')
gdf['NOM_CONCAT'] = gdf['NOM_CONCAT'].str.split(',  ')
gdf.NOM_CONCAT = gdf.NOM_CONCAT.fillna({i: [] for i in gdf.index})
gdf = gdf.explode('NOM_CONCAT')
print ("temp_complet_explode",gdf)

Current situation:

Situation I hope:

A: Per the doc:

Source: https://geopandas.org/reference.html
It's a method which applies directly on your GeoDataFrame object, therefore any extra argument you pass will be counted as a 2nd argument, hence the error you face. Please notice that GeoDataFrame.explode() is intended to:

Explode muti-part geometries into multiple single geometries.

Therefore, the following is working because all geometries are multilines, so it splits them into new rows, each hosting one of the part from the original geometry:
import geopandas as gpd
from shapely import wkt
gdf = gpd.GeoDataFrame({
    'ID': [1,2,3,4,5],
    'identifiant': [11,12,13,14,15],
    'nom_concat': ['123abc',['123def','123ghj'],['123klm','123nop'],'123qrs','123tuv'],
    'geometry': [wkt.loads(mlt) for mlt in 5*'MULTILINESTRING((3 4,10 50,20 25),(-5 -8,-10 -8,-15 -4))+'[:-1].split('+')]
})

which results in:

And calling .explode() will actually explode your geometries:

But if you do not have multiple geometries:
import geopandas as gpd
from shapely import wkt
gdf2 = gpd.GeoDataFrame({
    'ID': [1,2,3,4,5],
    'identifiant': [11,12,13,14,15],
    'nom_concat': ['123abc',['123def','123ghj'],['123klm','123nop'],'123qrs','123tuv'],
    'geometry': [wkt.loads(mlt) for pkt in 5*'MULTILINESTRING((3 4,10 50,20 25),(-5 -8,-10 -8,-15 -4))+'[:-1].split('+')]
})

calling .explode() will return your original dataframe:

What you want is probably to use pandas explode method instead, which is waiting for a column parameter:
import geopandas as gpd
from shapely import wkt
import pandas as pd

gdf2 = gpd.GeoDataFrame({
    'ID': [1,2,3,4,5],
    'identifiant': [11,12,13,14,15],
    'nom_concat': ['123abc',['123def','123ghj'],['123klm','123nop'],'123qrs','123tuv'],
    'geometry': [wkt.loads(mlt) for pkt in 5*'MULTILINESTRING((3 4,10 50,20 25),(-5 -8,-10 -8,-15 -4))+'[:-1].split('+')]
})

df = pd.DataFrame(gdf2) # convert to a panda DataFrame instance
type(df)

df.explode('nom_concat') # call pandas explode method on a column

You can finally convert it back to a GeoDataFrame:
exploded_gdf = gpd.GeoDataFrame(df.explode('nom_concat'))

Beware of the index changes after the explosion. You can obviously change it depending on your needs, e.g. with .reset_index().


text:
Q: MEF Property Export with PartCreationPolicy When I try to do this:
[Export(typeof(IMyService))]
[PartCreationPolicy(CreationPolicy.Shared)]
private MyService Service
{
    get
    {
        var service = new MyService();
        service.Configure();
        return service;
    }
}

I get a compile error: Attribute 'PartCreationPolicy' is not valid on this declaration type. It is only valid on 'class' declarations.
Is this a bug? I don't see why MEF would allow property exports but not allow one to specify the part lifetime.
Using VS2010 RC.

A: The PartCreationPolicy should go on the class, even if the export goes on the property.  The class is what corresponds to the part, and the creation policy will control whether MEF creates a new instance of the class each time an export is requested from it or not.
I am not sure whether you want to use Shared or NonShared.  You have the CreationPolicy set to Shared in your code example, but then you are creating a new instance of MyService in your property getter.  That seems to indicate you may be looking for a creation policy of NonShared.
If you do want a new service to be created each time an export is requested, you should do it via the creation policy, and not by creating a new instance in the getter.  The value of an export is not supposed to change at runtime, and in fact MEF will only call the getter once, and store the return value for when it needs to access the exported value again.  So creating a new instance in your getter can make it look like there would be multiple services created when there will actually only be one.


text:
Q: How do you assess/evaluate a messaging architecture? I'm working on a project that relies on integrating with SMS/MMS messaging aggregator companies for deploying applications to cellphones as well as performing mobile payments through SMS. Many concepts in such architectures are closely related to messaging pattersn in enterprise integration and SOA worlds. I'm currently in the process of evaluating different SMS messaging vendors and would like to know if there is some special criteria that an architect looks for in messaging architectures that should be of concern.
My approach is to use the architecture "ilities" (performance, availability, scalability, security...etc) to come up woth a scoring model for each vendor's system. However, does anyone recommend other approaches or criteria to look for when integrating with such architectures?
Thanks a bunch.

A: Full Disclosure: I worked for one of the largest SMS/MMS brokers so I might be a bit biased.
I think the things that are important to you will be hard to get reliable (i.e. non-sales spin) numbers out of the brokers.  The things we focused on at the broker I worked for were:

*

*Scalability: we chose horizontal scalability) using commodity hardware for most things

*Throughput: how many connections to each operator does the broker maintain live/fallback

*Failover methodology: is the broker connected to redundant SMSC/MMSCs on each operators that they are available for?

*Connection Methodology: is the broker connected directly via SMPP/MM4|7 or do they utilize the SS7 backbone directly, i.e. they have a point code.

*Queueing capacity: the how long can the aggregator queue messages in the event of operator outages before messages get lost?

*Direct vs. Peer connections: How many of your potential delivery MNOs are directly connected to the broker and how many are reached via peers?

*End-to-end transit time

*QOS

A: Do you really intend to evaluate the architecture, ie. the internal structure of the aggregator? If I was doing that I'd be very interested in factors such as the decomposition into components, their degree of cohesiveness and their relative decoupling. These would be important for a number of reasons, not least the future felxibility of the product.
Another place where the internal structure of the product becomes interesting is in the area of scalability and availability. If claims are made for such "ilities" I'd very much want to know "How does the architecture achieve that?"
I think your approach of taking an external view, stacking up your non-functional requirements against the products "ilities", is probably the most pragmatic approach. I'd also be interested in the "ilities" of the vendor themselves - what's the installed base, do we believe in the ongoing support of the product, what leve of product support, is it local to your timemezone etc.

A: To score `illities' correctly, you should take into consideration what the requirements are.
You could try to score all `illities' as objectively as possible, and then weight each score according to the requirements.
P.S. Shouldn't cost (€'s) be part of the equation too. For users and providers of course!


text:
Q: Why are all references to my IDispatch object not released? I'm hosting an IWebBrowser2 control in my C++ program using nothing but plain Win32 (no mfc, atl, wtl etc). On DISPID_NAVIGATECOMPLETE2 I add a custom object to be accessed from javascript running on the displayed webpage.
To add the custom object I call InvokeEx with DISPATCH_PROPERTYPUT and a DISPPARAMS structure with a pointer to my custom object.
During the call to InvokeEx the AddRef function of my custom object is called and I increment its reference counter. But the object never gets a call to its Release function, so the reference counter never decreases down to zero again.
Who is responsible for calling Release() after AddRef() has been called in InvokeEx?
EDIT: (Adding some code)
This is the code that adds my custom object to the IHTMLWindow2. custObj points to my custom object
IHTMLWindow2 *win = NULL;
GetDoc()->get_parentWindow(&win);
IDispatchEx *winEx = NULL;
win->QueryInterface(&winEx);

DISPID dispid;
HRESULT hr = winEx->GetDispID(objName, fdexNameEnsure, &dispid); //objName is "JSObject"

DISPID namedArgs[] = {DISPID_PROPERTYPUT};
DISPPARAMS params;
params.rgvarg = new VARIANT[1];
params.rgvarg[0].pdispVal = custObj;
params.rgvarg[0].vt = VT_DISPATCH;
params.rgdispidNamedArgs = namedArgs;
params.cArgs = 1;
params.cNamedArgs = 1;

hr = winEx->InvokeEx(dispid, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, &params, NULL, NULL, NULL);

This is the object that I'm adding (some private members have been left out for brevity)
class JSObject : public IDispatch {
private:
    long ref;
public:
    JSObject();

    // IUnknown
    virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv);
    virtual ULONG STDMETHODCALLTYPE AddRef();
    virtual ULONG STDMETHODCALLTYPE Release();

    // IDispatch
    virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(UINT *pctinfo);
    virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(UINT iTInfo, LCID lcid,
        ITypeInfo **ppTInfo);
    virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(REFIID riid,
        LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId);
    virtual HRESULT STDMETHODCALLTYPE Invoke(DISPID dispIdMember, REFIID riid,
        LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult,
        EXCEPINFO *pExcepInfo, UINT *puArgErr);
};

EDIT 2:
Now that it seems to be working like it should I decided to put it on github.
https://github.com/Tobbe/CppIEEmbed. Please fork and improve if you can :)

A: Well, you are assigning a property, aren't you? As long as this property exists and refers to your object, it will have a reference added.
If you want the remote object to release your reference you should assign NULL to the property, or some other object.


text:
Q: Bijections and composite functions Let $X$ be a set and let $f : X$ $\longrightarrow$ $X$ be a function. Show that $f$ is a bijection if and only if there is a function $g : X$ $\longrightarrow$ $X$ such that $f(g(x)) = g(f(x)) = x$ $\forall$ $x$$\in$$X$.
I know I should use the definitions of injective and surjective here but I do not know how to apply them. I realize to prove the iff statement I need to show both sides imply each other.

A: First assume that $f: X\longrightarrow X$ is a bijection.  Then there is an inverse function call it $f^{-1}: X \longrightarrow X$.  Then we have for each $x\in X$ that,
$$f(f^{-1}(x))=f^{-1}(f(x))=x $$
Now assume that there is some function $g:X\longrightarrow X$ such that $f(g(x))=g(f(x))=x$,  for each $x\in X$.  Then I will show $f$ is a bijection.  Let $x\in X$.  I know that $f(g(x))=x$  Therfore we have an element $g(x)\in X$ such that $f(g(x))=x$  So we have surjectivity.  Now Let $f(x)=f(y)$.  This tells me that
$$g(f(x))=g(f(y)) \Rightarrow x=y$$
Therefore we have injectivity.  Therefore, $f$ is a bijection.

A: $(\Leftarrow)$: $f(g(x)) = x$ for all $x$ leads to $f$ is surjective ($g(x)$ is a pre-image of $x$). $g(f(x)) = x$ for all $x$ leads to $f$ is injective ($f(x) = f(y)$ then $g(f(x)) = g(f(y))$, hence $x = y$).
$(\Rightarrow)$: Put $g = f^{-1}$ (note that the set $f^{-1}(x) = \{y : f(y) = x\}$ has a unique element when $f$ is bijective), then one has $f(g(x)) = x$ for all $x$. Replace $x$ by $f(x)$, one has $f(g(f(x)) = f(x)$ for all $x$. Now because $f$ is injective, $g(f(x)) = x$ for all $x$.


text:
Q: How to read in multiple files into pandas? I have a folder that has hundreds or files which contain comma separated data, however, the files themselves have no file extensions (i.e., EPI or DXPX; NOT EPI.csv or DXPX.csv).
I am trying to create a loop that reads in only certain files that I need (between 15-20 files). I do not want to concat or append the dfs. I merely want to read each df into memory and be able to call the df by name.
Even though there is no extension, I can read the file in as .csv
YRD = pd.read_csv('YRD', low_memory=False)

My expected result from the loop below is two dfs: one labeled YRD and another labeled HOUSE. However, I only get one df named df_raw and it is only the final file in the list. Sorry if this is a silly question, but I cannot figure out what I am missing.
df_list = ['YRD','HOUSE']

for raw_df in df_list:
    raw_df = pd.read_csv(raw_df, low_memory=False)

A: This is because you reassign the value raw_df every time you encounter a new file...
You should create new variables, not reuse the old ones:
mydfs=[]
for raw_df in df_list:
    mydfs.append( pd.read_csv(raw_df, low_memory=False))

or you can put them into a dictionnary:
mydfs={}
for raw_df in df_list:
    mydfs[raw_df]= pd.read_csv(raw_df, low_memory=False)


text:
Q: I am attempting to group-by ID and sort by date within each group to find the time between events Here is an example data frame to recreate the data I am working with:
df = pd.DataFrame( {
'id': [1,1,1,1,2,2,2,3,3,4,4,4],
'date': ['2017-01-09', '2017-01-19', '2017-01-20', '2017-01-21', '2017-01-26', '2017-01-30', '2017-02-07', '2017-02-10', '2017-02-13', '2017-02-15', '2017-02-20', '2017-02-21'],
'event': ['A','A','B','A','A','A','B','A','B','A','A','B']
} )

What I am attempting to do is group-by 'id', however, using the grouby method is not actually grouping records by id:
df = df.groupby(['id'])
Furthermore, I would like to sort by date within each group and then create a new column for the number of days between event 'B' and the most recent event 'A' prior to event 'B' within each group.
Any help with this would be greatly appreciated!
Edit - I would expect the output to look something like this example: http://www.datasciencemadesimple.com/wp-content/uploads/2017/11/Group-a-dataframe-in-python-pandas-%E2%80%93-group-by-function-in-pandas-4.png

A: I have a solution below, but I think there should be an efficient way to solve it.
df['date'] = pd.to_datetime(df['date'])

df.groupby("id").apply(
    lambda x: x.loc[x['event']=='B', 'date'] - x.loc[(x['event']!='B')&(x['date'] <= x.loc[x['event']=='B', 'date'].values[0]), 'date'].max()
).reset_index(name='date_gap').drop(columns=['level_1'])


text:
Q: Access-Control-Allow-Origin problems on the same domain How is it possible that when I try to make an XMLHTTPRequest from a javascript file to a web service located on the very same domain, I get:
Origin http://mydomain.com is not allowed by Access-Control-Allow-Origin ???
If I change mydomain.com to localhost, I no longer have problems, but I would like to keep it  as mydomain.com
What do I have to edit, and why in the first place, since it's the same domain?

A: It probably is because of the missing www. If you test with yourdomain.com and your site is at www.yourdomain.com it is concidered cross-domain and cross-domain calls are not allowed by default.

A: 1)  look in your request/response headers. Is the server returning a weird access-control-allow-origin header?
2) It's not just the domain, it's also the protocol (http vs https vs ftp etc), the port (if you have a :8080 or something like that), and potentially the part after the .com/


text:
Q: Natural Transformation: Direct Products I have result that tells me $$\displaystyle \varphi : \text{Hom}_R \bigg(A, \prod_{i \in I} B_i \bigg) \to \prod_{i \in I} \text{Hom}_R(A, B_i)$$ is a $Z(R)$-isomorphism. The next result tells me that it is natural (which is the part I'm not understanding):

The isomorphism $\varphi$ is natural: if $(C_j)_{j \in J}$ is a family of left $R$-modules and, for each $i \in I$, there exist $j \in J$ and an $R$-map $\sigma_{ij} : B_i \to C_j$, then there is a commutative diagram
  $\require{AMScd}$
  \begin{CD}
    \text{Hom}_R \bigg(A, \prod_{i \in I} B_i\bigg) @>\varphi>> \prod_{i \in I} \text{Hom}_R(A, B_i)\\
    @V \sigma_* V V@VV \widetilde \sigma V\\
    \text{Hom}_R \bigg( A, \prod_{j \in J} C_j \bigg) @>>\varphi> \prod_{j \in J} \text{Hom}_R(A, C_j)
    \end{CD}
  where $\displaystyle \sigma : \prod_{i \in I} B_i \to \prod_{j \in J} C_j$ is given by $(b_i) \mapsto (\sigma_{ij}b_i)$, and $\sigma_*$ is the induced map, and $\widetilde \sigma : (g_i) \mapsto (\sigma_{ij}g_i)$.

My definition for natural transformation is:

Let $S, T : \mathcal A \to \mathcal B$ be covariant functors. A natural transformation $\tau : S \to T$ is a one-parameter family of morphisms in $\mathcal B$, $\tau = (\tau_A : SA \to TA)_{A \in \text{Obj(A)}}$ making the following diagram commute for all $f : A \to A'$ in $\mathcal A$:
  $\require{AMScd}$
  \begin{CD}
    SA @>\tau_A>> TA\\
    @V S_f V V @VV T_f V\\
    SA' @>>\tau_{A'}> TA'
    \end{CD}

I'm having trouble figuring out what are $S, T$? Or even $\mathcal A, \mathcal B$?
For instance, am I looking at $\mathcal A$ is a category where the objects are families of left $R$-modules $(B_i)_{i \in I}$? and then $S$ is a functor which takes this category to the category of sets, defined by $$S\big( (B_i)_{i \in I}\big) = \text{Hom}_R\bigg(A, \prod_{i \in I} B_i \bigg)?$$
Or is $\mathcal A$ the category of left $R$-modules where we just look as products as a special case? My concern with this is that maps between products like $\sigma : \prod B_i \to \prod C_j$ are defined in a special way, so where is this taken into account?
To conclude this post, I'm hoping someone can help me see the result in terms of the definition I've been given for natural transformations. (As for showing that the diagram was commutative, that was fairly straight forward.)
Source: "Introduction to Homological Algebra", Joseph Rotman, Page 54, Theorem 2.30.

A: Ok, I believe that the book try to do the following thing (although avoiding a lot of details).
As a general case for every category $\mathbf C$ you can build a category $\text{Fam}(\mathbf C)$ whose:

*

*objects are families of objects in $\mathbf C$, that is stuff like $(c_i)_{i \in I}$ where each $c_i$ is in $\mathbf C$

*morphisms from $(c_i)_{i \in I}$ to $(d_j)_{j \in J}$ are pairs $\langle f, \sigma \rangle$ where $f \colon J \to I$ and
$\sigma=\langle\sigma_j \colon c_{f(j)} \to d_j\rangle_{j \in J}$

*composition of pair of morphisms
$$(c_i)_{i \in I} \stackrel{\langle f, \sigma\rangle}{\longrightarrow}(d_j)_{j \in J} \stackrel{\langle g,\tau
\rangle}{\longrightarrow}(e_l)_{l \in L}$$
is defined to be the morphism
$$(c_i)_{i \in I} \stackrel{\langle h, \psi\rangle}{\longrightarrow} (e_l)_{l \in L}$$
where $h=f \circ g$ and $\psi_{l}=\tau_l \circ \sigma_{g(l)}\colon c_{f(g(l))} \to e_l$ for every $l \in L$.
The identities are the obvious ones.

If $\mathbf C$ is a category with products we have a functor
$$\prod \colon \text{Fam}(\mathbf C) \to \mathbf C$$
that associates to every family $(c_i)_{i \in I}$ (a choice of) its product $\prod_I c_i$.
The arrow part of this functor is not as such straightforward to describe but you can try as an exercise to write it out.
Now back to your problem. As a start we know that for every ring $R$ the category $\mathbf{Mod}_R$ of $R$ modules and $R$-linear maps
has products hence for the observation above you have a functor
$$\prod \colon \mathbf{Fam}(\mathbf {Mod}_R) \to \mathbf{Mod}_R$$
On the other hand for every $R$-module $A$ you also have a functor
$$y_A \colon \textbf{Mod}_R \to \textbf{Mod}_{Z(R)}$$
that sends every module $B$ into the $Z(R)$-module $\text{Hom}_R(A,B)$.
This functor extend naturally to a functor
$$\bar y_A \colon \textbf{Fam}(\textbf{Mod}_R) \to \textbf{Fam}(\textbf{Mod}_{Z(R)})$$
that sends every family $(B_i)_{i \in I}$ of $R$-modules into the family of $Z(R)$-module
$(\text{Hom}_{Z(R)}(A,B_i))_{i \in I}$.
Also the category $\textbf{Mod}_{Z(R)}$ admits its own product functor $\prod$.
From these data you obtain the following functors
$$\mathbf{Fam}(\mathbf{Mod}_R) \stackrel{\prod}{\longrightarrow} \textbf{Mod}_R \stackrel{y_A}{\longrightarrow} \textbf{Mod}_{Z(R)}$$
and
$$\mathbf{Fam}(\mathbf{Mod}_R) \stackrel{\bar y_A}{\longrightarrow} \textbf{Fam}(\textbf{Mod}_{Z(R)})
\stackrel{\prod}{\longrightarrow} \textbf{Mod}_{Z(R)}$$
The first functor associates to each family $(B_i)_{i \in I}$ of $R$-modules the $Z(R)$-module $\text{Hom}_R(A,\prod B_i)$
the second one the module $\prod \text{Hom}_R(A,B_i)$.
The statement of the theorem is saying the family of morphisms $\varphi$ is a natural transformation for these two functors.


text:
Q: Can additivity of the Euler characteristic be interpreted in terms of the Poincaré–Hopf theorem? Whenever there is a long exact sequence in homology induced by a short exact sequence of chain complexes one finds that the corresponding Euler characteristics are additive. For example, if $Y \subset X$ is a closed submanifold of a closed manifold $X$ (dim$X=n$, codim$Y=k$) with orientable normal bundle then the Leray sequence is the exact sequence
\begin{equation*}
\cdots \to H_i(X-Y) \to H_i(X) \to H_{i-k}(Y) \to H_{i-1}(X-Y) \to \cdots
\end{equation*}
Thus, Euler characteristics of these spaces satisfy $\chi(X) = \chi(X-Y)+\chi(Y)$. How is this interpreted in terms of the Poincaré–Hopf theorem that says the Euler characteristic of a closed manifold $M$ is
\begin{equation*}
\sum_a \mbox{index}_{x_i}(v) = \chi(M)
\end{equation*}
where the sum is over isolated zeroes of a vector field $v \in TM$? Can the intuitive argument that the sum of the right hand side decomposes into two parts (on and off $Y$) simply be used to prove additivity of the Euler characteristic in this case? It seems too simple to be true...


text:
Q: Initialising a unique pointer in a loop (to be used in a hash table) For the past several years I have been doing number crunching in Python using dictionaries. I am recapping C after several years, and I am trying to mimic python dictionary functionality using a hash table. My hash table works fine, but I'm struggling with adding new entry's programmatically in a loop. Here is my code:
#define TABLE_SIZE 16

typedef struct item{
    char key[64];
    int value;
    int list[5];
    struct item *next;
} item;

// Create hash table array
item *hash_table[TABLE_SIZE];

void init_hash_table(){
    for (int i = 0; i < TABLE_SIZE; i++)
        hash_table[i] = NULL;
}

int hash(char *key){
    unsigned long H = 5381;
    int c;
    while ((c = *key++))
        H = ((H << 5) + H) + c;
    H = H % TABLE_SIZE;
    int hash = (int)H;
    return hash;
}

int insert_item(item *pItem){
    if (pItem == NULL){
        printf("Invalid item");
        return -1;
    }
    else {
        int index = hash(pItem->key);
        pItem->next = hash_table[index];
        hash_table[index] = pItem;
        return index;
    }
}

void print_table(){
    printf("\n--- Table Start ---\n");
    for (int i = 0; i < TABLE_SIZE; i++){
        if (hash_table[i] == NULL)
            printf("\t %d \t --- \t\n", i);
        else {
            item *tmp = hash_table[i];
            printf("\t %d ", i);
            while(tmp != NULL){
                printf("\t --- \t %s", tmp->key);
                tmp = tmp->next;
            }
            printf("\n");
        }
    }
    printf("--- Table End ---");
}

int main(){

    // Initialise hash table
    init_hash_table();
    char letters[] = "ABCDEFGHIJ";

    // Insert data
    for (int i = 0; i < 10; i++){
        item itemN = {.key = letters[i]};
        printf("%s ", itemN.key);
        printf("%p\n", &itemN);
        insert_item(&itemN);
    }

    // Print the table
    print_table();

    return 0;
}

Essentially I want 10 entries added to the hash table, each unique with the key as a different letter (A to J). The problem is each itemN in main has the same address in memory, so the same pointer is being overwritten each time. Hence my output looks like:
A 0061FEB0
B 0061FEB0
C 0061FEB0
D 0061FEB0
E 0061FEB0
F 0061FEB0
G 0061FEB0
H 0061FEB0
I 0061FEB0
J 0061FEB0

--- Table Start ---
         0       ---
         1       ---
         2       ---
         3       ---     J
         4       ---
         5       ---
         6       ---     J
         7       ---     J
         8       ---     J
         9       ---     J
         10      ---     J
         11      ---     J
         12      ---     J
         13      ---     J
         14      ---     J
         15      ---
--- Table End ---

The question is, how can I generate a new item variable in the loop with a unique address? This seems like pretty standard functionality to implement, since we cannot always initialise variables manually. Sorry if I am missing something obvious!
Thanks

A: Code keeps inserting the same item.  &itemN is the address of the local object itemsN.  That item goes out of scope and it no longer valid after the loop { ...}
for (int i = 0; i < 10; i++){
  item itemN = {.key = letters[i]};
  ...
  insert_item(&itemN);
}
print_table();  // no longer valid for code to use `&itemN`.

.key = letters[i] is also invalid as that is attempting to assign  char to a char *.  That implies warnings are not fully enabled.  Save time, enable them all.

Perhaps insert 10 different items.
item items[10] = { 0 };
for (int i = 0; i < 10; i++){
    items[i].key[0] = letters[i];
    printf("%s ", items[i].key);
    printf("%p\n", &item[i]);
    insert_item(&items[i]);
}

GTG

A: The basic problem is that your hash table does not actually store items, it stores pointers, and your insert_item function takes a pointer and inserts that pointer directly in the hash table, which means it will only be valid as long as that object is alive.  When the lifetime of the object ends, the pointer becomes dangling and your hash table becomes invalid, so pretty much anything after that is undefined behavior.
Whenever you deal with pointers in C (which is pretty much all the time), you need to be aware of the lifetime of the pointed at objects and make sure that the pointer will not be in use after the lifetime ends.  In your case, you are defining your item as a local (auto) within a loop in main, so the lifetime will end as soon as that iteration of the loop ends.  So by the time you go to put a second item in the hash table, you have a dangling pointer in the table, and all bets are off.
The usual way of dealing with this is to have your hash table "have ownership" of the objects in the table, and have your insert_item make a copy of the item (using malloc to allocate some memory for the copy):
int insert_item(item *pItem){
    if (pItem == NULL){
        printf("Invalid item");
        return -1;
    }
    else {
        int index = hash(pItem->key);
        item *copy = malloc(sizeof(item));
        if (copy == NULL) {
            printf("Ran out of memory\n");
            return -1; }
        *copy = *pItem;
        copy->next = hash_table[index];
        hash_table[index] = copy;
        return index;
    }
}

This way, all the item objects actually in the hash table will have an extended lifetime -- they will live until you explicitly free them.  You want to do that when you are done with the hash table itself, so you might have a destroy_table function to do that.


text:
Q: Dart null vs Null As far as a know, checking if a object is null or Null should be the same thing on Dart.
Something like:
print(bar == null);
print(bar is Null);

should print the same value. But, in a flutter app using firebase I got the following behaviour:
  print(snapshot.data['appearance']['details'].runtimeType); // Null
  print(snapshot.data['appearance']['details'].runtimeType == null); // false
  print(snapshot.data['appearance']['details'].runtimeType == Null); // true
  print(snapshot.data['appearance']['details'].runtimeType is Null); // false

the field value is null on firebase. Why is it behaving like this?

A: null is a value. Null is a type.
.runtimeType returns a Type.  It cannot return a null value (that would mean the object has no type).  null.runtimeType returns Null; that is, the null object has a type named Null.
As for why .runtimeType is Null is false, see: What is the difference between 'is' and '==' in Dart?