text:
Q: NuGet Automatic Package Restore when using git submodules I am trying to understand if there is any way to rely on Nuget Automatic Package Restore when referencing libraries hosted on Github. The problem is that when I add certain library as submodule, it has it's own /packages/ directory. But, when I add csproj from that library into my solution since there are no DLLs in /packages/ directory of that submodule, build fails.
Obviously, easy fix on my machine is to open up .sln file from submodule that I've referenced, do a build. Now, building from my main solution will obviously work since /packages/ folder in submodule is populated. But, this is not something I can do on build server.
Any way of solving this problem without completely messing up submodule? I obviously also don't want to change submodule .csproj because that would put it out of sync with origin. Ideally I would love if I could instruct nuget to pull packages for referenced submodule .csproj in it's own /packages/ directory.

A: There are two types of automatic package restore. One that is triggered when you build a solution within Visual Studio, and one that is MSBuild based and requires modifying your project to run NuGet.exe restore as part of the build. The MSBuild based restore is enabled by selecting Enable NuGet Package Restore, but this has been deprecated by the NuGet team.
For a build server you would need to do either:

*

*Run NuGet.exe restore for all solutions before you run the build.

*Have the NuGet packages restored by MSBuild as the main solution is built.

To restore the NuGet packages with MSBuild you can use the deprecated MSBuild based NuGet package restore or perhaps better is to create a Before.YourSolution.sln.targets file as described in the Ultimate Cross Platform NuGet Restore post. The custom Before....targets file would need to restore packages for the submodule.
If you use an MSBuild based restore then one of the benefits is that there is no pre-build step that someone needs to run before building the solution since building the solution does the restore. One of the problems of the MSBuild based package restore, at least with the one that is enabled when selecting Enable NuGet Package Restore in Visual Studio, is that it can cause problems with NuGet packages that use their own custom MSBuild .targets files.


text:
Q: Android - No drawer view found with gravity RIGHT I'm getting this exception when I try to open the Navigation Drawer from the right
Exception:
java.lang.IllegalArgumentException: No drawer view found with gravity RIGHT
at
mDrawerLayout.openDrawer(Gravity.RIGHT);

My Layout file :
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_gravity="right"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Framelayout to display Fragments -->
    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- Listview to display slider menu -->
    <ListView
        android:id="@+id/list_slidermenu"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="right"
        android:choiceMode="singleChoice"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector"
        android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>

Is there anything I'm doing Wrong?
Thanks for your Assistance.

A: Anyways I got it working myself,For others who are finding difficulty to solve, Here's what I have did, I changed  android:layout_gravity="right" of the list view to  android:layout_gravity="end" it started  working fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Html Formatting Grid View I'm trying to format my grid view so it looks like the following:

so instead of looking like a table it has 2 columns and 3 rows.
Thanks in advance

A: Consider switching your server control to an <asp:ListView>. This gives you granular control over your markup, compared to a gridview.
Here's a great ListView tutortial by the Gu.

A: Use an asp:ListView instead. It allows for template items, meaning you can specify the HTML yourself while still having much of the list-type functionality that, say, an asp:Repeater would lack.
The listview was new to .NET 3.5, though, so if you are using an older version, I would just use the repeater. Both allow you to specify your own markup, which you will need to do to render your items as you have them shown above.

A: I would personally use a asp:Repeater control as that gives you greater control over the html you want to display.

A: If the use of a GridView is mandatory, you can do this:

    GridView

<asp:GridView id="MyList" CssClass="Grid" AutoGenerateColumns="false" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>

                        <asp:Image ImageUrl='<%# Eval("ImageUrl") %>' runat="server"/>

                        <asp:HyperLink Text="Some Link" NavigateUrl='<%# Eval("Link") %>' runat="server" />

                        <asp:Label Text='<%# Eval("Text") %>' runat="server" />

                        <asp:Label Text='<%# Eval("DateTime") %>' runat="server" />

            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Only for demonstration purposes, in code behind you can do this:
public class Item
{
    public string ImageUrl { get; set; }
    public string Link { get; set; }
    public string Text { get; set; }
    public string DateTime { get; set; }
}

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Item[] items = new Item[5]{ new Item()
                                        {
                                            ImageUrl="img/imageplaceholder.jpg",
                                            Link="~/somelink1.html",
                                            Text="Some Text 1",
                                            DateTime=DateTime.Now.ToShortDateString()
                                        },
                                    new Item()
                                        {
                                            ImageUrl="img/imageplaceholder.jpg",
                                            Link="~/somelink2.html",
                                            Text="Some Text 2",
                                            DateTime=DateTime.Now.ToShortDateString()
                                        },
                                    new Item()
                                        {
                                            ImageUrl="img/imageplaceholder.jpg",
                                            Link="~/somelink3.html",
                                            Text="Some Text 3",
                                            DateTime=DateTime.Now.ToShortDateString()
                                        },
                                    new Item()
                                        {
                                            ImageUrl="img/imageplaceholder.jpg",
                                            Link="~/somelink4.html",
                                            Text="Some Text 4",
                                            DateTime=DateTime.Now.ToShortDateString()
                                        },
                                    new Item()
                                        {
                                            ImageUrl="img/imageplaceholder.jpg",
                                            Link="~/somelink5.html",
                                            Text="Some Text 5",
                                            DateTime=DateTime.Now.ToShortDateString()
                                        }
                                  };

            MyList.DataSource = items;
            MyList.DataBind();
        }
    }
}

And use the following CSS:
table
{
    table-layout:fixed;
    width:100%;
}

.item_container
{
    width: 700px;
    background-color:#FFE5FF;
}

.image_container
{
    width:100px;
    float:left;
}

.link_text_container
{
    width: 600px;
    float: left;
    background-color:#E5FFF2;
}

.datetime_container
{
    width: 100%;
    clear:both;
    background-color:#B3ECFF;
}

It will produce the desired layout with a GridView, but indeed, the asp:ListView is a better choice.
GridView Layout http://i53.tinypic.com/2l5l5s.jpg


text:
Q: Как вынести определённый механизм в отдельный класс и затем обращаться к нему и правильно ли это с точки зрения ООП Как вынести определённый механизм в отдельный класс и затем обращаться к нему и правильно ли это с точки зрения ООП.
есть код:

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Windows.Forms;

namespace InstaBulochka
{
    public partial class Form1 : Form
    {

        IWebDriver web;
        public Form1()
        {

            ChromeOptions options = new ChromeOptions();
            options.AddArguments("--headless"); //
            web = new ChromeDriver(@"D:/");
            web.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {

            web.Navigate().GoToUrl("https://www.123.com/accounts/login/");
            web.FindElement(By.CssSelector("input[name='username']")).SendKeys("login");
            web.FindElement(By.CssSelector("input[name='password']")).SendKeys("passport");
            web.FindElement(By.CssSelector("input[name='password']")).SendKeys(OpenQA.Selenium.Keys.Enter);
            try { String err = web.FindElement(By.CssSelector("#slfErrorAlert")).Text;
                Console.WriteLine(err);
            } catch (Exception ) { Console.WriteLine("log and pass is good"); }

            Console.WriteLine(isSMSOnPagePresent("Подозрительная попытка входа"));

        }

        public Boolean isSMSOnPagePresent(String text) {
            IWebElement body = web.FindElement(By.TagName("body"));
            String bodyText = body.Text;
            return bodyText.Contains(text);
        }
    }
}

Хотелось бы, весь процесс авторизации вынести в отдельный класс ну скажем avtoriz (мне кажется так удобнее) и обращаться к нему из главного класса Form1. Как-то так, абстрактно: avtoriz.авторизироваться(лог,пасс); при этом конструктор IWebDriver web; должен быть именно только в классе Form1, и не создавая новых экземпляров объекта.
Подскажите, пожалуйста, решение желательно кодом.
И с точки зрения ООП правильно ли я хочу сделать?

A: делаем класс для аутентификатора
public class Authenticator
{
    private IWebDriver _driver;
    public Authenticator(IWebDriver driver)
    {
        _driver = driver;
    }

    public void Authenticate(string login, string password)
    {
         _driver.Navigate().GoToUrl("https://www.123.com/accounts/login/");
        ..........
    }
}

Правим код формы
public class MyForm : Form
{
    private Authenticator _authenticator;
    IWebDriver web;

    public MyForm()
    {
        ChromeOptions options = new ChromeOptions();
        options.AddArguments("--headless"); //
        web = new ChromeDriver(@"D:/");
        web.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

        _authenticator = new Authenticator(web);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        _authenticator.Authenticate("login", "password");
    }
}

всё.
upd
Как я пришел к такому решению?
Изначально автор просил выделить конкретный функционал в отдельный класс. Так родился класс
public class Authenticator
{
    public void Authenticate(string login, string password)
    {
        web.Navigate().GoToUrl("https://www.123.com/accounts/login/");
        ..........
    }
}

однако, у класса пока нет одного параметра - web, который пока не настроен и непонятно как с ним работать. Для его передачи в класс есть 2 опции: передать его в конструктор, или передать её прямо в метод вместе с другими параметрами метода.
Поскольку параметр web не специфичен для конкретного запроса, а, скорее, лежит в основе класса Authenticator (то есть если, например, вы добавите в класс метод LogOff, то вам параметры login\password уже не понадобятся - они нужны только для метода Authenticate, а вот web - понадобится, то есть он нужен не для одного метода, а для работы всего класса), я решил данный параметр рассматривать как зависимость класса и пробросил его через конструктор. Заодно и переименовал, мне удобнее его понимать как driver или webdriver, чем просто web. Подчеркивание перед названием поля - это просто следование общей рекомендации, когда имена всех приватных полей начинаются с подчеркивания. Подробнее про всякие рекомендации можно почитать тут или в книге.
public class Authenticator
{
    private IWebDriver _driver;
    public Authenticator(IWebDriver driver)
    {
        _driver = driver;
    }

    public void Authenticate(string login, string password)
    {
        _driver.Navigate().GoToUrl("https://www.123.com/accounts/login/");
        ..........
    }
}

Далее, надо встроить этот класс в форму. Есть 2 варианта как это сделать. Первый - это создавать класс в обработчике события
public class MyForm : Form
{
    IWebDriver web;
    ..........
    private void button1_Click(object sender, EventArgs e)
    {
        var authenticator = new Authenticator(web);
        authenticator.Authenticate("login", "password");
    }
}

Это вроде кажется правильным подходом, но на самом деле, это нарушит принцип единственности ответственности - (подробнее про SOLID), так как мы не хотим, чтобы обработчики событий делали что то кроме обработки событий (то есть инициализация каких то сервисных классов не должна присутствовать в обработчиках, если вы не хотите в итоге получить лапшу в коде).
Остается инициализировать класс до того, как он понадобится. В идеале, мы знаем, что класс Authentocator - это зависимость формы и должен быть передан в конструктор формы (см материал про Dependency Injection), но я решил, что у вас нет ни корня агрегации, ничего, с чем можно работать прямо "по правилам", потому я показал более легкий вариант - с созданием зависимости прямо в конструкторе класса. Это не очень хорошая практика в больших корпоративных решениях, но в каких-то небольших проектах такое вполне допустимо, если без фанатизма.
public class MyForm : Form
{
    private Authenticator _authenticator;
    IWebDriver web;

