text:
Q: Formulation of Transformation optics using a Material Manifold Dear Community,
recently, Transformation optics celebrates some sort of scientific revival due to its (possible) applications for cloaking, see e.g. Broadband Invisibility by Non-Euclidean Cloaking by Leonhard and Tyc.
Willie Wong explained to me in another thread how a so-called material manifold could be used to include the effects of nonlinear optics as some sort of effective metric $\tilde{g}$. Indeed, this should not only work in that case, the easiest example of such an approach should be transformation optics.
Bevore explaining what is meant with such a construction, I will formulate the question:
How can one understand transformation optics in terms of the material manifold?
The material manifold
The following explanations are directly linked to Willie's comments in the mentioned thread. Since I will formulate them on my own, mistakes might occur, which are in turn only related to me. Willie further gives the references Relativistic and nonrelativistic elastodynamics with small shear strains by Tahvildar-Zahdeh for a mathematical introduction and Beig & Schmidt's Relativistic Elasticity which is a very clear work.
Given a spacetime $(M,g)$ and a timelike killing vector field $\xi$, $g(\xi, \xi) = 0$ and a three-dimensional Riemannian material manifold $(N,h)$, the material map $\phi{:} M\rightarrow N$ for which $d\phi{(\xi)} = 0$ is an equivalence class mapping trajectories of point particles on $M$ onto one point in $N$. One can further define a metric $\tilde{g}$ as the pull-back of $h$, $\tilde{g}_{(x)}(X,Y) = h_{(\phi{(x)})}(d\phi{(X)}, d\phi{(Y)})$.
So, my question could be recast:

How can $\tilde{g}$ be used to explain transformation optics?

Sincerely
Robert
Edith adds some further thoughts:
Special case: Geometrical optics
Geometrical optics is widely used when wave-phenomena like interference do not play a major role. In this case we approach the question from relativity. I will scetch my thoughts in the following.
Minkowsky spacetime is described by the metric $\eta = \eta_{\mu\nu}dx^\mu dx^\nu$. Fixing coordinates, we can always bring it into the form
$$\eta = -c^2 dt^2 + d\mathbf{r}^2$$
where I explicitly kept the speed of light $c$ and differ between space and time.
Light rays can be described by null geodesics $v$ for which $\eta(v,v) = 0$, hence
$$\left( v^t \right)^2\eta_{tt} = \frac1{c^2} v^i v^j \eta_{ij}$$
Interpreting the speed of light not as a constant but as a function, $\frac1{c^2} = \epsilon_0\mu_0 \epsilon_r(x^\mu) \mu_r(x^\mu)$ (isotropic quantities assumed here, not tensorial ones - generaliziation is obvious but would blow up formulas here), we can directly interpret
$$\tilde{g} = \epsilon_0\mu_0 \epsilon_r(x^\mu) \mu_r(x^\mu)\eta_{ij}dx^i dx^j$$
where, as before, $i$ and $j$ correspond to space-coordinates only. Since $\epsilon_r$ and $\mu_r$ are functions, $\tilde{g}$ will correspond to a curved three dimensional space. Furthermore, the material manifold can be identified as
$$(d\phi)_i (d\phi)_j = \epsilon_r \mu_r \eta_{ij}$$
and has (under the given assumption of isotropy) the form of a conformal transformation, also discussed in another question.
I am not sure about refraction at jumps of $\epsilon_r$ and $\mu_r$ at this point - the formulation given makes only sense for differentiable quantities.
Now, what about full electrodynamics?

A: I am not an expert in this field, but I have done a fair amount of reading on covariant formulations electromagnetism in curved spacetime, and I happen to find using differential forms particularly useful. As genneth mentioned, formulating Maxwell's equations using the electromagnetic field tensor definitely seems like the way to go. This is a great intro to using geometric algebra in this type of formulation, but I think this one is the winner. I personally like the fact that no isotropy is assumed.
I would try to summarize it, but I really do not think I could do any better than the author in that second link.
----Pure undocumented speculation here----
My knowledge of this field is entirely from reading, so read at your own risk! I was asked how geometric algebra might help here. In geometric algebra, an basis $\gamma$ spans the your space in question. I think of them as a representation of direction--so if you wedge two of them you get an orientable 2D simplex, wedge three of them, and you get an orientable 3D simplex, and so forth. The electromagnetic field is spin 1, so its basis is $\gamma_i \wedge \gamma_j$ for all $i\not=j$. Then it is is a matter of sticking a number next to each of those $\gamma_i \wedge \gamma_j$ to represent to electromagnetic field. In goemetric algebra, B is "imaginary"--i.e. it is a three form. I prefer to keep it a sum of two forms and redefine the electromagnetic field tensor replacing E/c==>E so the units work out. Then, given an E and B field at each point in space, you can just "tack on" a
$\gamma_i \wedge \gamma_j$ and get an electromagnetic field tensor for your curved spacetime.
As you noted when posing your question, you can encode all the information concerning the permittivity and permeability in the "effective metric" of your spacetime. Then you can use:
$$\gamma_i \cdot \gamma_j=g_{ij}$$
to define your anticommutation relations.
Now you can define Maxwell's equation [sic]
$$\nabla F = J$$
where J is the current 3-form and $J_0=\rho$


text:
Q: Updating multiple values SQL, checking on values in update statement I am going through some unwanted behaviour in my code, and wonder if the order of which values are updated is important.
We have value x,y,z that are evaluated based on each other.
X is either 'I', 'U' or 'D'
Y is either 'J' or 'N'
Z is either 'J' or 'N'
which values that are valid is evaluated based on the other ones such as:
UPDATE values
SET X = CASE WHEN X IN ('I','U') AND (Y = 'N' OR Y IS NULL) THEN 'D'
             WHEN X = 'D' AND Y = 'J' THEN 'N'
ELSE X
END,
Y = CASE WHEN X IN ('I','U') AND (Y = 'N' OR Y IS NULL) THEN 'J'
         WHEN X = 'D' AND Y = 'J' THEN 'N'
ELSE Y
END,
Z = CASE WHEN X <> 'D' AND Z = 'J' THEN 'N'
ELSE Z
END

My question is, does the order of the cases affect the updates after, or not.
Would the updated X value be evaluated in the following cases?

A: Please note that the order of the columns in the SET clause of an update is meaningless.
The entire row is updated at once in an update statement, meaning you are validating your updates using the old values in the columns.
Here's a quick demo:
Create and populate sample table:
DECLARE @T AS TABLE
(
    A int,
    B int
)

INSERT INTO @T (A, B) VALUES (1, 2)

Update B to the value of A, and A to 3:
UPDATE @T
SET B = A,
    A = 3

SELECT A, B
FROM @T

-- Result:

A   B
3   1

Update A to 4, and B to the value of A:
UPDATE @T
SET A = 4,
    B = A

SELECT A, B
FROM @T

-- Result:

A   B
4   3

See it live on rextester.
What you can do is use a stored procedure or a prepared statement, and set the values on the table according to the parameters values:
CREATE PROCEDURE UpdateValues
(
    @X char(1),
    @Y char(1),
    @Z char(1)
)
AS

UPDATE [values]
SET X = CASE WHEN @X IN ('I','U') AND (@Y = 'N' OR @Y IS NULL) THEN 'D'
             WHEN @X = 'D' AND @Y = 'J' THEN 'N'
ELSE @X
END,
Y = CASE WHEN @X IN ('I','U') AND (@Y = 'N' OR @Y IS NULL) THEN 'J'
         WHEN @X = 'D' AND @Y = 'J' THEN 'N'
ELSE @Y
END,
Z = CASE WHEN @X <> 'D' AND @Z = 'J' THEN 'N'
ELSE @Z
END

This way, you will be setting the values on the table based on the new values and not on the old values.

redpajama_set_name: RedPajamaStackExchange


text:
Q: D3 update x coordinate element Given a linear scale with domain [0, 1] and range [0, window width], I would like to render ticksNumber = 5 vertical lines equally spaced.
So, I created the array ticksValues that contains the lines x coordinates computed as width * ticksValues[i].
Then I bind this array with the line DOM elements by index. What I would like to have is always 5 (or 6, depends by d3) lines equally spaced on the entire range that change because depends on the window width.
My code doesn't work, why? Seems like the data binding is not correct

const ticksNumber = 5

