text:
Q: Problem with drawing For now the following code is supposed to draw a circle onMouseDragged over the black Canvas.
Unfortunately it doesn't (=
Do I miss something?
Thanks in advance...
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.applet.*;
import java.awt.Graphics.*;

public class IdrawApplet extends Applet  {

    int mosX;
    int mosY;
    Panel pGadgets;
    Canvas myCanvas;
    Label lRed;
    TextField tfRed;
    TextField tfGreen;
    TextField tfBlue;
    Label lGreen;
    Label lBlue;

    Graphics g;

  public void init() {

    g = getGraphics();
    lRed = new Label("Red-value: ");
    lBlue = new Label("Blue-value: ");
    lGreen = new Label("Green-value: ");
    tfRed = new TextField();
    tfRed.setText("255");
    tfGreen = new TextField();
    tfGreen.setText("255");
    tfBlue = new TextField();
    tfBlue.setText("255");

    pGadgets = new Panel();
    pGadgets.setLayout(new GridLayout(1, 6, 5, 5));
    add(pGadgets);
    pGadgets.add(lRed);
    pGadgets.add(tfRed);
    pGadgets.add(lGreen);
    pGadgets.add(tfGreen);
    pGadgets.add(lBlue);
    pGadgets.add(tfBlue);

    myCanvas = new Canvas();
    myCanvas.setBackground(new Color(0,0,0));
    myCanvas.setBounds(0, 0, 600, 400);

    add(myCanvas);
    myCanvas.addMouseMotionListener(new MouseMotionListener() {

        public void mouseMoved(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        public void mouseDragged(MouseEvent e) {
            // TODO Auto-generated method stub
            paint(g);

        }
    });

  }

  public void paint(Graphics g) {
      g.setColor(Color.green);
      g.fillOval(mosX, mosY, 30, 30);

      }

}

A: Two things:
public void mouseDragged(MouseEvent e)
{
   mosX = e.getX();
   mosY = e.getY();
   repaint(); //NOT paint(g);
}

//...
public void paint(Graphics g)
{
    //draw on the canvas not on the component
    //since the canvas gets drawn over it
    Graphics g2 = myCanvas.getGraphics();
    g2.setColor(Color.green);
    g2.fillOval(mosX, mosY, 30, 30);
}

If you have anything more complex, you should subclass Canvas and override it's paint() method.

A: Try this:
public void mouseDragged(MouseEvent e)
{
    mosX = e.getX();
    mosY = e.getY();

    repaint();
}

The problem was that you were not updating your coordinates for the mouseDragged event. Also instead of calling paint() directly, you should call repaint(). Calling repaint() will ensure your paint() is called automatically.
EDIT:
To paint on Canvas object, override paint() of the Canvas object.
myCanvas = new Canvas()
{
    public void paint(Graphics g)
    {
        g.setColor(Color.green);
        g.fillOval(mosX, mosY, 30, 30);
    }
};

Now your mouseDragged method becomes :
public void mouseDragged(MouseEvent e)
{
    mosX = e.getX();
    mosY = e.getY();

    myCanvas.repaint();
}


text:
Q: Search all items with LINQ C# WP8.1 I need to make a query in a JSON. For example the word "Love", will search the entire JSON file and return in a list all the sentences that contain the word "love".
My Classes
 public class CategoriaFrase
 {
     [JsonProperty("Categoria")]
     public string categoria { get; set; }
     public List<Frase> frases { get; set; }
 }

 public class Frase
 {
     public string frase { get; set; }
     public string autor { get; set; }
 }

My Deserialization code:
 string texto;
 try
 {
      StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(@"ms-appx:///Categorias/Frases.txt"));

      using (StreamReader sRead = new StreamReader(await file.OpenStreamForReadAsync()))
      texto = await sRead.ReadToEndAsync();

