text:
Q: Updating UI from a background thread which is called in a loop in main UI when the thread finishes I have a WinForms application that is calling a business class method that performs some heavy duty action taking about 5 seconds for each call. The main form calls this method in a loop. This loop can run from 10 times to maybe up to 10 thousand times.
The WinForms application sends a parameter to the business class and has an area to display the time taken for each method call and what the value returned by the method. How do I inform my main window and update a text area in the main winform with what the method has returned for each call?
Currently the data comes all at once after all the threads have finished. Is there a way to update the UI for all the iterations of the loop once the each call is done? I don't mind if it is done sequentially also.
The FORM
    HeavyDutyClass hd;
    public Form1()
    {
        InitializeComponent();
        hd = new HeavyDutyClass();
    }

    //BUTTON CLICK
    private void Start_Click(object sender, EventArgs e)
    {

        int filecount = 5000;  //BAD - opening 5000 threads! Any other approach?
        hd.FileProcessed += new EventHandler(hd_FileProcessed);

        var threads = new Thread[filecount];

        for (int i = 0; i < filecount; i++)
        {
            threads[i] = new Thread(() => { hd.LongRunningMethod(); });
            threads[i].Start();
        }

    }

    //BUSINESS CLASS EVENT THAT FIRES WHEN BUSINESS METHOD COMPELTES
    void hd_FileProcessed(object sender, EventArgs e)
    {

        if (dgv.InvokeRequired)
        {
            dgv.Invoke((MethodInvoker)delegate { UpdateGrid(); });

        }
    }

    private void UpdateGrid()
    {
        dgv.Rows.Add(1);
        int i = dgv.Rows.Count;
        dgv.Rows [ i-1].Selected = true;
        dgv.FirstDisplayedScrollingRowIndex = i - 1;

    }

The business HeavyDuty class
    public event EventHandler FileProcessed;

    public HeavyDutyClass()
    {
    }

    protected virtual void OnMyEvent(EventArgs e)
    {
        if (FileProcessed != null)
        {
            FileProcessed(this, e);
        }
    }

    public bool LongRunningMethod()
    {
        for (double i = 0; i < 199990000; i++)
        {
            //time consuming loop
        }
        OnMyEvent(EventArgs.Empty);
        return true;
    }

A: Add a Winforms Project, Drop a Label Control on the Form , Copy-Paste this code and Hit F5
[EDIT]: Updated with the business class comment from the user
NB: My form class is named Form3. You may have to change your Program.cs or vice-versa.
using System.ComponentModel;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public class BusinessClass
    {
        public int MyFunction(int input)
        {
            return input+10;
        }
    }

    public partial class Form3 : Form
    {
        private BackgroundWorker _worker;
        BusinessClass _biz = new BusinessClass();
        public Form3()
        {
            InitializeComponent();
            InitWorker();
        }

        private void InitWorker()
        {
            if (_worker != null)
            {
                _worker.Dispose();
            }

            _worker = new BackgroundWorker
            {
                WorkerReportsProgress = true,
                WorkerSupportsCancellation = true
            };
            _worker.DoWork += DoWork;
            _worker.RunWorkerCompleted += RunWorkerCompleted;
            _worker.ProgressChanged += ProgressChanged;
            _worker.RunWorkerAsync();
        }

        void DoWork(object sender, DoWorkEventArgs e)
        {
            int highestPercentageReached = 0;
            if (_worker.CancellationPending)
            {
                e.Cancel = true;
            }
            else
            {
                double i = 0.0d;
                int junk = 0;
                for (i = 0; i <= 199990000; i++)
                {
                    int result = _biz.MyFunction(junk);
                    junk++;

                    // Report progress as a percentage of the total task.
                    var percentComplete = (int)(i / 199990000 * 100);
                    if (percentComplete > highestPercentageReached)
                    {
                        highestPercentageReached = percentComplete;
                        // note I can pass the business class result also and display the same in the LABEL
                        _worker.ReportProgress(percentComplete, result);
                        _worker.CancelAsync();
                    }
                }

            }
        }

        void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                // Display some message to the user that task has been
                // cancelled
            }
            else if (e.Error != null)
            {
                // Do something with the error
            }
        }

        void ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            label1.Text =  string.Format("Result {0}: Percent {1}",e.UserState, e.ProgressPercentage);
        }
    }
}

With this you can achieve Cancel functionality also very easily.
Observe that during initialisation, I set the WorkerSupportsCancellation = true & then I check for _worker.CancellationPending in the DoWork. So, if you want to cancel the process by a Cancel Button click, then you will write this code in the button handler- _worker.CancelAsync();


text:
Q: Jwt Token not provide current user details I have created a demo application in .net core 2.0 with https://auth0.com/blog/securing-asp-dot-net-core-2-applications-with-jwts/ This is an example for Authentication with JWT Token, but I noticed that when I create a token for one user and replace it with another token created for another user (from other browser), it will validate and allow access. Why?
Also if anyone has a good example of JWT token with current user logged in then please share the link, as I am new to this.

A: That's how the Bearer authentication schema works.

The server's protected routes will check for a valid JWT in the Authorization header, and if it's present, the user will be allowed to access protected resources.

(from :How do JSON Web Tokens work?)
So everyone who can present a valid and not expired token will get access to your protected resources. There's usually no check if the token was originally issued to you or to someone else.
You are of course free to implement such a check:

*

*find something that can't be forged to identify the device and is present on every request

*add this information or better a hashed value as a claim to the token. You're free to add claims (basically just key/value pairs) to your token.

*write your own custom authorization attribute and check if the request comes from the same device as stated in the respective claim in the JWT.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the timestamp from this string / laravel This text is saved all in one column in database table. I want to take the time-stamp from the chat replies. Is there any command who can split the string and get the time-stamp.
The chat starts from here:____________________________________________________________________________
Hi Guest 4878,
Thank you for chatting with us. Please find your chat transcript below.
Date: 2017-02-07
Name: Guest 4878
Email:
Topic:
Chat reference number: 11701
| 07.02.2017 13:46:36 | Guest 4878: Anybody here?
| 07.02.2017 13:46:52 | Admin: Hello, how may I help you?

A: You can use Carbon For that:
\Carbon\Carbon::parse($yourTimestamp)->format('H:i:s');

Or like this:
\Carbon\Carbon::parse($yourTimestamp)->timestamp;

A: Try
$time = \Carbon\Carbon:::createFromFormat('d.m.Y H:i:s', '07.02.2017 13:46:36');

//Or using model
$time = \Carbon\Carbon:::createFromFormat('d-m-Y H:i:s', $model->datetime);

//display timestamp
echo $time->timestamp;


text:
Q: How to calculate percentage with a SQL statement? i have two sql tables i want to compare two  tables ..comparing two tables is done now what i want is how many records are matched and not matched in the form of percentage .is it possible to write a query in sql to get percentage?
 and here is my tables
  src_table

----------------------------------------------------------------
src_table
----------------------------------------------------------------
1
2
3
a
b
c
a@
b@
c@
-----------------------------------------------------------------

and tgt_table is
-----------------------------------------------------------------
tgt_data
-----------------------------------------------------------------
1
4
5
a
e
f
a@
e@
f@
--------------------------------------------------------------------

and now i want matched data and unmatched in the form of percentage is it possible?

A: I assume you wish to calculate the percentage over the table tgt_data.
If this is not the case, just exchange the table names below.
The query depends on the capabilities of your SQL product.
If it cannot handle complex expressions with sub-queries, you will need
to break the expression into multiple statements.
The expression you would like to calculate is:
(select count(*) * 100 from tgt_data t where exists
  (select * from src_table where src_col = t.tgt_col))
/
(select count(*) from tgt_data)

If you need to formulate it as one SELECT statement, this is an alternate formulation:
select
(select count(*) * 100 from tgt_data t where exists
  (select * from src_table where src_col = t.tgt_col))
/ count(*)
from tgt_data

If your product calculates this in integer arithmetic, and you would like
the result in decimal, then replace 100 by 100.0 above.


text:
Q: Oracle MONTHS_BETWEEN to return a whole number I have an Oracle Select statement, and inside it I have the following:
MONTHS_BETWEEN(CON.F_CON_END_DATE, TRUNC(SYSDATE)) MONTHSTOEXPIRE,

The aim of that code is to get me the number of months between two dates. It does work, but it returns them in a way that is breaking my VB.NET code. Something about an overflow exception!
It returns 1.83870967741935 and I expect a 2?
What can I do to make my query return the nearest whole number for the MONTHSTOEXPIRE value?

A: I'm guessing you simply need to use the round() function?
ROUND(MONTHS_BETWEEN(CON.F_CON_END_DATE, TRUNC(SYSDATE)), 0) MONTHSTOEXPIRE

It works on my Oracle.
Let me know if it works on yours!

A: You can try

*

*Math.Round,

Rounds a value to the nearest integer or to the specified number of fractional digits.

*Math.Ceiling

Returns the smallest integer greater than or equal to the specified number.

*Math.Floor.

Returns the largest integer less than or equal to the specified number.

A: use like this
round(MONTHS_BETWEEN('29-Jun-2014', TRUNC(SYSDATE))) MONTHSTOEXPIRE
since you cannot always get exact month count, you can get the exact value and round it to the nearest integer


text:
Q: Python pandas: Getting the locations of a value in dataframe Suppose I have the following dataframe:
   'a' 'b'
0   0   0
1   1   0
2   0   1
3   0   1

Is there a way I could get the index/column values for which a specific value exists? For example, something akin to the following:
values = df.search(1)

would have values = [(1, 'a'), (2, 'b'), (3, 'b')].

A: If you don't mind working with a NumPy array with the first column expressing the index location and the second column expressing the index of the column name as it resides in df.columns, then it's very short:
In [11]: np.argwhere(df)
Out[11]:
array([[1, 0],
       [2, 1],
       [3, 1]])

If you want to format this into the list of tuples with actual column names, you can further do:
In [12]: [(x, df.columns[y]) for x,y in np.argwhere(df)]
Out[12]: [(1, 'a'), (2, 'b'), (3, 'b')]

You can use this same approach with logical expressions inside of np.argwhere, so for example say you have this DataFrame of some random data:
In [13]: dfrm
Out[13]:
          A         B         C
0  0.382531  0.287066  0.345749
1  0.725201  0.450656  0.336720
2  0.146883  0.266518  0.011339
3  0.111154  0.190367  0.275750
4  0.757144  0.283361  0.736129
5  0.039405  0.643290  0.383777
6  0.632230  0.434664  0.094089
7  0.658512  0.368150  0.433340
8  0.062180  0.523572  0.505400
9  0.287539  0.899436  0.194938

[10 rows x 3 columns]

Then you could do this for example:
In [14]: [(x, dfrm.columns[y]) for x,y in np.argwhere(dfrm > 0.8)]
Out[14]: [(9, 'B')]

As a search function, it can be defined like this:
def search(df, df_condition):
    return [(x, df.columns[y]) for x,y in np.argwhere(df_condition(df))]

For example:
In [17]: search(dfrm, lambda x: x > 0.8)
Out[17]: [(9, 'B')]