    public MyForm()
    {
        .......
        web = new ChromeDriver(@"D:/");
        ........
        _authenticator = new Authenticator(web);
    }
    ..........
}

Так и получился тот ответ, что я вам привёл.

A: например так:
public static class WebDriverExt
{
    public static bool LogIn(this IWebDriver driver, string login, string path)
    {
        driver.GoToUrl("https://www.123.com/accounts/login/");
        driver.FindElement(By.CssSelector("input[name='username']")).SendKeys("login");
        driver.FindElement(By.CssSelector("input[name='password']")).SendKeys("passport");
        driver.FindElement(By.CssSelector("input[name='password']")).SendKeys(OpenQA.Selenium.Keys.Enter);
        //...
    }

    public static bool GoToUrl(this IWebDriver driver, string url)
    {
        // todo: проверка url
        driver.Navigate().GoToUrl(url);
    }
}

использовать так:
driver.LogIn("login", "pass");


text:
Q: C# Close windows form I am opening up another form when a button is clicked, but can't decide how to close the current form when doing this. This is the code:
private void nextSportButton_Click(object sender, EventArgs e)
{
    for (int i = 0; i < Form1.sportsAdded; i++)
    {
        if (Form1.sportOpened == i)
        {
            Form1.IDNumber = Form1.sportIDArray[i];
            OutputForm OutputForm = new OutputForm();
            OutputForm.ShowDialog();
        }

        this.Close();
    }
}

A: Calling OutputForm.ShowDialog() waits until OutputForm is closed and only then returns to execute further code. You want to use OutputForm.Show() instead.
Note: If "this" is the main form (the first form shown) of your application, closing "this" will terminate the whole application.

A: first hide current form don't close after open your new form,
this.Hide();

Form1.IDNumber = Form1.sportIDArray[i];
OutputForm OutputForm = new OutputForm();
OutputForm.ShowDialog();

A: Use this.Hide(); instead of this.Close(); and using this.Close(); inside a for loop should throw an exception.


text:
Q: How to compute prices form daily returns? I have a dataframe with daily returns. I want to add another column with price series calculated based on daily returns.
This is the dataframe:
         date   daily
0  2020-09-01  0.0000
1  2020-09-02  0.0012
2  2020-09-03 -0.0005
3  2020-09-04 -0.0004
4  2020-09-07  0.0032
5  2020-09-08 -0.0015
6  2020-09-09  0.0005
7  2020-09-10  0.0003
8  2020-09-11  0.0001
9  2020-09-14  0.0043
10 2020-09-15  0.0037
11 2020-09-16 -0.0008

and this is the column of prices that i want to add:
       prices
0   100.000000
1   100.120000
2   100.069940
3   100.029912
4   100.350008
5   100.199483
6   100.249582
7   100.279657
8   100.289685
9   100.720931
10  101.093598
11  101.012724

I've tried to do a loop on column 'daily' and then calculate the price but i do not preserve the new values into the list prz.
prz= []

for row in df['daily']:
        prz.append(100 *(1+row))

A: First add 1, then use Series.cumprod and last multiply by 100, for invert use Series.pct_change with replace first NaN to 0:
df['prices'] = df['daily'].add(1).cumprod().mul(100)

df['back'] = df['prices'].pct_change().fillna(0)
print (df)
          date   daily      prices    back
0   2020-09-01  0.0000  100.000000  0.0000
1   2020-09-02  0.0012  100.120000  0.0012
2   2020-09-03 -0.0005  100.069940 -0.0005
3   2020-09-04 -0.0004  100.029912 -0.0004
4   2020-09-07  0.0032  100.350008  0.0032
5   2020-09-08 -0.0015  100.199483 -0.0015
6   2020-09-09  0.0005  100.249582  0.0005
7   2020-09-10  0.0003  100.279657  0.0003
8   2020-09-11  0.0001  100.289685  0.0001
9   2020-09-14  0.0043  100.720931  0.0043
10  2020-09-15  0.0037  101.093598  0.0037
11  2020-09-16 -0.0008  101.012724 -0.0008

A: You can also use numpy.cumproduct() here:
In [1349]: import numpy as np

In [1350]: df['prices'] = np.cumproduct(df.daily + 1) * 100

In [1351]: df
Out[1351]:
          date   daily      prices
0   2020-09-01  0.0000  100.000000
1   2020-09-02  0.0012  100.120000
2   2020-09-03 -0.0005  100.069940
3   2020-09-04 -0.0004  100.029912
4   2020-09-07  0.0032  100.350008
5   2020-09-08 -0.0015  100.199483
6   2020-09-09  0.0005  100.249582
7   2020-09-10  0.0003  100.279657
8   2020-09-11  0.0001  100.289685
9   2020-09-14  0.0043  100.720931
10  2020-09-15  0.0037  101.093598
11  2020-09-16 -0.0008  101.012724


text:
Q: Mongoose query with two arrays
What is the query that returns the values in 'all' array,  excluded
the values in 'friends' array

const userSchema = new Schema({
  all: [],
  friends:[],
 ....
});

all = [ObjectId('65ss135442890aa'), ObjectId('65ss135442890dd')];

friends =[ObjectId('65ss135442890aa')];

result of query should be <ObjectId('65ss135442890dd')>

A: One option is to use $setDifference:
db.collection.aggregate([
  {$project: {
      all: {$setDifference: ["$all", "$friends"]},
      _id: 0
    }
  }
])

See how it works on the playground example


text:
Q: Account subclass object creation So I have a question on how to create instances of a sub class in JAVA. Yes, this is a homework assignment for a grade, I have fully implemented a main class with a default and a paramaterized constructor for an Account class.
I have created two sub classes, Savings and Checking. The only specifications from the book for the assignment were that the Checking account cannot withdraw past an overdraft limit, and that the Savings account cannot overdraw at all.
class Checking extends Account{
        double overdraftLimit = -100;

        public void withdraw(double w) {
            if (balance - w < overdraftLimit)
                    System.out.println("You can't overdraft more than $100.");
            else
                balance = balance - w;
        }
    }

class Savings extends Account{
        double overdraftLimit = 0;

