text:
Q: How do I make a mob grinder in MCPE that actually spawns mobs Although I cannot show you an image I can describe. I basically killing the mobs by using fall damage, I make them falling into water more probable by having trap doors opened. I also have slabs to prevent spider spawning, but I don't know why any mobs are spawning. I am playing in am MCPE Realm that doesn't spawn mobs in the dark room. I also put torches around the dark room on the outside to increase the chance of mobs spawning inside. I built one above land and below land. I am not in a mycelium biome and I am not playing in peaceful. Flat world or regular it doesn't work. What is the problem.

A: The slabs are the problem. Remove them and it will work if the room is 100% dark and you are near the spawner.


text:
Q: How to handle existing external storage files on app upgrade in Android? An android app is getting updated after a long time. It was using external storage permission (READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE) to save the user selected files and images in a directory that the app created /sdcard/emulated/0/myapp
Now when the upgrade is getting pushed, Google has updated the file access framework and now restricted access to the external storage.
MANAGE_EXTERNAL_STORAGE is restricted by Google policy.
How can we move the existing app files in sdcard to the Android/data folder while upgrading the app so that the app has access to the existing files created in the older version?
Any help is appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue with SQLite query Problem Specification and Database Condition: There are 3 tables (Highschooler, Friend and Likes) in the database and Here is  database :
Highschooler
ID  name    grade
1510    Jordan  9
1689    Gabriel 9
1381    Tiffany 9
1709    Cassandra   9
1101    Haley   10
1782    Andrew  10
1468    Kris    10
1641    Brittany    10
1247    Alexis  11
1316    Austin  11
1911    Gabriel 11
1501    Jessica 11
1304    Jordan  12
1025    John    12
1934    Kyle    12
1661    Logan   12

Friend
ID1 ID2
1510    1381
1510    1689
1689    1709
1381    1247
1709    1247
1689    1782
1782    1468
1782    1316
1782    1304
1468    1101
1468    1641
1101    1641
1247    1911
1247    1501
1911    1501
1501    1934
1316    1934
1934    1304
1304    1661
1661    1025
1381    1510
1689    1510
1709    1689
1247    1381
1247    1709
1782    1689
1468    1782
1316    1782
1304    1782
1101    1468
1641    1468
1641    1101
1911    1247
1501    1247
1501    1911
1934    1501
1934    1316
1304    1934
1661    1304
1025    1661

Likes
ID1 ID2
1689    1709
1709    1689
1782    1709
1911    1247
1247    1468
1641    1468
1316    1304
1501    1934
1934    1501
1025    1101

Question is : For every student who likes someone 2 or more grades younger than themselves, return that student's name and grade, and the name and grade of the student they like.
My query is :
select HS11.name,HS11.grade,HS22.name,HS22.grade from
( select ID1,ID2 from Likes where ID1 in
(
select HS1.ID from Highschooler HS1, Highschooler HS2
where HS1.ID<> HS2.ID and (HS1.grade - HS2.grade) >=2
)
and ID2 in
(
select HS2.ID from Highschooler HS1, Highschooler HS2
where HS1.ID<> HS2.ID and (HS1.grade - HS2.grade) >=2
)
) as G, Highschooler HS11, Highschooler HS22
where HS11.ID=G.ID1 and HS22.ID = G.ID2

My query's output is :
Alexis 11 Kris 10
John 12 Haley 10

Expected output is:
John 12 Haley 10

So, I am getting 1 row extra which incorrect. Could anyone please point out what I am doing wrong here ?

A: Your SELECT statement can be simplified by using INNER JOIN. Then you can have one WHERE clause that specifies the requirement:
SELECT HS1.name, HS1.grade, HS2.name, HS2.grade
FROM Likes
INNER JOIN Highschooler HS1
  ON Likes.ID1 = HS1.ID
INNER JOIN Highschooler HS2
  ON Likes.ID2 = HS2.ID
WHERE (HS1.grade - HS2.grade) >=2

In other words, instead of trying to find the IDs you need by using subqueries with convoluted requirements, you select one virtual table, and place requirements on it directly.

A: I would go for
select a.name as liker, a.grade as liker_grade, c.name as likee, c.grade as likee_grade from
highschooler a inner join likes b on a.id = b.id1
left join highschooler c on b.id2 = c.id
where a.grade >= c.grade +2

and if the likes are always mutual (which usually is not the case, combine with itself and union all
select a.name as liker, a.grade as liker_grade, c.name as likee, c.grade as likee_grade from
highschooler a inner join likes b on a.id = b.id1
left join highschooler c on b.id2 = c.id
where a.grade >= c.grade +2
union all
select a.name as liker, a.grade as liker_grade, c.name as likee, c.grade as likee_grade from
highschooler a inner join likes b on a.id = b.id2
left join highschooler c on b.id1 = c.id
where a.grade >= c.grade +2

A: If yes, then this should work
Select main.*
  from Highscooler main
       join Likes lk on main.ID = lk.ID1
       join Highscooler mate on mate.ID = lk.ID2
  where main.Grade >= mate.Grade+2

EDIT: Corrected the answer (I thought 'likes' is expressed using the 'friends' table). Also did not understand 'like' (I am not using FB ;-) )
Corrected again :  I am not good in reading text ...

A: SELECT   liker.ID AS LikerID,
         liker.Name AS LikerName,
         liker.Grade AS LikerGrade,
         liked.ID AS LikedID,
         liked.Name AS LikedName,
         liked.Grade AS LikedGrade
FROM     Likes
JOIN     HighSchooler Liker ON Likes.ID1 = Liker.ID
JOIN     HighSchooler Liked ON Likes.ID2 = Liked.ID
WHERE    2 <= (Liker.Grade - Liked.Grade)

Should get you close

A: Something like this (sytax maybe wrong) and replace select * with the correct columns
select * from highschooler as me
left join on friend where me.id = friend.id1
left join on highschooler as f where f.id = freind.id2
where me.grade - f.grade >= 2


text:
Q: AdS to dS uplifting and its opposite So as I understand it, localized structures in AdS can wick rotated to dS, the boundary has to be complixified as can be seen here. Also, uplifting is another technique that can be used to move from AdS to dS. (Thanks to Mitchell Porter for this suggestion) My question is that just as an exercise, is it possible to move from dS to AdS, I don't know the name for such a process, it is in some sense "moving down" from dS to AdS. Take the following example, suppose I have a mapping of a scalar field from boundary to bulk in AdS, now that can be uplifted to dS, it won't hold make much sense anymore since AdS allows for SUSY however dS doesn't but let's say for a moment that it can be done. Now consider the opposite case, we have a scalar field mapping in dS, can that be brought down to AdS? I think it can be, and this should be actually easier since AdS allows for SUSY which should make the mapping a little easier. The lack of a concrete example for dS/CFT makes it (about the mapping which we considered in our hypothetical case for dS) difficult to ask this question but does it seem plausible that if such a mapping were to be constructed, it can be brought down to AdS? Thanks.

A: Well it just so happens that Mitchell answered this question in a private email, I'm posting the relevant part here for the greater good.

The Wick rotation in this case transforms a local patch of dS space
  into AdS space, or vice versa.
Think of the difference between concave and convex, a valley and a
  hill. Then you should imagine that we have some formula appropriate
  for a valley - e.g. you might have a line-of-sight device like
  surveyors use, and you need to adjust the angle of the view finder, in
  a way that depends on the curvature of the ground. We can turn it into
  the corresponding formula for the hill by replacing, somewhere in the
  formula, a positive number with a negative number - because the
  curvature now has the opposite sign. This is what's actually going on
  in these Wick rotations, although the details are somewhat more
  complicated.
Returning to the analogy, turning dS space as a whole into AdS space
  is like turning the whole valley into a hill.
Here is a picture for the analogy. Scroll down to the concave meniscus
  vs convex meniscus.
  http://www.tutorvista.com/content/physics/physics-iii/solids-and-fluids/shape-meniscus.php
  In the concave meniscus, the vectors normal to the surface (labeled R)
  diverge; in the convex meniscus, they converge.
In the previous paragraph, you can see two formulas, basically "Force1
  minus Force2" and "Force2 minus Force1", which correspond to the two
  situations. You can get one formula by multiplying the other by -1.
So here is the analogy. If you start with the force formula for a
  concave meniscus, and want to get the force formula for a convex
  meniscus, you perform the transformation "multiply by minus 1". That's
  analogous to: start with the quantum propagator for a scalar field in
  AdS space, and get the propagator in dS space by the transformation
  "perform a Wick rotation".
But if you actually want to turn a concave meniscus into a convex
  meniscus, you're not just "multiplying the meniscus by minus 1". What
  you would have to do is increase the intermolecular tension
  everywhere, until it changes the curvature.
In the same way, the uplift from AdS space to dS space involves
  changing the local curvature everywhere, by having extra fields whose
  energy density acts as an extra source of curvature (this is in the
  "Landscaping" paper by Silverstein and Polchinski).
So my first point is that uplifting isn't Wick rotation. It actually
  means that you add something to your model, which will make the space
  curve differently. What the Wick rotation allows you to do, is to take
  a formula appropriate for one type of space, and modify it so it
  applies to the other type of space - but these are formulas which
  describe what happens in a small patch of the space, they aren't
  describing its total structure.
So far, I've only been talking about physics in the bulk (dS or AdS).
  The existence of a boundary CFT, and the details of how it relates to
  the bulk physics, wasn't even discussed yet. Remember that half of
  what David Lowe writes about is just a mapping from the center of the
  bulk to the edge of the bulk, that is, it's something entirely within
  bulk physics. For example, it's about how the wavefunction of a
  particle changes as it travels from the interior to the edge. Then, at
  the edge of the bulk, is the truly holographic mapping; or at least,
  the edge of the bulk is the place where a point in the bulk maps to a
  single point on the boundary. (Points deep in the interior of the bulk
  correspond to some sort of sum over whole regions on the boundary.)
  The truly holographic mapping is this change in variables - from bulk
  variables to boundary variables.
So a big part of what we should be interested in is, what happens to
  the holographic change in variables if we go from AdS to dS. But there
  might be an easier case to study first: what happens to this change in
  variables if the curvature of AdS space changes (this would usually be
  expressed in terms of the "radius" of the AdS space, the distance from
  center of bulk to edge of bulk).
If you look up the notes of Thomas Hartman's talk from Strings 2011,
  he actually says how the boundary theory changes for Vasiliev's
  higher-spin gravity, as you go from AdS to dS. In AdS space, the
  boundary theory is a vector field theory with an O(N) symmetry, in dS
  space the boundary theory is now a scalar field theory with a Sp(N)
  symmetry (N is the number of vector fields or number of scalar
  fields). So going from AdS to dS requires the set of fields to change
  rather radically - though apparently there's still enough of a
  similarity that he and Anninos were able to deduce or guess that Sp(N)
  symmetry would be the dS counterpart. (Let me also say in passing that
  they have only solved the problem - if they have solved the problem;
  no paper yet... - for a particular case of AdS/CFT. When the bulk
  theory is string theory rather than Vasiliev's higher-spin gravity,
  the boundary theory is a supersymmetric field theory that Hartman
  doesn't know how to transform appropriately; he says this in questions
  after his talk.)
If you see Hartman's notes, I think you'll also find that he talks
  about the cosmological constant in the bulk space going from negative
  to positive. This just refers to the curvature, and the difference
  between AdS and dS. But you can also talk about the difference between
  AdS with strong curvature and AdS with weak curvature. This also
  requires a change in the boundary theory, but not such a big change.
One reason AdS/CFT is popular is that it is a 'strong-weak' duality.
  When quantum theories have strong "couplings" - when the interactions
  are strong - they become difficult or impossible to calculate with,
  because the usual approach of successive approximations - perturbation
  theory - doesn't work. The whole idea of perturbation theory is that
  each correction is smaller and less important than the last, so in
  order to approximate the actual result, you just keep adding smaller
  and smaller corrections. But when the interaction is strong, the
  corrections get bigger as you go, which means that the whole starting
  point was wrong.