In [18]: search(df, lambda x: x == 1)
Out[18]: [(1, 'a'), (2, 'b'), (3, 'b')]

A: df[df == 1].stack().index.tolist()

yields
[(1, 'a'), (2, 'b'), (3, 'b')]

A: use pd.melt + some other munging.
import pandas as pd

df = pd.DataFrame({'a':[0,1,0,0],
                    'b':[0,0,1,1]})

df1 = pd.melt(df.reset_index(),id_vars=['index'])
df1 = df1[df1['value'] == 1]
locations = zip(df1['index'],df1['variable'])

Output:
[(1, 'a'), (2, 'b'), (3, 'b')]


text:
Q: Manipulating xpath in order to post data to a sheet in Selenium with Java I wonder if it is possible to use an index to increase the range of the xpath of a given sheet to fill a given sheet using Java and Selenium

I'm working with a 3 x 3 matrix-sheet and i want to insert data to
different columns:

The XPATH of the first box and first column is this:
//*[@id="grid"]/table/tbody/tr[3]/td[3]/input

The XPATH of the second box and first column is this:
 //*[@id="grid"]/table/tbody/tr[4]/td[3]/input

The XPATH of the third box and first column is this:
//*[@id="grid"]/table/tbody/tr[5]/td[3]/input

The XPATH of the fourth box and first column is this:
//*[@id="grid"]/table/tbody/tr[6]/td[3]/input

The XPATH of the fifth box and first column is this:
//*[@id="grid"]/table/tbody/tr[7]/td[3]/input

So, the pattern says that "tr" is the box number of each column "td"
Take a look at this picture (i cannot upload images yet):
image

The third column has these Xpath:
The XPATH of the first box and third column is this:
//*[@id="grid"]/table/tbody/tr[3]/td[5]/input

The XPATH of the second box and third column is this:
//*[@id="grid"]/table/tbody/tr[4]/td[5]/input

The XPATH of the third box and third column is this:
//*[@id="grid"]/table/tbody/tr[4]/td[5]/input

The XPATH of the fourth box and third column is this:
//*[@id="grid"]/table/tbody/tr[4]/td[5]/input

The XPATH of the fifth box and third column is this:
//*[@id="grid"]/table/tbody/tr[4]/td[5]/input

Take a look at this picture:
image

My question is how can i post data from a data-set and paste it in the different boxes? How can i manipulate the xpath?
I mean, i want to paste these values:
[{1,2},{3,4},{90,90},{143,234},{09,89}]

Expected result:
[1  |  |2  ]
[3  |  |4  ]
[90 |  |90 ]
[143|  |243]
[09 |  |89 ]

Is it possible to put an index on the xpath?:
//*[@id="grid"]/table/tbody/tr[i]/td[j]/input

This is how i post data but it is harcoded:
driver.findElement(By.xpath("//*[@id=\"grid\"]/table/tbody/tr[3]/td[3]/input")).sendKeys("1");
driver.findElement(By.xpath("//*[@id=\"grid\"]/table/tbody/tr[4]/td[3]/input")).sendKeys("3");
driver.findElement(By.xpath("//*[@id=\"grid\"]/table/tbody/tr[5]/td[3]/input")).sendKeys("90");
driver.findElement(By.xpath("//*[@id=\"grid\"]/table/tbody/tr[6]/td[3]/input")).sendKeys("143");
driver.findElement(By.xpath("//*[@id=\"grid\"]/table/tbody/tr[7]/td[3]/input")).sendKeys("09");
driver.findElement(By.xpath("//*[@id=\"grid\"]/table/tbody/tr[3]/td[5]/input")).sendKeys("2");
driver.findElement(By.xpath("//*[@id=\"grid\"]/table/tbody/tr[4]/td[3]/input")).sendKeys("4");
driver.findElement(By.xpath("//*[@id=\"grid\"]/table/tbody/tr[5]/td[5]/input")).sendKeys("90");
driver.findElement(By.xpath("//*[@id=\"grid\"]/table/tbody/tr[6]/td[3]/input")).sendKeys("243");
driver.findElement(By.xpath("//*[@id=\"grid\"]/table/tbody/tr[7]/td[5]/input")).sendKeys("89");

How can i post the data by using the collection and indexes on the xpath?

A: Sounds like you want to do something like this:
int[] rows = new int[]{3, 4, 5, 6, 7, 3, 4, 5, 6, 7};
int[] columns = new int[]{3, 3, 3, 3, 5, 3, 5, 3, 5};
int[] data = new int[]{1, 3, 90, 143, 90, 2, 4, 90, 243, 89};

for (int i = 0; i < data.length; i++) {
    driver.findElement(By.xpath("//*[@id=\"grid\"]/table/tbody/tr["+rows[i]+"]/td["+columns[i]+"]/input")).sendKeys(""+data[i]+"");
}

(Ofcourse this is far from optimal, since everything is still hardcoded.)


text:
Q: How to combine multiple rows into one row in hql? Here is the case, lets say 3 tables, class, student, and grade.
Relation:  class 1:many students,  students many: 1 grade.
Meaning: one student can only attend one class, one class might have multiple students. And One student can only have one grade.
Entities:  I just simplify them
Class class{
   private int id;
   private String name;
   private Set<Students> students;
   //getter setter
}

Class student{
   private int id;
   private String name;
   private Class  class;
   private Grade grades
   //getter setter
}

Class Grade{
   private int id;
   private char grade;
   private Set<Student> students;
   //getter setter
}

