text:
Q: Check if key either not exist or should have a particular value in filter method I have an object as
var obj = [
    {
      key1: true,
    },
    {
      key1: true,
      key2: true,
    },
    {
      key1: true,
      key2: false,
    }
]

And my filter function is
const result = obj.filter(item => (!("key2" in item) || item.key2) );
return result;

Here I'm trying to filter the array items with either the key2 should not exist or the key2 should be true. However, I'm getting the complete items in the result and it is not removing the item with key2: false

var obj = [{
    key1: true,
  },
  {
    key1: true,
    key2: true,
  },
  {
    key1: true,
    key2: false,
  }
]

const result = obj.filter(item => (!("key2" in item) || item.key2));
console.log(result);

Expected result
var obj = [
  {
    key1: true,
  },
  {
    key1: true,
    key2: true,
  },
]

A: Use Object.hasOwnProperty('key2') to look for the key in the object

var obj = [
    {
      key1: true,
    },
    {
      key1: true,
      key2: true,
    },
    {
      key1: true,
      key2: false,
    }
]

const result = obj.filter(item => (!item.hasOwnProperty('key2') || item.key2) );
console.log(result);

A: You can also filter on undefined:

var data = [ { key1: true, }, { key1: true, key2: true, }, { key1: true, key2: false, } ]

let result = data.filter(({key2}) => key2 === undefined || key2)

console.log(result)

This would filter on key2 being either truthy or undefined
Or even shorter as suggested by Aswin:

var data = [ { key1: true, }, { key1: true, key2: true, }, { key1: true, key2: false, } ]

let result = data.filter(({key2}) => !key2)

console.log(result)


text:
Q: what do you call the gameplay of an application? I mean, when we want to analyse the usage of a game, we're talking about the gameplay. What are we talking about when we want to analyse the usage of an application in a similar way? I am not thinking of the user experience, but of the "gaming" experience (the journey) itself. Is there any special word for this? or any theatrical analogy?
Thanks

A: Always keep things as simple as possible when speaking with a diverse audience.
The gameplay aspect of any activity can be referred to as the "User experience". It's what the user experiences while interacting with the app, video game, board game (or, assembly of Ikea furniture, changing a car tire, operating the space shuttle, etc).

A: User journey is a term in UX (user experience) engineering that describes the route a user takes through an application or website, or more generally, the longer-term sequence of interactions a user has with a company or brand online/via social media/via apps. It's really an aspect of the user experience. Since you mention "journey", this is probably the best term (although there are a lot of other terms in UX engineering and system design).
https://uxplanet.org/a-beginners-guide-to-user-journey-mapping-bd914f4c517c
https://www.experienceux.co.uk/faqs/what-are-user-journeys/
https://www.appcues.com/blog/user-journey-map

A: suggestions:

*

*gamming stats

*usage stats

*retention stats

*xp stats

*total time on app

*no of days on app

*app streak

*engagement stats

*playing points

*participation points

*application stats / app stats

p.s. Analytics helps you form hypotheses, while statistics (stats) lets you test them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Facing error while loading data from Excel Sheet to DataTable using (OleDbConnection connection = new
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + ";Extended Properties=\"Text;HDR=" + header + ";IMEX=1;Readonly=1;Extended Properties=Excel 8.0;\""))
{
    using (OleDbCommand command = new OleDbCommand(sql, connection))
    {
        using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
        {
            dataTable = new DataTable();
            adapter.Fill(dataTable);
        }
    }
}

The above is the code I am using and getting the below error:

Cannot update.  Database or object is read-only.

Have someone faced the same issue?

A: your connection string contains "Readonly=1;". try changing "Readonly=0;". And try to remove "imex=1". So your code should be someting like that:
    using (OleDbConnection connection = new
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + ";Extended Properties=\"Text;HDR=" + header + ";Readonly=0;Extended Properties=Excel 8.0;\""))
{
    using (OleDbCommand command = new OleDbCommand(sql, connection))
        {
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
                {
                    dataTable = new DataTable();
                    adapter.Fill(dataTable);
                 }
         }
}

A: Try using the following syntax (remove Text from Extended properties since it is used to import csv files) :
using (OleDbConnection connection = new
OleDbConnection(String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"HDR={1};IMEX=1;Readonly=1;Extended Properties=Excel 8.0;\"",pathOnly ,header )))
{
    using (OleDbCommand command = new OleDbCommand(sql, connection))
    {
        using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
        {
            dataTable = new DataTable();
            adapter.Fill(dataTable);
        }
    }
}

If you have office 2007 or higher provider installed try using Microsoft.ACE.OLEDB.12.0 provider since the it also support reading old excel formats.
If you are trying to import text files (csv) then it is better to use text parsing libraries such as :

*

*TextFieldParser Class

*CsvHelper


text:
Q: Display dropdown selected item in URL of the website I am working on a single page asp.net application(webform) with 4 dropdowns.
Please take this example http://ifsccode.in
I need the same functionality in my website.The coding part is done.Everything is working fine but I want to display the dropdown selected item in the URL same as the above example.
I would like to tell you that I have created only one page application.
So please tell me how to achieve the Dropdown selected item in URL.

A: This page uses URL Rewriting. Actually the resulting URL is not generated by user selecting and option, but the url is allready there. Look at this link.
"/development_credit_bank_limited/daman_diu" is responding to a get request and displaying the page according to that request and parameters.
So what you have to do is first implement URL Rewriting in your application and then design your pages to use that convention.

A: Use QueryString like if I choose Emad from ddlEmployees in /Employee.aspx page then the url will be like this /Employee.aspx?Employee=Emad and redirect to the new url.

A: try this code following code
 protected void Page_Load(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(Request.QueryString["u"]))
    {
        // bind second dropdown with first's selected value
    }
    if (!string.IsNullOrEmpty(Request.QueryString["u"]) && !string.IsNullOrEmpty(Request.QueryString["m"]))
    {
        // bind third dropdown with first's selected value and second's selected value
    }
    if (!string.IsNullOrEmpty(Request.QueryString["u"]) && !string.IsNullOrEmpty(Request.QueryString["m"]) && !string.IsNullOrEmpty(Request.QueryString["n"]))
    {
        // bind Details
    }
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Response.Redirect("Default.aspx?id=" + DropDownList1.SelectedItem.Value + "");
}

protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
    String url = Request.RawUrl;
    Response.Redirect(url + "&m=" + DropDownList2.SelectedItem.Value + "");
}
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
    String url = Request.RawUrl;
    Response.Redirect(url + "&n=" + DropDownList3.SelectedItem.Value + "");
}

And do url rewritting also for this concept .....
I hope this will work for you......................


text:
Q: How to use "not" in XPath? I want to write something of the sort:
//a[not contains(@id, 'xx')]

(meaning all the links that there 'id' attribute doesn't contain the string 'xx')
I can't find the right syntax.

A: you can use not(expression) function
or
expression != true()

A: not() is a function in XPath (as opposed to an operator), so
//a[not(contains(@id, 'xx'))]

A: Use boolean function like below:
//a[(contains(@id, 'xx'))=false]

A: None of these answers worked for me for python. I solved by this
a[not(@id='XX')]

Also you can use or condition in your xpath by | operator. Such as
a[not(@id='XX')]|a[not(@class='YY')]

Sometimes we want element which has no class. So you can do like
a[not(@class)]


text:
Q: excluding some data while retrieving data from mongodb is not working i'm using mongodb nodejs driver.
const res = await chats.findOne({ _id: chatId }, { messages: 0, _id: 0 });

this is what i'm getting in response, i don't wanna get messages and _id property on received data
{
      "_id": "d0fff742-4af5-4e6a-bd51-9aa47da08fb9",
      "messages": "ea678ca7-81fb-479b-89f8-7995d8831992",
      "lastMessage": {
        "content": "Hey, how's it?",
        "sender": "urtheaman"
      }
    }
  }

collection.find(query, options)
$slice isn't working as well. i think entire options parameter isn't working.
const res = await messages.findOne(
      { _id: messagesId },
      { messages: { $slice: [from, 15] }, _id: 0 }
    );

A: You are supposed to get the whole document back and then have a function of your own that handles that data in a way that is useful to you.
You could do
function getLastMEssage (data){
    return data.lastMessage.content
}

A: Try using:
const res = await chats.findOne({ _id: chatId }, { messages: 1, _id: 1 });

If you want to have a field, make sure it's one else 0.

A: documentation says
You may specify either fields to include or fields to withhold but not both. For example, the following projection is invalid because it simultaneously includes the name field and withholds the address field
// Invalid
// Can't simultaneously include and withhold
{ "name": 1, "address": 0 }

// Valid
// Can exclude _id while including other fields
{ "_id": 0, "name": 1 }

i'm only withholding at a time, not doin both but still doesn't work.

A: You should use projection like this:
var cursor = client
    .db('so')
    .collection('sample')
    .find()
    .project({ _id: 0, messages: 0 });

await cursor.forEach(console.dir);
// { lastMessage: { content: "Hey, how's it?", sender: 'urtheaman' } }

You can see the full sample runnable file here.
Also, I would suggest that you should use mongoose instead of mongo driver for node for a better development experience.


text:
Q: Amazon Get Purchase Orders API I've been looking at MWS but it only seems to get customer orders through the API which is not what I need. It will give reference to a PO number but will not actually retrieve one. Am I missing something in the documentation or is it really not possible?
Anyone have experience with their API in this area, or a third party tool such as Zinc?
Edit: This is what I mean by a purchase order. Yellow are the fields I need (screenshot from Amazon).


text:
Q: Smartphone apps can't read the entirety of long text files? (Orgzly / Filenotes) I keep a lot of .txt files synced across all my devices with dropbox, and up until recently I've had no problem accessing them on my phone with an app called Orgzly. However I seem to have hit some sort of character limit as I'm continuously adding to one of these files and while the file is perfectly readable on any PC, Orgzly now seems to cut out near the end of the file. (For reference, I'm now at 1921 words over 37 pages if I paste the contents of the file into a blank word document)
I just tried another app called Filenotes and the exact same thing happens. Perhaps I'm I'm not searching the correct keywords, but a google search is not showing anything remotely useful within the top 50 hits.
So my question is this - Do smartphone operating systems or the app APIs have some sort of built in character limit for files? And is there any sort of workaround to get this file readable on my phone, short of accessing the .txt file via the dropbox app directly? (Which actually works, FYI)