        public void withdraw (double w) {
            if (balance - w < overdraftLimit)
                    System.out.println("You don't have enough money, fool.");
            else
                balance = balance - w;
        }
    }

My problem is that I'm not sure how to create an instance of a specific subclass, either Savings or Checking. Does anyone have suggestions for me? In my parent class, Account, I already have a method for withdraw ( double w ), such that thebalance -= w. I overrode the withdraw method in each of my subclasses already. My code compiles and runs, but in the problem I am instructed to write a test program that creates an object of type Account, Savings, Checking and invokes their toString() method. I've talked to my instructor and this problem wasn't fully completed before printing because there are no instructions on the overdraft limit allowed for the Checking account.
There is also no mention of the toString() method that I am supposed to be invoking so I am skipping that part of the assignment.

A: If I understand your problem correctly (and feel free to clarify), you need to create a constructor for each of the classes:
public Checking(){
    super();
    //other initialization
}

public Savings(){
    super();
    //other initialization
}

and call them from your main with the keyword new:
Savings mySavings = new Savings();
Checking myChecking = new Checking();
Account myAccount = new Account();


text:
Q: Axis2 getSOAPEnvelope() performance issue Using axis2 on solaris I've noticed that the message.getSOAPEnvelope() call is maxing out the server processing to 0.0 idle. The call takes about 10 seconds and then processing load goes back to normal. This is crazy for a single method especially something built into Axis.
Can anyone suggest a solution to this, I've not been able to find anything similar online.
// get message for sending
Message message = getSOAPMessage();
...
message=signSOAPEnvelope(message.getSOAPEnvelope()); //problem
...
SOAPEnvelope retMsg = (SOAPEnvelope) call.invoke(message.getSOAPEnvelope()); //problem

--ADDITIONAL INFORMATION---
Ok so the issue lies in teh SAXParser.parse() method called by axis (not axis2 btw). So I've done some further tests with other messages.
My application builds the SoapEnvelope and the message body is added to it. I've taken a message from another application that I know is working and following the soap envelope build I've overridden the message string with this older xml.  So the SoapEnvelope is identical in both cases, however the xml I took from the other project works well whilst my new xml doesn't. The crazy thing is the older xml is larger so should take longer. Below are the examples of the relevant xml as I can't work out why one should work and the other not.
WORKS OK: large older xml
    <ns2:applicationDetailSearchQuery
   xmlns:ns2="http://www.company.com.au/wib/ID/schema/query"
xmlns:ns3="http://www.company.com.au/wib/Counterparty/schema/query"
xmlns:tns="http://www.company.com.au/wib/icc/schema/query">

<tns:queryID scheme="http://www.company.com.au/treasury/idbb/queryid">44051</tns:queryID>
<tns:queryType>ApplicationDetailSearch</tns:queryType>
<tns:pageSize>10000</tns:pageSize>
<ns2:parameters>
    <ns2:tradeIdList>
        <ns2:tradeId>111111</ns2:tradeId>
    </ns2:tradeIdList>
    <ns2:queryByHeadDealId>N</ns2:queryByHeadDealId>
    <ns2:retrieveSchedule>N</ns2:retrieveSchedule>
    <ns2:retrieveCashFlowDeals>Y</ns2:retrieveCashFlowDeals>
    <ns2:dealType>BOND</ns2:dealType>
 </ns2:parameters>
</ns2:applicationDetailSearchQuery>

REALLY SLOW: small xml???
<ns5:querySetRequest setId="1" xmlns:ns2="http://schemas.company.com.au/ttt/icc/common/header-V2-0" xmlns:ns4="http://schemas.company.com.au/ttt/icc/Services/FXC/TradeEnquiryServiceEnvelope" xmlns:ns3="http://schemas.company.com.au/ttt/icc/common/envelopemsg-V2-0" xmlns:ns5="http://webservice.common.ttt/queryservice/types">
<ns5:query queryName="RemainingBalanceQuery" queryID="1">
    <ns5:parameter value="FWD:169805" type="String" name="KondorId"/>
    <ns5:parameter value="0.9592" type="Decimal" name="ExchgRate"/>
    <ns5:parameter value="USD" type="String" name="CurrencyCode"/>
    <ns5:parameter value="09/08/2011" type="String" name="MatDate"/>
</ns5:query>
</ns5:querySetRequest>

Any ideas what might be causing excessive cpu for this second set of xml?

A: This was an issue with excessive logging from the SAXParser. When I set logging to warn for the relevent packages it ran in milliseconds. Crazy stuff!


text:
Q: How to catch a compile-time exception? Is it possible in Clojure to catch an exception that occurs at compile time? Using try/catch is fine and easy for run-time exceptions, but suppose I have:
(defmacro will-throw-at-compile [] (assert false "it threw"))

(try (will-throw-at-compile) (catch Exception e "caught it"))

I can't find any way to catch this, the catch never happens. I've tried different types of exception classes as well, doesn't seem to be the problem.
I also thought that since the try above is a run-time call, making a macro to do the try at compile time:
(defmacro t [x] (try x (catch Exception e "caught it")))

Doesn't work either:
(t (will-throw-at-compile))

Perhaps can't be done?

A: You can make it work if the macro handles it's own exception.  Break out the majority of the work of the macro into a function:
(defn thrower []
  (throw (Exception. "it threw")))

(defmacro will-throw
  []
  (try
    (thrower)
    (catch Exception e (println "caught it")))
  (println "leaving macro"))

(will-throw)

Running this code results in:
> lein run
caught it
leaving macro

The idea is to put most or all of the macro functionality into a regular function, so it can be called & tested outside of the compile-time macro mechanism.  Then you can use regular unit-tests like so:
(deftest t-thrower
  (is (thrown? Exception (thrower)))
  (println "t-thrower complete"))

> lein test
caught it
leaving macro

lein test tst.clj.core
t-thrower complete

Ran 1 tests containing 1 assertions.
0 failures, 0 errors.


text:
Q: Variation of Hodge structures associated to a hermitian symmetric domain Let $D$ be an irreducible hermitian symmetric domain. Then there exists a variation of Hodge structures $(h_s)_{s\in D}$ on a vector space $V$ satisfying specific conditions which depend on $D$ such that the space $S=\{h_s\}$ is isomorphic to $D$. Let $X$ be a smooth projective variety and let $\pi\colon X\to D$ be a morphism such that $H^n(X_s,\mathbb{Q})$ gives back the Hodge structure associated to $D$. (The number $n$ is clearly the weight of $(h_s)$ and $X_s$ is the fiber over $s\in D$.) I think such a morphism $\pi$ and such a variety $X$ always exist although I do not really know why. I also think that there actually existst many such $X$ and $\pi$.
We know that the hermitian symmetric domains are classified by the special nodes in the Dynkin diagrams. So we can write down a complete list of their isomorphism types. The question is now the following: Can someone please write down an example of $X$ for each of the isomorphism types of $D$, such as the Grassmannian, isotropic Grassmannian, etc.?
If I consider the set $\mathcal{X}$ of all morphism $X\to D$ which give rise to the variation of Hodge structures associated to $D$. Can someone give an interesting invariant $j$ such that $j(X_s)$ is independent of $X\in\mathcal{X}$. If someone can do, what does the function $s\mapsto j(X_s)$ on $D$ look like?
Maybe there exists already something similar in the literature which you can refer to. This of course also counts as an answer.
(Please do not downvote my question and try to answer instead. Thank you.)

A: You might want to look at the book "Mumford-Tate Groups and Domains: Their Geometry and Arithmetic", by Mark Green, Phillip Griffiths, and Matt Kerr.  You should also look at the recent work of Colleen Robles.  These might have answers to some of your questions.

A: I think you meant to say that $\pi:X\to D$ is a family of smooth projective varieties ($X$ won't itself be a projective variety, because $D$ is noncompact).
Also, let me relax the condition to allow $h_s$ to be a direct summand of $H^n(X_s)$. Then as I understand (and I don't promise that I do) from Milne's Introduction to Shimura varieties, the existence of such a family is known in cases A,B,C and unkown in some others such as $E_6, E_7$, although it is expected. The basic idea is that if $D=G/K$ and $G$ embeds into a symplectic group, then $D$ embeds into a Siegel upper half plane, and you can restrict the universal family of abelian varieties.


text:
Q: net.sf.jasperreports.engine.JRException: Invalid page index range : 0 - -1 of 0 When I try printing the Jasper report it gets me the message:  "net.sf.jasperreports.engine.JRException: Invalid page index range : 0 - -1 of 0".
Code:
    try {
        JasperPrint impressao = JasperFillManager.fillReport(getClass().getClassLoader().getResourceAsStream("example.jasper"), parametros);
        JasperExportManager.exportReportToPdf(impressao);

        JasperPrintManager.printReport(impressao, true);
    } catch (JRException e) {
        e.printStackTrace();
    }

Report:
<?xml version="1.0" encoding="UTF-8"?><jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="base-estadual" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="9cbb7afc-abb5-4207-a29b-a0c7adde7df6">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="250"/>
<import value="com.myproject.ed.*"/>
<parameter name="PATH_IMAGENS" class="java.lang.String"/>
<queryString>
    <![CDATA[]]>
</queryString>
<background>
    <band splitType="Stretch"/>
</background>
<pageHeader>
    <band height="63">
        <textField evaluationTime="Report">
            <reportElement x="515" y="16" width="40" height="20" uuid="3892152b-6880-41da-bbc7-7bf79588061d"/>
            <textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
        </textField>
        <textElement textAlignment="Right"/>
        <textFieldExpression><![CDATA["Page "+$V{PAGE_NUMBER}+" of"]]>/textFieldExpression>
        </textField>
    </band>
</pageHeader>

Could someone help me to figure out why is it happening?

A: JasperFillManager likes to get a data source, even when you don't really have any. You could try adding an empty data source as a third parameter to JasperFillManager.fillReport:
JasperPrint impressao = JasperFillManager.fillReport(getClass().getClassLoader().getResourceAsStream("example.jasper"), parametros, new JREmptyDataSource());

A: Check whether the parameters which you are passing to the JasperFillManager.fillReport() is not null or empty. If it is empty or null then you will receive this same error.
 JasperPrint impressao = JasperFillManager.fillReport(getClass().getClassLoader().getResourceAsStream("example.jasper"), parametros);


text:
Q: Integration by Parts and Convergent/Divergent Series Calculus We are asked to integrate:
$$\int x (lnx) dx$$
Integration by parts gives us: (using L-I-A-T-E)
$$u = lnx$$
$$ du = (1/x)dx$$
$$ dv = xdx $$
We find v by integrating dv:
$$ v = (1/2)x^2 $$
Recall:
$$uv - \int v du$$
Performing our substiutions:
$$ (1/2)x^2lnx -(1/2)\int xdx$$
This gives results as:
$$(1/2)x^2(lnx-(1/2))$$
Now, taking the limit of the solution:
$$lim [(1/2)x^2(lnx-(1/2))] -> (1/4) as t -> infinity$$
If I take the limit of my solution as x approaches infinity my solution approaches (1/4) and therefore is a convergent series.

A: Your $\int x dx$ should be $\int \frac12 x dx$.  Then your final answer will be $\frac12 x^2(\ln x-\frac12)$


text:
Q: Why aren't static methods considered good OO practice? I'm reading Programming Scala. At the beginning of chapter 4, the author comments that Java supports static methods, which are "not-so-pure OO concepts." Why is this so?

A: Object-orientation is about three things:

*

*messaging,

*local retention and protection and hiding of state-process, and

*extreme late-binding of all things.

Of those three, the most important one is messaging.
Static methods violate at least messaging and late-binding.
The idea of messaging means that in OO, computation is performed by networks of self-contained objects which send messages to each other. Sending a message is the only way of communication/computation.
Static methods don't do that. They aren't associated with any object. They really aren't methods at all, according to the usual definition. They are really just procedures. There's pretty much no difference between a Java static method Foo.bar and a BASIC subroutine FOO_BAR.
As for late-binding: a more modern name for that is dynamic dispatch. Static methods violate that, too, in fact, it's even in their very name: static methods.
Static methods break some very nice properties of object-orientation. For example, object-oriented systems are automatically capability-safe with objects acting as capabilities. Static methods (or really any statics, be that static state or static methods) break that property.
You can also execute every object in parallel in its own process, since they only communicate via messaging, thus providing some trivial concurrency. (Like Actors, basically, which shouldn't be too surprising, since Carl Hewitt created the Actor Model based on Smalltalk-71, and Alan Kay created Smalltalk-71 partially based on PLANNER, which in turn was created by Carl Hewitt. The close relationship between actors and objects is far from coincidental, in fact, they are essentially one and the same.) Again, statics (both static methods, and especially static state) break that nice property.

A: Don't confuse "not-so-pure OO concepts" with "bad practice". Being "pure OO" is not some panacea that you should attempt to achieve. Just because static methods don't take an instance variable as a parameter does not mean that they are not useful. Some things just don't lend themselves to objects, and they should not be forced into that mold just for the sake of "purity".
Some people think that things should be "pure", and thus anything "impure" is bad practice. In reality, bad practice is just doing things that are confusing, hard to maintain, difficult to use, etc. Creating static methods that take an instance is bad practice because any method that takes an instance should probably be an instance method. On the other hand, things like utility and factory functions generally don't take an instance, so they should be static.
If you're wondering why they're not "pure OO", it's because they are not instance methods. A "pure" OO language would have everything being an object and all functions be instance methods. Of course, that's not terribly useful all the time. For example, consider the Math.atan2 method. It takes two numbers and doesn't require any state. What object could you even make it a method of? In a "pure" OO language, Math might itself be an object (a singleton, probably), and atan2 would be an instance method, but since the function doesn't actually use any state in the Math object, it is also not a "pure OO" concept.

A: One reason that static methods aren't very OO that hasn't been mentioned so far is that interfaces and abstract classes only define non-static methods.  Static methods thus don't fit very well into inheritance.
Note also that static methods do not have access to "super", which means that static methods cannot be overridden in any real sense.  Actually, they can't be overridden at all, only hidden.  Try this:
public class Test {
    public static int returnValue() {
        return 0;
    }

    public static void main(String[] arg) {
        System.out.println(Test.returnValue());
        System.out.println(Test2.returnValue());
        Test x = new Test2();
        System.out.println(x.returnValue());
    }
}

public class Test2 extends Test {
    public static int returnValue() {
        return 1;
    }
}

When you run this, you won't get what you expect.  Test.returnValue() gives what you expect.  Test2.returnValue() hides the method of the same name in the superclass (it does not override it), and it gives what you would expect.
One might naively expect "non-statically" calling a static method to use polymorphism.  It doesn't.  Whatever class the variable is declared as is the one used to look up the method.  This is bad form because someone might expect the code to do something different from what it actually does.
This doesn't mean, "Don't use static methods!"  It does mean that you should reserve use of static methods for those instances where you really want the Class object to own the method, and not just as a lazy way of making a singleton.

A: Static methods are not so pure OO concepts because they can be invoked without an object actually being associated with them. You use the class itself. You invoke them like this Classname.method(...);

A: Static methods cause tight coupling, which is a violation of good Object Oriented Design. The tight coupling of the calling code and the code within the static method cannot be avoided through Dependency Inversion because static methods inherently don't support object-oriented design techniques such as Inheritance and Polymorphism.
Besides static methods are difficult to test because of these tightly-coupled dependencies, which oftentimes lead to third-party infrastructure that the code depends upon - like a database, and it makes it very difficult to change the behavior without actually going in and changing the code.

A: Static methods aren't considered good OO practice due to below reasons:
1) Prevents from Re-usability:
Static methods can't be overriden. It can't be used to in interface.
2) Object Lifetime is very long:
Static methods remain in the memory for a log time and its garbage collection takes long time. Developer's don't have control on destroying or creating of Static variables.
Excessive usage of static variables can result in the memory overflow.
3) Also, some other points:
It doesn't respect the encapsulation because object does't remain in the complete control of its state. It doesn't follow concepts like Inversion of control, loose coupling, dependency injection, etc.

A: Concept of OO is talks about controlling/accessing data from an object, but static methods need not to be called using an object and they belong to class rather than object.
--Cheers


text:
Q: string indices must be integers when parsing Json, I have the json file and its content is like in the below.
I have a code for read and parse it. You can see my code in the below.
"['[{\"Manufacturer\": \"VMware, Inc.\", \"Model\": \"VMware7,1\", \"Name\": \"DC01\"}]', '[{\"Index\": \"1\", \"IPAddress\": [\"192.168.1.240,fe80::350e:d28d:14a5:5cbb\"]}]'

my code
with open('data2.json', 'w') as jsonFile:
    json.dump(str(output_array), jsonFile)
    jsonFile.close()

mySql_insert_query = """INSERT INTO wmi_inventory (wmi_data, date)
                                VALUES (%s, %s) """
now = datetime.now()
dt_string = now.strftime("%Y-%m-%d-%H:%M:%S")
record = (data, dt_string)
cursor.execute(mySql_insert_query, record)
connection.commit()

with open('data2.json','r') as lst:
     data=lst.read()
     d = json.loads(json.dumps(data))
     print(d["Name"])

When i run my code, im getting this error. How can i solve this?
Traceback (most recent call last):
  File "wmi_deneme.py", line 121, in <module>
    print(d["Name"])
TypeError: string indices must be integers

I have 3 outputs like :
 [{'Manufacturer': 'VMware, Inc.', 'Model': 'VMware7,1', 'Name': 'DC01'}]
 [{'Index': '1', 'IPAddress': ['192.168.1.240,fe80::350e:d28d:14a5:5cbb']}]
 [{'Name': 'DC01', 'UserName': None}]

I tried to get them all in an array and this is the result. So this is my output array.
[[{'Manufacturer': 'VMware, Inc.', 'Model': 'VMware7,1', 'Name': 'DC01'}], [{'Index': '1', 'IPAddress': ['192.168.1.240,fe80::350e:d28d:14a5:5cbb']}], [{'Name': 'DC01', 'UserName': None}]]

I want to reach this values
Name
Manucaturer
Username.
i'm stuck here

A: import json
output_array =  [[{'Manufacturer': 'VMware, Inc.', 'Model': 'VMware7,1', 'Name': 'DC01'}],
                 [{'Index': '1', 'IPAddress': ['192.168.1.240', 'fe80::350e:d28d:14a5:5cbb']}],
                 [{'Name': 'DC01', 'UserName': None}]]

# write to json
with open('data.json', 'w') as f:
    json.dump(output_array, f, indent=4)

# reading from JSON
with open('data.json') as f:
    data = json.load(f)
    for item in data:
        for dct in item:
            print('------------------')
            for key in ['Manufacturer', 'Name', 'UserName']:
                print(f"{key} --> {dct.get(key, 'Key Not Present')}")

Note the change I made to IPAddress - now it is list of strings, not list with single string representing 2 comma-separated IP addresses. But you can keep it single string despite it doesn't make sense.
This will produce following JSON
[
    [
        {
            "Manufacturer": "VMware, Inc.",
            "Model": "VMware7,1",
            "Name": "DC01"
        }
    ],
    [
        {
            "Index": "1",
            "IPAddress": [
                "192.168.1.240",
                "fe80::350e:d28d:14a5:5cbb"
            ]
        }
    ],
    [
        {
            "Name": "DC01",
            "UserName": null
        }
    ]
]

Now, when you have proper JSON file, the reading part (repeated below):
with open('data.json') as f:
    data = json.load(f)
    for item in data:
        for dct in item:
            print('------------------')
            for key in ['Manufacturer', 'Name', 'UserName']:
                print(f"{key} --> {dct.get(key, 'Key Not Present')}")

this will output
------------------
Manufacturer --> VMware, Inc.
Name --> DC01
UserName --> Key Not Present
------------------
Manufacturer --> Key Not Present
Name --> Key Not Present
UserName --> Key Not Present
------------------
Manufacturer --> Key Not Present
Name --> DC01
UserName --> None

It is bit odd that you have a [unnecessarily] deeply-nested structure like this, why not just list of dicts?


text:
Q: Lookup in mongo DB I am trying to model a database for a custom blog website using mongoDB. I have following collections
User collection :
[{
  "_id": {
    "$oid": "5ed15463f43c335cb2e9ef73"
  },
  "first_name": "xxx1",
  "last_name": "xxx1",
  "email": "xxx@gmail.com"
},{
  "_id": {
    "$oid": "5ed15463f43c335cb2e9ef74"
  },
  "first_name": "xxx2",
  "last_name": "xxx2",
  "email": "xxx2@gmail.com"
},{
  "_id": {
    "$oid": "5ed15463f43c335cb2e9ef75"
  },
  "first_name": "xxx3",
  "last_name": "xxx3",
  "email": "xxx3@gmail.com"
},{
  "_id": {
    "$oid": "5ed15463f43c335cb2e9ef76"
  },
  "first_name": "xxx4",
  "last_name": "xxx4",
  "email": "xxx4@gmail.com"
},{
  "_id": {
    "$oid": "5ed15463f43c335cb2e9ef77"
  },
  "first_name": "xxx3",
  "last_name": "xxx3",
  "email": "xxx3@gmail.com"
},{
  "_id": {
    "$oid": "5ed15463f43c335cb2e9ef78"
  },
  "first_name": "xxx4",
  "last_name": "xxx4",
  "email": "xxx4@gmail.com"
}]

Post collection: I have created embeded document called Comments and likes and used reference field of user_id from User collection.
[{
  "_id": {
    "$oid": "5f232c18a93ce29203b3f2f6"
  },
  "post_created_user_id": {
    "$oid": "5ed15463f43c335cb2e9ef73"
  },
  "post_date": {
    "$date": "2020-07-30T20:22:48.839Z"
  },
  "post_content": "Content 1",
  "post_likes": [
    {
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef75"
      }
    },
    {
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef76"
      }
    }
  ],
  "post_comments": [
    {
      "comment_id": {
        "$oid": "5f2850966efb9d4e803b2030"
      },
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef73"
      },
      "comment_content": "Test comment1",
      "comment_date": {
        "$date": "2020-08-03T17:59:50.132Z"
      }
    },
    {
      "comment_id": {
        "$oid": "5f2850ff6efb9d4e803b2033"
      },
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef74"
      },
      "comment_content": "test comments 1",
      "comment_date": {
        "$date": "2020-08-03T18:01:35.008Z"
      }
    }
  ]
},{
  "_id": {
    "$oid": "5f232c18a93ce29203b3f2f7"
  },
  "post_created_user_id": {
    "$oid": "5ed15463f43c335cb2e9ef73"
  },
  "post_date": {
    "$date": "2020-07-30T20:22:48.839Z"
  },
  "post_content": "content 2",
  "post_likes": [
    {
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef77"
      }
    },
    {
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef78"
      }
    }
  ],
  "post_comments": [
    {
      "comment_id": {
        "$oid": "5f2850966efb9d4e803b2030"
      },
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef73"
      },
      "comment_content": "Test comment1",
      "comment_date": {
        "$date": "2020-08-03T17:59:50.132Z"
      }
    },
    {
      "comment_id": {
        "$oid": "5f2850ff6efb9d4e803b2033"
      },
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef74"
      },
      "comment_content": "test comments 1",
      "comment_date": {
        "$date": "2020-08-03T18:01:35.008Z"
      }
    }
  ]
}]

