text:
Q: How can i support multiple screen sizes in android with single xml layout file I want to support my android screen in multiple screen sizes but i can do it with maintaining multiple xml layout file's
but according to requirement it i supposed to be done with the single XML layout in order to optimize the app usage.
so please can you help me
i have gone through multiple tutorials multiple links but not able to get last option with stack overflow

A: Create three different Layouts Folder in your res folder for all devices and use the dimensions accordingly.
Generic Layout Folders
res/layout-small
res/layout-normal
res/layout-large
res/layout-xlarge

After you are done with making your Normal/Medium Layouts follow these steps:

*

*Convert the Normal Dimensions for other Screen Sizes.

*Copy your Normal Layout xml files in to other Folders.

*Change the suffix of the dimensions used according to the folder that you are in

*Resize the Image Resources in your drawable folder (Width and Height - Same technique as we used for converting the dimens) and put them in their respective drawable folder (drawable-ldpi, drawable-mdpi, drawable-hdpi, drawable-xdpi and so on).

*Then your Layouts should work on every device with correct positioning.

For converting Values
0.75 - ldpi  (small)   //mdpi dimens *0.75
1.0  - mdpi  (normal)  //First create these dimensions
1.5  - hdpi  (large)   //mdpi dimens *1.5
2.0  - xhdpi (xLarge)  //mdpi dimens *2.0

For Example
android:layout_width="66dip" //in normal
android:layout_width="100dip"//in large 66*1.5=100(approx)
android:layout_width="52dip" //in small 66*0.75=52(approx)

Also new Qualifier has been introduced
 - SmallestWidth
 - AvailableScreenWidth
 - AvailableScreenHeight
read more about it here https://developer.android.com/guide/practices/screens_support.html
I hope this helps.

A: May be you can try below library which manages all the screen size resolution automatically.
compile 'com.intuit.sdp:sdp-android:1.0.4'

You need to just add the dependency in your build.gradle file and you are done.
You need to specify like:
android:layout_height="@dimen/_10sdp"

Instead of usual:
android:layout_height="@dimen/10dp"

A: drawable:
For images, you have to manage different drawable folders as per screen resolution:
drawable-ldpi        //240x320
drawable-mdpi        //320x480
drawable-hdpi        //480x800
drawable-xhdpi       //720x1280
drawable-xxhdpi      //1080X1920
drawable-xxxhdpi     //1440X2560
drawable-tvdpi       // nexus 7 etc
drawable-xlarge-xhdpi //tablet like nexus 10

dimes:
For dimens, If you are using different static dimes as per your UI then you have to define them respected to their values... folders.
Values folder for different smart phones resolutions:
values-ldpi\dimens.xml
values-mdpi\dimens.xml
values-hdpi\dimens.xml
values-xhdpi\dimens.xml
values-xxhdpi\dimens.xml
values-xxxhdpi\dimens.xml

Note: If you are using sp/sip/dp/dip then these values will be adjusted based on the density of device.
e.g Suppose you had set 10sp for TextView in mdpi(320X480) resolution device. Then this same value will be auto adjusted for other resolutions.
mdpi(10sp==10px)
hdpi(15px)
xhdpi(20px)
xxhdpi(30px)
xxxhdpi(40px)

These are the some general usage values folder which are used to manage dimens related to their screen resolutions.
Different values folder for different screens:
values-sw720dp          10.1" tablet 1280x800 mdpi

values-sw600dp          7.0"  tablet 1024x600 mdpi

values-sw480dp          5.4"  480x854 mdpi
values-sw480dp          5.1"  480x800 mdpi

values-xxxhdpi                 1440X2560 xxxhdpi

values-xxhdpi                  1080X1920 xxhdpi

values-xhdpi            4.7"   1280x720 xhdpi
values-xhdpi            4.65"  720x1280 xhdpi

values-hdpi             4.0" 480x800 hdpi
values-hdpi             3.7" 480x854 hdpi

values-mdpi             3.2" 320x480 mdpi

values-ldpi             3.4" 240x432 ldpi
values-ldpi             3.3" 240x400 ldpi
values-ldpi             2.7" 240x320 ldpi

For knowledge in depth go with Support screen resolution

A: If you provide text size as sp and other dimensions as dp. Android will automatically adjust for different layouts based on density of devices. If you want to control the values, you can put values in dimens.xml in each of values folders. The values folder inside res for different density devices will be following :
values-ldpi\dimens.xml
values-mdpi\dimens.xml
values-hdpi\dimens.xml
values-xhdpi\dimens.xml
values-xxhdpi\dimens.xml
values-xxxhdpi\dimens.xml

A: Well that depends on your code

*

*Dont use Static values

*Try to use Wrap content

*Use Relative and Linear Layout Depends on your Requirement

*For Drawables Use every DPI Folder

Look at these Links
1)https://developer.android.com/training/multiscreen/screensizes.html
2)How to support different screen size in android
3)Supporting multiple screen size - Android

A: try this
https://developer.android.com/guide/topics/manifest/supports-screens-element.html
   <supports-screens android:resizeable=["true"| "false"]
                      android:smallScreens=["true" | "false"]
                      android:normalScreens=["true" | "false"]
                      android:largeScreens=["true" | "false"]
                      android:xlargeScreens=["true" | "false"]
                      android:anyDensity=["true" | "false"]
                      android:requiresSmallestWidthDp="integer"
                      android:compatibleWidthLimitDp="integer"
                      android:largestWidthLimitDp="integer"/>

A: There are three ways to do this :
1) Put your images and icon in different drawable folder including drawable-mdpi , drawable-hdpi , drawable-xhdpi , drawable-xxhdpi , drawable-xxxhdpi which will be access image from particular folder based on screen resolutions.  Don't apply fixed values everywhere for image. Fixed dimensions can be vary with different device and image will be looked stretch. So use  wrap_content
2) Set dimensions in dimens.xml for different values folder.
values-mdpi\dimens.xml
values-hdpi\dimens.xml
values-xhdpi\dimens.xml
values-xxhdpi\dimens.xml
values-xxxhdpi\dimens.xml

3) Use LinearLayout with proper using of android:layout_weight.

A: You can define multi dimen files, and add dimensions of each view according to screen size in there.
You can find detailed answer here
A set of six generalized densities:

*

*ldpi (low) ~120dpi

*mdpi (medium) ~160dpi

*hdpi (high) ~240dpi

*xhdpi    (extra-high) ~320dpi

*xxhdpi (extra-extra-high) ~480dpi

*xxxhdpi (extra-extra-extra-high) ~640dpi

Here is the official docs

A: If you want to use single layout and that should support all the screens like ldpi, , mdpi, hdpi, x-hdpi, xx-hdpi then you have to use weight in your layout that will handle screen size for all the screens.
Here're a few things:
If you want to divide the space equally between Views with the same weight – set 0dp as Views' width.
If you set View width to wrap_content – size of the Views will depend on weight and content inside each View.


text:
Q: Repeat a function in javascript for "n" times to download text in parts I would like to download text in parts and add it to a file "foobar" by repeating the download and write function from "data1" to "datan" where n is the last piece of the text.
This needs to be done as the text file is too big to be written directly into "foobar".
My current solution (snippet) is:
var data1 = "AAAAA";
var data2 = "BBBBB";

....

path += '/foobar';

....

downloadfunction(['echo "'+data1+'" >> '+path]);
downloadfunction(['echo "'+data2+'" >> '+path]);

The code works, but my main issue is with the last two lines. Is there a way to make the code more elegant by repeating "downloadfunction" from "data1" to datan"? "n" is a known, but large, number.