text:
Q: cannot display gridview inside listview in my flutter demo app I'm converting my native android project in to flutter application, in this i need to display grid of options below other widgets.
here is code
void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Column homeThumb(String icon, String label) {
      Color color = Theme.of(context).primaryColor;

      return new Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          new Container(
            margin: const EdgeInsets.all(8.0),
            child: new Image.asset(icon, width: 32.0, height: 32.0),
          ),
          new Container(
            margin: const EdgeInsets.only(top: 8.0),
            child: new Text(
              label,
              textAlign: TextAlign.center,
              style: new TextStyle(
                fontSize: 12.0,
                fontWeight: FontWeight.w400,
                color: color,
              ),
            ),
          ),
        ],
      );
    }

    Widget homeIcon = new Container(
        child: new Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
          new Container(
              margin: const EdgeInsets.only(
                  top: 40.0, left: 8.0, right: 8.0, bottom: 8.0),
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  homeThumb("images/icons/list.png", 'Claim Offers'),
                  homeThumb("images/icons/wallet.png", 'Wallet'),
                  homeThumb("images/icons/cart.png", 'Redeem Offers'),
                ],
              )),
          new Container(
              margin: const EdgeInsets.all(8.0),
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  homeThumb("images/icons/user.png", 'Account'),
                  homeThumb("images/icons/badge.png", 'Merchants'),
                  homeThumb("images/icons/history.png", 'Shopping History'),
                ],
              )),
          new Container(
              margin: const EdgeInsets.all(8.0),
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  homeThumb("images/icons/bell.png", 'Notifications'),
                  homeThumb("images/icons/plane.png", 'Service Request'),
                  homeThumb("images/icons/share.png", 'Share & Earn'),
                ],
              )),

        ]));

    Widget grid = new GridView.count(
      crossAxisCount: 4,
      children: new List<Widget>.generate(16, (index) {
        return new GridTile(
          child: new Card(
              color: Colors.blue.shade200,
              child: new Center(
                child: new Text('tile $index'),
              )
          ),
        );
      }),
    );

    return new MaterialApp(
      title: 'Minkville',
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('Minkville'),
        ),
        body: new ListView(
          children: [
            new Image.asset(
              'images/slider/img_s1.jpg',
              width: 600.0,
              height: 180.0,
              fit: BoxFit.fill,
            ),
            homeIcon,
            grid

          ],
        ),
      ),
    );
  }
}

on debug, following logs are coming
I/flutter (16594): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 441 pos 12: 'child.hasSize': is not true.
I/flutter (16594): Another exception was thrown: RenderBox was not laid out: RenderRepaintBoundary#199e9 relayoutBoundary=up3 NEEDS-PAINT

A: Ignore all the above answers.
Make sure you set shrinkWrap : true in both ListView and GridView.
Problem Solved!!

A: My simplest example no CustomScrollView no SilverGrid just a normal ListView and GridView.
Heres Why I think you cant directly put a gridView inside a ListView because once you do that

*

*you cant differentiate whether you are scrolling a list or a grid because both are scrollable.

*ListView takes a widget and since it is scrollable it must require widgets of a defined height

so the work around here is to give it a widget of a specific height so if you give it a container of a specific height and add a grid view inside a container then this should do your job
List<MaterialColor> gridColors = [
  Colors.red,
  Colors.deepPurple,
  Colors.green,
  Colors.deepOrange,
  Colors.red,
  Colors.deepPurple,
  Colors.green,
  Colors.deepOrange,
  Colors.red,
  Colors.deepPurple,
  Colors.green,
  Colors.deepOrange
];

  static Widget body() {
    return ListView(
      children: <Widget>[
        Container(
          height: 400,
          color: Colors.green,
        ),
        Container(
          height: 400,
          color: Colors.deepOrangeAccent,
          child: GridView.builder(
              gridDelegate:
                  SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
              itemCount: 8,
              itemBuilder: (BuildContext context, int x) {
                return Container(
                  margin: EdgeInsets.all(10),
                  height: 100,
                  width: 100,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: gridColors[x],
                  ),
                );
              }),
        ),
        Container(
          height: 400,
          color: Colors.blue,
        ),
      ],
    );
  }

heres the output hope it helps someone

A: You need to wrap the GridView into an Expanded widget. More about that here.

A: 1. Identify Problem
new ListView(
  children: [
    new Image.asset(
      'images/slider/img_s1.jpg',
      width: 600.0,
      height: 180.0,
      fit: BoxFit.fill,
    ),
    homeIcon,
    grid // this is the problem
  ],
),

the problem is here. because the grid is defined as GridView Widget, Flutter cannot
renders it as children of ListView.
Widget grid = GridView.count(
      crossAxisCount: 4,
...

2. But I want the screen to be scrollable as well?
To do that, we need to replace SingleChildScrollView or similar widget, e.g ListView. We change it into CustomScrollView.
This is necessary because actually, Flutter recognizes two patterns :

*

*List View pattern
children will be added in the vertical direction

*Grid Box pattern
children will be added in the Z direction. If it has two-column, its 1st and 2nd children will be rendered on First Row. then its second-row rendered with 3rd and 4th.
Official Docs

3. How to write that section?
body: CustomScrollView( // replacement of SingleScrollChildView
  slivers: <Widget>[ // rather than children, it is named slivers
    // List Pattern section
    SliverList( // replacement of ListView
      delegate : // rather than children, it is named delegate
      ...
    ),
    // Grid Pattern section
    SliverGrid(
      delegate : // rather than children, it is named delegate
      ...
    ),

  ],
)

4. Final Code

*

*Changed ListView to SliverList to make a List Section

*Wrap it with CustomScrollView

*Put SliverGrid below SliverList, which is our Grid Section

*Render our grid variable, inside SliverGrid

body: new ListView( // replace this to SliverList
  children: [
    new Image.asset(
      'images/slider/img_s1.jpg',
      width: 600.0,
      height: 180.0,
      fit: BoxFit.fill,
    ),
    homeIcon,
    grid // needs to be moved into our Grid Section

  ],
),

body: CustomScrollView(
  slivers: <Widget>[
    // A. This is our List Section
    SliverList(
      delegate: SliverChildListDelegate([
        Image.asset(
          'images/slider/img_s1.jpg',
          width: 600.0,
          height: 180.0,
          fit: BoxFit.fill,
        ),
        homeIcon,
        // grid
      ]),
    ),
    // B. This is our Grid Section
    SliverGrid.count(
      children: <Widget>[grid],
      crossAxisCount: 1,
    ),
  ],
),

Demo

You may bundle it yourself by using this repo Github


text:
Q: Angular 4 testing: fakeAsync with Inject

I am trying to test service with private method which is called in constructor and contains observable:
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/interval';

@Injectable()
export class SomeService {

  private booleanValue: boolean = false;

  constructor() {
    this.obsMethod();
  }

  private obsMethod() {
    Observable.interval(5000).subscribe(() => {
      this.booleanValue = !this.booleanValue;
    });
  }

  public getBooleanValue() {
    return this.booleanValue;
  }
}

I prepared three specs. First with simple instance of service created with new operator. And it works. Second with TestBed.get() injection. And it works too.
When I use inject in beforeEach spec does not work. But why? Is it problem with fakeAsync and inject used at the same time? How can I use them both together?
I created working demo on plunker with service and three specs.
https://embed.plnkr.co/dw6tCGXH6LWlJuqNuQl8/

A: The problem with the third spec is that the interval observable is created outside of a fakeAsync() function, which means it uses the real setInterval() function, and thus all of the assertions in the test function run well before the 5 seconds, so the last assertion testing for the changed value fails.
One way I got this to work was to separate out the initialisation of the observable into a separate init() method, which can then be called from inside the fakeAsync() function in the test to allow tick() to work correctly.
The updated Plunkr is here.
The relevant code:
Service:
@Injectable()
export class SomeService {

  private booleanValue: boolean = false;

  constructor() {
  }

  public init() {
    this.obsMethod();
  }

  private obsMethod() {
    Observable.interval(5000).subscribe(() => {
        this.booleanValue = !this.booleanValue;
    });
  }

  public getBooleanValue() {
    return this.booleanValue;
  }
}

Final test:
describe('Some service specs with beforeEach Inject', () => {

  let serv: SomeService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        SomeService
      ]
    });
  });

  beforeEach(inject([SomeService], (ss) => {
    serv = ss;
  }));

  it('Third - not working spec', fakeAsync(() => {
    serv.init();
    expect(serv.getBooleanValue()).toBe(false);
    tick(5000 - 1);
    expect(serv.getBooleanValue()).toBe(false);
    tick(2);
    expect(serv.getBooleanValue()).toBe(true);
    discardPeriodicTasks();
  }));
});


text:
Q: Trying to navigate via HLS video in Flutter I'm trying to navigate via HLS video. Navigation includes clicking -15 seconds and +15 seconds buttons, clicking on a video progress bar and playing video again when it reaches 30 seconds timestamp. I use Flutter, video_player package with chewie package. HLS is not traditional. I receive a big HLS from video archive: it's a .m3u8 playlist with one .ts file inside it. If I try to paste the url with .m3u8 playlist to the browser it starts to load it and it takes nearly all day.
void makePlayChecker() {
    playerTimeChecker = Timer.periodic(Duration(seconds: 1), (timer) {
      if (videoPlayerController.value.position > videoMaxLength) {
        videoPlayerController.seekTo(Duration(seconds: 0));
      }
    });
  }

Upper method checks whether the video has reached 30 seconds timestamp, if so, I try to navigate it to its beginning, but unfortunately the video just resume playing without any navigation.
Future<void> initializePlayer() async {
    videoPlayerController = VideoPlayerController.network(
      generatedUrl,
      formatHint: VideoFormat.hls,
    );
    await Future.wait([
      videoPlayerController.initialize()
    ]);
    _createChewieController();
    await videoPlayerController.play();
    setState(() {});
  }

  void _createChewieController() {
    _chewieController = ChewieController(
      videoPlayerController: videoPlayerController,
      autoPlay: true,
      allowMuting: true,
      progressIndicatorDelay: Duration(seconds: 0),
      customControls: CustomCupertinoControls(
        backgroundColor: Colors.blue,
        iconColor: Colors.white,
      ),
      overlay: MixinWrapper(child: Text("UserMixin", style: TextStyle(color: Colors.red),)),
      allowPlaybackSpeedChanging: false,
      hideControlsTimer: Duration(minutes: 5),
    );
  }

Upper methods initialize video player and chewie controllers
How could I navigate via HLS video?


text:
Q: Advanced indexing - managing out of bounds behaviour I am trying to solve the issue of determining the out of bounds behaviour for indexing arrays. For the prior question see: How can I vectorize dynamically replacing array values with another (smaller) array?
If I have the following sample data:
array_large = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
array_small = [[1,2],[3,4],[5,6]]
array_index = [[1],[4],[5]] #*random index

Using this code
i = np.arange(array_large.shape[0])[:,None]
j = array_index+np.arange(array_small.shape[1])
array_large[i,j] = array_small

The behaviour for array_index[0] is clear, but if the index exceeds the target array an error is raised. I would like to ignore invalid indice, but index as much as possible of the smaller array into the larger one. How can I handle for these errors under the consideration that the desired output would be:
array_large = [[0,1,2,0,0],[0,0,0,0,3],[0,0,0,0,0]]

A: We can take advantage of the fact that array_large is constituted of 0s to define a mask, and set those indices beyond array_large.shape[1] to 0, as well as their corresponding value in array_small:
i = np.arange(array_large.shape[0])[:,None]
j = array_index+np.arange(array_small.shape[1])
m = j<array_large.shape[1]
array_large[i,j*m] = array_small*m

print(array_large)

array([[0, 1, 2, 0, 0],
       [0, 0, 0, 0, 3],
       [0, 0, 0, 0, 0]])


text:
Q: Spring Cloud Turbine - Unable to handle multiple clients? I'm having a bit of trouble getting Turbine to work in Spring Cloud.  In a nutshell, I can't determine how to configure it to aggregate circuits from more than one application at a time.
I have 6 separate services, a eureka server, and a turbine server running in standalone mode.  I can see from my Eureka server that all of the services are registered, including turbine.  My turbine server is up and running, and I can see its /hystrix page without issue.  But when I try to use it to examine turbine.stream, I only see the FIRST server that is listed in turbine.appConfig, the rest are ignored.
This is my Turbine server's application.yml, or at least the relevant parts:
---
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8010/eureka/
server:
  port: 8030
