text:
Q: Cannot read property 'text' of undefined - Vue.js Todat I am stuck with looping in Vue. I know the basics of loops and been looking around if these question are asked before. But none of them solved my problem.
Code loop:

       {{ todo.text }}

Code object:
todos: [
   { text: "Subscibe to Renatello.com newsletter", done: true },
   { text: "Learn Vue", done: false },
   { text: "Build awesome projects", done: false }
]

The error I get is: Cannot read property 'text' of undefined
Hopefully there is someone out here which can help me out.
SOLUTION:
The :v-for: as v-for="(todo, index) in todos" with an :key="index"
Thanks in advance.

A: Remove the colon before the v-for.

A: I'm not strong on Vue, but I don't think you want the : on :v-for, just v-for:

const app = new Vue({
    el: '#app',
    data: {
        todos: [
            {
                text: "Subscibe to Renatello.com newsletter",
                done: true
            },
            {
                text: "Learn Vue",
                done: false
            },
            {
                text: "Build awesome projects",
                done: false
            }
        ]
    }
})

setTimeout(() => {
    app.todos = [
        ...app.todos,
        {
            text: "more",
            done: false
        }
    ];
}, 1000);

            {{ todo.text }}


text:
Q: Pandas: concatenating conditioned on unique values I am concatenating two Pandas dataframes as below.
part1 = pd.DataFrame({'id'    :[100,200,300,400,500],
                   'amount': np.random.randn(5)
                    })

part2 = pd.DataFrame({'id'    :[700,100,800,500,300],
                   'amount': np.random.randn(5)
                    })

concatenated = pd.concat([part1, part2], axis=0)
     amount   id
0 -0.458653  100
1  2.172348  200
2  0.072494  300
3 -0.253939  400
4 -0.061866  500
0 -1.187505  700
1 -0.810784  100
2  0.321881  800
3 -1.935284  500
4 -1.351507  300

How can I limit the operation so that a row in part2 is only included in concatenated if the row id does not already appear in part1? In a way, I want to treat the id column like a set.
Is it possible to do this during concat() or is this more a post-processing step?
Desired output for this example would be:
concatenated_desired
     amount   id
0 -0.458653  100
1  2.172348  200
2  0.072494  300
3 -0.253939  400
4 -0.061866  500
0 -1.187505  700
2  0.321881  800

A: Calculate the id's not in part1
In [28]:
diff = part2.ix[~part2['id'].isin(part1['id'])]
diff

Out[28]:
     amount   id
0 -2.184038  700
2 -0.070749  800

now concat
In [29]:
concatenated = pd.concat([part1, diff], axis=0)
concatenated

Out[29]:
     amount   id
0 -2.240625  100
1 -0.348184  200
2  0.281050  300
3  0.082460  400
4 -0.045416  500
0 -2.184038  700
2 -0.070749  800

You can also put this in a one liner:
concatenated = pd.concat([part1, part2.ix[~part2['id'].isin(part1['id'])]], axis=0)

A: call drop_duplicates() after concat():
part1 = pd.DataFrame({'id'    :[100,200,300,400,500],
                   'amount': np.arange(5)
                    })

part2 = pd.DataFrame({'id'    :[700,100,800,500,300],
                   'amount': np.random.randn(5)
                    })

concatenated = pd.concat([part1, part2], axis=0)
print concatenated.drop_duplicates(cols="id")

A: If you get a column with an id, then use it as an index. Perform manipulations with a real index will make things easier. Here you can use combine_first that does what you are searching for:
part1 = part1.set_index('id')

part2 = part2.set_index('id')

part1.combine_first(p2)
Out[38]:
       amount
id
100  1.685685
200 -1.895151
300 -0.804097
400  0.119948
500 -0.434062
700  0.215255
800 -0.031562

If you really need not to get that index, reset it after:
part1.combine_first(p2).reset_index()
Out[39]:
    id    amount
0  100  1.685685
1  200 -1.895151
2  300 -0.804097
3  400  0.119948
4  500 -0.434062
5  700  0.215255
6  800 -0.031562

redpajama_set_name: RedPajamaStackExchange


text:
Q: Representation of prime number by binary quadratic form For wich prime numbers $p$ there exist integers $x,y$ such that $x^2+5y^2=p$?
For cases $x^2+y^2$ or $x^2+2y^2$ this condition is equivalent to discriminant of the form is quadratic residue modulo p, because $\mathbb{Z}[\sqrt{-1}]$ and $\mathbb{Z}[\sqrt{-2}]$ are euclidian, but my case can't be solved in this way because $\mathbb{Z}[\sqrt{-5}]$ is non-euclidian.

A: $x^2 + 5 y^2 $ represents primes $p=5$ or $p \equiv 1,9 \pmod {20}.$
The other form of that discriminant, $2x^2 + 2 x y + 3 y^2,$ represents $p=2$ and $p \equiv 3,7 \pmod {20}.$
For $p \neq 2,5,$ we have Legebdre symbol $(-20|p) = 1$ when $p \equiv 1,3,7,9 \pmod {20}.$ Given such a prime, we solve
$$  \beta^2 \equiv -20 \pmod p  $$
If $\beta $ is odd, replace it by $p-\beta$ which is even. So we have now
$$  \beta^2 \equiv -20 \pmod {4p}.  $$ This is
$$  \beta^2 = -20 + 4 p t $$ for some integer $t,$ or
$$ \beta^2 - 4 p t = -20.  $$
So, the binary quadratic form $$ \langle p, \beta, t \rangle  $$
has the correct discriminant. Gauss reduction takes this to either $ \langle 1,0,5 \rangle  $ or $ \langle 2,2,3 \rangle.  $ We can tell which one by $(5|p).$
Let's see; reduction is a step by step procedure for taking the Hessian matrix $H$ (second partial derivatives) of the original form to one of the choices, either diagonal with entries $(2,10)$ because of the doubling, or the other one. The resulting matrix equation is $P^T H P = G,$ where $P \in SL_2 \mathbb Z.$ But then $P^{-1}$ has also all integer entries, call it $Q = P^{-1}, $ and we have $Q^T G Q = H.$ The representation of $p$ is the left column of $Q.$


text:
Q: How to pass RequestVerification token in $.fileDownload call using jquery.filedownload.js I'm using the following code to download a file
            $.fileDownload("Account/downloadFile",
            {
                data: { AccountNumber: _accountNumber},
            successCallback: function () {

            },
            failCallback: function (responseHtml, url) {

            },
            prepareCallback: function () {
                //logger.log(" File Downloaded ", "", "", "success");
            }
        });

I want to pass __RequestVerificationToken = $(':input:hidden[name*="RequestVerificationToken"]').val() in this call.
I'm not able to pass in the headers.
Please help.
Thanks

A: Add it to the data parameter and change the httpMethod to POST as the antiforgery token is expected to be part of the form values.  You might also need to change the allowed method on the controller action.
$.fileDownload("Account/downloadFile", {
    httpMethod: 'POST',
    data: {
       "AccountNumber": _accountNumber,
       "__RequestVerificationToken":  $(':input:hidden[name*="RequestVerificationToken"]').val()
    },
    successCallback: function () {

    },
    failCallback: function (responseHtml, url) {

    },
    prepareCallback: function () {
        //logger.log(" File Downloaded ", "", "", "success");
    }
});


text:
Q: How to display data from SQL Server on a DataGridView I want to load or show the data from SQL Server on a DataGridView.
The build succeeds and there's no error when I run it. There's nothing wrong in form modul_koneksi (I think) because it works on my other form (form_login)
However, nothing shows up in my DataGridView. How can I fix this?
Code:
Imports System.Data.SqlClient

Public Class FormProduk
    Private Sub FormProduk_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim str As String = "Data Source=Fahriy;Initial Catalog=DBLogin;Integrated Security=True"
        Dim connection As New SqlConnection(str)
        Dim com As String = "Select * From tbl_user"
        Dim dataadapter As New SqlDataAdapter(com, connection)
        Dim dataset As New DataSet()
        dataadapter.Fill(dataset, "tbl_user")
        DataGridView1.DataSource = dataset.Tables()
    End Sub
End Class

A: You should define which table to load in the DataGridView:
DataGridView1.DataSource = dataset.Tables("tbl_user")

A: Not enough info to tell, are you sure your connection string str is correct. You can try change to this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim str As String = "Data Source=Fahriy;Initial Catalog=DBLogin;Integrated Security=True"
    Dim conn As New SqlConnection(str)
    Dim cmd As String = "Select * From tbl_user"
    Dim adapter As New SqlDataAdapter(cmd, conn)
    Dim tabeluser As New DataSet
    adapter.Fill(tabeluser)
    DataGridView1.DataSource = tabeluser.Tables
End Sub

A: You cannot set the .DataSource property with dataset.Tables. Instead you need to set it with a DataTable located in your DataSet:
DataGridView1.DataSource = dataset.Tables("tbl_user")

However I think you could simplify the code a little by getting rid of the SqlDataAdapter and loading straight into a DataTable
Dim dt As New DataTable
dt.Load(com.ExecuteReader())

DataGridView1.DataSource = dt

I would also consider implementing Using:

Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.

With the changes your code would look something like this:
Dim dt As New DataTable

Using con As New SqlConnection("Data Source=Fahriy;Initial Catalog=DBLogin;Integrated Security=True"),
      cmd As New SqlCommand("SELECT * FROM  tbl_user", con)
    con.Open()

    dt.Load(cmd.ExecuteReader())
End Using

DataGridView1.DataSource = dt


text:
Q: Is it possible to set a class variable using a different variable type is it possible to set a c# variable with a different variable type value than what the variable one is setting?
public class Test{

   public DateTime TimeSinceEpoch {
      get {return TimeSinceEpoch; }
      set{
         DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
         TimeSinceEpoch = Epoch.AddMilliseconds(value);}} //<-the value that's expected is a DateTime value..
}

How can i write:
  'TimeSinceEpoch = 1549090800000'
  and use TimeSinceEpoch as a normal DateTime variable?

Without Having tow sepperate get and set variables inside the class

A: This isn't allowed even in C++/CLI which does have a syntax for it:
public ref struct Test
{
    property System::DateTime TimeSinceEpoch
    {
        DateTime get();
        void set(DateTime);
        void set(long long);
    }
};

You get the following error:

error C3902: 'set': type of last parameter must be 'System::DateTime'

Intellisense actually produces two complaints, depending on which order you write them:

E1930:    a 'set' accessor was already declared for this property at

or

E1942:    the last parameter of the 'set' accessor does not match the property type

The underlying problem is that a .NET property has to list a type and a maximum of one setter in the metadata (Have a look at PropertyInfo.GetSetMethod -- it returns one setter or null, not an array).  Even though you could easily overload the setter function itself:
void set_TimeSinceEpoch(DateTime)
void set_TimeSinceEpoch(long)

only one of these two functions could be associated to the property.
You could use a helper type to allow multiple incoming types:
struct SuperDateTime
{
    public DateTime Value;
    public static implicit operator SuperDateTime(DateTime d) { return new SuperDateTime { Value = d }; }
    public static implicit operator SuperDateTime(long x) { return new SuperDateTime { Value = Epoch.AddMilliseconds(x) }; }
    public static implicit operator DateTime(SuperDateTime d) { return d.Value; }
}