In AdS/CFT, typically, when the boundary theory is strongly coupled,
  the bulk theory is weakly coupled, and vice versa. So if you have a
  strongly coupled field theory, it may have an AdS dual gravity
  description which is weak and therefore calculable. Or if you have a
  gravity theory in a strong coupling state, it may be dual to a weakly
  coupled boundary field theory.
If the curvature of the AdS space gets bigger, that should mean that
  the gravitational coupling is getting stronger, but in turn that means
  that the boundary coupling is getting weaker. And conversely, if the
  AdS space is getting flatter - more weakly curved, and approaching the
  transition to dS space - that should mean the boundary theory is
  getting strongly coupled. And even independently of AdS/CFT, it's well
  known that strongly coupled theories often have a dual description in
  terms of new variables which will be more easy to calculate with. So
  possibly this is an aspect of what happens on the boundary as you go
  from AdS to dS.


text:
Q: Artifacts in diamond-square algorithm
This is example of result of standart diamond-square landscape generation algorithm (i have used one from here - Diamond square algorithm). Algorithm is modified a bit to remove random height fluctuations, to make it clear what artifacts are.
It looks like this artifacts are result of disproportional accumulation of height in iterations, so points which was proceeded first (corners of biggest squares and diamonds) have lesser heights. Probably there is a way to correct this points..
So, does anyone know optimizations which allow fix this algorithm (but not blur effects, i dont want second pass optimizations) ?

A: After some investigation i've found a solution - problem lies in fact that algorithm should take height values outside of edges.. so, just increase terrain 2x size with virtual values, and resulting terrain have totally equal distribution of randomness all over it.


text:
Q: SQL - Select Columns from table where another table column value equals column name list seen a lot of similar posts about parsing data based on values but nothing quite what I want to get the result column from one table that contains the column names for another table. For example:
 Select [col1], [col2]
 from Table1
 where (select changes as (col#)
        from table2)

The col# is a list of the column names I want from Table1. Table2 changes column is a comma separated list. I wanted to figure a way to be able to get each column from Table1 that's in the list from table2. Any help is greatly appreciated.

A: You'll have to create the query on-the-fly. You can either do this by:

*

*First fetching the data from the changes column into your calling application, then assembling a SQL query string from that data and execute it, or

*Creating a dynamic statement within a stored procedure and EXECing it (or whatever your RDBMS's equivalent statement is).

Do be aware though that if the data in changes ever comes from user input, you are in for a world of hurt.
If you have control over the schema I would suggest to avoid this way of storing data. In general, comma-separated-lists are just unwieldy and fundamentally go against what a database is designed to do. A change-table structure with one Boolean value for each column that could change (id, col1_changed, col2_changed) or with a single row for each changed column (id, changed_col_name) would be much easier to use in a normal query.


text:
Q: Como ler um arquivo excel em c# e salvar os dados em strings? Galera,preciso fazer uma aplicação de console c# que lê um Excel e salva cada dado em uma string!!Já tentei várias bibliotecas e nada deu certo

A: Eu uso o GemBox.Spreadsheet 3.7 for .NET 3.0 - 4.5 para fazer importação de Excel
protected void lnkValidar_Click(object sender, EventArgs e)
{
    if (FileUpload.HasFile)
        {
            FileInfo finfo = new FileInfo(FileUpload.FileName);
            string fileExtension = finfo.Extension.ToLower();
            if (fileExtension != ".xlsx")
            {
                lblErro.UserError("Selecione um arquivo no formato .xlsx");
                return;
            }

            Stream fileStream = FileUpload.FileContent;
            var RetornoDados = ConverteExcelExcelFile(fileStream);

                var Msg = new StringBuilder();
                foreach (var sheet in RetornoDados.Worksheets)
                {
                    foreach (var row in sheet.Rows.Where(R => R.Index > 0))
                    {
                        try
                        {
                            Msg.Clear();
                            String Coluna0 = (Convert.ToString(row.AllocatedCells[0].Value)).Trim();
                            String Coluna1 = (Convert.ToString(row.AllocatedCells[1].Value)).Trim();
                            String Coluna2 = (Convert.ToString(row.AllocatedCells[2].Value)).Trim();
                            String Coluna3 = (Convert.ToString(row.AllocatedCells[3].Value)).Trim();

                         }
                        catch (Exception exc)
                        {
                            throw new Exception("Erro ");
                        }
                    }
                    break;     // Só o 1o sheet !
                }
        }
    }
}

public ExcelFile ConverteExcelExcelFile(Stream fileStream)
{
    SpreadsheetInfo.SetLicense("000000000000000"); // entre no site e pegue uma licença
    return ExcelFile.Load(fileStream, LoadOptions.XlsxDefault);
}

Ou o  Open XML ...
            if (FileUpload.HasFile)
            {
                FileInfo finfo = new FileInfo(FileUpload.FileName);
                string fileExtension = finfo.Extension.ToLower();
                if (fileExtension != ".xlsx")
                {
                    lblErro.UserError("Selecione um arquivo no formato .xlsx");
                    return;
                }

                Stream fileStream = FileUpload.FileContent;
                var retorno = Upload(fileStream);

                if (retorno is string)
                {
                  //erro
                }
                else
                {
                    // todo
                }
            }

    private Object Upload(Stream fileStream)
    {
        var dt = new DataTable();

        using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(fileStream, false))
        {
            IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
            string relationshipId = sheets.First().Id.Value;
            WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
            Worksheet workSheet = worksheetPart.Worksheet;
            SheetData sheetData = workSheet.GetFirstChild<SheetData>();
            IEnumerable<Row> rows = sheetData.Descendants<Row>();
            try
            {
                foreach (Cell cell in rows.ElementAt(0))
                {
                    dt.Columns.Add(GetCellValue(spreadSheetDocument, cell));
                }
            }
            catch
            {
                    throw;
            }
            try
            {
                int index = 0;

                foreach (Row row in rows)
                {
                    DataRow tempRow = dt.NewRow();

                    // Menor que a quantidade de colunas da planilha ... index
                    for (int i = 0; i < rows.Count(); i++) // index
                    {
                        tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
                    }

                    dt.Rows.Add(tempRow);
                }
            }
            catch
            {
                dt.Rows.RemoveAt(0);
                return dt;
            }
        }

        dt.Rows.RemoveAt(0);
        return dt;
    }

    public static string GetCellValue(SpreadsheetDocument document, Cell cell)
    {
        SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
        string value = "";
        if (cell.CellValue != null)
            value = cell.CellValue.InnerText;

        if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
        {
            return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
        }
        return value;
    }

A: Augusto Bueno, como não citou outros detalhes apenas a leitura do arquivo excel, se o arquivo vai conter campos fixos e etc. Este exemplo, http://www.linhadecodigo.com.br/artigo/1895/lendo-um-arquivo-do-excel-%E2%80%9Cxls%E2%80%9D-com-csharp.aspx esta pode auxiliar a conduzir para uma direção.