      List<CategoriaFrase> pesquis = JsonConvert.DeserializeObject<List<CategoriaFrase>>(texto);

This is the structure of my JSON:
[
  {
    "categoria": "Mensagens de Amizade",
    "frases": [
      {
        "frase": "Enquanto alguns escolhem pessoas perfeitas, eu escolho as que me fazem bem.",
        "autor": "Frases S2"
      },
      {
        "frase": "Amizade verdadeira não é ser inseparável. É estar separado, e nada mudar.",
        "autor": "Frases S2"
      },
    }
 "categoria": "Mensagens de Amor",
    "frases": [
       {
        "frase": "Amor não é só beijo e amasso. Amor é cuidado, amor é carinho, amor também é amizade.",
        "autor": "Frases S2"
      },
       {
        "frase": "Amor é isso: querer bem, querer perto, querer ver feliz, querer fazer feliz, querer explicar – e não conseguir – tudo isso que a gente sente.",
        "autor": "Frases S2"
      },

I need to query a certain word inside the JSON and return all the sentences that contain that particular word.

Update - 001 - I added the code but it did not work

A: pesquis.Where(p=>p.frases.frase.Contains("love")).Select(s=>s.frases.frase).ToList();

A: This query should work. It returns list of sentences that contains the word "Love".
(from k in pesquis
from l in k.frases
where l.frase.Contains("Love")
select l.frase).ToList()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proving that multiply by exponent in time domain yields a frequency shift in frequency domain using convolution. I'm trying to prove that $F[x(t)e^{-jat}] = X(w-a)$ using convolution.
using the convolution property I know I should get a convolution of $F(x(t))$ and $F(e^{-jat})$
So:
$$
F[x(t)e^{-jat}]= 1/2\pi X(w)*2\pi\delta(w+a) = \int X(\theta)\delta(\omega+a-\theta) d\theta
$$
as we know the delta function samples at the impulse moment therefore I get:
$$
X(\omega+a)
$$
and not $X(\omega-a)$
What am I doing wrong?


text:
Q: Install a default DataSource in OpenLiberty by maven plugin I was trying to set a DefaultDataSource for openliberty 20.0.0.1.
The src/liberty/config/server.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<server description="new server">

    <!-- Enable features -->
    <featureManager>
        <feature>javaee-8.0</feature>
    </featureManager>

    <!-- This template enables security. To get the full use of all the capabilities, a keystore and user registry are required. -->

    <!-- For the keystore, default keys are generated and stored in a keystore. To provide the keystore password, generate an
         encoded password using bin/securityUtility encode and add it below in the password attribute of the keyStore element.
         Then uncomment the keyStore element. -->
    <!--
    <keyStore password=""/>
    -->

    <!--For a user registry configuration, configure your user registry. For example, configure a basic user registry using the
        basicRegistry element. Specify your own user name below in the name attribute of the user element. For the password,
        generate an encoded password using bin/securityUtility encode and add it in the password attribute of the user element.
        Then uncomment the user element. -->
    <basicRegistry id="basic" realm="BasicRealm">
        <!-- <user name="yourUserName" password="" />  -->
    </basicRegistry>

    <!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" -->
    <httpEndpoint id="defaultHttpEndpoint"
                  httpPort="9080"
                  httpsPort="9443" />

    <!-- Automatically expand WAR files and EAR files -->
    <applicationManager autoExpand="true"/>

    <!-- Derby Library Configuration -->
    <library id="derbyJDBCLib">
      <fileset dir="${shared.resource.dir}" includes="derby*.jar"/>
    </library>

    <!-- Datasource Configuration -->
    <!-- remove jndiName="" to serve java:comp/DefaultDataSource for Java EE 7 or above -->
    <dataSource id="DefaultDataSource">
      <jdbcDriver libraryRef="derbyJDBCLib" />
      <properties.derby.embedded databaseName="taskdb" createDatabase="create"/>
    </dataSource>

</server>

And the liberty-maven-plugin is configured in pom.xml.
 <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-dependency-plugin</artifactId>
                        <version>3.1.1</version>
                        <executions>
                            <execution>
                                <id>copy</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>copy</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>org.apache.derby</groupId>
                                    <artifactId>derby</artifactId>
                                    <version>10.14.2.0</version>
                                    <type>jar</type>
                                    <overWrite>false</overWrite>
                                </artifactItem>
                            </artifactItems>
                            <outputDirectory>${project.build.directory}/liberty/wlp/usr/shared/resources</outputDirectory>
                        </configuration>
                    </plugin>
                    <!-- Enable liberty-maven-plugin -->
                    <plugin>
                        <groupId>io.openliberty.tools</groupId>
                        <artifactId>liberty-maven-plugin</artifactId>
                        <version>3.1</version>
                        <configuration>
                            <libertyRuntimeVersion>20.0.0.1</libertyRuntimeVersion>
                        </configuration>
                    </plugin>

I use maven-dependency-plugin to copy the derby to ${project.build.directory}/liberty/wlp/usr/shared/resources.
But when I run mvn clean liberty:run -Popenliberty. I found the derby is copied firstly, then the liberty:run goal will remove target/liberty, how to prevent liberty maven plugin to remove this folder?
I used a Maven profile openliberty for liberty server, check the complete codes.

A: Starting from version 3.3 of the Liberty Maven Plug-in there is a copyDependencies parameter:
pom.xml
<plugins>
  <plugin>
    <groupId>io.openliberty.tools</groupId>
    <artifactId>liberty-maven-plugin</artifactId>
    <version>3.3.4</version>
    <configuration>
      <!-- Usually best to add configuration at the plugin level rather than trying to configure particular executions -->
      <copyDependencies>
        <dependencyGroup>
          <!-- Relative to server config directory -->
          <location>lib/global/jdbc</location>
          <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
          </dependency>
        </dependencyGroup>
      </copyDependencies>
    </configuration>
      ...

server.xml
...
<!-- Derby Library Configuration -->
<library id="derbyJDBCLib">
  <fileset dir="${server.config.dir}/lib/global/jdbc" includes="derby*.jar"/>
</library>
...

See documentation for further details.

A: It seems like you're running the mvn clean liberty:run -Popenliberty command after a previous build invocation that performs the app compilation, war packaging, etc. By running the clean phase in the command you provided, Maven will delete the target folder and thus the output of any previous invocations. This is not related to the behavior of the Liberty Maven Plugin.
There is an open issue in the Liberty Maven Plugin repository to support copying of dependencies into the shared resource directory.
As a workaround, you could do:
mvn clean install liberty:create dependency:copy liberty:run -Popenliberty

This way the LMP will create the server, then copy the Derby dependency, then start the server in the foreground.


text:
Q: SwiftUI - Alert doesn't dismiss. It keeps coming back .alert(isPresented:$showingAlert) {
        Alert(
            title: Text("Are you sure you want to delete this?"),
            message: Text("There is no undo"),
            primaryButton: .destructive(Text("Delete")) {
                //(using showingAlert = false doesn't help.)
                //(leaving this section empty doesn't help as well so any code written here is unrelated.)
                unrelatedCode()
            },
            secondaryButton: .cancel()
        )
    }

Why does this code result in alert coming back to screen no matter which button I press on it?
Here's a vid for easier understanding:  https://imgur.com/a/hN5yC3t
Edit: Seems like a bug on swiftui's side I guess. Guess I'll work around it.
Edit 2: Everything that could be related to the issue:
struct EditProcessView: View {
@State var problem:Bool = false
@State var showingAlert = false

@State var text = ""
var body: some View {
    Form{
        //2 unrelated pickers.

        //Unrelated textfield
        Button("Delete"){
            showingAlert = true //Are you sure you want to delete this? Button.
        }
    }
    .frame(minWidth: 200, idealWidth: 200)
    .alert(isPresented: $problem) {Alert.init(title: Text("Fill the textfield with a number."))}
    .alert(isPresented:$showingAlert) {
        Alert(
            title: Text("Are you sure you want to delete this?"),
            message: Text("There is no undo."),
            primaryButton: .destructive(Text("Delete")) {
                //Unrelated code.

            },
            secondaryButton: .cancel()
        )
    }
}

A: The alert handles its own dismissal when the user taps one of the buttons in the alert, by setting the bound isPresented value back to false.
@State private var showAlert = false
var body: some View {
    Button("Tap to show alert") {
        showAlert = true
    }
    .alert(isPresented: $showAlert) {
        Alert(
            title: Text("Unable to Save Workout Data"),
            message: Text("The connection to the server was lost."),
            primaryButton: .default(
                Text("Try Again"),
                action: saveWorkoutData
            ),
            secondaryButton: .destructive(
                Text("Delete"),
                action: deleteWorkoutData
            )
        )
    }
}

A: Fatemeh's answer solved the issue, I faced the same issue in iOS 15. And in iOS 16, I can use .toogle() in the button to dismiss the alert with no issue.
.alert(Text("Instruction"), isPresented: $showHelp, actions: {
  Button {
   showHelp.toggle() //need to remove this in iOS 15, but no need to remove in iOS 16
  } label: {
    Text("OK")
  }
}, message: {
  Text("some text")
})


text:
Q: Get the index of an original list after removing entries Let's say I have a list:
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

I then have another list with indexes of which indexes I have to remove from the original_list:
remove_list = [0, 4, 6]

I then use Numpy to remove/delete these indexes:
final_list = np.delete(original_list, remove_list, axis = 0]

All good, let's say I now wish to find the max value of the final_list with np.amax(final_list). Is there now any way I can figure out which index this value had in the original_list?

A: Option 1: np.where:
>>> np.where(original_list == np.amax(final_list))
(array([8]),)

Option 2: .index()
>>> original_list.index(np.amax(final_list))
8

Note: If there are more than one matching indices, this method will only return the first / smallest index. If you want all indices, use np.where as above

A: Here is another way you could do this,
mask = np.zeros(original_list.shape, dtype=np.bool)
mask[remove_list] = True

np.ma.MaskedArray(original_list, mask=mask).argmax()


text:
Q: Save an std::map> in Oracle12c How do I store an array of numbers in an Oracle column?
I have an std::map> mymap and I want to store all data in the mymap in the table.
The table should have two columns

*

*an id, the key of the mymap

*and this is what I am looking here

What data type is needed to store the std::vector which represents the value of my key?
How it is done in Oracle12c?

A: You could serialize the vector to a comma separated list of numbers (or some other format) and store that, then deserialize when reading. Just one of many options. Another would be to store the individual numbers in some other table with a key indicating they are the same "vector". It could be solved in many ways.


text:
Q: Union of a sequence of path connected sets being path connected Theorem:
Let ${A_n}$ be a sequence of path connected subsets of a space $X$ such that for each integer $n\ge 1$, $A_n$ has at least one point in common with one the preceding sets $A_1, ..., A_{n-1}$. Then $\bigcup_{n=1}^\infty A_n$ is path connected.
I am trying to prove this theorem however, I'm having trouble constructing a proof because I don't know how to deal with the condition that $A_n$ has at least one point in common with one the preceding sets $A_1, ..., A_{n-1}$. How can I prove this theorem?

A: Let $x, y \in \bigcup_{n=1}^\infty A_n$. Then by definition, $x\in A_n$ and $y\in A_m$ for some $m, n$. So it suffices to show that
$$\bigcup_{n=1}^K A_n$$
is path connected for all $K$, given the condition. We can do induction on $K$. So it suffices to show that if $A_1, A_2 \subset X$ are two path connected subset in $X$ with $A_1\cap A_2 \neq \emptyset$, then $A_1\cup A_2$ is also path connected. Is that easier now?

A: To show that a space is path connected is to show that if $x,y$ are two points in that space, there is a path from $x$ to $y$.
If $x,y\in\bigcup_{n=1}^\infty A_n$ then for some index $j$ we have $x\in A_j$ and for some index $k$ we have $y\in A_k$.
The set $A_j$ has a point $x_\ell$ in common with $A_\ell$ for some $\ell<j$, and $A_k$ has a point $x_m$ in common with $A_m$ for some $m<k$.  So there's a path from $x$ to $x_\ell$ and there's a path from $y$ to $y_m$.  Then $A_\ell$ has a point in common with some point in some subset with a smaller index than $\ell$ and that one has a point in common with some subset with a still smaller index, and so on.  EXCEPT, that we cannot go on forever getting smaller numbers in the set $\{1,2,3,\ldots\}$.  So eventually we'll have a path from $x$ to some point in $A_1$.  And similarly a path from $y$ to some point in $A_1$.  And then we can draw a path connecting those two points in $A_1$.  Hence a path from $x$ to $y$.
(Of course, it's possible that we'll get a path from $x$ to $y$ without going as far as $A_1$, but if all else fails, that does it.)


text:
Q: While Loop Won't Exit I am trying to make a Hangman game in Java, I use 3 Strings to process the game. randWord is the word randomly selected word from a designated word list array (WORD_LIST), randWordExt is the randWord in extended format (e.g. penguin -> p e n g u i n), and guessWord is the String that gets updated while the player guesses.
    static String[] WORD_LIST =
    {
        //list of words implemented here
    };
    static String randWord;
    static String randWordExt = "";
    static String guessWord = "";
    static int LIVES = 10;

This is my main method where the problem is, the while loops is not exiting when the word is completely solved. Hence the final message is never displayed. It loops through perfectly, guessing works, but when the word is solved it doesn't exit the loop or display the final message.
    public static void main(String[] args) {

    boolean running = true;
    Scanner input = new Scanner(System.in);

        generateWord();
        System.out.println("You have " + LIVES + " lives to guess the word! \n" + guessWord);
        while(running){

            guessLetter(input.next().charAt(0));
            if(guessWord == randWordExt){

                running = false;

            } else {

                System.out.println(guessWord);
                System.out.println("Lives left: " + LIVES);

            }

        }
        input.close();

        System.out.println("The word was " + randWord + ", you guessed it in " + " moves!");

    }

The generateWord method:
public static void generateWord(){

    randWord = WORD_LIST[(int)(Math.random() * 87)];

    for(int i = 0; i < randWord.length(); i++){

        guessWord = guessWord + "_ ";

    }

    for(int i = 0; i < randWord.length(); i++){

        randWordExt = randWordExt + randWord.charAt(i) + " ";

    }

}

And finally the guessLetter method:
public static void guessLetter(char letter){

    boolean changed = false;

    for(int i = 0; i < randWordExt.length(); i++){

        if(!(guessWord.charAt(i) == letter)){

            if(randWordExt.charAt(i) == letter){

                guessWord = guessWord.substring(0, i) + letter + guessWord.substring(i + 1);
                changed = true;

            } else if (randWordExt.charAt(i) != letter && i == randWordExt.length() - 1 && changed == false){

                LIVES -= 1;
                System.out.println("\'" + letter + "\'" + " is not in the word!");

            }

        } else {

            System.out.println("\'" + letter + "\'" + "has already been guessed!");

        }

    }

}


text:
Q: How do I return a reference to something inside a RefCell without breaking encapsulation? I have a struct that has inner mutability.
use std::cell::RefCell;

struct MutableInterior {
    hide_me: i32,
    vec: Vec<i32>,
}
struct Foo {
    //although not used in this particular snippet,
    //the motivating problem uses interior mutability
    //via RefCell.
    interior: RefCell<MutableInterior>,
}

impl Foo {
    pub fn get_items(&self) -> &Vec<i32> {
        &self.interior.borrow().vec
    }
}

fn main() {
    let f = Foo {
        interior: RefCell::new(MutableInterior {
            vec: Vec::new(),
            hide_me: 2,
        }),
    };
    let borrowed_f = &f;
    let items = borrowed_f.get_items();
}

Produces the error:
error[E0597]: borrowed value does not live long enough
  --> src/main.rs:16:10
   |
16 |         &self.interior.borrow().vec
   |          ^^^^^^^^^^^^^^^^^^^^^^ temporary value does not live long enough
17 |     }
   |     - temporary value only lives until here
   |
note: borrowed value must be valid for the anonymous lifetime #1 defined on the method body at 15:5...
  --> src/main.rs:15:5
   |
15 | /     pub fn get_items(&self) -> &Vec<i32> {
16 | |         &self.interior.borrow().vec
17 | |     }
   | |_____^

The problem is that I can't have a function on Foo that returns a borrowed vec, because the borrowed vec is only valid for the lifetime of the Ref, but the Ref goes out of scope immediately.
I think the Ref must stick around because:

RefCell<T> uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can claim temporary, exclusive, mutable access to the inner value. Borrows for RefCell<T>s are tracked 'at runtime', unlike Rust's native reference types which are entirely tracked statically, at compile time. Because RefCell<T> borrows are dynamic it is possible to attempt to borrow a value that is already mutably borrowed; when this happens it results in task panic.

Now I could instead write a function like this that returns the entire interior:
pub fn get_mutable_interior(&self) -> std::cell::Ref<MutableInterior>;

However this potentially exposes fields (MutableInterior.hide_me in this example) that are really private implementation details to Foo.
Ideally I just want to expose the vec itself, potentially with a guard to implement the dynamic borrowing behavior. Then callers do not have to find out about hide_me.

A: You can wrap the Vec in an Rc.
use std::cell::RefCell;
use std::rc::Rc;

struct MutableInterior {
    hide_me: i32,
    vec: Rc<Vec<i32>>,
}
struct Foo {
    interior: RefCell<MutableInterior>,
}

impl Foo {
    pub fn get_items(&self) -> Rc<Vec<i32>> {
        self.interior.borrow().vec.clone() // clones the Rc, not the Vec
    }
}

fn main() {
    let f = Foo {
        interior: RefCell::new(MutableInterior {
            vec: Rc::new(Vec::new()),
            hide_me: 2,
        }),
    };
    let borrowed_f = &f;
    let items = borrowed_f.get_items();
}

When you need to mutate the Vec, use Rc::make_mut to obtain a mutable reference to the Vec. If there are still other Rcs referring to the Vec, make_mut will dissociate the Rc from the other Rcs, clone the Vec and update itself to refer to that new Vec, then give you a mutable reference to it. This ensures that the value in the other Rcs doesn't suddenly change (because Rc by itself doesn't provide interior mutability).

A: Instead of creating a brand new type, you can use Ref::map (since Rust 1.8). This has the same result as Levans' existing answer:
use std::cell::Ref;

impl Foo {
    pub fn get_items(&self) -> Ref<'_, Vec<i32>> {
        Ref::map(self.interior.borrow(), |mi| &mi.vec)
    }
}

You can also use new features like impl Trait to hide the Ref from the API:
use std::cell::Ref;
use std::ops::Deref;

impl Foo {
    pub fn get_items(&self) -> impl Deref<Target = Vec<i32>> + '_ {
        Ref::map(self.interior.borrow(), |mi| &mi.vec)
    }
}