Desire output :
 {
    "_id": {
        "$oid": "5f232c18a93ce29203b3f2f6"
    },
    "post_created_user_id": {
        "$oid": "5ed15463f43c335cb2e9ef73"
    },
    "post_date": {
        "$date": "2020-07-30T20:22:48.839Z"
    },
    "post_content": "Content 1",
      "post_likes": [{
        "user_id": {
            "$oid": "5ed15463f43c335cb2e9ef73"
        },
        user_info : {
            "first_name": "xxx1",
            "last_name": "xxx1",
            "email": "xxx@gmail.com"

    }, {
        "user_id": {
            "$oid": "5ed15463f43c335cb2e9ef74"
        },
        user_info : {
            "first_name": "xxx2",
            "last_name": "xxx2",
            "email": "xxx2@gmail.com"

    }],
    "post_comments": [{
        "comment_id": {
            "$oid": "5f2850966efb9d4e803b2030"
        },
        "user_id": {
            "$oid": "5ed15463f43c335cb2e9ef73"
        },
        "comment_content": "Test comment1",
        "comment_date": {
            "$date": "2020-08-03T17:59:50.132Z"
        },
        user_info : {
            "first_name": "xxx1",
            "last_name": "xxx1",
            "email": "xxx@gmail.com"
        }
    }, {
        "comment_id": {
            "$oid": "5f2850ff6efb9d4e803b2033"
        },
        "user_id": {
            "$oid": "5ed15483f43c335cb2e9ef74"
        },
        "comment_content": "test comments 1",
        "comment_date": {
            "$date": "2020-08-03T18:01:35.008Z"
        }
        user_info : {
            "first_name": "xxx2",
            "last_name": "xxx2",
            "email": "xxx2@gmail.com"
        }
    }]
}

Look up I tried on Post collection:
[
    {
        '$unwind': {
            'path': '$post_likes',
            'preserveNullAndEmptyArrays': True
        }
    }, {
        '$unwind': {
            'path': '$post_comments',
            'preserveNullAndEmptyArrays': True
        }
    }, {
        '$lookup': {
            'from': 'users_details',
            'localField': 'post_likes.user_id',
            'foreignField': '_id',
            'as': 'post_likes.user_info'
        }
    }, {
        '$lookup': {
            'from': 'users_details',
            'localField': 'post_comments.user_id',
            'foreignField': '_id',
            'as': 'post_comments.user_info'
        }
    }, {
        '$unwind': {
            'path': '$post_likes.user_info',
            'preserveNullAndEmptyArrays': True
        }
    }, {
        '$unwind': {
            'path': '$post_comments.user_info',
            'preserveNullAndEmptyArrays': True
        }
    }, {
        '$group': {
            '_id': '$_id',
            'post_created_user_id': {
                '$first': '$post_created_user_id'
            },
            'post_content': {
                '$first': '$post_content'
            },
            'post_likes': {
                '$push': '$post_likes'
            },
            'post_comments': {
                '$push': '$post_comments'
            }
        }
    }
]

Getting the following output with duplicates val.
[{
  "_id": {
    "$oid": "5f232c18a93ce29203b3f2f6"
  },
  "post_created_user_id": {
    "$oid": "5ed15463f43c335cb2e9ef73"
  },
  "post_content": "Content 1",
  "post_likes": [
    {
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef75"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef75"
        },
        "first_name": "xxx3",
        "last_name": "xxx3",
        "email": "xxx3@gmail.com"
      }
    },
    {
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef75"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef75"
        },
        "first_name": "xxx3",
        "last_name": "xxx3",
        "email": "xxx3@gmail.com"
      }
    },
    {
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef76"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef76"
        },
        "first_name": "xxx4",
        "last_name": "xxx4",
        "email": "xxx4@gmail.com"
      }
    },
    {
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef76"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef76"
        },
        "first_name": "xxx4",
        "last_name": "xxx4",
        "email": "xxx4@gmail.com"
      }
    }
  ],
  "post_comments": [
    {
      "comment_id": {
        "$oid": "5f2850966efb9d4e803b2030"
      },
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef73"
      },
      "comment_content": "Test comment1",
      "comment_date": {
        "$date": "2020-08-03T17:59:50.132Z"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef73"
        },
        "first_name": "xxx1",
        "last_name": "xxx1",
        "email": "xxx@gmail.com"
      }
    },
    {
      "comment_id": {
        "$oid": "5f2850ff6efb9d4e803b2033"
      },
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef74"
      },
      "comment_content": "test comments 1",
      "comment_date": {
        "$date": "2020-08-03T18:01:35.008Z"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef74"
        },
        "first_name": "xxx2",
        "last_name": "xxx2",
        "email": "xxx2@gmail.com"
      }
    },
    {
      "comment_id": {
        "$oid": "5f2850966efb9d4e803b2030"
      },
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef73"
      },
      "comment_content": "Test comment1",
      "comment_date": {
        "$date": "2020-08-03T17:59:50.132Z"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef73"
        },
        "first_name": "xxx1",
        "last_name": "xxx1",
        "email": "xxx@gmail.com"
      }
    },
    {
      "comment_id": {
        "$oid": "5f2850ff6efb9d4e803b2033"
      },
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef74"
      },
      "comment_content": "test comments 1",
      "comment_date": {
        "$date": "2020-08-03T18:01:35.008Z"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef74"
        },
        "first_name": "xxx2",
        "last_name": "xxx2",
        "email": "xxx2@gmail.com"
      }
    }
  ]
},{
  "_id": {
    "$oid": "5f232c18a93ce29203b3f2f7"
  },
  "post_created_user_id": {
    "$oid": "5ed15463f43c335cb2e9ef73"
  },
  "post_content": "content 2",
  "post_likes": [
    {
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef77"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef77"
        },
        "first_name": "xxx3",
        "last_name": "xxx3",
        "email": "xxx3@gmail.com"
      }
    },
    {
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef77"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef77"
        },
        "first_name": "xxx3",
        "last_name": "xxx3",
        "email": "xxx3@gmail.com"
      }
    },
    {
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef78"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef78"
        },
        "first_name": "xxx4",
        "last_name": "xxx4",
        "email": "xxx4@gmail.com"
      }
    },
    {
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef78"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef78"
        },
        "first_name": "xxx4",
        "last_name": "xxx4",
        "email": "xxx4@gmail.com"
      }
    }
  ],
  "post_comments": [
    {
      "comment_id": {
        "$oid": "5f2850966efb9d4e803b2030"
      },
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef73"
      },
      "comment_content": "Test comment1",
      "comment_date": {
        "$date": "2020-08-03T17:59:50.132Z"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef73"
        },
        "first_name": "xxx1",
        "last_name": "xxx1",
        "email": "xxx@gmail.com"
      }
    },
    {
      "comment_id": {
        "$oid": "5f2850ff6efb9d4e803b2033"
      },
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef74"
      },
      "comment_content": "test comments 1",
      "comment_date": {
        "$date": "2020-08-03T18:01:35.008Z"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef74"
        },
        "first_name": "xxx2",
        "last_name": "xxx2",
        "email": "xxx2@gmail.com"
      }
    },
    {
      "comment_id": {
        "$oid": "5f2850966efb9d4e803b2030"
      },
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef73"
      },
      "comment_content": "Test comment1",
      "comment_date": {
        "$date": "2020-08-03T17:59:50.132Z"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef73"
        },
        "first_name": "xxx1",
        "last_name": "xxx1",
        "email": "xxx@gmail.com"
      }
    },
    {
      "comment_id": {
        "$oid": "5f2850ff6efb9d4e803b2033"
      },
      "user_id": {
        "$oid": "5ed15463f43c335cb2e9ef74"
      },
      "comment_content": "test comments 1",
      "comment_date": {
        "$date": "2020-08-03T18:01:35.008Z"
      },
      "user_info": {
        "_id": {
          "$oid": "5ed15463f43c335cb2e9ef74"
        },
        "first_name": "xxx2",
        "last_name": "xxx2",
        "email": "xxx2@gmail.com"
      }
    }
  ]
}]