A: Eu já utilize a ExcelLib(https://code.google.com/p/excellibrary/); pesquisei agora e vi que consta como projeto arquivado...
A vantagem é manipular(criando, abrindo, salvando, etc.) sem a necessidade de ter o MSOffice instalado(com a limitação de ser apenas para ".xls").
Talvez seja até mais do que você precisa.
Bom trabalho


text:
Q: Pandas - Giving all rows (particularly) duplicate rows a unique identifier Let's say I have a DF with 5 columns and I want to make a unique 'key' for each row.
   a  b  c  d  e
1  1  2  3  4  5
2  1  2  3  4  6
3  1  2  3  4  7
4  1  2  2  5  6
5  2  3  4  5  6
6  2  3  4  5  6
7  3  4  5  6  7

I'd like to create a 'key' column as follows:
   a  b  c  d  e  key
1  1  2  3  4  5  12345
2  1  2  3  4  6  12346
3  1  2  3  4  7  12347
4  1  2  2  5  6  12256
5  2  3  4  5  6  23456
6  2  3  4  5  6  23456
7  3  4  5  6  7  34567

Now the problem with this of course is that row 5 & 6 are duplicates.
I'd like to be able to create unique keys like so:
   a  b  c  d  e  key
1  1  2  3  4  5  12345_1
2  1  2  3  4  6  12346_1
3  1  2  3  4  7  12347_1
4  1  2  2  5  6  12256_1
5  2  3  4  5  6  23456_1
6  2  3  4  5  6  23456_2
7  3  4  5  6  7  34567_1

Not sure how to do this or if this is the best method - appreciate any help.
Thanks
Edit: Columns will be mostly strings, not numeric.

A: On way is to hash to tuple of each row:
In [11]: df.apply(lambda x: hash(tuple(x)), axis=1)
Out[11]:
1   -2898633648302616629
2   -2898619338595901633
3   -2898621714079554433
4   -9151203046966584651
5    1657626630271466437
6    1657626630271466437
7    3771657657075408722
dtype: int64

In [12]: df['key'] = df.apply(lambda x: hash(tuple(x)), axis=1)

In [13]: df['key'].astype(str) + '_' + (df.groupby('key').cumcount() + 1).astype(str)
Out[13]:
1    -2898633648302616629_1
2    -2898619338595901633_1
3    -2898621714079554433_1
4    -9151203046966584651_1
5     1657626630271466437_1
6     1657626630271466437_2
7     3771657657075408722_1
dtype: object

Note: Generally you don't need to be doing this (it's unclear why you'd want to!).

A: try this.,
df['key']=df.apply(lambda x:'-'.join(x.values.tolist()),axis=1)
m=~df['key'].duplicated()
s= (df.groupby(m.cumsum()).cumcount()+1).astype(str)
df['key']=df['key']+'_'+s
print (df)

O/P:
   a  b  c  d  e          key
0  1  2  3  4  5  1-2-3-4-5_0
1  1  2  3  4  6  1-2-3-4-6_0
2  1  2  3  4  7  1-2-3-4-7_0
3  1  2  2  5  6  1-2-2-5-6_0
4  2  3  4  5  6  2-3-4-5-6_0
5  2  3  4  5  6  2-3-4-5-6_1
6  3  4  5  6  7  3-4-5-6-7_0
7  1  2  3  4  5  1-2-3-4-5_1

Another much simpler way:
df['key']=df['key']+'_'+(df.groupby('key').cumcount()).astype(str)

Explanation:

*

*first create your unique id using join.

*create a sequence s using duplicate and perform cumsum, restart when new value found.

*finally concat key and your sequence s.

A: Maybe you can do something link the following
import uuid
df['uuid'] = [uuid.uuid4() for __ in range(df.index.size)]

A: Another approach would be to use np.random.choice(range(10000,99999), len(df), replace=False) to generate unique random numbers without replacement for each row in your df:
df = pd.DataFrame(columns = ['a', 'b', 'c', 'd', 'e'],
                  data = [[1,  2,  3,  4,  5],[1,  2,  3,  4,  6],[1,  2,  3,  4,  7],[1,  2,  2,  5,  6],[2,  3,  4,  5,  6],[2,  3,  4,  5,  6],[3,  4,  5,  6,  7]])

df['key'] = np.random.choice(range(10000,99999), len(df), replace=False)

df

    a   b   c   d   e   key
0   1   2   3   4   5   10560
1   1   2   3   4   6   79547
2   1   2   3   4   7   24762
3   1   2   2   5   6   95221
4   2   3   4   5   6   79460
5   2   3   4   5   6   62820
6   3   4   5   6   7   82964


text:
Q: creating and dropping dynamically db_link each time connecting various DBs after updating table I want to create PL-SQL procedure which connect and update various DBs remotely from one db and update table on each DBs by creating dynamic db_link and this db_link should be created and dropped each time after updating the tables in all DBs. How can we do it? Please help.

A: Warning: There is a security breach about creating and dropping dynamically  db links because a table must store passwords for every remote account.
1-Create a table
Table name: REMOTE_INFO

host_name        varchar2(25) primary_key,
username_remote  varchar2(30),
password_remote  varchar2(30),
host_connection  varchar2(30),
table_local      varchar2(30),
schema_remote    varchar2(30),
table_remote     varchar2(30),
condition        varchar2(4000)

2-Package specification
create or replace package pk_remote
is
  /* ====================================================================================================
  -- ref: question on
  -- https://stackoverflow.com/questions/56339278/creating-and-dropping-dynamically-db-link-each-time-connecting-various-dbs-after
  -- 2019-05-30 by alvalongo
  ==================================================================================================== */
  kLINE_FEED   constant varchar2(1):=chr(10);
  --
  procedure pr_copy(p_iHost        varchar2,
                    p_oError   out number,
                    p_oMessage out varchar2
                   );
End pk_remote;

3-Package body
create or replace package body pk_remote
is
  /* ====================================================================================================
  -- ref: question on
  -- https://stackoverflow.com/questions/56339278/creating-and-dropping-dynamically-db-link-each-time-connecting-various-dbs-after
  -- 2019-05-30 by alvalongo
  ==================================================================================================== */
  --
  procedure pr_copy(p_iHost        varchar2,
                    p_oError   out number,
                    p_oMessage out varchar2
                   )
  is
    rcRemote   remote_info%rowtype;
    vLink_name varchar2(30);
    vSentence  varchar2(2000);
    ex_exit    exception;
  Begin
    p_oError:=0;
    p_oMessage:=null;
    if p_iHost is null then
       p_oError:=100;
       p_oMessage:='HOST cannot be null';
       raise ex_exit;
    End if;
    Begin
      select a.*
      into rcRemote
      from remote_info a
      where a.host_name=upper(trim(p_iHost));
    Exception
      when no_data_found then
           p_oError:=sqlcode;
           p_oMessage:='There is no host='||upper(trim(p_iHost));
           raise ex_exit;
    end;
    --
    vLink_name:=upper('DBL_'||rcRemote.host_name);
    --
    vSentence:=  'CREATE DATABASE LINK '||vLink_name||kLINE_FEED
               ||'CONNECT TO '||rcRemote.username_remote||kLINE_FEED
               ||'IDENTIFIED BY '||rcRemote.password_remote||kLINE_FEED
               ||'USING '||rcRemote.host_connection;
     --
     Begin
      execute immediate vSentence;
     Exception
      when others then
           p_oError:=sqlcode;
           p_oMessage:='Error creating db link:'||sqlerrm;
           raise ex_exit;
     end;
    --
    vSentence:=  'insert into '||rcRemote.schema_remote||','||rcRemote.table_remote||'@'||vLink_name||kLINE_FEED
               ||'select *'||kLINE_FEED
               ||'from '||rcRemote.table_local||' a'||kLINE_FEED
               ||'where '||rcRemote.condition;
     Begin
      execute immediate vSentence;
     Exception
      when others then
           p_oError:=sqlcode;
           p_oMessage:='Error inserting:'||sqlerrm;
           raise ex_exit;
     end;
    --
    vSentence:=  'drop DATABASE LINK '||vLink_name;
     --
     Begin
      execute immediate vSentence;
     Exception
      when others then
           p_oError:=sqlcode;
           p_oMessage:='Error dropping db link:'||sqlerrm;
           raise ex_exit;
     end;
  Exception
    when ex_exit then
         null;
    when others then
         p_oError:=sqlcode;
         p_oMessage:=sqlerrm;
  End pr_copy;
  --
End pk_remote;


text:
Q: Reinstall Windows 10 in virtualbox cannot activate right now I have a windows10-linux dual-boot system on my laptop. I rarely use windows but sometimes it is necessary. I installed windows10 in virtualbox but cannot activate it with the same product key, -makes sense.
My question is, if I deinstall the system on the real-machine, can I activate windows10 then on virtualbox? I used to reinstalled windows10 on the same machine, there was no problem. How could the server know, whether the key/system is activated or uninstalled?
Thanks

A: If Windows is preinstalled by the OEM, then the license (product key) is tied to that motherboard. An OEM license cannot be moved to a different motherboard, nor to a Virtual Machine.
If you purchased the Windows license directly from Microsoft, then you can move it to any machine or VM you wish.
The most common scenario for most folks is that their pre-installed Windows has an OEM license, so it cannot be moved to a VM.


text:
Q: how to auto convert nil to [NSNull null] when add it to array(dict)? I have some values need to be added to an array (using initWithObjects), and encode to JSON string later.
As everyone knows, when array meet a nil, it will stop read next value.
As convention of JSON Array, the nil should be act as an null in ordered position.
Should I check every value, and manually convert it to [NSNull null] before add it to array?

A:
Should I check every value, and manually convert it to [NSNull null] before add it to array?

Yes. You can create a simple helper method/function:
id GuardJSONElement(id arg) { return arg ? arg : [NSNull null]; }

and then:
[array addObject:GuardJSONElement(something)];


text:
Q: Why an object is invisible? I have a class. In this class I declare a a private variable private Agent agent;. In my class I have
private Thread controller = new Thread() {
...
}

Within the above private thread I call getParameter which is a private method of the considered class. Within the getParameter I call one of the methods of the agent. As a result I get a NullPointerException. So, I conclude that agent is not visible from the getParameter.
Why is that? Can it be that the reason of that is that the getParameter is within the private Thread? And, if it is the case, how the described problem can be resolved?
ADDED
I realized that I need to be more specific. My code is organized like that:
public class GameWindow {
   ...
   private Agent agent;
   ...
   private Thread controller = new Thread() {
        public void run() {
           ...
           Agent agent = new Agent();
           ...
           parameter = getParameter();
        }
  }
  ...
  private String getParameter() {
     ...
     agent.someMethod();
     ...
  }
}

ADDED 2
In the GameWindow I have:
public void startWindow() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            controller.start();
        }
    });
}

A: The NullPointerException has nothing to do with visibility. You are probably calling the getParameter method of a null object. Your agent variable is declared, but not initialiazed. You may want to code something like:
private Agent agent;
private Thread controller = new Thread() {
    agent = new Agent();
    // ...
    agent.getParameter(); // should not throw a NullPointerException
}

UPDATE AFTER CODE WAS ADDED
Your code has two definitions of agent. The first one in the class:
private Agent agent;

And the second one inside your run() method:
Agent agent = new Agent();

Your getParameter() method does not know the agent defined inside the run() method. It only knows the agent member of the class, which was not initialized. Your problem will be solved when you remove the second definition of agent:
public void run() {
       ...
       // Agent agent = new Agent();
       agent = new Agent(); // works fine: you are initiliazing the class member
       ...
       parameter = getParameter();
 }

OLD UPDATE:
The NullPointerException is thrown inside the getParameter() method. So I understand your code is like the following:
private Something getParameter() {
    agent.someMethod(); // exception thrown here
}

If this is your code, the problem remains the same: agent is not initialized. You must initialize it before calling any of its methods inside the getParameter() method.

A: Agent was never initialized.  You want something like this:
Agent agent = new Agent();

