问:
what will the equivalent statement of line in main?
```<code>class B{
    float floatVar;
    public:
    B(float a):floatVar(0.0){
        floatVar = a;
    }

    operator int(){   // Consider this as line A
        return floatVar;
    }
};

int main()
{
    B floatObj(5.5);
    cout << floatObj;  // Consider this as line B

    return 0;
}
</code>```

when i cout while overloading int() it displays 5 and when i replace int() with float() in line A , program displays 5.5.
I want to know how it is automatically calling the int() typecaster or the float() in cout?

答:
There is no synthesis of default printing function or alike in C++, thus defining a class with some fields doesn't print them by default if you try to print an objet of the class.

As you didn't defined any overloaded operator << to print to some ostream (like cout) the compiler found a way to print it through the defined conversion to int.

Body:
class B{
    float floatVar;
    public:
    B(float a):floatVar(0.0){
        floatVar = a;
    }

    operator int(){   // Consider this as line A
        return floatVar;
    }
};

int main()
{
    B floatObj(5.5);
    cout << floatObj;  // Consider this as line B

    return 0;
}

when i cout while overloading int() it displays 5 and when i replace int() with float() in line A , program displays 5.5.
I want to know how it is automatically calling the int() typecaster or the float() in cout?


来源: stackexchange

问:
ValueChange() event doesn't work on mobile
I am writing a calculator

The problem: i need to add $('.plan-select').val() into $('output').text() on button click. Events change() and input() didn't help catch the change of it in handler, so i found ValueChange() event here https://developer.mozilla.org/ru/docs/Web/Events.

I need <output> to instant refresh while click, it works fine with ValueChange() on PC but doesn`t work correctly on mobile.

// Button
$('.plan-select').on('click', function() {
  var value = $(this).data("plan");
  $(".planlist").val(parseInt(value)).change();
});

// Handler. it collects checked checkboxes and <select> statement
window.addEventListener('DOMContentLoaded', function() {
  var form = document.querySelector('form'),
    elem = form.querySelectorAll('[name^="itemtype"]'),
    value = form.querySelectorAll('[name^="labelname"]'),
    output = document.querySelector('output');

  function total() {
    output.innerHTML = [].reduce.call(elem, function(sum, el) {
      var n = (+el.value || 0) * (el.checked || el.tagName == "SELECT" || el.type == "text");
      return sum + n
    }, 0);
  }

  form.addEventListener('ValueChange', total);
  form.addEventListener('change', total);
  form.addEventListener('input', total);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Buttons -->
Option1
Option2
Option3

<!-- Form -->
<div id="pricing">
  <form id="calc">
    <select name="itemtype5" class="planlist" id="l">
      <option class="no-display" value="0">Hidden</option>
      <option value="35000">Option1</option>
      <option value="45000">Option2</option>
      <option value="65000">Option3</option>
    </select>

    <input type="checkbox" class="checkbox_check" name="itemtype1" id="d" data-genrename="Genre1" value="3000" data-time="10">
    <label>Genre1</label>

    <input type="checkbox" class="checkbox_check" name="itemtype2" id="e" data-genrename="Genre2" value="4000" data-time="15">
    <label>Genre</label>

    <input type="checkbox" class="checkbox_check" name="itemtype3" id="f" data-genrename="Genre3" value="10000" data-time="24">
    <label>Genre3</label>

    <input type="checkbox" class="checkbox_check" name="itemtype4" id="g" data-genrename="Genre4" value="3000" data-time="10">
    <label>Genre4</label>

    <label>Total:</label>
    <output name="o" class="total" for="a b c d e f g h l">35000</output>

  </form>
</div></code>```

Button:
https://elevate.kz/#plans

Handler:
https://elevate.kz/#pricing

Thank you.

答:
You had wrong quotes  around genre3

Try to use jQuery all the way:

function total() {
  let sum = 0;
  $("form :input").each(function() {
    var n = (+this.value || 0) * (this.checked || this.tagName == "SELECT" || this.type == "text");
    sum += n
  })
  $(".total").text(sum);
}