info:
  component: Turbine
turbine:
  clusterNameExpression: new String("default")
  appConfig: sentence,subject,verb,article,adjective,noun
management:
  port: 8990

When I run this and access the hystrix dashboard on my turbine instance, asking for the turbine.stream, the ONLY circuit breakers listed in the output are for the first service listed in appConfig, the "sentence" service in this case.  Curiously, if I re-arrange the order of these services and put another one first (like "noun"), I see only the circuits for THAT service.  Only the first service in the list is displayed.
I'll admit to being a little confused on some of the terminology, like streams, clusters, etc., so I could be missing some basic concept here, but my understanding is that Turbine could digest streams from more than one service and aggregate them in a single display.  Suggestions would be appreciated.

A: I don't have enough reputation to comment, so I have to write this in an answer :)
I had the exactly same problem:
There are two services "test-service" and "other-service", each with it's own working hystrix-stream
and there is one Turbine-Application, which is configured like this:
    turbine:
        clusterNameExpression: new String("default")
        appConfig: test-service,other-service

All of my services are running on my local machine.
Result is: My Hystrix-Dashboard just shows the metrics from "test-service".
Reason:
It seems to be, that a Turbine-Client which is configured the described way doesn't handle multiple services when they are running at the same host.
This is explained here:
https://github.com/Netflix/Hystrix/issues/117#issuecomment-14262713

Turbine maintains state of all these instances in order to maintain persistent connections to them and it does rely on the "hostname" and if the host name is the same then it won't instantiate a new connection to that same server (on a different port).

So the main point is, that all of your services must be registered with different hostnames. How you could do this on your local machine is described below.
 UPDATE 2015-06-12/2016-01-23: Workaround for local testing
Change your hostfile:
    # ...
    127.0.0.1 localhost
    127.0.0.1 localdomain1
    127.0.0.1 localdomain2
    # ...
    127.0.0.1 localdomainx

And then set the hostname for your clients each to a different domain-entry like this:
application.yml:
    eureka:
        instance:
            hostname: localdomainx


text:
Q: How to convert a ruby on rails app to a windows/Linux service? I need to convert the ruby on rails project that I start using bat files into a windows /Linux service

A: Windows Batch (.bat) files and Unix Shell Scripts are different.
But if you have a Ruby on Rails Service, then the languate is Ruby and Ruby is the same on every platform which supports Ruby.
So I assume that the Windows batch scripts that you mentioned are maybe only some supportive startup or management scripts.
Those you would need to rewrite on the Unix Platform.
On Unix there are several shells available but the defacto standard for writing shell scripts is the Bourne Shell (/bin/sh). More specific on Linux Systems this is the Bourne Shell which supports Bourne Shell Synthax and offers some useful extensions.
There are many primers out how to write Unix Shell scripts. I personally think that this is a very nice scripting language. And you can see already a lot of examples on your local Unix system, because shell scripts are being used in Unix in many ways. For example as startup script for services and applications.
More I can not tell you at this moment as your request was very generic, but I hope it helps you to get an idea what to do or to ask next.
When I started O'Reilly offered some very nice books, so maybe you could / should have a look at the O'Reily Bash Cookbook: http://shop.oreilly.com/product/0636920058304.do
Of course there are surely many other sources of information including the BASH documentation itself, here the link to the PDF of the Bash Reference Manual.
https://www.gnu.org/software/bash/manual/bash.pdf


text:
Q: Rails scoping elasticsearch using geocoded location I have an app that uses Geocoder to find Vendors within proximity of the User. I'm currently using ElasticSearch in another model, but I'd like to extend that to my Vendor model. The only thing is, I don't want users to search through all vendors, only those within x distance from them. Is something like this possible? I've looked through some of the elastic search documentation and haven't found anything yet. Here's my Vendor model and my devise User model:
class Vendor < ActiveRecord::Base

    geocoded_by :address
    after_validation :geocode,
        :if => lambda{ |obj| obj.address_changed? }
end

class User < ActiveRecord::Base

   devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

   validates :zip, presence: true

   geocoded_by :zip

   after_validation :geocode

end

Any thoughts on this? Open to any suggestions as I'm unsure of how to accomplish this. Thanks in advance!

A: I suppose that you would have indexed Vendor documents in your elasticsearch index. If not, then you need to do so along with storing the location co-ordinates.
From your question, I understand that you want to search all the vendors in the nearby location of the user. If that is the case, there is a geo location query that you can use in elasticsearch.
You can use one or any no. of coordinates (lat and long) along with x distance in your search query. Here are some of the useful links that might help you:
http://www.elasticsearch.org/blog/geo-location-and-search/
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-geo-distance-filter.html

A: Well, the elasticsearch API actually returns an ActiveModel record so you can use geocoder's near api by clubbing it -:
Model.search(params[:value]).near(params[:lat], params[:long], params[:dist])

This will return an Array of matching records


text:
Q: How to parse and convert ini file into bash array variables? I'm trying to convert an ini file into bash array variables. The sample ini is as below:
[foobar]
session=foo
path=/some/path

[barfoo]
session=bar
path=/some/path

so these become:
session[foobar]=foo
path[foobar]=/some/path
session[barfoo]=bar

and so on.
Right now, I could come up with only this command
awk -F'=' '{ if ($1 ~ /^\[/) section=$1; else if ($1 !~ /^$/) print $1 section "=" $2 }'

Also, another problem is, it doesn't take spaces near = into consideration. I think sed is probably better suited for this job but I don't know how to hold and store a temporary variable for the section name in sed.
So any idea how to do this?

A: If you want to eliminate the extra spaces, you can use the built-in function gsub. For example, you can add:
gsub(/ /, "", $1);

This will remove all spaces. If you want to remove spaces at the beginning or end of token, you can use
gsub(/^ /, "", $1);
gsub(/ $/, "", $1);

A: Here's a pure bash solution.
This is a new and improved version of what chilladx posted:
https://github.com/albfan/bash-ini-parser
For a really easy to follow initial example: After you download this, just copy the files bash-ini-parser, and scripts/file.ini to the same directory, then create a client test script using the example I've provided below to that same directory as well.
source ./bash-ini-parser
cfg_parser "./file.ini"
cfg_section_sec2
echo "var2=$var2"
echo "var5[*]=${var5[*]}"
echo "var5[1]=${var5[1]}"

Here are some further improvements I made to the bash-ini-parser script...
If you want to be able to read ini files with Windows line endings as well as Unix, add this line to the cfg_parser function immediately following the one which reads the file:
ini=$(echo "$ini"|tr -d '\r') # remove carriage returns

If you want to read files which have restrictive access permissions, add this optional function:
# Enable the cfg_parser to read "locked" files
function sudo_cfg_parser {

    # Get the file argument
    file=$1

    # If not "root", enable the "sudo" prefix
    sudoPrefix=
    if [[ $EUID -ne 0 ]]; then sudoPrefix=sudo; fi

    # Save the file permissions, then "unlock" the file
    saved_permissions=$($sudoPrefix stat -c %a $file)
    $sudoPrefix chmod 777 $file

    # Call the standard cfg_parser function
    cfg_parser $file

    # Restore the original permissions
    $sudoPrefix chmod $saved_permissions $file
}

A: Gawk accepts regular expressions as field delimiters. The following eliminates spaces around the equal sign, but preserves them in the rest of the line. Quotes are added around the value so those spaces, if any, are preserved when the Bash assignment is performed. I'm assuming that the section names will be numeric variables, but if you're using Bash 4, it would be easy to adapt this to use associative arrays with the section names themselves as the indices.
awk -F ' *= *' '{ if ($1 ~ /^\[/) section=$1; else if ($1 !~ /^$/) print $1 section "=" "\"" $2 "\"" }'

Note that you may want to also do the space removal that Khaled shows (on only $1 and section) since Bash variable names can't contain spaces.
Also, this method won't work if the values contain equal signs.
Another technique would be to use a Bash while read loop and perform the assignments as the file is read, using declare which is safe from most malicious content.
foobar=1
barfoo=2  # or you could increment an index variable each time a section is found
while IFS='= ' read var val
do
    if [[ $var == \[*] ]]
    then
        section=$var
    elif [[ $val ]]
    then
        declare "$var$section=$val"
    fi
done < filename

Again, associative arrays could fairly easily be supported.

A: I would use simple python script for this job since it has built in INI parser:
#!/usr/bin/env python

import sys, ConfigParser

config = ConfigParser.ConfigParser()
config.readfp(sys.stdin)

for sec in config.sections():
    print "declare -A %s" % (sec)
    for key, val in config.items(sec):
        print '%s[%s]="%s"' % (sec, key, val)

and then in bash:
#!/bin/bash

# load the in.ini INI file to current BASH - quoted to preserve line breaks
eval "$(cat in.ini  | ./ini2arr.py)"

# test it:
echo ${barfoo[session]}

Sure, there are shorter implementations in awk, but I think this is more readable and easier to maintain.

A: Always assuming to have Python's ConfigParser around, one may build a shell helper function like this:
get_network_value()
{
    cat <<EOF | python
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('network.ini')
print (config.get('$IFACE','$param'))
EOF
}

$IFACEand $param are the section respectively the parameter.
This helper then allows calls like:
address=`param=address get_network_value` || exit 1
netmask=`param=netmask get_network_value` || exit 1
gateway=`param=gateway get_network_value` || exit 1

Hope this helps!

A: If you have Git available and are OK with the constraint of not being able to use underscores in the key names, you can use git config as a general-purpose INI parser / editor.
It will handle parsing out the key/value pair from around the = and discard insignificant whitespace, plus you get comments (both ; and #) and type coercion basically for free. I have included a complete working example for the OP's input .ini and desired output (Bash associative arrays), below.
However, given a config file like this
; mytool.ini
[section1]
    inputdir = ~/some/dir
    enablesomefeature = true
    enablesomeotherfeature = yes
    greeting = Bonjour, Monde!

[section2]
    anothersetting = 42

…provided you just need a quick-and-dirty solution, and aren't married to the idea of having the settings in a Bash associative array, you could get away with as little as:
eval $(git config -f mytool.ini --list | tr . _)

# or if 'eval' skeeves you out excessively
source <(git config -f mytool.ini --list | tr . _)

which creates environment variables named sectionname_variablename in the current environment. This, of course, only works if you can trust that none of your values will ever contain a period or whitespace (see below for a more robust solution).
Other simple examples
Fetching arbitrary values, using a shell function to save typing:
function myini() { git config -f mytool.ini; }

An alias would be OK, here, too, but those are not normally expanded in a shell script [1], and anyway aliases are superseded by shell functions "for almost every purpose," [2], according to the Bash man page.
myini --list
# result:
# section1.inputdir=~/some/dir
# section1.enablesomefeature=true
# section1.enablesomeotherfeature=yes
# section2.anothersetting=42

myini --get section1.inputdir
# result:
# ~/some/dir

With the --type option, you can "canonicalize" specific settings as integers, booleans, or paths (automatically expanding ~):
myini --get --type=path section1.inputdir  # value '~/some/dir'
# result:
# /home/myuser/some/dir

myini --get --type=bool section1.enablesomeotherfeature  # value 'yes'
# result:
# true

Slightly more robust quick-and-dirty example
Make all variables in mytool.ini available as SECTIONNAME_VARIABLENAME in the current environment, preserving internal whitespace in key values:
source <(
    git config -f mytool.ini --list \
      | sed 's/\([^.]*\)\.\(.*\)=\(.*\)/\U\1_\2\E="\3"/'
)

What the sed expression is doing, in English, is

*

*finding a bunch of non-period characters up to a period, remembering that as \1, then

*finding a bunch of characters up to an equals sign, remembering that as \2, and

*finding all the characters after the equals sign as \3

*finally, in the replacement string

*

*the section name + variable name is upper-cased, and

*the value part is double-quoted, in case it contains characters that have special meaning to the shell if unquoted (like whitespace)

The \U and \E sequences in the replacement string (which upper-case that part of the replacement string) are GNU sed extension. On macOS and BSD, you'd just use multiple -e expressions to achieve the same effect.
Dealing with embedded quotes and whitespace in the section names (which git config allows) is left as an exercise for the reader. :)
Using section names as keys into a Bash associative array
Given:
; foo.ini
[foobar]
session=foo
path=/some/path