Can someone help me to construct the aggregation ?

A: Take a look step by step,
post_comments lookup

*

*$unwind post_comments because its array and we need to lookup by single comment

db.posts.aggregate([
  {
    $unwind: "$post_comments"
  },

*

*$lookup Its correct that you have prepared

  {
    $lookup: {
      from: "users_details",
      localField: "post_comments.user_id",
      foreignField: "_id",
      as: "post_comments.user_info"
    }
  },

*

*removed not needed field from user_info

  {
    $project: {
      "post_comments.user_info._id": 0
    }
  },

*

*$unwind post_comments.user_info because its an array and we need only single user_info object

  {
    $unwind: {
      path: "$post_comments.user_info"
    }
  },

*

*$group by _id because above unwind separated the all documents, and we need to combine here

  {
    $group: {
      _id: "$_id",
      post_created_user_id: {
        $first: "$post_created_user_id"
      },
      post_date: {
        $first: "$post_date"
      },
      post_content: {
        $first: "$post_content"
      },
      post_comments: {
        $push: "$post_comments"
      }
    }
  }
])

post_likes lookup

*

*repeat the above steps just change post_comments to post_likes and change in $group to push post_likes, you can check the below playground.

You can combine the above query part as they are in sequence, separated for the explanation purpose.
Playground: https://mongoplayground.net/p/GzVvEbPNwkA


text:
Q: Check if index in array exists from string do you know how to test, whether an index, based on what we pass in a string, exists in an array?
Assume the following code:
<?php

$myArray = [
    "elemOne" => "valueElemOne",
    "elemTwo" => [
        "elemTwoOne" => "valueElemTwoOne",
        "elemTwoTwo" => [
            "elemThreeOne" => "valueElemThreeOne",
            "elemThreeTwo" => "valueElemThreeTwo",
        ],
    ],
];

Now, I have a string $myString = "elemTwo/elemTwoTwo/elemThreeThree". What I want to do with $myString is somewhat format it in a way, so I could check
<?php

if(isset($myArray['elemTwo']['elemTwoTwo']['elemThreeThree'])) {
    // maybe do something
    return true;
} else {
    return false;
}

Naturally in my case this would return false, as the index "elemThreeThree" does not exist within my array. I tried splitting the string, tried to format as [elemTwo][elemTwoTwo][elemThreeThree] and then evaluating it, but nothing really worked.
Do you think of a possible approach that could help me?

A: simple solution could be
  <?php
     $arr = array('hello'=>array('world'=>array('in'=>'jo')));
     $myString = "hello/world/inf";

     function checkString($string, array $search_array) {
        $test = explode('/',$string);
        foreach($test as $key) {
           if(isset($search_array[$key])) $search_array = $search_array[$key];
           else return false;
        }
        return true;
     }
     var_dump(checkString($myString,$arr));
     die;

The Output of the function will true or false

A: Why did splitting it not work?
Is there something wrong with this?
<?php
$arrayTest = array(
    "arrayOne" => "string",
    "arrayTwo" => array(
        "arrayThree"    => "string",
        "arrayFour"     => array("winner" => "me")
    )
);

var_dump(expanded_key_exists($arrayTest, "arrayOne"));
var_dump(expanded_key_exists($arrayTest, "arrayTwo"));
var_dump(expanded_key_exists($arrayTest, "arrayTwo/arrayThree"));
var_dump(expanded_key_exists($arrayTest, "arrayTwo/arrayThree/arrayTwenty"));
var_dump(expanded_key_exists($arrayTest, "arrayTwo/arrayFour"));
var_dump(expanded_key_exists($arrayTest, "arrayTwo/arrayFour/winner"));

if(expanded_key_exists($arrayTest, "arrayTwo/arrayFour/winner")){
    echo "The winner is: " . expanded_array_key($arrayTest, "arrayTwo/arrayFour/winner");
}

function expanded_key_exists($array, $key){
    $arrayKeys = explode("/", $key);
    foreach($arrayKeys as $someKey){
        if(is_array($array) && array_key_exists($someKey, $array)){
            $array = $array[$someKey];
        }else{
            return false;
        }
    }
    return true;
}

function expanded_array_key($array, $key){
    $arrayKeys = explode("/", $key);
    foreach($arrayKeys as $someKey){
        if(is_array($array) && array_key_exists($someKey, $array)){
            $array = $array[$someKey];
        }else{
            return null;
        }
    }
    return $array;
}
?>


text:
Q: How to set unique values only for the child model? I have the following related models:
class DeviceType(models.Model):
    type_name = models.CharField(primary_key=True, max_length=64, unique=True)
    type_description = models.TextField(max_length=512, blank=True)

class DeviceTypeMarker(models.Model):
    marker_status = IntegerField()
    marker_status_text = models.CharField(max_length=64)
    marker = models.ImageField(upload_to='images/types/')
    marker_device_type = models.ForeignKey(DeviceType, on_delete=models.CASCADE, related_name='marker')

Where it is possible to define many DeviceType elements. For every DeviceType element there can be many different marker_status, marker_status_text and marker. The thing is that I don't want that inside a single DeviceType these elements are duplicated. They can be repeated but only in an another DeviceType.
For example, if type1 is a DeviceType object, then there can be only a marker_status with value "1", only a marker_status_textwith value "error" and the same for marker. This values could only be repeated in an other DeviceType object. For example, type2..
How is this done?

A: So you should add UniqueConstraint with all fields that should be unique together
class Meta:
    constraints = [
        models.UniqueConstraint(
            fields=['marker_status', 'marker_status_text',
                   'marker', 'marker_device_type'],
            name='unique_for_device')
    ]


text:
Q: IExcelReader how to read date and insert it into sql? I have in my excel some date fields that are in this format:
1/4/2016, 2/14/2016, etc.
When i try to insert that fields in a database I get an error:
String is not recongized as a valid DateTime
this is my code:
 IExcelDataReader excelReader;
                if (System.IO.Path.GetExtension(ope.FileName).ToUpper() == ".XLS")
                {

                    excelReader = ExcelReaderFactory.CreateBinaryReader(stream,true);
                }
                else
                {

                    excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                }

                excelReader.IsFirstRowAsColumnNames = true;
                DataSet result = excelReader.AsDataSet(true);

                DataClassesFinPodaciDataContext conn = new DataClassesFinPodaciDataContext();

                foreach (DataRow dr in result.Tables[0].Rows)
                {
                   string s1 = Convert.ToString(dr[4]);
                    DateTime conv1 = Convert.ToDateTime(s1);
                    string d2 = Convert.ToString(dr[14]);
                    DateTime conv2 = Convert.ToDateTime(d2);
                    string d3 = Convert.ToString(dr[15]);
                    DateTime conv3 = Convert.ToDateTime(d3);
                    string d4 = Convert.ToString(dr[19]);
                    DateTime conv4 = Convert.ToDateTime(d4);

                    //string d1 = string.Parse()
                    tblFinansijskiPodaci addTable = new tblFinansijskiPodaci()
                    {

                        Firma = Convert.ToInt32(dr[0]),
                        NazFirme = Convert.ToString(dr[1]),
                        VrstaNal = Convert.ToString(dr[2]),
                        BrojNal = Convert.ToInt32(dr[3]),
                        DatumNal = conv1,
                        SifraRJ = Convert.ToInt32(dr[5]),
                        Konto = Convert.ToString(dr[6]),
                        NazivKonta = Convert.ToString(dr[7]),
                        Partner = Convert.ToInt32(dr[8]),
                        NazivPartnera = Convert.ToString(dr[9]),
                        Adresa = Convert.ToString(dr[10]),
                        Mesto = Convert.ToString(dr[11]),
                        PIB = Convert.ToString(dr[12]),
                        BrojDok = Convert.ToString(dr[13]),
                        DatumDok = conv2,
                        DatumVal = conv3,
                        Opis = Convert.ToString(dr[16]),
                        Duguje = Convert.ToInt32(dr[17]),
                        Potrazuje = Convert.ToInt32(dr[18]),
                        DatumZaPDV = conv4,
                        Valuta = Convert.ToString(dr[20]),
                        DevDuguje = Convert.ToInt32(dr[21]),
                        DevPotrazuje = Convert.ToInt32(dr[22]),
                        Oslob = Convert.ToInt32(dr[23]),
                        IznosPDV = Convert.ToInt32(dr[24]),
                        Oslob1 = Convert.ToInt32(dr[25]),
                        IznosOslob = Convert.ToInt32(dr[26]),
                        UvozOsnovica = Convert.ToInt32(dr[27])

                    };
                    //   conn.ExecuteCommand("TRUNCATE TABLE Excel");
                    //  conn.ExecuteCommand("DELETE FROM tblFinansijskiPodaci where ime='a'");
                    conn.tblFinansijskiPodacis.InsertOnSubmit(addTable);

                }

                conn.SubmitChanges();
                excelReader.Close();