window.addEventListener('resize', getWindowSize)
function getWindowSize() {
  var width = window.innerWidth
  var height = window.innerHeight

  const xScale = d3.scaleLinear()
    .domain([0, 1])
    .range([0, width])
  const ticksValues = xScale.ticks(ticksNumber).map(d => d * width)

  const svg = d3.select('#svg')
  const grid = svg.append('g')
  grid
    .selectAll('line')
    .data(ticksValues, (d, i) => i)
    .enter()
    .append('line')
    .attr('x1', d => d)
    .attr('x2', d => d)
    .attr('y1', 0)
    .attr('y2', height)
    .attr('stroke', 'red')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg id="svg"></svg>

Here a codesandbox.

A: One issue is that the lines' positions are defined according to the window's width, but the SVG's width is not set. Define an explicit 100% width attribute to the SVG in order for all the lines to become displayed.
<svg id="svg" width="100%"></svg>

The last bar is going to be right at the limit of the viewport, hence not visible. Defining a margin fixes this problem. Example:
const margin = 50
var width = window.innerWidth - margin

This article shows good practices regarding margins in d3.
The formula used to compute position of lines seems correct. However, it is no necessary to bother with these details, as d3-scale does it for us.
let dataset = d3.range(ticksNumber) // [0, 1, 2, 3, 4]

xScale.domain(d3.extent(dataset))

// ...

selection.append('line')
  .attr('x1', d => xScale(d))
  // ...

Demo of this set of fixes in the snippet below.
Other issues with the sample code, not solved in this demo.

*

*a new grid of line is added on top of the existing ones each time the window is resized. Instead, the bars should be drawn once at page load. Then on resize, their x positions should be shifted.

*performance: window resize event listener should be debounced.

const ticksNumber = 5
  , margin = 50
  , dataset = d3.range(ticksNumber)

getWindowSize()

function getWindowSize() {
  var width = window.innerWidth - margin
  var height = window.innerHeight

  const xScale = d3.scaleLinear()
    .domain(d3.extent(dataset))
    .range([0, width])

  const svg = d3.select('#svg')
  const grid = svg.append('g')
  grid
    .selectAll('line')
    .data(dataset)
    .enter()
    .append('line')
    .attr('x1', d => xScale(d))
    .attr('x2', d => xScale(d))
    .attr('y1', 0)
    .attr('y2', height)
    .attr('stroke', 'red')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg id="svg" width="100%"></svg>

A: I fixed it. The merge selection was missing.
const grid = svg.append('g');
const update = grid.selectAll("line").data(ticksValues);
update.enter()
  .append("line")
  .merge(update)
  .attr("x1", d => this.xScale(d))
  .attr("x2", d => this.xScale(d))
  .attr("y1", 0)
  .attr("y2", height);


text:
Q: python-escpos QS Printer not printing My QS-5801 printer doesn't print out. My PC is running on Windows 10, have Python 2.7 and python-escpos installed. I tried this but it's not working.
>>>from escpos.printer import Serial
>>>ser = Serial('COM3', 9600, timeout=1)
Serial printer enabled
>>>ser.text('hello world') #nothing happened

The printer itself is ESC/POS compatible. I'm connecting to it via USB (prolific USB-to-Serial Comm PORT (COM3)).

A: This is actually the expected behaviour for your snippet. The text remains in the printer's buffer until a line feed \n is sent to terminate the line of text.
Assuming that your printer is correctly listening on COM1, you probably just want to modify your snippet to include a newline-
from escpos.printer import Serial
ser = Serial('COM3', 9600, timeout=1)
ser.text("Hello world\n")

The python-escpos README contains an example of this usage.


text:
Q: How do you see Jupyter notebook on a microsoft/cntk docker? I just installed the microsoft/cntk docker image and I was wondering how can I see the Jupyter notebook interface (in order to do the tutorials included in the docker image at /cntk/Tutorials) ?
For another docker image I simply did the following command:
docker run -d -p 8888:8888 -v /home/name/notebooks:/home/ds/notebooks dataquestio/python3-starter
and then I opened my browser and went to localhost:8888
Thank you

A: Thank you for raising this.
We have updated the Wiki on how to run Jupyter Notebooks in Docker containers.
See here: https://github.com/Microsoft/CNTk/wiki/CNTK-Docker-Containers#using-docker-container-to-run-cntk-jupyter-notebook-tutorials


text:
Q: Подпапки в Qt-проекте Столкнулся с необходимостью разнести файлы проекта по отдельным папкам/группам. К примеру, отдельно папка для гуек, отдельно для бизнес-логики и т.д. Уверен, что это можно сделать, но в упор не вижу, куда тыкать в QtCreator'е. Подскажите, пожалуйста.

A: Если речь идёт о внутренних ресурсах приложения, хранящихся а .qrc, то просто создай подпапки в директории проекта, перекинь туда файлы и заново добавь через "ПКМ"->"Выбрать существующие файлы" по файлу qrc


text:
Q: Open and exe and keeping it open - standalone exe opens just fine I have an exe (a console app) that runs just fine when I double click on it.
It sits in a folder on my local c:\ and I would like a c# winform button to open it, but it opens and closes.
My code for winform button is as simple as follows:
System.Diagnostics.Process.Start("C:\\Users\\" + Environment.UserName + "\\myFolder\\myExe.exe");

What am I missing that would make my myExe.exe open just as if I was doubleclicking on the executable? (opens and stays open)
Thanks to all in advance.


text: Q: SSRS Visual Studio I am using Visual Studio 2022 Community Edition to connect to PostgreSql via ODBC to create  paginated reports. I could use Power BI Report Builder but I think the engine underneath is the same.  The paginated reports would pull in about 100 to 150 data items queried from materialized views that has are indexed. The materialized views normally have about 200,000 rows and 20 columns. The paginated reports have no charts, just numbers.  My question is why it takes 2 to 4 minutes to populate each paginated report in Visual Studio, but it takes less than 1 or 2 seconds to query in PgAdmin or DBeaver. I tried the same paginated reports in Power BI Report Builder but it is just as slow. I would be grateful for any suggestion to speed up the paginated reports. Thank you!


text:
Q: how to pass apikey and assistant url instead of username and password in watson assistant using curl I want to pass apikey and url instead of username and password, to connect watson assistant with my webpage.
// Encode json data
    $json = json_encode($data, JSON_UNESCAPED_UNICODE);

    // Post the json to Watson Assistant API via cURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, 'https://gateway.watsonplatform.net/assistant/api/v1/workspaces/'.$workspace_id.'/message?version='.$release_date); //
    curl_setopt($ch, CURLOPT_USERPWD, $username.":".$password); // Set cURL Watson
    curl_setopt($ch, CURLOPT_POST, true );
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    $result = trim(curl_exec($ch));
    curl_close($ch); // Close
    echo json_encode($result, JSON_UNESCAPED_UNICODE); // Send response
  }

Here i would like to replace username and password with corresponded Apikey and url .

A: Please try this. Instead of username, use the keyword "apikey" and for password use the actual API Key that you have for the service. That should work.


text:
Q: "Go get it" for sportsmanship lists questions where mine is the only answer The Sportsmanship badge is about upvoting other people's answers where you yourself also have an answer.
Now, I think "Go get it" on this kind of badge is questionable to begin with (i.e. it encourages artificial upvoting), but - it exists. The thing is, the questions it lists include questions where you've given the only answer, so you can't upvote anybody else.

A:
The thing is, the questions it lists include questions where you've given the only answer, so you can't upvote anybody else.

You could contribute an answer to a question that is already answered and upvote the current answer. Of course your answer must be quality as you need your own answer to get an upvote for it to count.

it encourages artificial upvoting

I think the point is to give you an incentive to vote for question you may be in competition with to recieve acceptance by the OP.


text:
Q: Delaying actions Im brand new to this Android game development, and i am currently trying to create a platform game. Is there a way to make certain actions (such as changing variable values) have a few second delay without the delaying mechanism halting eveything else? i have already tried
new Thread(){
public void run(){
    try {
        Thread.sleep(2000);
        //variable value change
    } catch (InterruptedException e) {
        e.printStackTrace();
        }
    }
}.start();

method which i found, but it seems like this method stops any background music that is running with it. Ive also tried the Handler method but it seems to crash the game. I am using libgdx framework.

A: You have to understand that your game is running in an endless loop. Usually you will endlessly get your render(float deltaTime) called by LibGDX.
You could either just do it yourself like this:
public void render(float deltaTime) {
    countDown -= deltaTime;
    if (countDown <= 0) {
        doSomething();
    }
}

Or you could use the Timer class of LibGDX instead like this:
float delay = 1; // seconds

Timer.schedule(new Task(){
    @Override
    public void run() {
        // Do your work
    }
}, delay);

A: If you plan on doing OpenGL game (I encourage you to), you have the Renderer class which has built int methods: onDrawFrame(GL10 gl), onSurfaceChanged(GL10 gl), onSurfaceCreated(GL10 gl), the one you're interested in is onDrawFrame(GL10 gl).
So, the template of your class that extends Renderer should be like this:
public class CustomRenderer extends Renderer {
    @Override
    public void onDrawFrame(GL10 gl) {
        try {
            Thread.sleep((float)(1000/60)); // 1000 milliseconds divided by 60 so you get 60fps
            //Your code here
        }
        catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onSurfaceChanged(GL10 gl) {
        //Your code here
    }
    @Override
    public void onSurfaceCreater(GL10 gl) {
        //Your code here
    }
}


text:
Q: No wireless detected, no drivers available I am running Ubuntu 11.04 32bit on a Lenovo E520 with a Intel WiFi Link 1000 BGN device.
Though Windows7 can connect itself to WiFi as well as being able to see other WiFi networks, Ubuntu can not.
When I went to additional driver, no drivers are on the list.
How can I connect my laptop to wireless network and use drivers in Ubuntu?

A: I'm a bit late for this, but if someone arrives here looking for this question, here is the answer. It worked for me in Ubuntu 11.04 and 11.10.
Open a  terminal and type
sudo modprobe -r acer_wmi

You should be able to connect to the wireless till next reboot.

*

*Making the change permanent

Edit the file /etc/modprobe.d/blacklist.conf with your favorite text editor, ie gksu gedit /etc/modprobe.d/blacklist.conf, and add this line at the end of the file
blacklist acer_wmi

Reboot and you're done.
Please note: This applies to wireless card having rtl8188ce chipset. You can view that by typing lspci in a terminal and searching for the entries respective to Network Controller.
The problem should be solved for Ubuntu 12.04.


text:
Q: Grid with two rows and scrollviewers I would like to have Grid with two rows. Rows should take only space needed for them (thats why Grid VerticalAlignment is set to Top). When there is not enough space to show both rows scrollbars should appear. I have tried different combinations with Auto, *, MinHeight etc. but without success.
<Window x:Class="WpfApplication5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:my="clr-namespace:WpfApplication5"
        Title="MainWindow" Height="388" Width="525" FontSize="25">
    <Grid VerticalAlignment="Top">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <ScrollViewer Grid.Row="0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <Border Height="100" Background="Red" >
                <StackPanel>
                    <TextBlock Text="1"/>
                    <TextBlock Text="2"/>
                    <TextBlock Text="3"/>
                    <TextBlock Text="4"/>
                </StackPanel>
            </Border>
        </ScrollViewer>
        <ScrollViewer Grid.Row="1"  HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <Border Background="Green" >
                <StackPanel>
                    <TextBlock Text="1" />
                    <TextBlock Text="2"/>
                    <TextBlock Text="3"/>
                    <TextBlock Text="4"/>
                    <TextBlock Text="5"/>
                    <TextBlock Text="6"/>
                    <TextBlock Text="7"/>
                    <TextBlock Text="8"/>
                    <TextBlock Text="9"/>
                    <TextBlock Text="10"/>
                </StackPanel>
            </Border>
        </ScrollViewer>
    </Grid>
</Window>

EDIT Check this image. Why there is not 4 in first row, why there is empty space at bottom.

A: <Border Height="100" Background="Red" >

Height="100" makes the content in the 1st row no.4 to hide inside.  Also, you have made the rows in to two equal parts, however the content is not equal which leaves empty space at the bottom of the window.

A: There is no solution out of the box, because it depends on what ratio you want between the two scrollviewers, in my example I choose 50/50:
<Window x:Class="WpfApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">

<Canvas x:Name="OverallCanvas" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
    <Grid x:Name="OverallGrid" Width="{Binding ElementName=OverallCanvas, Path=ActualWidth}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <ScrollViewer x:Name="Scroll1" Grid.Row="0" VerticalScrollBarVisibility="Auto">
            <StackPanel x:Name="Control1" Background="Red">
                <TextBlock Text="1.1"/>
                <TextBlock Text="1.2"/>
                <TextBlock Text="1.3"/>
                <TextBlock Text="1.4"/>
                <TextBlock Text="1.5"/>
            </StackPanel>
        </ScrollViewer>
        <ScrollViewer x:Name="Scroll2" Grid.Row="1" VerticalScrollBarVisibility="Auto">
            <StackPanel x:Name="Control2" Background="Green">
                <TextBlock Text="2.1"/>
                <TextBlock Text="2.2"/>
                <TextBlock Text="2.3"/>
                <TextBlock Text="2.4"/>
                <TextBlock Text="2.5"/>
                <TextBlock Text="2.6"/>
                <TextBlock Text="2.7"/>
                <TextBlock Text="2.8"/>
                <TextBlock Text="2.9"/>
                <TextBlock Text="2.10"/>
            </StackPanel>
        </ScrollViewer>
    </Grid>
</Canvas>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        this.SizeChanged += MainWindow_SizeChanged;
        Control1.SizeChanged += MainWindow_SizeChanged;
        Control2.SizeChanged += MainWindow_SizeChanged;
    }

    private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        UpdateScrollHeight();
    }

    private void UpdateScrollHeight()
    {
        double overallHeight = OverallCanvas.ActualHeight;
        double c1Height = Control1.ActualHeight + Control1.Margin.Top + Control1.Margin.Bottom;
        double c2Height = Control2.ActualHeight + Control2.Margin.Top + Control2.Margin.Bottom;

        if (overallHeight - c1Height - c2Height < 0)
        {
            double halfHeight = overallHeight / 2;
            double c1Additional = Math.Max(0, halfHeight - c2Height);
            double c2Additional = Math.Max(0, halfHeight - c1Height);
            Scroll1.MaxHeight = halfHeight + c1Additional;
            Scroll2.MaxHeight = halfHeight + c2Additional;
        }
        else
        {
            Scroll1.MaxHeight = double.PositiveInfinity;
            Scroll2.MaxHeight = double.PositiveInfinity;
        }
    }
}

I only used the canvas to measure the size available inside the window, this could be done differently as well ...