I also have a result class:
 Class Result{
     private String name;
     private String status;
     private String grade;
     private long count;
     public Result(name,status){ //omit}
     public Result(name,grade,count){ //omit}
     //getter setter
 }

Now to find number of grades each class has:
class    grade   count
math      A      2
math      B      10
science   A      2
ans so on

the hql I am using:
@Query("select new Result(class.name, grade.grade, count(*) as numOfCount) from Class class
left join class.students as student
left join student.grade as grade
group by class.name, grade.grade order by class.name");
public List<Result> findResult(Pagable pagable);

This hql will product list of result object like above with pagination, and I can loop through to get each result. Now for display reason, I want to have something like this:
class       status
math      A,2 | B, 1
science      A, 2

What should I add to the above hql to have a such result? I have to product something like that in hql, I can't do it in Java. Reason is because of pagination.
Let me explain: if now the page size is 2, and we just use the above hql, we will get:
 class    grade   count
    math      A      2
    math      B      10

and in Java we make it into math A,2 | B, 1, this will only show one row, but we need 2.

If hql is not possible, how can I do it in native query. I checked on sql, it has listagg.
 @Query(value="select name, listagg(status,'|') within group(order by status)
       from (select cl.name, gr.grade|| ',' ||count(*) as status from CLASS cl,
               Grade gr, Student, st
               where cl.classId = st.classId and gr.studentId= st.studentId
               group by cl.name,  gr.grade order by cl.name
       ) group by name", nativeQuery=true)
  public list<Result> findResult();

This native oracle sql will give desired result, I test it in oracle sql developer. But in spring, I have trouble convert it into Result object. It gives can't not convert to Result exception.
Please help. Either help native query or hql will do the job. Thanks in advance.

A: You can try to change return-type to List in last findResult() (I think it will be List<Object[]> or something like that) and than transform result in List<Result> by for-loop.
Or you can use SqlResultSetMapping for your native query mapping.


text:
Q: Публикация результата через Facebook SDK для Unity: как получить разрешение на publish_actions? До публикации приложения нужно протестировать отправку результатов игр в Facebook.
Для этого надо получить разрешение на publish_actions, что у меня сделать не вышло.
Создал в Facebook свое приложение, вызываю такой код:
List<string> publishPermissions = new List<string>{ "publish_actions" };
FB.LogInWithPublishPermissions(publishPermissions, callback);

Мне в редакторе Unity показывают модальное окно Facebook, в нем щелкаю на Find Access Token:

Перехожу в Facebook, там копирую User Token:

Вношу его в прежде упомянутое окно Unity и нажимаю Send Success:

В результате среди разрешенных permission нет publish_actions и среди отклоненных тоже:

Что я не так настроил?

A: Для того, чтобы получить право publish_actions, нужно проходить ревью приложения на Facebook

A: Нашел - чтобы получить право publish_actions без прохождения ревью приложения надо:

*

*Пройти по https://developers.facebook.com/tools/explorer/

*Выбрать свое приложение из выпадающего списка справа сверху

*Нажать Get Access Token

*Выбрать разрешения, которые нужны

*Использовать этот токен

*Если надо можно увеличить срок действия токена до нескольких месяцев, вместо нескольких часов - идем по адресу https://developers.facebook.com/tools/accesstoken/

*Нажимаем на Debug напротив User Token, а далее - кнопку Extend Access Token


text: Q: Why my iBook G4 superdrive spits out the Mac OS X Leopard Install Disk? The SuperDrive of my late 2005 iBook G4 died, so I installed a new one. But now the new drive does not mount the Leopard Install Disk. But it mounts any other DVDs/CDs (music, movies). The disk mounts on my MacBook Pro. Can anyone answer me why it is happening ?


text:
Q: python:use a function to remove a list element,I get confused with the result def testf(st):
    st=st[1:]
    print st
def popf(st):
    st.pop(0)
    print st
a = ["response", ["wis", "hello"], ["deng", "shen"]]
testf(a)
print a
a = ["response", ["wis", "hello"], ["deng", "shen"]]
popf(a)
print a

Below is the output:
[['wis', 'hello'], ['deng', 'shen']]
['response', ['wis', 'hello'], ['deng', 'shen']]
[['wis', 'hello'], ['deng', 'shen']]
[['wis', 'hello'], ['deng', 'shen']]

I want to use a function to delete a list element, but I'm confused why the function testf() can't delete the element after the function but the popf() function can do. what's the difference? if not in the function, st=st[1:] = st.pop(0) (del st[0] also works).

A: In first function you are assigning a new value to st in this statement so it is a completely new variable and not the one passed as the argument:
st = st[1:]

You can check it using id before and after assignment:
In [13]: def testf(st):
   ....:     print('before: ', id(st))
   ....:     st = st[1:]
   ....:     print('after: ', id(st))
   ....:

In [14]: a = ["response", ["wis", "hello"], ["deng", "shen"]]

In [15]: id(a)
Out[15]: 85287112L

In [16]: testf(a)
('before: ', 85287112L)
('after: ', 85289480L)

But in the second function there is no assignment hence the id remains same. It means you modified the list passed in the arguments:
In [17]: def popf(st):
   ....:     print('before: ', id(st))
   ....:     st.pop(0)
   ....:     print('after: ', id(st))
   ....:

In [18]: popf(a)
('before: ', 85287112L)
('after: ', 85287112L)

A: popf mutates the st list that it is passed. testf does not: it simply overwrites the name with another list that is a copy without the first element.


text:
Q: How to mock query for joined tables in SQLAlchemy and alchemy-mock when where-statement filters data from multiple tables? I have schema:
CREATE SCHEMA problem AUTHORIZATION blockchain;

CREATE TABLE problem.users (
    id serial PRIMARY KEY NOT NULL,
    nick varchar NOT NULL
);

CREATE TABLE problem.passwords_keys (
    id serial PRIMARY KEY NOT NULL,
    user_id serial references problem.users,
    password varchar NOT NULL,
    valid bool NOT null DEFAULT TRUE
);

For the schema I've generated SLQAlchemy classes with sqlacodegen:
export DB_PASSWORD=...
export DB_USER=...
sqlacodegen "postgresql://${DB_USER}:${DB_PASSWORD}@localhost/default_database --schema problem | tee schema.py
# coding: utf-8
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, text
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
metadata = Base.metadata

class User(Base):
    __tablename__ = 'users'
    __table_args__ = {'schema': 'problem'}

    id = Column(Integer, primary_key=True, server_default=text("nextval('problem.users_id_seq'::regclass)"))
    nick = Column(String, nullable=False)

class PasswordsKey(Base):
    __tablename__ = 'passwords_keys'
    __table_args__ = {'schema': 'problem'}

    id = Column(Integer, primary_key=True, server_default=text("nextval('problem.passwords_keys_id_seq'::regclass)"))
    user_id = Column(ForeignKey('problem.users.id'), nullable=False, server_default=text("nextval('problem.passwords_keys_user_id_seq'::regclass)"))
    password = Column(String, nullable=False)
    valid = Column(Boolean, nullable=False, server_default=text("true"))

    user = relationship('User')

Those classes I want to mock to perform query:
SELECT p."password" "password" FROM
    problem.passwords_keys p
    JOIN problem.users u ON(p.user_id=u.id)
    WHERE p."valid" = true AND u.nick = 'Bush';

So I've created code:
from mock_alchemy.mocking import UnifiedAlchemyMagicMock  # pip3 install mock-alchemy
from unittest import mock
import schema

nick = 'Bush'

session = UnifiedAlchemyMagicMock(data=[
    (
        [
            mock.call.query(schema.PasswordsKey),
            mock.call.join(schema.User),
            mock.call.filter(schema.PasswordsKey.valid == True),
            mock.call.filter(schema.User.nick == nick),
        ],
        [schema.PasswordsKey(id=2, user_id=22, password='qwerty1', valid=True)]
    ),
])

keys_for_user = session.query(schema.PasswordsKey)\
    .join(schema.User)\
    .filter(schema.PasswordsKey == True)\
    .filter(schema.User.nick == nick)
password = keys_for_user.first().password
print(f'1. Found private key {password} by nick "{nick}"')

But it is not working:
Traceback (most recent call last):
  File "/home/agh/Pulpit/blockchain/watra-ledger/src/stack/mock.py", line 32, in <module>
    password = keys_for_user.first().password
AttributeError: 'NoneType' object has no attribute 'password'

What is interesting that when I do not filter with another table - everything is working:
from mock_alchemy.mocking import UnifiedAlchemyMagicMock  # pip3 install mock-alchemy
from unittest import mock
import schema

session = UnifiedAlchemyMagicMock(data=[
    (
        [
            mock.call.query(schema.PasswordsKey),
            mock.call.join(schema.User),
            mock.call.filter(schema.PasswordsKey.valid == True),
         ],
        [schema.PasswordsKey(id=1, user_id=11, password='qwerty', valid=True)]
    ),
])

keys_for_user = session.query(schema.PasswordsKey)\
    .join(schema.User)\
    .filter(schema.PasswordsKey.valid == True)
row = keys_for_user.first()
print(f'2. Found valid password "{row.password}"')

And the result is:
2. Found valid password "qwerty"

Another solution which I found is not to mock filtering, but it looks dirty for me (IMO the code is to just make tests pass not to test):
from mock_alchemy.mocking import UnifiedAlchemyMagicMock  # pip3 install mock-alchemy
from unittest import mock
import schema

nick = 'Bush'

session = UnifiedAlchemyMagicMock(data=[
    (
        [
            mock.call.query(schema.PasswordsKey),
            mock.call.join(schema.User),
            # mock.call.filter(schema.PasswordsKey.valid == True),
            # mock.call.filter(schema.User.nick == nick),
         ],
        [schema.PasswordsKey(id=1, user_id=11, password='qwerty', valid=True)]
    ),
])

keys_for_user = session.query(schema.PasswordsKey)\
    .join(schema.User)\
    .filter(schema.PasswordsKey == True)\
    .filter(schema.User.nick == nick)
password = keys_for_user.first().password
print(f'3. Found private key {password} by nick "{nick}"')

Unfortunately I need to filter by user nick and there must be some way to make this working.

A: I've finally found out - there is no problem with querying joined tables - it is problem that mock.call.filter should be called once even for multiple filters.
So instead of:
session = UnifiedAlchemyMagicMock(data=[
    (
        [
            mock.call.query(schema.PasswordsKey),
            mock.call.join(schema.User),
            # mock.call.filter(schema.PasswordsKey.valid == True),
            # mock.call.filter(schema.User.nick == nick),
         ],
        [schema.PasswordsKey(id=1, user_id=11, password='qwerty', valid=True)]
    ),
])

We should do:
session = UnifiedAlchemyMagicMock(data=[
    (
        [
            mock.call.query(schema.PasswordsKey),
            mock.call.join(schema.User),
            mock.call.filter(schema.PasswordsKey.valid == True,
                             schema.User.nick == nick),
         ],
        [schema.PasswordsKey(id=1, user_id=11, password='qwerty', valid=True)]
    ),
])

Link to example in official documentation.


text:
Q: How to change size of title's text on Action Bar? There is an ActionBar on each Android 4.0 application, and it got a title. I need to make this size less. But I don't understand how I can do it, because ActionBar doesn't provide public methods for it. Remark: I don't want to use custom views.

A: on my system, res/styles AppTheme has a note saying
<!-- All customizations that are NOT specific to a particular API-level can go here. -->

and this is the style indicated in AndroidMainfest.xml.  I added
<item name="android:textSize">15sp</item>

and it worked and I'd rather do this than a custom actionbar.

A: I have followed this method to skip the creation of custom style:

*

*Create a custom layout with required text size and

*apply that to your action bar.

1) Create a layout file (titlebar.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/action_bar_title"
        android:text="@string/app_name"
        android:textColor="@color/colorPrimary"
        android:textSize="24sp" />
</LinearLayout>

Here set your required textSize.
2) MainActivity.java
    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); //bellow setSupportActionBar(toolbar);
    getSupportActionBar().setCustomView(R.layout.titlebar);

hope this helps.

A: Actually, you can do what you want to customize the ActionBar. It must be done through the Theme. You can do something like this :
<style name="Theme.YourTheme" parent="android:style/Theme">
    <item name="android:actionBarStyle">@style/Theme.YourTheme.Styled.ActionBar</item>
</style>

<style name="Theme.YourTheme.Styled.ActionBar">
    <item name="android:titleTextStyle">@style/Theme.Viadeo.Styled.YourTheme.TitleTextStyle</item>
</style>

<style name="Theme.YourTheme.Styled.ActionBar.TitleTextStyle" parent="@android:style/Widget.TextView">
    <item name="android:textSize">12sp</item>
</style>

A: The text's size in Android ActionBar is standard.
Since ICS, Android now develops a standard so that applications will (hopefully) follow the same UI guidelines and design principles.
http://developer.android.com/guide/practices/ui_guidelines/index.html
This is why you can't change it.
However, if you still want to do so, you could use a custom Theme or maybe implement ActionBar (a fork) and modify its sources: https://github.com/johannilsson/android-actionbar to get maximum control.

A: You could always do something like this:
ActionBar actionBar = getActionBar();
actionBar.setTitle(Html.fromHtml("<small>YOUR TITLE</small>"));

A: You can use
subtitle:"exsample"

XML
 <androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    android:theme="?attr/actionBarTheme"
    app:subtitle="subTitle"
    app:title = "Title"
    android:tag="dff"/>

JAVA
getSupportActionBar.setSubtitle("Sub Title");


text:
Q: Tuxguitar 1.3.1 no sound ubuntu 14.04 Once again, no sound in Tuxguitar. Before it updated, the TiMidity fix worked, running through the Gervill midi port. However, in the new tuxguitar update, that port is gone, along with the sound.
I have the alsa, oss, and jsa plugins installed and selected. I've tried what every other post on here has said, but I think this is a new issue arising from the 1.3.1 update.
Any help would be greatly appreciated!

A: The same happened to me, and the only way I could make it work was installing the 1.3.2 version from sourceforge.
If you want to do it, it's easy with a couple of hints.
Installing
After compiling it myself, I realised there's another tar already compiled here. Click on the tuxguitar-1.3.2-linux-x86_64.tar.gz.
Unpack somewhere, and you will see a tuxguitar.sh inside. Launching with ./tuxguitar.sh everything works. By default it uses the "Gervill" thing that other answers say to use.
Compiling tuxguitar from source
warning: I only recommend this if no other option worked. I guess there are other easier ways.
You will need mvn (sudo apt-get install maven), and a java version installed (it's likely you already have java 7 or 8, type java -version to find out).
At the moment, as the ubuntu package only lists up to 1.3.1, uninstall your current tuxguitar (and all the plugins).
Once you have downloaded the tar, this is what I did. I'm sure there are better ways, but this worked:

tar zxvf tuxguitar-1.3.2-src.tar.gz
cd tuxguitar-1.3.2-src/build-scripts/tuxguitar-linux-x86_64-deb/
mvn install -DskipTests
cd target/
sudo dpkg --install tuxguitar-1.3.2-linux-x86_64.deb
/opt/tuxguitar/tuxguitar.sh


text:
Q: How to avoid multiple nodes with the same tag in xml with namespace using jQuery 'find'? I have the following XML
<ProjectResponse xmlns="Services.Messages" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Projects xmlns:a="Services.DTO">
    <a:Project>
      <a:ID>113</a:ID>
      <a:Name>Test project</a:Name>
      <a:Documents>
        <a:ProjectDocument>
          <a:FileName>DS.docx</a:FileName>
          <a:ID>65</a:ID>
          <a:ProjectID>113</a:ProjectID>
        </a:ProjectDocument>
      </a:Documents>
    </a:Project>
  </Projects>
</ProjectResponse>

When i perform $(this).find('[nodeName=a:ID]') in 'each' function i get 2 IDs, one from Project and another from Document.
$(projectsXml).find('Projects').children().each(function() {
            var projectId = $(this).find('[nodeName=a:ID]').text();

The question is how can i get only Project ID, not Document ID and another IDs that can occur ?

A: Use .children() instead of .find() inside as well, so it only looks for immediate children, like this:
$(projectsXml).find('Projects').children().each(function() {
  var projectId = $(this).children('[nodeName=a:ID]').text();
});


text:
Q: Dependency injection in a class not working on a worker service Is there a way to DI something into a class?
For example,
I have a .net 6 worker service that looks like the following:
Startup:
IConfiguration builder =
    new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", false, true)
    .AddEnvironmentVariables()
    .Build();

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddHostedService<Worker>();
        services.AddSingleton(mapper);

        services.AddScoped<MpwContext>(
            serviceProvider =>
            {
                return new MyDBContext(builder.GetSection("MyDBConnectionString").Value.ToString());
            });
    }

Worker.cs:
      public Worker(ILogger<Worker> logger, IConfiguration configuration, IMapper mapper)
        {
            //All the constructor stuff here
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var partService = new PartService();

            await partService.DoSomething();
        }

PartService:
       public PartService(IMapper mapper, MyDbContext myDbContext)
        {
            _mapper = mapper;
            _myDbContext = myDbContext;
        }

        public async Task DoSomething()
        {
        }

The issue I am facing is where I say : var partService = new PartService();  It is telling me that I am missing all the paramters in the constructor.
There is no argument given that corresponds to the required field MyDbContext and mapper....
I know with mvc the constructors pick up on the DI stuff on its own, how can I do that in this case?
The Databases are scoped so I cannot consume them directly in the worker, so I need to DI them in to each respective service. But its asking for them on the object creation.

A: You've almost got it.
It's normal for background services to be singletons (and thus only allow singleton dependencies). By default, there's no DI scope within ExecuteAsync, but you can create your own:
private readonly IServiceProvider _serviceProvider;

public Worker(IServiceProvider serviceProvider, ILogger<Worker> logger, IConfiguration configuration, IMapper mapper)
{
  _serviceProvider = serviceProvider;
  ...
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
  using var scope = _serviceProvider.CreateScope();

  // Not working yet:
  var partService = new PartService();
  await partService.DoSomething();
}

The other thing you need to know is that the .NET DI is rather simple-minded. The common pattern is to explicitly register every single type you need, including types that only have a single constructor:
services.AddHostedService<Worker>();
services.AddSingleton(mapper);

services.AddScoped<MpwContext>(
    serviceProvider =>
    {
      return new MyDBContext(builder.GetSection("MyDBConnectionString").Value.ToString());
});
services.AddScoped<PartService>();

Now that you've defined PartService as a scoped service, you can ask the DI to create an instance for you:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
  using var scope = _serviceProvider.CreateScope();

  var partService = scope.ServiceProvider.GetRequiredService<PartService>();
  await partService.DoSomething();
}


text:
Q: fabric js how to use globalCompositeOperation in groups I am trying to create groupe using fabricjs
var group = new fabric.Group(
   [ circle, this.callerObject ],
   {globalCompositeOperation:'xor'}
);
console.log(group);
this.mainCanvas.add(group);

But which globalCompositeOperation I have not set it is not working it always give the same result. I can make it using clear canvas, but I want to know, can I do it using native fabricjs methods?

A: I find solution myself)) to make it work need add globalCompositeOperation to the second object.
 this.callerObject.set('globalCompositeOperation','xor');
 var group = new fabric.Group(
   [ circle, this.callerObject ]
);

But it have new problem)) this is work across all images)
To solve problem with cross showing
I have convert group to dataUrl, and to save state of object create new group, with object and image from previous group.
createXorGroup: function(object){
        var self = this;
        var baseStateTop = this.callerObject.top;
        var baseStateLeft = this.callerObject.left;
        this.callerObject.set('globalCompositeOperation','xor');
        this.callerObject.set('active', false);
        var group = new fabric.Group([ object, this.callerObject ]);
        fabric.Image.fromURL(
            group.toDataURL(),
            function(image){
                image.setOriginToCenter && image.setOriginToCenter();
                self.callerObject.set('globalCompositeOperation','source-over');
                self.callerObject.set('opacity', 0);
                group = new fabric.Group([ self.callerObject, image ]);
                self.mainCanvas.add(group);
                group.setOriginToCenter && group.setOriginToCenter();
                group.set('top', baseStateTop).set('left', baseStateLeft).setCoords();
                group.setCenterToOrigin && group.setCenterToOrigin();
                self.mainCanvas.remove(self.callerObject);
                group.inCircle = true;
                group.set('active', true);
            },
            {
                originX: 'center',
                originY: 'center',
                top: this.callerObject.top,
                left: this.callerObject.left
            }
        );
    }