A: You can create a new struct similar to the Ref<'a,T> guard returned by RefCell::borrow(), in order to wrap this Ref and avoid having it going out of scope, like this:
use std::cell::Ref;

struct FooGuard<'a> {
    guard: Ref<'a, MutableInterior>,
}

then, you can implement the Deref trait for it, so that it can be used as if it was a &Vec<i32>:
use std::ops::Deref;

impl<'b> Deref for FooGuard<'b> {
    type Target = Vec<i32>;

    fn deref(&self) -> &Vec<i32> {
        &self.guard.vec
    }
}

after that, update your get_items() method to return a FooGuard instance:
impl Foo {
    pub fn get_items(&self) -> FooGuard {
        FooGuard {
            guard: self.interior.borrow(),
        }
    }
}

and Deref does the magic:
fn main() {
    let f = Foo {
        interior: RefCell::new(MutableInterior {
            vec: Vec::new(),
            hide_me: 2,
        }),
    };
    let borrowed_f = &f;
    let items = borrowed_f.get_items();
    let v: &Vec<i32> = &items;
}


text:
Q: Locus of centroid of a $\triangle{ABC}$ with $A=(\cos\alpha,\sin\alpha)$, $B=(\sin\alpha,-\cos\alpha)$, and $C=(1,2)$
If $A(\cos\alpha, \sin\alpha)$, $B(\sin\alpha, -\cos\alpha)$ and $C(1,2)$ are the vertices of $\triangle ABC$, find the locus of the triangle's centroid as $\alpha$ varies.

Let centroid be $(h,k)$,
$$(h,k)\equiv\left(\frac{\sin(\alpha) + \cos(\alpha) + 1}{3},\frac{\sin(\alpha) - \cos(\alpha) + 2}{3}\right)\tag{1}$$
How to proceed further? Hints would be appreciated!

As suggested by @wonderman
From $(1)$,
$$\sin(\alpha) + \cos(\alpha) = 3h - 1 \qquad \sin(\alpha) - \cos(\alpha) = 3k - 2$$
When we square the above and add,
$$ (3h - 1)^2 + (3k - 1)^2 = 2$$
Substituting $h$ as $x$ and $k$ as $y$,
$$3x^2 + 3y^2 - 2h - 4k + 1 = 0$$

A: Consider $(\sin \alpha + \cos \alpha)^2 + (\sin \alpha - \cos \alpha)^2$.  What does this work out to?

A: The centroid of $ABC$ lies on the segment joining $C$ with the midpoint $M$ of $AB$, precisely at $\frac{2}{3}$ of such segment.
In your problem $M$ travels from $(-1,0)$ to $(1,0)$ and $C$ is fixed, so the locus of centroids is a segment with endpoints $(-1/3,2/3)$ and $(1,2/3)$.


text:
Q: How to check outlook is the default mail client I use this code to check if outlook is the default mail client:
Function IsOutlookIsDefaultEmailPrg:Boolean;
var
  reg: TRegistry;
  key : string;
begin
  Result := False;
  with TRegistry.Create do
  TRY
    RootKey := HKEY_LOCAL_MACHINE;
    if OpenKeyReadOnly('Software\Clients\Mail') then
    begin
      key := Uppercase(ReadString('')); //default value
    end;
    result :=  (Pos('MICROSOFT OUTLOOK',Key) > 0);
  FINALLY
    Free;
  END;
end;

it works in general, but on some pc's it has been reported not to work, I checked and the registry key was there.
Is Pos case sensitive? Any idea why this cannot work at times? Any better suggestion?

A: I see you are using the HKLM key to check the default client but this can be user depended, so you should really check the HKCU entry (and fall back to HKLM if HKCU does not have the entry).
I also removed the With statement and used the ContainsText (include StrUtils unit) function instead of Pos :
function IsOutlookTheDefaultEmailClient:Boolean;
var
  Reg : TRegistry;
begin
  Result := False;
  Reg := TRegistry.Create;
  try
    // first check HKCU
    Reg.RootKey := HKEY_CURRENT_USER;
    if Reg.OpenKeyReadOnly('Software\Clients\Mail') then
     begin
      Result := ContainsText(Reg.ReadString(''), 'Microsoft Outlook');
      Reg.CloseKey;
     end
    // fall back to HKLM
   else
    begin
     Reg.RootKey := HKEY_LOCAL_MACHINE;
     // this part is susceptible to registry virtualization and my need elevation!
     if Reg.OpenKeyReadOnly('Software\Clients\Mail') then
      begin
       Result := ContainsText(Reg.ReadString(''), 'Microsoft Outlook');
       Reg.CloseKey;
      end;
    end;
  finally
    Reg.Free;
  end;
end;

EDIT
The only time this code can fail is when Registry virtualization comes into play. This is typical in UAC scenarios.
Please check on a failing computer if this key exists in regedit:
HKCU\Software\Classes\VirtualStore\MACHINE\SOFTWARE\Clients\Mail

if that is the case, your application will read this key and not the real HKLM key. The only solution is request elevation or run your application as administrator.

A: This is my understanding of the issues:

*

*The Pos function is case-sensitive. So if the value is Microsoft Outlook then your test will not find it. You should instead use ContainsText. Not only does that do what you want, but it is much more readable than Pos()>0.

*The system checks first in HKCU\Software\Clients\Mail. If no default mail client is found there, then it checks in HKLM\Software\Clients\Mail. You should do likewise.

*On Windows 7 and later, both HKCU\Software\Clients and HKLM\Software\Clients\Mail are shared. On earlier versions of Windows they are redirected. There is potential for errors there. You should use KEY_WOW64_64KEY to access the 64 bit view of the registry.


text:
Q: getUser() only returning 0 now; was working yesterday? I have an app where the Facebook Login was working great as of yesterday.  I switched to AWS EC2 to get a bigger server for some capacity planning for today.
Unfortunately, the Facebook Login is no longer working.  In particular, after getting the access_token from the JavaScript authorization, the getUser() call returns only 0.  The code is below.
Since the server is the only thing that has changed (and IP) is there some configuration related to my server that I'm missing/unaware of?
if(isset($_GET["access_token"])) {
    $access_token = $_GET["access_token"];
    $facebook = new Facebook(array(
        'appId' => FACEBOOK_APP_ID,
        'secret' => FACEBOOK_SECRET,
    ));
    $facebook->setAccessToken($access_token);
    $user = $facebook->getUser();
    if($user) {
        try {
            $user_profile = $facebook->api('/me');

            $user_name = $user_profile["name"];
            $user_email = $user_profile["email"];
            $fb_uid = $user_profile["id"];
            $fb_access_token = $access_token;

        } catch (FacebookApiException $e) {
            $status_header = 'HTTP/1.1 500 Internal Server Error';
            header($status_header);
            header('Content-type: application/json');

            echo json_encode(array('message' => 'Facebook Exception'));
            exit;
        }
    } else {
        $status_header = 'HTTP/1.1 500 Internal Server Error';
        header($status_header);
        header('Content-type: application/json');

        echo json_encode(array('message' => 'Facebook user does not exist', 'access_token' => $access_token, 'user' => $user, 'fb' => $facebook));
        exit;
    }

}

A: Verify the FACEBOOK_APP_ID and FACEBOOK_SECRET values are the correct ones and that the url you are accessing the site from is set as the site url and site domain on the application settings page.
Otherwise verify the PHP SDK versions are the same and the PHP versions are the same. This may help narrow down the problem.

A: Two possible ideas:

*

*The Curl library you are using on that system is not working properly. Try doing the call from the shell using some of the examples that are scattered around FB's site.

*I once moved an app to a different server and had FB API calls inexplicably not work -- on the exact same code, after an rsync -- despite updating the new server IPs to be in our whitelist. I surmise that either the Facebook Developer App whitelist updating feature is broken or that IP was banned permanently from all of Facebook's APIs. If all else fails, try moving to a different EC2 instance in a different availability zone to see if it works there.
p.s. At the time, I emailed Facebook's "contact me if you have any problems" developer rep to check if the IP updating might be broken, but of course I got no response from the helpful team over there.


text:
Q: Having Trouble outputting to a file I have this simple code here
import os

path = (raw_input("Enter dir: "))
f = open('script_list.log', 'w')
for dirpath, dirname, filenames in os.walk(path):
  for filename in [f for f in filenames]:
    f.write(str(filename) + "\n")
    print os.path.join(dirpath, filename)

When I run it I am getting the following
Enter dir: scripts
Traceback (most recent call last):
  File "C:\Documents and Settings\CRichards\My Documents\My Dropbox\this_code.py", line 8, in <module>
    f.write(str(filename) + "\n")
AttributeError: 'str' object has no attribute 'write'

I know it must be something simple, I just can't see it.

A: You're rebinding f in the loop when you do [f for f in filenames]. When you get to the point where f.write is called, f is the last member of filenames, so it's a string. Rename the outer f to something like log or output, or better, get rid of the useless list comprehension:
for file name in filenames:

suffices.
(List comprehensions don't introduce a new scope.)

A: for filename in [f for f in filenames]:

should instead be
for filename in filenames:


text:
Q: Add a new row below when the documents identifies a number (1, 2, 3, 4, 5, 6) in the upper row We have a table with different columns. One of the columns indicates how many people we will accommodate in an apartment. We need to create as many new rows as there are people in the apartment. The code I have now is to add 1 row below range X:X. I need a number of rows X to be added based on the number that appears in column K and not based on the selected range.
I have achieved the function to add X number of rows below, but I cannot find the way to identify de number and activate the action.
Image of the table
Final result
function guests2() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('2:2').activate();
  spreadsheet.getActiveSheet().insertRowsAfter(spreadsheet.getActiveRange().getLastRow(), 1);
  spreadsheet.getActiveRange().offset(spreadsheet.getActiveRange().getNumRows(), 0, 1, spreadsheet.getActiveRange().getNumColumns()).activate();
  spreadsheet.getRange('3:3').activate();
  spreadsheet.getActiveSheet().insertRowsAfter(spreadsheet.getActiveRange().getLastRow(), 1);
  spreadsheet.getActiveRange().offset(spreadsheet.getActiveRange().getNumRows(), 0, 2, spreadsheet.getActiveRange().getNumColumns()).activate();
  spreadsheet.getRange('4:4').activate();
  spreadsheet.getActiveSheet().insertRowsAfter(spreadsheet.getActiveRange().getLastRow(), 1);
  spreadsheet.getActiveRange().offset(spreadsheet.getActiveRange().getNumRows(), 0, 3, spreadsheet.getActiveRange().getNumColumns()).activate();
  spreadsheet.getRange('5:5').activate();
  spreadsheet.getActiveSheet().insertRowsAfter(spreadsheet.getActiveRange().getLastRow(), 1);
  spreadsheet.getActiveRange().offset(spreadsheet.getActiveRange().getNumRows(), 0, 4, spreadsheet.getActiveRange().getNumColumns()).activate();
  spreadsheet.getRange('6:6').activate();
  spreadsheet.getActiveSheet().insertRowsAfter(spreadsheet.getActiveRange().getLastRow(), 1);
  spreadsheet.getActiveRange().offset(spreadsheet.getActiveRange().getNumRows(), 0, 5, spreadsheet.getActiveRange().getNumColumns()).activate();
  spreadsheet.getRange('7:7').activate();
  spreadsheet.getActiveSheet().insertRowsAfter(spreadsheet.getActiveRange().getLastRow(), 1);
  spreadsheet.getActiveRange().offset(spreadsheet.getActiveRange().getNumRows(), 0, 6, spreadsheet.getActiveRange().getNumColumns()).activate();
};