text:
Q: Incompatibilidade android 4.4.2 com ionic 2 Fiz um aplicativo em ionic 2 e tudo funciona perfeitamente, porém, um usuário ao utilizar no celular com android 4.4.2, algumas funcionalidades, como por exemplo, o upload de arquivos, não funciona.
Não gera erros, simplesmente não faz o upload.
Além do tempo do loading inicial, antes do splash, demorar quase 1 minuto para carregar.
Alguém tem alguma ideia se é alguma incompatibilidade do ionic com essa versão do android?


text:
Q: Overriding print statement in java based on object class I have the following code in Java
I am able to print the calculated values in printDistance method.
Output:
4.0
3.0
But I need the output in below format(Expected Output).Please help
3D Distance = 4.0
2D Distance = 3.0
 public class Point2D {

    double x;
    double y;

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }

    public Point2D(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public double dist2D(Point2D p) {
        x = (int) Math.ceil(Math.sqrt(Math.pow((p.getX() - x), 2) + Math.pow((p.getY() - y), 2)));
        return x;
    }

    public static void printDistance(double d) {
        System.out.println(d);
    }

    static public void main(String args[]) {
        Point3D obj1 = new Point3D(1.0, 2.0, 3.0);
        Point3D obj2 = new Point3D(3.0, 4.0,5.0);
        printDistance(obj1.dist3D(obj2));
        printDistance(obj1.dist2D(obj2));
    }
}

class Point3D extends Point2D {

    double z;

    public double getZ() {
        return z;
    }

    public Point3D(double x, double y, double z) {
        super(x, y);
        this.z = z;
    }

    public double dist3D(Point3D p) {
        return (int) Math.ceil(Math.sqrt(Math.pow((p.getX() - x), 2) + Math.pow((p.getY() - y), 2) + +Math.pow((p.getZ() - z), 2)));
    }
}

A: You can do it as follows:
public class Point2D {

    double x;
    double y;

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }

    public Point2D(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public String dist2D(Point2D p) {
        x = (int) Math.ceil(Math.sqrt(Math.pow((p.getX() - x), 2) + Math.pow((p.getY() - y), 2)));
        return "2D Distance = "+x;
    }

    public static void printDistance(String d) {
        System.out.println(d);
    }

    static public void main(String args[]) {
        Point3D obj1 = new Point3D(1.0, 2.0, 3.0);
        Point3D obj2 = new Point3D(3.0, 4.0,5.0);
        printDistance(obj1.dist3D(obj2));
        printDistance(obj1.dist2D(obj2));
    }
}

class Point3D extends Point2D {

    double z;

    public double getZ() {
        return z;
    }

    public Point3D(double x, double y, double z) {
        super(x, y);
        this.z = z;
    }

    public String dist3D(Point3D p) {
        return  "3D Distance = "+ Math.ceil(Math.sqrt(Math.pow((p.getX() - x), 2) + Math.pow((p.getY() - y), 2) + +Math.pow((p.getZ() - z), 2)));
    }
}

Output:
3D Distance = 4.0
2D Distance = 3.0


text:
Q: How to use python to send emails with multiple attachments I can't get this to attach multiple documents to an email. It attaches the first document and then sends the document. I am a noob when it comes to using the auto-email function. Could anyone explain this or show me how to fix this?
    self.name = name
    fromaddr = "Your Email"
    toaddr = "Sending Email"
    msg = MIMEMultipart()
    #email address
    msg['From'] = fromaddr
    # Receivers email address
    msg['To'] = toaddr
    #subject
    msg['Subject'] = ' Weekly Report'
    #body of the mail
    body = 'Hey, I\'m testing the automated email function, let me know if you get it and how does it look!'
    #msg instance
    msg.attach(MIMEText(body, 'plain'))
    # open the file to be sent
    a = 0
    for i in self.name:
        while a < len(self.name):
            filename = i + '.pdf'
            attachment = open(i + '.pdf', "rb")
            a+=1
            print(len(self.name))
            print(a)
    p = MIMEBase('application', 'octet-stream')
    p.set_payload((attachment).read())
    encoders.encode_base64(p)
    p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
    msg.attach(p)
    s = smtplib.SMTP('smtp.gmail.com', 587)
    s.starttls()
    s.login(fromaddr, "password")
    text = msg.as_string()
    s.sendmail(fromaddr, toaddr, text)
    s.quit()

A: Try this (Reference:- https://dzone.com/articles/send-email-attachments-python)
import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
  assert type(send_to)==list
  assert type(files)==list

  msg = MIMEMultipart()
  msg['From'] = send_from
  msg['To'] = COMMASPACE.join(send_to)
  msg['Date'] = formatdate(localtime=True)
  msg['Subject'] = subject

  msg.attach( MIMEText(text) )

  for f in files:
    part = MIMEBase('application', "octet-stream")
    part.set_payload( open(file,"rb").read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
    msg.attach(part)

  smtp = smtplib.SMTP(server)
  smtp.sendmail(send_from, send_to, msg.as_string())
  smtp.close()


text:
Q: Error in setting up ionic project I am unable to create an Ionic project. I get an error when i run npm install command. I am new to Ionic project so kindly guide me if i am wrong.
The problem is this, if I create a blank ionic project:
ionic start myProjectName1 blank --type ionic1
It will successfully download (app base, starter template and resources)
https://github.com/ionic-team/ionic-app-base/archive/master.tar.gz
 https://github.com/ionic-team/ionic-starter-blank/archive/master.tar.gz
https://github.com/ionic-team/ionic-default-resources/archive/master.tar.gz

Then the npm install kicks off. It attempts to download a sass binary that doesn't exist (404 error):
https://github.com/sass/node-sass/releases/download/v3.13.1/win32-x64-57_binding.node

I have checked from
https://github.com/sass/node-sass/releases/download

and version 3.13.1 does not exist


text:
Q: How to expand (fully reveal) the Steam launch options? With Titan Quest for instance, some launch option titles cut off essentially after the game name. The modal window can't be expanded (by dragging from the edges) and there's no tooltip text. There's no easy way to always select the preferred option.
The only way I'm aware of is to view the options  on SteamDB (steamdb.info/app/<app ID>/config/), and perhaps by parsing local Steam configuration files.

Steam build Jan 16 2022, Linux (settings → interface → 'enlarge text and icons based on monitor size' is enabled, essentially mandatory on 4K displays)


text:
Q: how to scrape all links from a page in r I want to scrape all the division links from a website, but I keep getting NAs. Any ideas on a fix?
library(rvest)
library(tidyverse)

pageMen = read_html('https://www.bjjcompsystem.com/tournaments/1869/categories')

get_links <- pageMen %>% html_nodes('.panel-default') %>% html_attr('href')
get_links

By adjusting the above, I managed to scrape one link, but cannot find where all the other links are contained when I inspect the elements
get_links <- pageMen %>% html_elements(xpath = '/html/body/div[3]/div/div/div/ul/li[1]/a') %>% html_attr('href') %>% paste0('https://www.bjjcompsystem.com',.)
get_links

A: You could do
library(rvest)
library(tidyverse)

pageMen = read_html('https://www.bjjcompsystem.com/tournaments/1869/categories')

get_links <- pageMen %>%
  html_nodes('.categories-grid__category a') %>%
  html_attr('href') %>%
  paste0('https://www.bjjcompsystem.com', .)

get_links[1:5]
#> [1] "https://www.bjjcompsystem.com/tournaments/1869/categories/2053146"
#> [2] "https://www.bjjcompsystem.com/tournaments/1869/categories/2053150"
#> [3] "https://www.bjjcompsystem.com/tournaments/1869/categories/2053154"
#> [4] "https://www.bjjcompsystem.com/tournaments/1869/categories/2053158"
#> [5] "https://www.bjjcompsystem.com/tournaments/1869/categories/2053162"


text:
Q: Can I write Ruby code that is executed only when my script is run, but not when it is required? I want to write a Ruby script something like this:
class Foo
  # instance methods here

  def self.run
    foo = Foo.new
    # do stuff here
  end
end

# This code should only be executed when run as a script, but not when required into another file
unless required_in?  # <-- not a real Kernel method
  Foo.run
end
# ------------------------------------------------------------------------------------------

I want to be able to unit test it, which is why I don't want the code outside of the class to run unless I execute the script directly, i.e. ruby foo_it_up.rb.
I know I can simply put the Foo class in another file and require 'foo' in my script. In fact, that is probably a better way to do it, just in case Foo's functionality is needed somewhere else. So my question is more academic than anything, but I'd still be interested in knowing how to do this in Ruby.

A: This is usually done with
if __FILE__ == $0
  Foo.run
end

but I prefer
if File.identical?(__FILE__, $0)
  Foo.run
end

because programs like ruby-prof can make $0 not equal __FILE__ even when you use --replace-progname.
$0 refers to the name of the program ($PROGRAM_NAME), while __FILE__ is the name of the current source file.


text:
Q: applet works on debian but not windows [mousePressed doesn't execute] I wrote a java applet and put it up on a server.
When I visit the page from debian/iceweasel the thing works perfectly.
When I visit the same page from windows/firefox the applet loads and runs but the code from the mousePressed and mouseEntered methods doesn't execute. MouseClicked works fine, though.
Has anyone had that problem?
What other info do you need to tackle the problem? Do you need the code? The html of the page?
The applet is here:
http://whackamile.byethost3.com/
If you could go there and tell me your OS/browser combo and whether it works, that would be great! (the cursor is supposed to change when the mouse enters "mole" and it should be clickable)

A: It was my custom cursor icon size/position. Windows, apparently, has a 32x32 limit.


text:
Q: WPF ComboBox...how to set the .Text property? Is there a way to set the .Text property of the Wpf ComboBox control directly?
My combobox is bound to a List<T> collection, but when I try to set .Text property in the DropDownClosed event, it totally ignores it.

A: If you're trying to set the text to the text of one of the items in the list it should work correctly.
If you're trying to set it to an item that isn't in the list then the IsEditable property needs to be true. You can set the IsReadOnly property to true if you don't actually want users typing into the combo box.
If none of these cases fit you, can you post the code you're using?

A: You can also try adding one more ComboBoxItem with Visibility=Collapsed, set that one as the selected item and set its content to whatever is needed.


text:
Q: Xorg: High CPU Usage (94%) on Moving Mouse (Ubuntu 18.04) whenever I move my mouse enough it causes high cpu usage. Screenshot provided is on a fresh X session.
Xorg Taking up a lot of CPU
This also causes some frequent freeze ups if I'm running some other programs e.g gaming.
[1075299.085] (II) event4  - Corsair Corsair Vengeance M90 Mouse: SYN_DROPPED event - some input events have been lost.
[1077813.434] (II) event4  - Corsair Corsair Vengeance M90 Mouse: SYN_DROPPED event - some input events have been lost.
[1077814.079] (II) event4  - Corsair Corsair Vengeance M90 Mouse: SYN_DROPPED event - some input events have been lost.
[1077814.246] (II) event4  - Corsair Corsair Vengeance M90 Mouse: SYN_DROPPED event - some input events have been lost.
[1077814.682] (II) event4  - Corsair Corsair Vengeance M90 Mouse: SYN_DROPPED event - some input events have been lost.
[1077831.975] (EE) client bug: timer event4 debounce: offset negative (-18ms)
[1077831.975] (II) event4  - Corsair Corsair Vengeance M90 Mouse: SYN_DROPPED event - some input events have been lost.
[1077831.975] (II) event4  - Corsair Corsair Vengeance M90 Mouse: WARNING: log rate limit exceeded (5 msgs per 30000ms). Discarding future messages.
[1120008.128] (II) event4  - Corsair Corsair Vengeance M90 Mouse: SYN_DROPPED event - some input events have been lost.

Is there any way for the CPU usage not to be this high?
EDIT:
I tried with other mice. The CPU usage appears to increase with the Mouse DPI or to be exact, a generic mouse will cause a CPU usage spike, but not as much as a gaming mouse.
I also checked if I have hardware acceleration enabled.
$ glxinfo | grep "direct rendering"
direct rendering: Yes

EDIT 2:
CPU is an AMD FX-6350
GPU is AMD RX Vega 56

A: You could try changing the mouse polling rate parameter on the usbhid Kernel module. You can modify its value on the fly by running as super user
echo "4" > /sys/module/usbhid/parameters/mousepoll

This changes the polling rate from the default value 0 (i.e. "unlimited") to 4 ms (or 250 Hz).
Note: Afterwards you will have to replug your mouse in order to see any effect.
Provided that helps, you could make this change permanent by appending the parameter to the line GRUB_CMDLINE_LINUX_DEFAULT in /etc/default/grub like so
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash usbhid.mousepoll=4"

Then run
update-grub

and
reboot


text:
Q: Optimization in sql server query My Below query in my stored procedure takes more time.Is there any way to optimize this below query.Input parameters are Name and CA.
SELECT @E_ID=vb.e_id
FROM VALUES va, mappings im, VALUES va2
WHERE im.pv_name=vb.value
AND va.E_ID in (select e_id from listings where id = 200)
AND va.f_id=100
AND va2.f_id=101 AND va.e_id=va2.e_id
AND im.w_i_name='"'+@NAME+'"' AND va2.value='["'+@CA+'"]'
ORDER BY va.e_id

A: We see now that contrary to the popular opinion, IN / EXISTS queries are not less efficient than a JOIN query in SQL Server. But JOIN queries are less efficient on non-indexed tables. I'm not sure, but you can modify as following this:
SELECT @E_ID=vb.e_id
FROM VALUES va, mappings im, VALUES va2
join (select e_id from listings where id = 200) tmp on tmp.e_id = va.E_ID
WHERE im.pv_name=vb.value

A: The first thing I would do is to make sure is that every single field mentioned in the WHERE clause and in the ORDER BY clause is indexed.
The second thing I would do is try the following:
...
LEFT JOIN listings on va.E_ID = listings.e_id WHERE listings.id = 200
...

(Though I would be surprised if the query optimizer does not take care of this.)
The third thing I would do is try the following:
...
(SELECT * FROM VALUES WHERE f_id=100) va,
(SELECT * FROM VALUES WHERE f_id=101) va2,
...


text:
Q: Regex matching or array search Suppose I have 60 words and I want to check if an input is any of these words

Which is faster:
1) making a regex and ORing the words in it
2) looping on an array and searching?

A: You can easily test this yourself. Out of curiosity, I created a test case of four different scenarios:

*

*Pattern.matcher().matches() with an on-demand Pattern instance (created for each run)

*Pattern.matcher().matches() with a cached Pattern instance (created before all runs)

*String.equals() for each element in the array, executed within a loop

*Set.contains() on a cached Set (created before all runs)

Data Set: Input array containing 6000 randomly generated strings of 6 characters each. Each test was executed 10,000 times, the results of all runs were totaled and averaged.
The results (all times in ms - lower is obviously better). The first number is the total execution time of all 10,000 runs, the second number is the average of each run:
On-Demand Regex:    12934 (1.29 avg)
Pre-compile Regex:    458 (0.05 avg)
Loop:                  77 (0.01 avg)
Set.contains:           4 (0.00 avg)

Long story short: if you're going to use a regular expression (which you shouldn't) at least create and cache the Pattern. But assuming performance is what matters, you're not going to beat Set.contains() if you know the list of words ahead of time.
Note The On-demand regex test includes the cost of constructing the StringBuilder instance that is given to the Pattern.compile() method, so not necessarily all of the extra time is spent in regex compilation. The Set.contains test also has a slight advantage in that it's inlined, and avoids the extra stack creation of the method call. I modified the test to have that execute inside of a separate method, but it didn't materially affect the results.