I have also tried
double d = double.Parse(Convert.ToString(dr[4])); DateTime conv = DateTime.FromOADate(d);

but that didnt work,since, I think since my date is not in a only numbers format.

A: You need to parse your dates specifiying the input format of dates to parse.
DateTime.ParseExact("1/4/2016", "d/M/yyyy);


text:
Q: How to zoom in and out the text size in the canvas, tkinter python I have created a canvas widget and added some objects such as rectangles and texts.
I have also bound a zoom function to the mouse wheel. It works for rectangles; however, it does not work for texts.
I want to make the zoom work for the text too, but I couldn't find the way to do it.
Any help would be appreciated.
class Layout(tk.Frame):

    def __init__(self, root):
        tk.Frame.__init__(self, root)[![enter image description here][1]][1]
        self.canvas = tk.Canvas(self, width=200, height=750, background="white")
        self.xsb = tk.Scrollbar(self, orient="horizontal", command=self.canvas.xview)
        self.ysb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.ysb.set, xscrollcommand=self.xsb.set)
        self.canvas.configure(scrollregion=(0,0,1000,1000))

        self.xsb.grid(row=1, column=0, sticky="ew")
        self.ysb.grid(row=0, column=1, sticky="ns")
        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        #self.canvas.create_text(50,10, text="Click and drag to move the canvas\nScroll to zoom.")

        # This is what enables using the mouse:
        self.canvas.bind("<ButtonPress-1>", self.move_start)
        self.canvas.bind("<B1-Motion>", self.move_move)
        #linux scroll
        self.canvas.bind("<Button-4>", self.zoomerP)
        self.canvas.bind("<Button-5>", self.zoomerM)
        #windows scroll
        self.canvas.bind("<MouseWheel>",self.zoomer)

    #move
    def move_start(self, event):
        self.canvas.scan_mark(event.x, event.y)
    def move_move(self, event):
        self.canvas.scan_dragto(event.x, event.y, gain=1)

    #windows zoom
    def zoomer(self,event):
        if (event.delta > 0):
            self.canvas.scale("all", event.x, event.y, 1.1, 1.1)
        elif (event.delta < 0):
            self.canvas.scale("all", event.x, event.y, 0.9, 0.9)
        self.canvas.configure(scrollregion = self.canvas.bbox("all"))

    #linux zoom
    def zoomerP(self,event):
        self.canvas.scale("all", event.x, event.y, 1.1, 1.1)
        self.canvas.configure(scrollregion = self.canvas.bbox("all"))
    def zoomerM(self,event):
        self.canvas.scale("all", event.x, event.y, 0.9, 0.9)
        self.canvas.configure(scrollregion = self.canvas.bbox("all"))

root = Tk()
root.title("Seoul Cell")
root.geometry("1300x1000")
root.resizable(True, True)

if __name__ == "__main__":

    global monitor1
    monitor1 = Layout(root)
    monitor1.pack(fill="both", expand=True)

for i in range(10):
    x1= random.randrange(0, 1000)
    x2 = random.randrange(0, 1000)
    y1 = random.randrange(0, 1000)
    y2 = random.randrange(0, 1000)
    monitor1.canvas.create_rectangle(x1, x2, y1, y2, fill = "black", stipple= "gray50")
    monitor1.canvas.create_text(x1, y1, text = "random word!", font = ("Helvetica", 10))
root.mainloop()

A: Ben Mega's solution works fine and answers well the question. I am just showing below a different way of implementing the fontsize change when zooming in and out.
The idea is to use a common tkinter.font.Font for all text items so that we can just change the size of this font object instead of reconfiguring all the items. The font size can then be changed globally using .configure(size=<new size>).
Here is the code. I have added a create_text() method to the Layout class to avoid having to set the font manually when creating the item.
import tkinter as tk
from tkinter.font import Font
import random

class Layout(tk.Frame):

    def __init__(self, root):
        tk.Frame.__init__(self, root)
        self.font = Font(self, "Arial 10")  # create font object
        self.fontsize = 10  # keep track of exact fontsize which is rounded in the zoom

        self.canvas = tk.Canvas(self, width=200, height=750, background="white")
        self.xsb = tk.Scrollbar(self, orient="horizontal", command=self.canvas.xview)
        self.ysb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.ysb.set, xscrollcommand=self.xsb.set)
        self.canvas.configure(scrollregion=(0,0,1000,1000))

        self.xsb.grid(row=1, column=0, sticky="ew")
        self.ysb.grid(row=0, column=1, sticky="ns")
        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        # This is what enables using the mouse:
        self.canvas.bind("<ButtonPress-1>", self.move_start)
        self.canvas.bind("<B1-Motion>", self.move_move)
        #linux scroll
        self.canvas.bind("<Button-4>", self.zoomerP)
        self.canvas.bind("<Button-5>", self.zoomerM)
        #windows scroll
        self.canvas.bind("<MouseWheel>",self.zoomer)

    #create text
    def create_text(self, *args, **kwargs):
        self.canvas.create_text(*args, **kwargs, font=self.font)

    #move
    def move_start(self, event):
        self.canvas.scan_mark(event.x, event.y)

    def move_move(self, event):
        self.canvas.scan_dragto(event.x, event.y, gain=1)

    #windows zoom
    def zoomer(self,event):
        if (event.delta > 0):
            self.fontsize *= 1.1
            self.canvas.scale("all", event.x, event.y, 1.1, 1.1)
        elif (event.delta < 0):
            self.fontsize *= 0.9
            self.canvas.scale("all", event.x, event.y, 0.9, 0.9)
        self.font.configure(size=int(self.fontsize))  # update fontsize
        self.canvas.configure(scrollregion = self.canvas.bbox("all"))

    #linux zoom
    def zoomerP(self,event):
        self.fontsize *= 1.1
        self.font.configure(size=int(self.fontsize))
        self.canvas.scale("all", event.x, event.y, 1.1, 1.1)
        self.canvas.configure(scrollregion = self.canvas.bbox("all"))

    def zoomerM(self,event):
        self.fontsize *= 0.9
        self.font.configure(size=int(self.fontsize))
        self.canvas.scale("all", event.x, event.y, 0.9, 0.9)
        self.canvas.configure(scrollregion = self.canvas.bbox("all"))

root = tk.Tk()
root.title("Seoul Cell")
root.geometry("1300x1000")
root.resizable(True, True)

monitor1 = Layout(root)
monitor1.pack(fill="both", expand=True)

for i in range(10):
    x1= random.randrange(0, 1000)
    x2 = random.randrange(0, 1000)
    y1 = random.randrange(0, 1000)
    y2 = random.randrange(0, 1000)
    monitor1.canvas.create_rectangle(x1, x2, y1, y2, fill = "black", stipple= "gray50")
    monitor1.create_text(x1, y1, text="random word!")
root.mainloop()

A: The reason just scaling the canvas doesn't work is that the text font size is stuck at 10. To fix this, we need to add a property for font size, scale this, and then modify the text widgets. This isn't perfect due to the fact you can't do fractional font sizes but I think it works alright.
Here is the modified code.
import tkinter as tk
from tkinter import Tk
import random

#fontSize = 10

class Layout(tk.Frame):

    def __init__(self, root):
        tk.Frame.__init__(self, root) #[![enter image description here][1]][1]
        self.canvas = tk.Canvas(self, width=200, height=750, background="white")
        self.xsb = tk.Scrollbar(self, orient="horizontal", command=self.canvas.xview)
        self.ysb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.ysb.set, xscrollcommand=self.xsb.set)
        self.canvas.configure(scrollregion=(0,0,1000,1000))

        self.xsb.grid(row=1, column=0, sticky="ew")
        self.ysb.grid(row=0, column=1, sticky="ns")
        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        self.canvas.fontSize = 10
        #self.canvas.create_text(50,10, text="Click and drag to move the canvas\nScroll to zoom.")

        # This is what enables using the mouse:
        self.canvas.bind("<ButtonPress-1>", self.move_start)
        self.canvas.bind("<B1-Motion>", self.move_move)
        #linux scroll
        self.canvas.bind("<Button-4>", self.zoomerP)
        self.canvas.bind("<Button-5>", self.zoomerM)
        #windows scroll
        self.canvas.bind("<MouseWheel>",self.zoomer)

    #move
    def move_start(self, event):
        self.canvas.scan_mark(event.x, event.y)

    def move_move(self, event):
        self.canvas.scan_dragto(event.x, event.y, gain=1)

    #windows zoom
    def zoomer(self,event):
        if (event.delta > 0):
            self.canvas.scale("all", event.x, event.y, 1.1, 1.1)
            self.canvas.fontSize = self.canvas.fontSize * 1.1
        elif (event.delta < 0):
            self.canvas.scale("all", event.x, event.y, 0.9, 0.9)
            self.canvas.fontSize = self.canvas.fontSize * 0.9
        for child_widget in self.canvas.find_withtag("text"):
            self.canvas.itemconfigure(child_widget, font = ("Helvetica", int(self.canvas.fontSize)))
        self.canvas.configure(scrollregion = self.canvas.bbox("all"))

    #linux zoom
    def zoomerP(self,event):
        self.canvas.fontSize = self.canvas.fontSize * 1.1
        self.canvas.scale("all", event.x, event.y, 1.1, 1.1)
        for child_widget in self.canvas.find_withtag("text"):
            self.canvas.itemconfigure(child_widget, font = ("Helvetica", int(self.canvas.fontSize)))
        self.canvas.configure(scrollregion = self.canvas.bbox("all"))

    def zoomerM(self,event):
        self.canvas.fontSize = self.canvas.fontSize * 0.9
        self.canvas.scale("all", event.x, event.y, 0.9, 0.9)
        for child_widget in self.canvas.find_withtag("text"):
            self.canvas.itemconfigure(child_widget, font = ("Helvetica", int(self.canvas.fontSize)))
        self.canvas.configure(scrollregion = self.canvas.bbox("all"))