A: Based on your problem statement in comment and final result image:-

the only thing is that I don't need to add rows bades on the sum of
the guest in column K. Just based on the value in each row. I have add
the image of the final result. Ej - 1 guest -> Add 1 row below. 2
guests -> add 2 rows below...

Try this sample script:-
function addRows()
{
  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const ssSource = ss.getSheetByName('replace it with sheet name') // put your sheet name in quotes
  const range = ssSource.getRange('K:K').getValues().flat();
  var addedRow = 1
  var lastadded = 0
  for( var i = 1 ; i < range.length ; i++)
  {
    try
    {
      addedRow = addedRow + lastadded + 1
      ssSource.insertRowsAfter(addedRow, range[i])
      lastadded = range[i]
    }
    catch(err)
    {
       console.log(err)
    }
  }
}

Reference:-
insertRowsAfter()


text:
Q: Nodes in Windows Forms So I have experience in C++ and I am now messing around in C# .NET with the Windows Forms. I know how to create a new Form, which I can use as a new window. And that you can also create user control, a component or a normal class.
Now I made an application in C++ but I want to convert it to C# .NET. In C++ I made the whole gui myself. But I want to do that now in C# .NET for practice.
In that application, the user could create nodes (Like you can in unreal engine 4 in the blueprints, see example picture)
Now I am unsure what would be the best way to do this in Windows forms.
Making a new form doesn't seem like the correct way. Because the nodes have to be inside of the main screen. And you should be able to move the grid which hold the nodes. So nodes shouldnt be able to exit the main screen that holds them.
Is it better to create it from scratch myself in a class? Or can I achieve this with a user control or component class? I do not understand what the best use of these classes are and what they are used for.
So I want to make something like this, and the question is what is the best type of class to make the nodes with?:

A: I think you should use WPF to obtain node-base UI. I developed a program with such an interface in WPF and it was pretty simple (I didn't have any experience in WPF):

You can create almost every layout you want using grids, borders, stackpanels, dockpanels, paths etc.


text:
Q: Value not being bound to selected option in Select Menu I have a <select> control on my Blazor page with 3 options. I am setting selected on the option of "Bear". If the user does not touch the <select> control, I want the bound value to equal "Bear".
However, what I notice is that it only updates the bound value to what I select AFTER I update the <select> control. How do I force it to take the selected value when the <select> component is never touched?
<select @bind="selectedValue">
    <option value="Apple">Apple</option>
    <option selected="selected" value="Bear">Bear</option>
    <option value="John Cena">John Cena</option>
</select>

Selected Value: @selectedValue

@code {

    string selectedValue;
}

Apprently, Blazor Fiddle exists: https://blazorfiddle.com/s/d3flx9tc

A: Just assign the value "Bear" to selectedValue, like the following:
string selectedValue = "Bear";

And remove the attribute selected="selected"
Now, "Bear" is selected, and the variable selectedValue contains the string "Bear". This is how you should initialize your elements.
Incidentally, you should use only selected without ="selected". It is meaningless. You could use selected="DoNotSelectMe", and it will still work


text:
Q: KeyboardAvoidingView not working with Expo I cannot seem to get the keyboard to push the content up in my React-Native Expo app. I am testing this from the expo App by publishing it from my development machine.
Try as I might, nothing seems to push the view up when the keyboard comes into focus, is there a specific order of components, or some property I am missing; I have included the versions, the render block and the style blocks I think which are relevant.
I am using the following versions (latest);
"expo": "^29.0.0",
"react": "16.3.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-29.0.0.tar.gz",

For the login page, the render code looks like the following;
 render() {
    return (
      <SafeAreaView style={styles.flexContainer}>
      <KeyboardAvoidingView
        style={styles.flexContainer}
        behavior="padding"
      >
        <Image style={styles.image} source={require('../../assets/images/backgroundWelcome.png')} role="presentation" />
        <View style={styles.container}>
          <View style={[styles.row, styles.border]}>
            <TextInput
              placeholder='Email'
              style={styles.input}
              onChangeText={(input) => this.setState({email: input})}
              value={this.state.email}
            />
          </View>
          <View style={[styles.row, styles.border]}>
            <TextInput
              placeholder='Password'
              style={styles.input}
              secureTextEntry={true}
              onChangeText={(input) => this.setState({password: input})}
              value={this.state.password}
            />
          </View>

          <View style={styles.row}>


text:
Q: Akka -- Deploy two ActorSystems on the same host I'm writing this as a follow up to PlayFramework -- Look up actors in another local ActorSystem, but this time targetting the question specifically to the Akka crowd.
The question is simple: Does it make sense to deploy two ActorSystems on the same host (not just on the same host but even on the same JVM), given that there appears to be no way to simply lookup the other system through system.actorSelection unless you remote to localhost?
In other words, since system1.actorSelection("akka://system2/user/my-actor") does not work, but system1.actorSelection("akka.tcp://system2@127.0.0.1:2552/user/my-actor") does, why even consider deploying two systems?
I suspect you're going to ask about a use case, so here's one for you. Assume I have a complex real-time system using Akka and that this system is deployed as autonomous agents on any number of machines. Ideally, I'd like to have fine-grained control of the resources I allocate to this system and I'd like it to be somewhat isolated. Furthermore, assume that I want to write a small control interface (e.g., a REST API) with the specific purpose to provide input and monitor the real-time system. Naturally, I would make that control system another ActorSystem which interacts with the first system. It makes sense, right? I don't want to have actors running in the same ActorSystem as the real-time processing (for isolation, practicality, separate logging, non pollution of resource monitoring, supervision -- that would add one more branch to the hierarchy --, etc.). That control ActorSystem would never be deployed on a separate machine since it goes hand in hand with the real-time system. Yet, the only way for these two systems to communicate is through loopback tcp.
Is what I'm suggesting not the proper/intended way to do things? Am I missing something? Is there a way to do this that I haven't considered? Does my use case even call for using Akka?
Thanks in advance for your input!

A: Instead of having two separate actor systems, you could have a top level actor for each of the branches and run each branch on a dedicated dispatcher. Each top level actor will have its own error kernel as well. Having 2 actor systems mostly makes sense, when they are not related, but as yours communicate, I would not separate them.


text:
Q: Rails automated testing of POROs in a app/lib directory I want to include some additional non-rails classes in my Rails App. I created a lib directory under app/ and a lib directory under test/ I am using minitest.
How do I make it so rails test also runs the tests under the new test/lib directory? How do I make it so my app includes app/lib in the autoload mechanism?

A: In the application.rb file add the following configuration which will load files from the app/lib folder
config.autoload_paths += "#{Rails.root}/app/lib/"


text:
Q: Can't configure WebPack to work with SASS files I'm using WebPack and now I'm going to need to do the compilation of SASS fiels (we'll be working with Bootstrap). First of all, I installed node-sass and sass-loader (not sure if any of those is needed at all). Then, in my server.js I've added the following line (nothing more that would refer to the Sass object, yet).
import Sass from "node-sass";

The compilation gave me errors that fs package is missing so based on this answer I've tried the following (both individually and simultaneously). The error about fs disappeared but instead there's something about unexpected token in the package.json of the node-sass module.
node: { fs: "empty" },
target: "node",
...

I have no idea what those would do and how those affect anything. Both seem to be produce the same error. Any light on that would be an extra bonus as they appear quite different from each other.
Then, I also tried to enable to the loader in my webpack.config.js by the following addition suggested here. Even tried to map the source like described here. Another post suggests using a different syntax for target specification... Nothing seems to help and finally I got totally confused and gave up.
module: {
  loaders: [
    { test: /\.js$/, loader: "babel", exclude: /node_modules/ },
    { test: /\.scss$/, loader: 'style!css!sass' }
  ]
},
sassLoader: { sourceMap: true },
...

Some of the posts I'm reading are old and I feel that they might be outdated and do more harm than good. And there seems to be quite a few posts not answered that regard the connection between WebPack and SASS (e.g. this and this). I fear that I might be barking up the wrong tree...
I need help being pointed in the right direction.

A: There should be no need to write import Sass from "node-sass"; anywhere in your code. The node-sass package is part of your build-pipeline which is using webpack and thus running in a node environment. But your front-end code typically does not have any connection to a node env because it's running in the browser. This also explains why you got errors related to fs. You should also get rid of your node: { fs: "empty" }, target: "node", ... stuff. In a pure front-end related webpack pipeline you shouldn't need those hacks.
Try the following in your webpack.config.js file:
module.exports = {
  ...
  module: {
    loaders: [
      {
        test: /\.scss$/,
        loaders: ["style-loader", "css-loader", "sass-loader"]
      }
    ]
  }
};

To get things going don't use source-maps from the beginning, but add them once the rest of the setup is running. To get sourcemaps each loader must re-use the result from the previous loader, which is why you should start with having a look how sourcemaps are configured for sass-loader.


text:
Q: Gyroscope Issues with Device Orientation I'm getting pitch and roll data from my device's gyroscope using this tutorial: http://www.thousand-thoughts.com/2012/03/android-sensor-fusion-tutorial/
All the readings are extremely accurate (there's a filter applied to the code in the tutorial to eliminate gyro drift). Unfortunately, the code only works when my device is placed flat on a surface that is parallel to the ground. The most ideal position for my app to work would be with the top of the device pointing straight up (ie, the device is perpendicular to the ground with the screen facing the user). Whenever I orient my device in this position, the pitch values go to +90 degrees (as expected). What I would like to do is set this position as the 0 degree point (or initial position) for my device so that the pitch readings are 0 degrees when my device is oriented upright (in portrait mode) with the screen facing the user.
I asked the author of the tutorial with help on this issue and he responded:
"If you want to have the upright position as the initial one, you will have to rotate your frame of reference accordingly. The simplest way would be to rotate the resulting rotation matrix by -90 degrees about the x-axis. But you have to be careful about at which point in the algorithm to apply this rotation. Always remember that rotations are not commutative operations. To be more specific on this, I would have to review the code again, since I haven't worked with it for a while now."
I'm really really confused and stumped as to how to rotate my frame of reference. I guess the bottom line is that I have no idea how to rotate the matrix by -90 degrees about the x-axis. If someone could help me out with this part, it would be fantastic. Here's my code in case anyone would like to refer to it:
public class AttitudeDisplayIndicator extends SherlockActivity implements SensorEventListener {

private SensorManager mSensorManager = null;

// angular speeds from gyro
private float[] gyro = new float[3];

// rotation matrix from gyro data
private float[] gyroMatrix = new float[9];

// orientation angles from gyro matrix
private float[] gyroOrientation = new float[3];

// magnetic field vector
private float[] magnet = new float[3];

// accelerometer vector
private float[] accel = new float[3];

// orientation angles from accel and magnet
private float[] accMagOrientation = new float[3];

// final orientation angles from sensor fusion
private float[] fusedOrientation = new float[3];

// accelerometer and magnetometer based rotation matrix
private float[] rotationMatrix = new float[9];

public static final float EPSILON = 0.000000001f;
private static final float NS2S = 1.0f / 1000000000.0f;
private float timestamp;
private boolean initState = true;

public static final int TIME_CONSTANT = 30;
public static final float FILTER_COEFFICIENT = 0.98f;
private Timer fuseTimer = new Timer();

// The following members are only for displaying the sensor output.
public Handler mHandler;
DecimalFormat d = new DecimalFormat("#.##");

//ADI background image.
private ImageView adiBackground;

//ADI axes.
private ImageView adiAxes;

//ADI frame.
private ImageView adiFrame;

//Layout.
private RelativeLayout layout;

//Pitch and Roll TextViews.
private TextView pitchAngleText;
private TextView bankAngleText;

//Instantaneous output values from sensors as the device moves.
public static double pitch;
public static double roll;

//Matrix for rotating the ADI (roll).
Matrix mMatrix = new Matrix();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_attitude_display_indicator);

    gyroOrientation[0] = 0.0f;
    gyroOrientation[1] = 0.0f;
    gyroOrientation[2] = 0.0f;

    // initialise gyroMatrix with identity matrix
    gyroMatrix[0] = 1.0f; gyroMatrix[1] = 0.0f; gyroMatrix[2] = 0.0f;
    gyroMatrix[3] = 0.0f; gyroMatrix[4] = 1.0f; gyroMatrix[5] = 0.0f;
    gyroMatrix[6] = 0.0f; gyroMatrix[7] = 0.0f; gyroMatrix[8] = 1.0f;

    // get sensorManager and initialise sensor listeners
    mSensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
    initListeners();

    // wait for one second until gyroscope and magnetometer/accelerometer
    // data is initialised then scedule the complementary filter task
    fuseTimer.scheduleAtFixedRate(new calculateFusedOrientationTask(),
                                  1000, TIME_CONSTANT);

    mHandler = new Handler();
    adiBackground = (ImageView) findViewById(R.id.adi_background);
    adiFrame = (ImageView) findViewById(R.id.adi_frame);
    adiAxes = (ImageView) findViewById(R.id.adi_axes);

    layout = (RelativeLayout) findViewById(R.id.adi_layout);
    new Color();
    layout.setBackgroundColor(Color.rgb(150, 150, 150));

    pitchAngleText = (TextView) findViewById(R.id.pitch_angle_text);
    bankAngleText = (TextView) findViewById(R.id.bank_angle_text);

}

// This function registers sensor listeners for the accelerometer, magnetometer and gyroscope.
public void initListeners(){
    mSensorManager.registerListener(this,
        mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
        SensorManager.SENSOR_DELAY_FASTEST);

    mSensorManager.registerListener(this,
        mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE),
        SensorManager.SENSOR_DELAY_FASTEST);

    mSensorManager.registerListener(this,
        mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
        SensorManager.SENSOR_DELAY_FASTEST);
}

//@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

//@Override
public void onSensorChanged(SensorEvent event) {
    switch(event.sensor.getType()) {
    case Sensor.TYPE_ACCELEROMETER:
        // copy new accelerometer data into accel array and calculate orientation
        System.arraycopy(event.values, 0, accel, 0, 3);
        calculateAccMagOrientation();
        break;

    case Sensor.TYPE_GYROSCOPE:
        // process gyro data
        gyroFunction(event);
        break;

    case Sensor.TYPE_MAGNETIC_FIELD:
        // copy new magnetometer data into magnet array
        System.arraycopy(event.values, 0, magnet, 0, 3);
        break;
    }
}

// calculates orientation angles from accelerometer and magnetometer output
    public void calculateAccMagOrientation() {
        if(SensorManager.getRotationMatrix(rotationMatrix, null, accel, magnet)) {
            SensorManager.getOrientation(rotationMatrix, accMagOrientation);
        }
    }

    // This function is borrowed from the Android reference
    // at http://developer.android.com/reference/android/hardware/SensorEvent.html#values
    // It calculates a rotation vector from the gyroscope angular speed values.
    private void getRotationVectorFromGyro(float[] gyroValues,
            float[] deltaRotationVector,
            float timeFactor)
    {
        float[] normValues = new float[3];

        // Calculate the angular speed of the sample
        float omegaMagnitude =
        (float)Math.sqrt(gyroValues[0] * gyroValues[0] +
        gyroValues[1] * gyroValues[1] +
        gyroValues[2] * gyroValues[2]);

        // Normalize the rotation vector if it's big enough to get the axis
        if(omegaMagnitude > EPSILON) {
        normValues[0] = gyroValues[0] / omegaMagnitude;
        normValues[1] = gyroValues[1] / omegaMagnitude;
        normValues[2] = gyroValues[2] / omegaMagnitude;
        }

        // Integrate around this axis with the angular speed by the timestep
        // in order to get a delta rotation from this sample over the timestep
        // We will convert this axis-angle representation of the delta rotation
        // into a quaternion before turning it into the rotation matrix.
        float thetaOverTwo = omegaMagnitude * timeFactor;
        float sinThetaOverTwo = (float)Math.sin(thetaOverTwo);
        float cosThetaOverTwo = (float)Math.cos(thetaOverTwo);
        deltaRotationVector[0] = sinThetaOverTwo * normValues[0];
        deltaRotationVector[1] = sinThetaOverTwo * normValues[1];
        deltaRotationVector[2] = sinThetaOverTwo * normValues[2];
        deltaRotationVector[3] = cosThetaOverTwo;
    }

    // This function performs the integration of the gyroscope data.
    // It writes the gyroscope based orientation into gyroOrientation.
    public void gyroFunction(SensorEvent event) {
        // don't start until first accelerometer/magnetometer orientation has been acquired
        if (accMagOrientation == null)
            return;

        // initialisation of the gyroscope based rotation matrix
        if(initState) {
            float[] initMatrix = new float[9];
            initMatrix = getRotationMatrixFromOrientation(accMagOrientation);
            float[] test = new float[3];
            SensorManager.getOrientation(initMatrix, test);
            gyroMatrix = matrixMultiplication(gyroMatrix, initMatrix);
            initState = false;
        }

        // copy the new gyro values into the gyro array
        // convert the raw gyro data into a rotation vector
        float[] deltaVector = new float[4];
        if(timestamp != 0) {
            final float dT = (event.timestamp - timestamp) * NS2S;
        System.arraycopy(event.values, 0, gyro, 0, 3);
        getRotationVectorFromGyro(gyro, deltaVector, dT / 2.0f);
        }

        // measurement done, save current time for next interval
        timestamp = event.timestamp;

        // convert rotation vector into rotation matrix
        float[] deltaMatrix = new float[9];
        SensorManager.getRotationMatrixFromVector(deltaMatrix, deltaVector);

        // apply the new rotation interval on the gyroscope based rotation matrix
        gyroMatrix = matrixMultiplication(gyroMatrix, deltaMatrix);

        // get the gyroscope based orientation from the rotation matrix
        SensorManager.getOrientation(gyroMatrix, gyroOrientation);
    }

    private float[] getRotationMatrixFromOrientation(float[] o) {
        float[] xM = new float[9];
        float[] yM = new float[9];
        float[] zM = new float[9];

        float sinX = (float)Math.sin(o[1]);
        float cosX = (float)Math.cos(o[1]);
        float sinY = (float)Math.sin(o[2]);
        float cosY = (float)Math.cos(o[2]);
        float sinZ = (float)Math.sin(o[0]);
        float cosZ = (float)Math.cos(o[0]);

        // rotation about x-axis (pitch)
        xM[0] = 1.0f; xM[1] = 0.0f; xM[2] = 0.0f;
        xM[3] = 0.0f; xM[4] = cosX; xM[5] = sinX;
        xM[6] = 0.0f; xM[7] = -sinX; xM[8] = cosX;

        // rotation about y-axis (roll)
        yM[0] = cosY; yM[1] = 0.0f; yM[2] = sinY;
        yM[3] = 0.0f; yM[4] = 1.0f; yM[5] = 0.0f;
        yM[6] = -sinY; yM[7] = 0.0f; yM[8] = cosY;

        // rotation about z-axis (azimuth)
        zM[0] = cosZ; zM[1] = sinZ; zM[2] = 0.0f;
        zM[3] = -sinZ; zM[4] = cosZ; zM[5] = 0.0f;
        zM[6] = 0.0f; zM[7] = 0.0f; zM[8] = 1.0f;

        // rotation order is y, x, z (roll, pitch, azimuth)
        float[] resultMatrix = matrixMultiplication(xM, yM);
        resultMatrix = matrixMultiplication(zM, resultMatrix);
        return resultMatrix;
    }

    private float[] matrixMultiplication(float[] A, float[] B) {
        float[] result = new float[9];

        result[0] = A[0] * B[0] + A[1] * B[3] + A[2] * B[6];
        result[1] = A[0] * B[1] + A[1] * B[4] + A[2] * B[7];
        result[2] = A[0] * B[2] + A[1] * B[5] + A[2] * B[8];

        result[3] = A[3] * B[0] + A[4] * B[3] + A[5] * B[6];
        result[4] = A[3] * B[1] + A[4] * B[4] + A[5] * B[7];
        result[5] = A[3] * B[2] + A[4] * B[5] + A[5] * B[8];

        result[6] = A[6] * B[0] + A[7] * B[3] + A[8] * B[6];
        result[7] = A[6] * B[1] + A[7] * B[4] + A[8] * B[7];
        result[8] = A[6] * B[2] + A[7] * B[5] + A[8] * B[8];

        return result;
    }

    class calculateFusedOrientationTask extends TimerTask {
        public void run() {
            float oneMinusCoeff = 1.0f - FILTER_COEFFICIENT;

            /*
             * Fix for 179° <--> -179° transition problem:
             * Check whether one of the two orientation angles (gyro or accMag) is negative while the other one is positive.
             * If so, add 360° (2 * math.PI) to the negative value, perform the sensor fusion, and remove the 360° from the result
             * if it is greater than 180°. This stabilizes the output in positive-to-negative-transition cases.
             */

            // azimuth
            if (gyroOrientation[0] < -0.5 * Math.PI && accMagOrientation[0] > 0.0) {
                fusedOrientation[0] = (float) (FILTER_COEFFICIENT * (gyroOrientation[0] + 2.0 * Math.PI) + oneMinusCoeff * accMagOrientation[0]);
                fusedOrientation[0] -= (fusedOrientation[0] > Math.PI) ? 2.0 * Math.PI : 0;
            }
            else if (accMagOrientation[0] < -0.5 * Math.PI && gyroOrientation[0] > 0.0) {
                fusedOrientation[0] = (float) (FILTER_COEFFICIENT * gyroOrientation[0] + oneMinusCoeff * (accMagOrientation[0] + 2.0 * Math.PI));
                fusedOrientation[0] -= (fusedOrientation[0] > Math.PI)? 2.0 * Math.PI : 0;
            }
            else {
                fusedOrientation[0] = FILTER_COEFFICIENT * gyroOrientation[0] + oneMinusCoeff * accMagOrientation[0];
            }

            // pitch
            if (gyroOrientation[1] < -0.5 * Math.PI && accMagOrientation[1] > 0.0) {
                fusedOrientation[1] = (float) (FILTER_COEFFICIENT * (gyroOrientation[1] + 2.0 * Math.PI) + oneMinusCoeff * accMagOrientation[1]);
                fusedOrientation[1] -= (fusedOrientation[1] > Math.PI) ? 2.0 * Math.PI : 0;
            }
            else if (accMagOrientation[1] < -0.5 * Math.PI && gyroOrientation[1] > 0.0) {
                fusedOrientation[1] = (float) (FILTER_COEFFICIENT * gyroOrientation[1] + oneMinusCoeff * (accMagOrientation[1] + 2.0 * Math.PI));
                fusedOrientation[1] -= (fusedOrientation[1] > Math.PI)? 2.0 * Math.PI : 0;
            }
            else {
                fusedOrientation[1] = FILTER_COEFFICIENT * gyroOrientation[1] + oneMinusCoeff * accMagOrientation[1];
            }

            // roll
            if (gyroOrientation[2] < -0.5 * Math.PI && accMagOrientation[2] > 0.0) {
                fusedOrientation[2] = (float) (FILTER_COEFFICIENT * (gyroOrientation[2] + 2.0 * Math.PI) + oneMinusCoeff * accMagOrientation[2]);
                fusedOrientation[2] -= (fusedOrientation[2] > Math.PI) ? 2.0 * Math.PI : 0;
            }
            else if (accMagOrientation[2] < -0.5 * Math.PI && gyroOrientation[2] > 0.0) {
                fusedOrientation[2] = (float) (FILTER_COEFFICIENT * gyroOrientation[2] + oneMinusCoeff * (accMagOrientation[2] + 2.0 * Math.PI));
                fusedOrientation[2] -= (fusedOrientation[2] > Math.PI)? 2.0 * Math.PI : 0;
            }
            else {
                fusedOrientation[2] = FILTER_COEFFICIENT * gyroOrientation[2] + oneMinusCoeff * accMagOrientation[2];
            }

            // overwrite gyro matrix and orientation with fused orientation
            // to comensate gyro drift
            gyroMatrix = getRotationMatrixFromOrientation(fusedOrientation);
            System.arraycopy(fusedOrientation, 0, gyroOrientation, 0, 3);

            // update sensor output in GUI
            mHandler.post(updateOrientationDisplayTask);
        }
    }

Thanks in advance for your help!

A: The theory...
I'm not really sure about the format in which your "frame of reference" matrix is represented, but typically rotations are done with matrix multiplication.
Basically, you would take your "frame of reference matrix" and multiply it by a 90 degrees rotation matrix.
Such a matrix can be found on Wikipedia:
Three-dimensional rotation matrices
Since your angle is 90 degrees, your sines and cosines would resolve to 1's or 0's which you can plug  directly into the matrix instead of computing the sines and cosines. For example, a matrix that would rotate 90 degrees counter-clockwise about the x axis would look like this:
1   0   0
0   0   1
0  -1   0

Also, please not that matrices like these operate on row vectors of x y z coordinates.
So for example, if you have a point in space that is at (2,5,7) and you would like to rotate it using the above matrix, you would have to do the following operation:
|2 5 7| |1  0  0|
        |0  0  1|
        |0 -1  0|

Which gives [2 -7 5]
...applied to your code
I have glanced quickly at your code and it seems like the modification you need to make involves the output of calculateAccMagOrientation() because it is used to initialize the orientation of the device.
1: public void calculateAccMagOrientation() {
2:     if(SensorManager.getRotationMatrix(rotationMatrix, null, accel, magnet)) {
3:         SensorManager.getOrientation(rotationMatrix, accMagOrientation);
4:     }
5: }

At line 2 in the above snippet is where you get your initial rotationMatrix. Try multiplying rotationMatrix by a hand crafted 90 degrees rotation matrix before calling getOrientation at line 3. I think this will effectively re-align your reference orientation:
public void calculateAccMagOrientation() {
    if(SensorManager.getRotationMatrix(rotationMatrix, null, accel, magnet)) {
        rotationMatrix = matrixMultiplication(rotationMatrix, my90DegRotationMatrix);
        SensorManager.getOrientation(rotationMatrix, accMagOrientation);
    }
}

Please note that depending on how the angles work in Android, you might need to use a 90 degrees clockwise rotation matrix instead of a counter-clockwise.
Alternative solution
It just occurred to me, maybe you could also simply subtract 90 from the final pitch result before displaying it?


text:
Q: TNS No Listener - Only in Visual Studio, DB tool and all pings work THEN:
Wednesday before Thanksgiving all works well, all my asp.net C# projects can hit/return data from all the Oracle DBs we use.
NOW:
Come in Monday: TNS No Listener every time I run any of our apps. It happens right in page_load where the code goes to the DB to fill some screen controls, happens on the first call.
All other DB tools on my box work fine, we use Benthic Golden for our DB viewer and it hits all the DBs we use. Ping and TNSPing both return an OK. The Oracle 'Net Manager' config tool tests 'good' on the DB instances.
WHAT I'VE DONE:
I installed TortoiseSVN (ver 3.?) as well as Visual SVN for Visual Studio (ver 1.79). I have re-installed Oracle 11.1g client (administrative option). We use 32 and 64 bit installing them in that order, making sure the Environment Variable PATH is correct (it is). This morning I re-installed VS 2012 Ultimate and am still getting the error.
RECENT PC ACTIVITY:
Our company just switched over from TFS to Subversion for our code repository. I'm thinking last Wednesday I installed the latest versions (we can use) of Tortoise SVN and Visual SVN. Everyone else on my team has the same, we all stay in lock step with each other, no one else is having this issue.
RESEARCH:
2 days of research mostly has the issue 180 degrees from mine, VS can hit the DB and all other DB tools cannot. The only hit that hit close in my mind was something about how IIS hits the DB. One post said to change the Application Pool advanced settings: change 'Enable 32-bit Applications' to 'True'. That didn't work.
I wanted to at lease throw this out to StackOverFlow before I hand my hard drive over to the tech's for a rebuild and start from scratch.
CURRENT TRY/CATCH INNER EXCEPTION:
System.Exception: ORA-12541: TNS:no listener
SQL Query (TESTDB01): SELECT DISTINCT CUSTOMER_ID AS VALUE, CUSTOMER_NAME AS TEXT FROM CUSTOMERTABLE WHERE CUSTOMER_ID IS NOT NULL ---> System.Data.OracleClient.OracleException: ORA-12541: TNS:no listener
at System.Data.OracleClient.OracleException.Check(OciErrorHandle errorHandle, Int32 rc)
   at System.Data.OracleClient.OracleInternalConnection.OpenOnLocalTransaction(String userName, String password, String serverName, Boolean integratedSecurity, Boolean unicode, Boolean omitOracleConnectionName)
   at System.Data.OracleClient.OracleInternalConnection..ctor(OracleConnectionString connectionOptions)
   at System.Data.OracleClient.OracleConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
   at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
   at System.Data.OracleClient.OracleConnection.Open()
   at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet)
   at CsgSystems.DirectNet.Core.CsgSystemsDatabase.GetDataSet(String strSQL, String strInstance)