[barfoo]
session=bar
path=/some/path

This will produce the result the OP is asking for, simply by rearranging some of the captures in the sed replacement expression, and will work fine without GNU sed:
source <(
    git config -f foo.ini --list \
      | sed 's/\([^.]*\)\.\(.*\)=\(.*\)/declare -A \2["\1"]="\3"/'
)

I predict there could be some challenges with quoting for a real-world .ini file, but it works for the provided example. Result:
declare -p {session,path}
# result:
# declare -A session=([barfoo]="bar" [foobar]="foo" )
# declare -A path=([barfoo]="/some/path" [foobar]="/some/path" )

A: With a lot of help from the answers in this post, as well as other on this site and some foogle (not a typo), I have come up with the following "solution" quoted because of the caveat at the end. I would prefer a pure bash method but everything I have seen either does not seem to work with my bash version or is rather cumbersome.
This fits the final category but still is less cumbersome than other options.
filename: functions
getSetting() {
    cat /dev/stdin | awk -v section="$1" -v key="$2" '
        BEGIN {
        if (length(key) > 0) { params=2 }
        else if (length(section) > 0) { params=1 }
        else { params=0 }
        }
        match($0,/;/) { next }
        match($0,/#/) { next }
        match($0,/^\[(.+)\]$/){
        current=substr($0, RSTART+1, RLENGTH-2)
        found=current==section
        if (params==0) { print current }
        }
        match($0,/(.+)=(.+)/) {
        if (found) {
            if (params==2 && key==substr($1, 0, length(key))) { print substr($0, length(key)+2) }
            if (params==1) { printf "%s\n",$1,$3 }
        }
    }'
}

filename: options.ini
[default]
 opt1=some value that matters not here
 opt2=another such value

[section2]
 opt1=something different
 opt2=another something different

filename: options This is the file that calls the function. so functions needs to be sourced here.
#!/bin/bash
appPath="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"

# Need to source the functions file to be able to use the above function
source $appPath/functions

defaultOpt1=$(cat $appPath/options/file.ini | getSetting 'default' 'opt1')
defaultOpt2=$(cat $appPath/options/file.ini | getSetting 'default' 'opt2')

sec2opt1=$(cat $appPath/options/file.ini | getSetting 'section2' 'opt1')
sec2opt2=$(cat $appPath/options/file.ini | getSetting 'section2' 'opt2')

And finally to access you need to source options:
filename: someapplication
#!/bin/bash
app="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"

# don't need to source functions again, but do need to source "options" file
source $app/sources/options

echo "$opt1 \n$opt2 \n$sec2opt1 \n$sec2opt2"

I have looked at other options to "automatically" generate the variable by parsing the whole INI file but I am not sure there is anything really simple.
With this way, you can update the variables as you need to add them to your ini file. But, the caveat being it's not scalable in any meaningful way yet.


text:
Q: How to round to nearest fraction of another number? I want to add a special scaling mode where it snaps to the closest multiple.  Right now, scaling up is fine, it's linear and goes something like this:
 // f(x := 35, n := 32) = 32
 // f(x := 66, n := 32) = 64
 x = floor(x / n) * n

But for scaling down, I want some sort of inverse exponential:
 // f(x := 18, n := 32) = 16
 // f(x := 12, n := 32) = 8
 // f(x := 7, n := 32) = 4

An implementation suggestion without using a loop in any language would suffice.  My current implementation is as follows (which 100% works):
float ScaleMultiple(float value, float multiple) {
    if (value > multiple) {
        return(floor(value / multiple) * multiple);
    } else if (value < multiple) {
        do {
            multiple /= 2.0f;
        } while (value >= multiple);
        return(multiple);
    } else {
        return(value);
    }
}

multiple is a positive floating point number and not necessarily a multiple of 2 and is at least equal to 1.
value is a positive floating point number and is at least equal to 1.

A: 32 / 18 ~= 1.8 ~= 2, the result you want is 32 / 2, right? For the case of 12 and 32, this would yield 3 though, not four. In order to get there, take the log-2 of that number, round that to an even number and then convert back. However, this has the problem that it doesn't work properly when n is not a power of two.

A: You can get the correct results for the values you give in Java as follows:
int f = (int)Math.pow(2,(int)(Math.log(x)/Math.log(2)));

There's insufficient information provided to answer the question for arbitrary n.


text:
Q: Repeat "If" query consequently in jQuery I would like to repeat an "If" query permanently to retrieve a piece of information and perform an action accordingly.
This should be used to display content only when a user is logged in.
Currently the query happens once as soon as the page is loaded. The problem is that when a user logs in after the page is loaded, the content does not appear and the page has to be reloaded. This is my current code:
import wixUsers from 'wix-users';

$w.onReady( () => {
if (wixUsers.currentUser.loggedIn) {
$w('#html1').show();
$w('#button17').show();
$w('#box9').hide();
$w('#button29').show();

}
else {
$w('#html1').hide();
$w('#button17').show();
$w('#box9').show();
$w('#button29').hide();

}
});

How is it possible to always check this?
Probably the solution for this is relatively simple, but I don't know much about jQuery. I appreciate any support!

A: If you want code to run after successful log-in then try wixUsers.onLogin (this needs to run inside onReady function).
import wixUsers from 'wix-users';

wixUsers.onLogin((user) => {
  let userId = user.id;
  let isLoggedIn = user.loggedIn;
  let userRole = user.role;
} );

You should be able to integrate the code snippet into your code by adding the following:
import wixUsers from 'wix-users';

function toggleLoginState(isLoggedIn) {
    if (isLoggedIn) {
        $w('#html1').show();
        $w('#button17').show();
        $w('#box9').hide();
        $w('#button29').show();

    }
    else {
        $w('#html1').hide();
        $w('#button17').show();
        $w('#box9').show();
        $w('#button29').hide();

    }
}

$w.onReady(() => {
    toggleLoginState(wixUsers.currentUser.loggedIn); // Set default state once page has finished loadading.

    wixUsers.onLogin((user) => {
        toggleLoginState(user.loggedIn); // This should always be true.
    });
});

More details can be found in the documentation https://www.wix.com/velo/reference/wix-users/onlogin


text:
Q: Scaling contents in FMX TScrollBox A Scrollbox containing a series of TImageControls stacked vertically. When I scale the images and readjust the ImageControl positions, the Scrollbox.contents does not size properly. If I scale less than 1, there is extra space at the bottom; when it is more than 1, the last image is cut off. I've tried to call various routines (AdjustSizeValue, InvalidateContentSize, RecalcUpdateRect, RecalcSize etc) but these do nothing.
Here is a complete test project illustrating the problem:
unit Unit3;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
  FMX.TabControl, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Edit,
  FMX.EditBox, FMX.SpinBox, FMX.Layouts;

type
  Tform1 = class(TForm)
    Button1: TButton;
    SpinBox1: TSpinBox;
    ScrollBox: TScrollBox;
    Layout1: TLayout;
    Label1: TLabel;
    TrackBar1: TTrackBar;
    Label2: TLabel;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure TrackBar1Change(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    procedure ImageMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Single);

    { Private declarations }
  public
    { Public declarations }
  end;

var
  form1: Tform1;

implementation
{$R *.fmx}

const
  PH = 1000;
  PW = 750;

procedure Tform1.Button1Click(Sender: TObject);

Function MakeImage(const aOwner:TControl; aNumber:integer): TImageControl;
begin
  result := TImageControl.Create(aOwner);
  result.EnableOpenDialog := false;
  result.SetBounds(0,0,PW,PH);
  result.Parent := ScrollBox;
  result.bitmap.SetSize( round(PW), round(PH)   );
  with Result.Bitmap.Canvas do
    if BeginScene then
    try
      fill.Color := TAlphaColorRec.Black;
      fill.Kind := TBrushKind.Solid;
      Font.Family := 'Arial';
      Font.Size := 100;
      FillText( RectF(00,00,200,200),aNumber.ToString,false,1, [], TTextAlign.Center,TTextAlign.Leading );
    finally
      EndScene;
    end;
end;

var
  i: Integer; Image:TImageControl; vertical:single;
begin
  vertical := 0;
  for i := 1 to round(SpinBox1.Value) do
  begin
     Image := MakeImage(ScrollBox,i);
     Image.Position.Y := vertical;
     vertical := vertical + Image.Height;
     Image.OnMouseMove := ImageMouseMove;
  end;
end;

procedure Tform1.Button2Click(Sender: TObject);
begin
  Scrollbox.AdjustSizeValue;
  Scrollbox.InvalidateContentSize;
  Scrollbox.RecalcUpdateRect;
  Scrollbox.RecalcAbsoluteNow;
  Scrollbox.Content.RecalcSize;
  Scrollbox.Content.RecalcUpdateRect;
  Scrollbox.Content.RecalcAbsoluteNow;
end;

procedure Tform1.ImageMouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Single);
begin
 Label1.Text := 'X:' + FloatToStrF(X,TFloatFormat.ffFixed,4,2) + ' Y:' + FloatToStrF(Y,TFloatFormat.ffFixed,4,2);
end;

procedure Tform1.TrackBar1Change(Sender: TObject);
var
  i: Integer; vertical,ScaleValue:Single;
begin
  vertical := 0;
  ScaleValue := TrackBar1.Value;
  Label2.Text := 'Scale: '+round(ScaleValue*100).ToString +'%';
  for i := 0 to ScrollBox.Content.ControlsCount - 1 do
  if ScrollBox.Content.Controls[i] is TImageControl then
    with ScrollBox.Content.Controls[i] as TImageControl do
    begin
      Scale.Y := TrackBar1.Value;
      Scale.X := TrackBar1.Value;
      Position.y := Vertical;
      Vertical := vertical + (PH*ScaleValue);
    end;
end;

end.