root = Tk()
root.title("Seoul Cell")
root.geometry("1300x1000")
root.resizable(True, True)

if __name__ == "__main__":

    global monitor1
    monitor1 = Layout(root)
    monitor1.pack(fill="both", expand=True)

for i in range(10):
    x1= random.randrange(0, 1000)
    x2 = random.randrange(0, 1000)
    y1 = random.randrange(0, 1000)
    y2 = random.randrange(0, 1000)
    monitor1.canvas.create_rectangle(x1, x2, y1, y2, fill = "black", stipple= "gray50")
    monitor1.canvas.create_text(x1, y1, text = "random word!", font = ("Helvetica", 10), tags="text")
root.mainloop()


text:
Q: Using std::swap on a vector of int I have a vector of int's... I just want to swap two values.
    std::vector<int> vec;

    vec.push_back(0);
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    vec.push_back(4);
    vec.push_back(5);
    vec.push_back(6);
    vec.push_back(7);
    vec.push_back(8);

    std::swap(vec.begin(), vec.end());

Before the swap being called I have my vec as:
[0,1,2,3,4,5,6,7,8]

After the std::swap(...) I was hoping to have the vec as:
[8,1,2,3,4,5,6,7,0]

But it remains as the initial state.
What is the problem here?

A: This should do the trick
assert(!vec.empty());
std::swap(vec.front(), vec.back());


text:
Q: Exception Value: ('08001', '[08001] [unixODBC][FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnect)') I'm using the pyodbc library to connect to a remote instance of sql server on windows from a python djanog web app running on an ubuntu Vm.
I have a database connection class, as below, which breaks on the line where I try and create a connection of object (there are a number of connectionStrings I've been trying);
import pyodbc

class SQLSeverConnection():

def __init__(self, DSN, user, password, database):
    connectionString = 'DSN=MSSQLServerDataSource;UID=django;PWD=password123!;DATABASE=HD'

    self.connection = pyodbc.connect(connectionString)
    self.cursor = self.connection.cursor()

def getTableNames(self):
    self.cursor.execute('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = \'BASE TABLE\'')
    tables = self.cursor.fetchall()
    return tables

def getColumnTitles(self, tableName):
    self.cursor.execute("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + tableName + "' ORDER BY ORDINAL_POSITION")
    columns = self.cursor.fetchall()
    return columns

def getColumnData(self, columnName, tableName, startDateTime, endDateTime):
    self.cursor.execute('SELECT ' + columnName + ' FROM ' + tableName + ' BETWEEN ' + startDateTime + ' AND ' + endDateTime + ' ORDER BY timestamp')
    data = self.cursor.fetchall()
    return data

When I runserver I get the error as described in the title.
My configuration files are as below;
(odbc.ini)
[MSSQLServerDataSource]
Driver = FreeTDS
Description = ODBC connection via FreeTDS
Trace = No
Servername = MSSQLServer
Database = HD
TDS_Version = 8.0

(odbcinst.ini)
[FreeTDS]
Description = TDS driver (Sybase/MS SQL)
# Some installations may differ in the paths
#Driver = /usr/lib/odbc/libtdsodbc.so
#Setup = /usr/lib/odbc/libtdsS.so
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
CPTimeout =
CPReuse =
FileUsage = 4

(freetds.conf)
#   $Id: freetds.conf,v 1.12 2007/12/25 06:02:36 jklowden Exp $
#
# This file is installed by FreeTDS if no file by the same
# name is found in the installation directory.
#
# For information about the layout of this file and its settings,
# see the freetds.conf manpage "man freetds.conf".

# Global settings are overridden by those in a database
# server specific section
[global]
    # TDS protocol version
;   tds version = 4.2

# Whether to write a TDSDUMP file for diagnostic purposes
# (setting this to /tmp is insecure on a multi-user system)
;   dump file = /tmp/freetds.log
;   debug flags = 0xffff

# Command and connection timeouts
;   timeout = 10
;   connect timeout = 10

# If you get out-of-memory errors, it may mean that your client
# is trying to allocate a huge buffer for a TEXT field.
# Try setting 'text size' to a more reasonable limit
text size = 64512

#Server For Django App
[MSSQLSever]
   host = <ip>
   port = 1433
   tds version = 8.0

When I type odbcinst -j into the terminal;
unixODBC 2.2.14
DRIVERS............: /etc/odbcinst.ini
SYSTEM DATA SOURCES: /etc/odbc.ini
FILE DATA SOURCES..: /etc/ODBCDataSources
USER DATA SOURCES..: /home/user/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8

The connection succeeds from the command line using isql and the dsn, user and password.
I really don't know what to do, I've been going round in circles with this for over a day now. Some help would be greatly appreciated!

A: Try this:
connectionString = 'DRIVER={FreeTDS};SERVER=10.1.3.230;PORT=1433;DATABASE=HD;UID=django;PWD=password123!;TDS_Version=7.2;'

You need to specify the TDS Version explicitly. See the different TDS Versions you can use here, 7.2 has worked for 2008+ for me on every SQL Server through 2014:
http://www.freetds.org/userguide/choosingtdsprotocol.htm
You'll need to do the same in your Django pyodbc settings. I'd recommend using this version of django-pyodbc:
https://github.com/lionheart/django-pyodbc/
Best of luck, let me know if it works for you.


text:
Q: How to export a cleaned dataframe to csv? I am attempting to export a cleaned dataframe to a csv file for it to be imported into a new jupyter notebook for ML purposes.
I ran the following code:
df_train.to_csv('../datasets/new_train.csv')
However, the output file, when opened, contains the same dataset as the input file (before cleaning).

A: Can you provide a minimal repeatable example, based on comments it is not clear on the mistake. Here is the sample code to prove it works
# Import pandas library
import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14], ['jerry', ]]
df = pd.DataFrame(data, columns=['Name', 'Age'])
print(df)
df.dropna(subset=['Age'], inplace=True)
print(df)
df.to_csv('names.csv')

Output of above code
    Name   Age
0    tom  10.0
1   nick  15.0
2   juli  14.0
3  jerry   NaN
   Name   Age
0   tom  10.0
1  nick  15.0
2  juli  14.0

Output of cat names.csv
,Name,Age
0,tom,10.0
1,nick,15.0
2,juli,14.0


text:
Q: Exception guarantees when moving object into std::vector If memory allocation fails while moving a object into a std::vector, and bad_alloc is thrown, does std::vector guarantee that the moved from object is unaltered/still valid ?
For example:
std::string str = "Hello, World!";
std::vector<std::string> vec;

vec.emplace_back(std::move(str));
/* Is str still valid and unaltered if the previous line throws? */

A: This is covered in [container.requirements.general]/11.2

if an exception is thrown by a push_back(), push_front(), emplace_back(), or emplace_front() function, that function has no effects.

So, you will not have a moved from object in the event of an exception.
This only covers if the vector throws.  We need to look at [vector.modifiers]/1 to see what happens if the move constructor itself throws:

If an exception is thrown while inserting a single element at the end and T is Cpp17CopyInsertable or is_nothrow_move_constructible_v<T> is true, there are no effects. Otherwise, if an exception is thrown by the move constructor of a non-Cpp17CopyInsertable T, the effects are unspecified.

emphasis mine
And in that case the behavior is unspecified.

In your case std::string has a noexcpet move constructor so you will have a valid object if an exception throws.


text:
Q: Cognito user attributes breaks Amplify Storage component Backend: Cognito and S3.
Frontend: React with aws-amplify.
Basic functionality works. I now need fine grained access control over directories in the S3 bucket. e.g. user-test can only access files in s3::my-bucket/user-test
The plan is to add user attributes (Principal Tag Attributes for access control) to the Federated Identity, which can be referenced on a per user basis in the Authorising Policy. However, the Amplify Storage component(s) break with ANY user attributes.
Any Storage request (list, get, put... ) returns this error:
AWSS3Provider - get signed url error TypeError: Cannot read properties of undefined (reading 'byteLength')
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'byteLength')
    at isEmptyData (isEmptyData.ts:11)
    at Sha256.update (webCryptoSha256.ts:32)
    at Sha256.update (crossPlatformSha256.ts:23)
    at hmac (credentialDerivation.ts:69)
    at credentialDerivation.ts:39
    at step (tslib.es6.js:100)
    at Object.next (tslib.es6.js:81)
    at tslib.es6.js:74
    at new Promise (<anonymous>)
    at __awaiter (tslib.es6.js:70)
    at getSigningKey (credentialDerivation.ts:37)
    at SignatureV4.getSigningKey (SignatureV4.ts:307)
    at SignatureV4.<anonymous> (SignatureV4.ts:153)
    at step (tslib.es6.js:100)
    at Object.next (tslib.es6.js:81)
    at fulfilled (tslib.es6.js:71)

I suspect my use case is beyond the scope of aws-amplify, what should I use instead?


text:
Q: Can Mathematica recompose an image? The OP in this post on superuser.com asks how to recompose an image; quoting:

I have a set of images, which are parts of a bigger image.
I would like the images to assembled as automated as possible, to
  recompose the whole picture.
How can I do that?

Just out of curiosity: how can I do that with Mathematica?
Probably ImageAssemble may work in most cases, but notice that in his example the various parts overlap: how to handle this?
Here three overlapping parts of an image:

And what if some of the parts are rotated? Like this:

The full image if needed:

A: Yesterday I showed how to locate a subimage inside a large image using ImageCorrelate. I will now show how to use the same approach to solve this problem.
Start by importing the images that you want to compose:
i1 = Import["http://i.stack.imgur.com/UjGAz.jpg"];
i2 = Import["http://i.stack.imgur.com/93kwm.jpg"];
GraphicsRow[{i1, i2}]

Since the right image is not completely contained by the left image, we cannot use my answer from the other question. However, if we split the right image into small enough pieces then there will be a piece that is covered completely by the left image. By locating this piece in the left image we know two positions, one in each image, that correspond to each other.
pieces = ImagePartition[i2, 64]

There may be several pieces that are covered by the left image, in which case there will be several good fits. I will select the piece that fits best, as given by ImageCorrelate.
minPixelValue[image_Image][subimage_Image] := Module[{corr, idata},
  corr = ImageCorrelate[image, subimage, EuclideanDistance];
  idata = ImageData[corr];
  idata = Map[Norm, idata, {2}];
  Min[idata]
  ]
bestFit = MinimalBy[Flatten[pieces], minPixelValue[i1]] // First;

Now I can find out where in the two images the piece that I selected as the best fit belongs:
{p1} = correspondingPixel[i1, bestFit];
{p2} = correspondingPixel[i2, bestFit];

GraphicsRow[{
  HighlightImage[i1, p1, Method -> {"DiskMarkers", 5}],
  HighlightImage[i2, p2, Method -> {"DiskMarkers", 5}]
  }]

Finally we need to compose the images. This is easier to do if we know where one of the images is positioned in the complete image, and also the dimensions of the complete image. I will assume such knowledge for convenience sake. I'll start by creating a padded version of the left image:
i = Import["http://i.stack.imgur.com/S2ISp.jpg"]; (* Full image *)
{right, bottom} = ImageDimensions[i] - ImageDimensions[i1];
padded = ImagePad[i1, {{0, right - 1}, {bottom - 1, 0}}]