A: You appear to be creating this new thread in an instance initializer. Which means that the containing instance may not be fully initialized when the thread starts running (you don't show where you call start()).

And some unasked-for advice: (1) don't subclass thread, create a Runnable, and (2) don't create your own threads, use an ExecutorService

A: Ditto Roman, but let me add one clarifying point.
If you do not have visibility to an object, you will get an error message when you try to compile. A null pointer exception is a RUNTIME error, not a compile-time error. You will never, ever get a null pointer exception for a visibility problem, for the simple reason that you will not be able to run the program if you have visibility problems, because the compile will have failed.
A null pointer exception means that you have not assigned an actual instance of the object to a variable. That could mean you never created an instance at all, or it could mean that you have one declaration hiding another, like here.


text:
Q: OpenSSL 1.1 result in error: variable 'mtcp_methods_sockp' has initializer but incomplete type static BIO_METHOD mtcp_methods_sockp I am running apache bench (ab) and ported it with OpenSSL 1.0 support on top of mTCP support
https://github.com/vincentmli/mtcp/commit/642835f786aa642ea0f20fe8db9b09054639453a#diff-02f7a72f514e6e0543e832d37450c251
but it breaks after I upgraded OpenSSL 1.0 to OpenSSL 1.1, I found there are quite a few projects having same problems including libevent, libevent has the fix in https://github.com/libevent/libevent/commit/3e9e0a0d46e4508e8782ec3787c6d86bab63046d
so I borrowed the fix from libevent and applied the code fix below:
#include <openssl/bio.h>
#include "openssl-compat.h"
#define get_last_socket_error() errno
#define clear_socket_error()    errno=0
/* clone of openssl crypto/bio/bss_sock.c */

#ifdef HAVE_MTCP

static int mtcp_sock_write(BIO *h, const char *buf, int num);
static int mtcp_sock_read(BIO *h, char *buf, int size);
static int mtcp_sock_puts(BIO *h, const char *str);
static long mtcp_sock_ctrl(BIO *h, int cmd, long arg1, void *arg2);
static int mtcp_sock_new(BIO *h);
static int mtcp_sock_free(BIO *data);
int BIO_mtcp_sock_should_retry(int s);

/*
static BIO_METHOD mtcp_methods_sockp = {
    BIO_TYPE_SOCKET,
    "socket",
    mtcp_sock_write,
    mtcp_sock_read,
    mtcp_sock_puts,
    NULL,
    mtcp_sock_ctrl,
    mtcp_sock_new,
    mtcp_sock_free,
    NULL,
};

BIO_METHOD *BIO_mtcp_s_socket(void)
{
    return (&mtcp_methods_sockp);
}
*/

static BIO_METHOD *mtcp_methods_sockp;

static BIO_METHOD *
BIO_mtcp_s_socket(void)
{
        if (mtcp_methods_sockp == NULL) {
                mtcp_methods_sockp = BIO_meth_new(BIO_TYPE_SOCKET, "socket");
                if (mtcp_methods_sockp == NULL)
                        return NULL;
                BIO_meth_set_write(mtcp_methods_sockp, mtcp_sock_write);
                BIO_meth_set_read(mtcp_methods_sockp, mtcp_sock_read);
                BIO_meth_set_puts(mtcp_methods_sockp, mtcp_sock_puts);
                BIO_meth_set_ctrl(mtcp_methods_sockp, mtcp_sock_ctrl);
                BIO_meth_set_create(mtcp_methods_sockp, mtcp_sock_new);
                BIO_meth_set_destroy(mtcp_methods_sockp, mtcp_sock_free);
        }
        return mtcp_methods_sockp;
}

/*
BIO *BIO_mtcp_new_socket(mctx_t mctx, int fd, int close_flag)
{
    BIO *ret;

    ret = BIO_new(BIO_mtcp_s_socket());
    if (ret == NULL)
        return (NULL);
    BIO_set_fd(ret, fd, close_flag);
    ret->ptr = mctx;
    return (ret);
}
*/

BIO *BIO_mtcp_new_socket(mctx_t mctx, int fd, int close_flag)
{
    BIO *ret;

    if(!fd)
        return NULL;
    ret = BIO_new(BIO_mtcp_s_socket());
    if (ret == NULL)
        return (NULL);
    BIO_set_init(ret, 1);
    BIO_set_fd(ret, fd, close_flag);
    BIO_set_data(ret, mctx);
    return (ret);
}

/*
static int mtcp_sock_new(BIO *bi)
{
    bi->init = 0;
    bi->num = 0;
    bi->ptr = NULL;
    bi->flags = 0;
    return (1);
}
*/

static int mtcp_sock_new(BIO *bi)
{
    BIO_set_init(bi, 0);
    BIO_set_num(bi, 0);
    BIO_set_data(bi, NULL);
    BIO_set_flags(bi, 0);
    return (1);
}

/*
static int mtcp_sock_free(BIO *a)
{
    if (a == NULL)
        return (0);
    mctx_t mctx = (mctx_t)a->ptr;
    mtcp_close(mctx, a->num);

    return (1);
}
*/

static int mtcp_sock_free(BIO *a)
{
    if (a == NULL)
        return (0);
    mctx_t mctx = (mctx_t)BIO_get_data(a);
    mtcp_close(mctx, BIO_get_num(a));

    return (1);
}

/*
static int mtcp_sock_read(BIO *b, char *out, int outl)
{
    int ret = 0;
    mctx_t mctx = (mctx_t)b->ptr;

    if (out != NULL) {
        clear_socket_error();
        //ret = readsocket(b->num, out, outl);
        ret = mtcp_read(mctx, b->num, out, outl);
        BIO_clear_retry_flags(b);
        if (ret <= 0) {
            if (BIO_mtcp_sock_should_retry(ret))
                BIO_set_retry_read(b);
        }
    }
    return (ret);
}
*/

static int mtcp_sock_read(BIO *b, char *out, int outl)
{
    int ret = 0;
    mctx_t mctx = (mctx_t)BIO_get_data(b);

    if (out != NULL) {
        clear_socket_error();
        //ret = readsocket(b->num, out, outl);
        ret = mtcp_read(mctx, BIO_get_num(b), out, outl);
        BIO_clear_retry_flags(b);
        if (ret <= 0) {
            if (BIO_mtcp_sock_should_retry(ret))
                BIO_set_retry_read(b);
        }
    }
    return (ret);
}

/*
static int mtcp_sock_write(BIO *b, const char *in, int inl)
{
    int ret;
    mctx_t mctx = (mctx_t)b->ptr;

    clear_socket_error();
    //ret = writesocket(b->num, in, inl);
    ret = mtcp_write(mctx, b->num, in, inl);
    BIO_clear_retry_flags(b);
    if (ret <= 0) {
        if (BIO_mtcp_sock_should_retry(ret))
            BIO_set_retry_write(b);
    }
    return (ret);
}
*/

static int mtcp_sock_write(BIO *b, const char *in, int inl)
{
    int ret;
    mctx_t mctx = (mctx_t)BIO_get_data(b);

    clear_socket_error();
    //ret = writesocket(b->num, in, inl);
    ret = mtcp_write(mctx, BIO_get_num(b), in, inl);
    BIO_clear_retry_flags(b);
    if (ret <= 0) {
        if (BIO_mtcp_sock_should_retry(ret))
            BIO_set_retry_write(b);
    }
    return (ret);
}

/*
static long mtcp_sock_ctrl(BIO *b, int cmd, long num, void *ptr)
{
    long ret = 1;
    int *ip;

    switch (cmd) {
    case BIO_C_SET_FD:
        mtcp_sock_free(b);
        b->num = *((int *)ptr);
        b->shutdown = (int)num;
        b->init = 1;
        break;
    case BIO_C_GET_FD:
        if (b->init) {
            ip = (int *)ptr;
            if (ip != NULL)
                *ip = b->num;
            ret = b->num;
        } else
            ret = -1;
        break;
    case BIO_CTRL_GET_CLOSE:
        ret = b->shutdown;
        break;
    case BIO_CTRL_SET_CLOSE:
        b->shutdown = (int)num;
        break;
    case BIO_CTRL_DUP:
    case BIO_CTRL_FLUSH:
        ret = 1;
        break;
    default:
        ret = 0;
        break;
    }
    return (ret);
}
*/

static long mtcp_sock_ctrl(BIO *b, int cmd, long num, void *ptr)
{
    long ret = 1;
    int *ip;

    switch (cmd) {
    case BIO_C_SET_FD:
        mtcp_sock_free(b);
        BIO_set_num(b, *((int *)ptr));
        BIO_set_shutdown(b, (int)num);
        BIO_set_init(b, 1);
        break;
    case BIO_C_GET_FD:
        if (BIO_get_init(b)) {
            ip = (int *)ptr;
            if (ip != NULL)
                *ip = BIO_get_num(b);
            ret = BIO_get_num(b);
        } else
            ret = -1;
        break;
    case BIO_CTRL_GET_CLOSE:
        ret = BIO_get_shutdown(b);
        break;
    case BIO_CTRL_SET_CLOSE:
        BIO_set_shutdown(b, (int)num);
        break;
    case BIO_CTRL_DUP:
    case BIO_CTRL_FLUSH:
        ret = 1;
        break;
    default:
        ret = 0;
        break;
    }
    return (ret);
}

here is the openssl-compat.h
#ifndef OPENSSL_COMPAT_H
#define OPENSSL_COMPAT_H

#include <openssl/bio.h>

#if (OPENSSL_VERSION_NUMBER < 0x10100000L)

static inline BIO_METHOD *BIO_meth_new(int type, const char *name)
{
        BIO_METHOD *biom = calloc(1, sizeof(BIO_METHOD));

        if (biom != NULL) {
                biom->type = type;
                biom->name = name;
        }
        return biom;
}

#define BIO_meth_set_write(b, f) (b)->bwrite = (f)
#define BIO_meth_set_read(b, f) (b)->bread = (f)
#define BIO_meth_set_puts(b, f) (b)->bputs = (f)
#define BIO_meth_set_ctrl(b, f) (b)->ctrl = (f)
#define BIO_meth_set_create(b, f) (b)->create = (f)
#define BIO_meth_set_destroy(b, f) (b)->destroy = (f)

#define BIO_set_init(b, val) (b)->init = (val)
#define BIO_set_data(b, val) (b)->ptr = (val)
#define BIO_set_shutdown(b, val) (b)->shutdown = (val)
#define BIO_set_num(b, val) (b)->num = (val)
#define BIO_set_flags(b, val) (b)->flags = (val)
#define BIO_get_init(b) (b)->init
#define BIO_get_data(b) (b)->ptr
#define BIO_get_shutdown(b) (b)->shutdown
#define BIO_get_num(b) (b)->num
#define BIO_get_flags(b) (b)->flags

#define TLS_method SSLv23_method

#endif /* (OPENSSL_VERSION_NUMBER < 0x10100000L) */

#endif /* OPENSSL_COMPAT_H */

but I got compiling error
make[2]: Entering directory '/usr/src/mtcp/apps/apache_benchmark/support'
/usr/src/mtcp/apps/apache_benchmark/srclib/apr/libtool --silent --mode=compile gcc -g -O2 -pthread -I/usr/src/mtcp/mtcp/lib/ -I/usr/src/mtcp/mtcp/src/include/ -DMULTI_THREADED -I/usr/src/mtcp/mtcp/lib/ -I/usr/src/mtcp/mtcp/src/include/ -DMULTI_THREADED    -DLINUX -D_REENTRANT -D_GNU_SOURCE    -I/usr/src/mtcp/apps/apache_benchmark/srclib/pcre -I. -I/usr/src/mtcp/apps/apache_benchmark/os/unix -I/usr/src/mtcp/apps/apache_benchmark/include -I/usr/src/mtcp/apps/apache_benchmark/srclib/apr/include -I/usr/src/mtcp/apps/apache_benchmark/srclib/apr-util/include -I/usr/src/mtcp/apps/apache_benchmark/srclib/apr-util/xml/expat/lib -I/usr/lib/include -I/usr/src/mtcp/apps/apache_benchmark/modules/ssl  -prefer-non-pic -static -c ab.c && touch ab.lo
ab.c: In function 'mtcp_sock_new':
ab.c:547:5: warning: implicit declaration of function 'BIO_set_num'; did you mean 'BIO_set_next'? [-Wimplicit-function-declaration]
     BIO_set_num(bi, 0);
     ^~~~~~~~~~~
     BIO_set_next
ab.c: In function 'mtcp_sock_free':
ab.c:570:22: warning: implicit declaration of function 'BIO_get_num'; did you mean 'BIO_get_init'? [-Wimplicit-function-declaration]
     mtcp_close(mctx, BIO_get_num(a));
                      ^~~~~~~~~~~
                      BIO_get_init
..........CUT......
/usr/src/mtcp/apps/apache_benchmark/support/ab.c:547: undefined reference to `BIO_set_num'
.libs/ab.o: In function `mtcp_sock_free':
/usr/src/mtcp/apps/apache_benchmark/support/ab.c:570: undefined reference to `BIO_get_num'
.libs/ab.o: In function `mtcp_sock_ctrl':
/usr/src/mtcp/apps/apache_benchmark/support/ab.c:703: undefined reference to `BIO_get_num'
/usr/src/mtcp/apps/apache_benchmark/support/ab.c:704: undefined reference to `BIO_get_num'
/usr/src/mtcp/apps/apache_benchmark/support/ab.c:695: undefined reference to `BIO_set_num'
.libs/ab.o: In function `mtcp_sock_read':
/usr/src/mtcp/apps/apache_benchmark/support/ab.c:603: undefined reference to `BIO_get_num'
.libs/ab.o: In function `mtcp_sock_write':
/usr/src/mtcp/apps/apache_benchmark/support/ab.c:638: undefined reference to `BIO_get_num'
.libs/ab.o: In function `main':
/usr/src/mtcp/apps/apache_benchmark/support/ab.c:2916: undefined reference to `SSLv3_client_method'
/usr/src/mtcp/apps/apache_benchmark/support/ab.c:2913: undefined reference to `SSLv2_client_method'
/usr/src/mtcp/apps/apache_benchmark/support/ab.c:2978: undefined reference to `CRYPTO_malloc_init'
collect2: error: ld returned 1 exit status
Makefile:38: recipe for target 'ab' failed
make[2]: *** [ab] Error 1

Since I defined BIO_set/get_init/data/shutdown/num in openssl-compat.h, why it only shows undefined reference to `BIO_set/set_num', not others? I am confused


text:
Q: User specific report in SQL - how to select data based on User Domain name? Due to security requirements, I want to make report where each salesman views only sales data of his Region, and may not view data of other salesmen.
I can imagine that a salesman generating the report can somehow pass in a query his DomainUsername (UserID) based on Windows authentication. Then the query will select only the data based on that UserID. How to get DomainUsername (UserID) of the user accessing the report in SQL query?
What are the ways for making user specific reports?

A: In SQL Server, you should be able to get the domain_username of the user using:
SELECT user

If you are looking for his ID, may be you can check in the sysusers table using the domain_username fetched from the above query.


text:
Q: KeyError: 'oauth_state' Hi I am currently trying to test the code on https://github.com/futurice/whereareyou
I have a problem on the master server side.
The error received
Traceback (most recent call last):
File "/home/arms/.local/lib/python2.7/site-packages/flask/app.py", line 1997, in call
return self.wsgi_app(environ, start_response)
File "/home/arms/.local/lib/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/home/arms/.local/lib/python2.7/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/arms/.local/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/home/arms/.local/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/arms/.local/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/arms/.local/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/home/arms/.local/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functionsrule.endpoint
File "/home/arms/Project/whereareyou/app.py", line 112, in callback
google = get_google_auth(state=session['oauth_state'])
File "/home/arms/.local/lib/python2.7/site-packages/werkzeug/local.py", line 377, in
getitem = lambda x, i: x._get_current_object()[i]
KeyError: 'oauth_state'

Please help. Thank you.

A: I was facing the same problem when I was using session in my app with the following link provided by Flask :
http://127.0.0.1:5000/
Solution: It however perfectly works with http://localhost:5000/
Just replace your local IP address(127.0.0.1) with "localhost".


text:
Q: Mixed boundary value problems for Heat equation This might be a very simple question, but basically I am looking for a good reference for studying the heat equation on Riemannian manifolds with boundary, specifically when data is put on lateral sides of the boundary. A more precise formulation is given below.
Let $(M,g)$ be a compact smooth Riemannian manifold with a smooth boundary. Let $T>0$, let $V\in C^{\infty}([0,T]\times M)$ and consider the heat equation with boundary data $f$:
\begin{equation}\label{pf0}
\begin{aligned}
\begin{cases}
\partial_t u-\Delta_g u+Vu=0\,\quad &\text{on $(0,T)\times M$},
\\
u=f\,\quad &\text{on $\Sigma=(0,T)\times \partial M$,}\\
u(0,x)=0 \,\quad &\text{on $M$,}
\end{cases}
    \end{aligned}
\end{equation}
I haven't found any references for regularity of solutions to this rather standard PDE with $f$ in Sobolev spaces. Can something precise be said about the regularity of solutions, say if $f \in H^k_0(\Sigma)$ for $k>0$ or perhaps when $f \in H^r_0(0,T;H^s(\partial M))$?


text:
Q: Combine Google Analytics with external data I need to merge my GA statistics with external data (stored in SQL but I can expose them by some web service). Perfectly all the data should be available in GA for reporting but I found no solution for import the data into GA.
Do you know any piece of software that can do this and present the merged results in some readable form to the user? It should meet the following requirements:

*

*Should be a web application

*Should not be a software-as-a-service solution (will be hosted in infrastructure provided by me)

*Should provide some level of automation in data import

Analytics Canvas looks interesting but I wonder if there are any other applications.

A: Analytics Canvas is indeed a good option, it has really good data extraction and transformation capabilities, and handles nicely any data out of both SQL data sources and the most recent GA API.

A: Google Analytics allows you import data through the API and manually through the Web Interface. For example this is a very good article on integrating external CRM user data with Google Analytics. But Google analytics also support importing the following types of data:

*

*Product Data

*Refund Data

*Cost Data

*Content Data

*User Data

You can also create your own custom dimensions and metrics and import that data into Google Analytics and view the results in your own custom reports.


text: Q: Is it possible to have a notification in my app when user connects to bluetooth while in background? I want to achieve a certain behavior in my application - regardless of the app's state. When a user connects to a bluetooth device from his phone, I want to get a notification in my app and do something. I tried to achieve this using AVAudioSession.routeChangeNotification but it seems to work only when the app is in the foreground. I read that the events newDeviceAvailable and oldDeviceUnavailable will be triggered in the background only if my app plays music. However my app doesn't - I just want to know that there're a connection change. Are there any manipulations that can be done, to listen to those events even if the app is in the foreground/killed?


text:
Q: Bottle serve file from a different directory I have simple Bottle application which serves a page for /Startpage location. The index.html page is located under /banana folder and the banana folder is located under the same folder where my views.py exist.
When I try this, its unable to find the page and throws internal server error
@app.wrap_app.route('/StartPage',method='GET')
def doStartPage():
    return template('banana/index.html')

How can I refer my /banana folder in my template?

A: The bottle FAQ specifies the following

Bottle searches in ./ and ./views/ for templates. In a mod_python or mod_wsgi environment, the working directory (./) depends on your Apache settings. You should add an absolute path to the template search path so bottle searches the right paths.

You will need to add the bananas folder to the TEMPLATE_PATH
base_path = os.path.abspath(os.path.dirname(__file__))
bananas_path = os.path.join(base_path, 'bananas')
bottle.TEMPLATE_PATH.insert(0, bananas_path)

EDIT: Improved the answer with Graham's suggestion to use paths relative to where the code is located.

A: You can do something like this :
Create a rooting rule for your folder :
@route('/banana/<filepath:path>')
def file_stac(filepath):
    return static_file(filepath, root="./banana")

And then, you only need to refer to this folder like this :
@route('/foo')
def bar():
    return template('banana/foo.tpl')

You can do the same for as many folder as you want, and this is usefull for serving css/js files inside a template (on your template, you can then do :
<link href="banana/css/bootstrap.min.css" rel="stylesheet">

Hope it helped !

A: Almost 8 years late, but I did as follow for my issue, but replacing my folder with yours:
@route(/banana/<filename>)
def banana(filename):
    return static_file(filename, root='./views/banana/')


text:
Q: Factorize $(x+1)(x+2)(x+3)(x+6)- 3x^2$ I'm preparing for an exam and was solving a few sample questions when I got this question -
Factorize : $$(x+1)(x+2)(x+3)(x+6)- 3x^2$$
I don't really know where to start, but I expanded everything to get :
$$x^4 + 12x^3 + 44x^2 + 72x + 36$$
I used rational roots test and Descartes rule of signs to get guesses for the roots. I tried them all and it appears that this polynomial has no rational roots.So, what  should I do to factorize this polynomial ?
(I used wolfram alpha and got the factorization : $(x^2 + 4x + 6) (x^2 + 8x + 6)$ But can someone explain how to get there ?)

A: A way to do it is to write $(x+2)(x+3) = x^2 + 6x + 6 - x$, $(x+1)(x+6) = x^2 + 6x + 6 + x$, so
$$
(x+2)(x+3)(x+1)(x+6) = (x^2 + 6x + 6)^2 -x^2
$$
which gives that
$$
(x+2)(x+3)(x+1)(x+6) - 3x^2 = (x^2 + 6x + 6)^2 -4x^2 = (x^2+ 4x + 6)(x^2 +8x + 6).
$$

A: I'm assuming that you are looking for a factorization of the polynomial
$$
f = x^4 + 12x^3 + 44x^2 + 72x + 36
$$
in $\mathbb Q[x]$.
By the Lemma of Gauss and the fact that $f$ is monic, this is the same as looking for a factorization in $\mathbb Z[x]$.
Since there are no rational roots, the only remaining possibility is the factorization into two factors of degree 2. Since the polynomial is monic, the factors may be assumed to be monic.
So the putative factors have the form $x^2 + ax + b$ and $x^2 + cx + d$ with $a,b,c,d\in\mathbb Z$.
This leads to
$$
f = (x^2 + ax + b)(x^2 + cx + d) = x^4 + (a + c)x^3 + (ac + b + d)x^2 + (ad + bc)x + bd.
$$
Comparing the coefficients, we get four equations
$$
a+c = 12\\
ac + b + d = 44\\
ad + bc = 72\\
bd = 36
$$
Up to swapping the two factors, the last equation has the solutions
$$
(b,d)\in\{(1,36),(-1,-36),(2,18),(-2,-18),(3,12),(-3,-12),(4,9),(-4,-9),(6,6),(-6,-6)\}.
$$
It's a bit of work, but plugging these values into the remaining three equations, you find that only for $b=d=6$ there is a solution, which is $a = 4$, $b = 8$ or $a = 8$, $b=4$. This gives you the two factors.

A: $$(x+1)(x+2)(x+3)(x+6)-3x²$$
$$(x+1)(x+6)(x+3)(x+2)-3x²$$
$$(x²+6x+1x+6)(x²+3x+2x+6)-3x²$$
$$(x²+6x+6+1x)(x²+5x+6+x-x)-3x²$$
$$(x²+6x+6+1x)(x²+5x+x+6-x)-3x²$$
$$(x²+6x+6+1x)(x²+6x+6-x)-3x²$$
$$(x²+6x+6)²(+1x)(-x)-3x²$$
$$(x²+6x+6)²-x²-3x²$$
$$(x²+6x+6)²-4x²$$
$$(x²+6x+6)²-(2x)²$$
Apply $a²-b²=(a+b)(a-b)$
$$(x²+6x+6+2x)(x²+6x+6-2x)$$
$$(x²+8x+6)(x²+6x-2x+6)$$
$$(x²+8x+6)(x²+4x+6)$$
$$x(x+8+6/x)x(x+4+6/x)$$
Answer: $$x²(x+8+6/x)(x+4+6/x)$$

A: $(x+1)(x+2)(x+3)(x+6)-3x^2$
$\rightarrow(x+1)(x+6)(x+2)(x+3)-3x^2$
$\rightarrow(x^2+x+6x+6)(x^2+2x+3x+6)-3x^2$
$\rightarrow(x^2+7x+6)(x^2+5x+6)-3x^2$
$\rightarrow(x^2+6+7x)(x^2+6+5x)-3x^2$
Put :- $x^2+6=y$ eq($1$) . So :-
$(y+7x)(y+5x)-3x^2$
$\rightarrow y^2+7xy+5xy+35x^2-3x^2$
$\rightarrow y^2+12xy+32x^2$
$\rightarrow y^2+4xy+8xy+32x^2$
$\rightarrow y(y+4x)+8x(y+4x)$
$\rightarrow (y+4x)(y+8x)$
Put value of $y$ from eq(1), we get :-
$\rightarrow (x^2+6+4x)(x^2+6+8x)$


text:
Q: Прямоугольники следуют по криволинейному пути С помощью div, shapes или svgs можно ли изогнуть элемент, чтобы он следовал по криволинейному пути?
Ниже просто пример, но представьте прямоугольники, изгибающиеся по краям, прямо сейчас он только что повернул на 90 градусов от одного кадра к другому.

<!DOCTYPE html>

<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">      <title>frame</title>

Свободный перевод вопроса Curve rectangle to follow a path от участника  @Mateus Silva.

A: Это решение SVG. Я использую 4 перекрывающихся paths, где stroke-dasharray выглядит следующим образом: stroke-dasharray: 2 2 2 2 2 2 2 2 2 2 242 Если вы суммируете тире и промежутки, общее количество равно 260.
Также добавлено stroke-linecap: round. Когда тире находятся очень близко к одному из других
stroke-linecap: round, они накладываются друг на друга, создавая видимость непрерывной линии.
Общая длина path также составляет 260. Я анимирую свойство stroke-dashoffset path.

path {
  fill: none;
  stroke-width: 10;
  stroke-linecap: round;
  stroke-dasharray: 2 2 2 2 2 2 2 2 2 242;
  animation: dash 5s linear infinite;
}

@keyframes dash {
  to {
    stroke-dashoffset: -260;
  }
}
<svg viewBox="0 0 100 70" >

  <path id="pth" stroke="red" d="M10,10L90,10L90,60L10,60z" />

  <path stroke="blue" d="M70,10L90,10L90,60L10,60L10,10z" />

  <path stroke="green" d="M90,60L10,60L10,10L90,10z" />

  <path stroke="orange" d="M30,60L10,60L10,10L90,10L90,60z" />

</svg>

UPDATE
Чтобы избежать мерцания в углах, я меняю прямоугольные path на path со скругленными углами. Чтобы прояснить, что я имею в виду, я добавляю дополнительный path: #track.

path {
  fill: none;
  stroke-width: 10;
  stroke-linecap: round;
  stroke-dasharray: 2 2 2 2 2 2 2 2 2 225;
  animation: dash 5s linear infinite;
}

#track {
  stroke-width: 1;
  stroke-dasharray: 245 0;
}

@keyframes dash {
  to {
    stroke-dashoffset: -245;
  }
}

svg {
  width: 300px;
}
<svg viewBox="0 0 100 70">

  <path id="pth" stroke="red" d="M27.000,10.000 Q37,10 47.000,10.000L80.000,10.000 Q90,10 90.000,20.000L90.000,50.000 Q90,60 80.000,60.000L20.000,60.000 Q10,60 10.000,50.000L10.000,20.000 Q10,10 20.000,10.000Z" />

  <path stroke="blue" d="M90.000,27.000 Q90,37 90.000,47.000L90.000,50.000 Q90,60 80.000,60.000L20.000,60.000 Q10,60 10.000,50.000L10.000,20.000 Q10,10 20.000,10.000L80.000,10.000 Q90,10 90.000,20.000Z" />

  <path stroke="green" d="M73.000,60.000 Q63,60 53.000,60.000L20.000,60.000 Q10,60 10.000,50.000L10.000,20.000 Q10,10 20.000,10.000L80.000,10.000 Q90,10 90.000,20.000L90.000,50.000 Q90,60 80.000,60.000Z" />

  <path stroke="orange" d="M10.000,45.000 Q10,35 10.000,25.000L10.000,20.000 Q10,10 20.000,10.000L80.000,10.000 Q90,10 90.000,20.000L90.000,50.000 Q90,60 80.000,60.000L20.000,60.000 Q10,60 10.000,50.000Z" />

  <path id="track" d="M90.000,27.000 Q90,37 90.000,47.000L90.000,50.000 Q90,60 80.000,60.000L20.000,60.000 Q10,60 10.000,50.000L10.000,20.000 Q10,10 20.000,10.000L80.000,10.000 Q90,10 90.000,20.000Z" stroke="black" />

</svg>

Свободный перевод  ответа от участника  @enxaneta.


text:
Q: Best practice for DAO pattern? I've seen a lot of codes use a service-dao pattern , I don't know the origin of this pattern . It force the front layer call service  , then delegates some of the service task to dao.
I want to ask :

*

*Does DAO layer do purely data access related task ? What about things like exception encapsulation?

*Is there any other pattern can be used to replace this or better than this ?

*I think pojo domain models and transaction scripts  make even simple problem became complicated  , is it possible to completely eliminate dao layer ?

A: The main goal of such a layer is to provide abstraction of the persistance back-end. however, most of the times, due to specificities of persistance back-end, total hiding is not possible; A typical example is the query handling. To query a DB using hibernate, you'll write some kind of query code (using HQL, query API, ...) and a totally different paradigm when using JCR, a BigTable, or something else. As a consequence, most of the time, this pattern fails.
Besides there is also the - more annoying - issue of DAO/DTO. You are then pushed forward to write a first class holding your data, then a second copying data from your first one without any added value just for the sake of layer isolation.
There is however some work that has been done in this field. For a micro-framework i've started and implemented for google-app-engine, I've made a little list of so-called dao frameworks easying this rather mundane code.
Notice I plan, in the future, to be able to offer total transparency through gaedo service definition, but it's only a hope ;-) (and is not of immediate interest to you, I guess).

A: Access to data varies depending on the source of the data. Access to persistent storage, such as to a database, varies greatly depending on the type of storage (relational databases, object-oriented databases, flat files, and so forth) and the vendor implementation.
Use a Data Access Object (DAO) to abstract and encapsulate all access to the data source. The DAO manages the connection with the data source to obtain and store data.
The DAO implements the access mechanism required to work with the data source. The data source could be a persistent store like an RDBMS, an external service like a B2B exchange, a repository like an LDAP database, or a business service accessed via CORBA Internet Inter-ORB Protocol (IIOP) or low-level sockets. The business component that relies on the DAO uses the simpler interface exposed by the DAO for its clients. The DAO completely hides the data source implementation details from its clients. Because the interface exposed by the DAO to clients does not change when the underlying data source implementation changes, this pattern allows the DAO to adapt to different storage schemes without affecting its clients or business components. Essentially, the DAO acts as an adapter between the component and the data source.

A: Ideally, your DAO layer 'abstracts away' the access to some data storage system (database, file system, LDAP directory, ...). So in that sense it is used only for data access related tasks. However, you could also have a DAO layer that accesses a web service or some other component external to your application. That's the key point, it provides access to some external component.
The main idea is that there are no implementation details of your DAO layer that escape to higher layers (isolation). A good starting point for thinking about this is: what would I need to do if I plan to replace the component (a database for example) that my DAO layer provides access to? For example, you have some data inside XML files and you plan to migrate the data to a database.
Suppose you have all kinds of XML-related exceptions that escape your DAO layer. Then it becomes quite hard to migrate your XML layer to a database layer. However, if you've encapsulated all implementation details of your DAO layer, this will become a lot easier.
In the end, it's about maintainability of your code. The less dependencies you have on implementation details of a specific layer (services, DAO, ...), the better maintainable your code is.


text:
Q: How to Build RTEMS 4.11 environment properly in a Linux Mint I'm an unexperienced linux and rtems user trying to build and configure rtems 4.11 environment on a Linux Mint host. I want this environment to compile a RTEMS application for an ERC32 chipset. I'm following the instructions given by the 4.11 version of the RTEMS Source Builder Manual. I've done the suggested steps but when it comes to the building command:
../source-builder/sb-set-builder --log=l-sparc.txt \   <1>
      --prefix=$HOME/development/rtems/4.11 \       <2>
      4.11/rtems-sparc

it fails and returns:

"Rtems Source Builder - Set Builder, 5 (35c533f545c8) Build set:
  4.11/rtems-sparc error: no build set file found: 4.11/rtems-sparc.bset Build FAILED"

I used the command:
 ../source-builder/sb-set-builder --list-bset

in the list appears:

5/rtems-sparc.bset  6/rtems-sparc.b

set
So I found another question related to this:
no build set file found 4.11/rtems-sparc on rtems (VB)
The answer says to use the following command:
../source-builder/sb-set-builder \
    --log=1-sparc.txt \
    --prefix=${HOME}/rtems-4.11-work/tools 5/rtems-sparc

note that the 4.11 was replaced by 5. I used this command and the build
worked, however all executables now are like "sparc-rtems5-something".
I tried to compile a hello_world.c example with "sparc-rtems5-gcc" but it
is missing rtems.h
I thought that after the building steps everything including dependencies
would be in their proper directories and the compiler would recognize it.
Also, I've searched for the rtems.h file and I haven't found it in any part of
the system.
After all the history, I have some questions:
1) Is it good or technically appropriate to replace 4.11 by 5 in that
   step ? Given that a supposedly I have a 4.11 environment.