but this will break readers of the property, who now have to say TimeSinceEpoch.Value before using a member (if passing as an argument to another function, the implicit conversion will kick in).  To overcome that, you'd need to write a forwarding function for every single member DateTime has.

A: You need a private variable for DateTime and a long property.  See code below :
    public class Test
    {

       private DateTime Epoch { get;set; }
       public long TimeSinceEpoch {
          get {return  Epoch.Ticks; }
          set{
             DateTime temp = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
             Epoch = temp.AddMilliseconds(value);
          }
        }
    }

A: You may just use it the way you do and to get Milliseconds:
var ms = (TimeSinceEpoch - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalMilliSeconds;

or maybe create an extension method for it like:
public static class Extensions
{
     public static long MilliSeccondsSinceEpoch(this DateTime d)
     {
         DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
         return (d - Epoch).TotalMillisecond;
     }
}

Then you can use it like:
TimeSinceEpoch = DateTime.Now;
var ms = TimeSinceEpoch.MilliSeccondsSinceEpoch();

A: The following code works as i wanted it to. Hope it helps somone else
public class Test{
   private DateTime Time {get;set;}
   public object TimeSinceEpoch {
      get{
         return (DateTime)Time
      }
      set{
         DateTime x = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
         Time = x.AddMilliseconds(Convert.ToDouble(value));
      }
   }
}

A: You could achieve this using implicit casts:
public struct EpochBasedDateTime
{
    public EpochBasedDateTime(DateTime value) => Value = value;
    public EpochBasedDateTime(int milliseconds)
        : this(Epoch.addMilliseconds(milliseconds)
    {
    }

    public static readonly DateTime Epoch = new DateTime(1970,1,1);
    public DateTime Value {get;}
    public static implicit operator EpochBasedDateTime (int milliseconds)
       => new EpochBasedDateTime(milliseconds);
    public static implicit operator DateTime (EpochBasedDateTime date)
       => date.Value;
}

So you can
public class Test
{
    public EpochBasedDateTime TimeSinceEpoch {get; set;}
}

var test = new Test();
test.TimeSinceEpoch =  12345;
DateTime dt = test.TimeSinceEpoch;

However, you're probably better off explicitly converting your number to a date using a utility method:
public static class Epoch
{
    public static readonly DateTime Value {get;} = new DateTime(1970,1,1);
    public static DateTime AddMilliseconds(ms)
        => Value.AddMilliseconds(ms);
}

So you can
DateTime foo = Epoch.AddMilliseconds(12345);

or
DateTime foo = Epoch.Value.AddMilliseconds(12345);


text:
Q: Cannot set CONFIG_SFP I'm working with kernel V4.14.
There is a driver for SFPs in Linux. Config does not work however:
There is an entry in the makefile:
obj-$(CONFIG_SFP)       += sfp.o

There is also an entry in the ./drivers/net/phy/Kconfig:
config SFP
    tristate "SFP cage support"
    depends on I2C && PHYLINK
    select MDIO_I2C

But with find ("/") in menuconfig, I cannot find the config item.
Any clue why I cannot find this item?
I also cannot set PHYLINK
Symbol: PHYLINK [=n]
Type  : tristate
    Defined at drivers/net/phy/Kconfig:163
    Depends on: NETDEVICES [=y]
    Selects: PHYLIB [=y] && SWPHY [=y]

A: To enable CONFIG_SFP, starting from scratch on x86-64:

*

*select "General setup"

*

*enable "Compile also drivers which will not load"

*select "Device drivers"

*

*select "Network device support"

*

*select "Ethernet driver support"

*

*enable "Marvell Armada 370/38x/XP/37xx network interface support"

*select "PHY Device support and infrastructure"

*

*enable "SFP cage support"

You won't find PHYLINK because it's an invisible entry, automatically activated when necessary.


text:
Q: How to change multiple existing data frame values to nan I want to change the existing dataframe value to nan. What is the way to do it when you need to change several?
dataframe['A', 'B'....] = np.nan

I tried this but nothing changed

A: Double brackets are required in this case, to pass the list of columns to the dataframe index operator []. For the OP case would be:
dataframe[['A', 'B'....]] = np.nan

Reproducible example:
import numpy as np
import pandas as pd

dict= {'ColA':[1,2,3], 'ColB':[4,5,6], 'ColC':[7,8,9], 'ColD':[-1,-2,-3] }

df=pd.DataFrame(dict,index=['I1','I2','I3'])
print(df)

df[['ColA','ColD']]=np.nan
print(df)

Note:
This solution was originally suggested via comment, now included as an answer with a reproducible example for future reference.


text:
Q: How to add google map infowindow dynamically? Here I am using Google map API to show Google map in my site. Here I am able to add google map statically by following code:
        var map = new GMap2(document.getElementById('map'));
        map.addControl(new GSmallMapControl());
        map.setCenter(new GLatLng(21.183008, 81.36186199999997), 6);

        var marker = new GMarker(new GLatLng(21.183008, 81.36186199999997), {});
        GEvent.addListener(marker, "mouseover", function () {
            marker.openInfoWindow("Hi ");
        });
        GEvent.addListener(marker, "mouseout", function () {
            map.closeInfoWindow();
        });
        map.addOverlay(marker);

        var marker1 = new GMarker(new GLatLng(21.25, 81.62), {});
        GEvent.addListener(marker1, "mouseover", function () {
            marker1.openInfoWindow("HI All");
        });
        GEvent.addListener(marker1, "mouseout", function () {
            map.closeInfoWindow();
        });
        map.addOverlay(marker1);

I have set of marker value in array. When I try it to create dynamically only last information window displayed.
awaiting for response....

A: This has to do with closures in Javascript and it is a common problem. See the Google Maps Javascript API Docs for a solution.
And for more information about closures I would recommend you to search on Stackoverflow (like the comment here, for example) ;)


text:
Q: Ubuntu 12.04: Apache2 symlink to Windows Drive I have Ubuntu 12.04 and Windows 7 on the same machine.
<VirtualHost *:80>
     ServerAdmin admin@example.org
     #ServerName example.org
     #ServerAlias www.example.org
     DocumentRoot /var/www/
     ErrorLog /var/www/logs/error.log
     CustomLog /var/www/logs/access.log combined
</VirtualHost>

Here is my /var/www
wenbert@wenbert-ubuntu:/var/www$ cd /var/www/
wenbert@wenbert-ubuntu:/var/www$ ls -la
total 28
drwxr-xr-x  5 root    root 4096 May  5 14:51 .
drwxr-xr-x 14 root    root 4096 May  5 12:05 ..
drwxr-xr-x  2 root    root 4096 May  5 14:44 logs
lrwxrwxrwx  1 wenbert root   33 May  5 14:32 mysite -> /media/Data/xampp/htdocs/mysite

My /media/Data/xampp/htdocs/mysite is like this:
wenbert@wenbert-ubuntu:/media/Data/xampp/htdocs/mysite$ ls -la
total 44
drwx------ 1 wenbert wenbert     0 May  5 14:06 .
drwx------ 1 wenbert wenbert 40960 May  5 13:54 ..
drwx------ 1 wenbert wenbert     0 May  5 14:11 logs
drwx------ 1 wenbert wenbert     0 May  5 13:57 sql
drwx------ 1 wenbert wenbert  4096 May  5 13:52 www

I noticed that the permissions for this directory is drwx------ - I think this is causing the problem. I also could not see the mysite directory when I browse to http://localhost
So, how would I go about this? I would want my Windows htdocs to be also accessible when I boot to Ubuntu.
UPDATE:
wenbert@wenbert-ubuntu:/var/www$ ps aux | grep apache
root      1446  0.0  0.2  37944  7708 ?        Ss   17:45   0:00 /usr/sbin/apache2 -k start
www-data  1460  0.0  0.1  38016  5708 ?        S    17:45   0:00 /usr/sbin/apache2 -k start
www-data  1461  0.0  0.1  37984  4280 ?        S    17:45   0:00 /usr/sbin/apache2 -k start
www-data  1462  0.0  0.1  37984  4280 ?        S    17:45   0:00 /usr/sbin/apache2 -k start
www-data  1463  0.0  0.1  37984  4284 ?        S    17:45   0:00 /usr/sbin/apache2 -k start
www-data  1464  0.0  0.1  37984  4284 ?        S    17:45   0:00 /usr/sbin/apache2 -k start
www-data  5313  0.0  0.1  37968  4032 ?        S    19:28   0:00 /usr/sbin/apache2 -k start
www-data  5314  0.0  0.1  37968  4032 ?        S    19:28   0:00 /usr/sbin/apache2 -k start
www-data  5315  0.0  0.1  37968  4032 ?        S    19:28   0:00 /usr/sbin/apache2 -k start
www-data  5316  0.0  0.1  37968  4032 ?        S    19:28   0:00 /usr/sbin/apache2 -k start
www-data  5317  0.0  0.1  37968  4032 ?        S    19:28   0:00 /usr/sbin/apache2 -k start
wenbert   5338  0.0  0.0   4388   824 pts/2    R+   19:30   0:00 grep --color=auto apache

A: In order for Apache to follow symlinks, you need
Options FollowSymlinks

in your configuration.  You should also make sure the www-data user has read permissions on the files, and read and execute permissions on the directories.


text:
Q: Grid container like Bootstrap container So, I want to create a page layout what will look like this:
For example, in Bootstrap I can simple write:

And everything will be cool.
Is there a good clean solution to do something like this in Material-UI? By default Grid system create fluid-container with full width.

A: I solved this problem by creating a custom CSS file and pasting in the bootstrap .container class from bootstrap-grid.css file like this.
custom-style.css
.container {
  width: 100%;
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

@media (min-width: 576px) {
  .container {
    max-width: 540px;
  }
}

@media (min-width: 768px) {
  .container {
    max-width: 720px;
  }
}

@media (min-width: 992px) {
  .container {
    max-width: 960px;
  }
}

@media (min-width: 1200px) {
  .container {
    max-width: 1140px;
  }
}

and simply import this custom-style.css file into your index.js file of your ReactJS project.
import 'path/to/your/custom-style.css';

In material-ui, Predefined components have their own paddings setup and when combining them with our custom .container class, it might give additional un-wanting padding, to overcome this problem, we can write our helper classes in the same custom-style.css file like this.
// padding helper classes
.p-0 {
  padding: 0 !important;
}

.pt-0 {
  padding-top: 0 !important;
}

.pb-0 {
  padding-bottom: 0 !important;
}

.ptb-0 {
  padding-top: 0 !important;
  padding-bottom: 0 !important;
}

after this is setup, we can use our custom classes just like we use it in html markup, but in React, with className property
<Grid container>
  <AppBar position="static">

      <Toolbar className="p-0" >
        <Typography variant="h6" color="inherit" className={classes.grow}>
          Learning
        </Typography>
        <Hidden xsDown>
          <Button color="inherit">Login</Button>
          <Button color="inherit">Register</Button>
        </Hidden>
        <Hidden smUp>
          <IconButton className={classes.menuButton} color="inherit" aria-label="Menu">
            <MenuIcon />
          </IconButton>
        </Hidden>
      </Toolbar>

  </AppBar>
</Grid>

and now it is aligned properly just like bootstrap .container class

A: If you're looking for something that behaves like bootstrap's .container then I would use Material UIs <Container /> tag. As a starting wrapper/container, I would not use the <Grid /> tag.
<Container maxWidth="lg">

</Container>

https://material-ui.com/components/container/

A: This can be accomplished using the Grid component and Responsive Breakpoints.  Take a look at the Layout, Grid page in the docs.
Here is an example:
const styles = theme => ({
  demo: {
    height: 240,
    background: "#f00",
    [theme.breakpoints.up("lg")]: {
      width: 1170
    }
  }
});

class ResponsiveGrid extends React.Component {
  render() {
    const { classes } = this.props;
    return (
      <Grid container justify="center">
        <Grid
          container
          className={classes.demo}
          alignItems="center"
          justify="center"
        >
          <Grid lg={12} item>Content Here</Grid>
        </Grid>
      </Grid>
    );
  }
}

export default withStyles(styles)(ResponsiveGrid);

We define a set of styles which are added to the component as the classes prop using withStyles.  The demo class uses the theme to create a media query for the theme's lg breakpoint.  For viewports lg or larger, width will be set to 1170.
A large viewport is considered to be between 1280 and 1919 px.  These are the defaults and are based on the Material Design standard.
Read more about Responsive Breakpoints and see this codesandbox for a working version of my example.

A: Building on OP's comment on OP's post, you can make a specific component that is meant to create a bootstrap style container:
import React from "react";
import { Grid } from "@material-ui/core";

const BootstrapContainerGrid = props => {
  return (
    <Grid container style={{ marginTop: "3em" }}>
      <Grid item lg={2} md={2} sm={1} xs={false} />
      <Grid item lg={8} md={8} sm={10} xs={12}>
        {props.children}
      </Grid>
      <Grid item lg={2} md={2} sm={1} xs={false} />
    </Grid>
  );
};
export default BootstrapContainerGrid;

Then pass in your actual component as a child to this bootstrap style container:
<BootstrapContainerGrid>
  <MyComponent>
    ...
  </MyComponent>
</BootstrapContainerGrid>

Now at least you have reusability and make it easy to edit how your "container" appears.
UPDATE [5/26/19]: Material-ui v4 has a Container component in core "@material-ui/core/Container" which seems to act like a bootstrap container.
https://material-ui.com/api/container/


text:
Q: Stringifying a QuerySet Will the queryset be evaluated i.e will django make database hits if i just stringify the queryset ?
i.e Will the below statement make database hits?
str(Model.objects.all())
The documentation  doesn't cleary mentions about str()

A: Short answer
Yes, because in this case str uses __repr__.
Reasoning:
According to this excellent SO answer on repr vs str in python:

if __repr__ is defined, and __str__ is not, the object will behave
  as though __str__=__repr__

Looking at the django code we see that __repr__ is defined and __str__ is not, so we can reason that the docs on repr cover str as well.
Try it
It's pretty easy to test this sort of thing out yourself:
>>> from django.db import connection
>>> len(connection.queries)
0
>>> str(User.objects.all())
"<QuerySet [<User: test>, ...]>"
>>> len(connection.queries)
1

Comment on some other answers
Database is not directly hit by calling all(), which is the beauty of the lazy queryset evaluation.  A DB query is not triggered until the elements of the response are required (as stated in the documentation pointed to by the OP).

A: For stringfy, i think there won't be any Database hit. only for Model.objects.all() it will hit the database. Once the result came, It will stringfy the queryset without database hit.
str() is just type conversion functions to strings.

A: Your code will only hit the DB once. Calling Model.objects.all() will include an SQL conversion that gets sent to the DB. Once received by your application, the str() call only calls the __str__ method inside a Model. If not defined, I think it will return a default syntax involving the primary key(which I can't remember off the top of my head since I always define __str__ for readability and testing purposes).


text:
Q: urlretrieve not working for this site I'm trying to download an image, however it does seem to work. Is it being blocked by ddos protection?
Here is the code:
urllib.request.urlretrieve("http://archive.is/Xx9t3/scr.png", "test.png")

Basically download that image as "test.png." I'm using python3 hence the urllib.request before urlretrieve.
import urllib.request

Have that as well.
Any way I can download the image? thanks!

A: For reasons that I cannot even imagine, the server requires a well known user agent. So you must pretend to use for example firefox and it will accept to send the image:
# first build a request object
req = urllib.request.Request("http://archive.is/Xx9t3/scr.png",
        headers = {
           'User-agent':
              'Mozilla/5.0 (Windows NT 5.1; rv:43.0) Gecko/20100101 Firefox/43.0'})

#then use it
resp = urllib.request.urlopen(req)
with open("test.png","wb") as fd:
    fd.write(resp.read())

Rather stupid, but when a server admin goes mad, just be as stupid as he is...

A: I'd advice you to use requests, basically the way you are trying to get the image is forbidden, check this:
import requests
import shutil

r = requests.get('http://archive.is/Xx9t3/scr.png', stream=True)
if r.status_code == 200:
    with open("test.png", 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f)

This snippet was adapted from here
The magic behind this is how the resource is retrieved, with requests that part is the stream=True line. Some servers are more restricted with this methods to pull some resources like media.


text:
Q: Unexpected NullPointerException while accessing results of a query I have this code and I don't understand why I'm getting a NullPointerException:
public static ArrayList<String> retrieveObject(String istance,String property){
    String sparqlQueryString= "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-   syntax-ns#> "+
        "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "+
        "PREFIX dbpedia: <http://dbpedia.org/resource/> "+
        "PREFIX o: <http://dbpedia.org/ontology/> "+
        "PREFIX dbprop: <http://dbpedia.org/property/>"+
        "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>" +
        "select ?c"+
        "where {<"+istance+"> "+property+" ?c.}";
    ArrayList<String> array = new ArrayList<String>();
    Query query = QueryFactory.create(sparqlQueryString);
    QueryExecution qexec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", query);
    ResultSet res = qexec.execSelect();
    for(; res.hasNext();) {
        QuerySolution soln = res.nextSolution();
        for(int i=0;i<query.getProjectVars().size();i++){
            array.add(soln.get(query.getProjectVars().get(i).getVarName()).asResource().toString());
        }

    }
    return array;
}

I call the method in this way:
System.out.println(retrieveObject("http://dbpedia.org/resource/Immanuel_Kant","o:deathPlace"));

A:
I have Null pointer exception at this line:
  array.add(soln.get(query.getProjectVars().get(i).getVarName()).asResource().toString());

Break the expression apart to find the NPE - one possibility is that it isn't a URI so asResource is wrong.
Better might be
   for(String var : query.getResultVars() {
        Resource r = soln.getResource(var) ;
        array.add(r.getURI()) ;
   }

(beware of blank nodes)


text:
Q: Sorting Name in mongodb using meteor I have a method as shown below on server.js file in meteor
  getNames : function(){
       var name = AccNames.find({}, {fields: {'Name': 1, '_id': 1}}).fetch();
        return name;
  }

How Can I sort the result in ascending order?
I mean how can I get the list of NAME in ascending order?
Is it possible to use fetch and sort together?

A: Use any one of the sort specifier syntaxes as another property in the find() second argument object:
getNames: function(){
    // All of these do the same thing (sort in ascending order by key "name"

    /*
       var sort_fields = [["Name", "asc"]];
       also the same as var sort_fields = ["Name"];
    */
    var sort_fields = {'Name': 1};
    var projection = {'Name': 1, '_id': 1};
    return AccNames.find({}, {fields: projection, sort: sort_fields}).fetch();
}


text:
Q: Allow empty string to turned into null Date in Spring Boot I'm looking to allow a th:field that collects a date via the BootStrap DatePicker to be empty.
What I run into is a validation error since it is empty, and it looks like this:
Failed to convert from type [java.lang.String] to type [@javax.annotation.Nullable java.util.Date] for value '';
Perhaps I don't quite understand the @Valid annotation well enough to know how to do this.
Any thoughts on how to get around this?

A: can you elaborate more on this error, I was having same error but in different scenario so wanted to understand the flow of error so I can share solution i did.


text:
Q: Mixing some math fonts I want the symbols such \int or \sum from the Latin Modern Math font and the \nabla and all the greek letter such \alpha \beta \psi etc from the Latin Modern Math but all numbers and letters from the EB Garamond. How can i do that?
\documentclass{article}
\usepackage{amsmath}
\usepackage[T1]{fontenc}
\usepackage{fontspec}
\usepackage{unicode-math}

\setmathfont[range=\mathup]  {EB Garamond}
\setmathfont[range=\mathbfup]{EB Garamond}
\setmathfont[range=\mathbfit]{EB Garamond}
\setmathfont[range=\mathit]  {EB Garamond}

\usepackage{mathptmx}

\setmainfont{EB Garamond}

\begin{document}
\[ \int f(\alpha+x)=\sum\beta \]
Some text\dots
\begin{equation}
\begin{split}
\frac{\partial^2 \nabla}{\partial \nabla^2}&=x^2 + yimc^2=z^2 \\
                                           &=\mathrm{x^2 + y^2 = z^2} \\
                                           &=\mathbf{x^2 + y^2 = z^2}
\end{split}
\end{equation}

\begin{equation}
i\hbar \frac{\partial \psi }{\partial t}=\frac{\hbar c}{i}\left(\alpha _1\frac{\partial \psi }{\partial x^1}+\alpha _2\frac{\partial \Psi }{\partial x^2}+\alpha _3\frac{\partial \psi }{\partial x^3}\right)+\alpha _4mc^2\psi
\end{equation}

\end{document}

And the shape of \partial how this example
\documentclass{article}

\usepackage[T1]{fontenc}

\usepackage{txfonts}

\begin{document}

\begin{equation}
\frac{\partial}{\partial}
\end{equation}

\end{document}

A: You have to carefully select the ranges and the symbols you need. Here's an example:
\documentclass{article}
\usepackage{amsmath}
\usepackage{unicode-math}

\setmathfont[range=\mathup]  {EB Garamond}
\setmathfont[range=\mathbfup]{EB Garamond}
\setmathfont[range=\mathbfit]{EB Garamond}
\setmathfont[range=\mathit]  {EB Garamond}
\setmathfont[range={\partial,\nabla,\hslash}]{TG Termes Math}
\setmathfont[range=\mathit/{greek,Greek}]{Latin Modern Math}

\setmainfont{EB Garamond}

\begin{document}
\[ \int f(\alpha+x)=\sum\beta \]
Some text\dots
\begin{equation}
\begin{split}
\frac{\partial^2 \nabla}{\partial \nabla^2}&=x^2 + yimc^2=z^2 \\
                                           &=\mathrm{x^2 + y^2 = z^2} \\
                                           &=\mathbf{x^2 + y^2 = z^2}
\end{split}
\end{equation}

\begin{equation}
i\hbar \frac{\partial \psi }{\partial t}=\frac{\hbar c}{i}\left(\alpha _1\frac{\partial \psi }{\partial x^1}+\alpha _2\frac{\partial \Psi }{\partial x^2}+\alpha _3\frac{\partial \psi }{\partial x^3}\right)+\alpha _4mc^2\psi
\end{equation}

\end{document}


text:
Q: Como fazer um insert no banco de dados a partir de um relacionamento muitos para muitos no typeorm Estou desenvolvendo um cadastro de profissionais onde cada profissional pode falar um ou mais idiomas, contudo ao salvar profissionais, os idiomas nao sao salvos
@Entity('idioma')
export class Idioma {
  @PrimaryGeneratedColumn()
  id: number;
  @Column()
  lang: string;
  @Column()
  native: boolean;
}

@Entity('Profissional')
export class Profissional {
  @PrimaryGeneratedColumn()
  id: number;
  @Column()
  name: string;
  @Column()
  @IsOptional()
  phone: string;
  @Column()
  @IsOptional()
  celPhone: string;
  @Column()
  @IsOptional()
  sexo: string;
  @Column()
  @IsOptional()
  nasc: Date;
  @Column('bool')
  @IsOptional()
  fumante: boolean;
  @Column()
  @IsOptional()
  ocupation: string;
  @Column()
  @IsEmail()
  email: string;
  @OneToMany(
    () => Idioma,
    idioma => idioma.id,
    {cascade: true}
  )
  lang: Idioma[];
  @Column()
  password: string;
  @Column('decimal', { precision: 5 })
  latitude: number;
  @Column('decimal', { precision: 5 })
  longitude: number;
  @Column('decimal', { precision: 2 })
  @IsOptional()
  workPrice: number;
}

async create(profissional: ProfissionalDto) {
    const errors = validate(profissional);

    profissional.password = bcrypt.hashSync(profissional.password, 12);
    const prof = this.profissionalRepository.save(profissional);

    return prof;
  }

A: O que faltou aí é que na entidade Idioma, faz,-se necessário a declaração dos relacionamentos, como pode ser visto na documentação:

You can omit @JoinColumn in a @ManyToOne / @OneToMany relation. @OneToMany cannot exist without @ManyToOne. If you want to use @OneToMany, @ManyToOne is required. However, the inverse is not required: If you only care about the @ManyToOne relationship, you can define it without having @OneToMany on the related entity. Where you set @ManyToOne - its related entity will have "relation id" and foreign key.

Você pode omitir @JoinColumn em uma relação @ManyToOne / @OneToMany. @OneToMany não pode existir sem @ManyToOne. Se você quiser usar @OneToMany, @ManyToOne é necessário. No entanto, o inverso não é necessário: se você se preocupa apenas com o relacionamento @ManyToOne, pode defini-lo sem ter @OneToMany na entidade relacionada. Onde você define @ManyToOne - sua entidade relacionada terá "id de relação" e chave estrangeira.

Ou seja, vc utilizou @OneToMany() na entidade Profissional, é obrigatório declarar @ManyToOne() em Idioma, pois o TypeORM monta toda a lógica no banco de dados em função deste relacionamento, como pode ser visto acima, se quiser pode declarar só o @ManyToOne() e omitir @OneToMany() que não terá problemas:
@Entity('idioma')
export class Idioma {
  @PrimaryGeneratedColumn()
  id: number;
  @Column()
  lang: string;
  @Column()
  native: boolean;
  @ManyToOne(() => Profissional, profissional => profissional.lang)
  profissional: Profissional;
}

@Entity('Profissional')
export class Profissional {
  @PrimaryGeneratedColumn()
  id: number;
  ...
  @OneToMany(() => Idioma, idioma => idioma.id, {
    cascade: true
  })
  lang: Idioma[];
  ...
}


text:
Q: Сортировка вставками (модифицировать алгоритм) Написать алгоритм сортировки. Но не совсем сортировка вставками, алгоритм нужно немного модифицировать. Сделала иллюстрацию после 7 прохода цикла: 8 элемент копируем в дополнительную переменную, сравниваем её с предыдущими элементами, когда находим правильную позицию, переносим туда восьмой элемент, все после него сдвигаем на 1 вправо.
void Sort(coord* ar, int s)
{
    int i, j;
    for (i = 1; i <= s; i++) { //сортування вставками
        for (j = i; j > 0 && ar[j - 1].sq > ar[j].sq; j--) {
            coord t = ar[j];
            ar[j] = ar[j - 1];
            ar[j - 1] = t;
        }
    }
}

A: Так, хотел вас довести, чтоб вы написали сами, но так как мы тут запутались... Я думаю, что от вас хотят этого:
void sort(int * a, size_t size)
{
    for(size_t i = 0; i < size-1; ++i)
    {
        // Начиная от i, ищем минимальный элемент
        int m = a[i]; size_t mi = i;
        for(size_t j = i; j < size; ++j)
            if (m > a[j]) { m = a[j]; mi = j; }

        // Копируем вправо
        for(size_t j = mi; j > i; --j)
            a[j] = a[j-1];

        // Вставляем
        a[i] = m;
    }
}

Т.е. в еще неотсортированном куске ищем минимальный элемент, сдвигаем, как у вас написано, и вставляем его - и отсортированный кусок увеличивается. Жутко неоптимально, но что с преподов взять... :)
Полный пример тут.

A: Сортирвка вставками. Это классика.
Алгоритм замечательно описан и всесторонне проанализирован в третьем томе "Искусство программирования" Д. Кнута.
void
lin_insort (int *a, int n)
{
  for (int i = 1; i < n; i++) {
    int j, t = a[i];
    // linear search desired position `j` for `a[i]` in sorted array
    for (j = i - 1; j >= 0 && t < a[j]; j--)
      a[j + 1] = a[j]; // shift right during search
    a[j + 1] = t;      // put a[i] to true position
  }
}

Вероятно это наиболее эффективный из всех простых (с временем выполнения O(N^2)) алгоритмов сортировки. Он прекрасно использует уже существующее упорядочение элементов сортируемого массива.
Идея алгоритма состоит во вставке очедного элемента в уже упорядоченную часть массива. Очевидно, что массив из одного элемента  упорядочен. Последовательно берем элементы, начиная с индекса 1 и рассматриваем находящиеся перед ним, как уже отсортированный массив (т.е. проводим линейный поиск).
Запомним очередной элемент массива и перебирая элементы от конца к началу  ищем позицию, в которую надо вставить новый элемент. По ходу поиска копируем элементы вправо. Найдя подходящую позицию (все элемены перед ней меньше или равны вновь вставляемому), запишем в нее запомненный ранее элемент.
На практике данный алгоритм обычно используется как составная часть многих "серьезных" алгоритмов сортировки типа "разделяй и властвуй" (QuickSort, MergeSort) с временем  выполнения O(N log N) для сортировки "хвостов" (частей сортируемого массива из нескольких десятков элементов, образующихся в процессе эффективного разделения всего массива).

Иногда для поиска позиции вставки вместо линейного поиска (время O(N)) используют двоичный (он же логарифмический) поиск (время O(log N)), поскольку массив в котором ищем, уже упорядочен.
Возможно таким будет ваше следующее задание, именно поэтому сейчас вас попросили  сначала найти позицию вставки, а потом сдвинуть все элементы вправо.
Сортировка вставками с двоичным поиском выглядит вот так:
// binary search the `pos` for insert `key`
// all elements to left from `pos` are less or equal the `key`
// all elements from pos to `n` are greater the `key`
int
search_pos (int key, int *a, int n)
{
  int first = 0,
    last = n,
    mid;

  while (first < last) {
    mid = first + (last - first) / 2;
    if (key < a[mid])
      last = mid;
    else
      first = mid + 1;
  }

  return first;
}

void
bin_insort (int *a, int n)
{
  for (int i = 1; i < n; i++) {
    int t = a[i],
      pos = search_pos(t, a, i); // binary search desired position for `a[i]` in sorted array
    // now shift to the right all elements between `i - 1` and `pos`
    for (int j = i; j > pos; j--)
      a[j] = a[j - 1];
    a[pos] = t;
  }
}


text:
Q: Getting box with gray background when right-clicking icons in Windows 8.1 taskbar I thought I might try asking here since I couldn't find a solution to my problem anywhere, or maybe I didn't search correctly, but I just don't know how to describe this:
Basically, I get a box with a gray background after right-clicking any icon in the taskbar. However, right-clicking icons in the notification area works correctly.
Screenshot of the problem:

This happened today after doing a clean install of Windows 8.1 Pro, installing drivers, and getting Windows updates, nothing else.

A: Found the solution!
Uninstall update KB3072318 and restart!


text:
Q: Lotus Notes get value from rich text to a text field I'm following this guide (look under "Views" section):
http://www-10.lotus.com/ldd/dominowiki.nsf/dx/Working_with_IBM_Lotus_Notes_rich_text_fields
But I can't get/retrieve the value in my view. I created a new column, added the variable "HiddenUserField" and tried to use @Abstract as described in the guide. Also I tried @Text, but no luck.

A: You have to create this hidden field in your form, not in view. Use the formula
@Abstract([TextOnly]; 1000; ""; "ProposedRes")

After you added it to your form you have to recalculate all documents so that this hidden field gets filled. As an alternative you could write an agent which sets the hidden field using @Abstract in all documents.


text:
Q: How to manage different environment specific alerts in Prometheus I have  one Prometheus for all types of environments, i.e. DEV, PROD, STAGING ...
it's  useful to see whole big  picture in one place but  i would like  to have something  like tabs or color mark for  different types of environments
I have different  titles for  different  types of  environments,  i.e.
DEV | Hight CPU usage
PROD| Hight CPU usage

....
i would like  to have different  tabs or  nested groups something like this:
DEV
  |_ DEV | Hight CPU usage
PROD
  |_ PROD| Hight CPU usage


text:
Q: Protractor timeout on Angular 6 navigation I am trying to use Protractor to test a simple login function and everything looks correct when the browser pops up but the test fails anyway.
import { AppPage } from './app.po';
import {browser, by, element, ProtractorBrowser} from 'protractor';

describe('new App', () => {
  let page: AppPage;

  beforeEach(() => {
    page = new AppPage();
  });

  it('should login successfully', () => {
    page.navigateTo();
    element(by.id('email')).element(by.tagName('input')).sendKeys('email');
    element(by.id('password')).element(by.tagName('input')).sendKeys('password');

    element(by.id('login-button')).click()

    browser.sleep(3000).then(() => {
      browser.getCurrentUrl().then(actualUrl => {
        expect(actualUrl).toEqual('/clients')
      })
    })

  })
});

The page correctly fills in the form and navigates to /clients however the logs say:
**************************************************
*                    Failures                    *
**************************************************

1) new App should login successfully
  - Failed: script timeout
    (Session info: chrome=85.0.4183.121)
    (Driver info: chromedriver=85.0.4183.87 (cd6713ebf92fa1cacc0f1a598df280093af0c5d7-refs/branch-heads/4183@{#1689}),platform=Mac OS X 10.15.5 x86_64)

What am I missing here?


text:
Q: Why delete method gives me wrong path? with I have simple delete link:
= link_to "Delete", messages_path(message.id), :method => :delete
Gives me error:  No route matches [DELETE] "/messages.316"
How to fix this?
I have ruby 1.9.3p0 Rails 3.1.1
My routes.rb
  resources :messages do
    collection do
      get :outbox
    end
  end

when i change this to message_path i recieve wrong number of arguments (0 for 1) -> full_trace: https://gist.github.com/1967988
-> all files: https://gist.github.com/1967994
   outbox_messages GET    /messages/outbox(.:format)          {:action=>"outbox", :controller=>"messages"}
           messages GET    /messages(.:format)                 {:action=>"index", :controller=>"messages"}
                    POST   /messages(.:format)                 {:action=>"create", :controller=>"messages"}
        new_message GET    /messages/new(.:format)             {:action=>"new", :controller=>"messages"}
       edit_message GET    /messages/:id/edit(.:format)        {:action=>"edit", :controller=>"messages"}
            message GET    /messages/:id(.:format)             {:action=>"show", :controller=>"messages"}
                    PUT    /messages/:id(.:format)             {:action=>"update", :controller=>"messages"}
                    DELETE /messages/:id(.:format)             {:action=>"destroy", :controller=>"messages"}

EDIT:
Releated with How to destroy polymorphic model? Method destroy missing argument

A: You need to say message_path (singular) since it is the path for a single message:
link_to "Delete", message_path(message.id), :method => :delete

A: You're using the wrong URL helper. Just pass the message variable as the second argument for link_to.
Example:
= link_to "Delete", message, :method => :delete

A: You want message_path(message) not messages_path. messages_path returns the index.


text:
Q: Shelah's "Can you take Solovay's inaccessible away?" I was wandering if there was a book, thesis or some notes where Shelah's argument for

*

*$\mathtt{ZF}+\mathtt{DC}+$"All sets of reals are Lebesgue measurable" is equiconsistent with $\mathtt{ZFC} + \exists \kappa$ inaccessible

*$\mathtt{ZF}+\mathtt{DC}+$"All sets of reals have the Baire property" is equiconsistent with $\mathtt{ZFC}$
contained in Can you take Solovay's inaccessible away? is explained in a newer and/or "more digestible" way. Is there?
Thanks!

A: Chapter 9.5 of the book by Bartoszynski-Judah presents Raisonnier's proof (answering your question 1):
Assume that $\aleph_1$ is not inaccessible in $L$, hence a successor in $L$.  So there is a real $x$ which knows that the $L$-predecessor is countable, hence $\aleph_1^{L[x]}=\aleph_1$, so $X:=\mathbb R \cap L[x]$ is uncountable.
Now assume that  all $\Sigma^1_2(x)$-sets are Lebesgue measurable. Then (this needs some work) the "Raisonier filter" $F_X$ built from $X$, which is a $\bf \Sigma^1_3$-set, is a rapid filter and therefore (again some work, known earlier) not measurable.


text:
Q: KeyError: 'sessionId' when using IEWebDriver in Robot Tests i am getting a KeyError: 'sessionId' error when im running my robot tests on Internet Explorer using IEWebDriver. i made sure i am using the latest IEWebDriver (which is 3.6). when i run in Chrome, everything is running fine. how do i fix this?
here are some system information:

*

*IE version: 11

*Robot Framework Version: 2.9

*robotframework-selenium2library version: 1.7.4

*windows version: 7

Thank you so much in advance.

A: I had the same issue, but fixed by upgrade to the latest Python selenium library:
pip install -U selenium


text:
Q: TextBox strings to multiple rows I have a an ActiveX Multi-Line TextBox1 embedded in a Work Sheet. It has values (separated by line breaks/carriage returns) that I'm trying to get into multiple cells (A1:A5 in this case, but however many I need depending on however many lines the user enters in TextBox1), but so far I've only been able to get them into one cell (in this case, A1). I've tried setting the LinkedCell to multiple ranges in the Properties of TextBox1, but this doesn't work.

 What I've got:                                            TextBox1
                                                              |

             A
                                                  ------------------------------
 1            a                                  |a                             |
              b                                  |b                             |
              c                                  |c                             |
              d                                  |d                             |
              e                                  |e                             |
                                                  ------------------------------

 ------------------------------------------------------------------

 What I'm trying to get:

                                                           TextBox1
                                                              |

             A
                                                -------------------------------
 1           a                                  |a                             |
 2           b                                  |b                             |
 3           c                                  |c                             |
 4           d                                  |d                             |
 5           e                                  |e                             |
                                                --------------------------------

 -----------------------------------------------------------

Is there a way to output the value/strings separated by breaks/carriage returns of TextBox1 into multiple cells? Thanks!

Here is a macro that I've recently tried:
Sub TextBoxToRow()
  Dim Arr As Variant

  Arr = Split(ActiveSheet.TextBox1.Text, vbLf)
  Range("B2").Resize(, UBound(Arr) + 1) = Arr
End Sub

where the value is grabbed from the textbox and use the carriage return as a delimiter. But no go
I think the problem is that the macro simply may not be launching when I enter the strings into the textbox (which is what I meant when I said "no go"...simply that nothing happens).

A: The key here, is to use the change event of your textbox, so whenever you change anything your macro will run.
Easiest way to insert it is to go to the code module of your worksheet containing the textbox, open dropdown at top left corner and select the name of your textbox, it'll automatically insert sub for change event.
I also needed to slightly modify your code to work:
Private Sub TextBox1_Change()
    Dim Arr As Variant
    Dim i As Long
    Dim Target As Range

    Arr = Split(ActiveSheet.TextBox1.Text, vbLf)
    Set Target = Range("B2")
    For i = LBound(Arr) To UBound(Arr)
        Target.Value = Arr(i)
        Set Target = Target.Offset(1, 0)
    Next i
End Sub

If you don't want each change to be reflected, just once you leave textbox, then you can use LostFocus event instead of Change.


text:
Q: WPF Graph Layout Component Does anyone know of or even better.. can wholeheartedly recommend a WPF graph layout component (Microsoft Research had GLEE a while back but it hasn't been updated after 1.0 since 2007 and isn't WPF etc) as seen e.g. in the screenshot below?
I've seen yFiles WPF and Lasalle's AddFlow for WPF, but are there any alternatives?
RedGate Ants Memory Profiler as example http://www.red-gate.com/products/ants_memory_profiler/screenshot_gallery/Class_Explorer.gif
(c) Screenshot: RedGate Ants Memory Profiler

A: Try http://graphsharp.codeplex.com/.
I started a project, today, using MSAGL, but I would rather use WPF for the UI.
From the site:

*

*Can use all kinds of algorithms (layout, overlap removal, edge,
  highlight)

*Vertex dragging supported

*Templates for vertices and edges supported

*Mutable graph -> automatic relayout after the graph changes (burst mode:
  lot of modification but only 1
  relayout)

*Async layout (background thread) supported

*Position changes are animated!

A: Take a look demos at http://www.goxam.com/.

A: Take a look at GraphX for .NET PRO. We have much to offer in both free and commercial versions: many customizable layouts, edge routing, graph filters and advanced styles for everything.
We're the successor of the now discontinued graphsharp.


text:
Q: Radio button returning undefined when not shown I have a question involving two radio buttons: Yes and No. If "no" is selected, nothing happens. If "yes" is selected, another question with two radio buttons appear, also with Yes or No. The problem is that when "no" is selected it does not present the other questions, which makes this error then appear when submitted"

Element Mailincare_1 is undefined in a Java object of type class coldfusion.filter.FormScope.

Form Code:

   Mail to address other than mailing address listed above?
   <cfoutput><input type="radio" value="Yes" name="Mailto_1" id="Mailto_1" required="yes" /></cfoutput>
   Yes
   <cfoutput><input type="radio" value="No" name="Mailto_1" id="noMailto_1" /></cfoutput>
   No

   Please choose one.

   Mail in care of someone else's name?
   <cfoutput><input type="radio" value="Yes" name="Mailincare_1" id="Mailincare_1"/></cfoutput>
   Yes
   <cfoutput><input type="radio" value="No" name="Mailincare_1" id="noMailincare_1" /></cfoutput>
   No

   Please choose one.

Sorry for posting all this, but I just wanted to show how the sessions are being set up.
<cfif structKeyExists(form, "submit")>
     <cfset errors = []>
     <cfif not arrayLen(errors)>
        <cfloop index="Add" from="1" to="#session.checkout.quantity.pcount#" step="1">
            <cfset session.checkout.info["firstname_#Add#"]=form["firstname_#Add#"]>
                ...
                <cfif Add EQ 1>
                    <cfset session.checkout.info["Mailto_#Add#"]=form["Mailto_#Add#"]>
                       <cfset session.checkout.info["Mailincare_#Add#"]=form["Mailincare_#Add#"]>
                    ...
                </cfif>
                ....
            </cfloop>
            <cflocation url="vehicleInfo.cfm" addToken="false">
    </cfif>
</cfif>

A: There are a few ways to deal with this.  In no particular order, here are three of them

*

*check for the existence of the form field before doing anything with
it.

*Use <cfparam> to ensure the field always exists

*Add a hidden form field with the same name to your form.  When you
submit the form, use ListLast to get the value of the radio button if
it was submitted.


text:
Q: Unable to understand the err Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    The operator + is undefined for the argument type(s) java.lang.Integer,
    java.lang.Integer

    at TestClass.Print3.main(Print3.java:14)

public class Print3 {
    public static Integer wiggler(Integer x) {
        Integer y = x+10;
        x++;
        System.out.println(x);

        return y;
    }

    public static void main(String[] args) {
        Integer dataWrapper = new Integer(5);
        Integer value = wiggler(dataWrapper);
        System.out.println(dataWrapper+value);
    }
}

A: I haven't seen this compile error before, its very strange to me because normally Java compiler will unbox the Integer object into a int primitve type and use the addition.
I have compiled your file and look at the binary code:
  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=3, locals=3, args_size=1
         0: new           #6                  // class java/lang/Integer
         3: dup
         4: iconst_5
         5: invokespecial #7                  // Method java/lang/Integer."<init>":(I)V
         8: astore_1
         9: aload_1
        10: invokestatic  #8                  // Method wiggler:(Ljava/lang/Integer;)Ljava/lang/Integer;
        13: astore_2
        14: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;
        17: aload_1
        18: invokevirtual #2                  // Method java/lang/Integer.intValue:()I
        21: aload_2
        22: invokevirtual #2                  // Method java/lang/Integer.intValue:()I
        25: iadd
        26: invokevirtual #9                  // Method java/io/PrintStream.println:(I)V
        29: return
      LineNumberTable:
        line 11: 0
        line 12: 9
        line 13: 14
        line 14: 29
}

I omitted the uninteresting binary code because the interessting part is in the main Method.
What i want to show you is that the Java Compiler will automatically unbox the Wrapper class into an int primitive type with the call Method java/lang/Integer.intValue:()I
in line 18 and 22 after that the addition will be executed.
So the other answers will no help neither.
I will suggest to use another Java Compiler respectively update your jdk
and try to compiler it on another machine.
You can also test you code with ideone and as you see it works perfectly.
http://ideone.com/9tJYf1

A: Try using this code instead:
public class Print3 {
    public static Integer wiggler(Integer x) {
        Integer y = new Integer(x.intValue() + 10);
        x = new Integer(x.intValue() + 1);
        System.out.println(x);

        return y;
    }

    public static void main(String[] args) {
        Integer dataWrapper = new Integer(5);
        Integer value = wiggler(dataWrapper);
        int result = dataWrapper.intValue() + value.intValue();
        System.out.println(result);
    }
}

As @Eran mentioned, I would have expected your code to work without issues.  Apparently your version of Java is choking on the addition of two Integers.


text:
Q: Dynamic angular models? Okay, so I am building a fake dish builder for a restraunt. I have a form that includes everything you need to build it, and the only thing I am having trouble with is the ingredient list. Here is my HTML:

      {{ing}}
      <input type="checkbox" name="{{ing}}" ng-click="addIngredient(ing)"/>
      <input type="number" name="more" ng-model="ings.ing.more" placeholder="price for extra"/>
      <input type="number" name="less" ng-model="ings.ing.less" placeholder="price for less/none"/>

and here is the (relevent) JS:
$scope.ings = {};

$scope.ingredientList = ['lettuce', 'tomatoe', 'steak', 'pulled pork', 'green onion', 'red onion', 'mozarella', 'cheddar', 'bacon bits', 'chicken'];

$scope.addIngredient = function(which){
    $scope.ings[which] = which;
}
$scope.makeItem = function(item){
    item.ingredients = $scope.ings;
    console.log(item);
    ItemService.createItem(item)
      .then(handleRes, handleRes);
}

As I'm sure you guessed, when I am trying to check a box for a specific ingredient and add the price modifiers for more or less of that specific ingredient, it modifies the price for all ingredients in the list. E.g., I can't have individual modifiers because of the model. I know this is a problem with the model, but how can I rewrite my code to accomplish what I'm doing?
for those reading this after the correct answer has been chosen, see the fiddle located here to see a more accurate HTML of what I was working with. By the way, the fiddle doesn't entirely work (for reasons I don't know, but I rarely use JSFiddle), but it is super easy to understand what I was trying to do if you see it I think. http://jsfiddle.net/Lrpjwyrg/13/

A: I don't know if this is the right answer. But i think it is close to what you want.

angular.module('app', [])
    .controller('cntrl', function ($scope) {

    $scope.ingredientList = [{
        name: 'lettuce',
        count: 0,
        price: 23,
        selected: false
    }, {
        name: 'tomatoe',
        count: 0,
        price: 87,
        selected: false
    }, {
        name: 'steak',
        count: 0,
        price: 98,
        selected: false
    }, {
        name: 'pulled pork',
        count: 0,
        price: 292,
        selected: false
    }];

    $scope.setItOne = function (idx) {
        if ($scope.ingredientList[idx].count < 1) {
            $scope.ingredientList[idx].count = 1;
        }
        updateSelectedingredients();
    };

    function updateSelectedingredients() {
        $scope.selectedingredients = $scope.ingredientList.filter(function (item) {
            return item.selected;
        });
    }

        $scope.getTotal = function(){
            var total = 0;
            ( $scope.selectedingredients || []).forEach(function(item){
                total = total + item.count * item.price;
            });
            return total;
        };

    $scope.makeItem = function () {
        alert(JSON.stringify($scope.selectedingredients));
    }

});

{{ing.name}}
            <input type="checkbox" name="{{ing}}" ng-model="ing.selected" ng-change="setItOne($index)" />
            <button ng-click="ing.count = ing.count + 1">Up</button>
            <button ng-click="ing.count = ing.count - 1" ng-disabled="ing.count < 1">Down</button>
             | {{ing.count}} x {{ing.price | currency}} = {{ing.count * ing.price | currency}}

Selected items

{{item.name }} x {{item.count}} -> {{item.count}} x {{item.price | currency}} = {{item.count * item.price| currency}}

            Total: {{ getTotal() | currency}}

        <button ng-click="makeItem()">Make Item</button>

A: i a bit change your fiddle:
first, use ng-model="ings[ing].more" and ng-model="ings[ing].less".
second, save object in ings array instead of just string
$scope.addIngredient = function(which) {
  $scope.ings[which] = {
    name: which
  };
}

angular.module('CpCtrl', []).controller('ControlPanelCtrl', [
  '$scope',
  function($scope) {
    $scope.message = '';
    $scope.inglist = ['lettuce', 'tomatoe', 'steak', 'pulled pork', 'green onion', 'red onion', 'mozarella', 'cheddar', 'bacon bits', 'chicken'];
    $scope.sauceList = ['bbq', 'ranch', 'nacho cheese', 'yum sauce'];
    $scope.ings = {};

    $scope.addIngredient = function(which) {
      $scope.ings[which] = {
        name: which
      };
    }
    $scope.makeItem = function(item) {
      item.ingredients = $scope.ings;
      console.log(item);
    }

  }
]);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />

 Welcome

 Make Item

      <form>

          Item Name
          <input class="form-control" type="text" ng-model="item.itemname" id="itemname" />

          Item Description
          <textarea class="form-control" ng-model="item.itemdescription" id="itemdescription"></textarea>

            <input type="checkbox" name="pizza" ng-model="item.pizza" ng-click="setBase()" />Pizza

            <input type="checkbox" name="sub" ng-model="item.sub" ng-click="setBase()" />Sub

            <input type="checkbox" name="spud" ng-model="item.spud" ng-click="setBase()" />Spud

          Spud Price
          <input class="form-control" type="number" name="spud-price" ng-if="item.spud" id="spud-price" ng-model="item.price.spud" />

          Pizza Price
          <input class="form-control" type="number" name="pizza-price" ng-if="item.pizza" ng-model="item.price.pizza" />

          Sub Price
          <input class="form-control" type="number" name="sub-price" ng-if="item.sub" ng-model="item.price.sub" />

          {{ing}}
          <input type="checkbox" name="{{ing}}" ng-click="addIngredient(ing)" />
          <input type="number" name="more" ng-model="ings[ing].more" placeholder="price for extra" />
          <input type="number" name="less" ng-model="ings[ing].less" placeholder="price for less/none" />

          Add Picture(s)
          <input type="file" name="picture" />

        Create
      </form>


text:
Q: Java cannot find S3 service I've got a problem following tutorial
Have been looking for solutions, but no result
IntelliJ can't read imports from package amazonaws services S3, when I build an app, the error says

pom.xml
    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>youtube</artifactId>
        <groupId>pl.marcin</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>backend</artifactId>

    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
            <dependency>
                <groupId>io.awspring.cloud</groupId>
                <artifactId>spring-cloud-aws-context</artifactId>
                <version>2.3.2</version>
            </dependency>
        <dependency>
            <groupId>io.awspring.cloud</groupId>
            <artifactId>spring-cloud-aws-autoconfigure</artifactId>
            <version>2.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>16</source>
                    <target>16</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

class which is connected with error
package pl.marcin.youtube.service;

import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;

import java.io.IOException;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class S3Service implements FileService {

    public static final String YOUTUBE_DEMO = "youtube-mw";

    private final AmazonS3Client awsS3Client;

    @Override
    public String uploadFile(MultipartFile file) {

        var filenameExtension = StringUtils.getFilenameExtension(file.getOriginalFilename());
        var key = UUID.randomUUID().toString() + "." + filenameExtension;

        var metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());
        metadata.setContentType(file.getContentType());
        try {
            awsS3Client.putObject(YOUTUBE_DEMO, key, file.getInputStream(), metadata);
        } catch (IOException ex){
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR,
                    "An exception occured while uploading a file");
        }
        awsS3Client.setObjectAcl(YOUTUBE_DEMO, key, CannedAccessControlList.PublicRead);
        return awsS3Client.getResourceUrl(YOUTUBE_DEMO, key);
    }
}

A: If you want to build a Spring App that works with Amazon S3, refer to this AWS tutorial. It walks you through building a Java Spring BOOT app that uses Amazon S3, Amazon Rekognition, and other services. It also uses AWS SDK for Java V2 - which is the recommended SDK to use.
The use case for this app is it analyzes many nature images that are located in an Amazon S3 bucket.
Detect objects in images with Amazon Rekognition using an AWS SDK
There is also a sample Spring BOOT app that streams videos located in an Amazon S3 bucket:

Which seems to be what you are trying to do. See
Building a Spring Boot web application that Streams Amazon S3 content over HTTP


text:
Q: Number of spanning trees in a subgraph A spanning tree of a connected graph is identified with any acyclic subgraph that contains all vertices of this graph. How to formally prove or where to find a proof that any subgraph of a connected graph contains equal or less numer of spanning trees than the original graph ?

A: In general, the combinatorial strategy to prove that $|X| \le |Y|$ is to find an injective function from $X$ to $Y$.
In this case, you have a subgraph $H$ of a connected graph $G$; to prove that $G$ has at least as many spanning trees as $H$, you want to find an injective function which turns spanning trees of $H$ into spanning trees of $G$.
Given a spanning tree $T$ of $H$, we can extend it to a spanning tree of $G$ as follows. For as long as $T$ is not a spanning tree of $G$ (that is, for as long as it does not contain the vertices of $G$) we can make $T$ larger by

*

*Picking an arbitrary vertex $v$ of $G$ which is not yet in $T$.

*Finding the shortest path from $v$ to $T$, ending at a vertex $w$ in $T$.

*Creating a larger tree $T'$ consisting of the tree $T$ and the $v,w$-path found in step 2.

Repeat this with the new tree $T'$ until you have a tree that spans all the vertices of $G$.
You should check that (a) this process is always possible to carry out, (b) it always ends with a spanning tree of $G$, and (c) if we start with different spanning trees of $H$, we are guaranteed to end up with different spanning trees of $П$.
(Statement (c) is necessary to guarantee that the function we construct is injective, which is vital to get the inequality we want.)

A: Another way to prove that is to use the well-known recursive formula for $t(G)$ (number of spanning trees of graph $G$)
$$
t(G) = t(G\backslash e) + t(G|e) \,,
$$
where $e$ is an arbitrary edge of $G$, $G\backslash e$ is subgraph of $G$ obtained by removing edge $e$ and $G|e$ is graph obtained from $G$ by contracting edge $e$ (proof is quite simple).
It follows that $t(G\backslash e) < t(G)$, and then we can use induction on number of subgraph's edges to infer the general inequality you asked for.


text:
Q: How can I benchmark the XML parser of my choice? I will handle a huge XML file and I will go with XMLReader. Below are three ways to go with, but I need to know which one is the fastest. How can I know this? The planet.xml file is located at http://trash.chregu.tv/planet-big.xml.bz2 in case hat you may need it. Thank you!

A: You might want to consider the PHP profiling extension:
http://www.php.net/apd
You can examine the results with pprofp:
http://www.compago.it/php/phpckbk-CHP-21-SECT-3.html

A: I haven't worked with XML much in PHP, but if you're dealing with a really large file, a streaming parser is the way to go.  Reading the whole thing into memory and building a DOM tree is pretty expensive (and may even fail, if the document's too big to hold in memory).


text:
Q: Highcharts: xAxis with vertical gridlines I need to create a line chart where the xAxis would show vertical gridlines instead of horizontal ones, just like in "charts: {inverted: true}" case (example on the screen below).
vertical gridlines effect
Unfortunately, that solution isnt' entirely accurate because it switches the order of the data as well, so in fact the Distance scale ends up at the side of the chart, while it should be at the bottom of it, like here:
proper data order but with horizontal gridlines
My question is: is there a way to make gridlines display vertically without switching the order of the data?
Here's the exemplary chart from Highcharts demo, where I would like to change the display of the gridlines:
$(function () {
$('#container').highcharts({
    chart: {
        type: 'spline',
        inverted: false
    },
    xAxis: {
        reversed: false,
        labels: {
            formatter: function () {
                return this.value + 'km';
            }
        },
    },
    yAxis: {
        title: {
            text: 'Temperature'
        },
        labels: {
            formatter: function () {
                return this.value + '°';
            }
        },
    },
    legend: {
        enabled: false
    },
    series: [{
        name: 'Temperature',
        data: [[0, 15], [10, -50], [20, -56.5], [30, -46.5], [40, -22.1],
            [50, -2.5], [60, -27.7], [70, -55.7], [80, -76.5]]
    }]
});

PS I would prefer not to tamper with the order of the data that's being passed to the function.

A: Have you consider using xAxis.gridLineWidth and xAxis.gridLineColor parameters?
http://api.highcharts.com/highcharts/xAxis.gridLineWidth
http://api.highcharts.com/highcharts/xAxis.gridLineColor
$(function() {
  $('#container').highcharts({
    chart: {
      type: 'spline',
      inverted: false
    },
    xAxis: {
      reversed: false,
      gridLineWidth: 1,
      labels: {
        formatter: function() {
          return this.value + 'km';
        }
      },
    },
    yAxis: {
      title: {
        text: 'Temperature'
      },
      gridLineWidth: 0,
      labels: {
        formatter: function() {
          return this.value + '°';
        }
      },
    },
    legend: {
      enabled: false
    },
    series: [{
      name: 'Temperature',
      data: [
        [0, 15],
        [10, -50],
        [20, -56.5],
        [30, -46.5],
        [40, -22.1],
        [50, -2.5],
        [60, -27.7],
        [70, -55.7],
        [80, -76.5]
      ]
    }]
  });
});

Here you can see an example how it can work:
http://jsfiddle.net/r3wd8j7t/1/


text:
Q: get images in json files I'm trying to create a PWA interface in my symfony app, right now I'm creating the manifest.json and trying to call images from the manifest to define the icons but instead of searching inside my public folder for the images, it's taking the path as a URL
Same problem happens in my sw.js file, since I can't link the pages and files that I want to cache
my manifest.json:
 {
    "name": "Hello World",
    "short_name": "Hello",
    "icons": [{
        "src": "Agentassets/images/hello-icon-128.png",
          "sizes": "128x128",
          "type": "image/png"
        }, {
          "src": "Agentassets/images/hello-icon-144.png",
          "sizes": "144x144",
          "type": "image/png"
        }, {
          "src": "Agentassets/images/hello-icon-152.png",
          "sizes": "152x152",
          "type": "image/png"
        }, {
          "src": "Agentassets/images/hello-icon-192.png",
          "sizes": "192x192",
          "type": "image/png"
        }, {
          "src": "Agentassets/images/hello-icon-256.png",
          "sizes": "256x256",
          "type": "image/png"
        }, {
          "src": "Agentassets/images/hello-icon-512.png",
          "sizes": "512x512",
          "type": "image/png"
        }],
    "lang": "en-US",
    "start_url": "Agent/Agent.html.twig",
    "display": "standalone",
    "background_color": "white",
    "theme_color": "white"
  }

and here's my sw.js
var cacheName = 'hello-pwa';
var filesToCache = [
  "Agent/Agent.html.twig",
  'AgentInterface/css/style.css',
  'AgentInterface/js/main.js'
];

/* Start the service worker and cache all of the app's content */
self.addEventListener('install', function(e) {
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      return cache.addAll(filesToCache);
    })
  );
});

/* Serve cached content when offline */
self.addEventListener('fetch', function(e) {
  e.respondWith(
    caches.match(e.request).then(function(response) {
      return response || fetch(e.request);
    })
  );
});


text:
Q: Can I use elevated permissions using JSOM, CSOM, or REST? I am working with an On-Premise SharePoint 2016 farm and I am looking for some way to elevate permissions, so I don't use the logged-in user's credentials but another set of permissions that the logged in user doesn't have themselves. This is internal, so I am not looking for a 100% secure way to do this.

A: Sorry, but there is no way to run at elevated privileges from the client-side, and if there was a way, it would be roughly 0% secure.
Depending on what you're trying to achieve, there are some ways that you might be able to work around it.

*

*For instance, if you can do it from a workflow, SharePoint 2010
workflows can do an impersonation step which runs as the user who
published the workflow.

*And SharePoint 2013 workflow can do an App
step and be granted permissions that are beyond the current user's
permission (I haven't actually done this one, so my description may not be entirely accurate).

*Finally, if you have the luxury of deploying server side code, you can expose limited functionality through your own web services running at elevated, and then call them from the client-side (though I'm guessing this isn't an option for you).


text:
Q: Headers issue (Angular): server responds with 401 and 200 in the same request? I have this small app asking a service to an API. I have set the credentials like this:
this.http.get<Response>(url, {
        headers: new HttpHeaders().set('Authorization', 'Basic '
        + btoa('C7YHKF91RAABYXNK :JMGYBMAT1X18KA2W '))
      })
        .subscribe(data => {
          Response = data['results'];

But the logs are "strange":

There's a 401 and then a 200 and the API is not returning what was suposed to return (a png image). On Edge, when I hit submit, the browser asks for the token. I input the credentials and then the service works (chrome is similar)...Yesterday everything was working fine, but now I have this problem. Is it the API? Are the headers wrongly set up? I have a live demo for testing here. Thanks for the help!
EDIT as suggested by @Mudassar
onSubmit({ valid }: { valid: boolean }, f: any) {

    if {//
    }
    else {

      let color = encodeURIComponent(this.params.handwriting_color);
      const url =
        `https://api.handwriting.io/render/png?handwriting_id=${this.params.handwriting_id}&text=${this.params.text}&handwriting_size=${this.params.handwriting_size}&handwriting_color=${color}`;

      //SET HEADERS
      let headers= new HttpHeaders();
      headers.append('Authorization', 'Basic ' + btoa('C7YHKF91RAABYXNK :JMGYBMAT1X18KA2W '))
headers.append("Access-Control-Allow-Origin", "new[] { (string)context.Request.Headers['Origin'] }");
      headers.append("Access-Control-Allow-Headers", "new[] { 'Origin, X-Requested-With, Content-Type, Accept, Authorization' }");
      headers.append("Access-Control-Allow-Methods", "new[] { 'GET, POST, PUT, DELETE, OPTIONS' }");
      headers.append("Access-Control-Allow-Credentials", "new[] { 'true' }");

      //REQUEST
      this.http.get<Response>(url, {
        headers: headers
      })
        .subscribe(data => {
          Response = data['results'];

        }, (err: HttpErrorResponse) => {
          if (err.error instanceof Error) {
            console.log('An error occurred:', err.error.message);
          } else {
            console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
            console.log(Response);
          }
        });
    }

But I still get the 401...

A: This might be due to not setting the CORS
Access-Control-Allow-Headers: Authorization

further setting this should ensure proper working
 headers.append("Access-Control-Allow-Origin", new[] { (string)context.Request.Headers["Origin"] });
 headers.append("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept, Authorization" });
 headers.append("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });
 headers.append("Access-Control-Allow-Credentials", new[] { "true" });

EDIT: Starting to feel the problem might be to do with the server side hence suggesting to add on the server side to expose the Authorization header.
 "Access-Control-Expose-Headers" : "Authorization"


text:
Q: UseCases or Interactors with Kt Flow and Retrofit Context
I started working on a new project and I've decided to move from RxJava to Kotlin Coroutines. I'm using an MVVM clean architecture, meaning that my ViewModels communicate to UseCases classes, and these UseCases classes use one or many Repositories to fetch data from network.
Let me give you an example. Let's say we have a screen that is supposed to show the user profile information. So we have the UserProfileViewModel:
@HiltViewModel
class UserProfileViewModel @Inject constructor(
    private val getUserProfileUseCase: GetUserProfileUseCase
) : ViewModel() {
    sealed class State {
        data SuccessfullyFetchedUser(
            user: ExampleUser
        ) : State()
    }
    // ...
    val state = SingleLiveEvent<UserProfileViewModel.State>()
    // ...
    fun fetchUserProfile() {
        viewModelScope.launch {
            // ⚠ We trigger the use case to fetch the user profile info
            getUserProfileUseCase()
                .collect {
                    when (it) {
                        is GetUserProfileUseCase.Result.UserProfileFetched -> {
                            state.postValue(State.SuccessfullyFetchedUser(it.user))
                        }
                        is GetUserProfileUseCase.Result.ErrorFetchingUserProfile -> {
                            // ...
                        }
                    }
                }
        }
    }
}

The GetUserProfileUseCase use case would look like this:
interface GetUserProfileUseCase {
    sealed class Result {
        object ErrorFetchingUserProfile : Result()
        data class UserProfileFetched(
            val user: ExampleUser
        ) : Result()
    }

    suspend operator fun invoke(email: String): Flow<Result>
}

class GetUserProfileUseCaseImpl(
    private val userRepository: UserRepository
) : GetUserProfileUseCase {
    override suspend fun invoke(email: String): Flow<GetUserProfileUseCase.Result> {
        // ⚠ Hit the repository to fetch the info. Notice that if we have more
        // complex scenarios, we might require zipping repository calls together, or
        // flatmap responses.
        return userRepository.getUserProfile().flatMapMerge {
            when (it) {
                is ResultData.Success -> {
                    flow { emit(GetUserProfileUseCase.Result.UserProfileFetched(it.data.toUserExampleModel())) }
                }
                is ResultData.Error -> {
                    flow { emit(GetUserProfileUseCase.Result.ErrorFetchingUserProfile) }
                }
            }
        }
    }
}

The UserRepository repository would look like this:
interface UserRepository {
    fun getUserProfile(): Flow<ResultData<ApiUserProfileResponse>>
}

class UserRepositoryImpl(
    private val retrofitApi: RetrofitApi
) : UserRepository {
    override fun getUserProfile(): Flow<ResultData<ApiUserProfileResponse>> {
        return flow {
            val response = retrofitApi.getUserProfileFromApi()
            if (response.isSuccessful) {
                emit(ResultData.Success(response.body()!!))
            } else {
                emit(ResultData.Error(RetrofitNetworkError(response.code())))
            }
        }
    }
}

And finally, the RetrofitApi and the response class to model the backend API response would look like this:
data class ApiUserProfileResponse(
    @SerializedName("user_name") val userName: String
    // ...
)

interface RetrofitApi {
    @GET("api/user/profile")
    suspend fun getUserProfileFromApi(): Response<ApiUserProfileResponse>
}

Everything has been working fine so far, but I've started to run into some issues when implementing more complex features.
For example, there's a use case where I need to (1) post to a POST /send_email_link endpoint when the user first signs in, this endpoint will check if the email that I send in the body already exists, if it doesn't it will return a 404 error code, and (2) if everything goes okay, I'm supposed to hit a POST /peek endpoint that will return some info about the user account.
This is what I've implemented so far for this UserAccountVerificationUseCase:
interface UserAccountVerificationUseCase {
    sealed class Result {
        object ErrorVerifyingUserEmail : Result()
        object ErrorEmailDoesNotExist : Result()
        data class UserEmailVerifiedSuccessfully(
            val canSignIn: Boolean
        ) : Result()
    }

    suspend operator fun invoke(email: String): Flow<Result>
}

class UserAccountVerificationUseCaseImpl(
    private val userRepository: UserRepository
) : UserAccountVerificationUseCase {
    override suspend fun invoke(email: String): Flow<UserAccountVerificationUseCase.Result> {
        return userRepository.postSendEmailLink().flatMapMerge {
            when (it) {
                is ResultData.Success -> {
                    userRepository.postPeek().flatMapMerge {
                        when (it) {
                            is ResultData.Success -> {
                                val canSignIn = it.data?.userName == "Something"
                                flow { emit(UserAccountVerificationUseCase.Result.UserEmailVerifiedSuccessfully(canSignIn)) }
                            } else {
                                flow { emit(UserAccountVerificationUseCase.Result.ErrorVerifyingUserEmail) }
                            }
                        }
                    }
                }
                is ResultData.Error -> {
                    if (it.exception is RetrofitNetworkError) {
                        if (it.exception.errorCode == 404) {
                            flow { emit(UserAccountVerificationUseCase.Result.ErrorEmailDoesNotExist) }
                        } else {
                            flow { emit(UserAccountVerificationUseCase.Result.ErrorVerifyingUserEmail) }
                        }
                    } else {
                        flow { emit(UserAccountVerificationUseCase.Result.ErrorVerifyingUserEmail) }
                    }
                }
            }
        }
    }
}

Issue
The above solution is working as expected, if the first API call to the POST /send_email_link ever returns a 404, the use case will behave as expected and return the ErrorEmailDoesNotExist response so the ViewModel can pass that back to the UI and show the expected UX.
The problem as you can see is that this solution requires a ton of boilerplate code, I thought using Kotlin Coroutines would make things simpler than with RxJava, but it hasn't turned out like that yet. I'm quite sure that this is because I'm missing something or I haven't quite learned how to use Flow properly.
What I've tried so far
I've tried to change the way I emit the elements from the repositories, from this:
...
    override fun getUserProfile(): Flow<ResultData<ApiUserProfileResponse>> {
        return flow {
            val response = retrofitApi.getUserProfileFromApi()
            if (response.isSuccessful) {
                emit(ResultData.Success(response.body()!!))
            } else {
                emit(ResultData.Error(RetrofitNetworkError(response.code())))
            }
        }
    }
...

To something like this:
...
    override fun getUserProfile(): Flow<ResultData<ApiUserProfileResponse>> {
        return flow {
            val response = retrofitApi.getUserProfileFromApi()
            if (response.isSuccessful) {
                emit(ResultData.Success(response.body()!!))
            } else {
                error(RetrofitNetworkError(response.code()))
            }
        }
    }
..

So I can use the catch() function like I'd with RxJava's onErrorResume():
class UserAccountVerificationUseCaseImpl(
    private val userRepository: UserRepository
) : UserAccountVerificationUseCase {
    override suspend fun invoke(email: String): Flow<UserAccountVerificationUseCase.Result> {
        return userRepository.postSendEmailLink()
            .catch { e ->
                if (e is RetrofitNetworkError) {
                    if (e.errorCode == 404) {
                        flow { emit(UserAccountVerificationUseCase.Result.ErrorEmailDoesNotExist) }
                    } else {
                        flow { emit(UserAccountVerificationUseCase.Result.ErrorVerifyingUserEmail) }
                    }
                } else {
                    flow { emit(UserAccountVerificationUseCase.Result.ErrorVerifyingUserEmail) }
                }
            }
            .flatMapMerge {
                userRepository.postPeek().flatMapMerge {
                    when (it) {
                        is ResultData.Success -> {
                            val canSignIn = it.data?.userName == "Something"
                            flow { emit(UserAccountVerificationUseCase.Result.UserEmailVerifiedSuccessfully(canSignIn)) }
                        } else -> {
                            flow { emit(UserAccountVerificationUseCase.Result.ErrorVerifyingUserEmail) }
                        }
                    }
                }
            }
        }
    }
}

This does reduce the boilerplate code a bit, but I haven't been able to get it working because as soon as I try to run the use case like this I start getting errors saying that I shouldn't emit items in the catch().
Even if I could get this working, still, there's way too much boilerplate code here. I though doing things like this with Kotlin Coroutines would mean having much more simple, and readable, use cases. Something like:
...
class UserAccountVerificationUseCaseImpl(
    private val userRepository: AuthRepository
) : UserAccountVerificationUseCase {
    override suspend fun invoke(email: String): Flow<UserAccountVerificationUseCase.Result> {
        return flow {
            coroutineScope {
                val sendLinksResponse = userRepository.postSendEmailLink()
                if (sendLinksResponse is ResultData.Success) {
                    val peekAccount = userRepository.postPeek()
                    if (peekAccount is ResultData.Success) {
                        emit(UserAccountVerificationUseCase.Result.UserEmailVerifiedSuccessfully())
                    } else {
                        emit(UserAccountVerificationUseCase.Result.ErrorVerifyingUserEmail)
                    }
                } else {
                    if (sendLinksResponse is ResultData.Error) {
                        if (sendLinksResponse.error == 404) {
                            emit(UserAccountVerificationUseCase.Result.ErrorEmailDoesNotExist)
                        } else {
                            emit(UserAccountVerificationUseCase.Result.ErrorVerifyingUserEmail)
                        }
                    } else {
                        emit(UserAccountVerificationUseCase.Result.ErrorVerifyingUserEmail)
                    }
                }
            }
        }
    }
}
...

This is what I had pictured about working with Kotlin Coroutines. Ditching RxJava's zip(), contact(), delayError(), onErrorResume() and all those Observable functions in favor of something more readable.
Question
How can I reduce the amount of boilerplate code and make my use cases look more Coroutine-like?
Notes
I know some people just call the repositories directly from the ViewModel layer, but I like having this UseCase layer in the middle so I can contain all the code related to switching streams and handling errors here.
Any feedback is appreciated! Thanks!
Edit #1
Based on @Joffrey response, I've changed the code so it works like this:
The Retrofit API layer keeps returning suspendable function.
data class ApiUserProfileResponse(
    @SerializedName("user_name") val userName: String
    // ...
)

interface RetrofitApi {
    @GET("api/user/profile")
    suspend fun getUserProfileFromApi(): Response<ApiUserProfileResponse>
}

The repository now returns a suspendable function and I've removed the Flow wrapper:
interface UserRepository {
    suspend fun getUserProfile(): ResultData<ApiUserProfileResponse>
}

class UserRepositoryImpl(
    private val retrofitApi: RetrofitApi
) : UserRepository {
    override suspend fun getUserProfile(): ResultData<ApiUserProfileResponse> {
        val response = retrofitApi.getUserProfileFromApi()
        return if (response.isSuccessful) {
            ResultData.Success(response.body()!!)
        } else {
            ResultData.Error(RetrofitNetworkError(response.code()))
        }
    }
}

The use case keeps returning a Flow since I might also plug calls to a Room DB here:
interface GetUserProfileUseCase {
    sealed class Result {
        object ErrorFetchingUserProfile : Result()
        data class UserProfileFetched(
            val user: ExampleUser
        ) : Result()
    }

    suspend operator fun invoke(email: String): Flow<Result>
}

class GetUserProfileUseCaseImpl(
    private val userRepository: UserRepository
) : GetUserProfileUseCase {
    override suspend fun invoke(email: String): Flow<GetUserProfileUseCase.Result> {
        return flow {
            val userProfileResponse = userRepository.getUserProfile()
            when (userProfileResponse) {
                is ResultData.Success -> {
                    emit(GetUserProfileUseCase.Result.UserProfileFetched(it.toUserModel()))
                }
                is ResultData.Error -> {
                    emit(GetUserProfileUseCase.Result.ErrorFetchingUserProfile)
                }
            }
        }
    }
}

This looks much more clean. Now, applying the same thing to the UserAccountVerificationUseCase:
interface UserAccountVerificationUseCase {
    sealed class Result {
        object ErrorVerifyingUserEmail : Result()
        object ErrorEmailDoesNotExist : Result()
        data class UserEmailVerifiedSuccessfully(
            val canSignIn: Boolean
        ) : Result()
    }

    suspend operator fun invoke(email: String): Flow<Result>
}

class UserAccountVerificationUseCaseImpl(
    private val userRepository: UserRepository
) : UserAccountVerificationUseCase {
    override suspend fun invoke(email: String): Flow<UserAccountVerificationUseCase.Result> {
        return flow {
            val sendEmailLinkResponse = userRepository.postSendEmailLink()
            when (sendEmailLinkResponse) {
                is ResultData.Success -> {
                    val peekResponse = userRepository.postPeek()
                    when (peekResponse) {
                        is ResultData.Success -> {
                            val canSignIn = peekResponse.data?.userName == "Something"
                            emit(UserAccountVerificationUseCase.Result.UserEmailVerifiedSuccessfully(canSignIn)
                        }
                        else -> {
                            emit(UserAccountVerificationUseCase.Result.ErrorVerifyingUserEmail)
                        }
                    }
                }
                is ResultData.Error -> {
                    if (sendEmailLinkResponse.isNetworkError(404)) {
                        emit(UserAccountVerificationUseCase.Result.ErrorEmailDoesNotExist)
                    } else {
                        emit(UserAccountVerificationUseCase.Result.ErrorVerifyingUserEmail)
                    }
                }
            }
        }
    }
}

This looks much more clean and it works perfectly. I still wonder if there's any more room for improvement here.

A: The most obvious problem I see here is that you're using Flow for single values instead of suspend functions.
Coroutines makes the single-value use case much simpler by using suspend functions that return plain values or throw exceptions. You can of course also make them return Result-like classes to encapsulate errors instead of actually using exceptions, but the important part is that with suspend functions you are exposing a seemingly synchronous (thus convenient) API while still benefitting from asynchronous runtime.
In the provided examples you're not subscribing for updates anywhere, all flows actually just give a single element and complete, so there is no real reason to use flows and it complicates the code. It also makes it harder to read for people used to coroutines because it looks like multiple values are coming, and potentially collect being infinite, but it's not the case.
Each time you write flow { emit(x) } it should just be x.
Following the above, you're sometimes using flatMapMerge and in the lambda you create flows with a single element. Unless you're looking for parallelization of the computation, you should simply go for .map { ... } instead. So replace this:
val resultingFlow = sourceFlow.flatMapMerge {
    if (something) {
        flow { emit(x) }
    } else {
        flow { emit(y) }
    }
}

With this:
val resultingFlow = sourceFlow.map { if (something) x else y }