And now I'll use ImageCompose to merge the images:
ImageCompose[padded, i2, p1, p2]

We can apply the same method again to merge this image with the third image. In general, if there are $n$ images then they can be merged like this in a recursive manner. Unless all images overlap with each other the order in which images are merged will be important, so it may require finesse.

A: This is not very automated but perhaps it will motivate experts:
Copied the images

Changing image to graphic and finding corresponding points:
fun[img_] :=
 With[{id = ImageDimensions[img]}, {Texture[img],
   Polygon[{{1, 1}, {id[[1]], 1}, id, {1, id[[2]]}},
    VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}]}]
{ma, mb} = ImageCorrespondingPoints[a, b];
{mta, mtc} = ImageCorrespondingPoints[a, c];

Using manipulate and pasting desired bookmarks:
Manipulate[
 Graphics[{GeometricTransformation[
    fun[a]~Join~{Red, PointSize[0.025], Point[ma]},
    TranslationTransform[{x, y}]], Opacity[0.5], fun[b], Yellow,
   PointSize[0.01], Point[mb]}],
 {x, -300, 10, Appearance -> "Labeled"}, {y, -300, 100,
  Appearance -> "Labeled"}]

Manipulate[
 Graphics[{GeometricTransformation[
    fun[c]~Join~{Red, PointSize[0.025], Point[mtc]},
    TranslationTransform[{x, y}]], Opacity[0.5],
   GeometricTransformation[fun[a], TranslationTransform[abt]], Yellow,
    PointSize[0.01],
   GeometricTransformation[Point[mta], TranslationTransform[abt]]}],
 {x, -300, 10, Appearance -> "Labeled"}, {y, -300, 100,
  Appearance -> "Labeled"}]

The bookmarks:
abt = "ab" /. {"ab" :> {x = -122.5`, y = -171.`}}
act = "ac" /. {"ac" :> {x = -128.`, y = 1.`}}

Piecing together:
Graphics[{GeometricTransformation[fun[a], TranslationTransform[abt]],
  GeometricTransformation[fun[c], TranslationTransform[act]], fun[b]}]

The code could be made more concise. I do not have time at present (this was a "stream of consciousness"). I look forward to learning from other answers.

In case of doubt


text:
Q: xslt returning first occurance of column I have an xml document which looks like
<book>xxxxxxxxxxx</book>
<record>
  <field>
    <column>Title</column>
    <value>HF80</value>
  </field>
  <field>
    <column>page</column>
    <value>97</value>
  </field>

.....
...
I need to print the "column" heading as a table row. I can get all the records in a table but dont know how to go about this.
The output I need would look like :-
tr td Title /td td Page /td /tr
Pointers welcome..
O

A: Something like this?
<xsl:template match="/">

      <xsl:apply-templates select="root/record/field" />

</xsl:template>

<xsl:template match="/root/record/field">

    <xsl:value-of select="./value" />

</xsl:template>

A: This transformation:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="record">

<xsl:apply-templates select="field/column"/>

<xsl:apply-templates select="field/value"/>

 </xsl:template>

 <xsl:template match="column|value">
  <xsl:apply-templates/>
 </xsl:template>

 <xsl:template match="book/text()"/>
</xsl:stylesheet>

when applied on this XML document (your provided XML made well-formed):
<books>
    <book>xxxxxxxxxxx</book>
    <record>
        <field>
            <column>Title</column>
            <value>HF80</value>
        </field>
        <field>
            <column>page</column>
            <value>97</value>
        </field>
    </record>
</books>

produces the wanted result:

      Title
      page

      HF80
      97


text:
Q: Running Java in Internet Explorer 11 I have JRE 8u211 installed on a Windows 10 box with IE 11.  I can see the Java plugin (and plugin 2) are installed and enabled.  I have the "Allow active content to run in files on my computer" option checked under Security.  But I cannot get a Java applet to load.  Every time the page loads, I get the "The page you are viewing uses Java" notification as if the browser thinks I don't have Java installed.
What am I missing?

A: Figured it out.  I'd forgotten that IE traditionally doesn't seem to like x64 Java installs very much.  Once I dropped a 32 bit version, everything worked.
In the perfect dream world where all software development makes use of current and best practices, applets might be dead.  But in the actual world of legacy support, they are (unfortunately) still alive.

A: I second the comment by Elliot Fischer... However, there is still quite a lot of Hardware that is still being supported, or even potentially manufactured (sold for sure) that can only function with these Java applets.
I had this problem with my Motorola FX7400. Of course Motorola says it's "Service & Support Discontinuation Date" is 30.8.2019. Of course the latest firmware is from 2015 and doesn't have a hint of any type of certificate or signing of java applets!
For most applets that have not been updated since the very latest Java Security settings were upgraded in around 2013-2015 and which most likely are also only 32-bit and have no signing of any sort on them; Do the following steps. Of course, even I CANNOT RECOMMEND THIS METHOD AT ALL FOR APPLICATIONS RUN FROM THE INTERNET Also, you should take precautions when trying to use Java like this on Hardware you are not familiar with.
The steps that are required for Windows 7, 8.1 & 10 with Internet Explorer 11 are as follows:

*

*Download and install latest JRE SE 32bit from here: https://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html (And yes, you need to give out your private data including address and phone number. You also need to pay for a license, if you are not a developer or a private user)

*Start Internet Explorer 11 (64 bit seems to work fine)

*Ensure ActiveX filtering is disabled Tools -> ActiveX filtering On my install disabling this was only necessary to be able to run the Java test from the "alternate page", which is marked "IE 11 users:": https://www.java.com/en/download/installed.jsp

*Check that the Java plugin is enabled Tools -> Manage Add-ons

*Check that your security zone has Scripting of Java applets enabled. On my IE11 it was enabled by default even for the Internet-zone set to Medium-High with protected mode on Tools -> Internet Options -> Security -> (select your appropriate zone) -> Custom level -> Scripting of Java applets

*If the applet that needs to run is not properly signed (very likely...), it is required to set every single URL where an applet is run in to the exceptions. (As of writing this answer, at least wildcars for paths are working.)

*When running the applet, accept the security exception prompts that Java prompts for.

*And finally! For some reason there will at some point when loading an applet that previously loaded fine be a prompt about not being able to run the applet, because only applications that meet the very high security settings (signed applets) can be run. To get back to running again, Java's temporary files need to be removed. Restoring security prompts has no effect. Start Menu -> Configure Java -> General tab -> Temporary Internet Files -> Settings... -> Delete Files -> OK C:\Users\%username%\AppData\LocalLow\Sun\Java\Deployment\Cache -directory probably also works.

Security and prompts really have come far in the past 10 years, haven't they?

A: I jumped here searching for an answer that I found elsewhere and I would like to share.
According to my experience  the problems of IEx64 with jre x64 are due to the fact that internet explorer tabs are 32 bit processes, so they work only if they find a 32 bit jre. There is a registry key to force IEx64 to open x64 tabs:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main
Dword TabProcGrowth set to 0

I heard it is considered a security flaw, but it can be accepted if IE is used only with well known legacy web applications.
About IEx64
In the folder
\Program Files (x86)\Internet Explorer

there is the 32 bit version and when you open a page in IEx64 it is actually displayed by an new instance of IEx86. You can check this using task manager, going on detail tab and looking at the application path.


text:
Q: Counting duplicates with multiple criteria (SUM IF FREQUENCY MATCH) I'm trying to get a count of crashes from an event log using the SUM IF FREQUENCY MATCH combination of formulas.  Column A has all the event IDs (but there are duplicates that i would like to ignore in the count). Column E has the road name where the crash occurred and I only want to count the crashes that occur on specific roads (I-96, I-196, M-6, US-131, US-31).  Column J has the event type, where I only want to count "crash" events.  The event type must be crash to count, but it can be any of the 5 roads listed (hence the and/or function). There are occasionally blanks in column E so I don't want those to screw up the Match function, but the other columns referenced do not have any blanks.  Currently this is my formula below, but I'm just getting a value of "0" as a result after CRTL/SHIFT/ENTER.  Any ideas on where I went wrong??
=SUM(IF(FREQUENCY(IF('Sheet1'!$E:$E<>"",IF(AND('Sheet1'!$J:$J="Crash",OR('Sheet1'!$E:$E="I-96",'Sheet1'!$E:$E="I-196",'Sheet1'!$E:$E="M-6",'Sheet1'!$E:$E="US-131",'Sheet1'!$E:$E="US-31")),MATCH('Sheet1'!$A:$A,'Sheet1'!$A:$A,0))),ROW('Sheet1'!$A:$A)-ROW('Sheet1'!$A$1)),1))

A: Sounds like a pivot table is in order:
try pivoting (which lets you filter) the data on roads, then put the crash type in your columns which will then aggregate the counts and give you the table you're looking for.
If Id's are unique, then you should 'remove duplicates' first.

A: I would like to suggest two different methods to solve the issue:
Method 1:

*

*To get the unique list of Roads got Crash,
enter this Array (CSE) Formula in Cell E64,
finish with Ctrl+Shift+Enter & fill down.
{=IFERROR(INDEX($B$64:$B$75, MATCH(0, IF($G$63=$C$64:$C$75, COUNTIF($E$63:$E63, $B$64:$B$75), ""), 0)),"")}

*Formula in Cell F64, also fill it down.
=COUNTIFS($B$64:$B$75,E64,$C$64:$C$75,$G$63)

*Formula in Cell F70,
=SUM(F64:F68).

Method 2:

*

*After get the unique list of Roads got Crash,
using above shown Array Formula, enter this one
in Cell F71.
=SUMPRODUCT(ISNUMBER(MATCH($B$64:$B$75,$E$64:$E$68,0))*($C$64:$C$75=$G$63))
Adjust cell references in the Formula as needed.


text:
Q: Add column counting repetitions of a sequence I'm trying to add a column to a data frame that counts how many times a sequence has been run through--in this case, months that go up to 12.
I started with month and year, but for my analysis I need to use an adjusted month_lag column.
year.reprex <- rep(1982:2015, each=12)
month.reprex <- rep(1:12, times=34)
df <- cbind(year.reprex, month.reprex) %>%
  as_tibble() %>%
  mutate(
    month_lag = ifelse(month.reprex < 12, month.reprex+1, 1))

I want to add a column with a numeric counter for how many times month_lag has run up to 12. The first value of month_lag is 2, so I can't just count the number of sequences of 1:12. This counter will be offset from the actual year column by one month. In this reprex, for the first eleven rows (month_lag goes from 2 to 12), I want the year_counter to be 1. When month_lag resets to 1 in row 12, the year_counter should increase to 2, and continue ticking up every time month_lag runs up to 12 and starts over at 1. A dplyr solution would be great if possible.

A: We can increment a counter whenever month_lag is 1 which can be achieved using cumsum
library(dplyr)

df %>% mutate(year_lag = cumsum(month_lag == 1) + 1)

# year.reprex month.reprex month_lag   year_lag
#         <int>        <int>     <dbl>    <dbl>
# 1        1982            1         2        1
# 2        1982            2         3        1
# 3        1982            3         4        1
# 4        1982            4         5        1
# 5        1982            5         6        1
# 6        1982            6         7        1
# 7        1982            7         8        1
#....

Or in base R
df$year_lag <- cumsum(df$month_lag == 1) + 1