text:
Q: Visual Studio 2013 Crash When Rebuilding SalesInvoice SSRS Report I am facing VS crash problem after copying SSRS report design.
I need to modify SalesInvoice SSRS report. Our normal practice is to make a copy of the design we are going to modify before starting modification.
Before i copy the design (design_1), i do rebuild to SalesInvoice, the rebuild can be success with two warmings.
Successful Compile Msg:

After duplicated a design by copying and pasting it, i tried to rebuild the copied design, i got following error message.
Compile Error Msg:

I remove the copied design (design_1) and try to copy other design (design_2). design_2 can be rebuilt successfully.
I tried to duplicate other designs, only some of them has rebuild error.
I believe that it should be some error in those designs.
is there any way i can easily locate what and where the problem is in those report designs?
My environment is AX 2012 R3 CU11 (6.3.4000.127) with VS 2013 version update 5 (12.0.40629.00) and SQL 2012 64-bit (11.0.6567.0).
We upgraded AX from R2 to R3 this year and the report has no such issue before.

A: By reducing obsolete report design, the problem can be fixed. Too many designs will cause report size too big and it will lead VS becomes unstable when compiling.


text:
Q: jQuery select(live, change) and .ajax only firing once I have a page that has 52 drop-down menus with the class of regionalSelect.
I have bound the change event to trigger an ajax run to the controller to save to the database and the success callback function is to refresh the page.
After the refresh, the functionality no longer works.
I place this code is my document ready
 $("select.regionalSelect").live('change', function(){
        var sel = $(this).val();
        var id =      $(this).parent().parent().find("td[name=propNumber]").html();

        $.ajax({
            url:"<?php echo site_url('conn/reassignRegional'); ?>",
            type: 'POST',
            data:{ id: id, regional: sel },
            success: function(msg){
                var link = "<?php echo site_url('conn/PropertiesAndRegions'); ?>";
                window.location.href=link;
            } // end success
        }); // end ajax

    }); // end change

The controller just takes the posted values and inserts it into the database. When the page refreshes, the list is correct but additional changes can't be made.
Since I am presenting a list of our properties and their current regional directors and a mechanism to change as regionals get reassigned, the continued availability of editing is a necessity.
I have been staring at this a while and I am not that experienced a coder as it is, so I decided to ask for fresh eyes.
All help is greatly appreciated!
Thanks,
Jon

A: Do you need to be using .live()? If your select elements aren't being added dynamically to the page after it loads, then it isn't necessary. Instead, you might be able to use
$('select.regionalSelect').change(function() {
    ...
});

instead, which has mostly the same behavior but a different purpose.
Also, when redirecting with JS, you should assign your link to window.location.href instead of just window.location. And make sure your AJAX requests aren't cached (POSTs shouldn't be, but you never know).
To disable cache globally for jQuery, you can do this:
$.ajaxSetup({
    cache: false
});