and
object form1: Tform1
  Left = 0
  Top = 0
  Caption = 'Form3'
  ClientHeight = 480
  ClientWidth = 640
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  DesignerMasterStyle = 0
  object Layout1: TLayout
    Align = Left
    Size.Width = 249.000000000000000000
    Size.Height = 480.000000000000000000
    Size.PlatformDefault = False
    TabOrder = 1
    object Button1: TButton
      Position.X = 64.000000000000000000
      Position.Y = 56.000000000000000000
      TabOrder = 1
      Text = 'Start'
      OnClick = Button1Click
    end
    object SpinBox1: TSpinBox
      Touch.InteractiveGestures = [LongTap, DoubleTap]
      TabOrder = 3
      Cursor = crIBeam
      Max = 500.000000000000000000
      Value = 10.000000000000000000
      Position.X = 56.000000000000000000
      Position.Y = 104.000000000000000000
    end
    object Label1: TLabel
      Align = Bottom
      Position.Y = 192.000000000000000000
      Size.Width = 249.000000000000000000
      Size.Height = 288.000000000000000000
      Size.PlatformDefault = False
      TextSettings.HorzAlign = Center
      TabOrder = 4
    end
    object TrackBar1: TTrackBar
      CanParentFocus = True
      Max = 1.700000047683716000
      Min = 0.300000011920929000
      Orientation = Horizontal
      Position.X = 111.000000000000000000
      Position.Y = 152.000000000000000000
      TabOrder = 5
      Value = 1.000000000000000000
      OnChange = TrackBar1Change
    end
    object Label2: TLabel
      Position.X = 39.000000000000000000
      Position.Y = 152.000000000000000000
      Size.Width = 73.000000000000000000
      Size.Height = 17.000000000000000000
      Size.PlatformDefault = False
      TabOrder = 6
    end
    object Button2: TButton
      Position.X = 64.000000000000000000
      Position.Y = 208.000000000000000000
      TabOrder = 7
      Text = 'Adjust'
      OnClick = Button2Click
    end
  end
  object ScrollBox: TScrollBox
    Align = Client
    Size.Width = 391.000000000000000000
    Size.Height = 480.000000000000000000
    Size.PlatformDefault = False
    TabOrder = 2
    ShowSizeGrip = True
    Viewport.Width = 391.000000000000000000
    Viewport.Height = 480.000000000000000000
  end
end

Can anyone solve this?

A: I was able to reproduce the problem, and I did leave some comments on your question before, but deleted as I realized they were wrong.
The solution is rather simple (as they usually are) when the correct code is applied. So here it is:
procedure TForm5.TrackBar1Change(Sender: TObject);
//var
//  i: Integer; vertical,ScaleValue:Single;
begin
  ScrollBox.Scale.X := TrackBar1.Value;
  ScrollBox.Scale.Y := TrackBar1.Value;
  ScrollBox.RecalcSize; // This was missing

  Label2.Text := TrackBar1.Value.ToString(ffFixed, 3, 3);
end;


text:
Q: Fortran Algorithm Help - Getting wrong results I am currently working on a fortran matrix calculator.  I have the program compiling and it seems to work except i am not receiving the correct results.  When i select the addition feature my program accepts in two matrices and is to add them together.  My result seems to be coming out wrong.  Such as if i choose two matrices both of size 2x2 and list 1's as each entry i receive the addition result of 3,3,3.  I cant figure out where i went wrong in the algorithm. I have not checked the other algorithms yet as I am trying to fix one algorithm at a time.  Below is my code
  *START PROGRAM
  PROGRAM MAIN

  *DECLARATIONS
  INTEGER SELECTION, DONE, VALID, J, I, K, M, N
  INTEGER, DIMENSION(10,10):: SUM, A, B

  *INTITIALIZE
  M = 0
  N = 0
  J = 0
  I = 0
  K = 0
  DONE = 1
  VALID = 1

  *LOOP UNTIL USER CHOOSES TO QUIT

  DO WHILE(DONE .GT. 0)

  *DISPLAY MENU UNTIL VALID ENTRY IS ENTERED

  DO WHILE (VALID .GT. 0)
  *PRINT MENU
  PRINT *,'MATRIX CALCULATOR'
  PRINT *,'PLEASE MAKE A SELECTION'
  PRINT *,'1) MATRIX ADDITION'
  PRINT *,'2) MATRIX SUBTRACTION'
  PRINT *,'3) MATRIX MULTIPLICATION'
  PRINT *,'4) MATRIX TRANSPOSE'
  PRINT *,'5) QUIT PROGRAM'
  READ (*,*) SELECTION

  *VALID ENTRY CHECK
  IF (SELECTION .GT. 5 .OR. SELECTION .LT. 1) THEN
  PRINT *,'PLEASE ENTER A VALID SELECTION'
  ELSE
  VALID= -1
  END IF

  *END WHEN VALID ENTRY IS ENTERED
  END DO

  *QUIT?
  IF (SELECTION .EQ. 5) THEN
  DONE = -1
  ELSE
  *OTHERWISE CONTINUE
  *GET DIMENTIONS INPUT
  PRINT *,'PLEASE ENTER THE DIMENTIONS'
  PRINT *,'ENTER IN M:'
  READ (*,*) M
  PRINT *,'ENTER IN N:'
  READ (*,*) N
  *GET IN MATRIX
  PRINT *, 'PLEASE ENTER IN MATRIX A'
  DO J=1, M
  DO I=1, N
  PRINT *, 'ENTER IN VALUE I, I', J, I
  READ(*,*) A(M,N)
  END DO
  END DO

  PRINT *, 'PLEASE ENTER IN MATRIX B'
  DO J=1, M
  DO I=1, N
  PRINT *, 'ENTER IN VALUE I, I', J,I
  READ(*,*) B(M,N)
  END DO
  END DO

  *PERFORM DESIRED CALCULATION
  SELECT CASE(SELECTION)
  *CASE 1
  CASE (1)
   PRINT *,'MATRIX ADDITION'
   DO J=1,M
   DO I=1,N
   SUM(J,I)=A(J,I)+B(J,I)
   END DO
   END DO

  *PRINT ADDITION RESULT
   PRINT *,'ADDITION RESULT'
   DO J=1, M
   DO I=1, N
   WRITE (*,*) SUM(J,I)
   END DO
   END DO
  *CASE 2
  CASE (2)
   PRINT *,'MATRIX SUBTRACTION'
   DO J=1,M
   DO I=1,N
   SUM(J,I)=A(J,I)-B(J,I)
   END DO
   END DO

  *PRINT SUBTRACTION RESULT
   PRINT *,'SUBTRACTION RESULT'
   DO J=1, M
   DO I=1, N
   WRITE (*,*) SUM(J,I)
   END DO
   END DO
  *CASE 3
  CASE (3)
   PRINT *,'MATRIX MULTIPLICATION'
   DO J=1, M
   DO I=1, N
   DO K=1, N
   SUM(J,I) = SUM(J,I)+A(J,K)*B(I,J)
   END DO
   END DO
   END DO

  *PRINT MULTIPLICATION RESULT
   DO J=1, M
   DO I=1, N
   WRITE (*,*) SUM(J,I)
   END DO
   END DO
  *CASE 4
  CASE (4)
   PRINT *,'MATRIX TRANSPOSE'
   DO J=1, M
   DO I=1, N
   B(I,J) = A(J,I)
   END DO
   END DO
  *PRINT TRANSPOSE RESULT
   PRINT *, 'MATRIX A RESULT'
   DO J=1, M
   DO I=1, N
   WRITE (*,*) A(J,I)
   END DO
   END DO
   PRINT *, 'MATRIX B RESULT'
   DO J=1, M
   DO I=1, N
   WRITE (*,*) B(J,I)
   END DO
   END DO
  CASE DEFAULT
   PRINT *,'SOMETHING HAS GONE WRONG'
  END SELECT

  *USER SELECTED TO QUIT
  END IF
  END DO
  PRINT *, 'PROGRAM HAS ENDED'
  *END PROGRAM
  STOP
  END

A: One way you to avoid some of the errors you made would be to use Fortran's array functions.  You could, for example, sum arrays A and B, if they have the same size, with the single statement:
C = A + B

You could also use the intrinsic procedures matmul and transpose for matrix multiplication and transposition respectively.

A: The main problem is that when reading the matrices, you are reading them to the wrong indices. instead of READ(*,*) A(M,N) and READ(*,*) B(M,N), you should have READ(*,*) A(J,I) and READ(*,*) B(J,I)
In addition to this, you need to have allocatable arrays instead of declaring sum, A and B as dimension(1,1). I also think naming an array SUM is bad practice as it is the same name as a Fortran intrinsic function, so I've called it C here. Declare them like this:
integer, allocatable, dimension(:,:) :: A, B, C

then after you read the dimensions from the user, do this:
allocate(A(m, n))

With these changes, I get (2,2;2,2) when adding (1,1;1,1) to (1,1;1,1).
In general, I would also suggest indenting your loops properly and not using all caps, it makes the code a lot harder to read.

A: This is the problem:
  *PRINT ADDITION RESULT
   PRINT *,'ADDITION RESULT'
   DO J=1, M
   DO I=1, N
   WRITE (*,*) SUM(N,M)
   END DO
   END DO

You should have WRITE (*,*) SUM(J,I).

A: You declare SUM, A, and B to be 1x1 arrays, and then in the program you reference them outside of their declared bounds. Anything may happen.

A: Some of the mistakes noted in the other answers (e.g., out-of-bounds subscripting) can be automatically caught be compilers if you select the appropriate run time tests.   Selecting extensive warning and error checking options of the compiler will help you find mistakes quicker.   Which compiler are you using?


text:
Q: Change slideRight to SlideDown in JQuery.mmenu I have a menu with jquery.mmenu plugin but I need change the effect from slideRight to slideDown in order to make it into a dropdown.
How can I make this change?

A: Go to this page - http://mmenu.frebsite.nl/playground.html. In extensions, under change the position of the menu, change the selection and you can copy the code from the bottom of that page.
Here is the relevant section
$("#menu").mmenu({
    "offCanvas": {
        "position": "top"
    }
});


text:
Q: Logarithm of a matrix with zero diagonal elements. I want to calculate the natural logarithm of this matrix$$A=\begin{bmatrix}0&0&0&0\\0&\frac{1}{2}&\frac{i}{2}&0\\0&-\frac{i}{2}&\frac{1}{2}&0\\0&0&0&0\end{bmatrix}$$
After calculating the eigenvalues and eigenvectors I find: $\lambda_1=1,\lambda_2=0,\lambda_3=0,\lambda_4=0$. These values are the diagonal elements in  D of $A=M D M^{-1}$. Here $M$ is the modal matrix and $D$ the diagonal matrix looking like:$$D=diag(\lambda_1,\lambda_2,\lambda_3,\lambda_4)$$
Now taking the natural logarithm of the matrix would require me to take the natural logarithm of the elements of $D$. So what is my result? I should just say that three of the elements are undefined or that the logarithm of this matrix doesn't exists/diverges? Is there some pre requirement for A that I did not take into account?

A: The same way $\log(0)$ doesn't exist means you can't find $x$ such that $e^x=0$, the matrix exponential also refuses to output singular matrices.
So finding a zero eigenvalue means $e^B=A$ has no solution.