A: Put the data in an array, then you can loop and modify your function to take data and path as arguments:
var data = ['AAAAA', 'BBBBB', 'CCCCC'];
function download(data, path){
  save("echo " + data + " >> " + path);
}
...
path += '/foobar';
...
data.forEach(function(d){
  download(d, path);
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to replicate using joins and unions? I have an SQL script I want to replicate inside tableau using tableau's joins.
SQL script (script simplified just for explanation):
Select *
From transactions
Inner join data1

UNION

Select *
From transactions
Inner join data2

How do replicate this in tableau using joins n unions? (No tableau custom SQL please)

A: You can do manual unions or wildcard unions: Tableau Help
Depending on your data connection, some features of it may or may not be supported.
Same with joins, lots of ways to do it: Tableau Help
Make sure you're looking up the docs and searching for an answer before posting. These types of this are easy to find.


text:
Q: How to identify cause of errors in a Google Cloud Function I have a Google Cloud Function that is using FireStore and Google Sheets API.
In the invocations/seconds chart (see screenshot below) there are some errors but in the logs there are none.
I also tried to see if the quotas limits was exceeded, but there are so many metrics I couldn't understand how they work.
How can I know what are these errors?
And if it is because of quotas limits, is there a dashboard to easily know which one to increase?


text:
Q: Linq-select group from specific date Problem: Looking to select 1 row of each type
Table: EntryPrices
AttendingTypesId (int)
Name (nvarchar)
Price (int)
GroupId (int)
FromDate (DateTime) //yyyy-MM-dd
Sample:
Basic entry - 100 - 1 - 2012-08-01
Sponsor entry - 350 - 2 - 2012-08-01
Staff entry - 70 - 3 - 2012-08-01
Basic entry - 150 - 1 - 2012-10-01
Basic entry - 200 - 1 - 2012-12-01
As you can see, there are 3 basic entries. Each is valid depending on the date when they registered.
So if a person registers in mid september, he gets it for 100
mid November 150 and end December 200.
However i want to get the "valid" fee depending on todays date and i want to list that in a dropdown list.

So if i query this today (2012-aug-02) i should get the following
  rows:
Basic entry - 100 - 1 - 2012-08-01
Sponsor entry - 350 - 2 - 2012-08-01
Staff entry - 70 - 3 - 2012-08-01
If i query this (2012-dec-20) i should get the following rows:
Sponsor entry - 350 - 2 - 2012-08-01
Staff entry - 70 - 3 - 2012-08-01
Basic entry - 200 - 1 - 2012-12-01

How can i construct this in linq-to-sql?
My idea was something like:
var f = from data in mc.AttendingTypes
                    where DateTime.Now.CompareTo(data.FromDate) > 0
                    group data by new { data.GroupId, data.Name, data.Price, data.AttendingTypesId }
                    into newData
                    select new { newData.Key.Name, newData.Key.Price, newData.Key.AttendingTypesId };

A: I'd rather do something like that :
var today = DateTime.Now;

var result = mc.AttendingTypes
             .Where(at => at.FromDate <= today)
             .GroupBy(at => at.GroupId)
             .Select(g => g.OrderByDescending(m => m.FromDate).FirstOrDefault())
             .ToList();


text:
Q: How to set the SelectedItem when having databound ListPicker? I have a CartPage in WindowsPhone App. It shows Items in cart with their selected quantities.
I use a ListPicker to change the quantity. Now I have two questions,

*

*How to set the default Quantity in ListPicker (I am getting the Quantity of product from localstorage).

*When I select the quantity from ListPicker, How to save it into variable?
<Grid.Resources>

    <DataTemplate x:Name="PickerFullModeItemTemplate">
        <StackPanel Orientation="Horizontal" Margin="16 21 0 20" >
            <TextBlock Name="TextQuantity" Text="{Binding Quantity}" Margin="16 0 0 0" FontSize="43" FontFamily="{StaticResource PhoneFontFamilyLight}"/>

        </StackPanel>
    </DataTemplate>
</Grid.Resources>

<toolkit:ListPicker   toolkit:TiltEffect.IsTiltEnabled="True" Name="QuantityBox" Margin="264,91,142,36" Background="#FFA05E6A" FullModeItemTemplate="{StaticResource PickerFullModeItemTemplate}" BorderBrush="#FF8D7373" Foreground="#FF310836" FontSize="20" SelectionChanged="QuantityBox_SelectionChanged" MouseEnter="QuantityBox_MouseEnter" BorderThickness="1"/>

   public class ListQuantityClass
    {
        public int Quantity { get; set; }

    }

   List<ListQuantityClass> QuantitySource = new List<ListQuantityClass>();

                for (int i = 1; i <= 20; i++)
                {
                    QuantitySource.Add(new ListQuantityClass() { Quantity = i });
                }
                Custom.QuantityBox.ItemsSource = QuantitySource;

Both the below lines are giving me error:
                   Custom.QuantityBox.SelectedItem = cart.ProductQuantity;
                singletonInstance.QuantityChanged = int.Parse(QuantityBox.SelectedItem.ToString());

Actually Its obvious QuantityBox.SelectedItem WONT WORk because ListPicker is Databdound to QuantitySource  list.  What to use instead of QuantityBox.SelectedItem?

A: Since this is a two part question I will split it up into two sections.

*

*How to set the default Quantity in ListPicker (I am getting the
Quantity of product from localstorage).
You can set the SelectedItem only to an item in the ItemSource.  Using your example,
public partial class MainPage : PhoneApplicationPage
{

    List<ListQuantityClass> QuantitySource = new List<ListQuantityClass>();

    // Constructor
    public MainPage()
    {
        InitializeComponent();

        for (int i = 1; i <= 20; i++)
        {
            QuantitySource.Add(new ListQuantityClass() { Quantity = i });
        }
        my_listpicker.ItemsSource = QuantitySource;

        // setting default value to 3
        my_listpicker.SelectedItem = QuantitySource[2];

        // fancy search and set
        // my_SetSelectedItemBasedOnQuantity(my_listpicker, 4); // this will set it to 4

    }
}

*

*When I select the quantity from ListPicker, How to save it into
variable?
This is a much more involved problem.  You can loop through the Items in the ItemSource and check to see if it equals the SelectedItem and saved it that way.  But I much prefer if you use an event, like so.
    private void my_listpicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        try
        {
            var listpicker = sender as ListPicker;
            if (listpicker != null)
            {
                var selected_item = listpicker.SelectedItem as ListQuantityClass;
                int quantity = selected_item.Quantity;

                // TODO: Save the value in quantity to a file or send it to a webservice
            }
        }
        catch (Exception ex)
        {
            string error_message = ex.Message;
        }

    }

XAML
    <Grid.Resources>
        <DataTemplate x:Name="PickerItemTemplate">
            <TextBlock Text="{Binding Quantity}" FontSize="43"/>
        </DataTemplate>

        <DataTemplate x:Name="PickerFullModeItemTemplate">
            <TextBlock Text="{Binding Quantity}" Margin="16 0 0 0" FontSize="43"/>
        </DataTemplate>
    </Grid.Resources>

    <toolkit:ListPicker Header="my list picker demo"  x:Name="my_listpicker" ItemTemplate="{StaticResource PickerItemTemplate}" FullModeItemTemplate="{StaticResource PickerFullModeItemTemplate}" SelectionChanged="my_listpicker_SelectionChanged" MaxHeight="300"/>

Function to set SelectedItem based on Quantity
    private void my_SetSelectedItemBasedOnQuantity(ListPicker lp, int quantity)
    {
        // first search for quantity if a match is found set it
        try
        {

            foreach (ListQuantityClass lqc in lp.ItemsSource)
            {
                // match found
                if (lqc.Quantity == quantity)
                {
                    lp.SelectedItem = lqc;
                }
            }
        }
        catch (Exception ex)
        {
            string error = ex.Message;
        }
    }

A: I think you cannot use SelectedItem to set the selected item.You should set the SelectedIndex property instead. SelectedItem is used to get the selected item.Although the docs say that it can be used to set the selected item,I have never seen any practical implementation of the same.


text:
Q: R: Modifying an R Markdown Tutorial I am working with the R programming language.
I have the following 8 plots have been made beforehand and saved as HTML files in my working directory:
library(plotly)

Red_A <- data.frame(var1 = rnorm(100,100,100), var2 = rnorm(100,100,100)) %>%
  plot_ly(x = ~var1, y = ~var2, marker = list(color = "red")) %>%
  layout(title = 'Red A')

Red_B <- data.frame(var1 = rnorm(100,100,100), var2 = rnorm(100,100,100)) %>%
  plot_ly(x = ~var1, y = ~var2, marker = list(color = "red")) %>%
  layout(title = 'Red B')

Blue_A <- data.frame(var1 = rnorm(100,100,100), var2 = rnorm(100,100,100)) %>%
  plot_ly(x = ~var1, y = ~var2, marker = list(color = "blue")) %>%
  layout(title = 'Blue A')

Blue_B <- data.frame(var1 = rnorm(100,100,100), var2 = rnorm(100,100,100)) %>%
  plot_ly(x = ~var1, y = ~var2, marker = list(color = "red")) %>%
  layout(title = 'Blue B')

htmlwidgets::saveWidget(as_widget(Red_A), "Red_A.html")
htmlwidgets::saveWidget(as_widget(Red_B), "Red_B.html")
htmlwidgets::saveWidget(as_widget(Blue_A), "Blue_A.html")
htmlwidgets::saveWidget(as_widget(Blue_B), "Blue_B.html")

My Question: Using this template over here (https://testing-apps.shinyapps.io/flexdashboard-shiny-biclust/) - I would like to make a flexdashboard that allows the user to select (from two dropdown menus) a "color" and a "letter" - and then render one of the corresponding graphs (e.g. col = Red & letter = B -> "Red B").  I would then like to be able to save the final product itself as an HTML file. This would look something like this:

I tried to write the Rmarkdown Code for this problem by adapting the tutorial:
---
title: "Plotly Graph Selector"
output:
  flexdashboard::flex_dashboard:
  orientation: columns
vertical_layout: fill
runtime: shiny
---

Inputs {.sidebar}

 selectInput("Letter", label = h3("Letter"),
    choices = list("A" = 1, "B" = 2),
    selected = 1)

 selectInput("Color", label = h3("Color"),
    choices = list("Red" = 1, "Blue" = 2),
    selected = 1)

How can I continue with this?
Note
I know that it is possible to load HTML files into a dashboard that have been made beforehand, e.g.
# https://stackoverflow.com/questions/73467711/directly-loading-html-files-in-r
<object class="one" type="text/html" data="Red_A.html"></object>
<object class="one" type="text/html" data="Red_B.html"></object>
<object class="one" type="text/html" data="Blue_A.html"></object>
<object class="one" type="text/html" data="Blue_B.html"></object>

A: You could use iframe with renderUI to render the HTML files locally using addResourcePath with the location of your files. With paste0 and paste your could dynamically create the html files to select them. Here is some reproducible code:
---
title: "Plotly Graph Selector"
output:
  flexdashboard::flex_dashboard:
  orientation: columns
  vertical_layout: fill
  self_contained: false
runtime: shiny
---

```{r global, include=FALSE}
```

Inputs {.sidebar}
-----------------------------------------------------------------------

```{r}
 selectInput("Letter", label = h3("Letter"),
    choices = c("A", "B"),
    selected = "A")

 selectInput("Color", label = h3("Color"),
    choices = c("Red", "Blue"),
    selected = "Red")
```

Row
-----------------------------------------------------------------------

```{r}
addResourcePath("Downloads", "~/Downloads")
renderUI({
  color <- input$Color
  letter <- input$Letter
  tags$iframe(
    seamless="seamless",
    src=paste0("Downloads/", paste0(paste(color, letter, sep = "_"), ".html")),
    width = 600,
    height = 400)
})
```

Output:

If you want to remove the border around the plot, you could add frameBorder = "0" in your iframe call like this:
```{r}
addResourcePath("Downloads", "~/Downloads")
renderUI({
  color <- input$Color
  letter <- input$Letter
  tags$iframe(
    seamless="seamless",
    src=paste0("Downloads/", paste0(paste(color, letter, sep = "_"), ".html")),
    width = 600,
    height = 400,
    frameBorder = "0")
})
```

Output:

Using getwd() with basename like this:
```{r}
addResourcePath(basename(getwd()), getwd())
renderUI({
  color <- input$Color
  letter <- input$Letter
  tags$iframe(
    seamless="seamless",
    src=paste0(basename(getwd()), "/", paste0(paste(color, letter, sep = "_"), ".html")),
    width = 600,
    height = 400,
    frameBorder = "0")
})
```


text:
Q: $0$-th Galois cohomology with topological Milnor K-groups coefficients In local class field theory, the reciprocity map is constructed by using the isomorphism ${\rm Br}(F)\simeq \mathbb{Q/Z}$, where $F$ is a local field and ${\rm Br}(F)$ is its Brauer group. The cohomological cup product $$ H^{0}({\rm Gal}(F^{\rm sep}/F),(F^{\rm sep})^{\times})\times H^{2}({\rm Gal}(F^{\rm sep}/F),\mathbb{Z})\longrightarrow {\rm Br}(F)$$
provides reciprocity map $F^{\times}\simeq H^{0}({\rm Gal}(F^{\rm sep}/F),(F^{\rm sep})^{\times})\longrightarrow {\rm Hom}(H^{2}({\rm Gal}(F^{\rm sep}/F),\mathbb{Z}),{\rm Br}(F))\simeq {\rm Gal}(F^{\rm ab}/F)$.
For a finite field $\mathbb{F_{q}}$, we knew that $H^{2}({\rm Gal}(\mathbb{F_{q}^{\rm sep}/F_{q}}),\mathbb{Z})\simeq \mathbb{Q/Z}$. Recall that $\mathbb{Z}=K^{\rm top}_{0}(\mathbb{F}^{\rm sep}_{q})$ and $(F^{\rm sep})^{\times}\simeq K^{\rm top}_{1}(F^{\rm sep})$ where $F$ is a local field, we can predict that $H^{2}({\rm Gal}(F^{\rm sep}/F),K_{n}^{\rm top}(F^{\rm sep}))\simeq \mathbb{Q/Z}$ where $F$ is a $n$-dimensional local field.
I have not shown this claim yet, but If this is true, I conjecture that we may be able to show higher class field theory by using cup product
$$
H^{0}({\rm Gal}(F^{\rm sep}/F),K_{n}^{\rm top}(F^{\rm sep}))\times H^{2}({\rm Gal}(F^{\rm sep}/F),\mathbb{Z})\longrightarrow H^{2}({\rm Gal}(F^{\rm sep}/F),K_{n}^{\rm top}(F^{\rm sep})) \simeq \mathbb{Q/Z}.
$$
So in this case, all I need is an isomorphism $H^{0}({\rm Gal}(F^{\rm sep}/F),K_{n}^{\rm top}(F^{\rm sep}))\simeq K_{n}^{\rm top}(F)$. This is clear when $n=1$. Ivan Fesenko proved that for a prime degree cyclic extension $L/F$ of a $n$-dimensional local field $F$, the invariant part $K_{n}^{\rm top}(L)^{{\rm Gal}(L/F)}$ is isomorphic to $K_{n}^{\rm top}(F)$.
Question. A finite Galois extension $E/F$ of $n$-dimensional local fields, is $0$-th cohomology $H^{0}({\rm Gal}(E/F),K_{n}^{\rm top}(E))$ isomorphic to $K_{n}^{\rm top}(F)$?

A: This is almost certainly false.
Check out
Y. Koya - A generalization of class formation by using hypercohomology
(Invent Math 1990)
On the 3rd page (707 in the journal pagination) it is stated to be "well-known" that your question has a negative answer for ordinary Milnor K-groups. Koya only takes all the troubles in this article exactly because of the failure of this property.
I don't know a concrete counterexample off-hand, but I am sure that any counterexample can be translated to one for topological Milnor K-groups.
The idea of topological Milnor K-groups is that they throw away data which is arithmetically irrelevant anyway, so at least per yoga this should work.
I would suspect that $K_2^{top}(F)\rightarrow K_2^{top}(E)$ is not even injective for all finite extensions of $2$-local fields. For $K_2$ Milnor K-theory for a field is still the same as Quillen $K$-theory and the latter is known to fail Galois descent. Even if you use etale $K$-theory, this only gives you Galois descent on the level of the spectrum, not of an individual homotopy group.


text:
Q: Can not import theano after installation windows 10 I've still not been able to resolve this problem, after working on it for a week.
I'm thinking of giving up and just running theano on a virutal machine; there just doesn't seem to be any support out there for Windows 10!
Or am I wrong; is there an easy fix to this?
>>> import theano
Traceback (most recent call last):
  File "C:\Users\cturn\Anaconda3\lib\site-packages\theano\theano\gof\lazylinker_c.py", line 75, in <module>
    raise ImportError()
ImportError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\cturn\Anaconda3\lib\site-packages\theano\theano\gof\lazylinker_c.py", line 92, in <module>
    raise ImportError()
ImportError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\cturn\Anaconda3\lib\site-packages\theano\theano\gof\cmodule.py", line 1784, in _try_compile_tmp
    os.remove(exe_path + ".exe")
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\cturn\\AppData\\Local\\Temp\\try_march_3v6ffkv9.exe'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\cturn\Anaconda3\lib\site-packages\theano\theano\__init__.py", line 66, in <module>
    from theano.compile import (
  File "C:\Users\cturn\Anaconda3\lib\site-packages\theano\theano\compile\__init__.py", line 10, in <module>
    from theano.compile.function_module import *
  File "C:\Users\cturn\Anaconda3\lib\site-packages\theano\theano\compile\function_module.py", line 21, in <module>
    import theano.compile.mode
  File "C:\Users\cturn\Anaconda3\lib\site-packages\theano\theano\compile\mode.py", line 10, in <module>
    import theano.gof.vm
  File "C:\Users\cturn\Anaconda3\lib\site-packages\theano\theano\gof\vm.py", line 659, in <module>
    from . import lazylinker_c
  File "C:\Users\cturn\Anaconda3\lib\site-packages\theano\theano\gof\lazylinker_c.py", line 125, in <module>
    args = cmodule.GCC_compiler.compile_args()
  File "C:\Users\cturn\Anaconda3\lib\site-packages\theano\theano\gof\cmodule.py", line 2088, in compile_args
    default_compilation_result, default_execution_result = try_march_flag(GCC_compiler.march_flags)
  File "C:\Users\cturn\Anaconda3\lib\site-packages\theano\theano\gof\cmodule.py", line 1856, in try_march_flag
    flags=cflags, try_run=True)
  File "C:\Users\cturn\Anaconda3\lib\site-packages\theano\theano\gof\cmodule.py", line 2188, in try_compile_tmp
    comp_args)
  File "C:\Users\cturn\Anaconda3\lib\site-packages\theano\theano\gof\cmodule.py", line 1789, in _try_compile_tmp
    err += "\n" + str(e)
TypeError: can't concat bytes to str

Um, can't concat bytes to str? What does this mean?

A: The error you are experiencing appears to result from another sub-process utilizing the same resources as the script you are attempting to write. Although it sounds trivial, I would recommend making sure that you have admin privileges, or at least privileges to the desired resources, and/or restart your computer to kill the sub-process using that module. You could also look in the task manager and kill any/all other processes using python, but that might take longer.
(This may be the program using the "resource" try_march_3v6ffkv9.exe)


text:
Q: Remove any ssh-keygen commands from init scripts I'm running Ubuntu 14.04 64 bit server. I'm following this guide:
Secure Secure Shell
https://stribika.github.io/2015/01/04/secure-secure-shell.html
It includes the instruction:

remove any ssh-keygen commands from the init script.

How do I accomplish this on Ubuntu 14.04?

A: Ubuntu does not have ssh-keygen in init scripts. Ubuntu generates keys using dpkg-reconfigure triggers. It is not an automatic action.
dpkg-reconfigure openssh-server

The quoted line refers to Fedora/RHEL/CentOS, which is using sshd-keygen service. It creates keys before running the sshd service itself and is triggered by AUTOCREATE_SERVER_KEYS variable in /etc/sysconfig/sshd. Removing something from init scripts is not a good advice. More correct would be to set AUTOCREATE_SERVER_KEYS=no in above mentioned file.


text:
Q: Swift iOS : Insert data into related entities in CoreData I am trying to understand the concept in saving and retrieving records in a one-to-many relationship entities in CoreData. i have two tables Products (Master) and Sales (Details) hence (one-to-many) relationship with the relationship key being (sales).
Issue 1: when registering a sale to a product. i create an instance of the Sales entity, populate the values, then add it to the product.sales (relationship) and attempt a managedObjectContext save.
First Question: Do i also have to enter the instance of the Sales entity into the Sales Entity? or that will be updated automatically since there is a relationship?
Second Question: If i want to query all the sales that happened to date, do i query the Sales Entity? or do i query the relationship in the Products Entity?
Thanks for your help!
tab images

A:
First Question: Do i also have to enter the instance of the Sales entity into the Sales Entity? or that will be updated automatically since there is a relationship?

Something you might not realize here is that you are inherently saving the object by adding it to the managedObjectContext. As soon as you do something like
let sale = Sale(context: managedObjectContext)

followed by
managedObjectContext.save()

the context issues a save request to your persistent store (your actual SQL database).
Therefore your question whether you need to store the Sale as well is answered, it will always be stored upon saving the context.

Second Question: If i want to query all the sales that happened to date, do i query the Sales Entity? or do i query the relationship in the Products Entity?

That depends...
First let me give you a little tip/best practise:
Always make sure to set up an inverse relationship
In the Core Data Editor for your Product entity's relationships you can do something like this:

Your sales relationships look something like this:

A relationship is nothing more but a dependency between two entities, therefore there is always an inverse relationship between two entities, make sure you hook them up as shown above.
Why am I telling you this ? Remember I mentioned it depends what entity you do your query on ? This is where it matters.
For example, if you want the Sale for a given Product, you would query the product itself (by querying its relationship called sale):
let product = [A product instance from your Core Data store]
let sale = product.sale // returns the sale the product is associated to

If you want all the products from a given sale, you would query the Sale entity leveraging the products relationship:
let sale = [A sale from your Core Data store]
let products = sale.products // the products contained in the sale

You mentioned that you want all the sales to a given date:
It would not make any sense querying the Product entity for that because each product only has a relationship to the sale it is contained in.
So, to answer your question, you should query the Sale entity to retrieve all the sales to a given date.
I hope that helps, let me know if something is unclear.

A:     let manageObjectContext = appDelegateObj.managedObjectContext
    let entity =  NSEntityDescription.entityForName("", inManagedObjectContext:manageObjectContext)
let manageObj =  NSManagedObject(entity: entity!,insertIntoManagedObjectContext: manageObjectContext)
manageObj.setValue("Mark Developer", forKey: "AttributeName")
        do {
            try manageObjectContext.save()
        } catch let error as NSError {
            print("Could not save \(error), \(error.userInfo)")
        }

A: I will need to look into this a bit further, as I too am still getting my head around Core Data, but until I can find the time to do that I think what might work for you is this:
issue 1: to also enter the sale into the sales entity. I do not believe this will be done for you. Where relationships really become important is in deleting. You can specify what you want he delete rules to be, whether nullify, deny, cascade, or no action. Raywenderlich.com has an excellent tutorial series on Core Data that may help you.
issue 2: I think it depends on in which table (although in CoreData the term is ManagedObject) the data you are looking for is stored. It would make most sense to me to query the sales entity. You don't have to query the whole sales entity if you do not want to. You can specify search parameters.

A: As of swift 3 you don't have to create the properties of a class of an entity that you created in Core Data because Core Data does that for you. You do have to initialize those properties though. Same thing is true for relationships. For example in the case of the product Class (the parent) the relationship to sales(the child) is already instantiated for you. So you can access and set the Entity Sale by getting the instance of the relationship in the Product Class. There might be other ways of doing that but I think using extensions is pretty cool.
extension Product {
//You would call this constructor like that: Product(sale) from any //part of your program as long as you "import CoreData"
//If its 1 Sale then s 1-1 if it's more than 1 it's 1-many
    convenience init?(Sale or Sales) {
    let MOC = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext

    self.init(context: MOC)

    //case 1 when sale is 1-many
    let sale = Sale(context: MOC)

    //case 2 when sale is many-many(this can be an array of objects that you sent)

    let sale1 = Sale(context: MOC)
    let sale2 = Sale(context: MOC)
    let sale3 = Sale(context: MOC)

    //setting sale  object
     sale.property = ""

//Now is time to set the relationship with the object that you just set
    //case when is 1 - many
    self.sale = sale

    //case when is many - many
    self.sale?.adding(sale1)
    self.sale?.adding(sale2)
    self.sale?.adding(sale3)

}
Now your Product will be related to your sales....


text:
Q: How to keep the Bootstrap 4.5 accordion according at the top of the page even when it is full of items? I am having a problem and cannot find a way to solve it.
I am using the Bootstrap 4.5 accordion and in some of the cards, I have a lot of items(images).
The problem comes when you open a large collapse and open the next one, because the first collapse is so large, the next collapse closes the first one which seems like sending the user at the bottom of the accordion.
I would like to keep the user "view" always centered on the collapse that is being open. Any idea how to do this with Vanilla Javascript please?

        <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </button>

      images

        <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          Collapsible Group Item #2
        </button>

      images

        <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
          Collapsible Group Item #3
        </button>

      images

Thank you


text:
Q: How to get average value from SQL(Superset, SQLAlchemy under PostgreSQL) timestamp I tried to calculate the average timestamp and the query is successfully executed directly in postgresql, but when executed through superset(python's SQLAlchemy), an error occurs when converting an integer to a timestamp. How can I fix the error or do it in another way?
Query1:
select
    to_timestamp(
        avg(
            cast(
                extract(epoch from last_checked_at) as integer)
                )::integer
        ) as datetime
from
    the_best_table

Query1 postgresql result:

datetime

2022-02-06 03:15:19+00

Query1 superset(SQLAlchemy) result:

PostgreSQL Error postgresql error: '>=' not supported between
instances of 'datetime.timedelta' and 'int'
This may be triggered by: Issue 1002 - The database returned an
unexpected error. link

Also below you can see the results of the query to convert an integer to datetime. The problem is in this part of the code.
Query2:
select to_timestamp(1644117319) as datetime

Query2 postgresql result:

datetime

2022-02-06 03:15:19+00

Query2 superset(SQLAlchemy) result:

PostgreSQL Error postgresql error: '>=' not supported between
instances of 'datetime.timedelta' and 'int'
This may be triggered by: Issue 1002 - The database returned an
unexpected error. link

A: I was not able to reproduce the error.
Works fine.
Setup in Postgresql Database:
postgres=> create table the_best_table(last_checked_at timestamp);
CREATE TABLE
postgres=> insert into the_best_table values(now());
INSERT 0 1
postgres=> select
    to_timestamp(
        avg(
            cast(
                extract(epoch from last_checked_at) as integer)
                )::integer
        ) as datetime
from
    the_best_table;
        datetime
------------------------
 2022-02-07 04:54:06+09
(1 row)

The exact two queries run fine for me in SQLAlchemy:
>>> from sqlalchemy import create_engine
>>> engine = create_engine('postgresql+pg8000://<username>:<passwd>@192.xxx.xxx.123/postgres')
>>>  metadata.create_all(engine)
>>> with engine.connect() as con:
...     rs = con.execute('select to_timestamp(avg(cast(extract(epoch from last_checked_at) as integer))::integer ) as datetime from the_best_table;')
...     for row in rs:
...             print(row)
...
(datetime.datetime(2022, 2, 7, 4, 54, 6, tzinfo=datetime.timezone(datetime.timedelta(seconds=32400))),)
>>> with engine.connect() as con:
...     rs = con.execute('select to_timestamp(1644117319) as datetime;')
...     for row in rs:
...             print(row)
...
(datetime.datetime(2022, 2, 6, 12, 15, 19, tzinfo=datetime.timezone(datetime.timedelta(seconds=32400))),)


text:
Q: Error casting NSFetchRequest to NSFetchRequest where T is generic NSManagedObject I want to state that I am fairly new to Swift and I was exploring CoreData concepts. I tried to test with a ToDo list app which on welcome screen shows user created task categories and upon clicking on any category the user will see all the tasks in that group. I tried to create a generic class something like ToDoListViewController<T: NSManagedObject> and to implement functionality available for both view controllers(CategoryViewController, TaskViewController). In that class I created a function loadItems which takes a predicate as an argument and populates the page with items from a fetch request. So the code roughly looks like this:
class ToDoListViewController<T: NSManagedObject>: UITableViewController {

    func loadItems(predicate: NSPredicate? = nil) {
        let request: NSFetchRequest<T> = T.fetchRequest()

        if predicate != nil {
                request.predicate = predicate!
            }

        do {
            let items = try context.fetch(request)
            // Do something
        } catch {
            print("Error fetching items from context \(error)")
        }
    }
}

The issue is that when I try to compile I get error:

Cannot assign value of type NSFetchRequest<NSFetchRequestResult> to type NSFetchRequest<T>

when assigning request variable. But if I force cast NSFetchRequest<NSFetchRequestResult> to NSFetchRequest<T> like this:
let request: NSFetchRequest<T> = T.fetchRequest() as! NSFetchRequest<T>

everything works fine. Since The NSManagedObject documentation clearly states that it conforms to NSFetchRequestResult protocol, why do I have to force cast NSFetchRequest<NSFetchRequestResult> to NSFetchRequest<T>?

A: You have to cast the type because the generic type of NSFetchRequest – which is constrained to NSFetchRequestResult – can also be NSDictionary or NSNumber or NSManagedObjectID.
Rather than making a generic type more generic I recommend to use a protocol with associated types like described here


text:
Q: (MonoGame) Creating multiple instances of one object I want to make a Box object, so i can make multiple instances of it.
I need to make the box show texture and detect intersections etc.
How would I do this so I could make a method like this.
addBox(x, y);

Without having to add anything to Update() and other areas?
Thanks.

A: You will have to loop over all added boxes in update and draw. Example:
class Box
{
    vector2d Postion;
    public Box(vector2d _position)
    {
        Position = _position;
    }
}

class Boxes : list<Box>
{

    public void AddBox(Position)
    {
        this.add(new Box(Position));
    }

    public void Update()
    {
        foreach (Box b in this) {
            //b.position += b.velocity
        }
    }

    public void Draw()
    {
        foreach (Box b in this) {
            //draw b
        }
    }
}

Boxes.AddBox(vecor2d(200,300))


text:
Q: Jordan similar matrix I have matrix
$B = \begin{bmatrix}1 & 1 & -2 & 0\\2 & 1 & 0 & 2 \\ 1 & 0 & 1 & 1 \\ 0 & -1 & 2 & 1\end{bmatrix}$.
I found the characteristic polynomial $(1-x)^4$ and was able to get my Jordan Matrix $J = \begin{bmatrix}1 & 1 & 0 & 0\\0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 1 \\ 0 & 0 & 0 & 1\end{bmatrix}$. I need to find $P$ and $P^{-1}$ such that $B=PJP^{-1}$, but I got completely stuck after finding the eigenvectors.
Would really appreciate the help.
Thanks.

A: Note: It is important to learn to type problems using MathJax for many reasons, see this wonderful MathJax Basic Tutorial and Quick Reference.
We have the matrix:
$$B = \begin{bmatrix}1 & 1 & -2 & 0\\2 & 1 & 0 & 2 \\ 1 & 0 & 1 & 1 \\ 0 & -1 & 2 & 1\end{bmatrix}$$
The characteristic polynomial is:
$$(\lambda - 1)^4 = 0 \implies \lambda_{1,2,3,4} = 1$$
To find the four linearly independent eigenvectors, we try solving $[A - \lambda_i I]v_i = 0$, which yields only two independent eigenvectors as:
$$v_1 = \begin{bmatrix}-1\\ 0 \\ 0 \\1 \end{bmatrix}, v_3 = \begin{bmatrix}0\\ 2 \\ 1 \\0 \end{bmatrix}$$
Note, I could have called these any two eigenvectors I wanted, but I am matching your $J$, so chose them as shown above.
Now, we need to find two generalized eigenvectors, we set up and solve $[A-I]v_2 = v_1$. After RREF, we have:
$$v_2 = \begin{bmatrix}0\\-1\\ 0 \\ 0 \end{bmatrix}$$
We repeat this process using $[A-I]v_4 = v_3$, yielding:
$$v_4 = \begin{bmatrix}1\\0\\ 0 \\ 0 \end{bmatrix}$$
We can now write $P$ as a linear combination of those column eigenvectors, yielding:
$$P = [v_1 | v_2 | v_3 | v_4] = \begin{bmatrix}-1 &  0 &  0 &  1 \\ 0 & -1 & 2 & 0 \\ 0 &  0 & 1 & 0 \\ 1 &  0 & 0 &  0 \end{bmatrix}$$
It is a simple matter to find $P^{-1}$ and now we have:
$$J = P^{-1}AP = \begin{bmatrix}1 & 1 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 1 \\ 0 & 0 & 0 & 1\end{bmatrix}$$


text:
Q: How to traverse a hash in javascript? I am confused about hashes in Javascript.  I am playing with this simple script ...

try it

... but I keep getting the error, Uncaught SyntaxError: Unexpected identifier.
How can I traverse obj in the above javascript?

A:
The for each[...] statement is deprecated

Mozilla.
Removing each does the trick:
for (item in obj)
{
    console.log("item: "+item +", value: "+obj[item]);
}


text:
Q: Draw soft edge line in c# wpf I'm trying to draw a line in WPF (C#). I use Line to do it. Picture is presented below:

As you see the line has hard edges. How can I fix this problem?
Here is my code:
<Canvas RenderOptions.BitmapScalingMode="Unspecified" RenderOptions.EdgeMode="Aliased" >

    <Line RenderOptions.EdgeMode="Unspecified" X1="10" Y1="60" X2="570" Y2="570" Stroke="White" StrokeThickness="4" Width="341" Canvas.Left="203" Height="505" Canvas.Top="66" />

</Canvas>


text:
Q: about ProgressDialog and onResume() I have 2 pages and all I want is if user click button at the first page ,it will show ProgressDialog and go to second page , and if user click back button to resume to the first page it won't show ProgressDialog so I try
Btn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            dialog = ProgressDialog.show(MainActivity.this, "",
                    "Loading. Please wait...", true);
            dialog.setMax(2);

            Intent statPage = new Intent(MainActivity.this, Statistic.class);
            startActivity(statPage);
        }
    });