2) What is that 5 and 6 directories with each one a sparc bset ?
   Why two sparc bsets ?
3) Have been the 4.11 git directories changed over years ? Even
   though it is old.
4) Could someone explain how to build properly the rtems 4.11 system
   or at least recommend some guide?
It is worth noting that I found the documentation too confusing for a beginner. There are three different explanations of the environment, two in the user guide (quick start and installation sections) and one in the Source Builder docs. Also they differ in instructions. So I don't know which one or which part of each one to follow.
My  uname -a command output:

Linux michel-COM 4.15.0-45-generic #48~16.04.1-Ubuntu SMP Tue Jan 29
  18:03:48 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

A: Short answer first: If you want to build a RTEMS 4.11 toolchain, you have to check out the 4.11 branch of the source builder. Try git checkout -t origin/4.11 in the rtems source builder directory. After that, a ../source-builder/sb-set-builder --list-bsets should list the 4.11/rtems-sparc.bset.
Now for the four questions:

1) Is it good or technically appropriate to replace 4.11 by 5 in that step ? Given that a supposedly I have a 4.11 environment.

If you want a 4.11 toolchain, you should not replace 4.11 by 5. Instead use the 4.11 release branches.

2) What is that 5 and 6 directories with each one a sparc bset ?
  Why two sparc bsets ?