A: There is no answer in real or complex matrices.
However you can get answer depending on what extension of complex numbers you allow.
On the projective complex numbers the answer is
$$\left(
\begin{array}{cccc}
 \infty  & 0 & 0 & 0 \\
 0 &\infty  &  \infty  & 0 \\
 0 &  \infty  & \infty  & 0 \\
 0 & 0 & 0 & \infty  \\
\end{array}
\right)$$
On oriented projective complex numbers the answer is
$$\left(
\begin{array}{cccc}
 -\infty  & 0 & 0 & 0 \\
 0 & -\infty  & i \infty  & 0 \\
 0 & -i \infty  & -\infty  & 0 \\
 0 & 0 & 0 & -\infty  \\
\end{array}
\right)$$
In terms of divergent integrals, the answer is
$$\left(
\begin{array}{cccc}
 -\int_0^1 \frac{dx}x  & 0 & 0 & 0 \\
 0 & -\int_0^1 \frac{dx}x  & i \int_0^1 \frac{dx}x & 0 \\
 0 & -i \int_0^1 \frac{dx}x  & -\int_0^1 \frac{dx}x  & 0 \\
 0 & 0 & 0 & -\int_0^1 \frac{dx}x  \\
\end{array}
\right)$$


text:
Q: Issue with nesting JPanels I am trying to create nest JPanels here is a verbal diagram from outer to inner containers.
inputScreen which has a borderlayout
-> inside the CENTER of inputScreen there is another borderlayout called
centerBorderLayout
---> inside the centerBorderLayout there are 2 vertical BoxLayouts named
accordingly one on the WEST and one on the EAST we can call those
BoxVL and BoxVR
for some reason only all the containers seem to work except for BoxVR. I mimiced the exact same process I did for BoxVL so I am unsure why Java is throwing errors at me when I try to display it.
CODE:
public void initInputScreen(){      // create text feilds for desired number of ingredients
    JPanel inputScreen = new JPanel();      //main JPanel
    JPanel centerBorderLayout = new JPanel();   // center border layout panel
    JPanel leftVertBoxLayout = new JPanel();   // center left colulmn panel
    JPanel rightVertBoxLayout = new JPanel();  // center right column panel

    BorderLayout border = new BorderLayout();       // creates border layout
    BoxLayout BoxVL = new BoxLayout(leftVertBoxLayout,BoxLayout.Y_AXIS);    //creates left vertical box layout
    BoxLayout BoxVR = new BoxLayout(rightVertBoxLayout,BoxLayout.Y_AXIS);   // creates right vertical box layout

    inputScreen.setLayout(border);                  //set inputSceen layout
    centerBorderLayout.setLayout(border);           //set center panel layout to border
    leftVertBoxLayout.setLayout(BoxVL);             // set center left panel layout to BoxVL
    rightVertBoxLayout.setLayout(BoxVR);            // set center right panel layout to BoxVR

    JLabel ingredientLabel = new JLabel();
    ingredientLabel.setText("ingredients");
    leftVertBoxLayout.add(ingredientLabel);

    JLabel quantLabel = new JLabel();
    quantLabel.setText("quantity");
    rightVertBoxLayout.add(quantLabel);

    JLabel header = new JLabel();
    header.setText("HEADER");
    header.setFont(new Font("Serif", Font.BOLD, 20));
    inputScreen.add(header, border.NORTH);

    for (int x=0; x<ingredNum; x++){
        JTextField ingredTemp = new JTextField();
        JTextField quantTemp = new JTextField();
        leftVertBoxLayout.add(ingredTemp);
        rightVertBoxLayout.add(quantTemp);
    }
    inputScreen.add(centerBorderLayout, border.CENTER);             //add center panel to inputScreen
    centerBorderLayout.add(leftVertBoxLayout, border.WEST);         // add box layout panels to centerPanel
    centerBorderLayout.add(rightVertBoxLayout, border.EAST);
    this.add(inputScreen);
    inputScreen.setVisible(true);
    pack();
    revalidate();
}

NOTE: there should be another column of JTextFields to the right with a label displaying "Quantity" (all the contents of BoxVR)

A: I found the issue. I needed to create a separate BorderLayout for centerBorderLayout. I was referencing a layout being used in inputScreen.
Solution:
create another BorderLayout and dedicate it to centerBorderLayout.


