text:
Q: How to implement aws subscriptions with mui-datatable I have been trying to use the mui-datatable alongside aws for some time now which has worked fine for things like queries and mutations. I recently tried to implement subscriptions but have faced a lot of issues with it and hope someone here will be able to help me. The problem is basically when I perform a mutation the table doesn't change but if I type another value into the field where i perform my mutations the table then updates. Here is the class which performs the mutation
AddRecord.js
addRecord = async () => { /*handles the mutations and sets it ro a state Record*/
    const result = await this.props.client.mutate(buildMutation(this.props.client,
      gql(createRecords),{
        inputType: gql(CreateRecordsInput),
        variables: {
          input: {
            record: this.state.Record,
          }
        }
        },
        _variables => [ gql(listRecordss) ],
        'Records'));
      console.log( "success", result )
 }
   render() {
       const { classes } = this.props;
       const { Record } = this.state;

   return (

<ListEintraege client={this.props.client} />

           <TextField
         id="outlined-eintreag-input"
         variant="outlined"
         onChange={this.handleChange('Record')}
         value={Record}
         multiline
         className={classes.textField}
         style={{ margin: 8, marginTop: 30 }}
         InputLabelProps={{
           shrink: true,
         }}
         fullWidth
       />
       <Button
       variant="contained"
       color="primary"
       className={classes.button}
       onClick={this.addRecord}
       >
       Eintrag <SendIcon color="secondary" style={{ margin: 8 }}/>
      </Button>
...

and the class which list the data
ListRecords.js
//subscrip() is just to show I tried that too
/* subscrip = async () => {
    let subscription;
        subscription = await this.props.client.subscribe({ query: gql(onCreateRecords) }).subscribe({
        next: data => {
          console.log(data.data.onCreateRecords);
         const k = data.data.onCreateRecords;
         console.log("I am:", k);
         this.state.Records2 = k;
         console.log("I be:", this.state.Records2);
        },
        error: error => {
          console.warn(error);
        }
      });
 }
*/

 render() {
    const { Records, Records3 } = this.state;

    const columns = [
        {
         name: "Datum & Uhrzeit",
         label: "Datum & Uhrzeit"
        },
        {
         name: "Eintrag",
         label: "Eintrag"
        },
        {
         name: "Arzt",
         label: "Arzt"
        },
        {
            name: "Patient",
            label: "Patient"
           },
       ];

    const data = [ // results of query
     ... Records3.map((rest, i) => (
      [rest.createdAt, rest.record, rest.arzt, rest.patient]
   )),

    ];

    const options = {
        ...
  };

  const onNewRecord = (prevQuery, newData) => {

    let updatedQuery = {...prevQuery};

    const updatedRecordsList = [
      newData.onCreateRecords,

      ...prevQuery.listRecordss.items
    ]

    updatedQuery.listRecordss.items =  updatedRecordsList;

    return updatedQuery;

    }

    return (

<MUIDataTable
            title={"Leistungen"}
            data={data}
            columns={columns}
            options={options}
            />

<Connect
        query={graphqlOperation(listRecordss)}
        subscription={graphqlOperation(onCreateRecords)}
        onSubscriptionMsg={onNewRecord}
    >

        {({data, loading, error}) => {
            if (loading) return "Loading"
            if (error) return "Error"
            this.state.Records3 = data.listRecordss.items
            console.log('markets', Records3)

            return

        }}
    </Connect>

Thanks for any help.

A: stupid mistake one just needs to pass the Mui table within the connect component and instead of using a state use a constant. Atleast that solved it for me in case someone comes across this.
<Connect
        query={graphqlOperation(listRecordss)}
        subscription={graphqlOperation(onCreateRecords)}
        onSubscriptionMsg={onNewRecord}
    >

        {({data, loading, error}) => {
            if (loading) return "Loading"
            if (error) return "Error"
            const bil = data.listRecordss.items
            console.log('bil', bil)

            return <MUIDataTable
            title={"Leistungen"}
            data={ bil.map((rest, i) => (
              [rest.createdAt, rest.record, rest.arzt, rest.patient]
           ))}
            columns={columns}
            options={options}
            />

        }}
    </Connect>


text:
Q: Applying radius corners to the end of the menu not every item This is my menu -

Dashboard

<a href="<?php echo bp_loggedin_user_domain() ?>">Profile

<a href="<?php echo bp_loggedin_user_domain() ?>messages">Messages

<a href="<?php echo bp_loggedin_user_domain() ?>friends">Friends

<?php bp_adminbar_notifications_menu() ?>

This is the CSS -
ul#menu li {
    list-style: none;
    float: left;
    margin: 0 0px 0 0;
    background-color: #F8FCFE;
    position: relative;
    z-index: 1;
    border-top-left-radius: 10px 10px;
    border-bottom-left-radius: 10px 10px;

}

ul#menu li a:link, ul#menu li a:visited {
    display: block;
    text-align: center;
    width: 88px;
    height: 53px;
    line-height: 53px;
    font-family: 'Montserrat', sans-serif;
    text-decoration: none;
    font-size: 13px;
    color: black;
    letter-spacing: 1px;
    outline: none;
    float: left;
    background: #F8FCFE;
    border-top-left-radius: 10px 10px;
    border-bottom-left-radius: 10px 10px;
}

What I would like is the left item to have top left, bottom left radius and the last item to have top right and bottom right to have radius. So it looks like vertical rectangle with radius corners.

A: have the first li and last one have a different class such as first and last, first with left top and bottom last with right top and bottom
li.first {
border-top-left-radius: 10px;
border-bottom-left-radius: 10px; }

li.last {
border-top-right-radius: 10px;
border-bottom-right-radius: 10px; }

the menu

Dashboard

<a href="<?php echo bp_loggedin_user_domain() ?>">Profile

<a href="<?php echo bp_loggedin_user_domain() ?>messages">Messages

<a href="<?php echo bp_loggedin_user_domain() ?>friends">Friends

<?php bp_adminbar_notifications_menu() ?>

A: html:

Dashboard

<a href="<?php echo bp_loggedin_user_domain() ?>">Profile

<a href="<?php echo bp_loggedin_user_domain() ?>messages">Messages

<a href="<?php echo bp_loggedin_user_domain() ?>friends">Friends

<?php bp_adminbar_notifications_menu() ?>

css:
ul#menu li {
list-style: none;
float: left;
margin: 0 0px 0 0;
background-color: #F8FCFE;
position: relative;
z-index: 1;
border-top-left-radius: 10px 10px;
border-bottom-left-radius: 10px 10px;
overflow:hidden;}

ul#menu li.one {border-radius: 10px 0px 0px 10px;}

ul#menu li.five {border-radius: 0px 10px 10px 0px;}

you can specify the corners per item clockwise like this : top left, top right, bottom right, bottom left.
rectified for copy and paste directly to css.

A: How about something like this jsFiddle example?
I left your HTML unchanged but updated the CSS to:
ul#menu li {
    list-style: none;
    float: left;
    margin: 0 0px 0 0;
}

li.one a{
    border:2px solid #999;
    border-top-left-radius: 10px 10px;
    border-bottom-left-radius: 10px 10px;
    border-right:none;
}
li.two a, li.three a {
    border-top:2px solid #999;
    border-bottom:2px solid #999;
}
li.four a{
    border:2px solid #999;
    border-top-right-radius: 10px 10px;
    border-bottom-right-radius: 10px 10px;
    border-left:none;
}

ul#menu li a:link, ul#menu li a:visited {
    display: block;
    text-align: center;
    width: 88px;
    height: 53px;
    line-height: 53px;
    font-family: 'Montserrat', sans-serif;
    text-decoration: none;
    font-size: 13px;
    color: black;
    letter-spacing: 1px;
    outline: none;
    float: left;
    background: #ccc;

}

A: CSS3 lets you define style for specific children. eg:
#menu li:last-child {
 // some def
}

#menu li:first-child {
 // some other definition
}

hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get binary data with XMLHttpRequest in a Firefox extension I'm trying to download some binary data from my Firefox extension. When I try to set a created XMLHttpRequest to arraybuffer mode:
oHTTP = new XMLHttpRequest();
oHTTP.responseType = "arraybuffer";

The error
InvalidStateErr
An attempt was made to use an object that is not, or is no longer, usable

is thrown.
Is there another way to download binary data in a Firefox extension?

A: You must call the open method first.


text:
Q: A proper integral which can't be evaluated if improper If you would like to find the electric potential of a conducting disc in space you would have several approaches.

*

*Laplace Equation.(not so great approach though!)

*Finding the charge on a conducting ellipsoid(this problem itself has many appraoches,so diverse!)then you take the limit when the ellipsoid becomes a disk.so you have the charge density and must integrate to get potential.

*Use a conducting rod as image charge and again taking a limit.
Its so fascinating that doing 1 leads to an infinite series (infinite series), 2 leads to a though integral and the (calculus), and 3 leads to finding the Real part of a very big Ln (arithmetic). And all these will give the same answer as they should. Three things so diffrent in "shape" but they turn out to be the same!
My situation is: I want to evaluate the integral which I got while doing $2$. Also I'd like to evaluate $3$ and know the real part and imaginary part of that gigantic Ln. (it would be an $X+iY$ representation.)!

A: $\displaystyle{\large%
?
\equiv
\int_{0}^{a}
{{\rm d}x \over \sqrt{x^{2} + c^{2}\,}\ \sqrt{a^{2} - x^{2}\,}}\,,
\quad a > 0}$.
With the change $x \equiv a\,\sin\left(\theta\right)$, we
get
$\displaystyle{%
? = \int_{0}^{\pi/2}
{{\rm d}\theta \over \sqrt{a^{2}\sin^{2}\left(\theta\right) + c^{2}}}
}$.
Now, we use la identity
$\displaystyle{%
\sin^{2}\left(\theta\right) = {1 - \cos\left(2\theta\right) \over 2}
.\quad}$ $?$ becomes:
\begin{align}
?
&=
\int_{0}^{\pi/2}
{{\rm d}\theta
 \over
 \sqrt{a^{2}\left\lbrack 1 - \cos\left(2\theta\right)\right\rbrack/2 + c^{2}}}
=
\sqrt{\vphantom{\large A}2\,}\int_{0}^{\pi/2}
{{\rm d}\theta
 \over
 \sqrt{a^{2} + 2c^{2} - a^{2}\cos\left(2\theta\right)}}
\\[3mm]&=
{\sqrt{\vphantom{\large A}2\,} \over 2}\int_{0}^{\pi}
{{\rm d}\theta
 \over
 \sqrt{a^{2} + 2c^{2} - a^{2}\cos\left(\theta\right)}}
=
{\sqrt{\vphantom{\large A}2\,} \over 2}\,
{2 \over \sqrt{\left(a^{2} + 2c^{2}\right) + a^{2}\,}}\,
{\bf E}\,\left(%
\sqrt{2c^{2} \over \left(a^{2} + 2c^{2}\right) + a^{2}}
\right)
\end{align}
where ${\bf E}\left(k\right) \equiv {\rm E}\left(\pi/2,k\right)$ is the Complete Elliptic Integral of the Second Kind.
$\displaystyle{{\rm E}\left(\varphi,k\right)
\equiv
\int_{0}^{\varphi}
 \sqrt{1 - k^{2}\sin^{2}\left(\alpha\right)\,}\ {\rm d}\alpha}$ is the Elliptic Integral of the Second Kind. In the derivation we used the identity:
$$
\int_{0}^{\pi}{{\rm d}x \over \sqrt{\alpha \pm \beta\cos\left(x\right)\,}}
=
{2 \over \alpha + \beta}\,
{\bf E}\,\left(\sqrt{2\beta \over \alpha + \beta\,}\,\right)\,,
\qquad
\alpha > \beta > 0
$$
$$
\begin{array}{|c|}\hline\\
\color{#ff0000}{\large\quad\int_{0}^{a}
{{\rm d}x \over \sqrt{x^{2} + c^{2}\,}\ \sqrt{a^{2} - x^{2}\,}}
=
{1 \over \sqrt{a^{2} + c^{2}\,}}\,
{\bf \color{#000000}{E}}\,\left(\left\vert c\right\vert \over \sqrt{a^{2} + c^{2}\,}\right)\,,\quad a > 0,\ c\not= 0\quad}
\\ \\ \hline
\end{array}
$$


text:
Q: Leer un archivo PHP de otro dominio Tengo un archivo .php al cual le paso un parámetro con una orden en SQL y me da el resultado en texto por la página.
Ejemplo:  domain.com/sql_bridge.php?order=SELECT%20*%20FROM%20settings
Entonces esto me retorna la sentencia, incluso soy capaz de recogerla con js desde el mismo dominio.
function ask(order="",callback){
  $("

").load("http://domine/sql_bridge.php?order="+encodeURI(order), function(responseTxt, statusTxt, xhr){
    callback(responseTxt,statusTxt,xhr)
  });
}

Lo que me gustaría es poder recoger el resultado del SQL desde otro dominio.


text:
Q: Call SpriteKit function through SwiftUI Button I wrote a function that should make a SKLabel appear when I hit the SwiftUI Button.
The function is called (console message prints), but the label itself is never added to the scene. Very confused.
HELP!
Here is my code.
import SwiftUI
import SpriteKit

class GameScene: SKScene {
    public func startGame() {
        let startGame = SKLabelNode()
        startGame.text = "Game Started"
        startGame.position = CGPoint(x: self.frame.midX, y: self.frame.midY)

        self.addChild(startGame)

        print("Function is called")
    }
}

struct ContentView: View {
    var gameScene: GameScene {
        let scene = GameScene()
        scene.size = CGSize(width: 400, height: 400)
        scene.scaleMode = .fill
        return scene
    }

    var body: some View {
        VStack{
            SpriteView(scene: gameScene)
                .padding()
                .frame(width: 400, height: 400)

            Button("Button") {
                gameScene.startGame()
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


text:
Q: java.lang.RuntimeException: Failed to invoke public android.arch.lifecycle.LiveData() with no args I'm trying to call API using Retrofit and Android architecture components but I'm getting this error

java.lang.RuntimeException: Failed to invoke public android.arch.lifecycle.LiveData() with no args

this is the data class for the response
data class ForecastResult(val city: City, val list: List<Forecast>)

Services Interface
interface ServicesApis { // using dummy data
@GET("data/2.5/forecast/")
fun getForecast(@Query("APPID") APPID: String = "xxxxxxxx"
                , @Query("q") q: String = "94043", @Query("mode") mode: String = "json", @Query("units") units: String = "metric"
                , @Query("cnt") cnt: String = "7"): Call<LiveData<ForecastResult>>
}

and the api implementation
class WeatherRepoImpl : WeatherRepo {
override fun getDailyForecast(): LiveData<Resource<ForecastResult>> {
    val forecast: MutableLiveData<Resource<ForecastResult>> = MutableLiveData()
    RestAPI.getAPIsrevice().getForecast().enqueue(object : Callback<LiveData<ForecastResult>> {
        override fun onResponse(call: Call<LiveData<ForecastResult>>?, response: Response<LiveData<ForecastResult>>?) {
            when {
                response!!.isSuccessful -> {
                    forecast.postValue(Resource.success(response.body()?.value))
                }
                else -> {
                    val exception = AppException(responseBody = response.errorBody())
                    forecast.postValue(Resource.error(exception))
                }
            }
        }

        override fun onFailure(call: Call<LiveData<ForecastResult>>?, t: Throwable?) {
            val exception = AppException(t)
            forecast.postValue(Resource.error(exception))
        }

    })
    return forecast
}

  }

appreciate your help!

A: Remove LiveData from API call and create ViewModel class have contained in MutableLiveData Object.
For Example:
API Call Definition something like this: (Remove LiveData)
   @GET("data/2.5/forecast/")
fun getForecast(@Query("APPID") APPID: String = "xxxxxxxx"
                , @Query("q") q: String = "94043", @Query("mode") mode: String = "json", @Query("units") units: String = "metric"
                , @Query("cnt") cnt: String = "7"): Call<ForecastResult>

Create One ViewModel Class:
class YourViewModel: ViewModel() {

    var allObjLiveData = MutableLiveData<YOUROBJECT>()

    fun methodForAPICall(){

        mApiService?.getForecast(.....)?.enqueue(object : Callback<YOUROBJECT>
        {
            override fun onFailure(call: Call<YOUROBJECT>, t: Throwable) {
                allObjLiveData.value = null
            }

            override fun onResponse(call: Call<YOUROBJECT>, response: Response<YOUROBJECT>) {
                allObjLiveData.value=response.body() //Set your Object to live Data
            }

        })
    }
}

Now in your activity or fragment initialization ViewModel class.
And observe to live data.
    yourViewModelClassObj?.allObjLiveData?.observe(this, Observer {
       //whenever object change this method call every time.
      }
    })

So You can use livedata in ViewModel class.

A: Yes so probably your API's response is not being correctly serialized.
Anyway, it doesn't make sense to wrap your LiveData to an API response. Just have your exposed object like so:
someLivedataObject: LiveData<YourApiResponseModel>

// So whenever the APIs response comes in:
someLivedataObject.postValue(YourApiResponseModel)

If for some reason doesn't work use
someLivedataObject.setValue(YourApiResponseModel)

You can read more about the difference between these on the documentation, notice that I'm calling the LiveData#setValue() method, do not use Kotlin's deference setter method.
And since your view is observing changes to your exposed someLivedataObject the UI is updated.

This is similar to the RxJava counterpart where API responses with Observable wrapper don't really make sense, it's not a continuous stream of data, hence makes more sense to use Single.

Take these suggestions with a grain of salt, I'm not fully aware of your application's use cases and there are exceptions to these rules.

A: I use LiveDataAdapter to convert Call to LiveData, that way you don't need wrap your Retrofit response as Call<LiveData<T>>.
This adapter is similar to Rx adapter by Jake.
Get the LiveDataAdapterFactory and LiveDataAdapter from here.
After adding the Adapter, you'll need to set it:
Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create(gson))
        .addCallAdapterFactory(LiveDataCallAdapterFactory())
        .baseUrl(BASE_URL)
        .client(httpClient)
        .build()

Self Promotion: I have made a video on the same over at: https://caster.io/lessons/android-architecture-components-livedata-with-retrofit


text:
Q: Loading a Custom Server Control on the fly System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(@"CustomControls.Nav.dll");
 //Namespace and assembly name are CustomControls.Nav , the class name for the control is WebBar
Type type = assembly.GetType("CustomControls.Nav.WebBar");

I am getting type as null.What am I doing wrong here?

A: What does Object Browser display when you look at this Assembly?  Is it showing CustomControls.Nav.WebBar?


text:
Q: Why doesn't FillPolygon draw after FillRectangle? I'm drawing directly onto a form with two FillPolygon statements to create two arrows - one black, one white. (The white arrow is slightly smaller and drawn over the black arrow.)
Here's the code in the form's OnPaint.
protected override void OnPaint(PaintEventArgs e)
{
    Graphics g = e.Graphics;

    g.FillPolygon(brushBlack, travelArrow);
    g.FillPolygon(brushWhite, featureArrow);
}

Works great. Now since the white arrow is going to be drawn several times in different rotations, I decided to use double-buffering to avoid as much flicker as possible.
I first created a DrawFeatureArrow method that I call in OnPaint.
protected override void OnPaint(PaintEventArgs e)
{
    Graphics g = e.Graphics;

    g.FillPolygon(brushBlack, travelArrow);
    DrawFeatureArrow(this, e);
}

Note: There's no rotation of the white arrow coded yet, I'm just trying to get the double-buffering set up.
DrawFeatureArrow looks like this.
private void DrawFeatureArrow(object sender, PaintEventArgs e)
{
    Bitmap buffer = new Bitmap(60, 159);
    Graphics gOff = Graphics.FromImage(buffer);

    gOff.FillRectangle(brushGreen, 0, 0, buffer.Width, buffer.Height);
    gOff.FillPolygon(brushWhite, featureArrow);

    ImageAttributes attr = new ImageAttributes();
    attr.SetColorKey(Color.Green, Color.Green);

    Rectangle srcRect = new Rectangle(0, 0, bugger.Width, buffer.Height);
    Rectangle destRect = new Rectangle(90, 66, 60, 159);

    Graphics f = e.Graphics;

    // Should draw green rectangle and white arrow
    f.DrawImage(buffer, 90, 66);  // Draws just a green rectangle

    // If uncommented, should draw just white arrow (green rectangle hidden by SetColorKey)
    // f.DrawImage(buffer, destRect, 0, 0, buffer.Width, buffer.Height, GraphicsUnit.Pixel, attr);

    f.Dispose();
    gOff.Dispose();
    buffer.Dispose();
}

When run, the green rectangle is drawn but not the white arrow.
Strangely enough, in DrawFeatureArrow, if you replace this
gOff.FillPolygon(brushWhite, featureArrow);

With this
gOff.FillRectangle(brushWhite, 10, 10, 20, 20);

You get a tiny white rectangle in the upper left of the green rectangle.
Very strange behavior. Hope someone can point out what I'm doing incorrectly.
Thanks in advance for the help.

A: You're drawing your feature arrow over buffer that has dimensions of 60, 159. Maybe the location of the feature arrow is outside of those dimensions and therefore did not end in the bitmap.


text:
Q: Is there a command line tool in Golang to only check syntax of my source code? For example there is a -c option in Ruby that checks syntax before running a code:
C:\>ruby --help
Usage: ruby [switches] [--] [programfile] [arguments]
-c              check syntax only

C:\>ruby -c C:\foo\ruby\my_source_code.rb
Syntax OK

Is there a similar functionality in Go?
P.S. An example from Ruby is only because I know it in Ruby. Not because of trolling or something.

A: You can use gofmt to check for syntax errors without actually building the project.
gofmt -e my_file.go > /dev/null

You can later use $? bash variable, return code 0 implies success, 2 means syntax check. /dev/null will eat the code, but the errors go to stderr
The -e option is defined as:

report all errors (not just the first 10 on different lines)

gofmt --help

usage: gofmt [flags] [path ...]
  -comments=true: print comments
  -cpuprofile="": write cpu profile to this file
  -d=false: display diffs instead of rewriting files
  -e=false: report all errors (not just the first 10 on different lines)
  -l=false: list files whose formatting differs from gofmt's
  -r="": rewrite rule (e.g., 'a[b:len(a)] -> a[b:]')
  -s=false: simplify code
  -tabs=true: indent with tabs
  -tabwidth=8: tab width
  -w=false: write result to (source) file instead of stdout

A: Is there much point only checking the syntax? The Go compiler is so fast you might as well compile everything too.
In this sense, the underlying mental model is quite different from that of Ruby.
Just use go build or go install. http://golang.org/cmd/go/

A: Ruby is an interpreted language so a command that checks the syntax might make sense (since I assume you could potentially run the program even if there are syntax errors at some point).
Go on the other hand is a compiled language so it cannot be run at all if there are syntax errors. As such, the simplest way to know if there are errors is to build the program with go build.

A: In agreement with @Rick-777, I would strongly recommend using go build.  It performs additional checks that go fmt does not (ex: missing or unnecessary imports).
If you are worried about creating a binary in your source directory, you could always go build -o /dev/null to discard the output, which essentially reduces go build to a test that the code will build. That gets you syntax checking, among other things.
EDIT: note that go build doesn't generate a binary when building non-main packages, so you don't need the -o option.

A: Updated answer for those that don't want to settle for only checking with gofmt:
You can substitute gotype for go build to get just the front-end of the go compiler that validates both syntax and structure:
https://godoc.org/golang.org/x/tools/cmd/gotype
It's comparative in speed to gofmt, but returns all the errors you'd get from go build.
The one caveat is that it appears to require other packages to be go installed, otherwise it doesn't find them. Not sure why this is.

A: golang syntax checker
Place the below code in a file called gochk in a bin dir and chmod 0755.
Then run gochk -- help
#!/bin/bash
#
# gochk v1.0 2017-03-15 - golang syntax checker - ekerner@ekerner.com
# see --help

# usage and version
if \
    test "$1" = "-?" || \
    test "$1" = "-h" || \
    test "$1" = "--help" || \
    test "$1" = "-v" || \
    test "$1" = "--version"
then
    echo "gochk v1.0 2017-03-15 - golang syntax checker - ekerner@ekerner.com"; echo
    echo "Usage:"
    echo "  $0 -?|-h|--help|-v|--version # show this"
    echo "  $0 [ file1.go [ file2.go . . . ] ] # syntax check"
    echo "If no args passed then *.go will be checked"; echo
    echo "Examples:"
    echo "  $0 --help # show this"
    echo "  $0 # syntax check *.go"
    echo "  $0 cmd/my-app/main.go handlers/*.go # syntax check list"; echo
    echo "Authors:"
    echo "  http://stackoverflow.com/users/233060/ekerner"
    echo "  http://stackoverflow.com/users/2437417/crazy-train"
    exit
fi

# default to .go files in cwd
gos=$@
if test $# -eq 0; then
    gos=$(ls -1 *.go 2>/dev/null)
    if test ${#gos[@]} -eq 0; then
        exit
    fi
fi

# test each one using gofmt
# credit to Crazy Train at
# http://stackoverflow.com/questions/16863014/is-there-a-command-line-tool-in-golang-to-only-check-syntax-of-my-source-code
#
for go in $gos; do
    gofmt -e "$go" >/dev/null
done


text:
Q: looping html tag on the same line using razor i feel a bit ridiculous asking this, but i cannot figure out how to get this tag to loop without putting each tag on a new line using asp.net's razor syntax
@if (poolitem.SupplierStarRating > 0)
{
     @for (int i = 0; i < poolitem.SupplierStarRating; i++)
     {

     }
 }

what i'm trying to do is avoid that little space that occurs when inline tags are placed on separate lines

A: Put your code in one line with no spaces
@for (int i = 0; i < 3; i++){}

It will generate

A: or you can use @Html.Raw
@for (int i = 0; i < ViewBag.Counter; i++)
{
  @Html.Raw("");
}


text:
Q: Prove $ \frac{a^2}{b + c} + \frac{b^2}{c + a} + \frac{c^2}{a + b} + \frac{36}{a + b + c} \geq 20 $ Show that if $a,b,c > 0$, such that $ab + bc + ca = 1$, then the following inequality holds:
$$ \frac{a^2}{b + c} + \frac{b^2}{c + a} + \frac{c^2}{a + b} + \frac{36}{a + b + c} \geq 20 $$
What I have tried is firstly using the inequality:
$\frac{x^2}{a} + \frac{y^2}{b} \geq \frac{(x + y)^2}{a + b}$, for any $x, y$ and any $a,b > 0$.
Using this inequality we obtain $\frac{a^2}{b + c} + \frac{b^2}{c + a} + \frac{c^2}{a + b} \geq \frac{a + b + c}{2}$, and then we have:
$$ \frac{a^2}{b + c} + \frac{b^2}{c + a} + \frac{c^2}{a + b} + \frac{36}{a + b + c} \geq \frac{a + b + c}{2} + \frac{36}{a + b + c} = \frac{(a + b + c)^2 + 72)}{2(a + b + c)} $$.
Using $ab + bc + ca = 1$, we would then have to prove that:
$$a^2 + b^2 + c^2 + 74 - 40(a + b + c) \geq 0 $$ and then I tried replacing in this inequality $c = \frac{1 - ab}{a + b}$, but I didn't get anything nice.
I also tried rewriting the lhs:
$$\frac{a^2}{b + c} = \frac{a^2(ab + bc + ca)}{b + c} = a^3 + \frac{a^2bc}{b + c}$$
And this would result in: $a^3 + b^3 + c^3 + abc(\frac{a}{b + c} + \frac{b}{c + a} + \frac{c}{a + b}) + \frac{36}{a + b + c} \geq 20$, but I didn't know how to continue from here.
Do you have any suggestions for this inequality?

A: Your first step gives a wrong inequality. Try $c\rightarrow0+$ and $a=b=1$.
Let $a+b+c=3u$, $ab+ac+bc=3v^2$ and $abc=w^3$.
Thus, we need to prove that
$$\frac{\sum\limits_{cyc}a^2(a+b)(a+c)}{9uv^2-w^3}+\frac{12}{u}\geq20.$$
Now, we see that it's a linear inequality of $w^3$ because $\sum\limits_{cyc}a^2(a+b)(a+c)$ is fourth degree and the condition does not depend on $w^3$.
Indeed, $$\sum_{cyc}a^2(a+b)(a+c)=\sum_{cyc}a^2(a(a+b+c)+bc)=$$
$$=(a^3+b^3+c^3)(a+b+c)+(a+b+c)abc=(27u^3-27uv^2+3w^3)3u+3uw^3.$$
Hence, we need to prove that
$$\frac{(27u^3-27uv^2+3w^3)3u+3uw^3}{9uv^2-w^3}+\frac{12}{u}\geq20,$$ which is a linear inequality of $w^3$ after full expanding.
Thus, it's enough to prove our inequality for an extreme value of $w^3$, which happens in the following cases.

*

*$w^3\rightarrow0^+$.

Let $c\rightarrow0^+$.
Thus, we need to prove that
$$\frac{a^2}{\frac{1}{a}}+\frac{\frac{1}{a^2}}{a}+\frac{36}{a+\frac{1}{a}}\geq20$$ or
$$(a-1)^4(a^4+4a^3+11a^2+4a+1)\geq0;$$
2. Two variables are equal.
Let $b=a$ and $c=\frac{1-a^2}{2a},$ where $0<a<1$.
Thus, we need to prove that:
$$\frac{2a^2}{a+\frac{1-a^2}{2a}}+\frac{\left(\frac{1-a^2}{2a}\right)^2}{2a}+\frac{36}{2a+\frac{1-a^2}{2a}}\geq20$$ or
$$(1-a)(1+a+3a^2-157a^3+415a^4-225a^5+381a^6-99a^7)\geq0,$$
which is smooth.
We can use also the following way.
$$\sum_{cyc}\frac{a^2}{b+c}=\sum_{cyc}\frac{a^2(ab+ac+bc)}{b+c}=a^3+b^3+c^3+\sum_{cyc}\frac{a^2bc}{b+c}=$$
$$=(a+b+c)^3-3(a+b+c)(ab+ac+bc)+3abc+\sum_{cyc}\frac{a^2bc}{b+c}\geq$$
$$\geq(a+b+c)^3-3(a+b+c).$$
Id est, it's enough to prove that
$$(a+b+c)^3-3(a+b+c)+\frac{36}{a+b+c}\geq20.$$
Can you end it now?

A: I can easy get an SOS (Sum of Squares)!
We have: $$\text{LHS-RHS} =\frac{A}{(a+b)(b+c)(c+a)(a+b+c)}\geqq 0$$
Where: $$A=\Big[4\, \left( a+b+c+5+\sqrt {3} \right)  \left( a+b+c-\sqrt {3} \right)
+20\,\sqrt {3}-24\Big]abc$$
$$\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,+\left( a+b+c \right) \Big[ \left( a+b+c \right) ^{2
}+4\,a+4\,b+4\,c+9\Big] \left( a+b+c-2 \right) ^{2} \geqq 0$$
Equality holds when $a=b,\,c=0$ and its permutations.

A: Let $p=a+b+c,\,q=ab+bc+ca,$ we write your inequality as
$$ \sum \frac{a^2}{b+c} + \frac{36(ab+bc+ca)} {a+b+c}\geqslant 20\sqrt{ab+bc+ca},$$
or
$$(a+b+c) \sum \frac{a}{b+c} - (a+b+c) + \frac{36(ab+bc+ca)} {a+b+c}\geqslant 20\sqrt{ab+bc+ca}.$$
Use
$$ \sum \frac{a}{b+c} \ge \frac{a^2+b^2+c^2}{ab+bc+ca} = \frac{p^2}{q}-2.$$
We need to prove
$$p\left(\frac{p^2}{q}-2\right) - p + \frac{36q} {p}\geqslant 20\sqrt{q},$$
equivalent to
$$\frac{(p^4-3p^2q+36q^2)^2}{p^2q^2} \geqslant 400q,$$
or
$$\frac{(p^4+2p^2q+81q^2)(p^2-4q)^2}{p^2q^2} \geqslant 0.$$
Equality occur when $a=b=1,\,c=0.$ The proof is completed.


text:
Q: Marginal characteristic function from a multivariate charateristic function [I am posting this question here and not in Mathematics Stack Exchange because I will be using conventions as they are usually used in statistical physics (especially the notation is more involved in pure statistics).]
Given a multivariable characteristic function $G(k_1,k_2)$, what is the marginal characteristic function $G(k_1)$?
First some definitions. For continuous stochastic variables $x_1$ and $x_2$, the characteristic function is the Fourier transform of the probability distribution (I drop any pre-factors for simplicity).
$G(k) = \int_{-\infty}^{\infty} dx\ e^{ikx}\ p(x)$
$G(k_1,k_2) = \int_{-\infty}^{\infty} dx_1\ \int_{-\infty}^{\infty} dx_2\ e^{ik_1x_1}\  e^{ik_2x_2}\ p(x_1,x_2)$
The marginal probability for the variable $x_1$ is then
$p(x_1) = \int_{-\infty}^{\infty} dx_2\ p(x_1,x_2)$
Using the above three definitions, I want to show that (if true)
$$G(k_1) = \int_{-\infty}^{\infty} dk_2\ G(k_1,k_2)$$

My attempt at a proof:
I start by writing $G(k_1)$ as the inverse Fourier transform:
$$
G(k_1) = \int_{-\infty}^{\infty} dx_1\ e^{ik_1x_1}\ p(x_1)
$$
Now I write $p(x_1)$ as the marginal probability of the multivariate probability distribuion $p(x_1,x_2)$:
$$
G(k_1) = \int_{-\infty}^{\infty} dx_1\ e^{ik_1x_1}\ \int_{-\infty}^{\infty} dx_2\ p(x_1,x_2)
$$
Now I need to get a $G(k_1,k_2)$ in there somehow, so I multiply by $1=e^{-ik_2x_2}e^{ik_2x_2}$:
$$
\begin{align}
G(k_1) &= \int_{-\infty}^{\infty} dx_1\ e^{ik_1x_1}\ \int_{-\infty}^{\infty} dx_2\ e^{-ik_2x_2}e^{ik_2x_2}\ p(x_1,x_2)\\
&= \int_{-\infty}^{\infty} dx_2\ e^{-ik_2x_2}\ \int_{-\infty}^{\infty} dx_1\ e^{ik_1x_1}\ e^{ik_2x_2}\ p(x_1,x_2)
\end{align}
$$
which looks almost like what I need, except for the extra integrand $e^{-ik_2x_2}$, which makes it impossible to transform the integral into anything I know. Similar approaches (in which I substitute my known definitions largely end up with the same problem). How can I proceed? Which other approach can I use to show what I need?

A: I think I figured it out, although I am not 100% on the validity of the last step:

Begin with the definition of the marginal probability:
$$
p(x_1) = \int_{-\infty}^{\infty} dx_2\ p(x_1,x_2)
$$
which I now multiply by $e^{ik_1x_1}$ and integrate over $x_1$:
$$
\int_{-\infty}^{\infty} dx_1\ p(x_1)\ e^{ik_1x_1} = \int_{-\infty}^{\infty} dx_1\ \int_{-\infty}^{\infty} dx_2\ p(x_1,x_2)\ e^{ik_1x_1}
$$
The LHS is now the defintion of the characteristic function of $p(x_1)$, $G(k_1)$. The RHS is almost the definition of the characteristic function of $p(x_1,x_2)$, but it's missing a factor of $e^{ik_2x_2}$. This factor is identically $1$ if $k_2=0$. So I insert it under the condition that $k_2=0$ (Is this a valid step?):
$$
G(k_1) = \int_{-\infty}^{\infty} dx_1\ \int_{-\infty}^{\infty} dx_2\ p(x_1,x_2)\ e^{ik_1x_1}\ e^{ik_2x_2}
$$
Now the RHS is the definition of the characteristic function of $p(x_1,x_2)$ evaluated at $k_2=0$, $\left.G(k_1,k_2)\right|_{k_2=0}$. So finally:
$$
G(k_1) = \left.G(k_1,k_2)\right|_{k_2=0}
$$


text:
Q: How do I access an instance variable from a module that was included dynamically? I am dynamically including a module into the Baz class in the foobarbaz method.
However, when I execute this in ruby, I get a nil puts. Doesn't the module have access to Foo's instance variables?
class Foo
  attr_accessor :current_session

  def initialize(current_session)
    @current_session = current_session
  end

  def foobarbaz
    Baz.send(:include, Bar) # For Ruby < 2.1
    # Baz.include(Bar) # For Ruby > 2.1
  end
end

class Baz
end

module Bar
  def foobar
    @current_session
    # 'foobar'
  end
end

puts Foo.new('current_session').foobarbaz.new.foobar # nil

NOTE, for this, I was using Ruby 2.0.0. The following also does not puts desired result in Ruby 2.1.2.

A: Here is a meta programming for you :
#!/usr/bin/env ruby

class Foo
  attr_accessor :current_session

  def initialize(current_session)
    @current_session = current_session
  end

  def foobarbaz
    session = current_session
    Bar.module_eval { @current_session = session }
    Baz.send(:include, Bar)
  end
end

module_eval says

Evaluates the string or block in the context of mod, except that when a block is given, constant/class variable lookup is not affected....

Thus inside Bar.module_eval { @current_session = session }, @current_session is the instance variable of Bar only and I am setting the value of it to the instance variable value of the class Foo, which is @current_session.
Baz.send(:include, Bar) is helpfull, which returns class/module itself, which is including the other module. include(module, ...) → self.
class Baz
end

Read this post to understand the below stuff.
module Bar
  class << self
    attr_reader :current_session
  end

  def foobar
    Bar.current_session
  end
end

puts Foo.new('current_session').foobarbaz.new.foobar
# >> current_session

Update
As @Christian Fazzin gave a good suggestion :-
If you want Bar module to have write method also, then you have to do 2 changes -

*

*Bar should contain then attr_accesor :current_session, instead of what it has now.

*You don't need to use the power of module_eval there, rather use syntactic sugraness of write methods, like put Bar.current_session = current_session inside the method foobarbaz . Remove the lines session = current_session and Bar.module_eval { @current_session = session }.

A: After creating an instance of Foo (foo, say) and in doing so initializing foo's instance variable @current_session to 'current session', it appears to me that you want foo.foobarbaz to do the following:

*

*cause Baz to include the module Bar

*create an instance of Baz (baz, say)

*create an instance variable named @current_session for baz and assign it the value of foo's instance variable of the same name

*invoke baz.foobar to return the value of baz's instance variable @current_session.

If my understanding is correct, we can perform these four steps with four lines in Foo#foobarbaz:
class Baz
end

module Bar
  def foobar
    @current_session + ' in Baz'
  end
end

class Foo
  attr_accessor :current_session

  def initialize(current_session)
    @current_session = current_session
  end

  def foobarbaz
    Baz.include(Bar)
    baz = Baz.new
    baz.instance_variable_set(:@current_session, self.current_session)
    baz.foobar
  end
end

foo = Foo.new('current session')
foo.foobarbaz
  #=> "current session in Baz"

I've slightly modified what foobarbaz returns to show where it is coming from.
Note that the third line of foobarbaz could be changed to either of the following
baz.instance_variable_set(:@current_session, @current_session)
baz.instance_variable_set(:@current_session,
      instance_variable_get(:@current_session))

If the latter of these were used, @current_session's accessor would not be needed.

A: You'd just need to set instance variable (not class instance variable!) @current_session of class Baz.
With slightest modification of your code without need of additional class/module methods the most straightforward way is to define initialization method that sets the required variable:
class Foo
  attr_accessor :current_session

  def initialize(current_session)
    @current_session = current_session
  end

  def foobarbaz
    # define Baz#initialize on-the-fly, alternatively with define_method
    Baz.class_eval "def initialize; @current_session = '#{@current_session}';end"
    Baz.send(:include, Bar) # For Ruby < 2.1
  end
end

class Baz
end

module Bar
  def foobar
    @current_session
    # 'foobar'
  end
end

puts Foo.new('current_session').foobarbaz.new.foobar
# current_session


text:
Q: Passing data between ES6 classes? So I'm creating a node/express app for fun, and I made an ES6 class that calls the Twitter API and gets data back. Let's call this 'TwitterClient.es6'. In my 'server.es6' I'm serving up the routes (though I'll eventually change how this is done too), and I want to pass the data returned from my TwitterClient to my server. Without a database (yet), can this be done? I was thinking of using getters and setters but I'm slightly off and it's tripping me up. Right now the data is coming back undefined with my getter function and I'm not sure why. Not to mention Node is a pain to debug. I'm so used to React being able to pass props and state that I almost forgot how to do this in regular old JS! Any help would be amazing.
server.es6
import express from 'express';
import { DB_DEV } from 'database_config';
import bodyParser from 'body-parser';
import util from 'util';
import TwitterClient from 'twitter_client';
import http from 'http';
import debug from 'debug';

const server = express();

server.get('/', function (req, res) {
    var twitter_client = new TwitterClient();
    var data = twitter_client.getData();
    res.send(data);
});

server.listen(3000, function () {
    console.log('Example app listening at ' + 3000);
});

export default server;

TwitterClient.es6
import Twitter from 'twitter';

class TwitterClient {

    constructor() {
        this.fetchTweets();
    }

    fetchTweets() {
        console.log('fetch');
        var self = this;

        var twitter = new Twitter({
            consumer_key: 'xxx',
            consumer_secret: 'xxx',
            access_token_key: 'xxx',
            access_token_secret: 'xxx'
        });

        var params = {
            screen_name: 'jimmyfallon',
            count: 1
        };

        twitter.get('statuses/user_timeline', params, function(error, tweets,   response) {
            if (error) self.handleFetchError(error);
            self.handleFetchSuccess(tweets);
        });

    }

    handleFetchSuccess(tweets) {
        this.set(tweets);
    }

    handleFetchError(error) {
        console.log(error);
    }

    set(data) {
        console.log('I was set!');
        this.tweets = data;
    }

    getData() {
        console.log('I was got!');
        return this.tweets;
    }

    render() {
        console.log('render me timbers!');
        this.getMe();
    }

}

export default TwitterClient;

A: You are calling getData() before twitter.get(..) is done. This has nothing to do with classes and everything to do with the asynchronous nature of JavaScript.
I would let the class method return a promise. For example:
class TwitterClient {

    constructor() {
        this._tweets = this.fetchTweets();
    }

    fetchTweets() {
        console.log('fetch');
        var self = this;

        var twitter = new Twitter({
            consumer_key: 'xxx',
            consumer_secret: 'xxx',
            access_token_key: 'xxx',
            access_token_secret: 'xxx'
        });

        var params = {
            screen_name: 'jimmyfallon',
            count: 1
        };

        return new Promise(function(resolve, reject) {
            twitter.get('statuses/user_timeline', params, function(error, tweets, response) {
                if (error) reject(error);
                resolve(tweets);
            });
        });

    }

    getData() {
        return this._tweets;
    }

}

export default TwitterClient;

and
server.get('/', function (req, res) {
    var twitter_client = new TwitterClient();
    twitter_client.getData().then(
        function(data) {
            res.send(data);
        },
        function(error) {
            // ...
        }
    );
});

See these questions for more information:

*

*How do I return the response from an asynchronous call?

*Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference


text:
Q: Measure a DensityHistogram[] pair similarity I study human vision and more specifically eye-movements.
"If we display 2 symmetrical patterns (20 min one after the other), will our gaze distribution be symmetric is my research question."
The 2 figures at the bottom row below is what is displayed to subjects for 3 seconds. One pattern, then, later in the experiment, its symmetrical transform.
Above are their respective Gaze Density histograms. That is the distribution of where their eyes were while observing the stimuli. The Blue square is the Center Of Gravity of the stimuli.
How can I measure their similarity ? If I have some ideas, I think Mathematica offers great means of image analysis that could be used here.

You could find here the data : allSymFix : 93 sublist for the 93 stimuli pairs I present, along with a manipulate to see all the histograms
allSymFix[[1,1]] are all the gaze observed on stimuli 1 original version.
allSymFix[[1,2]]                           on its symmetrical transform

How can I measure the similarity within each allSymFix[[original stimuli]].
I will then compare it with the similarity computed on random pairs assembled

A: For the sake of having alternative solutions. Here I'm using BinCounts to create a grid of counts that represent the gaze densities.
An important thing is to make sure we are comparing "apples to apples" so I use the same binning for all subjects. Note that the data range from about -20 to 20 in both directions.
bspecX = {-20, 20, 1};
bspecY = {-20, 20, 1};

Now I bin the data using these specs reflecting the symmetric data about the y-axis.
hist1 = Table[BinCounts[allSymFix[[i, 1]], bspecX, bspecY], {i, 93}];
hist2 = Table[BinCounts[Transpose[{-1, 1}*Transpose[allSymFix[[i, 2]]]],
               bspecX,bspecY], {i, 93}];

Here is a look at one pair of "histograms" that I am comparing..

Similar to @Vitaliy's method I look at absolute deviations between the two histograms.
scores = MapThread[Total[Abs[(#1 - #2)], Infinity] &, {hist1, hist2}];

Now I also examine these "scores" for randomly chosen pairings...
scoresr =
  MapThread[
   Total[Abs[(#1 - #2)], Infinity] &, {RandomSample[hist1],
    RandomSample[hist2]}];

Lets compare the distributions of the scores for both the pairings and the randomly selected pairings.
SmoothHistogram[{scores, scoresr}, PlotStyle -> {Blue, Red}]

Notice that the statistic does separate the pairings (blue) from the randomly selected pairings (red) but that it isn't a perfect separation. This is probably at least partly due to the "random" pairings being somewhat artificially similar since they are taken from the same (rather small) collection of images.
Though it is statistics on statistics we can perform a formal test for location on the scores which tells us that we have enough evidence to reject the null that these two statistics have equal locations.
LocationTest[{scores, scoresr}, 0, "TestDataTable"]

A: I know you asked specifically for the comparison of the density histograms, but while thinking about your problem some issues I want to share came to my mind.
Let's first discuss your data. I mentioned this already to Andy in the chat, that one should be aware that the data might not be in the same coordinate system. Do you know for sure, that your reference frame of your sensors is the same for both measurements? If yes, and the origin of your coordinate-system is really in the center, then you can mirror your data to compare the two measurements. Andy and Vitaliy assumed this implicitly but when you look at a plot of your first data-set, it seems a bit as they were shifted.

If you are sure about your setting, this could mean smth. like that our eye is attracted to the same objects (because the overall appearance is similar) but in detail, we prefer to visit your disks from the left, maybe since we are biased because of our reading direction.
I hope it's becoming clear now, what this means for the approach of simply mirroring the data! One completely symmetric stimuli would be a disk at the origin and let's assume, that we have a preferred side which we look first, then you would maybe measure something like this

What would you expect as result for the transformed stimuli? Right, exactly the same. But now you mirror the other stimuli and compare the two outcomes:

While the for such a simple setting the two stimuli should be the same, you will measure considerable differences between them. I was thinking a while about this problem and whether it can be prevented but my knowledge in this area is limited and what follows is only a guess.
If you would present me only a few single pixel, I would have no other chance as just to inspect them without meaning and since they are so small, I would not have the chance to prefer any side. The situation gets complicated, when you present me more pixels in a cluster, because then I see more then just the pixels. It maybe remembers me of something, some object or the silhouette of a girl and then I clearly have my preferences where to look .
Therefore, the question is: Is a disk free of a biased view? And here I would say no, because they are too big, to really look directly in the center. It's really hard to observe oneself but I would say I like the sharp edges more then the flat center. You are in the position to test this. Present your test-persons a simple disk and see what happens. If the observation is not centered, you cannot simply mirror your data and believe you will get reliable results.
Back to your question. My first plot does not show all points of your data. I assumed that when an eye is attracted to something, it sort of rests there for a while. Therefore, the movement is smaller than when the eye makes a movement. This is the reason why I filtered your data by the velocity (first differences) to obtain the spots only:
data = allSymFix[[1]];
{spots1, spots2} = Function[{data}, First[Transpose[
      Select[
       (Transpose[{Most[#], Norm /@ Differences[#]}]) &[data],
       (Last[#] < 0.01) &]
      ]
     ]] /@ data;
spots2 = Times[{-1, 1}, #] & /@ spots2;
ListPlot[{spots1, spots2}, AspectRatio -> Automatic,
 PlotRange -> {{-15, 15}, {-15, 15}},
 PlotStyle -> {{Opacity[0.1], Blue}, {Opacity[0.1], Green}},
 Axes -> False, Frame -> True]

Let me stick to the assumption that those spots are more important for the comparison you want. If you like you can extend the approach to all points later. The simplest thing which came to my mind was to use every point in spots1 and find the nearest point in spots2 and calculate their distances. The Total or Mean of this list of distances is then I quite good measure how similar the observations are. Or, if you like you can estimate the parameters of a gamma-distribution on those distances and obtain more information; do what you like:
distances = ParallelMap[Norm[# - First@Nearest[spots1, #]] &, spots2];
Mean[distances]
(*
  0.86046
*)

For a symmetric pattern and under the assumption that disks are viewed at the center, the above measure will give a value close to zero for the simple disk above.
While I looked into your data, I was asking myself whether there is more interesting stuff to find out. One interesting point is to investigate in the movement of the eye. I don't know how exact your sensors are, but what I liked to know was: Have eyes a preferred direction in their movement. Since data is time data we can easily calculate the angle of each single eye-movement.
As I first saw the result, I could not believe it. Btw, I still doublt it and I think I do something wrong.
Histogram[
 If[Norm[{#1, #2}] > 10.^-3, ArcTan[#1, #2]] & @@@
  Differences[data[[1]]], 100, "PDF",
 Epilog -> {Red,
   Line[{{#, -.3}, {#, .3}}] & /@ Table[i, {i, -Pi, Pi, Pi/4}]}]

It seems our eyes know angles in fractions of Pi better then the most of us do. I marked the Pi/4 positions in red. I would have guessed, that we may have preferences in horizontal and vertical movement, but this?
Lucky enough for the transformed stimuli, the histogram looks exactly the same.
Another thing came to my mind: If we have preferences in direction and movement, maybe we like to scan patterns from left to right or top to bottom. Since the order in your data represents the time, we could look at the movements in x- and y-direction separately. Since only x-values are affected by your transformation, it's maybe ok to assume that the y-movement of the eyes shows some similarities. What I do is, I calculated all partial sums of the y values. So if the eye stays at one point for observation, it's a line with the slope of the y-value of this point in the following plot
ListLinePlot[
 FoldList[Plus, 0, Last[Transpose[#]]]/Length[#] & /@ data,
 Axes -> False, Frame -> True]

One has clearly to think about the value of such a plot, but I like inspecting different sides because humans are good in recognizing patterns. Note, that equal slopes of lines in the above plot show regions, where the same object was observed. You can compare this to the plot of pure y-values and you'll see, that there it's harder to extract features even if you smooth the data. Interesting here, are for instance the region at x=7500 where it seems as there were objects observed in the same order.

A: We'll use SmoothKernelDistribution. Correlated pair with left data set reflected around y-axis:
lefTimagE = SmoothKernelDistribution[{-1, 1} # & /@ allSymFix[[3, 1]]];
righTimagE = SmoothKernelDistribution[allSymFix[[3, 2]]];

Visualize in 3D:
  Row@Plot3D[Evaluate[#], {x, -13, 13}, {y, -13, 13}, PlotRange -> All,
  MeshFunctions -> {#3 &}, Mesh -> 15, PlotPoints -> 50] & /@
  {PDF[lefTimagE, {x, y}], PDF[lefTimagE, {x, y}] PDF[righTimagE, {x, y}],
  PDF[righTimagE, {x, y}]}

The middle is overlap - notice small values. Integrate to find total characteristic
NIntegrate[Evaluate[PDF[lefTimagE, {x, y}] PDF[righTimagE, {x, y}]],
{x, -13, 13}, {y, -13, 13}, Method -> "AdaptiveMonteCarlo"]

Answer: 0.00549086
Random pair:
lefTimagE = SmoothKernelDistribution[{-1, 1} # & /@ allSymFix[[3, 1]]];
righTimagE = SmoothKernelDistribution[allSymFix[[15, 2]]];

Visualize in 2D this time for verity:
Row@ContourPlot[Evaluate[#], {x, -13, 13}, {y, -13, 13},PlotRange -> All,
Mesh -> 15, PlotPoints -> 50] & /@ {PDF[lefTimagE, {x, y}], PDF[lefTimagE,
{x, y}] PDF[righTimagE, {x, y}], PDF[righTimagE, {x, y}]}

The middle is overlap. Integrate to find total characteristic
NIntegrate[Evaluate[PDF[lefTimagE, {x, y}] PDF[righTimagE, {x, y}]],
{x, -13, 13}, {y, -13, 13}, Method -> "AdaptiveMonteCarlo"]

Answer: 0.0038788
I liked Andy's analysis of the whole set for his metric. I ran it for my integral metric too:
Correlated pairs:
coRdaT = Table[NIntegrate[Evaluate[PDF[SmoothKernelDistribution[{-1, 1}
# & /@ allSymFix[[k, 1]]], {x, y}] PDF[SmoothKernelDistribution[
allSymFix[[k, 2]]], {x, y}]], {x, -13,13}, {y, -13, 13},
Method -> "AdaptiveMonteCarlo"] , {k, 1, 93}];

Random pairs:
uNcoRdaT = Table[NIntegrate[Evaluate[PDF[SmoothKernelDistribution[{-1, 1}
# & /@ allSymFix[[k, 1]]], {x, y}] PDF[SmoothKernelDistribution[
allSymFix[[RandomInteger[{1, 93}], 2]]], {x, y}]], {x, -13, 13},
{y, -13, 13}, Method -> "AdaptiveMonteCarlo"] , {k, 1, 93}];

Analysis:
SmoothHistogram[{coRdaT, uNcoRdaT}, Filling -> Axis,
PlotStyle -> {{Thick, Blue}, {Thick, Red}}]

Conclusion: on average integral of overlap for correlated pairs almost order of magnitude greater than for random pairs.
======= ARCHIVE: less reliable, needs-polishing approach =======
Here is a very simple take on this. If my understanding is correct, @500 wishes to see spatial correlation between left and right 2D patterns. I'll use SmoothDensityHistogram because it IMO gives better data representation in this case, but you can use your original approach too. The idea is to use ImageMultiply to "amplify" overlapping regions. Midle image is the overlap for a specific set of your data. Note it was ImageAdjust-ed for better visual perception. As numeric measure you have red number (computed before ImageAdjust for uniform scale) The red number is total "intensity" of overlap which could be some sort of correlation measure. BTW we also need to reflect one of the images around vertical axis, otherwise overlap will be meaningless. Here is correlated pair - data set 3, left and right images. As you can see the red number is high and the overlap does look like originals.
ili = SmoothDensityHistogram[#, Background -> Black,
     ColorFunction -> GrayLevel, ImageSize -> 300,
     PlotRange -> {{-13, 13}, {-13, 13}}, ImagePadding -> 0,
     ImageMargins -> 0, PlotRangePadding -> 0, Mesh -> 0] & /@
   allSymFix[[3]];
il = {ImageReflect[ili[[1]], Left -> Right], ili[[2]]};
Framed@Labeled[GraphicsRow[Riffle[il, (cori =
       ColorConvert[ImageMultiply @@ il, "Grayscale"]) //
     ImageAdjust], Spacings -> 1], ImageData[cori] // Total // Total,
  Top, LabelStyle -> Directive[Red, Bold, 20]]

And here is random pairing of set 3 left image and set 15 right image. As you can see the red number is much less and the overlap does not look like originals.
ili = SmoothDensityHistogram[#, Background -> Black,
     ColorFunction -> GrayLevel, ImageSize -> 300,
     PlotRange -> {{-13, 13}, {-13, 13}}, ImagePadding -> 0,
     ImageMargins -> 0, PlotRangePadding -> 0,
     Mesh -> 0] & /@ {allSymFix[[3, 1]], allSymFix[[15, 2]]};
il = {ImageReflect[ili[[1]], Left -> Right], ili[[2]]};
Framed@Labeled[GraphicsRow[Riffle[il, (cori =
       ColorConvert[ImageMultiply @@ il, "Grayscale"]) //
     ImageAdjust], Spacings -> 1], ImageData[cori] // Total // Total,
  Top, LabelStyle -> Directive[Red, Bold, 20]]

A word of caution: Andy's good comment made me realize there are a few things to worry about here. Most impotently, in most cases our graphics resales the data before it passes them to ColorFunction. This means that for these different data sets their maximums will look same bright on the plots:
Max /@ {allSymFix[[3, 1]], allSymFix[[15, 2]]}
*Answer:* {10.466, 11.172}

This affects correct overlap estimates.


text:
Q: SQL XML query() using sql:variable not working I am trying to write a scalar value function in SQL Server 2008 R2 that will take a chunk of XML and an XQuery path, and return the result as a string. Looking at just the T-SQL to perform the XML XQuery for the time being, the following example shows two statements (1 & 2). The first one should work apparently, but doesn't. The second is the same thing but without the use of sql:variable().
declare @xml xml

set @xml = '<?xml version="1.0" encoding="UTF-8"?>
<Response version="1.0">
    <Transaction>
        <Processing>
            <Return>Some text that I need to extract.</Return>
        </Processing>
    </Transaction>
</Response>'

declare @xquery varchar(100)
set @xquery = '/Response/Transaction/Processing/Return'

-- Statement 1 : This should work, but it doesn't
select
    CAST(@xml.query('data(*[local-name(.) = sql:variable("@xquery")])') as varchar(max))

-- Statement 2 : This does work
select
    CAST(@xml.query('data(/Response/Transaction/Processing/Return)') as varchar(max))

Can anyone tell me why this is not working? What am I doing wrong, if indeed whether it is at all possible?
I have looked at numerous supposed working examples of this on this site, which is how I arrived at the above code, but I can't figure out why my implementation is not working.

A: This is not possible...
sql:variable is meant to deliver a certain value, not a full path...
The only chance I know of is dynamic SQL:
(btw: To retrieve a value you should not use .query() and cast it, better take .value()
declare @xml xml
set @xml = '<?xml version="1.0" encoding="UTF-8"?>
<Response version="1.0">
    <Transaction>
        <Processing>
            <Return>Some text that I need to extract.</Return>
        </Processing>
    </Transaction>
</Response>';

-- Statement "direct value"
select @xml.value('(/Response/Transaction/Processing/Return)[1]','varchar(max)');

--dynamic SQL
declare @xquery varchar(100)='(/Response/Transaction/Processing/Return)[1]'
declare @dynamicSQL NVARCHAR(100)='select @xml.value(''' + @xquery + ''',''varchar(max)'')';
exec sp_executesql  @dynamicSQL, N'@xml XML',@xml;


text:
Q: Post Image through Graph API change Via Link I am using a facebook php SDK to post image to users album using the user access token. First we will generate the token and then post the image. My issue is that posting image works fine but below each image on right side, facebook adds a link 'via MY APPLICATION NAME'.This link redirects user to my application page in facebook (http://www.facebook.com/apps/application.php?id=APPLICATION ID). I want to change this link to point to my personal website URL (www.abc.com).
Please let me know if this is possible.

A: I've seen other apps do it, and am looking for the same thing. I've glanced over all the app settings, and am currently reading the api trying to figure it out. It's probably going to be something stupid like deleting all the other urls to force it to default to your site url in the app settings...Let me know if you have any luck with this.


text:
Q: Correct way to start back ground work ASP.NET MVC 5 I'm building a ASP.NET MVC 5 web page currently. It's worth noting I'm fairly new to ASP.NET itself, prior to this I've only dealt with windows desktop applications.
My question is I'm unsure where to start my recurring background work. This work fires checks and updates to the MySql database on the server every few seconds. Currently I'm starting these checks just by adding a start method in the RouteConfig.cs class which I know is the wrong way to do it, just a quick hack while I search for the correct method. Where should I be starting this background work which should be kicked off as soon as the web page is available not when it's first searched for via the browser by a user?
This brings me to another question, a lot more work seemingly but would it be a better/more standard solution to write the background work as a windows service and establish a sort of interface between the web page front end and the windows service?

A: Search for Quartzin package manager, its best schedular for .net


text:
Q: Writing a pandas dataframe to a word document table via pywin32 I am currently working on a script that needs to write to a .docx file for presentation purposes.  I use pandas to handle all my data calculations in the script.  I am looking to write a pandas dataframe into a table at a bookmark in a word.docx file using PyWIN32. The dataframe consists of floats. The psuedo code is something like this.
frame = DataFrame(np.arange(28).reshape((4,7)), columns=['Text1',...'Text7'])

With pywin32 imported...
wordApp = win32.gencache.EnsureDispatch('Word.Application')
wordApp.Visible = False
doc = wordApp.Documents.Open(os.getcwd()+'\\template.docx')
rng = doc.Bookmarks("PUTTABLEHERE").Range
rng.InsertTable.here

Now i would like to create a table at this bookmark.  The dimensions of the table should be dictated by the dataframe. I would also like the column titles to be the header in the Word table.

A: Basically, all you need to do is create a table in word and populate the values of each cell from the corresponding values of data frame
# data frame
df= DataFrame(np.arange(28).reshape((4,7)), columns=['Text1',...'Text7'])

wordApp = win32.gencache.EnsureDispatch('Word.Application')
wordApp.Visible = False
doc = wordApp.Documents.Open(os.getcwd()+'\\template.docx')
rng = doc.Bookmarks("PUTTABLEHERE").Range

# creating Table
# add one more row in table at word because you want to add column names as header
Table=rng.Tables.Add(rng,NumRows=df.shape[0]+1,NumColumns=df.shape[1])

for col in range(df.shape[1]):
    # Writing column names
    Table.Cell(1,col+1).Range.Text=str(df.columns[col])
    for row in range(df.shape[0]):
        # writing each value of data frame
        Table.Cell(row+1+1,col+1).Range.Text=str(df.iloc[row,col])

Notice that Table.Cell(row+1+1,col+1) has been added two ones here. The reason is because Table in Microsoft Word start indexing from 1. So, both row and col has to be added 1 because data frame indexing in pandas start from 0.
Another 1 is added at row to give space for data frame columns as headers. That should do it !


text:
Q: Is try catch block necessary inside controller in laravel? I'm currently working on a project with my friend. He follows this method of writing codes. Is it good or bad? I'm also not that much experience developer.
public function store(Request $request)
 {
    try
    {
        $comment = new TicketComment();
        $comment->content = $request['comment'];
        $comment->user_id = Auth::user()->id;
        $comment->ticket_id = $request['ticketId'];
        $comment->save();
        $ticket = Ticket::where('id', '=', $comment->ticket_id)->first();
        $ticket->updated_at = $comment->created_at;
        $ticket->update();
    }
    catch(Exception $e)
    {
        request()->session()->flash('unsuccessMessage', 'Failed to add comment !!!');
        return redirect()->back();
    }
    request()->session()->flash('successMessage', 'Comment has been successfully added !!!');
    return redirect()->back();
}

A: Don't have a broad Exception catch block. Only catch exceptions you expect to be thrown in that block that way you can properly log unexpected exceptions and fix any other bugs in your code that may have caused those, instead of hiding them from yourself.
If you must do this then it might be in the context of something like:
public function store(Request $request)
 {
    try
    {
        $comment = new TicketComment();
        $comment->content = $request['comment'];
        $comment->user_id = Auth::user()->id;
        $comment->ticket_id = $request['ticketId'];
        $comment->save();
        $ticket = Ticket::where('id', '=', $comment->ticket_id)->first();
        $ticket->updated_at = $comment->created_at;
        $ticket->update();
    }
    catch(Exception $e)
    {
        if (!($e instanceof SQLException)) {
            app()->make(\App\Exceptions\Handler::class)->report($e); // Report the exception if you don't know what actually caused it
        }
        request()->session()->flash('unsuccessMessage', 'Failed to add comment !!!');
        return redirect()->back();

    }
    request()->session()->flash('successMessage', 'Comment has been successfully added !!!');
    return redirect()->back();
}

This way any unexpected exceptions will still be reported and you can go through your logs later to fix any bugs that are causing them.
As a reminder since PHP 7.1 you can have a union of exceptions in a catch block (Reference) e.g.
try { }
catch (ExceptionType1|ExceptionType2 $e) {

}

This way you can handle the exceptions you know you can handle and let Laravel handle the ones you are not sure how to handle.
Note that you generally don't have to have try-catch blocks in controller code, you can always use the exception handler to do the flash/redirect back combination for all unhandled exceptions if that is your preferred way of handling them.

A: It is allways good to handle the errors. However, Laravel has built in error handling, which ease this process. This does not mean you dont need the try catch block.
Read more about laravel error handling: https://laravel.com/docs/5.8/errors

A: Even that laravel has his own built in error handling you better use try & catch.
Don't use it on development mode but on production mode. The use of try & catch is user friendly, which means that user will not see the traditional page with the error generated from laravel (in case of any error), but will see your default message.
Example of how to use it:
public function index()
{
   try {

           return view('index.blade.php');

   } catch (\Exception $exception) {

           \Log::error($exception);

           return redirect()->back()->with(['message' => 'There was an error']);
   }
}

If you see this part \Log::error($exception);, it means that the error generated from laravel will be registered on logs file under storage/logs/laravel.log so you as e developer can see the problem with that method. On  the other part if something goes wrong with accessing the page: view('index.blade.php') the user will be redirected back to the previous page with a message saved in session, which is: 'There was an error'.
To catch the message in case of errors in your blade you should:
           @if (session('message'))

{{ session('message') }}

            @endif

Happy coding!

A: here is how I handled the same. I logged the error instead of returning it to user interface.
public function postData()
{
 try
  {
    //your logics to post goes here
  }
      catch (\Exception $exception) {

                if (!($exception instanceof \SQLiteException)) {
                    app()->make(\App\Exceptions\Handler::class)->report($exception); // Report the exception if you don't know what actually caused it

                }
                Alert::toast('Error Toast', 'An error occurred');

                \Log::error($exception);

                return redirect()->back();

            }
            Alert::success('SuccessAlert', 'alert');
            return back();
        }


text:
Q: How to find the correct operation to fit a limited set of operations? I'm trying to find a math operation indicated by -> which will result in y given x.
x -> y
0 -> 0
1 -> 6
2 -> 5
3 -> 4
4 -> 3
5 -> 2
6 -> 1

Of course, 7 - x works for all of these except for
0 -> 0

Is there a simple operation that would fit all of these examples? How could I find that operation? Are there better ways to describe this problem?

A: Just take the remainder after dividing it by $7$, that is  $$ 7 - x \mod 7$$


text:
Q: Filter the data from array of object based on condition using lodash I have the below Array of object set, I need to take the some of them based on the condition from the whole array set using lodash.
I have used _.filter(data, condition) in lodash, but expected result is not
coming.
Anyone help me to resolve this ?
Condition : EarnCode < 90 && Hours === 0 (result will be skipped those data).
Request Array set:
[
  {
    "id" : 1,
    "EmpId" : 100,
    "AcctCode" : "2001-00",
    "SuperID" : 2000,
    "ReportNo" : "20180213.2015-06.2768.6",
    "EarnCode" : 96,
    "Hours" : 0
  },
 {
    "id" : 3,
    "EmpId" : 100,
    "AcctCode" : "2001-00",
    "SuperID" : 2000,
    "ReportNo" : "20180213.2015-06.2768.6",
    "EarnCode" : 96,
    "Hours" : 0
  },
  {
    "id" : 2,
    "EmpId" : 100,
    "AcctCode" : "2001-00",
    "SuperID" : 2000,
    "ReportNo" : "20180213.2015-06.2768.6",
    "EarnCode" : 1,
    "Hours" : 0
  },
  {
    "id" : 5,
    "EmpId" : 100,
    "AcctCode" : "2001-00",
    "SuperID" : 2000,
    "ReportNo" : "20180213.2015-06.2768.6",
    "EarnCode" : 1,
    "Hours" : 3
  }
]

Expected Result:
[
{
        "id" : 1,
        "EmpId" : 100,
        "AcctCode" : "2001-00",
        "SuperID" : 2000,
        "ReportNo" : "20180213.2015-06.2768.6",
        "EarnCode" : 96,
        "Hours" : 0
      },
{
        "id" : 3,
        "EmpId" : 100,
        "AcctCode" : "2001-00",
        "SuperID" : 2000,
        "ReportNo" : "20180213.2015-06.2768.6",
        "EarnCode" : 96,
        "Hours" : 0
      },
 {
        "id" : 5,
        "EmpId" : 100,
        "AcctCode" : "2001-00",
        "SuperID" : 2000,
        "ReportNo" : "20180213.2015-06.2768.6",
        "EarnCode" : 1,
        "Hours" : 3
      }
]

A: Just for completeness, following CRice's answer which is likely the way to go about this, if you insist that you must use lodash:

const inputSet = [{
  "id": 1,
  "EmpId": 100,
  "AcctCode": "2001-00",
  "SuperID": 2000,
  "ReportNo": "20180213.2015-06.2768.6",
  "EarnCode": 96,
  "Hours": 0
}, {
  "id": 3,
  "EmpId": 100,
  "AcctCode": "2001-00",
  "SuperID": 2000,
  "ReportNo": "20180213.2015-06.2768.6",
  "EarnCode": 96,
  "Hours": 0
}, {
  "id": 2,
  "EmpId": 100,
  "AcctCode": "2001-00",
  "SuperID": 2000,
  "ReportNo": "20180213.2015-06.2768.6",
  "EarnCode": 1,
  "Hours": 0
}, {
  "id": 5,
  "EmpId": 100,
  "AcctCode": "2001-00",
  "SuperID": 2000,
  "ReportNo": "20180213.2015-06.2768.6",
  "EarnCode": 1,
  "Hours": 3
}]

// Negate your condition, filter keeps items where the condition is
// true, so for your example, you need either Hours to be non-zero
// OR for EarnCode to be greater than 90.
const resultSet = _.filter(inputSet, i => i.Hours !== 0 || i.EarnCode >= 90);
console.log(resultSet); // Includes items 1, 3, and 5.
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

A: No need to use lodash (if you don't want to), since the built in array .filter method will be enough to do this.
All you have to do is give it the right condition. In your case, that the item does not have 0 hours and an EarnCode less than 90. That condition can be represented as either:
!(EarnCode < 90 && Hours === 0)
or eqivalently:
EarnCode >= 90 || Hours !== 0
Using that second one, your filter might look like this:

const inputSet = [{
  "id": 1,
  "EmpId": 100,
  "AcctCode": "2001-00",
  "SuperID": 2000,
  "ReportNo": "20180213.2015-06.2768.6",
  "EarnCode": 96,
  "Hours": 0
}, {
  "id": 3,
  "EmpId": 100,
  "AcctCode": "2001-00",
  "SuperID": 2000,
  "ReportNo": "20180213.2015-06.2768.6",
  "EarnCode": 96,
  "Hours": 0
}, {
  "id": 2,
  "EmpId": 100,
  "AcctCode": "2001-00",
  "SuperID": 2000,
  "ReportNo": "20180213.2015-06.2768.6",
  "EarnCode": 1,
  "Hours": 0
}, {
  "id": 5,
  "EmpId": 100,
  "AcctCode": "2001-00",
  "SuperID": 2000,
  "ReportNo": "20180213.2015-06.2768.6",
  "EarnCode": 1,
  "Hours": 3
}]

// Negate your condition, filter keeps items where the condition is
// true, so for your example, you need either Hours to be non-zero
// OR for EarnCode to be greater than (or equal to) 90.
const resultSet = inputSet.filter(i => i.Hours !== 0 || i.EarnCode >= 90);
console.log(resultSet); // Includes items 1, 3, and 5.


text:
Q: Is " \; " an escape sequence for semicolon in urls Is the combination \; an escape sequence for semicolon i.e. ;.
Pardon me for the shortness of the question before, actually I am using this "\;" to escape the ";" on Linux terminal and as well as windows. It is being used to separate the different parameters querystring of a URL. Using only ";" works for windows but not on Linux. However using "\;" instead of ";" works for both Linux and windows.
The URL is being passed to some command for processing the resource pointed by URL.
My query was simply, Is '\;' a standard escape character for ';' on linux and windows console/shell ?

A: In urls, the escape symbol for ; is %3B
For more information see http://www.december.com/html/spec/esccodes.html

A: No. But the combination \; will give an error. I think you have to try \\; instead of \;.
Because ; is not a escape character in Java. And with \ you can only put the escape characters. If you want some non-escape characters with \ then you have to use \\

A: Semicolon does not need escaping in urls.
You can test it yourself in your javascript console (for Chrome, or maybe Firebug in FF) by using encodeURI(';')

A: No. In URLs, you escape by %XX where XX is the hex code of the character you want. You can get the correctly escaped string easily in javascript by using the escape() or encodeURIComponent() functions.
See this other question for more

A: Your url read pass the arugumnets encodeURIComponent


text:
Q: Can't make MySQL queries in PHP webpage So I'm working on a website where I need to pull data from a MySQL server and show it on a webpage. I wrote a simple PHP script to read data from the database depending upon an argument passed in the URL and it works just fine.
Here is the script:
<?php
function updator($item)
{
  $servername = "localhost";
  $username = "yaddvirus";
  $password = "password";
  $dbname = "database";

  // Create connection
  $conn = mysqli_connect($servername, $username, $password, $dbname);

  // Check connection
  if (!$conn) {
      die("Connection failed: " . mysqli_connect_error());
  }
  echo "Connected successfully";
  $table = "inventory";
  //$item = "Rose Almonds";

  $sql = "SELECT * FROM $table WHERE item = '$item'";
  $result = $conn->query($sql);

  while($data=$result->fetch_assoc()){
    echo "
{$data['item']}

";
    echo "
{$data['item_desc']}

";
    echo "
{$data['price125']}

";
    echo "
{$data['price250']}

";
  }
      //echo "0 results";
  $conn->close();
}
if (defined('STDIN')) {
  $item = $argv[1];
} else {
  $item = $_GET['item'];
}
//$item = "Cherry";
updator($item);

?>

This script works exactly as expected. I call it using http://nutsnboltz.com/tester.php?item=itemname and it pulls and shows the data just fine.

P.S You can test it out by using Cherry or Blueberry as items.

The problem is, when I'm trying to put this data in my productpage.php file, I can't get the data to show up. Here's how the file hierarchy goes:
<php
*Exact same php script as above*
?>

Header and navbar come here

 RANDOM TEXT BEFORE

        <?php
        while($data=$result->fetch_assoc()){
          echo "
{$data['item']}

";
          echo "
{$data['item_desc']}

";
          echo "
{$data['price125']}

";
          echo "
{$data['price250']}

";
        }
         ?>

        <H!> MORE RANDOM TEXT

footer here
scripts etc

So the script above the footer prints everything just fine. However, down where the HTML is, nothing is printed after the PHP code. It only shows my Navbar and the H1 tag saying "RANDOM TEXT BEFORE" and that's about it. My footer is gone along with everything else.
What exactly is the issue here and how do I fix this?

A: The problem seems to be that you're declaring $result inside the updator function, so it's not available when you're attempting to call it later.
The best thing to do might be to return $result from the function and assign that to a variable - something like this:
function updator($item)
{
    // ... some code ...

    $sql = "SELECT * FROM $table WHERE item = '$item'";
    $result = $conn->query($sql);

    // ... some more code ...

    return $result;
}

<-- HTML CODE HERE -->

<?php
$item = !empty($_GET['item']) ? $_GET['item'] : false;

// yes I know it's a bit hacky to assign the variable
// within the 'if' condition...
if($item && $result = updator($item)) {
    while($data=$result->fetch_assoc()){
        echo "
{$data['item']}

";
        echo "
{$data['item_desc']}

";
        echo "
{$data['price125']}

";
        echo "
{$data['price250']}

";
    }
}
?>


text:
Q: SDL_Event->key.keysym.sym symbol keys (colon, double quote, question mark...) http://www.libsdl.org/docs/html/sdlkey.html
Here are the key enums listed in the SDL documentation.
Specifically for this question we only need a subset.
SDLK_COLON      //value is 58 (ascii)
SDLK_SEMICOLON  //value is 59 (ascii)

//Code Example illustrating question
void KText::OnKeyDown(SDLKey key, SDLMod mod, Uint16 unicode) {
    if(key == SDLK_COLON) exit(1);
}

When I hit semicolon, clearly it won't exit.  When I hold shift and hit semicolon (keying a colon) it still doesn't exit.  I've tested, no matter if I'm holding shift or not it throws the default key.  This could be by design or it could be a bug.  I could simply say well, if I'm holding shift and key semicolon then I should use colon instead.  However that seems rather a pain to remap all the keys while holding shift.
Has anyone else found a work around for this?
Edit:
Looking at values inside the function for key indicate the key is the same regardless of holding shift or not and it's not specific to semicolon/colon.  It's the same for all keys (makes sense for letter keys sense there is no SLDK_A only SDLK_a, but for brackets, quotes, greater than/less than, dollar sign, etc they do not show up only the base key)

A: So, after much commenting back and forth: To correctly read the keyvalue, the unicode value should be used, which means SDL_EnableUNICODE(1); somewhere in initialization of the program (so that unicode gets filled in - it does add a tiny bit [in most cases, it's function call to a function that performs a lookup in a table of some sort, but it may be a little more than that] of extra processing, so if it's not needed, it's wasted to try to translate every keypress to their respectice actual unicode value).


text:
Q: How to see if redis is installed from within a python shell From the shell prompt I can easily view whether I have redis on my machine by doing:
PROD WEB ➜  /home  redis
~redis

How would I do the same from within the python shell? Do I have to use a subprocess call?

A: You can install a module of redis, and use it. For example:
import redis
redis.Redis('localhost', .....)


text:
Q: Specifying properties returned from API in client I want to limit the amount of properties that are returned from my REST api built in dotnet core. When accessing resources the client only needs specific subsets of the data returned from the api. What is a good way to tell the api which properties the client wants returned?
My initial thought would be to add query parameters to the endpoint like this:
http://www.restapi.com/v1/resource?fields=id,name,type
But I am not sure the best way to implement this in the api so that it is reusable and clean.

A: You're right that you usually don't want to return your full domain model or data model over your web API. Usually you define a custom model type for this purpose, which you can also decorate with attributes for model binding and model validation, if desired.
If you want the client to be able to determine what properties it gets, you can return an anonymous type built for this purpose, or perhaps have several DTO types predefined that the client's parameters result in.


text:
Q: Hidden Markov Model - understanding Viterbi algorithm I try to understand the Viterbi algorithm for solving hidden Markov models. There is a pseudo-code of it in Wikipedia:

In the row that marked in blue (starts with $T_2$) I don't understand: how does it choose a state in case where there is more than one state with the maximum likelihood? in this implementation it will pick the first state that has the maximum, but it makes no sense.

A:
it will pick the first state that has the maximum, but it makes no sense

Why not? Ties are esentially irrelevant, in the sense that any election will find the same global maximum. Hence to pick the first one is as correct as picking any other.


text:
Q: JSON Object changes randomly from api I get data from an API in which the JSON object changes randomly, like if it is at "position": 1, now it will change randomly to "number": 1. So, how can I check in my application if the object is at "position": 1 or "number": 1 and use it as int?
JSON :-
{
    "now": [{
        "time": {
            "starts_in": 0,
            "ends_in": 79580,
            "starts_at": 0,
            "ends_at": "2018-01-21T08:00:00.788Z"
        },
        "coins": {
            "free": 8,
            "first_win": 16,
            "max": 52,
            "collected": 0
        },
        "unk1": -88317689,
        "position": 1,
        "xp_multiplier": 0,
        "location_scid": {
            "scid_type": 15,
            "scid_id": 1
        },
        "tid": "TID_WANTED_3",
        "location": "Terre",
        "mode": {
            "name": "Bty",
            "color": "#0884FA",
            "description": " The team wins!"
        },
        "unk4": 0,
        "info": "",
        "unk5": 0,
        "unk6": 0
    }, {
        "time": {
            "starts_in": 0,
            "ends_in": 36380,
            "starts_at": 0,
            "ends_at": "2018-01-20T20:00:00.788Z"
        },
        "coins": {
            "free": 24,
            "first_win": 0,
            "max": 32,
            "collected": 0
        }
    }],
    "later": [{
        "time": {
            "starts_in": 79580,
            "ends_in": 165980,
            "starts_at": "2018-01-21T08:00:00.788Z",
            "ends_at": "2018-01-22T08:00:00.788Z"
        },
        "coins": {
            "free": 8,
            "first_win": 16,
            "max": 52,
            "collected": 0
        },
        "unk1": -88217689,
        "position": 1,
        "xp_multiplier": 0,
        "location_scid": {
            "scid_type": 15,
            "scid_id": 7
        },
        "tid": "TID_GOLDRUSH_1",
        "location": "Mine",
        "mode": {
            "name": "Grab",
            "color": "#AA57CF",
            "description": " An. "
        }
    }]
}
Thanks in advance :)

A: JSONObject c = //Your jsonObject;
  String position = c.getInt("position");
  String number = c.getInt("number");
  if(position!=null){
    //TODO You know it is position and it's int value
  }else if(number!=null){
    //TODO You know it is number and it's int value
  }else{
    //TODO Its neither of two
  }

A: If you're using Gson to convert your JSON to a class, you can use both position and number as attributes for your destination class.
After that, check which one is null and which one is not and use that is not null as your number.

A: Just try this one,
JSONObject object = (Your jsonObject);
if(object.has("position")){
      ** do your code here **
}else if(object.has("number"){
      ** do your code here **
}


text:
Q: Error: expected primary-expression before ']' token in C++ I'm trying to create something similar to string.find with vectors c++98, but I can't fix this error.
I have simplified the code and left only the error.
If I can get help on how to achieve this.
#include <iostream>
#define MAX 99999
using namespace std;

int free_pos (int v[]);
int find_line (int v[], int pos);

int main() {
   char text[MAX];
   int loc_key[MAX],start_line[MAX]; //

   for(int i=0; i<free_pos(loc_key);i++) {
       cout << "Line: " << i+1;
       int pos = find_line(start_line[],loc_key[i]); //Here is the error
       for(int j=start_line[pos];j<start_line[pos+1];j++) {
            cout<<text[j];
       }
       cout<<endl;
   }
   return 0;
}

int free_pos (int v[]) {
    for(int i=0;i<MAX;i++){
        if(v[i] == 0)
            return i;
    }
    return 99;
}

int find_line (int v[], int pos) {
    for(int i=0; i<free_pos(v); i++) {
        if(v[i]==pos)
            return v[i];
        if(v[i]< pos)
            return v[i-1];
    }
}

A: Your both functions
int free_pos (int v[]);
int find_line (int v[], int pos);

take arrays as an input, but then you try to call int pos = find_line(start_line[],loc_key[i]);, which should take the name of an array only, as it is the name which is known by the program as an array. You can easier (in my opinion) get it, if you write both of these functions following way:
int free_pos (int* v);
int find_line (int* v, int pos);

They do the same job as your functions, but you can see that their arguments are: an int pointer (array) and an int. Then, calling the function needs only the int pointer, which in your case is start_line, and the integer loc_key[i]. If you still have problems understanding it, you could read about dynamic memory allocation of arrays, which is done as: int* arr; arr = new int[your_size]; - I think it is clearer while thinking that way.

A: #include<bits/stdc++.h>
using namespace std;
int max(int arr[],int n){
maximum=INT_MAX;
for(int i=0;i<n;i++){
if(arr[i]>maximum){
maximum=arr[i]}}
return maximum;}

int main(){
int size;
cin>>size;
for(int i=0;i<size;i++){
cin>>arr[i]}
cout<<max(arr,size);
return 0;}


text:
Q: I'm having trouble submitting form data to an email I have the following code in a form on my site:
<form method="post" name="myemailform" action="js/formtoemail.php" id="contactform">

Name<input name="name" type="text" />

Email<input name="email" type="text" />

Message <textarea name="message" cols="1" rows="7"> </textarea>

Submit

</form>

This is supposed to just pass the name, email and message to the .php file so the data can be emailed and then display a success message.
It doesn't seem to email however.  The php is as follows:
<?php
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$email_from = 'email@email.com';
$email_subject = "New Form submission";
$email_body = "You have received a new message from $visitor_email with the user $name.\n".  "Here is the message:\n $message".
$to = "user@email.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to,$email_subject,$email_body,$headers);
?>

What am I doing wrong?


text:
Q: Mongo DB - Filter data element in nested array Query :
db.DEFAULT.find({ "bookStore.books.book.bookId":7501},{"bookStore.books.book.bookId" :1});

Collection :
{
"_id" : ObjectId("5988814feb46972540cebccd"),
"bookStore" : [
    {
        "books" : [
            {
                "book" : {
                    "bookId" : 7501
                }
            },
            {
                "book" : {
                    "bookId" : 7502
                }
            },
            {
                "book" : {
                    "bookId" : 7500
                }
            }
        ]
    }
]
}

When I run the query, it displays all the 3 records. Is there anyway only the matching record will be displayed in the results.

A: You need $map with $filter since your arrays have more than one level of nestings:
db.collection.aggregate([
    {
        $addFields: {
            bookStore: {
                $map: {
                    input: "$bookStore",
                    as: "bs",
                    in: {
                        books: {
                            $filter: {
                                input: "$$bs.books",
                                as: "b",
                                cond: {
                                    $eq: [ "$$b.book.bookId", 7501 ]
                                }
                            }
                        }
                    }
                }
            }
        }
    }
])

Mongo Playground


text:
Q: how to show foreign key value instead of its ID i'm try to display foreign key value , but it instead return the id , in template
models.py
class Product(models.Model):
    product_name = models.CharField(unique=True, max_length=50)
    pass

    def __str__(self):
        return self.product_name

class Order(models.Model):
    id = models.AutoField(primary_key = True)
    products = models.ManyToManyField(Product ,through='ProductOrder')
    pass

    def __str__(self):
        return str(self.products.all())

 class ProductOrder(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    ordering = models.ForeignKey(Order,
    on_delete=models.CASCADE,blank=True,null=True)
    pass

    def __str__(self):
        return str(self.product)

this is my views.py
class ListOfOrder(ListView):
template_name = 'order/product_group.html'
context_object_name = 'productss'

def get_queryset(self):
    return ProductOrder.objects.all()

template.html
{% for product in productss %}

    {{ product.product }}

      {% endfor %}

i expected to display the product name but it instead displayed the ID of the product
thanks for your answer


text:
Q: How to use TDengine 's query_a() api in c By reading TDengine C API reference. I see that TDengine support async APIs and one of then which is called query_a(). And I'm new to C. I want to call this API in multiple thread.
The API instructions are as follow:
   // taos: The database connection returned by calling taos_connect()
   // sql: The SQL statement needed to execute
   // fp: User-defined callback function, whose third parameter code is used to indicate whether the operation is successful, 0 for success, and negative number for failure (call taos_errstr() to get the reason for failure). When defining the callback function, it mainly handles the second parameter TAOS_RES *, which is the result set returned by the query
   // param:the parameter for the callback
    void taos_query_a(TAOS *taos, const char *sql, void (*fp)(void *param, TAOS_RES *, int code), void *param); Execute SQL statement asynchronously.

    // res: The result set returned when taos_query_a() callback.
    // fp: Callback function. Its parameter param is a user-definable parameter construct passed to the callback function;
    // numOfRows is the number of rows of data obtained (not a function of the entire query result set).
    // In the callback function, applications can get each row of the batch records by calling taos_fetch_rows() forward iteration.
    // After reading all the records in a block, the application needs to continue calling
    // taos_fetch_rows_a() in the callback function to obtain the next batch of records for
    // processing until the number of records returned (numOfRows) is zero (the result is returned)
    // or the number of records is negative (the query fails).
    void taos_fetch_rows_a(TAOS_RES *res, void (*fp)(void *param, TAOS_RES *, int numOfRows), void *param);
    Get the result set of asynchronous queries in batch, which can only be used with taos_query_a().

more details can refer [API reference][1]
I don't know how execute mounts of query_a() in muliplte thread, and how could I know that the callback method have done. Can some help?
[1]: https://tdengine.com/docs/en/v2.0/connector#c-cpp

A: I am not familiar with C, But you can reference TDengine's repo, They also have sample code for this api.
you can reference the usage of the query_a() at github query_a example in C


text:
Q: How do I change the color of my background smoothly? Here is the code in question - https://codepen.io/illpill/pen/VbeVEq
function newColor() {
    var randomNumber = Math.floor(Math.random() * (colors.length));
    document.body.style.backgroundColor = colors[randomNumber];
}

Right now that is the newColor() function...
When the button clicks, I'd like it to smoothly transition into the next quote as opposed to abruptly loading it. I'd also like for the quote to fade into white and then into a new quote... How is this achieved? Is it better to use jQuery?
Thanks!

A: Add transition to your body for background-color property.
body {
  transition : background-color 1s ease-in-out;
}

To add transition to any element you should write,
element-selector {
  transition: [CSS property] [duration] [timing-function];
}

For heading tags it will be
h3,h4 {
  transition: [css property] [duration] [timing-function]
}

Transition only works when there is a change in the CSS property specified for the given element.

A: You can use CSS to fade the background (like others have shown here), but you'll have to use JavaScript to fade the text in and out.
Here's a working version with the quote and author fading between random states:
$('#quote').fadeOut(400,function(){
  $(this).html(quotes[randomNumber][0]).fadeIn();
});
$('#author').fadeOut(400,function(){
  $(this).html(quotes[randomNumber][1]).fadeIn();
});

A: Keep your code as is and add a css property:
.your-element-selector {
  transition: all ease 500ms;
}

Or with JS:
document.body.style.transition = 'all ease 500ms';


text:
Q: Does water have a minimal thickness because of van der waals force? I have read this question:
The thickness of a puddled sheet of water
https://en.wikipedia.org/wiki/Surface_tension#Puddles_on_a_surface

The liquid mass flattens out because that brings as much of the mercury to as low a level as possible, but the surface tension, at the same time, is acting to reduce the total surface area. The result of the compromise is a puddle of a nearly fixed thickness.
    The same surface tension demonstration can be done with water, lime water or even saline, but only on a surface made of a substance to which water does not adhere. Wax is such a substance. Water poured onto a smooth, flat, horizontal wax surface, say a waxed sheet of glass, will behave similarly to the mercury poured onto glass.
Another way to view surface tension is in terms of energy. A molecule in contact with a neighbor is in a lower state of energy than if it were alone (not in contact with a neighbor). The interior molecules have as many neighbors as they can possibly have, but the boundary molecules are missing neighbors (compared to interior molecules) and therefore have a higher energy. For the liquid to minimize its energy state, the number of higher energy boundary molecules must be minimized. The minimized number of boundary molecules results in a minimal surface area.

Now i do understand that in this more QM answer, it says that the molecules at the boundary must be minimized (because they have higher energy). This minimizes the size (and thickness because of gravity).
What this does not explain is, though, why this minimalization does not continue until only a single layer molecules are left on the surface.
This minimalization must stop somewhere where the forces equilize, that is:

*

*gravity

*van der waals
https://en.wikipedia.org/wiki/Van_der_Waals_force
https://pubs.acs.org/doi/10.1021/jp806376e
Am I correct that it is the van der waals force that keeps the molecules in a droplet and that gravity is trying to flatten the droplet as much as possible, thereby thinning the water, making as little number of layers of water molecules on top of each other as possible?
Question:

*

*Is it the van der waals force that keeps the minimal size of the water droplet and the minimal thickness of the water (that is the minimal number of layers of molecules)?

A:
What this does not explain is, though, why this minimalization does not continue until only a single layer molecules are left on the surface.

Because the force of surface tension is trying to minimize the surface, not the thickness of water, since surface tension acts like a rubber sheet covering it and trying to pull it all together.
In case of the contact angle being $\theta = 180^°$, when the surface doesn't attract water at all, is the shape only a result of gravity and surface tension. The thickness would be minimized only if there were no surface tension (because then there would have to be no compromise between minimizing thickness (gravity) and minimizing surface and therefore making the liquid into a sphere (surface tension)).
The contact angle depends both on the liquid and the surface, so in order to have liquid of volume $V$ completely covering surface $A$ with a layer as thin as possible $\left(\approx\frac{V}A\right)$, we'd need such a combination of liquid and surface for which $\theta = 0^°$. An example of such a combination are ordinary surfaces under normal temperature and pressure, and water with dissolved carbon (and other components) that usually covers ordinary surfaces with a liquid layer several nanometers thick.

Am I correct that it is the van der Waals force that keeps the molecules in a droplet and that gravity is trying to flatten the droplet as much as possible, thereby thinning the water, making as little number of layers of water molecules on top of each other as possible?

Yes, but in addition to van der Waals force and gravity, there are also hydrogen bonds that also try to keep molecules in the droplet.

Is it the van der Waals force that keeps the minimal size of the water droplet and the minimal thickness of the water

Van der Waals force and hydrogen bonds only try to keep minimal surface (i.e. as spherical as possible). It's only gravity that tries to keep the minimal thickness of the water (as long as we neglect the attraction between the liquid and the solid surface it lies upon, otherwise there would be a fourth force).


text:
Q: Should I place my HTML inside JS, and innerHTML to .root, just like React.js? Should I consider
HTML:

JS:
document.querySelector(`.root`). innerHTML = `{ **html here** }`;

Would this ease my work out make it even worse?

A: depends on the project. data heavy stuff generating html from js is the way to go... for more static sites, html is just fine.
I generally don't write more html than this.


text:
Q: Bootstrap Modal being temperamental I am by no means a web developer but helped out at work with a webpage they needed doing and had been quoted a crazy price for.
The page is basically a list of sections represented by an image and when the image is clicked a modal opens which contains more information.
Some people have complained that the modals sometimes do not open, this is not limited to a particular one and people have said that they can open it, close it and then try opening it again but it does not work. This doesn't happen all the time though, sometimes there are no issues.
I have not been able to replicate this and I have tried several browsers. The users have all been using chrome or IE.
My code for the image for a section is,

Urinary Tract Infections

The code for the modal that opens when clicking this image is,

<button aria-label="Close" class="close" data-dismiss="modal" type="button"> </button>

Urinary Tract Infections

//the information held in the modal

When the modal is open there is a button at the bottom to close the modal,
  <button class="btn btn-primary" data-dismiss="modal">Close Window</button>

Or an 'x' button in the top right

<button aria-label="Close" class="close" data-dismiss="modal" type="button"> </button>

Is there anything that anyone can see to suggest why sometimes a modal may not open? As I say, I have never been able to replicate this but people have said it happens occasionally?
Thanks