The current development version of RTEMS is 5. I would recommend to use RTEMS 5 for most new developments. In general the development version works quite stable and most active projects that I know of use a snapshot of that version. It's also the one with the best community support.
6 is a experimental version of the toolchain only. While 5 uses gcc releases (most of the time), 6 is updated automatically to snapshots. See https://lists.rtems.org/pipermail/devel/2018-December/023954.html for details how that one was created.

3) Have been the 4.11 git directories changed over years ? Even though it is old.

4.11 has been moved to branches.

4) Could someone explain how to build properly the rtems 4.11 system or at least recommend some guide?

You should be able to follow the documentation with the difference, that you have to use the 4.11 branches of all repositories.

It is worth noting that I found the documentation too confusing for a beginner. There are three different explanations of the environment, two in the user guide (quick start and installation sections) and one in the Source Builder docs. Also they differ in instructions. So I don't know which one or which part of each one to follow.

I have to be honest: I haven't started my RTEMS work with the documentation. So I'm not really sure about it's quality. I know that at least some of the points have been addressed in the current (version 5) documentation. For example, the source builder manual has been eliminated.


text:
Q: Projecting an instance from a A4Solution I'm trying to make a new UI to visualize my Alloy instances. I've got an A4Solution and have been successful in extracting atoms, relations, checking atom signatures BUT I can't seem to understand how to project the instance on some sig.
I've noticed that I can try to use the edu.mit.csail.sdg.alloy4viz.AlloyInstance, I've got options to project there, but that'd imply in starting over, from a different angle.
Would that be the way to go? I'd prefer to extract that from the A4Solution object.
Thanks

A: You might want to look at the edu.mit.csail.sdg.alloy4viz.StaticProjector class and its project methods---that's how the Alloy Visualizer implements projections.  If your visualization uses the edu.mit.csail.sdg.alloy4viz.AlloyModel class, you should be able to reuse the existing code in StaticProjector; from your post it seems, however, that you'd prefer not use any of the alloy4viz classes, in which case it should not be too difficult to understand how StaticProjector works and reapply the same ideas to your project.  Or you could convert an A4Solution object to an AlloyInstance[1] and build your visualizer around the alloy4viz classes, which, in my opinion, would be a good way to go about your project.
[1] something like:
a4sol.writeXML("instance.xml")
AlloyInstance inst = StaticInstanceReader.parseInstance(new File("instance.xml"));


text:
Q: Manipulate Nested Boolean Query String in Python I have string boolean queries like this
   queryString= """And(
                      OR(abc,xyz,wxy),
                      AND(AND(xyz,wxy),xzy),
                      XOR(x1,y1, AND(xy,zz))
                      )"""

At current it is hard for me to modify the above query string, as I want to

*

*Add another OR(x3,y3) in the last XOR

*Remove entire  OR(abc,xyz,wxy)
with desired output
   resultQueryString= """And(
                            AND(AND(xyz,wxy),xzy),
                            XOR(x1,y1, AND(xy,zz),OR(x3,y3))
                            )"""

I think I cannot easily do it unless I come up with a sophisticated regex for each different query.
I am trying to write a python function which would take above string boolean query as input and output a tree data structure.
So that I can traverse the tree and evaluate or change whatever portion of query I want to change.
In above example, if I had it as a tree, I can easily see the root is AND and traverse/modify other branches so on.

A: The ast.parse function seems to do almost exactly what you want:
ast.dump(ast.parse("""And(
                        AND(AND(xyz,wxy),xzy),
                        XOR(x1,y1, AND(xy,zz),OR(x3,y3))
                        )""").body[0].value)

Call(func=Name(id='And', ctx=Load()), args=[Call(func=Name(id='AND', ctx=Load()), args=[Call(func=Name(id='AND', ctx=Load()), args=[Name(id='xyz', ctx=Load()), Name(id='wxy', ctx=Load())], keywords=[], starargs=None, kwargs=None), Name(id='xzy', ctx=Load())], keywords=[], starargs=None, kwargs=None), Call(func=Name(id='XOR', ctx=Load()), args=[Name(id='x1', ctx=Load()), Name(id='y1', ctx=Load()), Call(func=Name(id='AND', ctx=Load()), args=[Name(id='xy', ctx=Load()), Name(id='zz', ctx=Load())], keywords=[], starargs=None, kwargs=None), Call(func=Name(id='OR', ctx=Load()), args=[Name(id='x3', ctx=Load()), Name(id='y3', ctx=Load())], keywords=[], starargs=None, kwargs=None)], keywords=[], starargs=None, kwargs=None)], keywords=[], starargs=None, kwargs=None)