public void onResume() {
    if (dialog.isShowing()) {
        dialog.dismiss();
     }
    super.onResume();
}

but it forceclose
05-09 10:02:54.520: ERROR/AndroidRuntime(623): FATAL EXCEPTION: main

05-09 10:02:54.520: ERROR/AndroidRuntime(623): java.lang.RuntimeException: Unable to resume activity {android.test.cal/android.test.cal.MainActivity}: java.lang.NullPointerException
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3128)
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3143)
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2684)
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at android.os.Looper.loop(Looper.java:123)
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at android.app.ActivityThread.main(ActivityThread.java:4627)
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at java.lang.reflect.Method.invokeNative(Native Method)
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at java.lang.reflect.Method.invoke(Method.java:521)
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at dalvik.system.NativeStart.main(Native Method)
05-09 10:02:54.520: ERROR/AndroidRuntime(623): Caused by: java.lang.NullPointerException
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at android.test.cal.MainActivity.onResume(MainActivity.java:165)
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1149)
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at android.app.Activity.performResume(Activity.java:3823)
05-09 10:02:54.520: ERROR/AndroidRuntime(623):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3118)
please help

A: Please write progress dialog code in onPause instead of onResume . When You called another activity from your main activity at that time onPause is called and it dismiss the progress dialog.