text:
Q: Talking to IdentityServer4 with an Angular SPA application for authentication/authorization receiving a token then talking to Web API I have an asp.net core Web API. I am currently making calls directly to it using an Angular 4 app.
I now want to add authentication and authorization layer.
I would like to do this by adding another project (strictly for auth) of type : ASP.NET Core MVC (w/ Individual User Accounts) to my solution and then adding IdentityServer4 to it. The plan is to use the existing Identity tables to store users, roles, etc.
Once this is all setup I am a bit confused about how my Angular 4 SPA app or any other third party authenticates through the IdentityServer app. I would assume this then returns a token of some sort. Then proceeds to make calls to my original Web API project (i.e. GetCustomers()) with that token.
From the research I did it looks like the only other thing that I need is JWT bearer authentication in ASP.NET Core.
Can someone please provide me with some links/information on how to go about this entire process. Haven't found any good videos that go through the entire thing. Also, please confirm that the above pattern I am talking about sounds correct.

A: Identity Server has different flows/grant types, the one you talking about called implicit in that case Identity Server will return a jwt token so you have to be storing that jwt token on a client and then attaching that token to request header when requesting your secure webapi routes.

Official samples it is very good starting point also checkout their blog that has lots of useful info covering the topic.
Talking about the good videos on the topic here is a good one from the recent NDC conf IdentityServer4: New & Improved for ASP.NET Core also if you want to learn stuff more deeply you can checkout this pluralsignt course by Dominick Baier


text:
Q: Bash: source file executes code inside strings (Premise:)
Hi, i'm trying to read a JSON file whose content has to be copied inside a variable in a file that i'm going to need later, according to google the only way to do this is by using source. I need to avoid command execution during the sourcing tho, and, being a JSON file, all those quotes are causing me a bit of a headache.
Because of this I need to be sure that each and every one of them is escaped to be treated as plain text. I tried using sed command like this:
sed -e "s/'/\\\'/g" -e 's/"/\\"/g'

Checking again in the file i can see that every single quote has been escaped apart from the outer ones
ex: {{"foo":"bar"},{"bar":"foo}} -> VAR='{{\"foo\":\"bar\"}{\"bar\":\"foo\"}}'

Somehow when i execute the sourcing i get a lot of errors about commands and directories not existing.
(Question:)
Do you have any idea of what's going on? Is this even a viable solution to get to my goal? Is there any better way? If what i'm asking is not possible, is there any other way to use a file as a string variable store?
(Goal generic desired behaviour:)

*

*read json

*create conf file

*attach json content to variable declaration string ("VAR=$(readthejson)")

*attach variable declaration string to conf file

*source conf file

*use var as a string

(Trial specific desired behaviour:)
a=$( sed -e "s/'/\\\'/g" -e 's/"/\\"/g' myjson.json )
echo "LOCK='$a'"  >> file

The lines above successfully fill my file with json content and escapes all quotes
(example from a package-lock.json file:)
  LOCK='{
  \"name\": \"Undecided\",
  \"version\": \"0.0.1\",
  \"lockfileVersion\": 2,
  \"requires\": true,
  \"packages\": {
    \"\": {
      \"version\": \"0.0.1\",
      \"dependencies\": {
        \"@capacitor/android\": \"3.1.2\",
        \"@capacitor/app\": \"1.0.2\",
        \"@capacitor/core\": \"3.1.2\",
        \"@capacitor/haptics\": \"1.0.2\",
  ...

At this point i would expect that sourcing file would result in my strings being loaded in my script and being usable like so:
source file
echo "$LOCK"

output:
{
  "name": "Undecided",
  "version": "0.0.1",
  "lockfileVersion": 2,
  "requires": true,
  "packages": {
    "": {
      "version": "0.0.1",
      "dependencies": {
        "@capacitor/android": "3.1.2",
        "@capacitor/app": "1.0.2",
        "@capacitor/core": "3.1.2",
        "@capacitor/haptics": "1.0.2",

(Actual behaviour:)
The script escapes everything as needed. Though when i source it it outputs this:
usage: install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode]
               [-o owner] file1 file2
       install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode]
               [-o owner] file1 ... fileN directory
       install -d [-v] [-g group] [-m mode] [-o owner] directory ...
file: line 2128: },: command not found
file: line 2129: "node_modules/@hapi/bourne":: No such file or directory
file: line 2130: "version":: command not found
file: line 2131: "resolved":: command not found
file: line 2132: "integrity":: command not found
file: line 2133: "deprecated":: command not found
file: line 2134: },: command not found
file: line 2135: "node_modules/@hapi/hoek":: No such file or directory
file: line 2136: "version":: command not found
file: line 2137: "resolved":: command not found
file: line 2138: "integrity":: command not found
file: line 2139: "deprecated":: command not found
file: line 2140: },: command not found
file: line 2141: "node_modules/@hapi/joi":: No such file or directory
file: line 2142: "version":: command not found
file: line 2143: "resolved":: command not found
file: line 2144: "integrity":: command not found
file: line 2145: "deprecated":: command not found
file: line 2146: "dependencies":: command not found
file: line 2147: "@hapi/address":: No such file or directory
file: line 2148: "@hapi/bourne":: No such file or directory
file: line 2149: "@hapi/hoek":: No such file or directory
file: line 2150: "@hapi/topo":: No such file or directory
file: line 2151: syntax error near unexpected token `}'
file: line 2151: `      }'

It looks like it's ignoring backslashes, or that they get swapped with non escaped quotes and then sourced.
I mean, i would expect that echo "\"lorem\"\"ipsum\"" result in "lorem""ipsum", not in a
lorem command not found
ipsum command not found
Disclaimer: i'm not asking to code for me or debug my code (it's sad i really have to specify this)

A:
Is there any better way?

If you want to output the value to the file to be sourced later, whatever the variable value, I like to use declare -p.
lock=$(cat myjson.json)
declare -p lock >> file_to_be_sourced.sh

declare is specific to Bash, and it will always output a properly quoted string that can be sourced later. Another way is to use printf "%q".

Do you have any idea of what's going on?

"s/'/\\\'/g" part is wrong. If you start with ' quotes, you have replace ' with '\''. \ is literal when inside ' quotes. And remove the s/"/\\"/g part - just keep inside ' quotes. The difference is cool to observe when using /bin/printf which is from coreutils vs printf as bash builtin - they use different quoting "style":
$ var="a\"b'c"
$ echo "$var"
a"b'c
$ printf "%q\n" "$var"
a\"b\'c
$ /bin/printf "%q\n" "$var"
'a"b'\''c'
$ declare -p var
declare -- var="a\"b'c"

If what i'm asking is not possible, is there any other way to use a file as a string variable store?

If it's a "store" with many strings, could be you could use an associative array.
declare -A mapvar
mapvar["abc"]=$(< file1.json)
mapvar["def"]=$(< file2.json)
declare -p mapvar > file_to_be_sourced.sh

A: I finally got to a solution.
Apparently if you echo "Something='$a'" it does't matter if you have single, double, triple, escaped or whatever quotes inside that variable: he just doesn't care and use the double ones.
For example in my case he just ignored the outermost ' and considered everything else as a command
My solution was very easily to:
echo "Something:\"$a\""

And now it's treated as an actual string.
I'm pretty confused about why, but that's probably caused by how bash works with quotes


text:
Q: EF Unique property in entity - one context, multiple databases code first I have a specific scenario:

*

*one DbContext MyContext

*twoDatabases Db1 and Db2

*Entity MyEntity with properties a, b, and c

Context:
public class MyContext : DbContext
{
    public MyContext(string connString) : base(connString)
    {

    }

    public virtual DbSet<MyEntity> MyDbSet { get; set; }

I apply migration in db1, it creates table MyEntity, with columns a,b,c.
Now with the same context i want to have MyEntity in db2 but only with columns a,b. What I do is:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    if(IsDb2)
    {
        modelBuilder.Entity<MyEntity>().Ignore(x => x.PropertyC);
    }
}

But it results in error when adding a migration: The property PropertyC is not a declared property on type MyEntity.
Is what I'm trying to achieve even possible with EF? I'm using EF 6.
Many thanks in advance for clarifying this!


text:
Q: Cambiarle el tamaño a un label html Tengo un label y quiero que no este tan junto con otras cosas.
El label lo tengo así:
Solicitudes Reasignadas
<progress id="file" max="100" value="70">70%</progress>

Dentro de un H3, que es Solicitud.
Adjunto foto.

A: Puedes modificar el tamaño de la barra y su distancia respecto a otros elementos usando las propiedades width y margin de css
progress{
   width: 100px; /*más ancho*/
   margin: 20px; /*separación de otros elementos*/
}

si lo prefieres, puedes usar margin-top/margin-left/margin-bottom/margin-right para establecer el margen en solo uno de los lados del elemento


text:
Q: Word2Vec on sets of integers The purpose (and power) of Word2Vec is the context of the language (i.e., given a sentence like "I ate blankword for breakfast" we can assume that only a small fraction of our corpus, like eggs, salad etc.. might fit there).
I wonder if this idiom still works when we remove the context of the language and consider Word2Vec on sets. For example, consider the case where each person has some vector of integers associated to it, like [301, 285, 417,..], where this vector describes properties of that person. Clearly, the order of the properties does not matter.
We can assume that each person has at most 70 such properties. And that the entire corpus has about 500 properties. The goal is given some person, detect the list of k most similar persons, where k is some integer parameter.
Can we use Word2Vec for this task? On one hand, given a vector of properties, it seems that we can use Word2Vec with pretty large window size. On the other hand, this kind of contradicts the assumption that only a small fraction of our corpus fits for any given word.

A: Your assumption "only a small fraction of our corpus fits for any given word" is not an inherent precondition for applying these kinds of algorithms. It might be true in the common case – natural language, given usual word co-occurrence patterns – but word2vec & similar algorithms are often applied to other kinds of data that are only vaguely natural-language-like.
So the answer to "can we use word2vec for this?" is: yes, of course you can try. But only trying (perhaps with other tuning) and evaluating the results will tell you if the approach is beneficial for your specific data & goals.
Related thoughts:

*

*As a baseline which already aligns with much of your thinking, you could set word2vec & related "dense embedding" approaches aside for a moment, and just model your datapoints as sparse 500-dimension one-hot vectors of your (~about) 500 properties. You can then calculate things like cosine-similarity between these vectors as a simple, fast way to get a quantitative similarity between any pair, or find the top-k most-similar items. Finding the most common extra "on" properties in neighbors then becomes a very-simple recommender/basket-predictor.

*You can further refine that approach with direct dimensionality-reduction. Note that word-vector algorithms (like GLoVe or word2vec) are essentially methods for lossy-compression, that start with the giant set of all very-wide co-occurrence-within-a-context-window sparse vectors, and turn that into a set of per-word much-narrowed lower-dimensional dense embeddings. But you can do similar dimensionality-reductions on your 500d feature vectors, without necessarily bringing in all the other window/language/etc assumptions inherent to word-vector models. (And more generally, you may want to think of your task as recommendation/prediction rather than some adaptation of word2vec.)

*To the extent you do try word2vec-like algorithms, note that they most shine with large training sets & large vocabularies – typically tens of thousands to millions of modeled tokens. Your mere 500 unique tokens is quite a bit smaller, so you may need to try a wider-range of non-default settings to get the best results. One very vague & rough rule-of-thumb I use to: the model's dimensions (vector_size) should be no more than the square-root of the number of unique tokens. That suggests vector_size=22 or less for your data, rather than the usual 100-400 values common with plentiful training data & large vocabularies. Similarly, other more-obscure parameters may also help when your co-occurrences or goals are different from usual natural-language applications. For example, in the Python Gensim Word2Vec implementation, a parameter called ns_exponent (fixed at 0.75 in many implementations) may vary; there's at least one paper suggesting applications like recommendation systems may benefit from a very-different value here.