(the .body[0].value removes two pointless layers of abstraction, and the .dump is just for output.
Here is the code that then does the transformations you requested on the output:
class Filterer(ast.NodeTransformer):
    def visit_Call(self, node):
            name=node.func.id
            if name == "OR" and len(node.args) == 3:
                    return None
            elif name == "XOR":
                    args = [ast.Name("x3",ast.Load()),
                            ast.Name("y3",ast.Load())]
                    func = ast.Name("OR",ast.Load())
                    node.args.append(ast.Call(func, args, [], None, None))
            return self.generic_visit(node)

and here is the code that prints the result in your format with the exception of whitespace: (Python doesn't have a builtin in its ast module for this):
class Printer(ast.NodeVisitor):
    def visit_Call(self, node):
            self.visit(node.func)
            print("(",end="")
            comma = False
            for arg in node.args:
                    if comma:
                            print(",",end="")
                    comma=True
                    self.visit(arg)
            print(")",end="")
    def visit_Name(self, node):
            print(node.id,end="")

Thus, the final code would be:
Printer().visit(Filterer().visit(ast.parse(queryString)))


text:
Q: Unsupported Gradle version error with Android Studio 2021.3 when creating a new Android Studio Project I am trying to build a new Android Studio Project as the title says and I am having this error in the Android Studio IDE :
Unsupported Gradle.
The project uses Gradle version which is incompatible with Android Studio 2021.3.

Possible solution:
 - Open Gradle wrapper settings, upgrade version to 3.0 or newer and reload the project

gradle-wrapper.properties
#Thu Dec 15 13:54:44 EET 2022
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME

I could not find any solution on the Internet. Please help.
I have tried changing the version to 3.0 but I don't know how to solve this problem and I need to do a project for university in Kotlin, and it does not work.


text:
Q: Wordpress not loading Woocommerce attributes section in product While I tried to add a new product to My Wordpress Woocommerce site. The Product data -> attributes section shows a loading icon and not allowing to add new Attributes to the page.
Because of this issue I updated the Wordpress and Woocommerce to new version. Also I tried to deactivate some plugin. Nothing works. I installed the following plugins in My Wordpress site.

*

*Booster for WooCommerce

*Contact Form 7

*Envato WordPress Toolkit

*Google Analytics Counter Tracker

*Header and Footer Scripts

*Jetpack by WordPress.com

*Nancy Shortcodes

*WPBakery Visual Composer

My Google chrome console showing the following error.

A: Problem:
The problem happening because of the Visual Composer Plugin.
Solution for The Problem:
The problem can be solved by UN-installing the Visual Composer Plugin and install the latest version of the plugin.
The direct plugin update will not work sometimes, So try to install by removing the folder of the plugin from the WordPress and upload the latest version manually and do the update.
Try to update the plugin with the Ultimate Visual Composer Version 3.16.12. This will solve your problem.


text:
Q: How to visualize tensorboard for tensorflow 2 I am a newbie and I have had some trouble in using tensorboard.
I stared Spyder in Anaconda prompt by
conda activate D:\Software\Anaconda\envs\tf
spyder

And this is my simple code in file trial.py
import tensorflow as tf
a = 2
b = 3
x = tf.add(a, b)
writer = tf.summary.create_file_writer('./graphs')
print(writer)

Then I ran this code in spyder. I opened another Anaconda prompt and added this line
conda activate D:\Software\Anaconda\envs\tf
tensorboard --logdir=D:\Dung\Maytinh\Python\graphs --port 6006

I opened my Chrome and typed: http://localhost:6006/. The result was below:

I have tried many times and I could not understand where the error was. Some guides in the internet belong to tensorflow 1 and can not suit to handle. Please help me!

A: This is based on the documentation
import tensorflow as tf
a = 2
b = 3

@tf.function
def func(x, y):
  return tf.add(a, b)

writer = tf.summary.create_file_writer('./graphs')

tf.summary.trace_on(graph=True, profiler=True)
z = func(a, b)
with writer.as_default():
  tf.summary.trace_export(
      name="trace",
      step=0,
      profiler_outdir='./graphs')

tensorboard --logdir ./graphs


text:
Q: Tell if IntPtr points to managed or unmanaged memory I'm using a wrapped C-library in C# and need to convert an image from that library to a Bitmap and back, but without copying the pixel buffer.
Converting to a Bitmap was simple:
Bitmap WrapAsBitmap(CImage image)
{
    return new Bitmap(image.Width, image.Height, image.BytesPerLine, PixelFormat.Format24bppRgb, image.Data);
}

By just passing in the original pixel buffer (image.Data) to the Bitmap constructor, no copy is needed. For doing the opposite, I need to call LockBits and UnlockBits to get access to the IntPtr of the original pixel buffer:
CImage WrapAsCImage(Bitmap bitmap)
{
    BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
    var image = new CImage(bitmap.Width, bitmap.Height, data.Stride * 3, data.Scan0);
    bitmap.UnlockBits(data);
    return image;
}

Now, as you can see, if data.Scan0 is in managed memory, this is actually a dangerous approach as the bits are 'unlocked' before the newly constructed image will be used. If bitmap was constructed from the WrapAsBitmap method, then there is no problem as data.Scan0 points to unmanaged memory which will not be moved by .NET. Therefore, I want to build in a safety check that checks the location (managed/unmanaged) of the data.Scan0 pointer.
An other solution I was thinking of was to inherit from the Bitmap class and keep track of the original pointer image.Data along with the Bitmap, but the Bitmap class is sealed, so I'm out of luck.
In short: any ideas how to detect the location (managed/unmanaged) of an IntPtr?

A: There is no scenario where that IntPtr is ever going to point to managed memory.  Not when the image data was generated by C code of course.  Not when it was generated by Bitmap either, GDI+ is unmanaged code.  You can reason this through by yourself, you can only ever obtain an IntPtr for managed memory by pinning it.  GCHandle.AddrOfPinnedObject().  A hard requirement to prevent the garbage collector from invalidating the pointer when it compacts the heap.  Nowhere do you see a documented need to pin.
There is no point in implementing the test.
You do have the rock-hard requirement to keep that IntPtr valid for the lifetime of the Bitmap wrapper.  Up to the point where you call its Dispose() method.  You cannot make this automagic, other than by encapsulating the Bitmap object in a class that implements IDisposable itself.  Not doing so causes very ugly mis-behavior, you only get an AccessViolationException when you're lucky.  A corrupted bitmap with random pixel content is the normal failure mode.
If you can't implement that guarantee then you should not do this and copy the bitmap data instead.  It is not hard to implement, just not pretty.

A: The Bitmap class is actually just a managed wrapper for a GDI+ Bitmap object. Since that object does not operate on a fixed buffer which is exposed to user code, nor is that buffer guaranteed to be in a particular format, you will not be able to perform the operation you have described.
In other words, without restricting your problem space from what you have asked, there will definitely be cases where buffer copying is required.


text:
Q: java.lang.NoSuchMethodError: java.io.File.toPath() There was a problem when I used the Stream-upload plugin to upload file
.Questions are as follows:
java.lang.NoSuchMethodError: java.io.File.toPath()Ljava/nio/file/Path;

environment:  jdk 1.7 + tomcat 6.0 + MyExclipse

A: toPath method requires Java 7. Make sure you are using the same version of Java across the machine.


text:
Q: How can i query a Primary key objects in django 2 template after querying my database, my template doesn't display anything. Please find attached my model, url, templates
MODEL
   class ScrumyUser(models.Model):
   userRole = (
       ('O', 'Owner'),
       ('A', 'Admin'),
       ('Q', 'Quality Analyst'),
       ('D', 'Developer'),
   )
   fullname = models.CharField(max_length=100)
   role = models.CharField(max_length=1, choices=userRole)

class GoalStatus(models.Model):
   goalStatus = (
       ('P', 'Pending'),
       ('V', 'Verified'),
       ('D', 'Done'),
   )
   status = models.CharField(max_length=1, choices=goalStatus)

class ScrumyGoals(models.Model):
   goalType = (
       ('WG', 'Weekly Goal'),
       ('DT', 'Daily Task'),
   )

   user_id = models.ForeignKey(ScrumyUser, on_delete=models.CASCADE)
   status_id = models.ForeignKey(GoalStatus, on_delete=models.CASCADE)
   goal_type = models.CharField(max_length=2, choices=goalType)
   goal_description = models.TextField()
   date_created = models.DateTimeField('dateCreated')
   date_updated = models.DateTimeField(null=True, blank=True)

VIEWS
from django.views import generic
from .models import ScrumyGoals, ScrumyUser, GoalStatus

class IndexView(generic.ListView):
    template_name = 'greyscrumy/index.html'
    context_object_name = 'goals'

    def get_queryset(self):

        return ScrumyGoals.objects.all()

TEMPLATE INDEX
THIS TEMPLATE DOESN'T DISPLAY ANY DATA ON THE BROWSER
{% if goals %}

{{ object_list.fullname }}

   {% for goal in goals.scrumygoals_set.all %}

{{ goal.goal_type }}

    {% endfor %}

{% else %}

No goals are available.

{% endif %}

THE SECOND DISPLAYS BUT I DON'T KNOW HOW TO ACCESS SCRUMYUSER AND GOALSTATUS
PLEASE I WOULD REALLY LOVE TO UNDERSTAND THIS, I HAVE MADE SEARCHES ON GOOGLE SINCE YESTERDAY AND COULDN'T FIND ANYTHING
{% for goal in goals %}

    {% for innergoal in goals %}
        {{ innergoal.id }} {{ innergoal.goal_description }}
    {% endfor %}

{% endfor %}

A: Like this:
{% for goal in goals %}

{{ goal.user_id.fullname }}

{{ goal.goal_type }}

{{ goal.goal_description }}

{{ goal.date_created }}

{{ goal.date_updated }}

{{ goal.user_id.role }}

{{ goal.status_id.status }}

{% endfor %}


text:
Q: compile a Qt single file from command line: undefined reference to vtable I'd like to compile a single file QT application from command line, for test in a quick way some features. See the code of the file below.
I'm compiling with:
qmake -project && qmake && make

And I' getting this error:
Togglebutton.o:Togglebutton.cpp:function ButtonDialog::ButtonDialog(QWidget*): error: undefined reference to 'vtable for ButtonDialog'
Togglebutton.o:Togglebutton.cpp:function ButtonDialog::ButtonDialog(QWidget*): error: undefined reference to 'vtable for ButtonDialog'
Togglebutton.o:Togglebutton.cpp:function ButtonDialog::~ButtonDialog(): error: undefined reference to 'vtable for ButtonDialog'
Togglebutton.o:Togglebutton.cpp:function ButtonDialog::~ButtonDialog(): error: undefined reference to 'vtable for ButtonDialog'

I'm not a c++ guru, I've tried to google about undefined reference to vtable but I don't understad why I'm getting this error also with one file..
Someone can help me in understaning the undefined vtable error?
/*
 * Copyright (c) 2006-2007, Johan Thelin
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *     * Neither the name of APress nor the names of its contributors
 *       may be used to endorse or promote products derived from this software
 *       without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <QPushButton>
#include <QHBoxLayout>
#include <QMessageBox>

#include <QApplication>
#include <QDialog>
class QPushButton;

class ButtonDialog : public QDialog
{
  Q_OBJECT

public:
  ButtonDialog( QWidget *parent=0 );

private slots:
  void buttonClicked();
  void buttonToggled();

private:
  QPushButton *clickButton;
  QPushButton *toggleButton;
};

ButtonDialog::ButtonDialog( QWidget *parent ) : QDialog( parent )
{
  clickButton = new QPushButton( "Click me!", this );
  toggleButton = new QPushButton( "Toggle me!", this );
  toggleButton->setCheckable( true );

  QHBoxLayout *layout = new QHBoxLayout( this );
  layout->addWidget( clickButton );
  layout->addWidget( toggleButton );

  connect( clickButton, SIGNAL(clicked()), this, SLOT(buttonClicked()) );
  connect( toggleButton, SIGNAL(clicked()), this, SLOT(buttonToggled()) );
}

void ButtonDialog::buttonClicked()
{
  QMessageBox::information( this, "Clicked!", "The button was clicked!" );
}

void ButtonDialog::buttonToggled()
{
  QMessageBox::information( this, "Toggled!", QString("The button is %1!").arg(toggleButton->isChecked()?"pressed":"released") );
}

int main( int argc, char **argv )
{
  QApplication app( argc, argv );

  ButtonDialog dlg;
  dlg.show();

  return app.exec();
}

A: I had the same mistake, when I declared a Q_OBJECT class in cpp file. Create a header and move class declaration there.


text:
Q: NullPointerException when I'm trying to read a resource I have a Gluon Mobile JavafX project.
I'm trying to read a resource from my apk and I'm receiving an error only in Android.
    private void leerConfiguracion() {  logger.log(Level.INFO, "ConfiguradorGeneralService:leerConfiguracion: BEGIN ... ");

    try
    {

        File fileLugares = new File(ConfiguradorGeneralService.class.getResource("/com/registrodevisitas/json/configuracion.json").getFile());

        logger.log(Level.INFO, "ConfiguradorGeneralService:leerConfiguracion: Leyendo configuración: " + fileLugares.getAbsolutePath());

        // create a FileClient to the specified File

        FileClient fileClient = FileClient.create(fileLugares);

        // create a JSON converter that converts the nodes from a JSON array into language objects

        InputStreamIterableInputConverter<ConfiguradorGeneral> converter = new JsonIterableInputConverter<>(ConfiguradorGeneral.class);

        // retrieve a list from a ListDataReader created from the FileClient

        configuracion = DataProvider.retrieveList(fileClient.createListDataReader(converter));

    }
    catch(Exception e)
    {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }

    logger.log(Level.INFO, "ConfiguradorGeneralService:leerConfiguracion: END ");

}

The error on Android is:
I/figuradorGeneralService(11481): ConfiguradorGeneralService:leerConfiguracion: BEGIN ...
E/figuradorGeneralService(11481): null
E/figuradorGeneralService(11481): java.lang.NullPointerException
E/figuradorGeneralService(11481):       at com.registrodevisitas.services.ConfiguradorGeneralService.leerConfiguracion(ConfiguradorGeneralService.java:50)
E/figuradorGeneralService(11481):       at com.registrodevisitas.services.ConfiguradorGeneralService.<init>(ConfiguradorGeneralService.java:34)
E/figuradorGeneralService(11481):       at java.lang.Class.newInstanceImpl(Native Method)
E/figuradorGeneralService(11481):       at java.lang.Class.newInstance(Class.java:1208)
E/figuradorGeneralService(11481):       at com.airhacks.afterburner.injection.Injector.lambda$getDefaultInstanceSupplier$8(Injector.java:233)
E/figuradorGeneralService(11481):       at com.airhacks.afterburner.injection.Injector.access$lambda$3(Injector.java)
E/figuradorGeneralService(11481):       at com.airhacks.afterburner.injection.Injector$$Lambda$4.apply(Unknown Source)
E/figuradorGeneralService(11481):       at com.airhacks.afterburner.injection.Injector.instantiateModelOrService(Injector.java:116)
E/figuradorGeneralService(11481):       at com.airhacks.afterburner.injection.Injector.injectMembers(Injector.java:151)
E/figuradorGeneralService(11481):       at com.airhacks.afterburner.injection.Injector.injectMembers(Injector.java:136)
E/figuradorGeneralService(11481):       at com.airhacks.afterburner.injection.Injector.injectAndInitialize(Injector.java:129)
E/figuradorGeneralService(11481):       at com.airhacks.afterburner.injection.Injector.registerExistingAndInject(Injector.java:107)
E/figuradorGeneralService(11481):       at com.airhacks.afterburner.injection.Injector.instantiatePresenter(Injector.java:60)
E/figuradorGeneralService(11481):       at com.airhacks.afterburner.views.FXMLView.lambda$loadSynchronously$2(FXMLView.java:89)
E/figuradorGeneralService(11481):       at com.airhacks.afterburner.views.FXMLView.access$lambda$1(FXMLView.java)
E/figuradorGeneralService(11481):       at com.airhacks.afterburner.views.FXMLView$$Lambda$2.call(Unknown Source)
E/figuradorGeneralService(11481):       at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:929)
E/figuradorGeneralService(11481):       at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
E/figuradorGeneralService(11481):       at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
E/figuradorGeneralService(11481):       at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
E/figuradorGeneralService(11481):       at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
E/figuradorGeneralService(11481):       at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
E/figuradorGeneralService(11481):       at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
E/figuradorGeneralService(11481):       at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
E/figuradorGeneralService(11481):       at com.airhacks.afterburner.views.FXMLView.loadSynchronously(FXMLView.java:91)
E/figuradorGeneralService(11481):       at com.airhacks.afterburner.views.FXMLView.initializeFXMLLoader(FXMLView.java:100)
E/figuradorGeneralService(11481):       at com.airhacks.afterburner.views.FXMLView.getView(FXMLView.java:112)
E/figuradorGeneralService(11481):       at com.registrodevisitas.RegistroDeVisitas.lambda$init$0(RegistroDeVisitas.java:55)
E/figuradorGeneralService(11481):       at com.registrodevisitas.RegistroDeVisitas.access$lambda$0(RegistroDeVisitas.java)
E/figuradorGeneralService(11481):       at com.registrodevisitas.RegistroDeVisitas$$Lambda$1.get(Unknown Source)
E/figuradorGeneralService(11481):       at com.gluonhq.impl.charm.a.d.a.a(SourceFile:32)
E/figuradorGeneralService(11481):       at com.gluonhq.charm.glisten.application.MobileApplication.a(SourceFile:620)
E/figuradorGeneralService(11481):       at com.gluonhq.charm.glisten.application.MobileApplication.switchView(SourceFile:391)
E/figuradorGeneralService(11481):       at com.gluonhq.charm.glisten.application.MobileApplication.switchView(SourceFile:368)
E/figuradorGeneralService(11481):       at com.gluonhq.charm.glisten.application.MobileApplication.start(SourceFile:218)
E/figuradorGeneralService(11481):       at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$144(LauncherImpl.java:863)
E/figuradorGeneralService(11481):       at com.sun.javafx.application.LauncherImpl.access$lambda$8(LauncherImpl.java)
E/figuradorGeneralService(11481):       at com.sun.javafx.application.LauncherImpl$$Lambda$9.run(Unknown Source)
E/figuradorGeneralService(11481):       at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$157(PlatformImpl.java:326)
E/figuradorGeneralService(11481):       at com.sun.javafx.application.PlatformImpl.access$lambda$6(PlatformImpl.java)
E/figuradorGeneralService(11481):       at com.sun.javafx.application.PlatformImpl$$Lambda$7.run(Unknown Source)
E/figuradorGeneralService(11481):       at com.sun.javafx.application.PlatformImpl.lambda$null$155(PlatformImpl.java:295)
E/figuradorGeneralService(11481):       at com.sun.javafx.application.PlatformImpl.access$lambda$18(PlatformImpl.java)
E/figuradorGeneralService(11481):       at com.sun.javafx.application.PlatformImpl$$Lambda$19.run(Unknown Source)
E/figuradorGeneralService(11481):       at java.security.AccessController.doPrivileged(AccessController.java:52)
E/figuradorGeneralService(11481):       at com.sun.javafx.application.PlatformImpl.lambda$runLater$156(PlatformImpl.java:294)
E/figuradorGeneralService(11481):       at com.sun.javafx.application.PlatformImpl.access$lambda$5(PlatformImpl.java)
E/figuradorGeneralService(11481):       at com.sun.javafx.application.PlatformImpl$$Lambda$6.run(Unknown Source)
E/figuradorGeneralService(11481):       at com.sun.glass.ui.monocle.RunnableProcessor.runLoop(RunnableProcessor.java:92)
E/figuradorGeneralService(11481):       at com.sun.glass.ui.monocle.RunnableProcessor.run(RunnableProcessor.java:51)
E/figuradorGeneralService(11481):       at java.lang.Thread.run(Thread.java:8
I/figuradorGeneralService(11481): ConfiguradorGeneralService:leerConfiguracion: END

This file is on RESOURCE/COM....

This method is working perfectly on windows.
Any help would be nice. Thank you.

A: On Android (and iOS), you can't directly access classpath resources as a File, like you can on desktop. Instead, you need to access resources by using the InputStream. This works on all the supported platforms (android, iOS and desktop).
Try to access your resource with the following code:
BasicInputDataSource source = new BasicInputDataSource(ConfiguradorGeneralService.class.getResourceAsStream("/com/registrodevisitas/json/configuracion.json"));

InputStreamIterableInputConverter<ConfiguradorGeneral> converter = new JsonIterableInputConverter<>(ConfiguradorGeneral.class);

configuracion = DataProvider.retrieveList(new InputStreamListDataReader<>(source, converter));


text:
Q: How to calculate difference between data in different rows? I have got monthly data in this format
   PrecipMM          Date
    122.7         2004-01-01
     54.2         2005-01-01
     31.9         2006-01-01
    100.5         2007-01-01
    144.9         2008-01-01
     96.4         2009-01-01
     75.3         2010-01-01
     94.8         2011-01-01
     67.6         2012-01-01
     93.0         2013-01-01
    184.6         2014-01-01
    101.0         2015-01-01
    149.3         2016-01-01
     50.2         2004-02-01
     46.2         2005-02-01
     57.7         2006-02-01

I want to calculate all of the difference of precipMM in same month of different years.
My dream output is like this:
   PrecipMM          Date         PrecipMM_diff
    122.7         2004-01-01           NA
     54.2         2005-01-01         -68.5
     31.9         2006-01-01         -22.3
    100.5         2007-01-01          68.6
    144.9         2008-01-01          44.4
     96.4         2009-01-01         -48.5
     75.3         2010-01-01         -21.2
     94.8         2011-01-01          19.5
     67.6         2012-01-01         -27.2
     93.0         2013-01-01          25.4
    184.6         2014-01-01          91.6
    101.0         2015-01-01         -83.6
    149.3         2016-01-01          48.3
     50.2         2004-02-01           NA
     46.2         2005-02-01          -4.0
     57.7         2006-02-01          11.5

I think diff() can do this but I have no idea how.

A: I think you can do this with lag combined with group_by from dplyr.  Here's how:
library(dplyr)
library(lubridate)  # makes dealing with dates easier

# Load your example data
df <- structure(list(PrecipMM = c(4.4, 66.7, 48.2, 60.9, 108.1, 109.2,
101.7, 38.1, 53.8, 71.9, 75.4, 67.1, 92.7, 115.3, 68.9, 38.9),
    Date = structure(5:20, .Label = c("101.7", "108.1", "109.2",
    "115.3", "1766-01-01", "1766-02-01", "1766-03-01", "1766-04-01",
    "1766-05-01", "1766-06-01", "1766-07-01", "1766-08-01", "1766-09-01",
    "1766-10-01", "1766-11-01", "1766-12-01", "1767-01-01", "1767-02-01",
    "1767-03-01", "1767-04-01", "38.1", "38.9", "4.4", "48.2",
    "53.8", "60.9", "66.7", "67.1", "68.9", "71.9", "75.4", "92.7"
    ), class = "factor")), class = "data.frame", row.names = c(NA,
-16L), .Names = c("PrecipMM", "Date"))

results <- df %>%
  mutate(years = year(Date), months = month(Date)) %>%
  group_by(months) %>%
  arrange(years) %>%
  mutate(lagged.rain = lag(PrecipMM), rain.diff = PrecipMM - lagged.rain)

results
# Source: local data frame [16 x 6]
# Groups: months [12]
#
#    PrecipMM       Date years months lagged.rain rain.diff
#       (dbl)     (fctr) (dbl)  (dbl)       (dbl)     (dbl)
# 1       4.4 1766-01-01  1766      1          NA        NA
# 2      92.7 1767-01-01  1767      1         4.4      88.3
# 3      66.7 1766-02-01  1766      2          NA        NA
# 4     115.3 1767-02-01  1767      2        66.7      48.6
# 5      48.2 1766-03-01  1766      3          NA        NA
# 6      68.9 1767-03-01  1767      3        48.2      20.7
# 7      60.9 1766-04-01  1766      4          NA        NA
# 8      38.9 1767-04-01  1767      4        60.9     -22.0
# 9     108.1 1766-05-01  1766      5          NA        NA
# 10    109.2 1766-06-01  1766      6          NA        NA
# 11    101.7 1766-07-01  1766      7          NA        NA
# 12     38.1 1766-08-01  1766      8          NA        NA
# 13     53.8 1766-09-01  1766      9          NA        NA
# 14     71.9 1766-10-01  1766     10          NA        NA
# 15     75.4 1766-11-01  1766     11          NA        NA
# 16     67.1 1766-12-01  1766     12          NA        NA