text:
Q: Uploading an image from Photo Library or Camera to Firebase storage (Swift) I want to make a button in my iOS application, when the user clicks on it, he/she gets two options: either choose a photo from the Album or take a photo from the camera to the firebase database.
What's the structure I have to follow to make this possible? Uploading the image to the firebase database!

A: Make sure you have your first view controller in storyboard connected to a navigation Controller
 class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{

  var imagePicker : UIImagePickerController = UIImagePickerController()

  override func viewDidLoad() {
    super.viewDidLoad()

    imagePicker.delegate = self
   }

     //============================================================================================================================================================

//////
//
//PROFILE PICTURE FUNCTIONS
//
/////

@IBAction func addPictureBtnAction(sender: UIButton) {

    addPictureBtn.enabled = false

    let alertController : UIAlertController = UIAlertController(title: "Title", message: "Select Camera or Photo Library", preferredStyle: .ActionSheet)
    let cameraAction : UIAlertAction = UIAlertAction(title: "Camera", style: .Default, handler: {(cameraAction) in
        print("camera Selected...")

        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) == true {

            self.imagePicker.sourceType = .Camera
            self.present()

        }else{
            self.presentViewController(self.showAlert("Title", Message: "Camera is not available on this Device or accesibility has been revoked!"), animated: true, completion: nil)

        }

    })

    let libraryAction : UIAlertAction = UIAlertAction(title: "Photo Library", style: .Default, handler: {(libraryAction) in

        print("Photo library selected....")

        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) == true {

            self.imagePicker.sourceType = .PhotoLibrary
            self.present()

        }else{

           self.presentViewController(self.showAlert("Title", Message: "Photo Library is not available on this Device or accesibility has been revoked!"), animated: true, completion: nil)
        }
    })

    let cancelAction : UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel , handler: {(cancelActn) in
    print("Cancel action was pressed")
    })

    alertController.addAction(cameraAction)

    alertController.addAction(libraryAction)

    alertController.addAction(cancelAction)

    alertController.popoverPresentationController?.sourceView = view
    alertController.popoverPresentationController?.sourceRect = view.frame

    self.presentViewController(alertController, animated: true, completion: nil)

}

func present(){

        self.presentViewController(imagePicker, animated: true, completion: nil)

}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
     print("info of the pic reached :\(info) ")
     self.imagePicker.dismissViewControllerAnimated(true, completion: nil)

}

//Show Alert