It is not native fabricjs object, I have override some properties for my work, but I hope you understand the main aim and it will be helpful
Continue to work with this library
To make xor to svg I have write this:
setGlobalCompositeOperation: function(object, type){
        if(object.imageType == 'svg'){
            for (var i = 0; i < object.paths.length; i++) {
               this.setGlobalCompositeOperation(object.paths[i], type);
            }
        }else{
            object.set('globalCompositeOperation', type);
        }
    }
But this do not work for text in mozila 31.6.0(( I'm looking solution for text


text:
Q: ui-router dots in name not working The UI-Router docs shows that you can use dots in route name:

State 1

Show List

But however in my app this doesn't work. This is an example that worked fine until I changed client to client.ts everywhere:
<!DOCTYPE html>

    <title>AngularJS: UI-Router Quick Start</title>

    <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.min.css" rel="stylesheet">

      Quick Start

Home

Clients

Route 1

Plunker here: http://plnkr.co/edit/ZD7WlC9aKzpwte9dVMxC?p=preview
As you can see the link can't be clicked :/

A: What you need to do is add an abstract state for clien in that case.
Here's the plunkr, with the added state: plunkr
Whenever you define states with the dot. You still need to at least define the abstract state for the child. In your case for clien.
Also something from the docs

If you register only a single state, like contacts.list, you MUST define a state called contacts at some point, or else no states will be registered. The state contacts.list will get queued until contacts is defined. You will not see any errors if you do this, so be careful that you define the parent in order for the child to get properly registered.


text:
Q: Why my download speed is just half of the speed given by my Wi-Fi providing device in Ubuntu 20? I had just upgraded to Ubuntu 20 (focal fossa). When I try to download anything in any browser or through terminal, the downloading speed in my PC is just half of my Wi-Fi providing device.
Please clarify if it is just my myth or there is some technical error?
And there were no other apps running in background on both devices at that time. The Wi-Fi drivers are the one provided by Ubuntu 20 itself and my laptop is HP 15.
The image is showing the speed given by my WiFi providing device, it's 1.8MB/s

This image is showing the downloading speed in Firefox. Check the first one it's 792KB/s

A: The download speed you are currently seeing is not the limit provided by your provider. If you use some network speed monitoring tool, you will notice that value changes continously depending on what network process is running in the background. So assuming you have been provided with 19mbs, when the network traffic is pow you will see a small value in your speed infldicator but when you are having big network usage e.g. downloads, the value will go up depending on whats being downloaded at that time.
It is also good to note that some providers provide different limits for the upload and download speeds. e.g. 10mbs could be defined as 4mbps download and 6mbps upload.


text:
Q: Python: Elif and Else not working I'm constructing an interactive timetable for terminal with Python, but at the end of my code where i have if, elif and else statements no matter what user input i give it keeps passing the if statement. Any Solutions would be greatly appreciated and Thank You for your time :)
while True:
    TimeTable()
    print "\nDo you wish to go again? "
    answer = raw_input()
    if answer == "Yes" or "yes":
        print " "
        continue
    elif answer == "No" or "no":
        print "Ok then"
        break
    else:
        print "Ok then"
        break

A: answer == "Yes" or "yes"

# is the same as
(answer == "Yes") or "yes"

and is always True. You can solve your problem this way:
answer in ["Yes", "yes"]


text:
Q: HTML5 details element for accordion Is the details element semantically appropriate to markup an accordion?
Example:

Section 1

Section 2

Section 3

I ask this question because the spec isn't very clear about its usage. It just states the details element is a disclosure widget.
I certainly don't want to use the element for something that it's not meant to be.
EDIT
Would something like this be better suited semantically?

Section 1

Section 2

Section 3

Thanks!

A: Yes,  elements are entirely appropriate (and the most semantic option) for what you're describing:
From http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#the-details-element:

The details element represents a disclosure widget from which the
  user can obtain additional information or controls. [emphasis mine]

And this is from http://html5doctor.com/the-details-and-summary-elements/:

Essentially, we can use  to create an accordion-like widget that the user can toggle open and closed. Inside , we can put any sort of content we want.

Perfect usage. For example, my company has a contact page with many contact options so we could setup an accordion for it like so:

    Mailing Address

U.S. Correspondence: 123 Main St., Washington, DC 00000-0000

International Correspondence: P.O.Box 1111, Washington, DC 00000-1111

    Phone Numbers

U.S.: 800-555-5555

Int'l: +1-800-555-5556

A note on styling: good semantics shouldn't be thrown overboard to address browser-specific styling issues. A CSS Reset may be in order, but there's no semantic reason not to use these helpful and appropriate elements for an accordion.
**Do note: Chrome currently is the only browser that supports the toggling functionality that I believe the spec intended for these elements. A Javascript fallback would be useful here.
**Edit 3/2017 - See http://caniuse.com/#feat=details for support tables. This feature is now supported by almost all but IE and Edge.

A: Don't use  for this, or you'll have this problem:
Insane Chrome issue...Chrome renders twisties?
That's probably not desired behaviour for your accordion.

A: Nice question. I was searching for that and saw even MDN is using  for their sidebar menu of links. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details
However, there are two problems:
 isn't animateable
Since it's either open or not, there's no way to animate the transition - because there's no transition.
From MDN docs:

Unfortunately, at this time there's no built-in way to animate the
transition between open and closed.

No support for IE
If you care, it is not supported by Internet explorer :)


text:
Q: MongoDB $addToSet equivalent in CockroachDB As the title suggests, is there an operator similar to MongoDB's $addToSet in CockroachDB? I want to append a value to an array if it's not present.
I browsed the docs but didn't find an $addToSet operator.

A: The array_append function should work for this case, see this doc: https://www.cockroachlabs.com/docs/stable/array.html#using-the-array_append-function

A: You'll need two functions to do this with arrays. Either of these should work:
array_append(array_remove(myArray, newElement), newElement)
IF(array_position(myArray,newElement) IS NULL, array_append(myArray,newElement), myArray)

If what you're representing should never contain duplicates, you might be better off using a JSON object type than an array type, since their keys are automatically unique. Here's an example:
create table unique_groups(id int primary key, vals jsonb default '{}');

insert into unique_groups values (1, '{}'), (2, '{"a": true}');

-- Add "b" to each set
update unique_groups set vals = jsonb_set(vals, '{b}', 'true') where true;

select * from unique_groups;
  id |         vals
-----+-----------------------
   1 | {"b": true}
   2 | {"a": true, "b": true}

-- Add "a" to each set
update unique_groups set vals = jsonb_set(vals, '{a}', 'true') where true;

select * from unique_groups;
  id |          vals
-----+-------------------------
   1 | {"a": true, "b": true}
   2 | {"a": true, "b": true}


text:
Q: How to convert ndarray::ArrayView to &ndarray::Array without copying? I'm using the ndarray crate and I have a function that take a reference to Array2:
fn use_array(array: &Array2<u8>) {
    // ...
}

I'm trying to call this function with a view:
image.axis_iter(Axis(2)).for_each(|layer| {
    fun(&layer.to_owned());
});

It leads to an error:
   |
92 |         fun(&layer);
   |             ^^^^^^ expected struct `ndarray::OwnedRepr`, found struct `ndarray::ViewRepr`
   |
error: could not compile `poisson-editing`.
warning: build failed, waiting for other jobs to finish...
   = note: expected type `&ndarray::ArrayBase<ndarray::OwnedRepr<u8>, ndarray::dimension::dim::Dim<[usize; 2]>>`
              found type `&ndarray::ArrayBase<ndarray::ViewRepr<&u8>, ndarray::dimension::dim::Dim<[usize; 2]>>`

I can solve it by owning the array elements, but then I'm creating an unnecessary copy of the array.
image.axis_iter(Axis(2)).for_each(|layer| {
    use_array(&layer.to_owned());
});

Is there a way to avoid the copy here?

Update:
Now I consider it a foolish question. This conversion is not possible because you can not have &T without creating T. There is clearly no way to create Array2<u8> without retaining ownership over the underlying data. I deluded myself into thinking that it should be possible because both ArrayView and &Array does not own the data.

A: No, you can't obtain an &Array2<u8>, because an &Array2<u8> is always a reference to a full 2d array, while your layer contains additional metadata to identify the correct sections of the owned Array2 that are accessible.
However, you could do it the other way around: You can make use_array take an ArrayView2<u8> (if it's not part of some external code you depend on) and then change any calls that previously called use_array with a full 2d array reference to use_array(your_array2.view()).


text:
Q: How to pass an array of members of a struct as a parameter to a function? Here is my problem:
I have a struct:
struct point
{
    int x;
    int y;
};

and then I have an array:
for (int i = 0;i < n;i++)
{
    arr[i].x=rand() % n + 1;
}

I defined the quicksort function as follows:
 void quicksort(int *a, int left, int right);

and I want to sort the point by X coordinate, so I call the quicksort:
quicksort(arr.x, 0, n-1);

And this is the error message:

error: request for member 'x' in 'arr', which is of non-class type 'point [(((unsigned int)(((int)n) + -0x000000001)) + 1)]'

Sorry if the question is too stupid or badly formulated, the truth is I'm a newbie and I'm really willing to learn as much as possible and I'd be very thankful for your help!

A: If you always want to sort by x, then you can hard-code it into the sort function, and just pass a pointer to the array to sort:
void quicksort(point * arr, int left, int right) {
    // test points with
    // if (arr[i].x < arr[j].x) {/* i sorts before j */}
}

quicksort(arr, 0, n-1);

To specify a class member to sort by, you need a pointer-to-member, not a pointer; something like:
void quicksort(point * arr, int point::*member, int left, int right){
    // test points with
    // if (arr[i].*member < arr[j].*member) {/* i sorts before j */}
}

quicksort(arr, &point::x, 0, n-1);

More generically, you could follow the example of std::sort and accept any comparison functor:
template <typename RandIter, typename Compare>
void quicksort(RandIter begin, RandIter end, Compare compare) {
    // test points with
    // if (compare(*it1, *it2)) {/* *it1 sorts before *it2 */}
}

quicksort(arr, arr+n,
    [](point const &lhs, point const &rhs) {return lhs.x < rhs.x;});

And of course, unless you're learning how to implement a sorting algorithm, just use std::sort.

A: quicksort(arr,0,n-1);

then within quicksort, try to compare the arr[i].x

A: There are a few problems with your code.
1. quicksort accepts int* but you try to pass int value x
2. You try to pass int but you actually call an undefined variable arr.x
What you need to do is either call in the form of &arr[i].x, but to accomplish what you want, you probably want to pass the entire struct as a pointer.

A: You need to pass arr as the parameter, as that is the array to be sorted. arr.x is meaningless. You are not passing the string "arr.x" as a parameter which can somehow be interpreted as meaning sort on the x field - when the compiler sees this, it is looking for an x element of arr, which doesn't exist, as the error message suggests - only the elements of arr (e.g. arr[0]) have x elements (accessed as arr[0].x).

A: Assuming this is for academic purposes (why else would you declare your own sorting algorithm instead of using one of the ones already implemented with a custom comparator?), you can do this a few ways:
Array
std::array<point, 10> myArray; // declares an array of size 10 for points
template<size_t N>
void quicksort(std::array<point, N>& arr, ...)
{
    // implement sort operating on arr
}

Vector
std::vector<point> myVector; // declares a dynamic array/vector of points
void quicksort(std::vector<point>& arr, ...)
{
    // implement sort operating on arr
}

If for some god-awful reason, you want to keep it in C:
Legacy
const size_t SIZE = 10;
point arr[SIZE]; // declare an array of 10 points
void quicksort(point* p, const size_t n, ...)
{
    // implement sort operating on elements in p passing in SIZE for n
}

A: I'd rather defined the function as:
 void quicksort(void *a,int left,int right, size_t size, int (*fp)(void*,void*));

size is the size of one element of array and fp is a compare function which returns true if the two arguments are equal. Now you can pass the call the function as:
quicksort(arr,0,n-1,sizeof(arr)/sizeof(arr[0]), compare);

where function compare is something like:
int compare(void* a, void* b) { return *((int*)a) >= *((int*)b); }

Rest of the implementation of function is trivial I think.

A: (almost) never try to fool the system by passing a pointer to a member when you really want to pass a pointer to an object. Do as Grijesh suggested. Passing a member can lead to horrible side effects. For example, quicksort is going to sort all the integers together, regardless of which of them are X's and which are Y's. In milder cases you may get wrong compare criteria, and often hard to debug effects such as incorrect pointer optimization. Just be honest with the compiler and pass the object pointer if you need to pass an object pointer. There are very very very few exceptions, mostly to do with low-level system programming where the "other side' of the function call won't be able to handle the object.


text:
Q: I have this php code how can i make it generate random length from 1 to 16 I have this php code how can i make it generate random from 1 to 10
$seed = str_split('aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ123456789');
$rand = array_rand($seed, 16);
$convert = array_map(function($n){
    global $seed;
    return $seed[$n];
},$rand);

$var1 = implode('',$convert);

so need this one to show random not 16 like its there but random length from 1 to 16 each time user comes.

A: Here's a code snippet without using map
function generateRandString($length = 10) {
    $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    $charsLength = strlen($chars);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $chars[rand(0, $charsLength - 1)];
    }
    return $randomString;
}

A: You can shuffle() the array and use array_slice() to get n number of items from the array.
Including a rand() inside the array slice means it returns a random length between 1 and 10 characters.
$seed = str_split('aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ123456789');

shuffle($seed);
echo implode("", array_slice($seed,0,rand(1,10)));

https://3v4l.org/RX9XO

A: Easiest way to achieve what you want without rewriting all your code is to replace:
$rand = array_rand($seed, 16);

with
$rand = array(array_rand($seed, mt_rand(1,10)));

That will simply pass a different length parameter to array_rand() on each run


text:
Q: Find strings in files with regex in bash I have a bunch of files, where template tags are used. I want to list all the different template tags used in all of the files.
This is my used bash script, which gives no match...
for f in EHS/*.html;  do
  value=`cat ${f}`;
  [[ $value =~ "({%.*?%})" ]]
  if [[ ${BASH_REMATCH[0]} ]]; then
    echo "Found: ${BASH_REMATCH[0]}";
  fi
done;

This is a snippet from one of the html files:

  The ordernumber is: {%OrderNumber%}

  The partnumer is: {%PartNumber%}

So my goal is to just return all of the different tags used...

A: Two problems:

*

*The regex should be unquoted, but {} needs escaping, as their meaning is special.

*bash doesn't support frugal quantifiers like *?.
It's easier to use grep:
grep -o '{%[^}]*%}'

The -o option only returns the matching parts, one per line.
Note that strings like {%ab%cd}ef%} aren't matched as there's no easy way how to prevent parts of multicharacter delimiters in standard grep. With pgrep, you can use
grep -o -P '{%.*?%}'

as you originally intended.


text:
Q: How to solve a iterative slots allocation problem (points motion) I am starting a project which involves an allocation problem, and having explored a bit by myself, it is pretty challenging for me to solve it efficiently.
What I call here allocation problem is the following:

*

*There is a set of available slots in 3D space, randomly sampled ([xspot_0, yspot_0, zspot_0], [xspot_1, yspot_1, zspot_1], etc.). These slots are identified with an ID and a position, and are fixed, so they will not change with time.

*There are then mobile elements (same number as the number of available slots, on the order of 250,000) which can go from spot to spot. They are identified with an ID, and at a given time step, the spot in which they are.

*Each spot must have one and only one element at a given step.

*At first, elements are ordered in the same way as spots: the first element (element_id=0) is in the first spot (spot_id=0), etc.

*But then, these elements need to move, based on a motion vector that is defined for each spot, which is also fixed. For example, ideally at the first step, the first element should move from [xspot_0, yspot_0, zspot_0] to [xspot_0 + dxspot_0, yspot_0 + dyspot_0, zspot_0 + dzspot_0], etc.

*Since spots were randomly sampled, the new target position might not exist among the spots. The goal is therefore to find a candidate slot for the next step that is as close as possible to the "ideal" position the element should be in.

*On top of that first challenge, since this will probably be done through a loop, it is possible that the best candidate was already assigned to another element.

*Once all new slots are defined for each element (or each element is assigned to a new slot, depending on how you see it), we do it again, applying the same motion with the new order. This is repeated as many times as I need.

Now that I defined the problem, the first thing I tried was a simple allocation based on this information. However, if I pick the best candidate every time based on the distance to the target position, as I said some elements have their best candidate already taken, so they pick the 2nd, 3rd, ... 20th, ... 100th candidate slot, which becomes highly wrong compared to the ideal position.
Another technique I was trying, without being entirely sure about what I was doing, was to assign a probability distribution calculated by doing the inverse exponential of the distance between the slots and the target position. Then I normalized this distribution to obtain probabilities (which seem arbitrary). I still do not get very good results for a single step.
Therefore, I was wondering if someone knows how to solve this type of problem in a more accurate/more efficient way. For your information, I mainly use Python 3 for development.
Thank you!


text:
Q: How to sort a Vector of type ?
Possible Duplicate:
C++ how to sort vector<class *> with operator <

Hello everyone!
Please i am trying to sort a vector of type "class" based on one of its data members. As follows:
The Header File: (Undirected_Graph.h)
#ifndef UNDIRECTED_GRAPH_H
#define UNDIRECTED_GRAPH_H

#include <vector>
using std::vector;

#include <climits>

class Edge;

class Node
{
    public:

        Node(int);                 //The constructor.

        int id;                    //For the id of the node.
        bool visited;              //For checking visited nodes.
        int distance;

        vector <Edge*> adj;       //The adjacent nodes.
};

class Edge
{
    public:

        Edge(Node*, Node*, int);   //The constructor.

        Node* start_Node;          //The start_Node start of the edge.
        Node* end_Node;            //The end of the edge.
        int w;                     //The weight of the edge.

        bool isConnected(Node* node1, Node* node2)  //Checks if the nodes are connected.
        {
            return((node1 == this->start_Node && node2 == this->end_Node) ||
                   (node1 == this->end_Node   && node2 == this->start_Node));
        }
};

class Graph
{
    public:

        Graph(int);                    //The Constructor.

        int max_Nodes;                 //Maximum Number of allowed Nodes.

        vector <Edge*> edges_List;     //For storing the edges of the graph.
        vector <Node*> nodes_List;     //For storing the nodes of the graph.

        void insertEdge(int, int, int);

        int getNumNodes();
        int getNumEdges();
};

#endif

The Implementation File: (Undirected_Graph.cpp)
#include "Undirected_Graph.h"

Node::Node(int id_Num)
{
    id = id_Num;
    visited = 0;
    distance = INT_MAX;
}

Edge::Edge(Node* a, Node* b, int weight)
{
    start_Node = a;
    end_Node = b;
    w = weight;
}

Graph::Graph(int size)
{
    max_Nodes = size;

    for (int i = 1; i <= max_Nodes; ++i)
    {
        Node* temp = new Node(i);

        nodes_List.push_back(temp);
    }
}

void Graph::insertEdge(int x, int y, int w)
{
    Node* a = nodes_List[x-1];
    Node* b = nodes_List[y-1];

    Edge* edge1 = new Edge(a, b, w);
    Edge* edge2 = new Edge(b, a, w);

    edges_List.push_back(edge1);

    a->adj.push_back(edge1);
    b->adj.push_back(edge2);
}

int Graph::getNumNodes()
{
    return max_Nodes;
}

int Graph::getNumEdges()
{
    return edges_List.size();
}

Now in the above code, after creating several nodes and edges, i need to sort the edges of this graph based on their weight. I am studying a way to implement Kruskal algorithm so i though of sorting the edges first based on their weight.
sort (myGraph.edges_List[index].begin(), myGraph.edges_List[index].end());

obviously does not work! since the vector edges_List is of type "Edge".
Assuming that (myGraph is an object of the class).
I was wondering if there is any good technique to do that?
Thanks in advance for your help! Any suggestions or ideas are greatly appreciated!

A: By default, std::sort uses using operator<, but you can also supply a comparison function object.
So:
bool your_comparer(const Edge * left, const Edge * right)
{
    // return true if left should come before right, false otherwise
}

// ...

sort (myGraph.edges_List.begin(), myGraph.edges_List.end(), your_comparer);

A: Another way is usage std::set container for storing your objects. And you always will have sorted container. All you need is define operator < for stored classes.
Usage vector with push_back is not effective way in terms of time. It cause unnecessary memory rellocations.


text:
Q: Put parts of switch case in seperate methods possible? So I have a big switch case in my main method. However it is way to long. I had the idea to put the different cases in a method each however, all of the cases contain break;and you obviously need a loop or switch case for a break;The break is also within the code. Any ideas on how I can do this?

A: You can make separate methods/functions for each action. Then inside the switch statement, you can call these methods. But if you want to avoid the switch statement, you can use Enums for different cases for example. So it would look something like this:
int f1(int arg1, int arg2...) {
    //do something
}

void f2(int arg1, int arg2...) {
    //do something
}

public static void main() {
    switch(statement){
        case 0:
            f1();

            break;

        case 1:
            f2();

            break;
    }
}


text:
Q: SCM: How can trunk have the latest code since inception of the project? I am trying to understand SCM in tool agnostic way, and I have some doubts over the thing that "TRUNK should have the latest code and should have all the newest feature".
For example, let us consider JDK project, and would it mean that when this project started it would have a "TRUNK" and that trunk has undergoes all the addition , deletion while going from JDK 1 to JDK 8 ?  I am having difficulty as to how a TRUNK of a project can have all the changes spanning years.
I did refer to various questions in SO, but I am not still clear on how can a TRUNK have latest source codes since inception of a project.
Any help, thanks in advance.

A: Considering same SVN repo is used throughout the project since the inception.
Trunk is a default branch in SVN, just like "master" in Git. Once development starts, branches are forked out from Trunk as per need. Now over the span of years, these branches gets merged with each other, including Trunk.
Its not necessary that each and every feature/a bug fix is developed and checked into Trunk. It can be the case that the code is checked into any of the available branch and the same gets merged into Trunk.

I did refer to various questions in SO, but I am not still clear on how can a TRUNK have latest source codes since inception of a project.

Latest source code on Trunk? It depends on SCM design. Trunk can have all the latest code, it may not build or not in deploy-able/production-ready state. Some like to have all the latest code on some branch and keep Trunk with stable/production-ready state.
since inception of a project? Yes, since merges happen with commit history maintained, all the branches including Trunk will have all the code available till latest commit on that branch.


text:
Q: interpolation to a css class in an external file angular 2 I'm wondering if is possible to pass a variable to a css class into an external css file in angular 2, like from:
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  bgc: string = 'orange'
}

then on the "app.component.css" I would like to pass like
.mydiv{ background: {{bgc}};  }

Is this possible?

A: I don't think this would be possible.
If you need a style to change programmatically, I would suggest looking into ngStyle at the link below:
https://angular.io/docs/ts/latest/api/common/index/NgStyle-directive.html


text:
Q: Unknown serial device/protocol My light switches at home are connected to a circuit board. The light switches themselves are push buttons connected to it. The circuit board is in turn connected with 3 wires (black, yellow, red) leading to another circuit board controlling an array of relays which switch the mains power to the lights. All circuit boards are connected to eachother with those 3 wires.
With a multimeter I found black to be GND, yellow around 13.3 VDC (it dips to 13 when push button is pressed), and red a steady 13V.
I couldn't find any serial protocols with 3 wires and those voltages. I thought I could search the correct adapter or circuit board needed, to ultimately hook up a raspberry pi / arduino to those 3 wires and send whatever serial data to control my lights.
I've looked into logic analyzers, osciloscopes, icsp, avr's, ... I need a little guidance in what the next step should be.
( )

A: Probably the PIC pulls down the voltage (which is pulled up by resistor to +12V [+13V as you measured it]) through an NPN transistor to make an open-collector shared serial bus.  The protocol could be anything - you'll need a logic analyzer to work out what it is.
It's probably something along the lines of:

simulate this circuit – Schematic created using CircuitLab


text: Q: Maven build fails due to Certificate for  doesn't match any of the subject alternative names: [ERROR] Failed to execute goal on project app: Could not resolve dependencies for project app:war:RELEASE: The following artifacts could not be resolved: org.springframework:spring-core:jar:5.2.0.M1, org.springframework:spring-web:jar:5.2.0.M1, org.springframework:spring-beans:jar:5.2.0.M1, org.springframework:spring-webmvc:jar:5.2.0.M1, org.springframework:spring-context:jar:5.2.0.M1, org.springframework:spring-expression:jar:5.2.0.M1, org.springframework:spring-context-support:jar:5.2.0.M1, org.springframework:spring-jdbc:jar:5.2.0.M1, org.springframework:spring-websocket:jar:5.2.0.M1, org.springframework:spring-messaging:jar:5.2.0.M1, org.springframework:spring-test:jar:5.2.0.M1, javax.media.jai:com.springsource.javax.media.jai.codec:jar:1.1.3, javax.media.jai:com.springsource.javax.media.jai.core:jar:1.1.3: Could not transfer artifact org.springframework:spring-core:jar:5.2.0.M1 from/to atlassian-public (https://packages.atlassian.com/maven/repository/public): Transfer failed for https://packages.atlassian.com/maven/repository/public/org/springframework/spring-core/5.2.0.M1/spring-core-5.2.0.M1.jar: Certificate for <packages.atlassian.com> doesn't match any of the subject alternative names: [*.services.atlassian.com, services.atlassian.com] -> [Help 1]


text:
Q: Graphic Card Drivers Installation in Lubuntu 12.10? I am using Lubuntu 12.10, I want install the drivers for my hybrid graphic card because my laptop fan is always running and produces great amount of heat.
Graphic Card Specification:-
00:02.0 VGA compatible controller: Intel Corporation 2nd Generation Core Processor Family Integrated Graphics Controller (rev 09)
01:00.0 VGA compatible controller: Advanced Micro Devices [AMD] nee ATI Caicos [Radeon HD 6400M/7400M Series]

Well, I followed this Correct Way to install ATI Video Drivers
I got some errors; please find fglrx-install.log:-
ankit@ankit-HP-Pavilion-g6-Notebook-PC:/tmp$ tail -1000  /usr/share/ati/fglrx-install.log
Check if system has the tools required for installation.
Uninstalling any previously installed drivers.

Creating symlink /var/lib/dkms/fglrx/8.98/source ->
                 /usr/src/fglrx-8.98

DKMS: add completed.

Kernel preparation unnecessary for this kernel.  Skipping...

Building module:
cleaning build area....
cd /var/lib/dkms/fglrx/8.98/build; sh make.sh --nohints --uname_r=3.5.0-17-generic --norootcheck.....(bad exit status: 1)
[Error] Kernel Module : Failed to build fglrx-8.98 with DKMS
[Error] Kernel Module : Removing fglrx-8.98 from DKMS

------------------------------
Deleting module version: 8.98
completely from the DKMS tree.
------------------------------


text:
Q: What is the docker.sock equivalent on Windows 10? I have an application that utilizes docker client to connect to docker daemon. I run this application from inside a container. To that end, I am running my container with following command on both Ubuntu and MacOS:
docker run -d -v /var/run/docker.sock:/var/run/docker.sock someimage

Recently, on my Windows machine I installed Docker for Windows and there is no
/var/run/docker.sock

file. I am unable to figure out what is the equivalent for docker.sock file on Windows.
Update: I found an equivalent of docker.sock on Windows on [docker's repository](https://github.com/docker/docker/search?utf8=%E2%9C%93&q=DefaultDockerHost
) but still I don't know how to map the volume using:
npipe:////./pipe/docker_engine** path

A: Are you are trying to run Windows containers on Windows host (and not Linux containers on Windows host via Moby VM)?
In this case you can't share named pipe (npipe:////./pipe/docker_engine) as docker volume.
It seems the only option is to use TCP sockets.
Here is how I've done it In PowerShell:
# Open firewall
# TODO: allow access only from internal nat-ed containers
netsh advfirewall firewall add rule name="Docker daemon " dir=in action=allow protocol=TCP localport=2375

# Find gateway ip address for internal docker nat network, set DOCKER_HOST based on it
$gatewayIpAddress = (docker network inspect nat | ConvertFrom-Json).IPAM.Config[0].Gateway
$dockerHost = "tcp://${gatewayIpAddress}:2375"
$Env:DOCKER_HOST = $dockerHost
[Environment]::SetEnvironmentVariable("DOCKER_HOST", $dockerHost, "Machine")

# Reconfigure docker daemon to use TCP
'{ "hosts": ["' + $dockerHost + '"] }' | Set-Content 'C:\ProgramData\docker\config\daemon.json'

Restart-Service docker

# Smoke Test
docker version

Potentially you can get away with simpler approach instead of finding out gateway IP above, just use COMPUTERNAME. This will mean a bit more network traffic when starting nested container as it will need to access DNS to resolve it to the IP address which would normally be main IP address of the host, not the docker nat gateway IP. Also it will be less secure as Docker daemon will be listening on the external IP of the host, so will be accessible from outside.
Then you can start a container and just pass env var DOCKER_HOST:
docker run -it -e DOCKER_HOST ...

Above is based on: https://learn.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/deploy-containers-on-nano#manage-docker-on-nano-server

A: The first /var/run/docker.sock refers to the same path in your boot2docker virtual machine. Correcly write /var/run/docker.sock


text:
Q: Sign Up Using Facebook Autofill my form How to make my facebook signup button do what the odesk signup button does.
https://www.odesk.com/signup/create-account/id/Contractor_50dbed1edc1416.20352143
Note: I have design the form the button placed everything. What do i do next.


text:
Q: Delegates and Notifications in Objective-C In my AppDelegate, I download some data from a JSON feed. I am downloading a now/next/later schedule for a few channels. I have three different view controllers for each now, next and later. In each view controller, a user can add/remove the channels so when that happens, the newly added channel data has to be downloaded again.
Since the data is downloaded in the AppDelegate and stored there, how would I pass it to the three view controllers? Should I implement three separate delegates? Keep in mind that when adding a new channel, its data has to be downloaded again (which I am doing outside the AppDelegate now).
Any help please?
Thanks

A: This is basically a matter of style and your approach isn't invalid as such.
I'd do it another way, though - the AppDelegate is not meant to be used as a workhorse and having several AppDelegates at the same time is simply impossible.
Here are some thoughts about how this could be done (though it's of course not the only proper way):

*

*First, I'd employ Core Data or some other sort of storage which is available from anywhere within your app.

*Then maybe I'd introduce some sort of "data controller" class (maybe a singleton). This class should handle both download of data and the distribution of that data to your viewcontrollers as requested.

*By having one central controller for that purpose, you'd ensure that data gets downloaded only once because the controller knows exactly which data is already in stock.

*Your viewcontrollers would neither be responsible for managing downloads anymore nor would they access the data on disk by themselves. They'd just make a request to your data controller and get a callback when the requested data is available - no matter if it was on disk already or has been downloaded for the occasion.

*This keeps your VCs slim and focused and reduces the pain of making changes to your interface.

A: Toastor's answer is correct and as he says, there are several ways to do this. One is to call a data access class and change the values OR listen for changes on the values. For the later, the Key-Value Observing Programming Guide says the following:

KVO is particularly useful for communication between model and
  controller layers in an application.

*

*A controller object typically observes properties of model
  objects, and a view object observes properties of model objects
  through a controller.

*In addition, however, a model object may observe other model
  objects (usually to determine when a dependent value changes) or even
  itself (again to determine when a dependent value changes).

Another is to make the dependency explicit, maybe passing a data access class saved in your app delegate. See Object-oriented design question, iPhone.


text:
Q: Not able to deploy saved model into AWS Sagemaker I am following this article https://machinelearningmastery.com/how-to-perform-object-detection-with-yolov3-in-keras/ to deploy YOLOv3 inside the AWS Sagemaker. I have the model.weights having weights and model.json having model structure and also model.h5 having model structure + weights. When I convert these files to protobuf format so that I can tar them and deploy on Sagemaker, this error comes in.
UnexpectedStatusException: Error hosting endpoint sagemaker-tensorflow-2020-04-12-10-57-05-
567: Failed. Reason:  The primary container for production variant AllTraffic did not pass the
ping health check. Please check CloudWatch logs for this endpoint..

Here is my code:

import tensorflow
tensorflow.__version__

Output:
'1.7.0'

import boto3, re
from sagemaker import get_execution_role

role = get_execution_role()

from tensorflow.keras.models import model_from_json

!ls keras_model/

import tensorflow as tf

json_file = open('/home/ec2-user/SageMaker/keras_model/' + 'model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json, custom_objects={"GlorotUniform": tf.keras.initializers.glorot_uniform})

loaded_model.load_weights('/home/ec2-user/SageMaker/keras_model/model_weights.h5')
print("Loaded model from disk ")

from tensorflow.python.saved_model import builder
from tensorflow.python.saved_model.signature_def_utils import predict_signature_def
from tensorflow.python.saved_model import tag_constants

# this directory sturcture will be followed as below. Do not change it.
model_version = '1'
export_dir = 'export/Servo/' + model_version

#Build the protocol buffer savedmodel at export_dir
build = builder.SavedModelBuilder(export_dir)

print(loaded_model.inputs)
print([t for t in loaded_model.outputs])

Output:
[<tf.Tensor 'input_1:0' shape=(?, ?, ?, 3) dtype=float32>]
[<tf.Tensor 'conv_81/BiasAdd:0' shape=(?, ?, ?, 255) dtype=float32>, <tf.Tensor 'conv_93/BiasAdd:0' shape=(?, ?, ?, 255) dtype=float32>, <tf.Tensor 'conv_105/BiasAdd:0' shape=(?, ?, ?, 255) dtype=float32>]

tf.convert_to_tensor(loaded_model.output)

Output:
<tf.Tensor 'packed:0' shape=(3, ?, ?, ?, 255) dtype=float32>

signature = predict_signature_def(inputs={"input_image": loaded_model.input},
                                  outputs={t.name: t for t in loaded_model.outputs})

from tensorflow.keras import backend as K
with K.get_session() as sess:
    build.add_meta_graph_and_variables(sess=sess, tags=[tag_constants.SERVING],
                                       signature_def_map={"serving_default":signature} )
    build.save()

!ls export/Servo/1/variables/

Output:
variables.data-00000-of-00001  variables.index

import tarfile
with tarfile.open('model.tar.gz', mode='w:gz') as archive:
    archive.add('export', recursive=True)

import sagemaker

sagemaker_session = sagemaker.Session()
inputs = sagemaker_session.upload_data(path='model.tar.gz', key_prefix='model')

!touch train.py

from sagemaker.tensorflow.model import TensorFlowModel
sagemaker_model = TensorFlowModel(model_data='s3://' + sagemaker_session.default_bucket() + '/model/model.tar.gz',
                                 role = role,
                                 entry_point= 'train.py')

%%time
predictor = sagemaker_model.deploy(initial_instance_count=1,
                                   instance_type='ml.t2.large')

Error:
-----------------------------*
---------------------------------------------------------------------------
UnexpectedStatusException                 Traceback (most recent call last)
<timed exec> in <module>()

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/sagemaker/model.py in deploy(self, initial_instance_count, instance_type, accelerator_type, endpoint_name, update_endpoint, tags, kms_key, wait, data_capture_config)
    478                 kms_key=kms_key,
    479                 wait=wait,
--> 480                 data_capture_config_dict=data_capture_config_dict,
    481             )
    482

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/sagemaker/session.py in endpoint_from_production_variants(self, name, production_variants, tags, kms_key, wait, data_capture_config_dict)
   2849
   2850             self.sagemaker_client.create_endpoint_config(**config_options)
-> 2851         return self.create_endpoint(endpoint_name=name, config_name=name, tags=tags, wait=wait)
   2852
   2853     def expand_role(self, role):

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/sagemaker/session.py in create_endpoint(self, endpoint_name, config_name, tags, wait)
   2381         )
   2382         if wait:
-> 2383             self.wait_for_endpoint(endpoint_name)
   2384         return endpoint_name
   2385

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/sagemaker/session.py in wait_for_endpoint(self, endpoint, poll)
   2638                 ),
   2639                 allowed_statuses=["InService"],
-> 2640                 actual_status=status,
   2641             )
   2642         return desc

UnexpectedStatusException: Error hosting endpoint sagemaker-tensorflow-2020-04-12-10-57-05-567: Failed. Reason:  The primary container for production variant AllTraffic did not pass the ping health check. Please check CloudWatch logs for this endpoint..

I think that error is due to the difference between the Tensor shape of loaded_model.inputs and loaded_model.outputs. But I am still not sure about what do the 3 and 255 represent in the shape. Any help will be greatly appreciated.
print(loaded_model.inputs)
[<tf.Tensor 'input_1:0' shape=(?, ?, ?, 3) dtype=float32>]

print([t for t in loaded_model.outputs])
[<tf.Tensor 'conv_81/BiasAdd:0' shape=(?, ?, ?, 255) dtype=float32>,
 <tf.Tensor 'conv_93/BiasAdd:0' shape=(?, ?, ?, 255) dtype=float32>,
 <tf.Tensor 'conv_105/BiasAdd:0' shape=(?, ?, ?, 255) dtype=float32>]

Cloudwatch log:
2020-04-12 11:01:33,439 INFO - root - running container entrypoint
2020-04-12 11:01:33,440 INFO - root - starting serve task
2020-04-12 11:01:33,440 INFO - container_support.serving - reading config
Downloading s3://sagemaker-us-east-1-611475884433/sagemaker-tensorflow-2020-04-12-10-57-05-375/sourcedir.tar.gz to /tmp/script.tar.gz
2020-04-12 11:01:33,828 INFO - container_support.serving - importing user module
2020-04-12 11:01:33,828 INFO - container_support.serving - loading framework-specific dependencies
2020-04-12 11:01:35,795 INFO - container_support.serving - starting nginx
2020-04-12 11:01:35,797 INFO - container_support.serving - nginx config:
worker_processes auto;
daemon off;
pid /tmp/nginx.pid;
error_log /var/log/nginx/error.log;
worker_rlimit_nofile 4096;
events {
  worker_connections 2048;
}
http {
  include /etc/nginx/mime.types;
  default_type application/octet-stream;
  access_log /var/log/nginx/access.log combined;

  upstream gunicorn {
    server unix:/tmp/gunicorn.sock;
  }

  server {
    listen 8080 deferred;
    client_max_body_size 0;

    keepalive_timeout 3;

    location ~ ^/(ping|invocations) {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_redirect off;
      proxy_pass http://gunicorn;
    }

    location / {
      return 404 "{}";
    }
  }
}

2020-04-12 11:01:35,815 INFO - container_support.serving - starting gunicorn
2020-04-12 11:01:35,820 INFO - container_support.serving - inference server started. waiting on processes: set([24, 23])
2020-04-12 11:01:35.904746: I tensorflow_serving/model_servers/server.cc:82] Building single TensorFlow model file config:  model_name: generic_model model_base_path: /opt/ml/model/export/Servo
2020-04-12 11:01:35.905995: I tensorflow_serving/model_servers/server_core.cc:462] Adding/updating models.
2020-04-12 11:01:35.906148: I tensorflow_serving/model_servers/server_core.cc:517]  (Re-)adding model: generic_model
2020-04-12 11:01:35.907173: I tensorflow_serving/core/basic_manager.cc:739] Successfully reserved resources to load servable {name: generic_model version: 1}
2020-04-12 11:01:35.907349: I tensorflow_serving/core/loader_harness.cc:66] Approving load for servable version {name: generic_model version: 1}
2020-04-12 11:01:35.907422: I tensorflow_serving/core/loader_harness.cc:74] Loading servable version {name: generic_model version: 1}
2020-04-12 11:01:35.907578: I external/org_tensorflow/tensorflow/contrib/session_bundle/bundle_shim.cc:360] Attempting to load native SavedModelBundle in bundle-shim from: /opt/ml/model/export/Servo/1
2020-04-12 11:01:35.907687: I external/org_tensorflow/tensorflow/cc/saved_model/reader.cc:31] Reading SavedModel from: /opt/ml/model/export/Servo/1
2020-04-12 11:01:35.939232: I external/org_tensorflow/tensorflow/cc/saved_model/reader.cc:54] Reading meta graph with tags { serve }
2020-04-12 11:01:35.980215: I external/org_tensorflow/tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
[2020-04-12 11:01:36 +0000] [24] [INFO] Starting gunicorn 19.9.0
2020-04-12 11:01:36.048327: I external/org_tensorflow/tensorflow/cc/saved_model/loader.cc:259] SavedModel load for tags { serve }; Status: fail. Took 140502 microseconds.
2020-04-12 11:01:36.048617: E tensorflow_serving/util/retrier.cc:37] Loading servable: {name: generic_model version: 1} failed: Not found: Op type not registered 'FusedBatchNormV3' in binary running on model.aws.local. Make sure the Op and Kernel are registered in the binary running in this process. Note that if you are loading a saved graph which used ops from tf.contrib, accessing (e.g.) `tf.contrib.resampler` should be done before importing the graph, as contrib ops are lazily registered when the module is first accessed.


text:
Q: The 36-digit patch in the output of print('%.70f' % (0.2 + 0.1)) I understand why 0.1 + 0.2 yields this in Python 3:
>>> 0.1 + 0.2
0.30000000000000004

...but I don't understand why there is a 36-digit stretch of (mostly) non-zero digits in the middle of the output shown below:
>>> print('%.70f' % (0.2 + 0.1))
0.3000000000000000444089209850062616169452667236328125000000000000000000

I do expect there to be an difference between 0.1 + 0.2 and the binary IEEE 754 float nearest to 0.1 + 0.2, but I don't understand why this difference would result in a 36-digit representation (corresponding to roughly ~120 bits of precision).
I could understand if the error had a much smaller (< 53 bit) precision, or had an (apparent) infinite precision, maybe be due to an artifact of the algorithm for evaluating '%.70f' % (0.2 + 0.1).  But I can't make sense of an error that would result in the 36-digit patch shown above.

A: The Python implementation you are using apparently uses IEEE-754 binary64 for floating-point. (This is common, but Python does not mandate it.)
In this format, numbers are represented as multiples of powers of two, where the specific power of two used depends on the magnitude of the number. (The floating-point format is also described in other ways that are mathematically equivalent to this, such as using a significand with a fixed number of fractional bits instead of an integer multiple as I am using here. This description is easier for the explanation at hand.)
For numbers around .3, the power of two used is 2−54. The result of adding .1 and .2, after rounding to fit in the floating-point format is 5404319552844596 times 2−54, or 5404319552844596 / 254.
That number, 5404319552844596 / 254, is exactly 0.3000000000000000444089209850062616169452667236328125.


text:
Q: WiX: Close app before install and run automatically only if it was running I have a slightly different need that most of the other posts I've found on a search...
I need my installer to check if the application is currently running on a re-install (or upgrade), shut it down but remember that it was running, and then after the installation, start the application only if it had been running at the start.
Is there not a set of standard custom actions that can be used to accomplish this?

A: Made CA for detection the application and set some property in this CA (i.e. APPISRUN; MsiSetProperty(hInstall, "APPISRUN","1"); ), execute this CA before removing existing products. Run the application after intsallation, if APPISRUN == 1. About CA - http://bonemanblog.blogspot.in/2005/10/custom-action-tutorial-part-i-custom.html


text:
Q: Code not working properly - without any errors So I'm intendending to either remove, update or insert a tuple dependening on some circumstances but I cannot get it to work.
First I see if I have any employee with a particular ESSN on a project number by checking:
count = cursor2.execute("SELECT Distinct ESSN FROM Works_On WHERE ESSN = ? AND Pno = ?", (SSN, ProjectNumber)).rowcount
Which I looked up should return -1 if the select did not find any, or if it is unsure how many tuples it found.In my case it returned 0.
However when I do these if - statements:
if((ChangeToHours==0) and (count != -1)):

    print "0"

    cursor2.execute("Delete FROM Works_On WHERE ESSN = ? AND Pno = ?", SSN, ProjectNumber)

    print "Removed %s from project %s" %SSN, ProjectNumber

if((ChangeToHours>0) and (ChangeToHours<=40) and (count != -1)):

    print "!= -1"

    cursor2.execute("Update Hours SET Hours= ? WHERE ESSN=? AND Pno =?", ChangeToHours, SSN,
ProjectNumber)

    print "Number of hours which employee %s works on project %s successfully changed to %d", SSN, ProjectNunmber,ChangeToHours

Using some SSN and project Number and ChangeToHours = 13 as an input I should get into the latter "if" but I get into the first one. Also, my code is not doing anything pass it printing 0, what I can see. At least it doesn't print the "Removed..." text which it should do.
I get no errors what-so-ever running this code.
Anyone have any idea?
Regards,
Cenderze

A: I fixed the problem myself.
Since this was my first laboration using Python I guess I overlooked the basics. ChangedToHours was not made into a float or any other data type which of course causes issues with these comparisons.
So, embarassing fix but might be of use for someone else!
Regards
Cenderze


text:
Q: Why does submitting a job fail with "NoSuchMethodError: scala.runtime.VolatileObjectRef.zero()Lscala/runtime/VolatileObjectRef;"? I'm trying to submit a spark job
It starts this way:
import javax.xml.parsers.{SAXParser, SAXParserFactory}

import org.apache.spark
import org.apache.spark.graphx.{Graph, Edge, VertexId}
import org.apache.spark.rdd.{PairRDDFunctions, RDD}
import org.apache.spark.storage.StorageLevel
import org.apache.spark.{SparkContext, SparkConf}
import scala.util.Try
import org.apache.log4j.{Level, Logger}

object MyApp {

  def main(args: Array[String]) {

    val sparkConf = new SparkConf().setAppName("MyApp")
    val sc = new SparkContext(sparkConf)

And when I launch it I get the following error:
App > Exception in thread "main" java.lang.NoSuchMethodError: scala.runtime.VolatileObjectRef.zero()Lscala/runtime/VolatileObjectRef;
App > at MyApp$.main(MyApp.scala)
App > at MyApp.main(MyApp.scala)
App > at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
App > at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
App > at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
App > at java.lang.reflect.Method.invoke(Method.java:606)
App > at org.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:328)
App > at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:75)
App > at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

What am I doing wrong?
EDIT: Included full stack trace.
Using Scala 2.10 and Spark 1.2.0.
What's weird is that in my jar, I have two classes. When I spark submit one, it works (it's a 4 lines dummy job), but when I run the longer one (about 40 lines), if fails with the error above

A: zero() on scala.runtime.VolatileObjectRef has been introduced in Scala 2.11
You probably have a library compiled against Scala 2.11 and running on a Scala 2.10 runtime.
See

*

*v2.10: https://github.com/scala/scala/blob/2.10.x/src/library/scala/runtime/VolatileObjectRef.java

*v2.11: https://github.com/scala/scala/blob/2.11.x/src/library/scala/runtime/VolatileObjectRef.java

A: Check the artifacts and versions of your Maven dependencies. I got the same error when I used
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.10</artifactId>
    <version>2.0.1</version>
</dependency>

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.11</artifactId>
    <version>2.0.1</version>
</dependency>

I had to change spark-core_2.10 to spark-core_2.11 and the exception disappeared.


text:
Q: Can you shallow clone 2 branches using git? I'd like to shallow clone part of a repository: just 1 feature branch (including all of the commits since branching from main) and a few commits on main before that.
I have tried git clone $repo --depth=N --branch=$feature which does correctly check out a shallow clone of $feature, and assuming I pick depth to be large enough goes back to the branch point.
What's the incantation to pull in main as well?
Essentially I want to be able to do:
git clone --branch=$feature
BASE=$(git merge-base $feature origin/main)
echo git rev-parse $BASE^
echo git rev-parse $BASE^^
echo git rev-parse $BASE^^^

to tell me the SHA1s of the few commits that happened just before branching.


text:
Q: Create dll from existing VB.NET project in Visual Studio 2017 At the moment I am migrating several projects from Visual Studio 2015 to Visual Studio 2017 Enterprise edition.
One of them is a VB.NET project, ODKWrapper, which provides a dll for other projects. The output path is specified, it should be created in ../Run/Release.
In VisualStudio2015 it worked well.
When I build the same project in Visual Studio 2017, no dll is generated and, even worse, a dll copied to the directory is deleted.
How can I create a dll from an existing project in Visual Studio 2017?
Thank you in advance.

A: I found the solution. When moving from VisualStudio2015 to VisualStudio 2017, the reference to log4net was lost. I had reset it and the project was all OK, but apparently on the wrong version of log4net. Now I've reconnected this reference and compiled as .dll works.
Many thanks for your help.


text:
Q: PHP behavior under the hood I was just wondering how PHP works under the hood in this certain scenario. Let's say I have these two pieces of code:
function foo() {
    return 2 * 2;
}

// First.
if (foo()) {
    bar(foo());
}

// Second.
if (($ref = foo())) {
    bar($ref);
}

Now the questions:

*

*In the first case, does PHP make some sort of temporary variable inside the if clause? If so, isn't the second piece of code always better approach?

*Does the second case take more memory? If answer to the first question is yes to the first question, then not?

A: The two codes are not equivalent, because the first one calls foo() twice (if it returns a truthy value). If it has side effects, such as printing something, they will be done twice. Or if it's dependent on something that can change (e.g. the contents of a file or database), the two calls may return different values. In your example where it just multiplies two numbers, this doesn't happen, but it still means it has to do an extra multiplication, which is unnecessary.
The answer to your questions is:

*

*Yes, it needs to hold the returned value in a temporary memory location so it can test whether it's true or not.

*Yes, it uses a little more memory. In the first version, the temporary memory can be reclaimed as soon as the if test is completed. In the second version, it will not be reclaimed until the variable $foo is reassigned or goes out of scope.

A: *

*In the first case, you are calling a function twice, so, if the function is time consuming, it is inefficient. The second case is indeed better since you are saving the result of foo().

*In both cases, PHP needs to allocate memory depending on what data foo() generates. That memory will be freed by the garbage collector later on. In terms of memory both cases are pretty much equivalent. Maybe the memory will be released earlier, maybe not, but most likely you won't encounter a case where it matters.

A: PHP can't make any temporary variable because it can't be sure that foo()'s returning value will always be the same. microtime(), rand() will return different values for each call, for example.
In the second example, it takes indeed more memory, since PHP needs to create and keep the value in memory.
Here is how to test it :
<?php

function foo() {
    return true;
}

function bar($bool) {
    echo memory_get_usage();
}

if (1) {
    // 253632 bytes on my machine
    if (foo()) {
        bar(foo());
    }
} else {
    // 253720 bytes on my machine
    if (($ref = foo())) {
        bar($ref);
    }
}