$(function() {
  // Button
  $('.plan-select').on('click', function() {
    var value = $(this).data("plan");
    $(".planlist").val(parseInt(value)).change();
  });

  $("#calc").on("change", "select[name^=itemtype]", total)
  $("select[name^=itemtype]").trigger("change");
  $("#calc").on("touchstart click", "input[type=checkbox][name^=itemtype]", total);
  $("#calc").on("input", "input[type=text][name^=itemtype]", total); // if exists

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Buttons -->
Option1
Option2
Option3

<!-- Form -->
<div id="pricing">
  <form id="calc">
    <select name="itemtype5" class="planlist" id="l">
      <option class="no-display" value="0">Сайт-визитка</option>
      <option value="35000">Option1</option>
      <option value="45000">Option2</option>
      <option value="65000">Option3</option>
    </select>

    <input type="checkbox" class="checkbox_check" name="itemtype1" id="d" data-genrename="Genre1" value="3000" data-time="10" />
    <label>Genre1</label>

    <input type="checkbox" class="checkbox_check" name="itemtype2" id="e" data-genrename="Genre2" value="4000" data-time="15" />
    <label>Genre</label>

    <input type="checkbox" class="checkbox_check" name="itemtype3" id="f" data-genrename="Genre3" value="10000" data-time="24" />
    <label>Genre3</label>

    <input type="checkbox" class="checkbox_check" name="itemtype4" id="g" data-genrename="Genre4" value="3000" data-time="10" />
    <label>Genre4</label>

    <label>Total:</label>
    <output name="o" class="total" for="a b c d e f g h l">35000</output>

  </form>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I am writing a calculator

The problem: i need to add $('.plan-select').val() into $('output').text() on button click. Events change() and input() didn't help catch the change of it in handler, so i found ValueChange() event here https://developer.mozilla.org/ru/docs/Web/Events.

I need <output> to instant refresh while click, it works fine with ValueChange() on PC but doesn`t work correctly on mobile.

// Button
$('.plan-select').on('click', function() {
  var value = $(this).data("plan");
  $(".planlist").val(parseInt(value)).change();
});

// Handler. it collects checked checkboxes and <select> statement
window.addEventListener('DOMContentLoaded', function() {
  var form = document.querySelector('form'),
    elem = form.querySelectorAll('[name^="itemtype"]'),
    value = form.querySelectorAll('[name^="labelname"]'),
    output = document.querySelector('output');

  function total() {
    output.innerHTML = [].reduce.call(elem, function(sum, el) {
      var n = (+el.value || 0) * (el.checked || el.tagName == "SELECT" || el.type == "text");
      return sum + n
    }, 0);
  }

  form.addEventListener('ValueChange', total);
  form.addEventListener('change', total);
  form.addEventListener('input', total);

});

Option1
Option2
Option3

  <form id="calc">
    <select name="itemtype5" class="planlist" id="l">
      <option class="no-display" value="0">Hidden</option>
      <option value="35000">Option1</option>
      <option value="45000">Option2</option>
      <option value="65000">Option3</option>
    </select>

    <input type="checkbox" class="checkbox_check" name="itemtype1" id="d" data-genrename="Genre1" value="3000" data-time="10">
    Genre1

    <input type="checkbox" class="checkbox_check" name="itemtype2" id="e" data-genrename="Genre2" value="4000" data-time="15">
    Genre

    <input type="checkbox" class="checkbox_check" name="itemtype3" id="f" data-genrename="Genre3" value="10000" data-time="24">
    Genre3

    <input type="checkbox" class="checkbox_check" name="itemtype4" id="g" data-genrename="Genre4" value="3000" data-time="10">
    Genre4

    Total:
    <output name="o" class="total" for="a b c d e f g h l">35000</output>

  </form>

Button:
https://elevate.kz/#plans

Handler:
https://elevate.kz/#pricing

Thank you.

Body:
You had wrong quotes  around genre3

Try to use jQuery all the way:

function total() {
  let sum = 0;
  $("form :input").each(function() {
    var n = (+this.value || 0) * (this.checked || this.tagName == "SELECT" || this.type == "text");
    sum += n
  })
  $(".total").text(sum);
}

$(function() {
  // Button
  $('.plan-select').on('click', function() {
    var value = $(this).data("plan");
    $(".planlist").val(parseInt(value)).change();
  });

  $("#calc").on("change", "select[name^=itemtype]", total)
  $("select[name^=itemtype]").trigger("change");
  $("#calc").on("touchstart click", "input[type=checkbox][name^=itemtype]", total);
  $("#calc").on("input", "input[type=text][name^=itemtype]", total); // if exists

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Buttons -->
<a href="#pricing" class="plan-select" data-plan="35000">Option1</a>
<a href="#pricing" class="plan-select" data-plan="45000">Option2</a>
<a href="#pricing" class="plan-select" data-plan="65000">Option3</a>

<!-- Form -->
<div id="pricing">
  <form id="calc">
    <select name="itemtype5" class="planlist" id="l">
      <option class="no-display" value="0">Сайт-визитка</option>
      <option value="35000">Option1</option>
      <option value="45000">Option2</option>
      <option value="65000">Option3</option>
    </select>

    <input type="checkbox" class="checkbox_check" name="itemtype1" id="d" data-genrename="Genre1" value="3000" data-time="10" />
    <label>Genre1</label>

    <input type="checkbox" class="checkbox_check" name="itemtype2" id="e" data-genrename="Genre2" value="4000" data-time="15" />
    <label>Genre</label>

    <input type="checkbox" class="checkbox_check" name="itemtype3" id="f" data-genrename="Genre3" value="10000" data-time="24" />
    <label>Genre3</label>

    <input type="checkbox" class="checkbox_check" name="itemtype4" id="g" data-genrename="Genre4" value="3000" data-time="10" />
    <label>Genre4</label>

    <label>Total:</label>
    <output name="o" class="total" for="a b c d e f g h l">35000</output>

  </form>
</div>


问:
Python Error: OrderedDict Object Has No Attribute OrderedDict Root
As a new python programmer, I'm practicing the LRU Cache Problem from Leetcode
Link: https://leetcode.com/problems/lru-cache/

Problem Description:

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

Here is the solution provided by Leetcode:

from collections import OrderedDict
class LRUCache(OrderedDict):

    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.capacity = capacity

    def get(self, key):
        """
        :type key: int
        :rtype: int
        """
        if key not in self:
            return - 1

        self.move_to_end(key)
        return self[key]

    def put(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: void
        """
        if key in self:
            self.move_to_end(key)
        self[key] = value
        if len(self) > self.capacity:
            self.popitem(last = False)
```

However I came across the following error when submitting the code:

Line 29: AttributeError: 'LRUCache' object has no attribute '_OrderedDict__root'

Could anyone give me some hints why I got that error? Really appreciate it?

答:
you should choose python3 as compile language.
OrderedDict has some new property in python3</p>

Body:
As a new python programmer, I'm practicing the LRU Cache Problem from Leetcode
Link: https://leetcode.com/problems/lru-cache/

Problem Description:

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

Here is the solution provided by Leetcode:

from collections import OrderedDict
class LRUCache(OrderedDict):

    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.capacity = capacity

    def get(self, key):
        """
        :type key: int
        :rtype: int
        """
        if key not in self:
            return - 1

        self.move_to_end(key)
        return self[key]

    def put(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: void
        """
        if key in self:
            self.move_to_end(key)
        self[key] = value
        if len(self) > self.capacity:
            self.popitem(last = False)

However I came across the following error when submitting the code:

Line 29: AttributeError: 'LRUCache' object has no attribute '_OrderedDict__root'

Could anyone give me some hints why I got that error? Really appreciate it?


问:
Why can't I push change to this up-to-date Git subtree?
I have a git subtree module called "gempak-tables" in subdirectory "gempak/tables":

```<code>$ git config -l | grep -i gempak
remote.gempak-tables.url=git@github.com:Unidata/GEMPAK-Tables.git
remote.gempak-tables.fetch=+refs/heads/*:refs/remotes/gempak-tables/*
$
</code>```

I can't push changes to the subtree module to GitHub, however:

```<code>$ git subtree push --prefix=gempak/tables gempak-tables master
git push using:  gempak-tables master
X11 forwarding request failed on channel 0
To git@github.com:Unidata/GEMPAK-Tables.git
 ! [rejected]        89d8f94d010e6677f146608674cf7408eecb4a61 -> master (non-fast-forward)
error: failed to push some refs to 'git@github.com:Unidata/GEMPAK-Tables.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Merge the remote changes (e.g. 'git pull')
hint: before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
$
</code>```

even though the subtree module appears to be up-to-date:

```<code>$ git subtree pull --prefix=gempak/tables gempak-tables master
X11 forwarding request failed on channel 0
From github.com:Unidata/GEMPAK-Tables
 * branch            master     -> FETCH_HEAD
Already up-to-date.
$
</code>```

My git(1) version:

```<code>$ git --version
git version 1.8.3.1
</code>```

I'm a subtree novice. Please help.

答:
The error you receive says that your git branch is behind. The git branch which contains the up to date subtree is not up to date.

Do a git pull not a git subtree pull

Body:
I have a git subtree module called "gempak-tables" in subdirectory "gempak/tables":

$ git config -l | grep -i gempak
remote.gempak-tables.url=git@github.com:Unidata/GEMPAK-Tables.git
remote.gempak-tables.fetch=+refs/heads/*:refs/remotes/gempak-tables/*
$

I can't push changes to the subtree module to GitHub, however:

$ git subtree push --prefix=gempak/tables gempak-tables master
git push using:  gempak-tables master
X11 forwarding request failed on channel 0
To git@github.com:Unidata/GEMPAK-Tables.git
 ! [rejected]        89d8f94d010e6677f146608674cf7408eecb4a61 -> master (non-fast-forward)
error: failed to push some refs to 'git@github.com:Unidata/GEMPAK-Tables.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Merge the remote changes (e.g. 'git pull')
hint: before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
$

even though the subtree module appears to be up-to-date:

$ git subtree pull --prefix=gempak/tables gempak-tables master
X11 forwarding request failed on channel 0
From github.com:Unidata/GEMPAK-Tables
 * branch            master     -> FETCH_HEAD
Already up-to-date.
$

My git(1) version:

$ git --version
git version 1.8.3.1

I'm a subtree novice. Please help.


问:
How to close a while loop for an ArrayList that is collecting user input
The question sounds simple enough but I have spent 2 hours looking for the answer and I can't seem to find it. I am trying to make a program that populates an array list with user input (of integers) and then closing it when the number 0 is typed.

So far I have:

```<code>import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.*;
/**
 * Write a description of class ArrayList2 here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */

public class Numbers

{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);

        System.out.println ("Enter a list of integers (Enter 0 when done): ");

        ArrayList<Integer> fullArray = new ArrayList<Integer>();

        while (keyboard.hasNextInt())
        {
            fullArray.add(keyboard.nextInt());
            System.out.println (fullArray);

        }

        System.out.println (fullArray);
    }
}
</code>```

My issue isn't getting the user input, but closing the arraylist when 0 is typed. I know that hasNextInt returns true as long as their's another int but 0 is also an int so it will not close the arraylist. I have tried simply saying if(keyboard.nextInt == 0), but that breaks my code and only adds every other number to my arraylist. If anyone can help me it would be much appreciated. thanks.

答:
Instead of adding a new nextInt() which will make you skip every other value, simply store the nextInt you already used into a variable (in this case nextValue), check to see if it is 0, break from the loop if it is, otherwise you add it to the List.

Here is the working version below:

```<code>public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println ("Enter a list of integers (Enter 0 when done): ");
    ArrayList<Integer> fullArray = new ArrayList<>();

    while (keyboard.hasNextInt()) {
        int nextValue = keyboard.nextInt();
        if (nextValue == 0) {
            break;
        }
        fullArray.add(nextValue);
        System.out.println (fullArray);
    }
}
</code>```

Body:
The question sounds simple enough but I have spent 2 hours looking for the answer and I can't seem to find it. I am trying to make a program that populates an array list with user input (of integers) and then closing it when the number 0 is typed.

So far I have:

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.*;
/**
 * Write a description of class ArrayList2 here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */

public class Numbers

{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);

        System.out.println ("Enter a list of integers (Enter 0 when done): ");

        ArrayList<Integer> fullArray = new ArrayList<Integer>();

        while (keyboard.hasNextInt())
        {
            fullArray.add(keyboard.nextInt());
            System.out.println (fullArray);

        }

        System.out.println (fullArray);
    }
}

My issue isn't getting the user input, but closing the arraylist when 0 is typed. I know that hasNextInt returns true as long as their's another int but 0 is also an int so it will not close the arraylist. I have tried simply saying if(keyboard.nextInt == 0), but that breaks my code and only adds every other number to my arraylist. If anyone can help me it would be much appreciated. thanks.

Body:
Instead of adding a new nextInt() which will make you skip every other value, simply store the nextInt you already used into a variable (in this case nextValue), check to see if it is 0, break from the loop if it is, otherwise you add it to the List.

Here is the working version below:

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println ("Enter a list of integers (Enter 0 when done): ");
    ArrayList<Integer> fullArray = new ArrayList<>();

    while (keyboard.hasNextInt()) {
        int nextValue = keyboard.nextInt();
        if (nextValue == 0) {
            break;
        }
        fullArray.add(nextValue);
        System.out.println (fullArray);
    }
}


问:
Python - Postgres query using sqlalchemy returns "Empty Dataframe"
I try to query some data from a postgres database and add the results into an excel with the below Python code (I am connecting to the server through ssh tunnel and connecting to database using sqlalchemy):

```<code>from sshtunnel import SSHTunnelForwarder
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
import pandas as pd
from pandas import DataFrame
import xlsxwriter
import openpyxl

with SSHTunnelForwarder(
    ('<server_ip>', 22),
    ssh_username="<server_username>",
    ssh_private_key='<private_key_path>',
    remote_bind_address=('localhost', 5432)) as server:
    server.start()
    print "server connected"

    #connect to DB
    local_port = str(server.local_bind_port)
    engine = create_engine('postgresql://<db_username>:<db_password>:' + local_port +'/<db_name>')
    Session = sessionmaker(bind=engine)
    s = Session()
    print 'Database session created'

    not_empty_query = False #flag empty queries
    arg_query = "SELECT * from portalpage where id not in (select entityid from sharepermissions where entitytype='PortalPage')"
    query = s.execute(arg_query)
    print(query)
    for row in query: #check if the query is empty
        if (row[0] > 0):
            not_empty_query = True
            break
    if not_empty_query == True: #if the query isn not empty add response into excel
        df = pd.DataFrame(pd.np.empty((0, 8)))
        df = DataFrame(query.fetchall())
        print(df)
        df.columns = query.keys()
        df.to_excel("out.xlsx", engine="openpyxl", sheet_name="Worksheet_Name")

s.close()
</code>```

It works for the most of the queries that I tried to execute, however with the above query it returns the below error:

```<code>ValueError: Length mismatch: Expected axis has 0 elements, new values have 8 elements
</code>```

While I was troubleshooting I printed the the df parameter and I got an "Empty Dataframe".
However when I run the same query in my database directly I get results.

I also noticed that in the response, on my database, some columns are empty (not sure if it makes any difference).

Please also find a print screen of the code execution.

The above will work if I remove the below piece of code:

```<code>for row in query: #check if the query is empty
    if (row[0] > 0):
        not_empty_query = True
        break
if not_empty_query == True:
</code>```

However, if I remove this 'for loop' then for other queries (mainly for queries which return empty results) I get the same error.
Please find an example below.

Ay ideas?

答:
Try to create an empty data frame first. </p>

```<code>if not_empty_query == True: #if the query isn not empty add response into excel
        df = pd.DataFrame(pd.np.empty((0, 8)))
        df = DataFrame(query.fetchall())
        print(df)
        df.columns = query.keys()
        df.to_excel("out.xlsx", engine="openpyxl", sheet_name="Worksheet_Name")
</code>```

Body:
I try to query some data from a postgres database and add the results into an excel with the below Python code (I am connecting to the server through ssh tunnel and connecting to database using sqlalchemy):

from sshtunnel import SSHTunnelForwarder
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
import pandas as pd
from pandas import DataFrame
import xlsxwriter
import openpyxl

with SSHTunnelForwarder(
    ('<server_ip>', 22),
    ssh_username="<server_username>",
    ssh_private_key='<private_key_path>',
    remote_bind_address=('localhost', 5432)) as server:
    server.start()
    print "server connected"

    #connect to DB
    local_port = str(server.local_bind_port)
    engine = create_engine('postgresql://<db_username>:<db_password>:' + local_port +'/<db_name>')
    Session = sessionmaker(bind=engine)
    s = Session()
    print 'Database session created'

    not_empty_query = False #flag empty queries
    arg_query = "SELECT * from portalpage where id not in (select entityid from sharepermissions where entitytype='PortalPage')"
    query = s.execute(arg_query)
    print(query)
    for row in query: #check if the query is empty
        if (row[0] > 0):
            not_empty_query = True
            break
    if not_empty_query == True: #if the query isn not empty add response into excel
        df = pd.DataFrame(pd.np.empty((0, 8)))
        df = DataFrame(query.fetchall())
        print(df)
        df.columns = query.keys()
        df.to_excel("out.xlsx", engine="openpyxl", sheet_name="Worksheet_Name")

s.close()

It works for the most of the queries that I tried to execute, however with the above query it returns the below error:

ValueError: Length mismatch: Expected axis has 0 elements, new values have 8 elements

While I was troubleshooting I printed the the df parameter and I got an "Empty Dataframe".
However when I run the same query in my database directly I get results.

I also noticed that in the response, on my database, some columns are empty (not sure if it makes any difference).

Please also find a print screen of the code execution.

The above will work if I remove the below piece of code:

for row in query: #check if the query is empty
    if (row[0] > 0):
        not_empty_query = True
        break
if not_empty_query == True:

However, if I remove this 'for loop' then for other queries (mainly for queries which return empty results) I get the same error.
Please find an example below.

Ay ideas?

Body:
Try to create an empty data frame first.

if not_empty_query == True: #if the query isn not empty add response into excel
        df = pd.DataFrame(pd.np.empty((0, 8)))
        df = DataFrame(query.fetchall())
        print(df)
        df.columns = query.keys()
        df.to_excel("out.xlsx", engine="openpyxl", sheet_name="Worksheet_Name")


问:
How to set versioning control systems through internet
I have project on my computer and I want my colleagues to work with it.
I want them to make a changes to project and let them commit their changes.
I don't have special server for it.
What can I use (Ubuntu)?
And can I use Dropbox for this type of work?</p>

答: Why not use http://bitbucket.org/ you can have up to 5 private repositories. </p>

ContentLicense: CC BY-SA 3.0


问:
How to list all the names and ages associated with each activity
I have a dataframe that contains information about which people are taking part in each activity. Unfortunately there are up to a number of different places each piece of information can be put. That is one row can give information for many different people. The column names are as follows:

```<code>['Name', 'Activity', 'Name.0', 'Age.0', 'Activity.0', 'Name.1', 'Age.1', 'Activity.1', 'Name.2', 'Age.2', 'Activity.2', 'Name.3', 'Age.3',  'Activity.3', 'Name.4', 'Age.4', 'Activity.4']
</code>```

For each Activity, I want to list all the people who are associated with it and their ages (if that information is provided). Ultimately I want to make one table per Activity. How can I do that?

It feels like I need to first need to deal with all the .* column names and then groupby Activity somehow but I am not sure how to do it.

Here is some anonymized data outputted using df.sample(5).to_dict().

```<code>{'Activity': {0: 'Audi', 1: 'Carn', 2: 'Pop-', 3: 'Samb', 4: 'Pre-'},
 'Activity.0': {0: 'Samb', 1: 'Pre-', 2: 'nan', 3: 'Samb', 4: 'Pre-'},
 'Activity.1': {0: 'Samb', 1: 'Audi', 2: 'nan', 3: 'Samb', 4: 'nan'},
 'Activity.2': {0: 'Pre-', 1: 'Audi', 2: 'nan', 3: 'nan', 4: 'nan'},
 'Activity.3': {0: 'nan', 1: 'Carn', 2: 'nan', 3: 'nan', 4: 'nan'},
 'Activity.4': {0: 'nan', 1: 'Carn', 2: 'nan', 3: 'nan', 4: 'nan'},
 'Age.0': {0: '18+', 1: 'Under 5', 2: '11', 3: '11', 4: 'Under 5'},
 'Age.1': {0: '11', 1: 'Under 5', 2: '11', 3: 17, 4: '18+'},
 'Age.2': {0: '11', 1: '18+', 2: 'nan', 3: '18+', 4: 'nan'},
 'Age.3': {0: 'Under 5', 1: '18+', 2: 'nan', 3: 'nan', 4: 'nan'},
 'Age.4': {0: 'nan', 1: '18+', 2: 'nan', 3: 'nan', 4: 'nan'},
 'Name': {0: 'Jess', 1: 'Tama', 2: 'Beki', 3: 'Havi', 4: 'Dror'},
 'Name.0': {0: 'Sam ', 1: 'Lila', 2: 'nan', 3: 'Joel', 4: 'Emil'},
 'Name.1': {0: 'Zipp', 1: 'Marg', 2: 'nan', 3: 'Solo', 4: 'Ari '},
 'Name.2': {0: 'Reub', 1: 'Joan', 2: 'nan', 3: 'Sami', 4: 'nan'},
 'Name.3': {0: 'Shev', 1: 'John', 2: 'nan', 3: 'nan', 4: 'nan'},
 'Name.4': {0: 'nan', 1: 'Edwa', 2: 'nan', 3: 'nan', 4: 'nan'}}
</code>```

For this example, let's take the activity called 'Audi'.  The only people doing this are 'Jess' (no age), 'Marge' (under 5) and 'Joan' (18+).  For the activity 'Samb', the people associated with it are 'Havi' (no age), 'Sam' (18+), 'Joel' (11),'Zipp' (11) and 'Solo' (17).   I would like the same thing for each of the activities.

答:
Alternative approach: uses itertools groupby, sorted and defaultdict to get the final result</p>

```<code>from itertools import groupby
fn = lambda x: x[0].split('.')[-1]
s = sorted(data.items(), key = fn)
R = []
groups=[]
#data must be sorted before the groupby function is invoked
for k, g in groupby(s, key = fn):
    m = list(g)
#this part fetches Activity and Name,
#since they have no numbers attached to them
#separates them, zips them, and assign to A
    if len(m)==1:
        [R.append(r) for r in m]
    else:
 #here we work on the rest that have numbers attached to the keys
   #we zip them as well, and append to groups
        first = [(i[0].split('.')[0],*i[-1].values()) for i in m]
        second = zip(*first)
        [groups. append(i) for i in second]
    A = list(zip(*[i[-1].values() for i in R]))
#all data in one place
groups.extend(A)

#get rid of 'noise'
groups = [i for i in groups if i not in [('Activity', 'Age', 'Name'),('nan', 'nan', 'nan')]]

from collections import defaultdict
d = defaultdict(list)
for k,*v in groups:
    d[k].append(v)

del (d['nan'])

defaultdict(list,
        {'Samb': [['18+', 'Sam '],
          ['11', 'Joel'],
          ['11', 'Zipp'],
          [17, 'Solo'],
          ['Havi']],
         'Pre-': [['Under 5', 'Lila'],
          ['Under 5', 'Emil'],
          ['11', 'Reub'],
          ['Dror']],
         'Audi': [['Under 5', 'Marg'], ['18+', 'Joan'], ['Jess']],
         'Carn': [['18+', 'John'], ['18+', 'Edwa'], ['Tama']],
         'Pop-': [['Beki']]})
</code>```

Body:
I have a dataframe that contains information about which people are taking part in each activity. Unfortunately there are up to a number of different places each piece of information can be put. That is one row can give information for many different people. The column names are as follows:

['Name', 'Activity', 'Name.0', 'Age.0', 'Activity.0', 'Name.1', 'Age.1', 'Activity.1', 'Name.2', 'Age.2', 'Activity.2', 'Name.3', 'Age.3',  'Activity.3', 'Name.4', 'Age.4', 'Activity.4']

For each Activity, I want to list all the people who are associated with it and their ages (if that information is provided). Ultimately I want to make one table per Activity. How can I do that?

It feels like I need to first need to deal with all the .* column names and then groupby Activity somehow but I am not sure how to do it.

Here is some anonymized data outputted using df.sample(5).to_dict().

{'Activity': {0: 'Audi', 1: 'Carn', 2: 'Pop-', 3: 'Samb', 4: 'Pre-'},
 'Activity.0': {0: 'Samb', 1: 'Pre-', 2: 'nan', 3: 'Samb', 4: 'Pre-'},
 'Activity.1': {0: 'Samb', 1: 'Audi', 2: 'nan', 3: 'Samb', 4: 'nan'},
 'Activity.2': {0: 'Pre-', 1: 'Audi', 2: 'nan', 3: 'nan', 4: 'nan'},
 'Activity.3': {0: 'nan', 1: 'Carn', 2: 'nan', 3: 'nan', 4: 'nan'},
 'Activity.4': {0: 'nan', 1: 'Carn', 2: 'nan', 3: 'nan', 4: 'nan'},
 'Age.0': {0: '18+', 1: 'Under 5', 2: '11', 3: '11', 4: 'Under 5'},
 'Age.1': {0: '11', 1: 'Under 5', 2: '11', 3: 17, 4: '18+'},
 'Age.2': {0: '11', 1: '18+', 2: 'nan', 3: '18+', 4: 'nan'},
 'Age.3': {0: 'Under 5', 1: '18+', 2: 'nan', 3: 'nan', 4: 'nan'},
 'Age.4': {0: 'nan', 1: '18+', 2: 'nan', 3: 'nan', 4: 'nan'},
 'Name': {0: 'Jess', 1: 'Tama', 2: 'Beki', 3: 'Havi', 4: 'Dror'},
 'Name.0': {0: 'Sam ', 1: 'Lila', 2: 'nan', 3: 'Joel', 4: 'Emil'},
 'Name.1': {0: 'Zipp', 1: 'Marg', 2: 'nan', 3: 'Solo', 4: 'Ari '},
 'Name.2': {0: 'Reub', 1: 'Joan', 2: 'nan', 3: 'Sami', 4: 'nan'},
 'Name.3': {0: 'Shev', 1: 'John', 2: 'nan', 3: 'nan', 4: 'nan'},
 'Name.4': {0: 'nan', 1: 'Edwa', 2: 'nan', 3: 'nan', 4: 'nan'}}

For this example, let's take the activity called 'Audi'.  The only people doing this are 'Jess' (no age), 'Marge' (under 5) and 'Joan' (18+).  For the activity 'Samb', the people associated with it are 'Havi' (no age), 'Sam' (18+), 'Joel' (11),'Zipp' (11) and 'Solo' (17).   I would like the same thing for each of the activities.

Body:
Alternative approach: uses itertools groupby, sorted and defaultdict to get the final result

from itertools import groupby
fn = lambda x: x[0].split('.')[-1]
s = sorted(data.items(), key = fn)
R = []
groups=[]
#data must be sorted before the groupby function is invoked
for k, g in groupby(s, key = fn):
    m = list(g)
#this part fetches Activity and Name,
#since they have no numbers attached to them
#separates them, zips them, and assign to A
    if len(m)==1:
        [R.append(r) for r in m]
    else:
 #here we work on the rest that have numbers attached to the keys
   #we zip them as well, and append to groups
        first = [(i[0].split('.')[0],*i[-1].values()) for i in m]
        second = zip(*first)
        [groups. append(i) for i in second]
    A = list(zip(*[i[-1].values() for i in R]))
#all data in one place
groups.extend(A)

#get rid of 'noise'
groups = [i for i in groups if i not in [('Activity', 'Age', 'Name'),('nan', 'nan', 'nan')]]

from collections import defaultdict
d = defaultdict(list)
for k,*v in groups:
    d[k].append(v)

del (d['nan'])

defaultdict(list,
        {'Samb': [['18+', 'Sam '],
          ['11', 'Joel'],
          ['11', 'Zipp'],
          [17, 'Solo'],
          ['Havi']],
         'Pre-': [['Under 5', 'Lila'],
          ['Under 5', 'Emil'],
          ['11', 'Reub'],
          ['Dror']],
         'Audi': [['Under 5', 'Marg'], ['18+', 'Joan'], ['Jess']],
         'Carn': [['18+', 'John'], ['18+', 'Edwa'], ['Tama']],
         'Pop-': [['Beki']]})


问:
OperationApplicationException on adding contact
I am trying to add a contact programmatically into my contact phonebook using ContentProviderOperation.

I have already enabled WRITE_CONTACT permission in my AndroidManifest.xml.

Here are the following code.

ArrayList <ContentProviderOperation> ops = new ArrayList <ContentProviderOperation>();

int rawContactID = ops.size();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
 .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
 .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
 .build());

ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
 .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
 .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, etname.getText().toString())
 .build());

ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
 .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
 .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, etmob.getText().toString())
 .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
 .build());

ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
 .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
 .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, etphone.getText().toString())
 .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
 .build());

ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
 .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE)
 .withValue(ContactsContract.CommonDataKinds.SipAddress.DISPLAY_NAME, etadd.getText().toString())
 .build());

ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
 .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
 .withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, etmail.getText().toString())
 .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
 .build());

try {
 getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
 Toast.makeText(getBaseContext(), "Contact is successfully added", Toast.LENGTH_SHORT).show();
} catch (RemoteException e) {
 e.printStackTrace();
} catch (OperationApplicationException e) {
 e.printStackTrace();
}
```

<p>but I am getting the exception. Here's my stack trace - </p>

```07-10 09:32:31.379    1143-1143/com.example.addcontact.app W/System.err﹕ android.content.OperationApplicationException: insert failed
07-10 09:32:31.379    1143-1143/com.example.addcontact.app W/System.err﹕ at android.database.DatabaseUtils.readExceptionWithOperationApplicationExceptionFromParcel(DatabaseUtils.java:158)
07-10 09:32:31.379    1143-1143/com.example.addcontact.app W/System.err﹕ at android.content.ContentProviderProxy.applyBatch(ContentProviderNative.java:512)
07-10 09:32:31.379    1143-1143/com.example.addcontact.app W/System.err﹕ at android.content.ContentProviderClient.applyBatch(ContentProviderClient.java:377)
07-10 09:32:31.379    1143-1143/com.example.addcontact.app W/System.err﹕ at android.content.ContentResolver.applyBatch(ContentResolver.java:1227)
07-10 09:32:31.389    1143-1143/com.example.addcontact.app W/System.err﹕ at com.example.addcontact.app.MainActivity$1.onClick(MainActivity.java:85)
07-10 09:32:31.389    1143-1143/com.example.addcontact.app W/System.err﹕ at android.view.View.performClick(View.java:4438)
07-10 09:32:31.389    1143-1143/com.example.addcontact.app W/System.err﹕ at android.view.View$PerformClick.run(View.java:18422)
07-10 09:32:31.389    1143-1143/com.example.addcontact.app W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
07-10 09:32:31.389    1143-1143/com.example.addcontact.app W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
07-10 09:32:31.389    1143-1143/com.example.addcontact.app W/System.err﹕ at android.os.Looper.loop(Looper.java:136)
07-10 09:32:31.389    1143-1143/com.example.addcontact.app W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5017)
07-10 09:32:31.399    1143-1143/com.example.addcontact.app W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
07-10 09:32:31.399    1143-1143/com.example.addcontact.app W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
07-10 09:32:31.399    1143-1143/com.example.addcontact.app W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-10 09:32:31.409    1143-1143/com.example.addcontact.app W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-10 09:32:31.409    1143-1143/com.example.addcontact.app W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
```

<p>I am not sure why I am getting insert failed at the following line. </p>

```getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
```

Any hints?

答:
I've noticed that you have 0 there, when it should be rawContactID instead.

ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                        .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, etname.getText().toString())
                        .build());
```

I've actually got it to work, you can checkout my gist here.

https://gist.github.com/delacrixmorgan/3b3efef4e449a9366836158c221142cd

Body:
I am trying to add a contact programmatically into my contact phonebook using ContentProviderOperation.

I have already enabled WRITE_CONTACT permission in my AndroidManifest.xml.

Here are the following code.

ArrayList <ContentProviderOperation> ops = new ArrayList <ContentProviderOperation>();

int rawContactID = ops.size();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
 .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
 .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
 .build());

ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
 .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
 .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, etname.getText().toString())
 .build());

ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
 .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
 .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, etmob.getText().toString())
 .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
 .build());

ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
 .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
 .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, etphone.getText().toString())
 .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
 .build());

ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
 .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE)
 .withValue(ContactsContract.CommonDataKinds.SipAddress.DISPLAY_NAME, etadd.getText().toString())
 .build());

ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
 .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
 .withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, etmail.getText().toString())
 .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
 .build());

try {
 getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
 Toast.makeText(getBaseContext(), "Contact is successfully added", Toast.LENGTH_SHORT).show();
} catch (RemoteException e) {
 e.printStackTrace();
} catch (OperationApplicationException e) {
 e.printStackTrace();
}

but I am getting the exception. Here's my stack trace -

07-10 09:32:31.379    1143-1143/com.example.addcontact.app W/System.err﹕ android.content.OperationApplicationException: insert failed
07-10 09:32:31.379    1143-1143/com.example.addcontact.app W/System.err﹕ at android.database.DatabaseUtils.readExceptionWithOperationApplicationExceptionFromParcel(DatabaseUtils.java:158)
07-10 09:32:31.379    1143-1143/com.example.addcontact.app W/System.err﹕ at android.content.ContentProviderProxy.applyBatch(ContentProviderNative.java:512)
07-10 09:32:31.379    1143-1143/com.example.addcontact.app W/System.err﹕ at android.content.ContentProviderClient.applyBatch(ContentProviderClient.java:377)
07-10 09:32:31.379    1143-1143/com.example.addcontact.app W/System.err﹕ at android.content.ContentResolver.applyBatch(ContentResolver.java:1227)
07-10 09:32:31.389    1143-1143/com.example.addcontact.app W/System.err﹕ at com.example.addcontact.app.MainActivity$1.onClick(MainActivity.java:85)
07-10 09:32:31.389    1143-1143/com.example.addcontact.app W/System.err﹕ at android.view.View.performClick(View.java:4438)
07-10 09:32:31.389    1143-1143/com.example.addcontact.app W/System.err﹕ at android.view.View$PerformClick.run(View.java:18422)
07-10 09:32:31.389    1143-1143/com.example.addcontact.app W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
07-10 09:32:31.389    1143-1143/com.example.addcontact.app W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
07-10 09:32:31.389    1143-1143/com.example.addcontact.app W/System.err﹕ at android.os.Looper.loop(Looper.java:136)
07-10 09:32:31.389    1143-1143/com.example.addcontact.app W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5017)
07-10 09:32:31.399    1143-1143/com.example.addcontact.app W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
07-10 09:32:31.399    1143-1143/com.example.addcontact.app W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
07-10 09:32:31.399    1143-1143/com.example.addcontact.app W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-10 09:32:31.409    1143-1143/com.example.addcontact.app W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-10 09:32:31.409    1143-1143/com.example.addcontact.app W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)

I am not sure why I am getting insert failed at the following line.

getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

Any hints?

Body:
I've noticed that you have 0 there, when it should be rawContactID instead.

ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                        .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, etname.getText().toString())
                        .build());

I've actually got it to work, you can checkout my gist here.

https://gist.github.com/delacrixmorgan/3b3efef4e449a9366836158c221142cd


问:
Use repository in referenced dll using entity framework
I have created a DLL that contains lots of authentication and user management that I'm trying to use in a separate project (MVC 3 Website).

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestProj.Authentication;

namespace TestSite.MVC.Areas.Admin.Controllers
{
    public class TestController : Controller
    {
        AuthenticationRepository authrep = new AuthenticationRepository();

        public ActionResult Index()
        {
            authrep.DeleteUser(1);
            return View();
        }
    }
}
</code>```

Now this obviously does'nt work, which is understandable.

Is it dependency injection I need here?

And in that case, how would the basic code look for that?

Do I need to add something in the constructor for the referenced DLL?

答:
Try structuring your controller like this:

```<code>public class TestController : Controller
    {
        IAuthenticationRepository AuthenticationRepository { get;set; }

        public void TestController (IuthenticationRepository authenticationRepository)
        {
          this.AuthenticationRepository = authenticationRepository;
        }

        public ActionResult Index()
        {
            this.AuthenticationRepository.DeleteUser(1);

            return View();
        }
    }
</code>```

Create an interface for your repository. You could then use a DI framework (like Ninject for MVC 3) to inject instances of AuthenticationRepository into usages of IAuthenticationRepository.

https://github.com/ninject/ninject/wiki

Body:
I have created a DLL that contains lots of authentication and user management that I'm trying to use in a separate project (MVC 3 Website).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestProj.Authentication;

namespace TestSite.MVC.Areas.Admin.Controllers
{
    public class TestController : Controller
    {
        AuthenticationRepository authrep = new AuthenticationRepository();

        public ActionResult Index()
        {
            authrep.DeleteUser(1);
            return View();
        }
    }
}

Now this obviously does'nt work, which is understandable.

Is it dependency injection I need here?

And in that case, how would the basic code look for that?

Do I need to add something in the constructor for the referenced DLL?

Body:
Try structuring your controller like this:

public class TestController : Controller
    {
        IAuthenticationRepository AuthenticationRepository { get;set; }

        public void TestController (IuthenticationRepository authenticationRepository)
        {
          this.AuthenticationRepository = authenticationRepository;
        }

        public ActionResult Index()
        {
            this.AuthenticationRepository.DeleteUser(1);

            return View();
        }
    }

Create an interface for your repository. You could then use a DI framework (like Ninject for MVC 3) to inject instances of AuthenticationRepository into usages of IAuthenticationRepository.

https://github.com/ninject/ninject/wiki


问:
Using aws STS to get temporary credentials: Where is the web identity token?
My users login to my application through a microservice that connects to cognito (the request is proxied via API gateway)

They get a session token.

Once logged in, they need to put some files to S3.

I want to give them temporary credentials using STS but to call sts.AssumeRoleWithWebIdentity I need a web identity token.

How can I get a web identity token with a session token as input?

I wrote a temporary lambda (node) that returns STS credentials upon logging with a username and password:

```<code>const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
const cognitoidentity = new AWS.CognitoIdentity();
cognitoidentityserviceprovider.initiateAuth(...) //AuthFlow: 'USER_PASSWORD_AUTH'
    cognitoidentity.getId(...)
        cognitoidentity.getCredentialsForIdentity(...)
</code>```

There can be some time between the login and the file upload and I don't want the user to submit user/password each time. There's no AuthFlow accepting a session token either.

I'm guessing the API Gateway could return something useful but I didn't find anything in the docs:
https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#context-variable-reference

答:
A few checks first:

let cognito authenticated user to "masquerade" under an iam role, to do that we use trust relationships, for quick you can reuse the iam role that get assigned to your cognito identity pool.

grant that iam role a policy to access to s3 bucket

Once done:

Run cognitoidentity.getCredentialsForIdentity(...) again, it will go through sts first, thus you don't have to call sts assume role api. If successful, the response should have AccessKeyId, SecretKey and SessionToken. These are expiry aws creds that have access to s3 and will be gone after an hour (unless set). Use them as normal session authentication.

```<code>creds = new SessionAWSCredentials(AccessKeyId, SecretKey, SessionToken);
s3Request = CreateAmazonS3Client(creds);
</code>```

Body:
My users login to my application through a microservice that connects to cognito (the request is proxied via API gateway)

They get a session token.

Once logged in, they need to put some files to S3.

I want to give them temporary credentials using STS but to call sts.AssumeRoleWithWebIdentity I need a web identity token.

How can I get a web identity token with a session token as input?

I wrote a temporary lambda (node) that returns STS credentials upon logging with a username and password:

const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
const cognitoidentity = new AWS.CognitoIdentity();
cognitoidentityserviceprovider.initiateAuth(...) //AuthFlow: 'USER_PASSWORD_AUTH'
    cognitoidentity.getId(...)
        cognitoidentity.getCredentialsForIdentity(...)

There can be some time between the login and the file upload and I don't want the user to submit user/password each time. There's no AuthFlow accepting a session token either.

I'm guessing the API Gateway could return something useful but I didn't find anything in the docs:
https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#context-variable-reference

Body:
A few checks first:

let cognito authenticated user to "masquerade" under an iam role, to do that we use trust relationships, for quick you can reuse the iam role that get assigned to your cognito identity pool.

grant that iam role a policy to access to s3 bucket

Once done:

Run cognitoidentity.getCredentialsForIdentity(...) again, it will go through sts first, thus you don't have to call sts assume role api. If successful, the response should have AccessKeyId, SecretKey and SessionToken. These are expiry aws creds that have access to s3 and will be gone after an hour (unless set). Use them as normal session authentication.

creds = new SessionAWSCredentials(AccessKeyId, SecretKey, SessionToken);
s3Request = CreateAmazonS3Client(creds);


问:
Issues sending data using axios in react native
I am having issue sending a put request.
I have tested the api using postman, when I send the request with a body of form-data and header of content-type ( application/json ), it doesn't work, infact when i dump the request, I realize nothing was sent, but again in postman if i send the request using body of raw, it works successfully, now bringing the same thing to my react native project using axios to make the same request, I get the same error as when I used form-data in postman, nothing get sent and I get error 500 (bad request).
So now in the backend, I used put the request under if, so when I run the function, I get success, but nothing get sent.
The thing is it sends nothing, no input at all is sent.

This is the function right here;

```<code>const setBasic = () => async ({ id }) => {
const data = new FormData();
data.append('Basic', 1)

const config = {
    method: 'put',
    url: `http://89bb1d61.ngrok.io/api/usersub/${id}`,
    body: JSON.stringify(data),
    headers: { "Content-type": "application/json" }

}

const response = await axios(config)
if (response) {
    console.log(response.data)
} else {
    console.log('Error')
}
</code>```

}

But nothing gets sent.

This is the server side code;

```<code>public function update(Request $request, $id)
{
    $user = User::find($id);

    if($request->has('Basic')){
        $user->Basic = $request->input('Basic');
        }
    //  $user->Basic = $request->input('Basic');
    if($request->has('Standard')){
        $user->Standard = $request->input('Standard');
        }
    if($request->has('Premium')){
        $user->Premium = $request->input('Premium');
        }

     $user->save();

     return response()->json([
      'message' => 'Success',

  ]);
}
</code>```

It will return the success message here, (I console logged response.data) but this is because I had wrapped if around the requests. If I were to remove the if , then bad request, the input isn't received.

答:
I fixed it by doing it this way;</p>

```<code>const setBasic = () => async ({ id }) => {
    const Basic = 1
    const response = await appApi.put(`/usersub/${id}`, { Basic });
    if (response) {
        console.log(response.data)
    }
}
</code>```

Body:
I am having issue sending a put request.
I have tested the api using postman, when I send the request with a body of form-data and header of content-type ( application/json ), it doesn't work, infact when i dump the request, I realize nothing was sent, but again in postman if i send the request using body of raw, it works successfully, now bringing the same thing to my react native project using axios to make the same request, I get the same error as when I used form-data in postman, nothing get sent and I get error 500 (bad request).
So now in the backend, I used put the request under if, so when I run the function, I get success, but nothing get sent.
The thing is it sends nothing, no input at all is sent.

This is the function right here;

const setBasic = () => async ({ id }) => {
const data = new FormData();
data.append('Basic', 1)

const config = {
    method: 'put',
    url: `http://89bb1d61.ngrok.io/api/usersub/${id}`,
    body: JSON.stringify(data),
    headers: { "Content-type": "application/json" }

}

const response = await axios(config)
if (response) {
    console.log(response.data)
} else {
    console.log('Error')
}

}

But nothing gets sent.

This is the server side code;

public function update(Request $request, $id)
{
    $user = User::find($id);

    if($request->has('Basic')){
        $user->Basic = $request->input('Basic');
        }
    //  $user->Basic = $request->input('Basic');
    if($request->has('Standard')){
        $user->Standard = $request->input('Standard');
        }
    if($request->has('Premium')){
        $user->Premium = $request->input('Premium');
        }

     $user->save();

     return response()->json([
      'message' => 'Success',

  ]);
}

It will return the success message here, (I console logged response.data) but this is because I had wrapped if around the requests. If I were to remove the if , then bad request, the input isn't received.

Body:
I fixed it by doing it this way;

const setBasic = () => async ({ id }) => {
    const Basic = 1
    const response = await appApi.put(`/usersub/${id}`, { Basic });
    if (response) {
        console.log(response.data)
    }
}


问:
Align ImageView to top right corner
I have a RelativeLayout with images next to each other. The number of images will be variable.

```<code>    <RelativeLayout
        android:id="@id/multipleImages"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/border">

        <ImageView
            android:id="@+id/multi_image1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag1"/>
        <ImageView
            android:id="@+id/multi_image2"
            android:layout_toRightOf="@+id/imag1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag2"/>
        <ImageView
            android:id="@+id/multi_image3"
            android:layout_toRightOf="@+id/multi_image2"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag3"/>

        <ImageView
            android:id="@+id/multi_image4"
            android:layout_toRightOf="@+id/multi_image3"
            android:layout_marginTop="2dp"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag4"/>

    </RelativeLayout>
</code>```

I want to add another image (the red rectangle) to the top-right corner slightly above the last image .
I tried layout_alignParentEnd but the layout goes full width.
Setting negative layout_marginTop the image goes up but is disappears outside the RelativeLayout.

答:
I have used ConstraintLayout instead of RelativeLayout. Try using my answer:

```<code> <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/multipleImages"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:background="@drawable/border">

    <ImageView
        android:id="@+id/multi_image1"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/imag" />

    <ImageView
        android:id="@+id/multi_image2"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/multi_image4"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/imag2" />

    <ImageView
        android:id="@+id/multi_image3"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/multi_image2"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/imag3" />

    <ImageView
        android:id="@+id/multi_image4"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/multi_image1"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/imag4" />

</android.support.constraint.ConstraintLayout>
</code>```

Title: Align ImageView to top right corner

Body:
I have a RelativeLayout with images next to each other. The number of images will be variable.

    <RelativeLayout
        android:id="@id/multipleImages"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/border">

        <ImageView
            android:id="@+id/multi_image1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag1"/>
        <ImageView
            android:id="@+id/multi_image2"
            android:layout_toRightOf="@+id/imag1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag2"/>
        <ImageView
            android:id="@+id/multi_image3"
            android:layout_toRightOf="@+id/multi_image2"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag3"/>

        <ImageView
            android:id="@+id/multi_image4"
            android:layout_toRightOf="@+id/multi_image3"
            android:layout_marginTop="2dp"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag4"/>

    </RelativeLayout>

I want to add another image (the red rectangle) to the top-right corner slightly above the last image .
I tried layout_alignParentEnd but the layout goes full width.
Setting negative layout_marginTop the image goes up but is disappears outside the RelativeLayout.

Body:
I have used ConstraintLayout instead of RelativeLayout. Try using my answer:

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/multipleImages"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:background="@drawable/border">

    <ImageView
        android:id="@+id/multi_image1"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/imag" />

    <ImageView
        android:id="@+id/multi_image2"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/multi_image4"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/imag2" />

    <ImageView
        android:id="@+id/multi_image3"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/multi_image2"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/imag3" />

    <ImageView
        android:id="@+id/multi_image4"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/multi_image1"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/imag4" />

</android.support.constraint.ConstraintLayout>


问:
create temp table that deletes itself when I end my transaction
I am using Postgres 9.6

I wish to CREATE temp table that will drop itself at the end of the transaction. I have been looking through the documentation and am having a hard time locating the answer to this.

答:
Quote from the manual

ON COMMIT

  The behavior of temporary tables at the end of a transaction block can be controlled using ON COMMIT. The three options are:

...

  DROP

  The temporary table will be dropped at the end of the current transaction block.

(emphasis mine)

The "end of transaction block" is defined by a commit or a rollback.


问:
typescript tsc exclude with cmd line args
I'm working through a tool which need setup compilation dynamically. In that case, we need to maintain a tsconfig json object in a database.

While we use it to compile on certain machine there is a file's writting action. I mean we need to fetch the tsconfig data and write it into a tsconfig.json file, then start to tsc compile.

Well, it seems unnecessary to write this config file in the whole process, so I'm seeking for a way to generate a tsc command line from tsconfig json.

From the office document, I found it's easy to transform compilerOptions to CLI arguments, but have no idea about how to deal with exclude.

```<code>{
    "compilerOptions": {
        "module": "system",
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "outFile": "../../built/local/tsc.js",
        "sourceMap": true
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}
</code>```

With the case above, I'v tried some like:

tsc src/apis/**/*  \
    "\!node_modules" \        # this didn't work
    "\!**/*.spec.ts" \        # this didn't work
    --module "system" \
    --noImplicitAny true \
    --removeComments true \
    --preserveConstEnums true \
    --outFile "../../built/local/tsc.js" \
    --sourceMap true
```

That didn't work, I need some suggestion about how tsc deal with the exclude case. Thank for your reading.

答: I'v got a workaround, it's, to mix up tsconfig.files, tsconfig.include and tsconfig.exlude into an array, then globby it, So that we can manually get the list of files to be flatten to CLI arguments.

Body:
I'm working through a tool which need setup compilation dynamically. In that case, we need to maintain a tsconfig json object in a database.

While we use it to compile on certain machine there is a file's writting action. I mean we need to fetch the tsconfig data and write it into a tsconfig.json file, then start to tsc compile.

Well, it seems unnecessary to write this config file in the whole process, so I'm seeking for a way to generate a tsc command line from tsconfig json.

From the office document, I found it's easy to transform compilerOptions to CLI arguments, but have no idea about how to deal with exclude.

{
    "compilerOptions": {
        "module": "system",
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "outFile": "../../built/local/tsc.js",
        "sourceMap": true
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}

With the case above, I'v tried some like:

tsc src/apis/**/*  \
    "\!node_modules" \        # this didn't work
    "\!**/*.spec.ts" \        # this didn't work
    --module "system" \
    --noImplicitAny true \
    --removeComments true \
    --preserveConstEnums true \
    --outFile "../../built/local/tsc.js" \
    --sourceMap true

That didn't work, I need some suggestion about how tsc deal with the exclude case. Thank for your reading.


问:
Declarations Cause Collision in the ObjectFactory
I have two xsd being import to the main xsd. Both have the same elements but just different namespace. So, I created a customized binding for the second xsd(B.xsd). I am still getting 'Two declarations cause a collision in the ObjectFactory class'. As far I understand, customized binding would actually provide a meaningful customized names for cases that the default XML name-to-Java identifier mapping cannot handle automatically.Thus, collisions will be avoided.

A.xsd

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema targetNamespace="urn:abc:def:ghi" xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:element name="lotNumber" type="xs:string"/>
    <xs:element name="itemExpirationDate" type="xs:date" />

</xs:schema>
</code>```

B.xsd

```<code><?xml version="1.0" encoding="UTF-8"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
     xmlns="http://abc.def.org/kj/ns"
     targetNamespace="http://abc.def.org/kj/ns"
     elementFormDefault="qualified"
     attributeFormDefault="unqualified">
    <xs:element name="ilmd">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="lotNumber" minOccurs="0"/>
                <xs:element ref="itemExpirationDate" minOccurs="0"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="lotNumber" type="xs:string"/>
    <xs:element name="itemExpirationDate" type="xs:string"/>
</xs:schema>
</code>```

binding.xml

```<code><jaxb:bindings
    xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    jaxb:extensionBindingPrefixes="xjc" jaxb:version="2.0">

    <jaxb:bindings
        schemaLocation="./xsd/B.xsd" node="/xs:schema">

        <jaxb:bindings node="//*/xs:element[@name='lotNumber']">
            <jaxb:property name="ucbLotNumber" />
        </jaxb:bindings>

        <jaxb:bindings node="//*/xs:element[@name='itemExpirationDate']">
            <jaxb:property name="ucbItemExpiratonDate" />
        </jaxb:bindings>

    </jaxb:bindings>

</jaxb:bindings>
</code>```

pom.xml

```<code><plugin>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-xjc-plugin</artifactId>
                <configuration>
                    <extensions>
                        <extension>org.apache.cxf.xjcplugins:cxf-xjc-ts:3.0.3</extension>
                    </extensions>
                </configuration>
                <executions>
                    <execution>
                        <id>Xsd2Java</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>xsdtojava</goal>
                        </goals>
                        <configuration>
                            <sourceRoot>${basedir}/target/generated-sources/cxf</sourceRoot>
                            <xsdOptions>
                                <xsdOption>
                                    <xsd>${basedir}/src/main/resources/xsd/Main.xsd</xsd>
                                    <packagename>abc.def</packagename>
                                    <bindingFile>src/main/resources/binding.xml</bindingFile>
                                    <extension>true</extension>
                                    <extensionArgs>
                                        <arg>-encoding</arg>
                                        <arg>UTF-8</arg>
                                    </extensionArgs>
                                </xsdOption>
                            </xsdOptions>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
</code>```

答:
if element contains complextype inside,You should add name attribute to complextype </p>

```<code><xs:element name="ilmd">
        <xs:complexType **name="ilmdArray"**>
            <xs:sequence>
                <xs:element ref="lotNumber" minOccurs="0"/>
                <xs:element ref="itemExpirationDate" minOccurs="0"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</code>```

Body:
I have two xsd being import to the main xsd. Both have the same elements but just different namespace. So, I created a customized binding for the second xsd(B.xsd). I am still getting 'Two declarations cause a collision in the ObjectFactory class'. As far I understand, customized binding would actually provide a meaningful customized names for cases that the default XML name-to-Java identifier mapping cannot handle automatically.Thus, collisions will be avoided.

A.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema targetNamespace="urn:abc:def:ghi" xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:element name="lotNumber" type="xs:string"/>
    <xs:element name="itemExpirationDate" type="xs:date" />

</xs:schema>

B.xsd

<?xml version="1.0" encoding="UTF-8"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
     xmlns="http://abc.def.org/kj/ns"
     targetNamespace="http://abc.def.org/kj/ns"
     elementFormDefault="qualified"
     attributeFormDefault="unqualified">
    <xs:element name="ilmd">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="lotNumber" minOccurs="0"/>
                <xs:element ref="itemExpirationDate" minOccurs="0"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="lotNumber" type="xs:string"/>
    <xs:element name="itemExpirationDate" type="xs:string"/>
</xs:schema>

binding.xml

<jaxb:bindings
    xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    jaxb:extensionBindingPrefixes="xjc" jaxb:version="2.0">

    <jaxb:bindings
        schemaLocation="./xsd/B.xsd" node="/xs:schema">

        <jaxb:bindings node="//*/xs:element[@name='lotNumber']">
            <jaxb:property name="ucbLotNumber" />
        </jaxb:bindings>

        <jaxb:bindings node="//*/xs:element[@name='itemExpirationDate']">
            <jaxb:property name="ucbItemExpiratonDate" />
        </jaxb:bindings>

    </jaxb:bindings>

</jaxb:bindings>

pom.xml

<plugin>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-xjc-plugin</artifactId>
                <configuration>
                    <extensions>
                        <extension>org.apache.cxf.xjcplugins:cxf-xjc-ts:3.0.3</extension>
                    </extensions>
                </configuration>
                <executions>
                    <execution>
                        <id>Xsd2Java</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>xsdtojava</goal>
                        </goals>
                        <configuration>
                            <sourceRoot>${basedir}/target/generated-sources/cxf</sourceRoot>
                            <xsdOptions>
                                <xsdOption>
                                    <xsd>${basedir}/src/main/resources/xsd/Main.xsd</xsd>
                                    <packagename>abc.def</packagename>
                                    <bindingFile>src/main/resources/binding.xml</bindingFile>
                                    <extension>true</extension>
                                    <extensionArgs>
                                        <arg>-encoding</arg>
                                        <arg>UTF-8</arg>
                                    </extensionArgs>
                                </xsdOption>
                            </xsdOptions>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

Body:
if element contains complextype inside,You should add name attribute to complextype

<xs:element name="ilmd">
        <xs:complexType **name="ilmdArray"**>
            <xs:sequence>
                <xs:element ref="lotNumber" minOccurs="0"/>
                <xs:element ref="itemExpirationDate" minOccurs="0"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>


问:
Why does Nservicebus not use WCF?
I see that NServiceBus uses MSMQ as its transport. Why doesn't it use WCF with MSMQ as the underlying transport? </p>

答:
The primary reason was that the MSMQ code was written before WCF even existed. As time progressed, most of the work focused on adding new features rather than revisiting the already solution MSMQ integration.

There's also things that NServiceBus does with respect to MSMQ that WCF doesn't do. For example, NServiceBus will create a queue if it doesn't exist. This makes it much smoother to work with NServiceBus than with WCF.

This does not imply that this functionality could not be preserved if migrated to work on top of WCF/MSMQ but the main thing is that it is just too low a priority as compared to all the other things slated for the next release.

Title: Why does Nservicebus not use WCF?


问:
AWS lambda No module named markupsafe error with jinja2
I created a lambda function to send emails in a specific template and for the template i am using jinja2 packaged along with lambda. My lambda import statements are like this below:

```<code>import datetime
import boto3
import threading
import time

from botocore.exceptions import ClientError
from boto3.dynamodb.conditions import Key, Attr
from libs.jinja2 import Environment, FileSystemLoader
</code>```

and my libs folder consists of jinja2 and when it failed with No module named Markupsafe i pip installed markupsafe into the libs folder as target and zipped the app(source code) and libs folder together. But it still doesn't work and fails with this below error:

```<code>{
  "errorMessage": "Unable to import module 'app.main': No module named 'markupsafe'",
  "errorType": "Runtime.ImportModuleError"
}
</code>```

答:
We had the similar problem, our aws lambda uses runtime python3.7

So jinja2 depends on markupsafe [1]

```<code>Collecting Jinja2>=2.10.1
Downloading Jinja2-2.11.1-py2.py3-none-any.whl (126 kB)
Collecting Flask==1.0.2
Downloading Flask-1.0.2-py2.py3-none-any.whl (91 kB)
Collecting Werkzeug==0.14.1
Downloading Werkzeug-0.14.1-py2.py3-none-any.whl (322 kB)
....
Collecting MarkupSafe>=0.23
Downloading MarkupSafe-1.1.1-cp37-cp37m-manylinux1_x86_64.whl (27 kB)
</code>```

The above dependecy tree works .

[1] https://jinja.palletsprojects.com/en/2.11.x/intro/#prerequisites

Body:
I created a lambda function to send emails in a specific template and for the template i am using jinja2 packaged along with lambda. My lambda import statements are like this below:

import datetime
import boto3
import threading
import time

from botocore.exceptions import ClientError
from boto3.dynamodb.conditions import Key, Attr
from libs.jinja2 import Environment, FileSystemLoader

and my libs folder consists of jinja2 and when it failed with No module named Markupsafe i pip installed markupsafe into the libs folder as target and zipped the app(source code) and libs folder together. But it still doesn't work and fails with this below error:

{
  "errorMessage": "Unable to import module 'app.main': No module named 'markupsafe'",
  "errorType": "Runtime.ImportModuleError"
}

Body:
We had the similar problem, our aws lambda uses runtime python3.7

So jinja2 depends on markupsafe [1]

Collecting Jinja2>=2.10.1
Downloading Jinja2-2.11.1-py2.py3-none-any.whl (126 kB)
Collecting Flask==1.0.2
Downloading Flask-1.0.2-py2.py3-none-any.whl (91 kB)
Collecting Werkzeug==0.14.1
Downloading Werkzeug-0.14.1-py2.py3-none-any.whl (322 kB)
....
Collecting MarkupSafe>=0.23
Downloading MarkupSafe-1.1.1-cp37-cp37m-manylinux1_x86_64.whl (27 kB)

The above dependecy tree works .

[1] https://jinja.palletsprojects.com/en/2.11.x/intro/#prerequisites


问:
Push Notifications in Mavericks iOS Simulator
I can't find anything about this, and I have never done anything with push notifications (but I know vaguely how they work). In Mavericks, now that OS X can receive push notifications from various things like websites, can iPhone Simulator receive push notifications? I've found plenty of answers from mid-2013 and earlier saying "no", but all of them are outdated because Mavericks was just recently released with its new push features.

I'm about to start working on an app for a school project that should use push notifications unless I want to be cheap and just poll the server. I understand that you NEED an iOS developer account to use push notifications, but it would make my life a lot easier if I could test on my computer.

答:
Now it is possible to receive a Push notification (with sound and badge count) in Simulator

Step 1 :- Create Project (Xcode 11.4 beta)

Step 2 :- import UserNotifications and registerForPushNotifications

Step 3 :- Create JSON file (payload.apns) like below

```<code>{
    "Simulator Target Bundle": "metiz.DemoSimPushnotification",
    "aps": {
        "title": "Xcode 11.4 Beta Update",
        "alert": "Push notification in simulator - take a look",
        "sound": "default",
        "badge": 1
    }
}
</code>```

Step 4 :-  Open terminal  write command $ xcrun simctl push
           com.example.myapp ExamplePush.apns”

< device > will be replaced by the device identifier.

com.example.myapp  will be replaced by your project’s bundle identifier

ExamplePush.apns will be replaced by the filename of our apns file.

like this:-

$ xcrun simctl push 4F19A097-DAE2-4298-99EB-23D4F2DBAF97 metiz.DemoSimPushnotification payload.apns

Now, press Enter! see the magic!

Reference link:-

https://www.metizsoft.com/blog/testing-push-notification-on-ios-simulator

Body:
Now it is possible to receive a Push notification (with sound and badge count) in Simulator

Step 1 :- Create Project (Xcode 11.4 beta)

Step 2 :- import UserNotifications and registerForPushNotifications

Step 3 :- Create JSON file (payload.apns) like below

{
    "Simulator Target Bundle": "metiz.DemoSimPushnotification",
    "aps": {
        "title": "Xcode 11.4 Beta Update",
        "alert": "Push notification in simulator - take a look",
        "sound": "default",
        "badge": 1
    }
}

Step 4 :-  Open terminal  write command $ xcrun simctl push
           com.example.myapp ExamplePush.apns”

< device > will be replaced by the device identifier.

com.example.myapp  will be replaced by your project’s bundle identifier

ExamplePush.apns will be replaced by the filename of our apns file.

like this:-

$ xcrun simctl push 4F19A097-DAE2-4298-99EB-23D4F2DBAF97 metiz.DemoSimPushnotification payload.apns

Now, press Enter! see the magic!

Reference link:-

https://www.metizsoft.com/blog/testing-push-notification-on-ios-simulator


问:
check owner permissions from file (multiple paths results) in bash script
friends,
I have a problem with my script. I tried to find a full path of /bin/openssl and next save results to the file and read from the file paths and check permissions and owners.
But in the result file /tmp/lista.txt , I have multiple paths. How to make a script to read and check every path from file result.
Any ideas?</p>

```<code>#!/bin/sh

module_id="AV.1.8.2.1"
echo " === $module_id module === "

#MODULE BODY
find / -wholename "*bin/openssl" -print > /tmp/list.txt

file="/tmp/list.txt"
path=$(cat /tmp/list.txt)
os=$(uname)
permission_other_good=0

if [ -e $path ]
then
    if [ $os = "Linux" ]
    then
        gid_min=$(grep ^GID_MIN /etc/login.defs)
        gid_min_value=$(echo $gid_min | cut -d " " -f2)
        uid_min=$(grep ^UID_MIN /etc/login.defs)
        uid_min_value=$(echo $uid_min | cut -d " " -f2)
        sys_gid_max=$(grep ^SYS_GID_MAX /etc/login.defs)
        sys_gid_max_value=$(echo $sys_gid_max | cut -d " " -f2)
        sys_uid_max=$(grep ^SYS_UID_MAX /etc/login.defs)
        sys_uid_max_value=$(echo $sys_uid_max | cut -d " " -f2)
        user_uid=$(stat -c %u $path)
        user=$(stat -c %U $path)
        group_gid=$(stat -c %g $path)
        group=$(stat -c %G $path)
        permission_other=$(stat -c %A $path | cut -b 8-10)

        if [ -z $gid_min_value ]
        then
            gid_min_value=1000
        fi

        if [ -z $uid_min_value ]
        then
            uid_min_value=1000
        fi

        if [ -z $sys_gid_max_value ]
        then
            sys_gid_max_value=$((gid_min_value-1))
        fi

        if [ -z $sys_uid_max_value ]
        then
            sys_uid_max_value=$((uid_min_value-1))
        fi
    fi

    if [ $os = "AIX" ]
    then
        gid_min_value=$(cat /etc/security/.ids | cut -d " " -f4)
        sys_gid_max_value=$((gid_min_value-1))
        uid_min_value=$(cat /etc/security/.ids | cut -d " " -f2)
        sys_uid_max_value=$((uid_min_value-1))
        user_uid=$(istat $path | awk -F " " 'NR==3{print $2}' | cut -d "(" -f1)
        user=$(istat $path | awk -F " " 'NR==3{print $2}' | cut -d "(" -f2 | cut -d ")" -f1)
        group_gid=$(istat $path | awk -F " " 'NR==3{print $4}' | cut -d "(" -f1)
        group=$(istat $path | awk -F " " 'NR==3{print $4}' | cut -d "(" -f2 | cut -d ")" -f1)
        permission_other=$(istat $path | awk -F " " 'NR==2{print $2}' | cut -b 7-9)
    fi

    if [ $permission_other = "r-x" ] || [ $permission_other = "r--" ] || [ $permission_other = "--x" ] || [ $permission_other = "---" ]
    then
        permission_other_good=1
    fi

    if [ $user_uid -le $sys_uid_max_value ] && [ $group_gid -le $sys_gid_max_value ] && [ $permission_other_good -eq 1 ]
    then
        compliant="Yes"
        actual_value="user = $user group = $group permission = $permission_other"
    else
        compliant="No"
        actual_value="user = $user group = $group permission = $permission_other"
    fi
else
    compliant="N/A"
    actual_value="File $file does not exist"
fi

# SCRIPT RESULT

echo :::$module_id:::$compliant:::$actual_value:::
echo " === End of $module_id module === "
</code>```

答:
This is how in bash you read a file line by line </p>

```<code>#!/bin/bash
inputfile="/tmp/list.txt"
while IFS= read -r line
do
  echo "do your stuff with $line"
done < "$inputfile"
</code>```

Body:
friends,
I have a problem with my script. I tried to find a full path of /bin/openssl and next save results to the file and read from the file paths and check permissions and owners.
But in the result file /tmp/lista.txt , I have multiple paths. How to make a script to read and check every path from file result.
Any ideas?

#!/bin/sh

module_id="AV.1.8.2.1"
echo " === $module_id module === "

#MODULE BODY
find / -wholename "*bin/openssl" -print > /tmp/list.txt

file="/tmp/list.txt"
path=$(cat /tmp/list.txt)
os=$(uname)
permission_other_good=0

if [ -e $path ]
then
    if [ $os = "Linux" ]
    then
        gid_min=$(grep ^GID_MIN /etc/login.defs)
        gid_min_value=$(echo $gid_min | cut -d " " -f2)
        uid_min=$(grep ^UID_MIN /etc/login.defs)
        uid_min_value=$(echo $uid_min | cut -d " " -f2)
        sys_gid_max=$(grep ^SYS_GID_MAX /etc/login.defs)
        sys_gid_max_value=$(echo $sys_gid_max | cut -d " " -f2)
        sys_uid_max=$(grep ^SYS_UID_MAX /etc/login.defs)
        sys_uid_max_value=$(echo $sys_uid_max | cut -d " " -f2)
        user_uid=$(stat -c %u $path)
        user=$(stat -c %U $path)
        group_gid=$(stat -c %g $path)
        group=$(stat -c %G $path)
        permission_other=$(stat -c %A $path | cut -b 8-10)

        if [ -z $gid_min_value ]
        then
            gid_min_value=1000
        fi

        if [ -z $uid_min_value ]
        then
            uid_min_value=1000
        fi

        if [ -z $sys_gid_max_value ]
        then
            sys_gid_max_value=$((gid_min_value-1))
        fi

        if [ -z $sys_uid_max_value ]
        then
            sys_uid_max_value=$((uid_min_value-1))
        fi
    fi

    if [ $os = "AIX" ]
    then
        gid_min_value=$(cat /etc/security/.ids | cut -d " " -f4)
        sys_gid_max_value=$((gid_min_value-1))
        uid_min_value=$(cat /etc/security/.ids | cut -d " " -f2)
        sys_uid_max_value=$((uid_min_value-1))
        user_uid=$(istat $path | awk -F " " 'NR==3{print $2}' | cut -d "(" -f1)
        user=$(istat $path | awk -F " " 'NR==3{print $2}' | cut -d "(" -f2 | cut -d ")" -f1)
        group_gid=$(istat $path | awk -F " " 'NR==3{print $4}' | cut -d "(" -f1)
        group=$(istat $path | awk -F " " 'NR==3{print $4}' | cut -d "(" -f2 | cut -d ")" -f1)
        permission_other=$(istat $path | awk -F " " 'NR==2{print $2}' | cut -b 7-9)
    fi

    if [ $permission_other = "r-x" ] || [ $permission_other = "r--" ] || [ $permission_other = "--x" ] || [ $permission_other = "---" ]
    then
        permission_other_good=1
    fi

    if [ $user_uid -le $sys_uid_max_value ] && [ $group_gid -le $sys_gid_max_value ] && [ $permission_other_good -eq 1 ]
    then
        compliant="Yes"
        actual_value="user = $user group = $group permission = $permission_other"
    else
        compliant="No"
        actual_value="user = $user group = $group permission = $permission_other"
    fi
else
    compliant="N/A"
    actual_value="File $file does not exist"
fi

# SCRIPT RESULT

echo :::$module_id:::$compliant:::$actual_value:::
echo " === End of $module_id module === "

Body:
This is how in bash you read a file line by line

#!/bin/bash
inputfile="/tmp/list.txt"
while IFS= read -r line
do
  echo "do your stuff with $line"
done < "$inputfile"


问:
This application failed to start because no Qt platform plugin could be initialized
I am stuck trying to run a very simple Python script, getting this error:

```<code>qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

zsh: abort      python3 mypuppy1.py
</code>```

The script code is:

```<code>import cv2
img = cv2.imread('00-puppy.jpg')
while True:
    cv2.imshow('Puppy',img)
    if cv2.waitKey(1) & 0xFF == 27:
        break
cv2.destroyAllWindows()
</code>```

However this Notebook code works in JupyterLab:

```<code>import cv2
img = cv2.imread('00-puppy.jpg')
cv2.imshow('Puppy', img)
cv2.waitKey()
</code>```

I am on macOS, using Anaconda and JupyterLab. I would appreciate any help with this issue. Thanks!

答: This can be solved installing python-opencv-headless instead of python-opencv

Body:
I am stuck trying to run a very simple Python script, getting this error:

qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

zsh: abort      python3 mypuppy1.py

The script code is:

import cv2
img = cv2.imread('00-puppy.jpg')
while True:
    cv2.imshow('Puppy',img)
    if cv2.waitKey(1) & 0xFF == 27:
        break
cv2.destroyAllWindows()

However this Notebook code works in JupyterLab:

import cv2
img = cv2.imread('00-puppy.jpg')
cv2.imshow('Puppy', img)
cv2.waitKey()

I am on macOS, using Anaconda and JupyterLab. I would appreciate any help with this issue. Thanks!


问:
Can you disable the VS feature that keeps separate window positions for Debugging and Editing?
I don't have the need to have my Visual Studio windows in different locations when editing versus debugging. In fact, I'd prefer my windows to stay where I put them, and not jump around as I switch between editing and debugging.

Is there a way to tell VS to not keep different window settings for the two modes?

I'm currently using VS 2005 if that matters.

Thanks,

-Dave

答:
Other than manual editing of an exported settings file, to copy one layout over another then importing, no.

Remember it isn't just window positions, but which ones are open, and debug generally includes additional debug only windows (call stack, threads, watch, ...).

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Richard


问:
Strange issue with Dictionary and Locks C#
At the moment I have a very strange issue regarding locking a dictionary. I have two different threads that access the dictionary, one thread puts in some entries, the other tries to read them out. All is well while making the entries, the strangest of problems occurs when I try to extract some values from the dictionary.

Here is what it looks like

```<code> lock (myDictionary)
{
 //Add an entry here for a key.
}
</code>```

// Retreival

```<code>lock(myDictionary)
{

 if (myDictionary.ContainsKey(key))
 myDictionary.TryGetValue(key, out store);
}
</code>```

As soon as a thread enters the above code, the keys are not found. BUT if I write the following

```<code>lock(myDictionary)
{
  Console.WriteLine(myDicionary.Count)
 if (myDictionary.ContainsKey(key))
   myDictionary.TryGetValue(key, out store);
}
</code>```

Out of nowhere I see the same dictionary containing the keys that were not found in the prior code. Now you guys can argue that what happened was the I/O delay caused enough time for the dictionary to store some values, but I donot have any timeouts or something that causes me to loose any processing, what this means till the dictionary contains some values to be extracted, next processing step will not occur and my program will wait till it gets some values. But unfortunately, this does not happen unless I put a Console.WriteLine... Anyone faced such situation before?

答:
The problem is most likely in the code that you are not showing. The type of issues that you describe is very common in multi-threading scenarios: everything comes down to timing, and timing is different when you change your code ever so slightly. In your particular case whatever value you are trying to access is there or not there depending on timing of what happening in other threads. It is simply possible that the value was not put there yet or was already deleted, when you code can't find it, but is present when you code can't see it.

It is impossible to say for sure, without seeing the rest of your code, especially the part that writes / deletes to / from the collection.

Few other things:

you need to lock both read and write access

even if you lock both read and write access you can't guaranty that a certain object is there unless you also use some other type of synchronization

As other said using ContainsKey in combination with TryGetValue does not make much sense, the way you wrote it. 'TryGetValue' exists so that you do NOT need to call ContainsKey: if value is there it will be returned to you straight away and if it's not, the result of the method call will tell you this.

Body:
At the moment I have a very strange issue regarding locking a dictionary. I have two different threads that access the dictionary, one thread puts in some entries, the other tries to read them out. All is well while making the entries, the strangest of problems occurs when I try to extract some values from the dictionary.

Here is what it looks like

 lock (myDictionary)
{
 //Add an entry here for a key.
}

// Retreival

lock(myDictionary)
{

 if (myDictionary.ContainsKey(key))
 myDictionary.TryGetValue(key, out store);
}

As soon as a thread enters the above code, the keys are not found. BUT if I write the following

lock(myDictionary)
{
  Console.WriteLine(myDicionary.Count)
 if (myDictionary.ContainsKey(key))
   myDictionary.TryGetValue(key, out store);
}

Out of nowhere I see the same dictionary containing the keys that were not found in the prior code. Now you guys can argue that what happened was the I/O delay caused enough time for the dictionary to store some values, but I donot have any timeouts or something that causes me to loose any processing, what this means till the dictionary contains some values to be extracted, next processing step will not occur and my program will wait till it gets some values. But unfortunately, this does not happen unless I put a Console.WriteLine... Anyone faced such situation before?