text:
Q: ffmpeg truncates paths on output when there are dots involved when run on bash If I have a path with dots in the path, for instance:
/home/user/Documents/hello/test.testing_23-24.123/test.testing_23-24.124

ffmpeg can locate the file if you pass the file's path as an argument but it will truncate the path name to the first dot it encounters in the file's path when it outputs the file.
For instance, I got this:
#!/bin/sh
src_folder=`pwd`

for filename in "${src_folder}"/*.MP4
  do
    ffmpeg -threads 0 -probesize 100M -analyzeduration 100M -i "${filename}" \
      -c:v libx265 -preset medium -pass 1 -tune grain -x265-params "crf=28:pmode=yes" \
      -c:a libmp3lame -q:a 9 -strict experimental "${filename%%.*}"_1stpass.mkv
  done

The output states:
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/home/user/Documents/hello/test.testing_23-24.123/test.testing_23-24.124/GOPR2103.MP4':

[..]

Output #0, matroska, to '/home/user/Documents/hello/test_hevc.mkv':

We see that the output file's folder path below:
 /home/user/Documents/hello/test.testing_23-24.123/test.testing_23-24.124

Gets truncated after ffmpeg encounters the first dot in it's output path. This only happens to the output's filename. Also it uses the truncated path as the filename.
Anyone that could point me in the right direction on how to solve this?
PS: I am aware that a bad workaround should be avoiding folders with dots :]

A: As Gyan pointed out in a comment, you've (unintentionally?) told the shell to strip as many characters as it can from the end of the file path until it finds the first dot/period; that's the meaning of %% followed by .*. You might have intended to strip off the "extension" of the filename (such as MP4), in which case you'd want to use a single %, which says to match the shortest number of characters.
Since you know that you're picking up MP4 files, you can further simplify the % expansion and simply ask it directly to strip off those 4 characters.
It's also a little pointless to expand pwd when the only thing you need it for is to gather filenames in the current directory.
Use something more like this:
for filename in ./*.MP4
  do
    ffmpeg -threads 0 -probesize 100M -analyzeduration 100M \
      -i "${filename}" \
      -c:v libx265 -preset medium -pass 1 -tune grain -x265-params \
      "crf=28:pmode=yes" -c:a libmp3lame -q:a 9 -strict experimental \
      "${filename%.MP4}"_1stpass.mkv
  done


text:
Q: Ubuntu Server 16.04 64bit had only 8Gb of RAM when 16GB are installed I have one DIMM installed on a Lenovo x3550 M5 server.
The OS is Ubuntu 16.04.2 64 bit uname -ra
Linux hostname 4.4.0-62-generic #83-Ubuntu SMP Wed Jan 18 14:10:15 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

free -hm gives:
              total        used        free      shared  buff/cache   available
Mem:           7.2G        238M        6.5G         20M        474M        6.7G
Swap:          7.4G          0B        7.4G

And sudo lshw -c memory gives:
*-memory
   description: System Memory
   physical id: 5
   slot: System board or motherboard
   size: 16GiB
 *-bank:0
      description: DIMM Synchronous 2133 MHz (0.5 ns)
      product: M393A2G40EB1-CPB
      vendor: Samsung
      physical id: 0
      serial: 88045A3F
      slot: Dimm 1
      size: 16GiB
      width: 64 bits
      clock: 2133MHz (0.5ns)

other banks are empty.
In the dmesg I do not see anything out of the ordinary:
 dmesg | grep memory
 [    0.000000] Scanning 1 areas for low memory corruption
 [    0.000000] Base memory trampoline at [ffff880000096000] 96000 size 24576
 [    0.000000] Early memory node ranges
 [    0.000000] PM: Registered nosave memory: [mem 0x00000000-0x00000fff]
 [    0.000000] PM: Registered nosave memory: [mem 0x0009c000-0x0009ffff]
 [    0.000000] PM: Registered nosave memory: [mem 0x000a0000-0x000dffff]
 [    0.000000] PM: Registered nosave memory: [mem 0x000e0000-0x000fffff]
 [    0.000000] PM: Registered nosave memory: [mem 0x432a8000-0x4b2affff]
 [    0.000000] PM: Registered nosave memory: [mem 0x4bfdd000-0x4bfebfff]
 [    0.000000] PM: Registered nosave memory: [mem 0x646b2000-0x793fefff]
 [    0.000000] PM: Registered nosave memory: [mem 0x793ff000-0x7b3fefff]
 [    0.000000] PM: Registered nosave memory: [mem 0x7b3ff000-0x7b787fff]
 [    0.000000] PM: Registered nosave memory: [mem 0x7b800000-0x8fffffff]
 [    0.000000] PM: Registered nosave memory: [mem 0x90000000-0xfed1bfff]
 [    0.000000] PM: Registered nosave memory: [mem 0xfed1c000-0xfed1ffff]
 [    0.000000] PM: Registered nosave memory: [mem 0xfed20000-0xfeffffff]
 [    0.000000] PM: Registered nosave memory: [mem 0xff000000-0xffffffff]
 [    0.043027] Initializing cgroup subsys memory
 [    0.044460] Freeing SMP alternatives memory: 32K (ffffffff820b8000 -  ffffffff820c0000)
 [    1.122178] Freeing initrd memory: 36936K (ffff8800337cc000 - ffff880035bde000)
 [    1.122674] Scanning for low memory corruption every 60 seconds
 [    2.616860] Freeing unused kernel memory: 1488K (ffffffff81f44000 - ffffffff820b8000)
 [    2.629739] Freeing unused kernel memory: 1792K (ffff880001840000 - ffff880001a00000)
 [    2.638571] Freeing unused kernel memory: 136K (ffff880001dde000 - ffff880001e00000)


text:
Q: Using CGEventTap to disable the keyboard I have found this:
Programmatically Disable Mouse & keyboard
But if I copy the code to an new proj and try build it it says build failed.
But there are no errors in the code it self.
Now my question is how i use event taps to do this (disable the keyboard)
Thanks for any suggestions. I'm new developing Mac OS X apps, so please forgive me if I ask something stupid.

A: This line gives your problem away (and you should have put this point in your original question):
Undefined symbols for architecture x86_64: "_MyEventTapCallBack

What this means is that wherever you defined MyEventTapCallBack isn't being linked into your application.
Check to make sure of case sensitivity (e.g. did you define it as "MyEventTapCallback" instead of "MyEventTapCallBack").
Also, if "MyEventTapCallBack" is defined in its own .m file, make sure the .m file is included as a member of the target. Check the file inspector on that .m file.  Where you see the red circles, make certain your target is checked.


text:
Q: How AspNet Identity with my model I'm trying to go through this tutorial on the External Authentication Services (C#). I need some initial explanations to go forward. Looking inside the default template that ships MVC5, I see this:
// You can add profile data for the user ...
public class ApplicationUser : IdentityUser
{
    public string HomeTown { get; set; }
    public DateTime? BirthDate { get; set; }
}

What if I want to call it User instead of ApplicationUser? Maybe I want to add a navigation properties so I can establish relationship with my other models? Also when I look at the table, the name is AspNetUsers instead of ApplicationUser. Finally, What if I want to use my own context?
Thanks for helping.

A:
1)What if I want to call it User instead of ApplicationUser?

You can change to any names you want, just make sure to replace ApplicationUser with the name.

2)Maybe I want to add a navigation properties so I can establish
  relationship with my other models?

If you have a class call Address, you want to add addressId as a foreign key, see below:
 public class Address
{
    public int Id { get; set; }
    public string Street { get; set; }
}

public class User : IdentityUser
{
    public string HomeTown { get; set; }
    public DateTime? BirthDate { get; set; }
    public int AddressId { get; set; }
    [ForeignKey("AddressId")]
    public virtual Address Address { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<User>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
    public DbSet<Address> Addresses { get; set; }
}

3)Also when I look at the table, the name is AspNetUsers instead of
  ApplicationUser.

ASP.NET Identity is inherited from the The ASP.NET membership system. When you register a new user
using the default template, AspNetUsers and AspNetUserRoles etc.. these tables are created by default.
You can modify these table name by modifying the IdentityModel.cs. For more detail take a look at the following link:
How can I change the table names when using Visual Studio 2013 ASP.NET Identity?

4)What if I want to use my own context?

You can create your own DBContex, MVC 5 allow you to have mutiple DBContext, such as ApplicationDbContext and DataDbContext(custom DbContext).
ApplicationDbContext usually contains ASP.NET Membership data table.
DataDbContext usually contains data tables unrelated to users.
public class Blog
{
    public int BlogId { get; set; }
    public int Title { get; set; }
}

public class MyDbContext : DbContext
{
    public MyDbContext()
        : base("DefaultConnection")
    {

    }
    public DbSet<Blog> Blogs { get; set; }
}

Note: You may need to use EF Migrations, see details here :
ASP.Net Identity customizing UserProfile


text:
Q: Eliminar Fila con Boton jquery Estoy llenando una tabla de uno en uno, pero en caso de no querer algun dato ya, simplemente se elimine, esta es mi tabl con jquery
 var row = '';
    row += '
';
    row += '' + XXXX+ '	';
    row += '' + XXXX+ '	';
    row += '' + XXX+ '	';
    row += '' + XXX+ '	';
    row += '<button  class="btn btn-danger" onclick=\"Eliminar(\'' + ID+ '\')\">Eliminar</button> 	';
$('#table').append(row);

Al dar clic en el boton eliminar mando como parametro el id de la fila que se quiere eliminar a una function
function Eliminar(ID)
{

    $("#table" + unidad).parent().parent().remove();

}

intento eliminar la fila de esta manera, pero no sucede nada, sin embargo si inspecciono el codigo, si esta tomando el Id.
de que manera puedo eliminar la fila?

A: Agrega una clase al boton y crea un manejador de click.  Luego, dentro del manejador utiliza this.  Asi:

var row = '';
    row += '
';
    row += 'XXXX	';
    row += 'XXXX	';
    row += 'XXX	';
    row += 'XXX	';
    row += '<button  class="btn btn-danger eliminar" >Eliminar</button> 	';
$('#table').append(row);

$(".eliminar").on("click", function() {
  $(this).parent().parent().remove();

});


text:
Q: PHP cant select radio button value im trying to get the value from radio button which was selected among other radio buttons. This is basically a calendar of month.
This is how i try to select the value.
$radio_value = $_POST['day'];
if(isset($_POST['get_value'])) {
for($i=1;$i<=$number;$i++) {
    if($radio_value == $i) {
    $_SESSION["value"] = $radio_value;
    }
}
}

This is how i create 30 radio buttons the $i variable is just for loop.
echo '<input name="day" type="radio" value="' . $i . '">' .$i.  '	';

All other html php related things work so this is the only problem.
EDIT
html form. form method is set to post and action is the php file so no problem here either.
<input type="submit" name="get_value" value="Patvirtinti"> &  nbsp;
<input type="submit" name="valyti_forma" value="Valyti forma">

I will try to explain this so you can understand.
I get $number value from cal_days_in_month. When i have the $number then i run a loop to create as many radio buttons as the value is. And then when i click the radio button and press my submit button i want to print that radio button value which is 1,2,3 etc(its a day in a month). Hope this is clear enough.


text:
Q: No owner defined between domain classes Currently i'm getting the following error :
No owner defined between domain classes [class mp.ra.Classgroup] and [class mp.ra.Event] in a many-to-many relationship.

The domain classes are set up as followed,
The event class:
class Event {
static hasMany = [classgroups:Classgroup]
static belongsTo = [eventgroup:Eventgroup,classgroup:Classgroup]

static constraints = {
    eventgroup nullable:true
}

And the Classgroup
class Classgroup {

static hasMany = [courses:Course,events:Event]

static constraints = {
    courses nullable:true
}

An Event can have multiple classgroups and a classgroup can have multiple events.
I use the belongs to property so i don't see why i'm getting this error.
EDIT: I changed The Event class and the error is gone , i dont know if this is a good solution
class Event {

Eventgroup eventgroup

static hasMany = [classgroups:Classgroup]
static belongsTo = [Eventgroup, Classgroup]

static constraints = {
    eventgroup nullable:true
}

A: In Grails many-to-many mapping we should define an owner class between both of the associated classes.
As earlier you defined :
belongsTo = [eventgroup:Eventgroup,classgroup:Classgroup]

with this GORM tried to create a column with classgroup name under Event table, but for many-to-many association with classgroup, database should suppose to have third table to have multiple records for many-to-many associations between Event and Classgroup. So was giving such error.
Hence later when you mention :
belongsTo = [Eventgroup, Classgroup]

it worked as it just got owner information.
So here Classgroup would be the owner of association, as Event belongsTo Classgroup.
Hope this helps. Thanks.


text:
Q: Как в POST запрос добавить дату? import requests
payload ={}
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',
           'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
           }
r =requests.post("http://httpbin.org/post", data=payload, headers=headers)
print (r.text)

 {
  "args": {},
  "data": "",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "close",
    "Content-Length": "0",
    "Host": "httpbin.org",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"
  },
  "json": null,
  "origin": "192.168.0.1",
  "url": "http://httpbin.org/post"
}

A: Отправка данных POST запросом в типе application/x-www-form-urlencoded. Когда браузер отправляет данные из тега <form>, то в таком типе он и описывает их.
import requests
from datetime import datetime

data = {
    'a': '1',
    'date': str(datetime.now()),
}
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',
}

rs = requests.post("https://httpbin.org/post", data=data, headers=headers)
print(rs.text)

Чтобы отправить данные в типе application/json, нужно вместо параметра data=, указывать json=: rs = requests.post("http://httpbin.org/post", json=data, headers=headers)
Модуль requests сам заполнит нужные заголовки


text:
Q: Generate a Web Service Client in WS-I compliance mode
I'm trying to create a web service client using Visual Studio 2010.
The client works very well if I use the wsdl file in version SOAP V2.
When I set the property WS-I Compliance to Yes in Magento and recompile the web service client in VS2010, it doesn't work!!! Some methods disappear from the resulting WSDL file.
I've found the same problem if I generate a java web service client using the tool wsimport.

Any idea of what's happening?

A: I ran into the same issue and instead of commenting out the catalogProductAttributeRemove, I actually looked into what was missing and added the additional sections to my wsi.xml file. Thanks to Juanma R. for pointing me in the direction of the file that needed to be corrected.
I referenced the entries for catalogProductAttributeCreate as a reference point for what other sections might need to exist to fix this. I don't really know anything about WSDL, just tried looking for what could be missing.
After I changed the file I refreshed all caches in Magento and confirmed the new entries were showing up in the WSDL file at /index.php/api/v2_soap?wsdl=1. I then removed the web reference that was added to VS 2010 and went through the steps of adding the web reference again. This time after adding it I got no errors.
The version of Magento that I was patching is Magento Enterprise 1.12.0.2 but I expect it's applicable to other versions that show this same error with catalogProductAttributeRemove.
Here is a quick diff I ran of what I changed in the wsi.xml file:
*** Z:\mage-1-12-0-2.dev\htdocs\app\code\core\Mage\Catalog\etc\wsi - Copy.xml backup    Tue Jul 3 12:08:31 2012 UTC
--- Z:\mage-1-12-0-2.dev\htdocs\app\code\core\Mage\Catalog\etc\wsi.xml  Fri Nov 9 18:40:58 2012 UTC
***************
*** 1509,1520 ****
                  <xsd:complexType>
                      <xsd:sequence>
                          <xsd:element minOccurs="1" maxOccurs="1" name="result" type="xsd:string" />
                      </xsd:sequence>
                  </xsd:complexType>
              </xsd:element>
          </xsd:schema>
      </wsdl:types>
      <wsdl:message name="catalogProductCurrentStoreRequest">
          <wsdl:part name="parameters" element="typens:catalogProductCurrentStoreRequestParam" />
      </wsdl:message>
      <wsdl:message name="catalogProductCurrentStoreResponse">
--- 1509,1540 ----
                  <xsd:complexType>
                      <xsd:sequence>
                          <xsd:element minOccurs="1" maxOccurs="1" name="result" type="xsd:string" />
                      </xsd:sequence>
                  </xsd:complexType>
              </xsd:element>
+
+
+ <!-- Added by Matt Johnson 2012-11-09 to fix VS 2010 support of SOAP reference -->
+           <xsd:element name="catalogProductAttributeRemoveRequestParam">
+               <xsd:complexType>
+                   <xsd:sequence>
+                       <xsd:element minOccurs="1" maxOccurs="1" name="sessionId" type="xsd:string" />
+                       <xsd:element minOccurs="1" maxOccurs="1" name="attribute" type="xsd:string" />
+                   </xsd:sequence>
+               </xsd:complexType>
+           </xsd:element>
+           <xsd:element name="catalogProductAttributeRemoveResponseParam">
+               <xsd:complexType>
+                   <xsd:sequence>
+                       <xsd:element minOccurs="1" maxOccurs="1" name="result" type="xsd:boolean" />
+                   </xsd:sequence>
+               </xsd:complexType>
+           </xsd:element>
+
+
          </xsd:schema>
      </wsdl:types>
      <wsdl:message name="catalogProductCurrentStoreRequest">
          <wsdl:part name="parameters" element="typens:catalogProductCurrentStoreRequestParam" />
      </wsdl:message>
      <wsdl:message name="catalogProductCurrentStoreResponse">
***************
*** 1883,1894 ****
      <wsdl:message name="catalogProductAttributeCreateRequest">
          <wsdl:part name="parameters" element="typens:catalogProductAttributeCreateRequestParam" />
      </wsdl:message>
      <wsdl:message name="catalogProductAttributeCreateResponse">
          <wsdl:part name="parameters" element="typens:catalogProductAttributeCreateResponseParam" />
      </wsdl:message>
      <wsdl:portType name="{{var wsdl.handler}}PortType">
          <wsdl:operation name="catalogCategoryCurrentStore">
              <wsdl:documentation>Set_Get current store view</wsdl:documentation>
              <wsdl:input message="typens:catalogCategoryCurrentStoreRequest" />
              <wsdl:output message="typens:catalogCategoryCurrentStoreResponse" />
          </wsdl:operation>
--- 1903,1923 ----
      <wsdl:message name="catalogProductAttributeCreateRequest">
          <wsdl:part name="parameters" element="typens:catalogProductAttributeCreateRequestParam" />
      </wsdl:message>
      <wsdl:message name="catalogProductAttributeCreateResponse">
          <wsdl:part name="parameters" element="typens:catalogProductAttributeCreateResponseParam" />
      </wsdl:message>
+
+ <!-- Added by Matt Johnson 2012-11-09 to fix VS 2010 support of SOAP reference -->
+   <wsdl:message name="catalogProductAttributeRemoveRequest">
+       <wsdl:part name="parameters" element="typens:catalogProductAttributeRemoveRequestParam" />
+   </wsdl:message>
+   <wsdl:message name="catalogProductAttributeRemoveResponse">
+       <wsdl:part name="parameters" element="typens:catalogProductAttributeRemoveResponseParam" />
+   </wsdl:message>
+
      <wsdl:portType name="{{var wsdl.handler}}PortType">
          <wsdl:operation name="catalogCategoryCurrentStore">
              <wsdl:documentation>Set_Get current store view</wsdl:documentation>
              <wsdl:input message="typens:catalogCategoryCurrentStoreRequest" />
              <wsdl:output message="typens:catalogCategoryCurrentStoreResponse" />
          </wsdl:operation>
***************
*** 2760,2771 ****
                  <soap:body use="literal" />
              </wsdl:input>
              <wsdl:output>
                  <soap:body use="literal" />
              </wsdl:output>
          </wsdl:operation>
      </wsdl:binding>
      <wsdl:service name="{{var wsdl.name}}Service">
          <wsdl:port name="{{var wsdl.handler}}Port" binding="typens:{{var wsdl.handler}}Binding">
              <soap:address location="{{var wsdl.url}}" />
          </wsdl:port>
      </wsdl:service>
--- 2789,2814 ----
                  <soap:body use="literal" />
              </wsdl:input>
              <wsdl:output>
                  <soap:body use="literal" />
              </wsdl:output>
          </wsdl:operation>
+
+
+ <!-- Added by Matt Johnson 2012-11-09 to fix VS 2010 support of SOAP reference -->
+       <wsdl:operation name="catalogProductAttributeRemove">
+           <soap:operation soapAction="" />
+           <wsdl:input>
+               <soap:body use="literal" />
+           </wsdl:input>
+           <wsdl:output>
+               <soap:body use="literal" />
+           </wsdl:output>
+       </wsdl:operation>
+
+
      </wsdl:binding>
      <wsdl:service name="{{var wsdl.name}}Service">
          <wsdl:port name="{{var wsdl.handler}}Port" binding="typens:{{var wsdl.handler}}Binding">
              <soap:address location="{{var wsdl.url}}" />
          </wsdl:port>
      </wsdl:service>

A: There is a mistake in the original Magento Core code, related to the operation "catalogProductAttributeRemove" (module core/Mage/Catalog).
To solve it, I've commented the following operation in the wsi.xml file of the module Catalog
 <!--wsdl:operation name="catalogProductAttributeRemove">
    <wsdl:documentation>Delete attribute</wsdl:documentation>
    <wsdl:input message="typens:catalogProductAttributeRemoveRequest" />
    <wsdl:output message="typens:catalogProductAttributeRemoveResponse" />
</wsdl:operation-->

After that the automatic building of a Web Service Client using VS2010 works perfectly!.

A: I included the diff into the wsi.xml from version 1.7.2 and uploaded it here.
So, if you can't read the diff correct, you can use this file directly.


text:
Q: Author name replaced by a dash for multiple works by same author When I have the same author appearing more than once in the bibliography, the name of the author is replaced by a dash. How can I change it to always display the full name or names? I'm using BibLaTeX and Biber. I made quite a few changes to the literature style already, so could it be due to one of those changes?
Here is my minimal working example:
\documentclass[listof=totoc,
index=totoc,
bibliography=totoc, parskip,
12pt, headsepline=true, a4paper]{scrartcl}

\usepackage[ngerman, english]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

%% Literaturverzeichnis
\usepackage[hidelinks]{hyperref}
\usepackage{csquotes}
\usepackage{etoolbox}
\usepackage[backend=biber, style=authoryear, maxbibnames=999, maxcitenames=2]{biblatex}
\addbibresource{Literature.bib}

% Autoren mit Slash getrennt und lastname-firstname
\renewcommand*{\multinamedelim}{\slash} \renewcommand*{\finalnamedelim}{\multinamedelim}
\DeclareNameAlias{sortname}{last-first}

% Doppelpunkt nach Jahresangabe in Klammern im Literaturverzeichnis
\renewcommand*{\labelnamepunct}{\addcolon\addspace}

% Titel im Literaturverzeichnis nicht kursiv
\DeclareFieldFormat{title}{#1\isdot}
\DeclareFieldFormat{journaltitle}{#1}
\DeclareFieldFormat{issuetitle}{#1}
\DeclareFieldFormat{maintitle}{#1}
\DeclareFieldFormat{booktitle}{#1}

% Jahreszahl im Fußnotenzitat in runden Klammern
\newbibmacro*{cite:parens:labelyear+extrayear}{%
  \iffieldundef{labelyear}
{}
{\printtext[parens]{\printtext[bibhyperref]{%
   \printfield{labelyear}%
   \printfield{extrayear}}}}}

\renewbibmacro*{cite}{%
  \iffieldundef{shorthand}
    {\ifthenelse{\ifnameundef{labelname}\OR\iffieldundef{labelyear}}
   {\usebibmacro{cite:label}%
    \setunit{\addspace}}
   {\printnames{labelname}%
    \setunit{\nameyeardelim}}%
 \usebibmacro{cite:parens:labelyear+extrayear}}
{\usebibmacro{cite:shorthand}}}

\begin{document}

Just some text\footcite{Test1}. And some additional text\footcite{Test2}

\clearpage
\printbibliography

\end{document}

And my bib file looks like this:
@book{Test1,
author = {Apostolik, Richard},
title = {Test title 1},
year = {2010a}
}

@book{Test2,
author = {Apostolik, Richard},
title = {Test title 2},
year = {2010b}
}

A: BibLaTeX has a dashed option for repeated names which is true by default (with the authoryear, at least). You just have to put dashed=false in the options to biblatex:
\usepackage[dashed=false, backend=biber, style=authoryear, maxbibnames=999, maxcitenames=2]{biblatex}


text:
Q: React JS, Spring and Postgres project For my project, I am building a fitness app with React front-end and Spring back-end. DB I am using is Postgres.
I have completed my back-end set up which includes all my controllers.
My front-end is supposed to be have a landing page which displays a list of all muscles. I have got that by writing the following code:
    const renderedMuscles = muscles.map((muscle) =>{
        return <MuscleCard muscle={muscle} key={muscle.id}/>
    });

I am then returning {renderedMuscles} which generates a list of muscle items.
I am now stuck on the following:

*

*I want to click on a muscle item and then fetch exercises for the clicked muscle from the DB. For example, clicking on 'chest' should return a list that includes 'bench press', 'dumbbell flies', 'press ups' etc.

*I then want to click on an exercise which brings up a form that has an increment and decrement button for reps, and increment and decrement button for weight and a save button.

How do I progress with this? My instructor suggested that I may have to use react controllers instead of Spring but other than that he doesn't know how I can achieve this or what I can do next. If I create a React router, what is it that I can achieve with it that I can't with my current set up?
I am more than half-way through my project and I feel I am really close to completion but really frustrated with what I am stuck on. Any help with this would be much appreciated. Thanks


text:
Q: Does "induction" for a functor algebra imply it is initial? I originally posted this question to MSE but there were no answers except for a partial one from me, so I'm trying again here. I'm an undergrad, not a researcher, so forgive me (and correct me!) if my terminology is nonstandard, or my ideas confused.

By "induction" I mean "no proper subalgebras". My thinking goes like this:

*

*For natural numbers, recursion and induction are in some sense the same thing. In particular, given a recursive definition of $f$ you would prove its totality roughly by saying "if I can define $f$ on $1\dots n$, then I can define it on $n+1$", i.e. by induction.

*The proper categorical notion of recursion is initial algebras – in particular, for $F(X) = 1\sqcup X$ an initial algebra is a natural number object, the property of being initial being precisely what you need to define functions by recursion.

*An initial algebra automatically has a notion of induction: initial objects have no proper subobjects, so if you have some subobject that is closed under the algebra operations, this means precisely that the inclusion is an algebra homomorphism, and therefore an isomorphism.

*I'd really like to go the other way, but in general the implication "$I$ is initial $\implies$ every mono into $I$ is an iso" cannot be reversed (its dual has a counterexample in $\mathbf{Set}$, in that every epi into $0$ is an iso but $0$ is not terminal).

  Are there circumstances where an algebra having no proper subalgebra means it is initial?

Observations that have been made since posting the question:

*

*There is an algebra $1 \sqcup \mathbb Z/n\mathbb Z \to \mathbb Z/n\mathbb Z$ that has no proper subalgebras, so induction works for it. Nevertheless it is not initial. The problem is that the algebra satisfies equations, since $n$ successors give the identity, so there aren't morphisms to algebras that don't satisfy those equations. This suggests that the algebra needs to be "free" in some sense.

*In light of the above, I might decide I'm interested in quasi-initial objects, since it is at least true that any morphism from $\mathbb Z/n\mathbb Z$ that is an algebra homomorphism is unique. It turns out that in any category with equalisers, if an object has no proper subobjects then it is quasi-initial, and of course a category of algebras has equalisers if its underlying category does.

What's the "freeness" condition that I want? What can I do to show that any morphisms exist from an object with no proper subobjects?

A: It looks as though you might have already observed this yourself, but suppose $F: C \to C$ is an endofunctor and $C$ has equalizers. Then if $F$ has a weakly initial algebra $X$ (meaning that for every $F$-algebra $Y$ there exists an $F$-algebra map $X \to Y$), then $X$ is initial if and only if every $F$-subalgebra of $X$ is all of $X$. For, if $f, g: X \to Y$ are two $F$-algebra maps, then their equalizer is an $F$-subalgebra of $X$, and its being equal to $X$ would force $f = g$.
This is not a completely idle observation however, because one sometimes has formal ways to construct weakly initial $F$-algebras. Suppose for instance that $C$ is finitely complete and cartesian closed and $F$ carries a structure of $C$-enriched functor. Then, if the end
$$\int_{c \in C} c^{c^{F(c)}}$$
exists (meaning an object universal with respect to dinatural maps to the functor $G: C^{op} \times C \to C$ defined by $G(d, c) = c^{d^{F(c)}}$), it is a weakly initial $F$-algebra. For instance, when $C = Set$ and $F(c) = 1 + c$, we have
$$\int_{c} c^{c^{1 + c}} \cong \int_c c^{c^c \times c} \cong \int_c (c^c)^{(c^c)}$$
which is the set of dinatural transformations $c^c \to c^c$. This is isomorphic to $\mathbb{N}$ conceived as the set of Church numbers $\lambda f: f^{(n)}$ where $f$ is of variable type $c^c$.
If you are interested specifically in natural numbers objects, then there is a remarkable theorem due to Peter Freyd:
Theorem: In a topos $E$, the following are equivalent for a structure $(N, o: 1 \to N, s: N \to N)$:

*

*$(N, o, s)$ is a natural numbers object;

*The maps $o: 1 \to N, s: N \to N$ are coproduct injections (that witness $N$ as a coproduct $1 + N$) and $N \to 1$ is the coequalizer of the pair $(1_N, s): N \to N$;

*$s$ is monic, the subobjects $s: N \to N$ and $o: 1 \to N$ are disjoint (have the initial object as their pullback), and any subalgebra of the algebra structure $(o, s): 1 + N \to N$ on $N$ is all of $N$.
The proof is not at all easy, but you can find it in Johnstone's Sketches of an Elephant, section D.5.


text:
Q: javascript - loop multidimesntional array I am sure this is really simple, I used to have a function for checking the contents of an array. Now Id like to modify it to check a two dimensional array.
function ChkArray(Str, Val){

for (var i=0;i<Str.length;i++){
        if (Str[i] == Val) {return i;}
    }
return -1;
}

My new attempt:
function ChkArray2(Str, Val){

for (var i=0;i<Str.length;i++){
        for (var ii=0;ii<Str[ii].length;ii++){
            if (Str[i][ii] == Val) {return i;}
        }
    }
return -1;
}

A: Close, in your inner loop, you want to check the length of the current item in the outer loop:
function ChkArray2(Str, Val){

    for (var i=0;i<Str.length;i++){
        for (var ii=0;ii<Str[i].length;ii++){
            if (Str[i][ii] == Val) {return i;}
        }
    }
    return -1;
}

that should work

A: If you're asking about better ways to tackle the problem, I would perhaps think about writing a function which can work with any number of dimensions in the array. In your example, the return value is the index of the top level array, but to make it generic, you would have to return the full "path" to the found element, and let the calling code decide what information it wants:
    function multiFind(arr, val) {  // please don't name an array "str"!
    for (var i = 0, l = arr.length; i < l; ++i) {
        if (arr[i] === val) {
            return [i];
        } else if (is_array(arr[i])) {
            var ret = multiFind(arr[i], val);
            if (ret !== false) {
                ret.unshift(i);
                return ret;
            }

        }
    }
    return false;
}

// this function by Doug Crockford
var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};

var inp = ["a","b",["c", ["d", "e", ["f", "g"], "h"]]];

multiFind(inp, "a"); // [0]
multiFind(inp, "b"); // [1]
multiFind(inp, "c"); // [2, 0]
multiFind(inp, "f"); // [2, 1, 2, 0]
multiFind(inp, "h"); // [2, 1, 3]
multiFind(inp, "x"); // false

A: I suggest using javascript foreach.
function ChkArray2(Str, Val){
    for (var i in Str){
        for (var ii in Str[i]){
            if (Str[i][ii] == Val){
                return i;
            }
        }
    }
    return -1;
}


text:
Q: Android: Could not read image from disk and use them in a Imageview I downloaded an image to the following target:
    String Target = Environment.getExternalStorageDirectory()+"Test.png"

At my smartphone, the file is located in (AFAIK) /storage/emulated0/Test.png.
Now, I want to read this file and load them into a ImageView.
My code ("id is Test.png"):
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        Log.d("tags", "Is mounted");
    }
    else {
        Log.d("tags", "Is not mounted");
        return;
    }

    Log.d("tags", "Path: "+Environment.getExternalStorageDirectory().getAbsolutePath().toString()+id);
    File imgFile = new  File(Environment.getExternalStorageDirectory().getAbsolutePath()+id);
    if(imgFile.exists()){
        Log.d("tags", "File found");
        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

        ImageView myImage = (ImageView) findViewById(R.id.iv);
        myImage.setImageBitmap(myBitmap);

    }else {
        Log.d("tags", "File not found");
    }

The location on my smartphone is exactly the same like in this code, but everytime, I get a FileNotFoundException. Why?
Edit: I found a solution. Between the getExternalStorageDirectory and my filename I need a separator like "/". Now it works.


text:
Q: Colab error: cannot import name 'pix2pixHD_model' from 'pix2pixHD' (unknown location) I am using Colab and I am trying to code a Pix2Pix gan.
here is my code:
 ! git clone https://github.com/NVIDIA/pix2pixHD
 ! pip install dominate

after this Code block it say this :
fatal: destination path 'pix2pixHD' already exists and is not an empty directory.
Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/
Requirement already satisfied: dominate in /usr/local/lib/python3.7/dist-packages (2.6.0)

Then I have this :
 ! cd pix2pixHD/
 ! python3 setup.py install
 import pix2pixHD
 from pix2pixHD import pix2pixHD_model
 gan_model = pix2pixHD.pix2pixHD_model()
 gan_model.compile(loss='mae', optimizer='adam')
 gan_model.fit(x, y, epochs=100, batch_size=1, callbacks=[pix2pixHD.save_weights_callback(gan_model, every=10)])

but I am getting this error :
python3: can't open file 'setup.py': [Errno 2] No such file or directory
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-46-6ae9c67e59ac> in <module>()
  2 get_ipython().system(' python3 setup.py install')
  3 import pix2pixHD
----> 4 from pix2pixHD import pix2pixHD_model
  5 gan_model = pix2pixHD.pix2pixHD_model()
  6 gan_model.compile(loss='mae', optimizer='adam')

ImportError: cannot import name 'pix2pixHD_model' from 'pix2pixHD' (unknown location)

So then I tried this:
 %cd pix2pixHD
 ! python3 setup.py install
 import pix2pixHD
 from pix2pixHD import pix2pixHD_model
 gan_model = pix2pixHD.pix2pixHD_model()
 gan_model.compile(loss='mae', optimizer='adam')
 gan_model.fit(x, y, epochs=100, batch_size=1, callbacks=[pix2pixHD.save_weights_callback(gan_model, every=10)])

but then I got this error:
[Errno 2] No such file or directory: 'pix2pixHD'
/content/pix2pixHD
python3: can't open file 'setup.py': [Errno 2] No such file or directory
 ---------------------------------------------------------------------------
 ImportError                               Traceback (most recent call last)
 <ipython-input-50-ef300b041421> in <module>()
  2 get_ipython().system(' python3 setup.py install')
  3 import pix2pixHD
 ----> 4 from pix2pixHD import pix2pixHD_model
  5 gan_model = pix2pixHD.pix2pixHD_model()
  6 gan_model.compile(loss='mae', optimizer='adam')

ImportError: cannot import name 'pix2pixHD_model' from 'pix2pixHD' (unknown location)

but I can see it right here:
Picture of my Colab
So I am not sure why it is not working.

A: 1. fatal: destination path 'pix2pixHD' already exists ...
you are trying to clone the repo again, just check if it already exists
2. ! python3 setup.py install
This is not a library you have to install. You can directly use train.py and test.py script once you have all the requirements(getting-started) ready
3.  from models.pix2pixHD import Pix2PixHDModel
If you want to import pix2pixmodel,import it like this
from models.pix2pixHD_model import Pix2PixHDModel

4. gan_model.compile(loss='mae', optimizer='adam')
You cannot start training this way.
Easier way is to use train.py. You can find command line arguments defined in options directory.
Please go through readme once


text:
Q: backbone.js - using parse without calling fetch On page load I'm bootstrapping my data to my collections via this technique. That works great, but I'm running into an issue where I have sub-models which also need to be cast.
For example, I return a JSON collection called Book, and each book array contains 10-20 models themselves called Pages. If I try and access Pages directly, I get the [object][object] error as Backbone can't figure out what type of object it is.
Previously when I was using fetch, I would get around this by using collections which contained a parse action. In parse I would do something like:
Collection_Books = Backbone.Collection.extend({
    model: Model_Book,
    parse: function (response) {
        response.Pages = new Collection_Pages(response.Pages);
        return response;
    }
});

Now that I'm accessing the data directly and not using fetch, the documentation implies that I no longer have access to the parse method.
If I am not using fetch or calling a server on page load, how can I cast sub-models using the Books > Pages example?

A: Not sure if this is new, but it looks like you can also just set the parse property of the options parameter to your constructor to true, thus telling the constructor to use your parse method:
modelInstance = new MyModel(obj, {parse: true});

http://backbonejs.org/#Model-constructor

A: Update: This answer is now out of date, see uglymunky's answer for more up to date information.

You're right, parse is only specified to be called during fetch so it won't be called when you're building a collection from raw data.
But, since you control the raw data that you're using to bootstrap your collection, you can call your collection's parse yourself:
var c = new YourCollection(
    YourCollection.prototype.parse([
        // attribute data goes here...
    ])
);

Demo: http://jsfiddle.net/ambiguous/kdaZ3/
Your parse methods (both collection and model) shouldn't care about their calling context so calling them directly from the prototype should be fine.


text:
Q: UWP and .NetCore - Inconsistent Font Family Names I'm using UWP for a front end GUI and a full trust background process written in .NetCore 3.1 for some heavy lifting tasks. However, I'm having an odd issue when it comes to pulling back all the installed fonts as the list returned is not consistent between the two frameworks.
In UWP the following code (based on the answer to this SO question) is used to populate a dropdown list and returns approximately 241 font families:
public List<string> FontFamilies
{
    get
    {
        return CanvasTextFormat.GetSystemFontFamilies(ApplicationLanguages.Languages).OrderBy(x => x).ToList();
    }
}

The selected fontfamily is then passed as a string to the .NetCore background process which attempts to get the font. However, var fonts = System.Drawing.Text.InstalledFontCollection() returns a very different list (477 elements) to the UWP function. Many of these additional items seem to be because the variations on the font families (e.g. regular, bold and italic) are not being collapsed into a single family. But in some cases the name is different; for example an OpenType font Playlist Script in UWP becomes Playlist in NetCore.
I've tried to seeing if the language IDs has something to do with the disparity but without success and wondered if anyone else has had to deal with a similar issue?

A: I hate unanswered questions on the internet, so I've posted what I came up with in solving this problem. I'm not going to mark it as the answer though in case someone else comes up with a more elegant solution at a later date.
It would appear that the various font libraries/frameworks in C# pull back different Name ID's when populating the FontFamily name. Normally, all the font names will match and this won't matter, but sometimes they don't and (given a large number of OTF fonts in play for my particular use case) this is what was causing my problem.
Using dp4 font viewer I was able to inspect the font metadata and cross reference the fields to the data being returned by the libraries. Using the Playlist Script font from my above example it turns out there were actually 3 names in play in my code.

*

*Playlist Script - I think that UWP uses a combination of the Family name and Sub-Family name.

*Playlist - The Family name presented by System.Drawing.Text.InstalledFontCollection

*Playlist-Script - The Full Font Name required by the ImageMagick.NET library I am using to render some images.

In the end I used the now abandoned SharpDX libraries as this was the only library I could find that gave me access to the font meta data to be able to extract the exact names I needed consistently.
fontFamily.GetFont(0).GetInformationalStrings(InformationalStringId.FullName, out var localizedStrings);
if (!familyNames.FindLocaleName(CultureInfo.CurrentCulture.Name, out int index))
{
    if (!familyNames.FindLocaleName("en-us", out index))
    {
        index = 0;
    }
}

var coreName = localizedStrings.Count > 0 ? localizedStrings.GetString(0) : familyNames.GetString(index);

I was then able to build a mapping of the UWP compatible names to the .NETCore compatible names and render the images as intended.


text:
Q: how to easily extract json data of a known class from kafka in spark 2.3.0 structured streaming In the this databricks blogpost they instruct how to extract json data from kafka:
# Construct a streaming DataFrame that reads from topic1
df = spark \
  .readStream \
  .format("kafka") \
  .option("kafka.bootstrap.servers", "host1:port1,host2:port2") \
  .option("subscribe", "topic1") \
  .option("startingOffsets", "earliest") \
  .load()
  .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")

# value schema: { "a": 1, "b": "string" }
schema = StructType().add("a", IntegerType()).add("b", StringType())
df.select( \
  col("key").cast("string"),
  from_json(col("value").cast("string"), schema))

Is there a way to create the schema from a known case class without manually defining all the fields?
Note: this is a spark 2.2 doc, and i believe you now have to add new in the schema line:
schema =  new StructType().add("a", new IntegerType()).add("b", new StringType())
I was able to figure this out thanks to this SO question.


text:
Q: Autotools - set path to library In my debian system there is an installed library.
I wan't to make a patch to the library and to the application, that uses it.
So, I downloaded sources of library's and application's packages. Then I patched a library and built it (without installing it to the system).
Now, when I ./configure the application, autotools detect the system's version of the library, not the mine one.
So, I did ./configure CFLAGS=-I/home/aquirel/dev/vte-0.28.2/src LDFLAGS=-L/home/aquirel/dev/vte-0.28.2/src/.libs
Is there any more intelligent way to do it?
Because, using this approach generates libtool temporary wrapper script instead of a executable binary.
And also, I don't want to install a patched version of a library to the system till I have tested it in the application.

A: You could install the vte package using the DESTDIR install:
$ cd /home/aquirel/dev/vte-0.28.2
$ make DESTDIR=/home/aquirel/dev/test-vte install

This will install all the headers/libraries to /home/aquirel/dev/test-vte as if it were /.  You'll have to set up paths to configure a little differently:
$ ./configure CFLAGS=-I/home/aquirel/dev/test-vte/usr/local/include LDFLAGS=-L/home/aquirel/dev/test-vte/usr/local/lib

and setup LD_LIBRARY_PATH for the vte shared libraries as well for your application test environment.

Because, using this approach generates libtool temporary wrapper script instead of a executable binary.

libtool always creates a wrapper script for applications that link shared libraries.  If you need to run your application under Valgrind or gdb, see here for more information about libtool's --mode=execute option.


text:
Q: how do i cache specific table with MySQL and asp.net framework 2.0? I want to cache frequently used data in asp.net with MySQL and .net framework 2.0. is there any way to do it with asp.net without using caching technique provided by MySQL i.e. query cache or table cache?

A: You can use Cache variable and put your data in that variable.
First bring the values in Data-Set or List or Data-Table put it in the Cache as follows
Suppose you have data in a data-set ds then
Cache.Insert("CacheTableA", ds, null, DateTime.MaxValue, TimeSpan.FromMinutes(10));

It will cache your data-set ds for 10 minutes.
And while using cast it from the Cache as
  DataSet ds=(DataSet)Cache["CacheTableA"];
  ....

You can go through this link to understand caching in Asp.net http://www.tutorialspoint.com/asp.net/asp.net_data_caching.htm


text:
Q: Sensitivity of placing the picture in multicols environment The following piece of code produces different text spacing.
\documentclass{article}

\usepackage{graphicx}
\graphicspath{{Picture/}}
\usepackage{multicol}
\usepackage{lipsum}
\usepackage{amsmath, amssymb}

\newtheorem{exercise}{Exercise}

\begin{document}

\begin{multicols}{2}[\columnsep 2em]
\includegraphics[width=\linewidth]{picture-sample}
\columnbreak
\begin{exercise}
Compute the integral
\[
\iint_{D}y\,\mathrm{dx}\mathrm{dy},
\]%
where $D$ is represented in the picture to the left.
\end{exercise}
\end{multicols}

\begin{multicols}{2}[\columnsep 2em]
\begin{exercise}
Compute the integral
\[
\iint_{D}y\,\mathrm{dx}\mathrm{dy},
\]%
where $D$ is represented in the picture to the right.
\end{exercise}
\columnbreak
\includegraphics[width=\linewidth]{picture-sample}
\end{multicols}

\end{document}

Why is happening like this? It is clear to me that the picture on the left side is treated differently than the picture on the right side. But why? And how can I fix this issue? Or maybe it is possible to produce the same effect with a different package or another environment?

A: The package paracol does a better job in this case. (It does not try to balance the columns.)

\documentclass{article}

\usepackage{graphicx}
\graphicspath{{Picture/}}
%\usepackage{multicol} % not used
\usepackage{lipsum}
\usepackage{amsmath, amssymb}

\newtheorem{exercise}{Exercise}

\usepackage{paracol} % <<<<<<<<<<<<<<<<<< added
\setcolumnwidth{0.5\textwidth/2em,0.5\textwidth}%  column separation =2em
\globalcounter{exercise} % counter execise made global

\begin{document}

\begin{paracol}{2}
    \noindent\includegraphics[width=\linewidth]{example-image-a}% starts in the left column
    \switchcolumn % go to  the right column
    \begin{exercise}
        Compute the integral
        \[
        \iint_{D}y\,\mathrm{dx}\mathrm{dy},
        \]%
        where $D$ is represented in the picture to the left.
    \end{exercise}
    %   \vspace*{50pt}% <<<<<<<<<<< add some separation
    \switchcolumn% go to  the left column
    \begin{exercise}
        Compute the integral
        \[
        \iint_{D}y\,\mathrm{dx}\mathrm{dy},
        \]%
        where $D$ is represented in the picture to the right.
    \end{exercise}
    \switchcolumn% go to  the right columnt
    \includegraphics[width=\linewidth]{example-image-b}
\end{paracol}

\end{document}

To add some space between the exercises use
\end{exercise}
\vspace*{50pt}% <<<<<<<<<<< add some separation
\switchcolumn% go to  the left column

A: You do not say what the picture-sample contains so one can't see what difference you observe, but I presume your picture has more height than the text in the other column. Is that is the case then your example should show in the first multicols a short second column with text and a gap at the bottom and in the second multicols the text spread out in the first column to match the height of the figure in the second column. Is that your problem?
The reason is that multicols is mainly meant for "text" and there is is usually the case that you want the last column to run short if there is not enough text to fill it.
This is controlled by the the counter finalcolumnbadness which has a default of 9999. Your text produces a badness of 10000(ugly) which why the column is shortened. You can see this when you run your example with the option balancingshow, i.e.,
\usepackage[balancingshow]{multicol}

So one way to make both identical is to add \setcounter{finalbadness}{10000}.
But you may prefer no speading out and in that case the solution is
\vspace*{\fill}
\columnbreak

for which there is an abbreviation \newcolumn  --- except that I have implemented it incorrectly -- so it doesn't work and need fixing. The fix is this and will appear in the next release of the package:
\makeatletter
\renewcommand\newcolumn{%
   \ifnum\col@number<\tw@
   \PackageError{multicol}%
    {\noexpand\newcolumn outside multicols}%
    {This command can only be used within
     a multicols or multicols* environment.}%
  \else
    \ifvmode
     \nobreak\vfill\kern\z@\penalty -\@Mv\relax  % <--- this was missing the kern
   \else
     \@bsphack
     \vadjust{\nobreak\vfill\kern\z@\penalty -\@Mv\relax}%
     \@esphack
   \fi
  \fi}
\makeatother


text:
Q: Is there a specific term for non interior points of a set A? For a set $A$ (a subset of some metric space $X$), the interior points are inside the set (i.e. an open ball around them totally contained within $A$). The boundary points may or may not belong to $A$. We could classify the boundary points into two categories. Those that belong to $A$ and those that don't belong to $A$.  Are there specific names for these categories?
In particular, is there a name for a point $x \in A$ which is not an interior point of $A$? Or should I just call them non-interior points of $A$?
Is there a name for the set $A \setminus \text{int } A$?

A: The set $A\setminus \operatorname{int}(A)$ is called (by some, it's not common) the frontier of $A$ (denoted $\text{Fr}(A)$). It can also be written as $\partial A\cap A$ where $\partial A$ is the (usual) boundary of $A$. For closed sets these sets (frontier and boundary) coincide.


text:
Q: JPopupMenu disappears on mouseEntered I have next structure: JPopupMenu contains JPanel which contains JMenuItems. The problem is, I cannot use it because JPopupMenu disappears when mouse enters to any menu item.
SSCCE:
public class PopupTest {
    public static void main(String[] a) {
        final JFrame frame = new JFrame();
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createLineBorder(Color.RED));

        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON3) {
                    final JPopupMenu menu = new JPopupMenu();
                    JPanel menuPanel = new JPanel();
                    menuPanel.setBorder(BorderFactory.createLineBorder(Color.GREEN));
                    menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.Y_AXIS));

                    for (int i = 0; i < 10; i++) {
                        JMenuItem item = new JMenuItem(String.valueOf(i));
                        menuPanel.add(item);
                    }

                    menu.add(menuPanel);
                    menu.show(panel, e.getX(), e.getY());
                }
            }
        });
        frame.setContentPane(panel);
        frame.setUndecorated(true);
        frame.setBackground(new Color(50, 50, 50, 200));

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                frame.setVisible(true);
            }
        });
    }
}

BTW, problem does not repeats when there is no JPanel between JPopupMenu and its items.
Does anyone know how to prevent that?

A: Not directly answering your question but I think, you are unnecessarily adding a panel with box layout to JPopupMenu when it supports adding JMenuitem directly to it. check the following code fragment:
                 final JPopupMenu menu = new JPopupMenu();
                   JPanel menuPanel = new JPanel();
                    menuPanel.setBorder(BorderFactory.createLineBorder(Color.GREEN));
                  //  menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.Y_AXIS));

                    for (int i = 0; i < 10; i++) {
                             JLabel item = new JLabel(i+"");
                             menuPanel.add(item);
                            }

                    menu.add(menuPanel);

                    menu.show(panel, e.getX(), e.getY());

A: Some tips:

*

*Define your pop up menu just once instead every time a button is pressed.

*You need to override mouseReleased or mousePressed method: Bringing Up a Popup Menu

*Use MouseEvent.isPopupTrigger to find out if pop up should be shown.

*Add menuItems directly to menu and not to a JPanel
Suggested changes:
    final JPopupMenu menu = new JPopupMenu();
    menu.setLayout(new GridLayout(2,5)); // How do you can, for example, lay out your menu items horizontally in 2 rows?
    for (int i = 0; i < 10; i++) {
        JMenuItem item = new JMenuItem(String.valueOf(i));
        menu.add(item);
    }

    MouseListener mouseListener = new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            if(e.isPopupTrigger()){
                menu.show(panel, e.getX(), e.getY());
            }
        }
    };

    panel.addMouseListener(mouseListener);

Picture


text:
Q: 100% height is not appling to body background image on mobile view I have added a bg image to body.. on mobile view it does not show fit the full height of mobile.. a tried it then giving bg-attachment : fixed but that also doesn't work.
I tried it with bg-attachment fixed.. giving height 100%
    body{
    background: url(../images/body-bg.jpg?v=1.1) no-repeat center top fixed;
    background-size: cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    height : 100%}

the bg height is only visible till the content we have used


text:
Q: Determine the 100th term of the sequence I want to find the 100th term of the following sequence:
$$\bbox[5px,border:2px solid #C0A000]{\small a_0 = 1}$$
$$\bbox[5px,border:2px solid #C0A000]{\small a_n = a_{n-1} + 2^{-n}}$$
The answer is supposed to be $\frac{2^{101} - 1}{2^{100}}$ but I'm not quite sure how to arrive to this conclusion. I've tried playing around with it but I don't really see it. I would really appreciate some help, thanks in advance!

A: Hint:$$a_n-a_{n-1}=2^{-n}$$ $$\sum_{i=1}^{100} a_i-a_{i-1}=\sum_{i=1}^{100} 2^{-i}$$ $$\implies a_{100}-a_0=?$$

A: $$a_n = \sum_{k=0}^n \left( \frac{1}{2} \right)^n$$
This is a geometric series, which sums to
$$a_n = \frac{1-(1/2)^{n+1}}{1/2}=2-(1/2)^n.$$
$$a_{100} = 2-(1/2)^{100}=\frac{2^{100}}{2^{100}} \cdot \left[ 2-(1/2)^{100} \right]=\frac{2^{101}-1}{2^{100}}.$$