func showAlert(Title : String!, Message : String!)  -> UIAlertController {

    let alertController : UIAlertController = UIAlertController(title: Title, message: Message, preferredStyle: .Alert)
    let okAction : UIAlertAction = UIAlertAction(title: "Ok", style: .Default) { (alert) in
        print("User pressed ok function")

    }

    alertController.addAction(okAction)
    alertController.popoverPresentationController?.sourceView = view
    alertController.popoverPresentationController?.sourceRect = view.frame

    return alertController
  }

}

Firebase Functions :-
func profilePictureUploading(infoOnThePicture : [String : AnyObject],completionBlock : (()->Void)) {

    if let referenceUrl = infoOnThePicture[UIImagePickerControllerReferenceURL] {
        print(referenceUrl)

        let assets = PHAsset.fetchAssetsWithALAssetURLs([referenceUrl as! NSURL], options: nil)
        print(assets)

        let asset = assets.firstObject
        print(asset)

        asset?.requestContentEditingInputWithOptions(nil, completionHandler: { (ContentEditingInput, infoOfThePicture)  in

            let imageFile = ContentEditingInput?.fullSizeImageURL
            print("imagefile : \(imageFile)")

            let filePath = FIRAuth.auth()!.currentUser!.uid +  "/\(Int(NSDate.timeIntervalSinceReferenceDate() * 1000))/\(imageFile!.lastPathComponent!)"

            print("filePath : \(filePath)")

                FIRControllerClass.storageRef.child("ProfilePictures").child(filePath).putFile(imageFile!, metadata: nil, completion: {

                    (metadata, error) in

                         if error != nil{

                            print("error in uploading image : \(error)")

                            self.delegate.firShowAlert("Error Uploading Your Profile Pic", Message: "Please check your network!")

                         }
                          else{

                                print("metadata in : \(metadata!)")

                                print(metadata?.downloadURL())

                                print("The pic has been uploaded")

                                print("download url : \(metadata?.downloadURL())")

                                self.uploadSuccess(metadata!, storagePath: filePath)

                                completionBlock()
                    }

            })
        })

    }else{

            print("No reference URL found!")

    }
}

//Saving the path in your core data to search through later when you retrieve your picture from DB

func uploadSuccess(metadata : FIRStorageMetadata , storagePath : String)
{

    print("upload succeded!")

    print(storagePath)

    NSUserDefaults.standardUserDefaults().setObject(storagePath, forKey: "storagePath.\((FIRAuth.auth()?.currentUser?.uid)!)")

    NSUserDefaults.standardUserDefaults().synchronize()

}

ps: - This repo link might be useful in future :) https://github.com/firebase/quickstart-ios (firebase official sample's)


text:
Q: Android Studio: errors in Dart are not showing on the screen I created a new project in Android Studio Bumble Bee. However when I enter some code that has errors in it the error is not showing up.
For example if I enter the following:
import './screens/authorization/auth_root_screen.dart';
When this directory or screen doesn't exist no error is shown.
Or even if I enter some code with a typo...
iiiiiiiiiiiiiiiiiiiiimport './screens/authorization/auth_root_screen.dart';
No error is shown in the IDE.
I guess I am missing a setting somewhere but I havent been able to find it. This always worked fine before I installed BumbleBee.
Any help would be gratefully received.
Thanks so much.

A: Hi thanks for looking at this. I have solved it myself. I'll post the solution here in case anyone has a similar question.
Do the following:

*

*At the bottom of the Android Studio IDE is a tab called: Dart Analysis. Click on it to open the tab.

*On the left hand side of the Dart Analysis screen that opens is a settings Icon. Click on this.

*On the settings screen, make sure that "Scope Analysis to the Current Package" is ticked on.
Here is a screen print:

A: Have you installed the Flutter extension for your Android Studio? You can find it in the Extensions section of your IDE.

A: Come do these things
First, run this  Flutter Doctor code in the terminal, be sure to check all the options
Specify the second SDK FLutter for Android Studio
Third, install the Dart and Flutter plugins


text:
Q: HTML/CSS - Align horizontaly div I'm trying to align div horizontally for far too long now.
The thing is, I set the width property but it doesn't seems to do anything.

.vtab
{
    border: 1px solid #ccc;
    background-color: #f1f1f1;
    padding: 14px 14px;
    width: 100%;
}

.vtab div
{
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    width: 100%;
}

.vtab div.left
{
    width: 25%;
    color:green;
}

.vtab div.middle
{
    width: 50%;
    color:yellow;
}

.vtab div.right
{
    width: 25%;
    color:red;
}

Hello, Jean-Michel

 00.00$

Does anybody have a clue ?
The divs keep stacking on the left of the container div.

A: you can achieve that using display:flex; and align-items:center;
.vtab {
    display: flex;
    align-items: center;
}

A:

.vtab
{
    border: 1px solid #ccc;
    background-color: #f1f1f1;
    padding: 14px 14px;
    display: table;
    width: 100%;
    box-sizing: border-box;
}

.vtab div
{
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}

.vtab div.left
{
    width: 25%;
    color:green;
}

.vtab div.middle
{
    width: 50%;
    color:yellow;
}

.vtab div.right
{
    width: 25%;
    color:red;
}

Hello, Jean-Michel

 00.00$


text:
Q: Single Query returning me 4 tables, How to get all of them back into dataset? How to fill multiple tables in a dataset.
I m using a query that returns me four tables.
At the frontend I am trying to fill all the four resultant table into dataset.
Here is my Query. Query is not complete. But it is just a refrence for my Ques
Select * from tblxyz compute sum(col1)

suppose this query returns more than one table, I want to fill all the tables into my dataset
I am filling result like this
con.open();
adp.fill(dset);
con.close();

Now when i checks this dataset. It shows me that it has four tables but only first table data is being displayed into it. rest 3 dont even have schema also.
What i need to do to get desired output

A: Use DataAdapter.TableMappings.
e.g. :
        DataSet ds = new DataSet();
        // setup DataSet if required

        SqlCommand cmd = new SqlCommand();
        // setup command

        SqlDataAdapter da = new SqlDataAdapter(cmd);

        da.TableMappings.Add("Table", "goofy");
        da.TableMappings.Add("Table1", "donald");
        da.TableMappings.Add("Table2", "daffy");
        da.TableMappings.Add("Table3", "foghorn");

        da.MissingSchemaAction =  MissingSchemaAction.AddWithKey;
        da.Fill(ds);

where "goofy" is the name of the DataTable you want your first result set to go into,
and "donald" is the second etc.

A: Check this links.
http://www.developer.com/article.php/3311341
http://vb.net-informations.com/dataset/dataset-multiple-tables-sqlserver.htm
Maybe the problem is that you need to return all your tables separetly, as different queries, for example, fill-ing the same DataSet in a loop.
Good Luck!


text:
Q: what are the things to know when embeding pdf on my website i want to embed a pdf file to my website. the pdf file is located beside the html file. i searched on this website and found many way to do it. but it's not working for me i tried many example and some of the examples are not working also. the pdf file is not showing. i have internet download manager installed and if i go to the demo website of how to show the pdf file. the IDM keeps on downloading it and now showing the content on the web page.
i have this sample code. can someone point out what am i doing wrong?
<!DOCTYPE html>

<embed src="1.pdf" width="500" height="375" type='application/pdf'>

code update:
im now using iframe

i even installed adobe pdf plugin for firefox in my browser. but when i reload the website im creating. it says "this pdf document might not be displayed correctly"
but when i check other's demo page for embeding pdf file online. i can see their pdf. but on my localhost i can't see mine? what am i doing wrong?

A: Try the following code instead.
<!DOCTYPE html>

Download


text:
Q: Interpreting Random Forest Model Results I would really appreciate your feedback with the interpretation of my RF model and how to generally evaluate the results.
57658 samples
   27 predictor
    2 classes: 'stayed', 'left'

No pre-processing
Resampling: Cross-Validated (10 fold)
Summary of sample sizes: 11531, 11531, 11532, 11532, 11532
Resampling results across tuning parameters:

  mtry  splitrule   ROC        Sens       Spec
   2    gini        0.6273579  0.9999011  0.0006250729
   2    extratrees  0.6246980  0.9999197  0.0005667791
  14    gini        0.5968382  0.9324610  0.1116113149
  14    extratrees  0.6192781  0.9740323  0.0523004026
  27    gini        0.5584677  0.7546156  0.2977507092
  27    extratrees  0.5589923  0.7635036  0.2905489827

Tuning parameter 'min.node.size' was held constant at a value of 1
ROC was used to select the optimal model using the largest value.
The final values used for the model were mtry = 2, splitrule = gini and min.node.size = 1.

After making several adjustments to the functional form of my Y variable, as well as the way I am splitting my data, I got the following results:
My ROC improved slightly, but interestingly my Sens & Spec changed drastically compared to my initial model.
35000 samples
   27 predictor
    2 classes: 'stayed', 'left'

No pre-processing
Resampling: Cross-Validated (10 fold)
Summary of sample sizes: 7000, 7000, 7000, 7000, 7000
Resampling results across tuning parameters:

  mtry  splitrule   ROC        Sens          Spec
   2    gini        0.6351733  0.0004618204  0.9998685
   2    extratrees  0.6287926  0.0000000000  0.9999899
  14    gini        0.6032979  0.1346653886  0.9170874
  14    extratrees  0.6235212  0.0753069696  0.9631711
  27    gini        0.5725621  0.3016414054  0.7575899
  27    extratrees  0.5716616  0.2998190728  0.7636219

Tuning parameter 'min.node.size' was held constant at a value of 1
ROC was used to select the optimal model using the largest value.
The final values used for the model were mtry = 2, splitrule = gini and min.node.size = 1.