text:
Q: JavaScript Linking drop down menu to checkboxes I am trying to link my HTML drop down menu to my table which has checkboxes in it.
This javascript function is trying to see if the "arc" value has been selected then disable the checkbox 3 which shows spectral:
function showShields()
{
if (document.getElementById("Shield").value == ("arc")
{
document.getElementById("checkBox3").disabled=true;
}
}

This is the HTML code:
<!DOCTYPE html>

What kind of shield are you interested in?

<select id="Shield">
   <option value="arc">ARC</option>
   <option value="divine">GAS</option>
   <option value="spectral">MIG</option>
   <option value="elysian">ANY</option>
</select>

   Checkbox
   Shield

   <input type="checkbox" id="checkBox1"
   ARC1

   <input type="checkbox" id="checkBox2"
   ARC2

   <input type="checkbox" id="checkBox3"
   SPECTRAL1

   <input type="checkbox" id="checkBox4"
SPECTRAL2

Could someone help me solve this?
Thank you

A: Your code is fine, although I did notice a missing parenthesis in the if condition:
function showShields()
{
if (document.getElementById("Shield").value == ("arc")) //your missing missing parenthesis was here
{
document.getElementById("checkBox3").disabled=true;
}
}

A: Try this: http://jsfiddle.net/Hpcsq/2/
function showShields(what)
    {
    if (what.value == ("arc"))
        {
        document.getElementById("checkBox3").checked=false;
        }
    }

<!DOCTYPE html>

<!DOCTYPE html>

What kind of shield are you interested in?

<select id="Shield" onchange="showShields(this)">
       <option value="arc">---</option>
   <option value="arc">ARC</option>
   <option value="divine">GAS</option>
   <option value="spectral">MIG</option>
   <option value="elysian">ANY</option>
</select>

   Checkbox
   Shield

   <input type="checkbox" id="checkBox1"
   ARC1

   <input type="checkbox" id="checkBox2"
   ARC2

   <input type="checkbox" id="checkBox3" checked="checked">
   SPECTRAL1

   <input type="checkbox" id="checkBox4"
SPECTRAL2


text:
Q: Parsing Network Device Inventory in XML Format with Python I'm new to Python-trying to parse an xml file which contains switch and router inventory.
I have tried this by importing ET and using the below code to just get the first one or two lines of inventory in the xml file:
(I've read the other solutions for parsing xml files on this sites and have tried some of them, even with BeautifulSoup, but have had no luck with how my xml file is structured.).
I can identify the root and child of the root with Python, however, what I'm having trouble with is drilling down and calling the actual data contained under "table_data". Below is a snippet of the xml file, there are about 20 more devices in the file.
In the for loop I've tried 'field name', I have also tried 'field' and 'name' with no results.
Of course, calling other tags within the 'for loop' does not work at this point.
I'd appreciate it if you would point me in the right direction.
import xml.etree.ElementTree as ET
tree = ET.parse('ios_inventory.xml')
root = tree.getroot()

for f in root.findall('field'):
    att=f.attrib
    n=att.get('name')

Contents of 'ios_inventory.xml'
  <?xml version="1.0"?>
<mysqldump xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<database name="IOS_INVENTORY">
    <table_structure name="Cisco_IOS_Inventory">
        <field Field="Hostname" Type="varchar(100)" Null="YES" Key="" Extra="" Comment="" />
        <field Field="Local_IPs" Type="varchar(5000)" Null="YES" Key="" Extra="" Comment="" />
        <field Field="Local_SVI_IPs" Type="varchar(5000)" Null="YES" Key="" Extra="" Comment="" />
        <field Field="IOS_Image" Type="varchar(200)" Null="YES" Key="" Extra="" Comment="" />
        <field Field="IOSVersion" Type="varchar(200)" Null="YES" Key="" Extra="" Comment="" />
        <field Field="Flash" Type="varchar(200)" Null="YES" Key="" Extra="" Comment="" />
        <field Field="SerialNo" Type="varchar(2000)" Null="YES" Key="" Extra="" Comment="" />
        <options Name="Cisco_IOS_Inventory" Engine="InnoDB" Version="10" Row_format="Compact"
        Rows="37" Avg_row_length="442" Data_length="16384" Max_data_length="0" Index_length="0"
        Data_free="5242880" Create_time="2017-05-31 04:23:01" Collation="latin1_swedish_ci"
        Create_options="" Comment="" />`
    </table_structure>
    <table_data name="Cisco_IOS_Inventory">
    <row>
        <field name="Hostname">SW2
</field>
        <field name="Local_IPs"></field>
        <field name="Local_SVI_IPs">10.100.x.x</field>
        <field name="IOS_Image">CAT3K_CAA-UNIVERSALK9-M</field>
        <field name="IOSVersion">03.06.10E RELEASE SOFTWARE (fc2)</field>
        <field name="Flash">1621966848 bytes total</field>
        <field name="SerialNo">xxxxxxxxxxxxx</field>
    </row>
    <row>
        <field name="Hostname">SW3
</field>
        <field name="Local_IPs"></field>
        <field name="Local_SVI_IPs">10.100.x.x</field>
        <field name="IOS_Image">CAT3K_CAA-UNIVERSALK9-M</field>
        <field name="IOSVersion">03.06.10E RELEASE SOFTWARE (fc2)</field>
        <field name="Flash">1621966848 bytes total</field>
        <field name="SerialNo">xxxxxxxxxxxxx</field>
    </row>
    <row>
        <field name="Hostname">RTR_2</field>
        <field name="Local_IPs">10.100.x.x | 10.253.x.x</field>
        <field name="Local_SVI_IPs"></field>
        <field name="IOS_Image">X86_64_LINUX_IOSD-UNIVERSALK9-M</field>
        <field name="IOSVersion">16.4.2, RELEASE SOFTWARE (fc1)</field>
        <field name="Flash">6741659648 bytes total</field>
        <field name="SerialNo">XXXXXXXXX</field>
    </row>

Thanks Jack. I've pasted the short xml sampl at the bottom. Want to get the output shown as below- with the corresponding values.
Please note: the Local_SVI_IPs can have multiple IP addresses in the xml file.
hostname:
Local_SVI_IPs:
IOS_Image:
IOSVersion:
Flash:
SerialNo:

        <field name="Hostname">SW2</field>
        <field name="Local_IPs"></field>
        <field name="Local_SVI_IPs">10.100.x.x</field>
        <field name="IOS_Image">CAT3K_CAA-UNIVERSALK9-M</field>
        <field name="IOSVersion">03.06.10E RELEASE SOFTWARE (fc2)</field>
        <field name="Flash">1621966848 bytes total</field>
        <field name="SerialNo">xxxxxxxxxxxxx</field>
    </row>

A: Try this on your actual xml; but with the one you supplied (note that the xml in the question is still not well formed):
from lxml import etree
hosts = """[your xml above, fixed]"""
doc = etree.XML(hosts)
rows  = doc.xpath('//row')
for row in rows:
        print('hostname: ',row.xpath('field[@name="Hostname"]/text()')[0].strip())
        if len(row.xpath('field[@name="Local_SVI_IPs"]/text()'))>0:
            print('Local_SVI_IPs: ',row.xpath('field[@name="Local_SVI_IPs"]/text()')[0].strip())
        else:
            print('Local_SVI_IPs: NA')
        print('IOS_Image: ',row.xpath('field[@name="IOS_Image"]/text()')[0].strip())
        print('IOSVersion: ',row.xpath('field[@name="IOSVersion"]/text()')[0].strip())
        print('Flash: ',row.xpath('field[@name="Flash"]/text()')[0].strip())
        print('SerialNo: ',row.xpath('field[@name="SerialNo"]/text()')[0].strip())
        print('-------')

Output:
hostname:  SW2
Local_SVI_IPs:  10.100.x.x
IOS_Image:  CAT3K_CAA-UNIVERSALK9-M
IOSVersion:  03.06.10E RELEASE SOFTWARE (fc2)
Flash:  1621966848 bytes total
SerialNo:  xxxxxxxxxxxxx
-------
hostname:  SW3
Local_SVI_IPs:  10.100.x.x
IOS_Image:  CAT3K_CAA-UNIVERSALK9-M
IOSVersion:  03.06.10E RELEASE SOFTWARE (fc2)
Flash:  1621966848 bytes total
SerialNo:  xxxxxxxxxxxxx
-------
hostname:  RTR_2
Local_SVI_IPs: NA
IOS_Image:  X86_64_LINUX_IOSD-UNIVERSALK9-M
IOSVersion:  16.4.2, RELEASE SOFTWARE (fc1)
Flash:  6741659648 bytes total
SerialNo:  XXXXXXXXX


text:
Q: Error when using selectRaw() Laravel method with parameter binding I'm trying to run this: $query->selectRaw('count(?)', [$column]) on Laravel 7.0, but gives me an error:
SQLSTATE[42P18]: Indeterminate datatype: 7 ERROR:  could not determine data type of parameter $1.
PS: $column is a string.
When I put count(distinct ?), it results in wrong count.
I already tried "{$column}" and '%'.$column.'%', but it didn't work.

A: I tried other ways for hours, until I ask in a community and someone answered me that it's not possible to do this. The binding will only works with column values or something like that, despite that it doesn't have detailed uses of the selectRaw method.
Well, I've lost many hours, so I gave up and went to my objective with another approach.

A: You can use param in selectRaw by using quotes
Example:
$column = 1;
$query->selectRaw('count(**$column**)');


text:
Q: Get device labels onpageshow I'm coding a web app, where user can use his camera (and choose which one to use). The problem is that I want user to be available to choose the camera before it is enabled. In the current code, when user turns on a page, he sees an empty list of cameras and when he enables the camera stream, dropdown list populates with camera names. I want the dropdown list populate when he turns on that web page.
P.S. when I stop() the camera, it disables camera and gives just a black screen. Why it is black instead of background colour?
CameraStreamView.cshtml
@using Api.Models
@{
    ViewBag.Title = "Smart Vision";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="~/Content/Contact-Form-Clean.css">
</head>

<body onpageshow="Init()">
<div id="container">
    <video id="video" style="display: block; margin: 0 auto; margin-top: 30px;" width="300" height="400" autoplay></video>
    <button id="enableStream" style="display: block; margin: 0 auto; margin-top: 20px; height: 70px; width: 200px" onclick="start()">Enable camera</button>
    <button id="disableStream" style="display: block; margin: 0 auto; margin-top: 20px; height: 70px; width: 200px" onclick="stop()">Disable camera</button>
    <label for="videoSource">Video source: </label><select id="videoSource"></select>
</div>

<script src="~/Scripts/GetCameraFeed.js"></script>
</body>
</html>

GetCameraFeed.js
const videoSelect = document.querySelector('select#videoSource');
const selectors = [videoSelect];

function gotDevices(deviceInfos) {
    // Handles being called several times to update labels. Preserve values.
    const values = selectors.map(select => select.value);
    selectors.forEach(select => {
        while (select.firstChild) {
            select.removeChild(select.firstChild);
        }
    });
    for (let i = 0; i !== deviceInfos.length; ++i) {
        const deviceInfo = deviceInfos[i];
        const option = document.createElement('option');
        option.value = deviceInfo.deviceId;
        if (deviceInfo.kind === 'videoinput') {
            option.text = deviceInfo.label;
            videoSelect.appendChild(option);
        }
    }
    selectors.forEach((select, selectorIndex) => {
        if (Array.prototype.slice.call(select.childNodes).some(n => n.value === values[selectorIndex])) {
            select.value = values[selectorIndex];
        }
    });
}

function Init() {
    navigator.mediaDevices.enumerateDevices().then(gotDevices).catch(handleError);
}

function gotStream(stream) {
    window.stream = stream; // make stream available to console
    video.srcObject = stream;
    // Refresh button list in case labels have become available
    return navigator.mediaDevices.enumerateDevices();
}

function handleError(error) {
    console.log('navigator.getUserMedia error: ', error);
}

function start() {
    const videoSource = videoSelect.value;
    const constraints = {
        video: { deviceId: videoSource ? { exact: videoSource } : undefined }
    };
    navigator.mediaDevices.getUserMedia(constraints).then(gotStream).then(gotDevices).catch(handleError);
}

function stop() {
    video.pause();
    video.src = "";
    stream.getTracks().forEach(track => track.stop());
    console.log("Stopping stream");
}

A: What you want is explicitly disallowed, due to fingerprinting concerns. Details about a user's setup let web sites identify them uniquely on the web, a privacy concern.
Once users trust your site with their camera and microphone, this information is considered relevant to share.
The working group determined this to be a reasonable trade-off, for several reasons:

*

*Most desktop users have only one camera or none.

*Most phone users have two, but you can use the facingMode constraint to pick.

*Given 1 and 2, an up-front choice is arguably an inferior user experience for most.

I would consider changing your code to ask for the default camera the first time, and give users a choice to change it after the fact, should they need to. It's what most WebRTC sites do.
Note that this should only be a problem the first time a user visits your site. Provided they've granted camera or microphone just once in the past, you should be able to see the labels, at least in Chrome.
Unlike Chrome, Firefox does not persist permission implicitly, so you'd need a little more work to get labels on page-load on repeat visits:
enumerateDevices returns a deviceId for each device, which is persisted for your site provided the user has granted (or will grant within this session) camera or microphone at least once. You can use cookies or local storage to correlate deviceIds to device labels. This also survives people manually revoking permission in Chrome.


text:
Q: SQL Statement - CPU Usage - hard parsing I was going through ADDM Reports in Oracle instance of my Project, and I found a SQL Statement appearing in ADDM snapshot consistently, below is one of the recommendations from report by Oracle:
Rationale
       The SQL spent only 0% of its database time on CPU, I/O and Cluster
       waits. Therefore, the SQL Tuning Advisor is not applicable in this case.
       Look at performance data for the SQL to find potential improvements.
   Rationale
      Database time for this SQL was divided as follows: 8% for SQL execution,
      92% for parsing, 0% for PL/SQL execution and 0% for Java execution.
   Rationale
      SQL statement with SQL_ID "aq58n0q3st7xq" was executed 4 times and had
      an average elapsed time of 4.5 seconds.
   Rationale
      At least 7 distinct execution plans were utilized for this SQL statement
      during the analysis period.
   Rationale
      Waiting for event "cursor: pin S wait on X" in wait class "Concurrency"
      accounted for 44% of the database time spent in processing the SQL
      statement with SQL_ID "aq58n0q3st7xq".

SQL statement is
   SELECT /*+ opt_param('_optimizer_use_feedback','false') */ DISTINCT
            col_1, col_2 FROM table_name WHERE :B1 = 0
            OR (col_3 BETWEEN 0 AND :B1 )

We also had a CPU bottleneck in the same hour, and first recommendation in report was to tune Top SQL Statements.
Being in a consulting project, I talked to my Manager about this. Their inputs were that since it is executing just for 4.5 secs and only 4 times so it is not a problem.
This makes me wonder whether this is actually a problem or not. If yes, then what would be the solution ?


text:
Q: Using Java with Nvidia GPUs (CUDA) I'm working on a business project that is done in Java, and it needs huge computation power to compute business markets. Simple math, but with huge amount of data.
We ordered some CUDA GPUs to try it with and since Java is not supported by CUDA, I'm wondering where to start. Should I build a JNI interface? Should I use JCUDA or are there other ways?
I don't have experience in this field and I would like if someone could direct me to something so I can start researching and learning.

A: First of all, you should be aware of the fact that CUDA will not automagically make computations faster. On the one hand, because GPU programming is an art, and it can be very, very challenging to get it right. On the other hand, because GPUs are well-suited only for certain kinds of computations.
This may sound confusing, because you can basically compute anything on the GPU. The key point is, of course, whether you will achieve a good speedup or not. The most important classification here is whether a problem is task parallel or data parallel. The first one refers, roughly speaking, to problems where several threads are working on their own tasks, more or less independently. The second one refers to problems where many threads are all doing the same - but on different parts of the data.
The latter is the kind of problem that GPUs are good at: They have many cores, and all the cores do the same, but operate on different parts of the input data.
You mentioned that you have "simple math but with huge amount of data". Although this may sound like a perfectly data-parallel problem and thus like it was well-suited for a GPU, there is another aspect to consider: GPUs are ridiculously fast in terms of theoretical computational power (FLOPS, Floating Point Operations Per Second). But they are often throttled down by the memory bandwidth.
This leads to another classification of problems. Namely whether problems are memory bound or compute bound.
The first one refers to problems where the number of instructions that are done for each data element is low. For example, consider a parallel vector addition: You'll have to read two data elements, then perform a single addition, and then write the sum into the result vector. You will not see a speedup when doing this on the GPU, because the single addition does not compensate for the efforts of reading/writing the memory.
The second term, "compute bound", refers to problems where the number of instructions is high compared to the number of memory reads/writes. For example, consider a matrix multiplication: The number of instructions will be O(n^3) when n is the size of the matrix. In this case, one can expect that the GPU will outperform a CPU at a certain matrix size. Another example could be when many complex trigonometric computations (sine/cosine etc) are performed on "few" data elements.
As a rule of thumb: You can assume that reading/writing one data element from the "main" GPU memory has a latency of about 500 instructions....
Therefore, another key point for the performance of GPUs is data locality: If you have to read or write data (and in most cases, you will have to ;-)), then you should make sure that the data is kept as close as possible to the GPU cores. GPUs thus have certain memory areas (referred to as "local memory" or "shared memory") that usually is only a few KB in size, but particularly efficient for data that is about to be involved in a computation.
So to emphasize this again: GPU programming is an art, that is only remotely related to parallel programming on the CPU. Things like Threads in Java, with all the concurrency infrastructure like ThreadPoolExecutors, ForkJoinPools etc. might give the impression that you just have to split your work somehow and distribute it among several processors. On the GPU, you may encounter challenges on a much lower level: Occupancy, register pressure, shared memory pressure, memory coalescing ... just to name a few.
However, when you have a data-parallel, compute-bound problem to solve, the GPU is the way to go.

A general remark: Your specifically asked for CUDA. But I'd strongly recommend you to also have a look at OpenCL. It has several advantages. First of all, it's an vendor-independent, open industry standard, and there are implementations of OpenCL by AMD, Apple, Intel and NVIDIA. Additionally, there is a much broader support for OpenCL in the Java world. The only case where I'd rather settle for CUDA is when you want to use the CUDA runtime libraries, like CUFFT for FFT or CUBLAS for BLAS (Matrix/Vector operations). Although there are approaches for providing similar libraries for OpenCL, they can not directly be used from Java side, unless you create your own JNI bindings for these libraries.

You might also find it interesting to hear that in October 2012, the OpenJDK HotSpot group started the project "Sumatra": http://openjdk.java.net/projects/sumatra/ . The goal of this project is to provide GPU support directly in the JVM, with support from the JIT. The current status and first results can be seen in their mailing list at http://mail.openjdk.java.net/mailman/listinfo/sumatra-dev

However, a while ago, I collected some resources related to "Java on the GPU" in general. I'll summarize these again here, in no particular order.
(Disclaimer: I'm the author of http://jcuda.org/ and http://jocl.org/ )
(Byte)code translation and OpenCL code generation:
https://github.com/aparapi/aparapi : An open-source library that is created and actively maintained by AMD. In a special "Kernel" class, one can override a specific method which should be executed in parallel. The byte code of this method is loaded at runtime using an own bytecode reader. The code is translated into OpenCL code, which is then compiled using the OpenCL compiler. The result can then be executed on the OpenCL device, which may be a GPU or a CPU. If the compilation into OpenCL is not possible (or no OpenCL is available), the code will still be executed in parallel, using a Thread Pool.
https://github.com/pcpratts/rootbeer1 : An open-source library for converting parts of Java into CUDA programs. It offers dedicated interfaces that may be implemented to indicate that a certain class should be executed on the GPU. In contrast to Aparapi, it tries to automatically serialize the "relevant" data (that is, the complete relevant part of the object graph!) into a representation that is suitable for the GPU.
https://code.google.com/archive/p/java-gpu/ : A library for translating annotated Java code (with some limitations) into CUDA code, which is then compiled into a library that executes the code on the GPU. The Library was developed in the context of a PhD thesis, which contains profound background information about the translation process.
https://github.com/ochafik/ScalaCL : Scala bindings for OpenCL. Allows special Scala collections to be processed in parallel with OpenCL. The functions that are called on the elements of the collections can be usual Scala functions (with some limitations) which are then translated into OpenCL kernels.
Language extensions
http://www.ateji.com/px/index.html : A language extension for Java that allows parallel constructs (e.g. parallel for loops, OpenMP style) which are then executed on the GPU with OpenCL. Unfortunately, this very promising project is no longer maintained.
http://www.habanero.rice.edu/Publications.html (JCUDA) : A library that can translate special Java Code (called JCUDA code) into Java- and CUDA-C code, which can then be compiled and executed on the GPU. However, the library does not seem to be publicly available.
https://www2.informatik.uni-erlangen.de/EN/research/JavaOpenMP/index.html : Java language extension for for OpenMP constructs, with a CUDA backend
Java OpenCL/CUDA binding libraries
https://github.com/ochafik/JavaCL : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings
http://jogamp.org/jocl/www/ : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings
http://www.lwjgl.org/ : Java bindings for OpenCL: Auto-generated low-level bindings and object-oriented convenience classes
http://jocl.org/ : Java bindings for OpenCL: Low-level bindings that are a 1:1 mapping of the original OpenCL API
http://jcuda.org/ : Java bindings for CUDA: Low-level bindings that are a 1:1 mapping of the original CUDA API
Miscellaneous
http://sourceforge.net/projects/jopencl/ : Java bindings for OpenCL. Seem to be no longer maintained since 2010
http://www.hoopoe-cloud.com/ : Java bindings for CUDA. Seem to be no longer maintained

A: From the research I have done, if you are targeting Nvidia GPUs and have decided to use CUDA over OpenCL, I found three ways to use the CUDA API in java.

*

*JCuda (or alternative)- http://www.jcuda.org/. This seems like the best solution for the problems I am working on. Many of libraries such as CUBLAS are available in JCuda. Kernels are still written in C though.

*JNI - JNI interfaces are not my favorite to write, but are very powerful and would allow you to do anything CUDA can do.

*JavaCPP - This basically lets you make a JNI interface in Java without writing C code directly. There is an example here: What is the easiest way to run working CUDA code in Java? of how to use this with CUDA thrust. To me, this seems like you might as well just write a JNI interface.

All of these answers basically are just ways of using C/C++ code in Java. You should ask yourself why you need to use Java and if you can't do it in C/C++ instead.
If you like Java and know how to use it and don't want to work with all the pointer management and what-not that comes with C/C++ then JCuda is probably the answer. On the other hand, the CUDA Thrust library and other libraries like it can be used to do a lot of the pointer management in C/C++ and maybe you should look at that.
If you like C/C++ and don't mind pointer management, but there are other constraints forcing you to use Java, then JNI might be the best approach. Though, if your JNI methods are just going be wrappers for kernel commands you might as well just use JCuda.
There are a few alternatives to JCuda such as Cuda4J and Root Beer, but those do not seem to be maintained. Whereas at the time of writing this JCuda supports CUDA 10.1. which is the most up-to-date CUDA SDK.
Additionally there are a few java libraries that use CUDA, such as deeplearning4j and Hadoop, that may be able to do what you are looking for without requiring you to write kernel code directly. I have not looked into them too much though.

A: I'd start by using one of the projects out there for Java and CUDA: http://www.jcuda.org/

A: Marco13 already provided an excellent answer.
In case you are in search for a way to use the GPU without implementing CUDA/OpenCL kernels, I would like to add a reference to the finmath-lib-cuda-extensions (finmath-lib-gpu-extensions) http://finmath.net/finmath-lib-cuda-extensions/ (disclaimer: I am the maintainer of this project).
The project provides an implementation of "vector classes", to be precise, an interface called RandomVariable, which provides arithmetic operations and reduction on vectors. There are implementations for the CPU and GPU. There are implementation using algorithmic differentiation or plain valuations.
The performance improvements on the GPU are currently small (but for vectors of size 100.000 you may get a factor > 10 performance improvements). This is due to the small kernel sizes. This will improve in a future version.
The GPU implementation use JCuda and JOCL and are available for Nvidia and ATI GPUs.
The library is Apache 2.0 and available via Maven Central.

A: There is not much information on the nature of the problem and the data, so difficult to advise. However, would recommend to assess the feasibility of other solutions, that can be easier to integrate with java and enables horizontal as well as vertical scaling. The first I would suggest to look at is an open source analytical engine called Apache Spark https://spark.apache.org/ that is available on Microsoft Azure but probably on other cloud IaaS providers too. If you stick to involving your GPU then the suggestion is to look at other GPU supported analytical databases on the market that fits in the budget of your organisation.


text:
Q: Rails 3 Active Record relation order: Use hash instead of string To sort a relation in Rails 3, we have to do this:
User.where(:activated => true).order('id ASC')

But I think this:
User.where(:activated => true).order(:id => :asc)

would make better sense because the way the field name be escaped should depend on the adapter (SqlLite vs Mysql vs PostgreSQL), right?
Is there something similar to that?

A: As far as I know there's no option for this syntax built into ActiveRecord, but it shouldn't be hard for you to add one. I found the order method defined in lib/active_record/relation/query_methods.rb. Theoretically, you should be able to do something like this:
module ActiveRecord
  module QueryMethods
    def order(*args)
      args.map! do |arg|
        if arg.is_a? Hash
          # Format a string out of the hash that matches the original AR style
          stringed_arg
        else
          arg
        end
      end

      super
    end
  end
end

A: I think the key problem is: ActiveRecord API is not aware of ordering semantic. It just accepts a string and bypasses to the underlying database. Fortunately, Sqlite, MySQL and PostgreSQL has no difference in order syntax.
I don't think ActiveRecord can do this abstraction well, and it doesn't need to do it. It works well with relation databases, but is hard to integrate with NoSQL, eg. MongoDB.
DataMapper, another famous Ruby ORM, did better abstraction. Take a look at its query syntax:
@zoos_by_tiger_count = Zoo.all(:order => [ :tiger_count.desc ])

The API is aware of the ordering semantic. By default, DataMapper will generate SQL order statement:
https://github.com/datamapper/dm-do-adapter/blob/master/lib/dm-do-adapter/adapter.rb#L626-634
def order_statement(order, qualify)
  statements = order.map do |direction|
    statement = property_to_column_name(direction.target, qualify)
    statement << ' DESC' if direction.operator == :desc
    statement
  end

  statements.join(', ')
end

However, it's possible to override at DB adapter layer:
https://github.com/solnic/dm-mongo-adapter/blob/master/lib/dm-mongo-adapter/query.rb#L260-264
def sort_statement(conditions)
  conditions.inject([]) do |sort_arr, condition|
    sort_arr << [condition.target.field, condition.operator == :asc ? 'ascending' : 'descending']
  end
end

TL;DR:

*

*You don't need worry about syntax problem if you are only using SqlLite, Mysql and PostgreSQL.

*For better abstraction, you can try DataMapper.

A: For this particular case, you could drop the 'ASC' bit as ordering in all database is implicitly ascending
Foo.order(:bar)

I am aware that this doesn't cover the case where you'd want to do order by bar desc but actually for order by this doesn't matter much unless you are using functions for the order by clause in which case maybe something like squeel would help


text:
Q: Is there a way to access the values of a lot of form collection elements without manually typing the reference value associated with each element? The above question is for ASP.NET MVC. I had to delete that part because of the title size restriction.
Let's say I have 100 checkboxes. Each checkbox has a reference value integer from 1 to 100. Some checkboxes are checked. Some are not. I press submit. A form collection is passed into an action method. Each checkbox of the form collection either has a value that represents if it is checked or not. Now I want to be able to access the values of each checkbox without manually typing the reference values from 1 to 100.
I've already tried just looping from 1- 100 over a FormCollection. In other words, I have the strings "1" to "100" created (not manually) to be put inside let's say a string a. Then I want form collection name[a] to be processed. Unfor. that does not happen.
Why this happens?
Can somebody give me a simple alternative?
Here is my code. Below, on the Form_Data[b], my debugger gives a null reference exception. If I put b="2(or any other integer from 3 to 91 inclusive)", my code works fine(which is why I suspect form collection reference values can only be read during compile-time).
for (int Speaker_Reference_Number = 2; Speaker_Reference_Number <= 91; Speaker_Reference_Number++)
{
    char a = '"';
    string c = a.ToString();
    string b ="";
    b = b + c;
    b = b + Speaker_Reference_Number;
    b = b + c;

    if (Form_Data[b].Equals("true,false"))
    {
        if (Speaker_Reference_Number <= 9)
        {
            Speakers = Speakers + "00" + Speaker_Reference_Number;
        }
    }
}


text:
Q: CefSharp ProgressBar for indicating download progress I am making a web browser based on CefSharp. When I try to download a file from the web, it prompts me to save the file, and when I press Save, it downloads the file without indicating any progress percentage. I want to add a ProgressBar to show download progress. How can I do this?

A: You can use an IDownloadHandler for that.
Suppose you have a browser control named Browser and a ProgressBar named Barin your XAML, you can do this in your code behind:
Browser.DownloadHandler = new MyDownloadHandler(Bar);

Here's the code for the MyDownloadHandler:
public class MyDownloadHandler : IDownloadHandler {
    private ProgressBar _bar;

    public MyDownloadHandler(ProgressBar bar) {
        _bar = bar;
    }

    public void OnBeforeDownload(IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback) {

    }

    public void OnDownloadUpdated(IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback) {
        _bar.Dispatcher.Invoke(new Action(() => {
            Debug.Print("{0}/{1} bytes", downloadItem.ReceivedBytes, downloadItem.TotalBytes);

            _bar.Maximum = downloadItem.TotalBytes;
            _bar.Value = downloadItem.ReceivedBytes;
        }));
    }
}