*The idea of boiling a text of order-irrelevant tokens into a summary vector bares some resemblance to the word2vec-inspired "Paragraph Vectors" algorithm, specifically in its "DBOW" mode. (This is available in Python Gensim as the Doc2Vec model, with mode dm=0.) In this mode, context-windows & order is irrelevant, as the document-vector is trained to predict each word individually. Alternatively, as you've alluded-to, in usual word2vec implementations you can approximate a "full-document window" with a very-large window value. (In recent Gensim versions, there's also a non-default shrink_windows=False option that prevents internal optimizations that have the effect of overweighting closer words during training.)


text:
Q: datalink error: DataResultSetOpen in rave report Am using xe2 rad studio with rave report 10.
I use Databaseconnection to Sql database
 use driver data view which i drag and drop three tables on it.
But when i press ok it shows below error:
datalink error: DataResultSetOpen: List index out of bounds (-1) in rave report

A: The solution is: There was an error of sql statement on driver data view's query.

A: There was an error of data structure is not correct, or the table does not exist.


text:
Q: Swift video trimming extension error - AVFoundationErrorDomain Code=-11822 I have this code (it's a react native module)
import Foundation
import AVFoundation
import CoreMedia

extension FileManager {
  func removeFileIfNecessary(at url: URL) throws {
    guard fileExists(atPath: url.path) else {
      return
    }

    do {
      try removeItem(at: url)
    }
    catch let error {
      throw TrimError("Couldn't remove existing destination file: \(error)")
    }
  }
}

struct TrimError: Error {
  let description: String
  let underlyingError: Error?

  init(_ description: String, underlyingError: Error? = nil) {
    self.description = "TrimVideo: " + description
    self.underlyingError = underlyingError
  }
}

extension AVMutableComposition {
  convenience init(asset: AVAsset) {
    self.init()

    for track in asset.tracks {
      addMutableTrack(withMediaType: track.mediaType, preferredTrackID: track.trackID)
    }
  }

  func trim(timeOffStart: Double) {
    let duration = CMTime(seconds: timeOffStart, preferredTimescale: 1)
    let timeRange = CMTimeRange(start: kCMTimeZero, duration: duration)

    for track in tracks {
      track.removeTimeRange(timeRange)
    }

    removeTimeRange(timeRange)
  }
}

extension AVAsset {
  func assetByTrimming(trimStartTime: CMTime,
                       assetDuration: CMTime) throws -> AVAsset {

    let timeRange = CMTimeRange(start: trimStartTime, end: assetDuration)

    let composition = AVMutableComposition()

    do {
      for track in tracks {
        let compositionTrack = composition.addMutableTrack(withMediaType: track.mediaType, preferredTrackID: track.trackID)
        compositionTrack?.preferredTransform = track.preferredTransform
        try compositionTrack?.insertTimeRange(timeRange, of: track, at: kCMTimeZero)
      }
    } catch let error {
      throw TrimError("error during composition", underlyingError: error)
    }

    return composition
  }

  func export(to destination: URL) throws {
    guard let exportSession = AVAssetExportSession(asset: self, presetName: AVAssetExportPresetPassthrough) else {
      throw TrimError("Could not create an export session")
    }

    exportSession.outputURL = destination
    exportSession.outputFileType = AVFileType.mov
    exportSession.shouldOptimizeForNetworkUse = true

    let group = DispatchGroup()

    group.enter()

    //        try FileManager.default.removeFileIfNecessary(at: destination)

    exportSession.exportAsynchronously {
      group.leave()
    }

    group.wait()

    if let error = exportSession.error {
      throw TrimError("error during export", underlyingError: error)
    }
  }
}

@objc(VideoTrimmer)
class VideoTrimmer : NSObject {

  func time(_ operation: () throws -> ()) rethrows {
    let start = Date()

    try operation()

    let end = Date().timeIntervalSince(start)
    print(end)
  }

  @objc func trimVideo(_ sourceURL: NSURL,
                       destinationURL: NSURL,
                       duration: Int,
                       preClipDuration: Int,
                       resolver resolve: @escaping RCTPromiseResolveBlock,
                       rejecter reject: RCTPromiseRejectBlock) -> Void {

    do {
      try time {
        let asset = AVURLAsset(url: sourceURL as URL)
        let assetDuration : CMTime = asset.duration
        let convertedDuration : CMTime = CMTime(seconds: Double(duration), preferredTimescale: 1)
        let preClipConvertedDuration : CMTime = CMTime(seconds: Double(preClipDuration), preferredTimescale: 1)
        var trimStartTime : CMTime
        trimStartTime = CMTimeSubtract(assetDuration, convertedDuration)
        let comparison : Int32 = CMTimeCompare(trimStartTime, preClipConvertedDuration)

        if comparison == 1 {
          trimStartTime = CMTimeSubtract(trimStartTime, preClipConvertedDuration)
        } else {
          trimStartTime = kCMTimeZero
        }
        let trimmedAsset = try asset.assetByTrimming(trimStartTime: trimStartTime, assetDuration: assetDuration)
        try trimmedAsset.export(to: destinationURL as URL)
        resolve("Video trimmed successfully")
      }
    } catch let error {
      reject(" \(error)", nil, error)
    }
  }
}

which fails with the following error:
 TrimError(description: "TrimVideo: error during export", underlyingError: Optional(Error Domain=AVFoundationErrorDomain Code=-11822 "Cannot Open" UserInfo={NSLocalizedFailureReason=This media format is not supported., NSLocalizedDescription=Cannot Open, NSUnderlyingError=0x1c4250b00 {Error Domain=NSOSStatusErrorDomain Code=-16976 "(null)"}}))

I'm passing the following path:
assets-library://asset/asset.mov?id=E7A2D28D-0FBA-4B40-80CE-B05013D74F28&ext=mov
also tried without the query assets-library://asset/asset.mov but no success.
The file exists because I have it in the camera roll.
Unfortunately I don't know swift well enough to investigate.
Any ideas how to make it read the source without complaining about the format?


text:
Q: Re-using JTextField in Java pop-ups I'm building a large Java application that uses multiple pop-up windows. Some of these windows must be able to be displayed at the same time (for instance, separate pop-ups for Google Earth and a webcam feed), but some of them can only be displayed one at a time (for instance, error messages). The first kind of pop-ups, the webcam kind, are working fine. But the error message pop-ups act like the webcam type of pop-ups (that is, they create new .class files and there can be multiple error pop-ups). How do I fix this? Should I create a new error class?
Also, in one of the webcam-type pop-ups, I have JTextFields which read a username and password. This log-in popup works fine, but if I use it once, close it, and use it again, doing a getText() on the JTextFields returns an empty string. I think this problem might be related to the one above, but I am not sure.
passwordAction.addActionListener(new ActionListener() {
            JFrame pwPop=new JFrame("Log in");
            JTextField unameField;
            JTextField pwField;
            public void actionPerformed(ActionEvent arg0) {
                pwPop.setBounds(250,200,300,150);
                JPanel pwPopPanel=new JPanel(new FlowLayout(FlowLayout.LEFT,10,10));
                pwPop.add(pwPopPanel);
                unameField=new JTextField();
                pwField=new JTextField();
                JButton logInButton=new JButton("Log in");
                JButton cancelButton=new JButton("Cancel");
                JLabel logInText=new JLabel("Username:");
                JLabel passwordText=new JLabel("Password:");
                JPanel buttonPanel=new JPanel(new FlowLayout(FlowLayout.CENTER,5,0));
                pwPopPanel.add(logInText);
                pwPopPanel.add(unameField);
                pwPopPanel.add(passwordText);
                pwPopPanel.add(pwField);
                buttonPanel.add(logInButton);
                buttonPanel.add(cancelButton);
                pwPopPanel.add(buttonPanel);
                logInButton.addActionListener(new ActionListener() {
                    JFrame logErrorFrame;
                    public void actionPerformed(ActionEvent arg0) {
                        if (doLogIn(unameField.getText(), pwField.getText(), "")) {
                            unameField.setText(null);
                            pwField.setText(null);
                            pwPop.setVisible(false);
                        }
                    }
                });
                pwPop.setVisible(true);
            }
        });

A: As Andrew Thompson showed me, JOptionPane is the solution I was looking for. It is capable of creating almost any type of popup you may need.
JOptionPane Javadoc
Simple Dialog with JOptionPane


text:
Q: Django redirect non www to www is redirecting to mysite/mysite/wsgi I'm redirecting non www to www in my django project. So far its in fact working by setting the PREPEND_WWW = True in my settings.py
But somehow when I enter mysite.com it will redirect me to www.mysite.com/mysite/mysite/wsgi.py
Is it possible just to redirect it to www.mysite.com?

A: I deleted all .pyc files from my project and ran the server with the python manage.py runserver --noreload command + reloaded my apache service.
Somehow this fixed my problem. Django was acting weird!


text:
Q: Bootstrap scrollspy active selector not working I have a simple bootstrap 3 scrollspy problem where the 'active' li tag is not getting activated when I scroll up/down the page. Everything else about the scrollspy works as expected.
I have seen all other stack overflow question regarding this and experimented in jsfiddle for about two hours with no progress.
Using dev tools and setting and li to :active manually shows the desired effect.
HTML

 ONE

 TWO

 THREE

 FOUR

one

two

three

four

CSS
li > a:hover,
li:active {
  border-bottom: 2px solid #2d9fff;
}

My jsfiddle link is located here:
https://jsfiddle.net/hswg5j3q/
Can anyone check out my jsfiddle and see what I am missing? Many thanks in advance.

A: It's because your fiddle doesn't include bootstrap.js. The JS is needed for the ScrollSpy component.
Working on Bootply:
http://bootply.com/wJHL1Vqpdi


text:
Q: extracting double quotes from html tags with a regex I'm extracting some content from a website with this pattern:
 ([^+]+)

and it outputs
< img src=""http://www."" border=""0""/>

with double quotes. What is wrong with my query?

A: your problem only makes sense if you modify your regexp.
but first of all, beware:

in general, what you try to achieve is not feasible using regexes. they are the inappropriate tool to do it. you will not come up with a solution 100% correct using regexes.

having said this, try to replace ([^+]+) with (([^<!--]+([^<]|<[^!]|<![^-]|<!-[^-]))+). note that this regex assumes the following:

*

*there are no html comments inside the message portion

*there are no strings containing html comment openings inside the message portion

*the message portion is a valid html fragment
(otherwise it would match eg. <!-<!-- / message -->)

you have been warned.
btw, the dquote doubling must be a standard escape mechanism of the imacro environment.


text:
Q: Error trying to create an image classifier for the RSNA Screening Mammography competition on Kaggle I would appreciate any help anybody can offer with the issue descibed here
Error creating image classifier
Many thanks in advance
Julian