This time, I split the data randomly, rather than by time and experimented with several mtry values using the following code:
```{r Cross Validation Part 1}
set.seed(1992) # setting a seed for replication purposes

folds <- createFolds(train_data$left_welfare, k = 5) # Partition the data into 5 equal folds

tune_mtry <- expand.grid(mtry = c(2,10,15,20), splitrule = c("variance", "extratrees"), min.node.size = c(1,5,10))

sapply(folds,length)

And got the following results:
Random Forest

84172 samples
   14 predictor
    2 classes: 'stayed', 'left'

No pre-processing
Resampling: Cross-Validated (10 fold)
Summary of sample sizes: 16834, 16834, 16834, 16835, 16835
Resampling results across tuning parameters:

  mtry  splitrule   ROC        Sens       Spec
   2    variance    0.5000000        NaN        NaN
   2    extratrees  0.7038724  0.3714761  0.8844723
   5    variance    0.5000000        NaN        NaN
   5    extratrees  0.7042525  0.3870192  0.8727755
   8    variance    0.5000000        NaN        NaN
   8    extratrees  0.7014818  0.4075797  0.8545012
  10    variance    0.5000000        NaN        NaN
  10    extratrees  0.6956536  0.4336180  0.8310368
  12    variance    0.5000000        NaN        NaN
  12    extratrees  0.6771292  0.4701687  0.7777730
  15    variance    0.5000000        NaN        NaN
  15    extratrees  0.5000000        NaN        NaN

Tuning parameter 'min.node.size' was held constant at a value of 1
ROC was used to select the optimal model using the largest value.
The final values used for the model were mtry = 5, splitrule = extratrees and min.node.size = 1.

A:
It looks like your random forest has almost no predictive power on the second class "left".
The best scores all have extremely high sensitivity and low specificity, which basically means that you classifier just classifies everything to class "stayed", which I imagine is the majority class. Unfortunately this is pretty bad, as it does not go too far from a naive classifier saying everything is from the first class.
Also, I can't quite understand if you only tried values for mtry 2,14 and 27, but in that case I would strongly suggest trying the whole 3-25 range (best values will most likely be somewhere in the middle).
Apart from that, since the performance looks to be rather bad (judging by the ROC) I suggest you work more on the feature engineering to extract some more information. Otherwise if you're OK with what you have or you think nothing more can be extracted, just tweak the probability threshold for the classification so that you have a sensitivity and specificity that mirror your requirement on the classes (you might care more about miscassifying "stayed" than "left" or vice versa, I dont know your problem).
Hope it helps!


text:
Q: Flatpickr onchange event set dateStr to +1 day var arrival = $('#datepicker');
    var departure = $('#datepicker1');

    arrival.flatpickr({
      dateFormat: "d-m-Y",
      disableMobile: true,
      locale: "de",
      minDate: "today",
      onChange: function(selectedDates, dateStr, instance) {
      departure.flatpickr({
        dateFormat: "d-m-Y",
        enableTime: false,
        minDate: dateStr,
      });
      departure.removeAttr('readonly');
      arrival.removeAttr('readonly');
    }
    });

    departure.flatpickr({
      dateFormat: "d-m-Y",
      disableMobile: true,
      locale: "de",
      minDate: "today",
      onChange: function(selectedDates, dateStr, instance) {
      arrival.flatpickr({
        dateFormat: "d-m-Y",
        enableTime: false,
        minDate: dateStr,
      });
      departure.removeAttr('readonly');
      arrival.removeAttr('readonly');
    }
    });

Hi everybody
I should create a booking form with Flatpickr and should get departure date +1 as arrival date but this is first time for me to as Flatpickr , if can someone help?
Thank you

A: I have found a solution using new Date(selectedDates).fp_incr(1) in combination with the Flatpickr config function onChange.
Example:

$(document).ready(function() {
  let arrival = $('#datepicker');
  let departure = $('#datepicker1');

  arrival.flatpickr({
    dateFormat: "d-m-Y",
    disableMobile: true,
    //locale: "de",
    minDate: "today",
    onChange: function(selectedDates, dateStr, instance) {
      //departure.set('maxDate', new Date(dateStr).fp_incr(5));
      departure.flatpickr({
        dateFormat: "d-m-Y",
        enableTime: false,
        minDate: new Date(selectedDates).fp_incr(1), // add 1 day
        //new Date(dateStr).fp_incr(1)
      });
      departure.removeAttr('readonly');
      arrival.removeAttr('readonly');
    }
  });

  departure.flatpickr({});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.11/flatpickr.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.11/flatpickr.min.js"></script>

<input id="datepicker" style="width:200px;">
<input id="datepicker1" style="width:200px;">


text:
Q: "Fill your boots" Expression I see in a movie this expression, but i'm not understand in the context scene.
In the scene the character gives to another a book. The first one says something that leaves the person who got the book angry. After that the character says "Fill your boots"

A: As per Cambridge, it is an instruction or offer to someone that they should take as much as they want of something. It might be something they have to pay for, or something being offered free. It might be food, physical goods of some other sort, or some non-tangible item. It might even be more abstract, such as services or help available from some source.


text:
Q: Is it possible to get the instance of the parent object inside a __proto__ function? // module

const obj = {
  geo: {}
}

const func = function(){}

func.__proto__.setGeo = function({lon, lat} = {}){
  return this.obj.geo = {lon, lat};
}

const parentObject = {
  func,
  obj
}

module.exports = parentObject

// controller

const parentObject = require('./module')

parentObject.func.setGeo({lon: 1, lat: 2})

Apparently this doesn't work because this inside setGeo is pointing to func.

A: Your question can be reduced to a scenario where you want to get access to the parent object of the function.
o = {
    f: function() {console.log(this)},
    g: 1
}

Now, the this keyword will point to the calling context always. However, the calling context can be varying in different scenarios.

*

*A plain function call.
o.f();

In this case, the calling context is the o object - which is what you are trying to access.

*Calling the function in a specific context
        o.f.call({name: 'new context'})

In this case, the calling context is {name: 'new context'}

*Using the function as a constructor
        obj = new o.f()

In this case the calling context is the brand new object you create
Now, most importantly, if the object o is the prototype of another object o1,  calling the above methods through o1 yields the same results.
Here are the three cases. Notice the console.

o = {
    f: function() {console.log(this)},
    g: 1
}

o.f();

o.f.call({name: 'new context'})

obj = new o.f()

o1 = Object.create(o);
o1.f();

A: Instead of using obj directly into parentObject You have to inherit the obj into func. Then your setGeo on proto will access obj using this instance. Check the changes below.
// module

const obj = {
  geo: {}
}

const func = function(){}

func.__proto__.obj = obj; // Inheriting parent

func.__proto__.setGeo = function({lon, lat} = {}){
  return this.obj.geo = {lon, lat};
}

const parentObject = {
  func
}

module.exports = parentObject

// controller

const parentObject = require('./module')

parentObject.func.setGeo({lon: 1, lat: 2})


text:
Q: Prohibitory sign showing on Mac startup While trying to install OS X El Capitan there was a brief power cut mid installation then the Mac tried to restart it first brought up the apple logo then brought up the prohibitory symbol. I can't get safe mode and I have done a hard restart all with the same thing can you help?

A: Sounds like the system files are corrupted, still try to boot into Recovery Mode by holding the Option key at startup until you see graphics of hard drives. Select Recovery with the arrow keys, then press Enter. Recovery mode will allow you to reinstall the OS.

A: Most likely a kernel panic, where vital system files are missing. Boot to Recovery Mode by holding Command + R at startup. If you have any backup drives (Time Machine), you can reinstall OS X using these drives, or fresh install. If your machine does not have a Recovery partition (older models), then you will need to replace the hard drive.


text:
Q: Multiple set-cookies in header rewrites each other curl If response header contains two Set-Cookie value as in the example:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNet-Version: 2.0.50727
Set-Cookie: ASP.NET_SessionId=***; path=/; HttpOnly
X-Powered-By: ASP.NET
Date: Sat, 12 Sep 2020 15:26:07 GMT
Content-Length: 14713
Set-Cookie: BIGipServerauto-ext-vla216-pool=***; path=/; Httponly

,then with parameters
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);

cUrl will write to file only the last, because of overwriting.
Is there a better way then manually read header and write to file via file_put_contents, to store multiple cookies for this case?

A: Curl does accept cookies from different Set-Cookie headers.
Take a look at the documentation:
https://curl.haxx.se/libcurl/c/CURLOPT_COOKIEFILE.html

CURLOPT_COOKIEFILE - file name to read cookies from

https://curl.haxx.se/libcurl/c/CURLOPT_COOKIEJAR.html

CURLOPT_COOKIEJAR - file name to store cookies to


text:
Q: Stuck in proof, Fermat's little theorem Question: if $d$ is a positive integer that is divisible by a prime $p \equiv 3 \bmod 4$, then $x^2 - dy^2 = -1$ has no solutions.
My attempts:
Try to show that if $p \equiv 3 \bmod 4$ is a prime then $x^2 \equiv -1 \bmod p$ has no solution. Proof, almost:
$x^2 \equiv -1 \bmod p \to (x^2)^{\frac{p-1}{2}} \equiv x^{p-1} \equiv (-1)^{\frac{p-1}{2}} \bmod p$

*

*if $\frac{p-1}{2}$ is even (which in fact is not even) then: $x^{p-1} \equiv 1 \bmod p$
$\to$ when $p \nmid x$ according to Fermat's little theorem it is True.
$\to$ when $p \mid x$ then $x^{p-1} \not \equiv 1 \equiv 0 \bmod p$, useless

*if $\frac{p-1}{2}$ is odd, which in fact $p$ is odd because: $p \equiv 3 \bmod 4$ then: $x^{p-1} \equiv -1 \bmod p$, Question: How to show this has no solution?
Assuming we proved Question is True, then:
$(x^2 - dy^2 = -1) \bmod p \to (x^2 = -1) \bmod p$
Any help will be appreciated.

A: You almost have it. Fermat's Little Theorem says that $x^{p-1}\equiv 1\pmod p$, so it can not be $-1$.
By the way, the proof that $p\equiv 1\pmod 4$ implies that $-1$ is a square mod $p$ is wrong. You have shown that $x\equiv -1\pmod p$ implies a true identity, but this proves nothing. This reasoning is wrong:

A implies B, and B is true. Therefore, A is true.


text:
Q: Is it possible to combine homebrews "brew list" with another command or argument to get the short description on all installed packages? I want the short description in combination with brew list or brew list --cask like in /api/formula.json on my installed brew packages.
Is this somehow possible?

A: brew desc $(brew list)
or formatted in columns with
brew desc --eval-all $(brew list) | awk 'gsub(/^([^:]*?)\s*:\s*/,"&=")' | column -s "=" -t
does the trick. thanks to carlocab:
https://github.com/Homebrew/brew/issues/14244#issuecomment-1346909437


text:
Q: How to add ASP.Net identity to Asp.Net Core when webApi template is selected? I have created a .NET Core project with WebApi template selected includes no authentication. I want to add ASP.NET identity in it for role based authorization. How can I achieve this?

A: Edit:
This answers the question but generally speaking I agree with the comment on the question above - JWT bearer tokens are the best fit for an API, it's best to understand that option before deciding on the best approach for your use case.
Original Answer
This will give you a bear bones webapi with aspnet core identity, first create your project (this assumes you've created a new folder and you're in it):
dotnet new webapi

Add aspnet core identity:
dotnet add package Microsoft.AspNetCore.Identity

Add some database provider to store your data:
dotnet add package Microsoft.EntityFrameworkCore.Sqlite

Now add a user type, the simplest version being:
public class ApplicationUser : IdentityUser
{
}

And a db context, here I'm setting up the connection string within the class but you'd probably want to use DbContextOptions instead:
public class IdentityContext : IdentityDbContext<ApplicationUser>
{
    protected override void OnConfiguring
        (DbContextOptionsBuilder optionsBuilder) =>
            optionsBuilder.UseSqlite("your connection string");
}

Then in your Startup.cs add the following marked lines:
public Startup(IConfiguration configuration)
{
    Configuration = configuration;

    //add this: simply creates db if it doesn't exist, no migrations
    using (var context = new IdentityContext())
    {
        context.Database.EnsureCreated();
    }
}

public void ConfigureServices(IServiceCollection services)
{
    //add this: register your db context
    services.AddDbContext<IdentityContext>();

    //and this: add identity and create the db
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<IdentityContext>();

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //add this
    app.UseAuthentication();

    app.UseMvc();
}

Note that by default the AddIdentity extension will set the default authentication scheme and add various cookies that you probably don't want in an API, the cut down alternative is as follows (to replace the above AddIdentity call in ConfigureServices):
services.AddIdentityCore<ApplicationUser>(options => { });
new IdentityBuilder(typeof(ApplicationUser), typeof(IdentityRole), services)
    .AddRoleManager<RoleManager<IdentityRole>>()
    .AddSignInManager<SignInManager<ApplicationUser>>()
    .AddEntityFrameworkStores<IdentityContext>();

This will give you the database side of things, you can then use UserManager and SignInManager to create and authenticate users, to get them use the DI system:
public class MyController : Controller
{
    private UserManager<ApplicationUser> _userManager = null;
    private SignInManager<ApplicationUser> _signInManager = null;

    public MyController(
        UserManager<ApplicationUser> userManager,
        SignInManager<ApplicationUser> signInManager)
    {
        _userManager = userManager;
        _signInManager = signInManager;
    }

    //etc...

And then use as follows:
var result = await _userManager.CreateAsync(
    new ApplicationUser()
    {
        UserName = "bob",
        Email = "bob@bob.com"
    }, "Test123!");
if (result.Succeeded)
    //do stuff...

And:
var user = await _userManager.FindByNameAsync("bob");
result = await _signInManager.CheckPasswordSignInAsync(user, "Test123!", false);
if (result.Succeeded)
    //do stuff...

Using CheckPasswordSignInAsync instead of PasswordSignInAsync will avoid the creation of a cookie if AddIdentity is used, if AddIdentityCore was also used above, then you must use CheckPasswordSignInAsync as PasswordSignInAsync will not work as an IAuthenticationSignInHandler will not have been setup.

A: There is nothing special the template is doing, all you need is the Microsoft.AspNet.Identity.Core NuGet package and the you should be able to follow from here:
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity


text:
Q: Serializing foreign languages using JSON.Net I want to serialize a .NET object to JSON which contains foreign language strings such as Chinese or Russian. When i do that (using the code below) in the resulting JSON it encodes those characters which are stored as strings as "?" instead of the requisite unicode char.
using Newtonsoft.Json;

var serialized = JsonConvert.SerializeObject(myObj, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, Formatting = Newtonsoft.Json.Formatting.Indented });

Is there a way to use the JSON.Net serializer with foreign languages?
E.g
אספירין (hebrew)
एस्पिरि (hindi)
阿司匹林 (chinese)
アセチルサリチル酸 (japanese)
Many Thanks!

A: It is not the serializer that is causing this issue; Json.Net handles foreign characters just fine.  More likely you are doing one of the following:

*

*Using an inappropriate encoding (or not setting the encoding) when writing the JSON to a file or stream.  You should probably be using Encoding.UTF8.

*Storing the JSON into a varchar column in your database rather than nvarchar.  varchar does not support unicode characters.

*Viewing the JSON with a viewer that does not support unicode, uses the wrong encoding and/or uses a font that does not have the full set of unicode character glyphs.  The Windows command prompt window seems to have this issue, for example.

To prove that the serializer is not the problem, try compiling and running the following example program.  It will create two different output files from the same JSON, one using UTF-8 encoding and the other using the default encoding.  Open each file using Notepad.  The "default" file will have the foreign characters as ? characters. In the UTF-8 encoded file, you should see all the characters are intact.  (If you still don't see them, try changing the Notepad font to "Arial Unicode MS".)
You can also see the foreign characters are correct in the JSON using the Visual Studio debugger; just put a breakpoint after the line where it serializes the JSON and examine the json variable.
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

class Program
{
    static void Main(string[] args)
    {
        List<Foo> foos = new List<Foo>
        {
            new Foo { Language = "Hebrew", Sample = "אספירין" },
            new Foo { Language = "Hindi", Sample = "एस्पिरि" },
            new Foo { Language = "Chinese", Sample = "阿司匹林" },
            new Foo { Language = "Japanese", Sample = "アセチルサリチル酸" },
        };

        var json = JsonConvert.SerializeObject(foos, Formatting.Indented);

        File.WriteAllText("utf8.json", json, Encoding.UTF8);
        File.WriteAllText("default.json", json, Encoding.Default);
    }
}

class Foo
{
    public string Language { get; set; }
    public string Sample { get; set; }
}

A: I have been using an Arabic text and I find the solution here
In this section Serialize all characters
options = new JsonSerializerOptions
{
    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
    WriteIndented = true
};
jsonString = JsonSerializer.Serialize(weatherForecast, options);


text:
Q: django url configuration not able to redirect to specific url when calling urls of one function through urls of another application I am working with two apps here. The user app create, delete, update, login and register a user. Whereas network app simply check if the session is set through @login_required decorator. My base template is located on the root. I have a login functionality from which I want to call login.
I am not able to access user.urls from network.urls
any help would be appreciated.
network.urls
from django.conf.urls import url, include
from . import views
from user import urls as user_urls
from user import views as user_views
#from django.contrib import admin

urlpatterns = [
    url(r'^$', views.IndexView.as_view()),
    url(r'^user/login/', include('user.urls', namespace='user')),
    url(r'^captcha', include('captcha.urls')),
    #url(r'^admin/', admin.site.urls),
]

user.urls
from django.conf.urls import url, include
from . import views

urlpatterns = [
    url(r'^login/', views.LoginView.as_view(), name='login'),
    url(r'^$', views.IndexView.as_view(), name="index"),
    #url(r'^register', views.RegisterView.as_view(), name='register')
]

now I want to call user login from the base template, which is

GS

                <form class="form-inline">
                    {%csrf_token%}
                    <input type="text" name="search" placeholder="Search" class="form-control">
                    <input type="submit" class="btn btn-info" value="Search">
                </form>

                     Log in

                 Sign Up

Home

Page 1

Page 2

Page 3

{%block left_nav %}{%endblock%}

{%block container%}{%endblock%}

{%block advertisement%}{%endblock%}


text:
Q: HLSL: How to transform vertex to screen space just like the rasterizer, but with subpixel accuracy? I want to draw a point-list using vertex- and pixelshader. Each point's rendered color should represent its subpixel accurate screen-space coordinate (outputting to R32G32_FLOAT texture).
I do the following in my VS:
struct VSOutput
{
    float4 position : SV_Position;
    float2 screenSpacePosition : COLOR;
};

VSOutput VS(uint index : SV_VertexID)
{
    float3 pointPos = inPointPositions[index];
    VSOutput output;
    output.position = mul(transform, float4(pointPos, 1));
    output.screenSpacePosition = (float2(+1, -1) * output.position.xy / output.position.w * 0.5f + 0.5f) * float2(width, height);
    return output;
}

In my PS I'd normally just use the screenSpacePosition field as my final target color, but since I experienced some issues I changed it to verify that the computed screenSpacePosition coincides with the actual pixel-position used for rasterization (to debug the issue). It will output a WHITE color if the computed screenSpacePosition matches the rasterized position, and RED otherwise.
float4 PS(VSOutput input) : SV_Target
{
    return all(floor(output.screenSpacePosition) == floor(input.position.xy)) ? float4(1, 1, 1, 1) : float4(1, 0, 0, 1);
}

Now allmost all pixels are white as is to be expected, but there is occasional red noise on top. I strongly assume the reason for this is that the rasterizer uses an internal 16.8 fixed-point format for mapping to actual pixels, such that mappings don't agreee 100% between that fixed-point format and my float transformation.
Is there any way to fix this issue ?

A: Use ceil() instead of floor().
Consider the point rasterization rule,
Point Rasterization Rules
Say if a screen space pos outputed by VS happens to be exactly at integer pixel coord (n, m), the pixel centered at (n - 0.5, m - .5) will be rasterized and receives the SV_POSITION (n - 0.5, m - 0.5) in PS, while the manually calculated pos that passed to PS still be (n, m), which will return different value after applying floor()


text:
Q: Embedded associated prime $\underline{\textbf{Embedded associated prime}}$
I am reading the book "Joins and Intersections". In the proof of Rees theorem I have some doubt.
Let $\mathbf M$ be a finitely generated $\mathbf A$-module and $\mathbf N$ be $A$-submodule of $\mathbf M$ generated by all such $m\in{\mathbf M}$  such that dim ${{\mathbf A}m}<{dim{\mathbf M}}$ .
Why $\frac{\mathbf M}{\mathbf N}$ does not have any embedded prime?

A: I think roughly speaking this is the reason: show for every associated prime $\mathfrak{p}$ of $M/N$, $\dim A/\mathfrak{p}=\dim M$. Then $M/N$ cannot have an embedded prime. To show the claim, suppose $\mathfrak{p}$ is an associated prime of $M/N$. Then this means $\mathfrak{p}$ is the annihilator of some element $x\in M/N$. Since $x\not\in N$, we have $\dim Ax=\dim M$. But $\dim Ax =\dim A/\mathrm{Ann}\; x=\dim A/\mathfrak{p}$.


text:
Q: Null properties are missing when returned by ActionResult My controller action method looks like this:
public virtual async Task<ActionResult<Customer>> GetCustomerAddress(int CustomerId)
{
    customer =  await scope.ServiceProvider
                           .GetRequiredService<CustomerClient>()
                           .GetCustomerAddressAsyn(CustomerId);

    Ok(Customer);
}

The customer model object is as follows:
public class Customer
{
     public int CustomerID { get; set; }
     public string CustomerName { get; set; }
     public string CustomerLastName { get; set; }
     public string CustomerMiddleName { get; set; }
}

The CustomerMiddleName value is null when stored at this variable.
Customer customer =  await scope.ServiceProvider
                                .GetRequiredService<CustomerClient>()
                                .GetCustomerAddressAsyn(CustomerId);

but when doing this
return Ok(Customer);

the CustomerMiddleName property itself is missing from the Json response on the postman test. Unable to comprehend why this happening. Null value properties are missing here when returned by OkObjectResult


text:
Q: ARM assembly recursive sum of 1..n So I've had the following task that needs to be written in ARM Assembly

Please test the subroutine by passing the value of n equals 5. The result
  should equal 15. If n equals 3, the result is 6.

I was given the corresponding Java code:
  int sum (int n)
   {
        int result;
        if (n == 1)
            return 1;
        result = Sum (n‐1) + n;
        return result;
    }

And I have written the following code in ARM Assembly
        NAME main
        PUBLIC main
        SECTION .text: CODE (2)
        THUMB

main
        LDR R4, =0x005          ; Value n
        BL SUM

STOP    B STOP

SUM
        MOV R1, #0x01
        PUSH {R1, LR}
        ADD R5, R5, R4          ; R5 = result
        CMP R5, #1              ; Compare result to 1
        BEQ ADD1

ADD0
        SUB R4, R4, #1          ; Value n - 1
        CMP R4, #0              ; Compare n to 0
        BEQ ADD1
        BL SUM

ADD1
        POP {R4, LR}
        BX LR                   ; Branch and exchange instruction set

        END

The code is running fine but I want to know if there could be any slight improvements/shortcuts.
I am also a little unsure about the comments but I believe what I have written is correct.


text:
Q: A question regarding series. So i have a question regarding series and how test works. Given we have the series
$\sum\limits_{n=1}^\infty {\dfrac{n}{e^n}}$
Doing the Divergence test on this series, i would interpet that as
$\lim_{n \to \infty}$${\dfrac{n}{e^n}}$=${\dfrac{\infty}{\infty}}$
And i really dont know what to make of this. For now i have just interpeted it as it meaning the divergence test is inconclusive and some other test is needed. Am i going wrong somewhere in that understanding?

A: Given series is $\,\color{blue}{\displaystyle{{S}_{\infty}=\sum^{\infty}_{n=1}{x}_{n}}}\,$  , where $\,\color{green}{{x}_{n}=\dfrac{n}{{e}^{n}}}$
To test whether it is convergent or divergent, let us perform D'Alembert's Ratio test.

Let $\,\color{magenta}{\sum{x}_{n}}\,$ be a series of positive real numbers and $\,\color{magenta}{\displaystyle\lim_{n\to\infty}\dfrac{{x}_{n+1}}{{x}_{n}}=l}\,$
Then $\,(i)\color{magenta}{\sum{x}_{n}}\,$ is convergent if $\,\color{magenta}{l<1}\,,\,\,\,\,(ii)\color{magenta}{\sum{x}_{n}}\,$ is divergent if $\,\color{magenta}{l>1}$

So, let us perform the ratio test.
$\,\displaystyle\lim_{n\to\infty}\dfrac{{x}_{n+1}}{{x}_{n}}\,$
$\,\displaystyle=\lim_{n\to\infty}\dfrac{\dfrac{n+1}{{e}^{n+1}}}{\dfrac{n}{{e}{n}}}\,$
$\,\displaystyle=\lim_{n\to\infty}\dfrac{(n+1){e}^{n}}{n\,{e}^{n+1}}\,$
$\,\displaystyle=\lim_{n\to\infty}\dfrac{n+1}{n\,e}\,$
$\,\displaystyle=\dfrac{1}{e}\lim_{n\to\infty}\dfrac{n+1}{n}\,$
$\,\displaystyle=\dfrac{1}{e}\lim_{n\to\infty}\left(1+\dfrac{1}{n}\right)\,$
$\,\displaystyle=\dfrac{1}{e}\,$
So, the limit $\,\displaystyle\color{magenta}{\lim_{n\to\infty}\dfrac{{x}_{n+1}}{{x}_{n}}}\,<1\,$
Hence, according to the ratio test, the given series is convergent

A: From the power series
for $e^x$,
$e^n > n^k/k!$
for all $k$.
Setting $k=3$,
$e^n>n^3/6$
so $n/e^n < 6/n^2$
and the sum of this converges.


text:
Q: Can NetCDF be returned with WCS 1.0.0 using GeoServer I am able to get NetCDF files to return using this request:
http://localhost:8080/geoserver/wcs?request=GetCoverage&service=WCS&version=2.0.1&coverageId=it.geosolutions__rhum&Format=application/x-netcdf&subset=http://www.opengis.net/def/axis/OGC/0/Long(5,20)&subset=http://www.opengis.net/def/axis/OGC/0/Lat(40,50)
However, I'd like to use WCS 1.0.0 instead. When I modify the request to the following:
http://localhost:8080/geoserver/wcs?request=GetCoverage&service=WCS&version=1.0.0&coverage=it.geosolutions:rhum&Format=NetCDF&bbox=5,40,20,50&width=500&height=500&elevation=2&CRS=EPSG:4326
I get this error:
java.lang.IllegalArgumentException: NetCDF encoding only supports granuleStack coverages
NetCDF encoding only supports granuleStack coverages

I'm not sure what this means and if it's just a limitation of WCS 1.0.0.
Can I get NetCDF files to return using WCS 1.0.0 with the NetCDF plugins?

A: Only WCS 2.0 can build the granule stack structure needed to encode an ND raster dataset.


text:
Q: Jenkins failed to create process with tox and py.test I'm running my python setup.py sdist at Jenkins shell
Tox is running and installs all dependencies but while getting to the py.test command if says():
py27 runtests: commands[0] | py.test --junit-xml=C:\my_folder\unit_test_results.xml
failed to create process.

my ini file looks like that:
[tox]
envlist = py27, docs

[testenv]
deps=pytest
commands=py.test --junit-xml={toxinidir}\unit_test_results.xml

[testenv:docs]
basepython=python
changedir=docs\source
deps=
    sphinx
    sphinx_epytext
commands=sphinx-build -W -b html -d {envtmpdir}\doctrees . {envtmpdir}\html

Any idea why it fails to create process?


text:
Q: How to export a meshless SVG? This problem does not exist in 13.2.1 anymore

I often need to export some svg with mma, but RegionPlot's diagrams will have some extra mesh after exporting SVG:
p = RegionPlot[x^2 + y^3 < 2, {x, -2, 2}, {y, -2, 2}];
Export["p.svg", p]

Not only does this make SVG very ugly, but it can lead to very large files. And is this a bug of MMA?

A: p = RegionPlot[x^2 + y^3 < 2, {x, -2, 2}, {y, -2, 2},
   PlotStyle -> {EdgeForm[]}];
Export["p.svg", p]

pp= RegionPlot[x^2 + y^3 < 2, {x, -2, 2}, {y, -2, 2},
   PlotStyle -> {EdgeForm[], FaceForm[Green]},
   BoundaryStyle -> None];
Export["pp.svg", pp]

ppp = RegionPlot[x^2 + y^3 < 2, {x, -2, 2}, {y, -2, 2},
   PlotStyle -> {EdgeForm[], FaceForm[None]}, BoundaryStyle -> Red];
Export["ppp.svg", ppp]

A: This code almost solves my problem, which will export very small and meshless SVG file, but the background is not transparent. I don't know how to export an SVG file with the transparent background..
p = RegionPlot[x^2 + y^3 < 2, {x, -2, 2}, {y, -2, 2}];
BoundaryDiscretizeGraphics[p, Frame -> True];
Export["p.svg", %,Background -> None]


text:
Q: Why can't I return a reference to a unique_ptr of a derived class created with a template? I have a compile time "plugin" system based on this link,  which I want to retain ownership of the plugins, which are literally unique - there should only be one instance of each type.
There is a registrar class which owns a plugin type, and owns a unique_ptr to the plugin.
I want to return a reference to the plugin whenever one is requested, to keep ownership clear.
More complete code below. Note the #define for registration in the header of a plugin.
Also, I'm renaming from Renderer in my code to Plugin here so if I've missed any that's what the random Render references are/were.
Factory class:
class PluginFactory
    {
    public:
        // Instance of Factory
        static PluginFactory& Instance();
        void Register(IPluginRegistrar *Registrar, std::string name);

        IPlugin& GetPlugin(std::string name);

    private:
        std::unordered_map<std::string, IPluginRegistrar *>_registry;
        // private constructor, prevent copying
        PluginFactory() : _registry() {};
        PluginFactory(PluginFactoryconst&) = delete;
        void operator=(PluginFactoryconst&) = delete;
    };

    PluginFactory& PluginFactory::Instance()
    {
        static PluginFactoryinstance;
        return instance;
    }
    void PluginFactory::Register(IPluginRegistrar *registrar, std::string name)
    {
        if (_registry.count(name))
            std::cout << name << " is already registered!\n";
        else
        {
            std::cout << "Registering " << name << "\n";
            _registry[name] = registrar;
        }
    }
    IPlugin& PluginFactory::GetPlugin(std::string name)
    {
        IPluginRegistrar* registrar = _registry.at(name);
        return registrar->GetPlugin();
    }
    #define REGISTER_PLUGIN(CLASSNAME) \
    namespace { \
    static MyNamespace::PluginRegistrar<CLASSNAME>\
    _registrar( #CLASSNAME ); \
    };

Plugin Base
    class IPlugin
    {
    public:
        IPlugin() { std::cout << "Constructing IPlugin class\n";  }
        virtual void DoThing(){ std::cout << "Here's the thing from an IPlugin!\n"; };

    };

Plugin Derived
    class TestPlugin : public IPlugin
    {
    public:
        TestPlugin ();
        virtual void DoThing() override;
    };
    REGISTER_RENDERER(TestPlugin)

    TestPlugin::TestPlugin () : IPlugin()
    {
        std::cout << "Constructing TestPlugin class\n";
    }

    void TestPlugin::DoThing()
    {
        std::cout << "Here's the thing from a TestPlugin!\n";
    }

Registrar
 class IPluginRegistrar
    {
    public:
        virtual IPlugin& GetPlugin() = 0;

    };

 template <class T>
    class PluginRegistrar: public IPluginRegistrar
    {
    public:
        PluginRegistrar(std::string classname); // constructor registers plugin with a plugin factory
        IPlugin& GetPlugin(); // GetPlugin is called by the factory
    private:
        std::string _name;
        std::unique_ptr<IPlugin> _ptr;
    };

    template <class T>
    PluginRegistrar<T>::PluginRegistrar(std::string classname) : _name(classname)
    {
        PluginFactory& factory = PluginFactory::Instance();
        factory.Register(this, classname);
    }

template <class T>
    IPlugin &
    PluginRegistrar<T>::GetPlugin()
    {
        if (!_ptr)
            _ptr = std::make_unique<T>();
        return *_ptr;
    }

Code in use:
    auto& factory = PluginFactory::Instance();
    auto plugin= factory.GetPlugin("TestPlugin");
    => outputs confirm derived class constructed
    plugin.DoThing();
    => output of IPlugin.DoThing(), not TestPlugin.DoThing()

The original version of this code returned a new unique_ptr<IPlugin> each time GetPlugin() was called, and worked great. However now I've switched return type to an IPlugin &, when I call a virtual function on the result, the base class function is called, not the derived.

A: auto plugin= factory.GetPlugin("TestPlugin");

This will copy the result into a new object, which will be a IPlugin (the original derived type will be sliced). You want to use a reference instead:
auto& plugin= factory.GetPlugin("TestPlugin");

You might want to make IPlugin::DoThing() a pure virtual function (i.e. virtual void DoThing() = 0) which will

*

*Force derived classes to implement it

*Prevent you from having an object of type IPlugin, i.e. make your original code fail to compile


text:
Q: Application crashes when passing array of animations I thought it would be a brilliant idea to pass an array of animations to an internal function that runs all animations one after each other, so I wouldn't need to nest animations within each other and each others' completionBlock. So I wrote a little method to test this out and, guess what, it crashes like hell. But I don't understand why. This is my method:
+(void) internalAnimateWithArrayOfAnimationBlocks:(NSArray*) animationBlocks withIndex:(NSUInteger) index withCompletionAnimation:(void (^)(BOOL finished)) completionBlock {
  __block NSArray* newAnims = animationBlocks;
  __block NSUInteger theIndex = index;
  if (index < [newAnims count] - 1) {
    [UIView animateWithDuration:0.1 animations:^{
      void (^animBlock) (void) = [newAnims objectAtIndex:theIndex];
      animBlock();
      theIndex++;
      [RMAnimater internalAnimateWithArrayOfAnimationBlocks:newAnims withIndex:theIndex withCompletionAnimation:completionBlock];
    }];
  }
  else {
    [UIView animateWithDuration:0.1 animations:^{
      void (^animBlock) (void) = [newAnims objectAtIndex:theIndex];
      animBlock();
      theIndex++;
    } completion:completionBlock];
  }
}

+(void) animateWithArrayOfAnimationBlocks:(NSArray*) animationBlocks withCompletionAnimation:(void (^)(BOOL finished)) completionBlock {
  [RMAnimater internalAnimateWithArrayOfAnimationBlocks:animationBlocks withIndex:0 withCompletionAnimation:completionBlock];
}

I pass this animations like this:
NSMutableArray* animations = [NSMutableArray array];
[animations addObject:^{
  CGRect frame = theTile.textField.frame;
  frame.origin.x -= 10;
  theTile.textField.frame = frame;
}];

When I debug it, it kindly goes through all my animations, calls the final animation with its completion block and then crashes deadly. What am I doing wrong here?

A: The problem is, call -addObject: of NSMutableArray will retain but not copy the added object. When you declare a block, it's in stack, which will be destroy in the end of the scope. To make it into heap, you must Block_copy or send copy message to the block. So to fix your problem, you must:
NSMutableArray* animations = [NSMutableArray array];
void (^animBlock)(void) = Block_copy(^{
  CGRect frame = theTile.textField.frame;
  frame.origin.x -= 10;
  theTile.textField.frame = frame;
});
[animations addObject:animBlock];
Block_release(animBlock);


text:
Q: pass div class value to a variable in php Here i want to pass div class value to the variable so far i had done like this.
Here is my div

 and here i have value getting 20 now i want to store that value in to a variable and use it in a PHP function.
my PHP code looks like this...
 <?php $p_amount=$this->db->get_where('tbl_abc',array('abc_id'=>`here i want that value`))->row();?>

i got value in div by using jquery see my code

first i want to store that div value in to a variable so i can use it in PHP please help me to solve.

A: You can get data through JavaScript.
Function printDiv(divName) {
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;

     document.body.innerHTML = originalContents;

}
Or you can use AJAX functionality.