text:
Q: Having trouble getting a custom zoom button in React-Leaflet I'm trying to build my own Zoom button with react-leaflet
I have the following code:
import React from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { Map, TileLayer } from 'react-leaflet';
import Control from 'react-leaflet-control';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import ZoomIn from 'material-ui/svg-icons/action/zoom-in';
import ZoomOut from 'material-ui/svg-icons/action/zoom-out';

class LeafletMap extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            animate: true,
            center: [
                -34.989610443115,
                -71.232476234436
            ],
            zoom: 13,
            zoomControl: false
        };
    }

    render() {
        return (

                <Map
                    animate={this.state.animate}
                    center={this.state.center}
                    zoom={this.state.zoom}
                    zoomControl={this.state.zoomControl}
                    >
                    <TileLayer
                        url={'http://{s}.tile.osm.org/{z}/{x}/{y}.png'}
                        attribution={'© OpenStreetMap'}
                    />
                    <Control position="topleft">
                        <MuiThemeProvider>

                                <FloatingActionButton mini={true}>
                                    <ZoomIn onClick={ () => alert('Zoom In') } />
                                </FloatingActionButton>

                                <FloatingActionButton mini={true}>
                                    <ZoomOut onClick={ () => alert('Zoom Out') }/>
                                </FloatingActionButton>

                        </MuiThemeProvider>
                    </Control>
                </Map>

        );
    }
}
export default LeafletMap;

All this is displaying good way, but now I want to to put a funcion where I can able to do zoom in or out. I don't have an idea how to call leaflet's methods using react-leaflet library.
I've tried many ways to implement it but without success.
Do you have any idea how to implement it?

A: There are a few ways to handle map functions/actions.

*

*Pass via props
Many options are available via the Map's props(bounds, center, zoom).  This way allows you to hold the zoom in your one state/store, instead of in leaflet.
const React = window.React;
const {
  Map,
  TileLayer,
  Marker,
  Popup
} = window.ReactLeaflet;

class ZoomInState extends React.Component {
  constructor() {
    super();
    this.state = {
      lat: 51.505,
      lng: -0.09,
      zoom: 13,
    };
    this.zoomIn = () => this.setState({zoom: this.state.zoom+1})
    this.zoomOut = () => this.setState({zoom: this.state.zoom-1})
  }

  render() {
    const position = [this.state.lat, this.state.lng];
    return ( < Map center = {
        position
      }
      zoom = {
        this.state.zoom
      }

      >
      < TileLayer attribution = '© OpenStreetMap contributors'
      url = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png' / >
      < Marker position = {
        position
      } >
        < Popup >

            <button onClick={this.zoomOut}>
              Zoom out
            </button >
            < button onClick = {this.zoomIn} >
              Zoom in
            < /button>

        </Popup >
      < /Marker>
      </Map >
    );
  }
}
export default ZoomInState

*Get map via refs
This way will not hold the zoom level in your component. Often this is a good practice, because it keeps a single source of truth. You can always get the zoom with map.getZoom()
const React = window.React;
const { Map, TileLayer, Marker, Popup } = window.ReactLeaflet;

class MapByRef extends React.Component {
  constructor() {
    super();
    this.state = {
      lat: 51.505,
      lng: -0.09,
      zoom: 13,
    };
  }

  bindMap(el) {
    this.map = el.leafletElement;
  }

  zoomIn() {
    this.map.zoomIn();
  }

  zoomOut() {
    this.map.zoomOut();
  }

  render() {
    const position = [this.state.lat, this.state.lng];
    return (
      <Map center={position} zoom={this.state.zoom} ref={::this.bindMap}>
        <TileLayer
          attribution='© OpenStreetMap contributors'
          url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
        />
        <Marker position={position}>
          <Popup>

              <button onClick={::this.zoomIn} >Zoom In</button>
              <button onClick={::this.zoomIn} >Zoom Out</button>

          </Popup>
        </Marker>
      </Map>
    );
  }
}
export default MapByRef

3. Get from Context
This way is nice if you want to make many child components that need to interact with the map. It also keeps leaflet as the single source of truth.
const React = window.React;
const { Map, TileLayer, Marker, Popup } = window.ReactLeaflet;

class CustomMarker {

  zoomIn(){
    this.context.map.zoomIn()
  }
  zoomOut(){
    this.context.map.zoomOut()
  }

  render() {
    return (
      <Marker position={position}>
        <Popup>
          <button onCLick={::this.zoomIn}>Zoom In</button>
          <button onCLick={::this.zoomOut}>Zoom In</button>
        </Popup>
      </Marker>
    )
  }
}
export CustomMarker

class MapWithCustomChildren extends React.Component {
  constructor() {
    super();
    this.state = {
      lat: 51.505,
      lng: -0.09,
      zoom: 13,
    };
  }

  render() {
    const position = [this.state.lat, this.state.lng];
    return (
      <Map center={position} zoom={this.state.zoom}>
        <TileLayer
          attribution='© OpenStreetMap contributors'
          url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
        />
        <CustomMarker />
      </Map>
    );
  }
}
export default MapWithCustomChildren


text:
Q: can't get abstract class out of package object in scala I have a package object with an abstract class in it like this:
package mainPackage

package object subPackage {

    abstract class MyBase(val i: Int)
    case class DerivedClass(override val i: Int) extends MyBase(i)

}

In another file, I import the package:
import mainPackage.subPackage._

This gives me access to DerivedClass, but for some reason, I can't see the abstract base class. Any idea why? I want to create a List[BaseClass], but it's not letting me.

A: The following worked for me:
package mainPackage

class Baba {
  import mainPackage.subPackage._

  new MyBase(1) {

  }

  val l: List[MyBase] = ???
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using an IOS app privately between family members I'm slowly learning flutter and building apps for Android and IOS.
As my first app I'm just testing a simple checklist app for my family members.
I know that if you build it, you can ship it as an apk for android users without the need to do anything Play Store related.
But what about iPhone users? I also don't need to do anything regarding the App Store and I certainly don't want to pay 99USD a year to just learn app development (As I'll maybe buy a mac in the future if I consider using Swift). I heard that it's possible using TestFlight but there was a 90 day build limit and other stuff (probably the license) so I was wondering if there's a way to download apps like .apk files and install them without limitations from apple?
I've also seen that there's .ipa files, but I believe those are just for Jailbroken iPhones.


text:
Q: I can't display my image in my temlate.vm (velocity) I'm trying to send an email with a template using springMvc. I used Velocity to disay the template. The problem is that the image in the cannot appear in my email. And I'm sure that my src is incorrect!
Here is my template.vm

Hi ${user.login}, welcome to the Chipping Sodbury On-the-Hill message boards!

            Your email address is ${user.emailAddress}.

A: Your problem has nothing to do with Velocity, and I'm pretty sure your URL  is not correct:
When displaying an image in an email, you have to choose between three solutions:

*

*hosting the image somewhere (then the image URL will be something like http://myserver/...)

*linking the image as an email attachment (in which case the image URL will be something like cid:{0})

*embedding the image in base64 (in which case the image URL will be something like data:image/jpeg;base64,...).

There are pros and cons for each method.


text:
Q: Reading rows in csv file I have a csv file that has data looks similar to this:
Year     Age
2001    58
2006    52
2006    12
2001    50
2012    59
2017    46

So I want to extract these two rows into two different list.
with open('age.csv', 'r') as files:
        next(files) # skip header

        for row in file_path:
            years = row[0]

return years, average_age

But this will only give me 20, 20, 20, something that I didn't want it to show.
So that I can have like:
years = [2001, 2006, 2006, 2001, blabla]

However, for age, I am planning to get the average age for each year. But I don't know how in this case.

A: You have opened the file, and are reading it line by line.  When you reference row[0] and row[1], you are referencing the first and second character of each line.  In this case, it happens to be 2 and 0 as part of the year.
You need to take it one more step and interpret the file as a CSV file, rather than just a series of lines.  Reading the documentation of Python's core CSV library should help.  Meanwhile, here's a code snippet from there which may jump start your process:
>>> import csv
>>> with open('eggs.csv', newline='') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
...     for row in spamreader:
...         print(', '.join(row))

Further, with your implementation, it looks like you are iterating over the entire file, constantly reading the first and second characters, and finally returning just the last line.  That looks like a possible error.

A: You need to split and strip the string.
with open('age.csv', 'r') as f:
        next(f) # skip header

        list_year = []
        list_age = []
        for row in f:
            year, age = (s.strip() for s in row.split(','))
            list_year.append(year)
            list_age.append(age)
        return (list_year, list_age)


text:
Q: how to maintain order while doing join in sql table 1 and table 2 have their primary key (key1,key2) to be the same. table 3 is a user defined table with one column field5 which is common to table2. I need to select the rows from table 1 and table 2 where field5 in table2 is in table3. I need to obtain the rows in the same order as table3.
table 1
key1 key2 field1 field2
table 2
key1 key2 field3 field4 field5
user defined table
field5
the query i am thinking is
select a.key1, a.key2, a.field1, a.field2, b.field3, b.field4
from table1 as a INNER JOIN table2 as b ON a.key1 = b.key1 AND a.key2 = b.key2
where b.field5 in (select field5 from table3)

this will not give me the rows in the same order as in table3.
I would need something like this to maintain the order?
select a.key1, a.key2, a.field1, a.field2, d.field3, d.field4 from
table1 as a INNER JOIN
 (select b.key1, b.key2, b.field3, b.field4
  from table2 as b INNER JOIN table3 as c
  ON b.field5 = c.field5) as d
WHERE a.key1 = d.key1 AND a.key2 = d.key2

A: If you would like to order output data, as it is ordered (inserted) in table3, I'd suggest, adding a column to table3 rowid int identity(1,1). This creates an autoincrement field, which will increase its value for each new row inserted.
Then you can select rows as they were inserted into that table as selecting order by table3.rowid
Reference from MSDN - IDENTITY (Property)

A: Order is only offered in the final result when you use an order by clause.
If you want "in the same order as table3" you must write a proper order by clause to recreate the order that you have in table3.
The join is free to scramble rows if it makes things go faster.

A: You need to add an ORDER BY clause.
SELECT a.key1, a.key2, a.field1, a.field2, d.field3, d.field4
FROM table1 as a INNER JOIN (select b.key1, b.key2, b.field3, b.field4 from table2 as b
INNER JOIN table3 as c ON b.field5 = c.field5) as d
WHERE a.key1 = d.key1 AND a.key2 = d.key2
ORDER BY c.field5;

EDIT:
I misunderstood your original intent. My solution sorts on the "value" for field5, which likely isn't the order they are laid out in the table.  You can not rely on the physical ordering of rows within a table and I'm afraid that what you're trying to do isn't something you should be relying on.  The reason, I don't think you could ever guarantee the order will match the "same order as table3" if what your after is physical order unless the table was clustered on field5.
For example, if the table was clustered on field1 and you use an identity or "sorting" column for sorting as others suggest, I would expect the sort on the identity/sorting column to be far different from the physical order of the rows in the table.  I'm not a SQL Server expert by any means, but many databases allow row movement as well, which could change the "order" the rows are physically stored without changing the values within your sort columns, thus breaking your rules again.
I'm not certain as to why you need these returned in this strict of an order.  If possible, I would eliminate that constraint and allow the data to be processed/handled by sorting the value of a column whether it be field5 or some other field.

A: You cannot depend on the physical ordering of rows in a table. To ensure a given order, add a sort field to your table3, and change your query to
select
  a.key1,
  a.key2,
  a.field1,
  a.field2,
  b.field3,
  b.field4
from table1 as a
INNER JOIN table2 as b ON a.key1 = b.key1 AND a.key2 = b.key2
INNER JOIN table3 as c on b.field5 = c.field5
ORDER BY c.sort_field

A: Give a try on this:
select a.key1, a.key2, a.field1, a.field2, b.field3, b.field4
from table1 as a
    JOIN table2 as b ON a.key1 = b.key1 AND a.key2 = b.key2
    join (select field5, ROW_NUMBER() over (order by (select null)) Table3_Order from table3) c on b.field5 c.field5
order by c.Table3_Order

Table3_Order is the original (I think, the phisical) order in the table3.

A: I just had this same problem myself and came up with another solution -- you can create a temp table with whatever columns you need (starting with field5).  Inserting all the "field5" values from table3 into your temp table first will lock in the order that you want (same order as they are in table3).  Then you can update the rest of your temp table columns by joining on field5 etc.  Something like this:
create table #tempTable(field5 varchar(200), key1 int, key2 int, field1 varchar(200), field2 varchar(200), field3 varchar(200), field4 varchar(200))
--insert field5 values (in order) into temp table's first column
insert into #tempTable
select field5,null,null,null,null,null,null from table3
--update all other columns in the temp table as needed by joining on field5 etc.
update temp
set key1 = b.key1,
    key2 = b.key2,
    field3 = b.field3,
    field4 = b.field4
from #tempTable temp
join table2 b on b.field5 = temp.field5
--add the final fields from table1 in the same way...
update temp
set field1 = a.field1,
    field2 = a.field2
from #tempTable temp
join table1 a on a.key1 = temp.key1

A: I had this problem and I solved it using ROWNUM in Oracle:
select a.key1, a.key2, a.field1, a.field2, b.field3, b.field4 from
(select rownum as to_order, key1, key2, field1, field2 from table1) as a
INNER JOIN table2 as b
ON a.key1 = b.key1 AND a.key2 = b.key2 where b.field5 in (select field5 from table3)
order by a.to_order;


text:
Q: How to add list of files to clipboard for cutting I've found this article on Code Project that shows how to add a list of files (paths) to the clipboard and flag it for moving instead of copying.
The method used is shown in multiple articles across the internet and is said to be working, but I can't seem to get it to work.
I'm on Windows 8.1 (64 bit). After I cut a few files from my list and try to paste the files somewhere in Explorer, I just hear a ding and nothing happens.
Copying files works though.
Here's what I have:
StringCollection paths = new StringCollection();
foreach (FileInformation file in lbxFoundFiles.SelectedItems)
{
    paths.Add(file.FileInf.FullName);
}

IDataObject data = new DataObject(DataFormats.FileDrop, paths);
MemoryStream memo = new MemoryStream(4);
byte[] bytes = new byte[] { 2, 0, 0, 0 };
memo.Write(bytes, 0, bytes.Length);
data.SetData("Preferred DropEffect", memo);
Clipboard.SetDataObject(data);

A: You've passed to DataObject constructor wrong data. Do it in such way:
byte[] moveEffect = { 2, 0, 0, 0 };
MemoryStream dropEffect = new MemoryStream();
dropEffect.Write(moveEffect, 0, moveEffect.Length);

StringCollection filestToCut = new StringCollection {"D:\\test.txt"};
DataObject data = new DataObject("Preferred DropEffect", dropEffect);
data.SetFileDropList(filestToCut);

//or execute default constructor and uncomment line below:
//data.SetData("Preferred DropEffect", dropEffect);

Clipboard.Clear();
Clipboard.SetDataObject(data, true);


text:
Q: Flex items exceed container height when wrapped in Firefox In the current Firefox (50), when the two items in the header wrap below 715px, the lower item extends below the header's height. I have played with the flex shorthand statements of each item, and min-widths, and tried a @media query for a screen with that max-width, and can't get it to stop. The page is here.
The CSS:

header {
  display: flex;
  flex-flow: row-reverse wrap;
  justify-content: space-around;
  height: 320px;
  padding: 20px 0;
}
.sec1 {
  flex: 4 2 200px;
  min-width: 200px;
  padding-right: 6vw;
  padding-left: 3vw;
  margin-top: 2vw;
  @media only screen and (max-width: 1350px) {
    flex: 6 1 0;
    margin-top: 6vw;
  }
}
.sec2 {
  align-self: center;
  flex: 7 0 250px;
  display: flex;
  flex-direction: row-reverse;
  justify-content: flex-start;
  p {
    width: 40%;
    text-align: right;
    margin-right: 30px;
    margin-bottom: 25px;
    align-items: flex-start;
  }
}
.accent {
  font-size: 20px;
  color: #967832;
  line-height: 24px;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 50px;
  border: 8px solid black;
  padding: 12px;
}
.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  align-items: stretch;
}
section {
  display: box;
  display: flex;
  padding: 15px;
  flex: 1 0 350px;
  margin-top: 3vw;
  margin-left: 6vw;
}

What would it really be like

to live on the Moon?

Realistic Lunar Colony, Coming Online

          This project is building a series of virtual colonies on the Moon. They will be richly detailed and interactive presentations that are entirely plausible, technically and scientifically. They will examine all the questions, consider all the implications.
          When humanity undertakes ventures on the scale of space settlement, it matters a great deal how many people have given it real thought beforehand. These colonies serve that purpose.

Mon, 07 Nov 2016 19:50:00 GMTLalande mapKim has finished composing an extremely detailed map of the Lalande crater. It is a huge file, but available at request.

The issue seems to be that Firefox isn't considering the height of the container when wrapping. What is the way to stop the overflow?

A: Your code is overly complex. Much of it can be safely removed. Try a process of elimination to pinpoint the problem.
Here's a revised version of your code (tested on Chrome & FF):

What would it really be like
 to live on the Moon?

revised codepen


text:
Q: Batch file run via shortcut changes destination folder I have a batch file that moves files from a specific folder to the current folder (the folder in which the command is run), but if I create a desktop link for that batch file and try running that instead, the files get moved to the folder in which the batch file resides rather than the folder in which the command is being run.  Why would this be?  Is there any way to rectify this?

A: There are two ways to fix this.
You can change the command in your batch file to explicitly name the folder:
move M:\Logs\*.* C:\NewLogFolder

Or you can change the Start In location in the shortcut to the new destination:

A: One way to work around this is to use the "Send To" context menu.
If you "start > run" shell:sendto, you will get to the magic folder where send-to shortcuts are kept. You can then add a shortcut to your batch file to your desktop and then then drag the batch file shortcut into this folder (permissions may block you from adding directly).
When the batch file is run via the shortcut, the parameter %1 will be set to the folder or file you highlighted.
So if I highlight the folder "c:\bar" and then "Sendto > Foo.bat":
foo.bat:
@echo off
echo %1
pause

Would emit:
C:\Bar

If the batch file was:
move M:\logs\*.* %1

You would wind up with the proper result, so long as you do not highlight a filename. So test for errors and sanity first.


text:
Q: Does Qt ObjectName() have to be unique? Simple question as in the title - if I call setObjectName() on an object, does it have to be unique, or is it just recommended because of convention? I've subclassed QLabel, and want to automatically give the objects created a name; if this is a bad idea, I'll find some way of setting a random unique name. (I'm actually using PyQt, but this shouldn't influence the answer!)
Update
In response to the 2 answers so far (which I should have predicted!), I want to do this so that I can ignore all instances of my subclass.  Calling findChildren(QLabel) cascades so that all subclasses of QLabel are also found - if I use the same object name for all my subclassed objects, then I can just regex in the 2nd argument of findChildren() so that I ignore them

A: If you look at the documentation for QObject, you can see that it states: -

This property holds the name of this object.
  You can find an object by name (and type) using findChild(). You can find a set of objects with findChildren().

Looking at findChildren(), it states: -

Returns all children of this object with the given name that can be cast to type T...

So, clearly it can be seen that multiple objects can have the same name.

A: No, but without unique names you wouldn't be able to find objects by name (without additional checks).

A: Setting an object name is not strictly needed, it defaults to an empty string.
However, if you need to find objects by their name, you surely want it to be unique!

A: The object name is essentially not used anywhere important. It's up to you how you set it up. There are two things of note:

*

*Objects created by setupUi function in code generated by uic: all objects have names, and the names are unique. It's for your convenience only, though.

*When using QMetaObject::connectSlotsByName on an object, all slots named on_foo_bar will be connected to a child object's bar signal, as long as the object is named foo.

*When using CSS stylesheets for widgets (QWidget class hierarchy), the object names can be used as ids in id selectors. That's handy sometimes.


text:
Q: Suggestions to handle `Wframe-larger-than`-warning on kernel module Hello and a happy new year,
I'm working on a kernel-module. It is necessary to do a numeric calculation of some parameter to set up the device correctly.
The function works perfectly but the gcc compiler (I'm using kbuild) gives me the warning:
warning: the frame size of 1232 bytes is larger than 1024 bytes [-Wframe-larger-than=]

If I'm right this means that space local variables exceed a limitation given by the machine the module compiled on.
There are some questions now:

*

*Does this warning refer to the whole memory space needed for the module, this explicit function or this function and its sub-functions?

*How critical is this?

*I don't see a way to reduce the needed memory. Are there some suggestions to handle this? Any how-to?

Maybe it is helpful: The calculation uses a 64bit fixed-point-arithmetic. All the functions of this library are inline functions.
Thanks in advance
Alex

Following the advice from @Tsyvarev the problem could reduce to the allocation in a function as this example shows (I know that the code doesn't make sense - it's only for showing how I declare the variables inside the functions):
uint8_t getVal ( uint8_t )
{
  uint64_t ar1[128] = {0};
  uint64_t ar2[128] = {0};
  uint8_t val;

  // a much of stuff

  return val;
}

void fun ( void )
{
  uint64_t ar1[128] = {0};
  uint64_t ar2[128] = {0};
  uint8_t cnt;

  for(cnt=0; cnt<128; cnt++)
  {
    ar1[cnt] = getVal(cnt);
    ar1[cnt] = getVal(cnt);
  }
}

A: to point 3:
As suggested the solution is to store the data to the heap with kmalloc instead to the stack.
uint8_t getVal ( uint8_t )
{
  uint64_t *ar1;
  uint64_t *ar2;
  uint8_t val, cnt;

  // allocate memory on the heap
  ar1 = kmalloc(sizeof(uint64_t), 128);
  ar2 = kmalloc(sizeof(uint64_t), 128);

  // initialize the arrays
  for(cnt=0; cnt<128; cnt++)
  {
    ar1[cnt] = 0;
    ar2[cnt] = 0;
  }

  // a much of stuff

  return val;
}

void fun ( void )
{
  uint64_t *ar1;
  uint64_t *ar2;
  uint8_t cnt;

  // allocate memory on the heap
  ar1 = kmalloc(sizeof(uint64_t), 128);
  ar2 = kmalloc(sizeof(uint64_t), 128);

  // initialize the arrays
  for(cnt=0; cnt<128; cnt++)
  {
    ar1[cnt] = 0;
    ar2[cnt] = 0;
  }

 for(cnt=0; cnt<128; cnt++)
  {
    ar1[cnt] = getVal(cnt);
    ar1[cnt] = getVal(cnt);
  }
}


text:
Q: How do you utilize the google maps elevation service as a jsx tag? I have been developing a customized google map, and a feature that I need is to be able to tell about the elevation of different locations on click. I have coded the map with a bunch of jsx tags (i.e a tag for google map, a tag for marker, etc...). However, I have not been able to figure out how to do this for the elevation service. So my question is, is it possible to use the google map elevation service as a jsx tag, and if so, what is the import? If not, what are some alternatives to adding this feature?

A: You can check first the Elevation Service of Google Maps Platform.
You can also check how I implemented it in a reactjs code in this working sample and code snippet below:
import React, { Component } from "react";
import { render } from "react-dom";
import Map from "./Map";
import "./style.css";

class App extends Component {
  render() {
    return (
      <Map
        id="myMap"
        options={{
          center: { lat: 41.0082, lng: 28.9784 },
          zoom: 8,
          mapTypeId: "terrain"
        }}
        onMapLoad={map => {
          const elevator = new google.maps.ElevationService();
          const infowindow = new google.maps.InfoWindow({});
          infowindow.open(map);
          // Add a listener for the click event. Display the elevation for the LatLng of
          // the click inside the infowindow.
          map.addListener("click", event => {
            displayLocationElevation(event.latLng, elevator, infowindow);
          });

          function displayLocationElevation(location, elevator, infowindow) {
            // Initiate the location request
            elevator.getElevationForLocations(
              {
                locations: [location]
              },
              (results, status) => {
                infowindow.setPosition(location);

                if (status === "OK") {
                  // Retrieve the first result
                  if (results[0]) {
                    // Open the infowindow indicating the elevation at the clicked position.
                    infowindow.setContent(
                      "The elevation at this point <br>is " +
                        results[0].elevation +
                        " meters."
                    );
                  } else {
                    infowindow.setContent("No results found");
                  }
                } else {
                  infowindow.setContent(
                    "Elevation service failed due to: " + status
                  );
                }
              }
            );
          }
        }}
      />
    );
  }
}

export default App;


text:
Q: Item wont remove from the shopping cart -- vanilla javascript I was trying to build a shopping cart with Vanilla javascript and HTML &CSS. I have run into a problem where by I could not remove an item form the shopping cart. I have been using the Local storage. When I click on the remove icon I get this error:

myown.js:171 Uncaught TypeError: Cannot read property
'getElementsByClassName' of undefined
at HTMLElement.

I have tried many things but it seems hard to get around.
Any help will be appreciated.
My code:
function deleteButtons(){

   let deleteButtons =document.querySelectorAll('.product ion-icon ');
   console.log("deleteButtons ");

   let productName;
   for (i=0; i< deleteButtons.length; i++) {
        deleteButtons[i].addEventListener('click', () =>{
            console.log("clicked");
            // productName = deleteButtons[i].parentElement;
            productName = deleteButtons[i].parentElement.textContent;
            console.log(productName );
        });
   }
}


text:
Q: Exchange 2007 Standard Edition We Have :

*

*Exchange 2007 Standard Edition

*IBM System X3650

*2 x Intel Xeon 5430 2.66 GHz

*Version 8.1 Build 240.6

*Mailbox, Hub Transport, Client Access Role Installed on One Box

*Total Number of Mailboxes : 110 - 130

6 Physical Disks

*

*Disk 0,1 (68 GB) = Raid-1, OS Partition ( C: Partition)

*Disk 2,3 (279GB) = Raid-1, Exchange Database (First and Second Storage Groups) ( D: Partition )

*Disk 4,5 (68 GB) = Raid-1, Exchange Transaction Logs ( E: Partition )

Setup:

*

*Storage Groups : D:\First Storage group\Mailbox database.edb

*Storage Groups : D:\Second Storage Group\Public Folder Database.edb

*Transaction Logs : E Partition

Problem 1:
On our D Partition (Mailbox Database Partition), total size is 279 GB, free space remaining is 64.7 GB, when I select the first storage group and second storage group folders and right click properties they report a size of 165 GB.
Mailbox database reports a size of 157GB when right clicked > Properties. where as the size displayed in the folder is 164,893,456 KB
So, we are missing around 50-54 GB, there is nothing else on these drives, no page file, nothing at all.
The partition housing the Transaction logs is reporting the sizes accurately.
Any suggestions / fixes on the above ?
Problem 2:
As you may have already read in Problem 1, the size of the mailbox database is 157GB or 164GB reported; which is not recommended,
a) What would you suggest we should do to divide mailboxes in storage groups on this same server ?
b) How would we move mailboxes into different storage groups ?
c) This is the information store size ? (Am I right in thinking that this is not recommended)
d) Having multiple storage groups with one Mailbox DB in each, would that reduce the size of the Information Store?
e) Any suggestions / how-to reduce the size of information store ?
We didn't install this, we have inherited this - what other recommendations you can make in order to keep ourselves better prepared for any server disaster?
We are backing up with Yosemite Backup on RD1000 (320GB) at the moment, which is backing up successfully, flushing the logs daily. We haven't done a test restore YET.
I have tried to provide as much info as possible, please let me know if you need further info.
Also, we haven't yet faced any problems in mailflow, access speeds, everything is working fine, we have two to five people accessing OWA or Outlook via vpn only.
Thanks for your time to read the above - will look forward to your expert suggestions.

A: These are my opinions so take them as such:

*

*Stop the Microsoft Software Shadow Copy Provider and Volume Shadow Copy services. I suspect you have some leftover VSS snapshots that are taking up the disk space.

*Create additional Mailbox Stores in your current Storage Group and split your mailboxes accordingly by moving some number of them to the new Mailbox Stores. Create as many Mailbox Stores as you feel is neccessary to keep the size reasonable. On Exchange Server 2003 it's recommended to keep the Mailbox Stores under 100GB, I'm assuming the same holds true for Exchange Server 2007. I don't see any need to create additional Storage Groups.

A: I haven't yet seen any size restrictions on db's or storage groups, only recommended RAM per storage group.  It's recommended that you place different DBs each in their own storage group, because each storage group only has one set of transactions logs, no matter how many databases it may contain.  You're going to be limited to 5 with Standard, so depending on your DB growth, this may influence your planning.
I'm a big fan of RAID5 for Exchange, myself, I'd add another disk to those volumes.  Redundancy and maximum uptime by far outstrips excessive speed for email in my book.


text:
Q: How can I activate interactivity on cartoDB.js with createLayer? I've made a map with cartoDB.js with the createLayer method. I've defined the sublayers,inside a variables called layerSource, giving them an interactivity field like this:
sublayers:[ {sql: "SELECT * FROM db_name",
interactivity: "cartodb_id",
cartocss: "styles"},...more sublayers...

After this I've added the layers to the map
cartodb.createLayer(map,layerSource)
                    .addTo(map)
                    .done(function(layer) {
                       for (var i = 0; i < layer.getSubLayerCount(); i++) {
                           sublayers[i] = layer.getSubLayer(i);
                       }
                    })
                    .error(function(err) {
                        console.log("error: " + err);
                    });

But the sublayers are not interactive. I've seen in the documentation that I have to enable the interactivity with setInteraction:true, but where I should activate this option?? Inside the createLayer (as an argument?), inside the .done??.. I assume this should be something very obvious but I'm new to javaScript and not being able to get this done.
EDIT:
After @Andy_Eschbacher answer.
I'm trying to do what you said but with the first block of code
.done(function(layer) {
                      for (var i = 0; i < layer.getSubLayerCount(); i++) {
                           sublayers[i] = layer.getSubLayer(i);
                       };

                        sublayer[0].on('featureClick',function(event, latlng, pos, data, layerIndex) {
                            console.log(data);
                        });
                    })
                    .error(function(err) {
                        console.log("error: " + err);
                    });

the console sends an error because sublayer is not defined, so I define a sublayer = layer.getSubLayer(0);as you do in this tutorial but no action is triggered.

A: You enabled interactivity, but you've not created infowindows, hovers, or printed anything to the console yet.
If you add the following within .done(function(layer) {....});, it will print to the console:
sublayers[0].setInteraction(true);
sublayers[0].on('featureClick',function(event, latlng, pos, data, layerIndex) {
    console.log(data);
});

If you want to enable infowindows, you need to add the following:
cdb.vis.Vis.addInfowindow(map, layer.getSubLayer(0), ['cartodb_id']);

This process is walked through in a tutorial on making public maps from private data.


text:
Q: SCSS image with overlay not displaying I am building a front-end template with SCSS being compiled with web pack. I created a jumbotron that has an image and gave it an overlay which displays properly, but upon giving an overlay an opacity of 0.8, none of the elements (the image and the dark overlay) displays on the browser.
Note: the code works until I made it an RGBA and added opacity, then it stopped displaying
the SCSS code below:
.section {
  // position: relative;

  &-jumbotron {
    height: 40rem;
    background-image: linear-gradient(to right bottom, rgba(var(--color-grey-dark-1), 0.8), rgba(var(--color-grey-dark-5), 0.8)),
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
  }
}

the variables are written in the root folder is:
:root {
  --color-grey-dark-1: #333333;
  --color-grey-dark-5: #222222;
}

A:

:root {
  --color-grey-dark-1: #333333;
  --color-grey-dark-5: #222222;
}

.section {
  &-jumbotron {
    height: 40rem;
    background-image: linear-gradient(to right bottom, var(--color-grey-dark-1), var(--color-grey-dark-5));
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
  }
}

Or if the colors need to be rgba you can do like this:

:root {
  --color-grey-dark-1: 51, 51, 51;
  --color-grey-dark-5: 34, 34, 34;
}

.section {
  &-jumbotron {
    height: 40rem;
    background-image: linear-gradient(to right bottom, rgba(var(--color-grey-dark-1), 0.5), rgba(var(--color-grey-dark-5)));
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
  }
}

A: I am glad that you have already received an answer that works, but I have to ask: since you are already using SCSS, why not using the variables it provides instead of regular CSS variables?
The syntax is a little bit cleaner and you wouldn't have to worry about browser support.
example:
(Note that you can define SCSS variables wherever you want. Although, it would be preferable to have them in a separate file).
  $color-grey-dark-1: rgb(51, 51, 51);
  $color-grey-dark-5: rgb(34, 34, 34);

.section {
  &-jumbotron {
    height: 40rem;
    background-image: linear-gradient(to right bottom, rgba($color-grey-dark-1, 0.8), rgba($color-grey-dark-5, 0.8));
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
  }
}

P.S. Some additional reading related to your question: Use CSS variables with rgba for gradient transparency


text:
Q: AudioRecorder in Android Error Invalid buffer size I need to record and play audio simultaneously and i use the help of 2 threads for it.here is the code
recorder = new AudioRecord(AudioSource.MIC, 8000,
            AudioFormat.CHANNEL_CONFIGURATION_MONO,
            AudioFormat.ENCODING_PCM_16BIT, bufferSize);

    if (recorder.getState() == android.media.AudioRecord.STATE_INITIALIZED)
        recorder.startRecording();
    isRecording = true;
    audioPlayer = new AudioTrack(AudioManager.STREAM_MUSIC, 8000,
            AudioFormat.CHANNEL_CONFIGURATION_MONO,
            AudioFormat.ENCODING_PCM_16BIT, bufferSize,
            AudioTrack.MODE_STREAM);

    audioPlayer.play();
    new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
             while(true)
             {
            readBytes = recorder.read(data, 0, bufferSize);
            if (readBytes == AudioRecord.ERROR_INVALID_OPERATION)
                System.out.println("ERROR_INVALID_OPERATION");
            else if (readBytes == AudioRecord.ERROR_BAD_VALUE)
                System.out.println("ERROR_BAD_VALUE");

            }

        }
    }).start();
    new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (readBytes > 0)
                audioPlayer.write(data, 0, readBytes);
        }
    }).start();

I get the error below:
02-23 14:19:59.625: E/AudioTrack(1786): Invalid buffer size: minFrameCount 2400, frameCount 2048
Thanks in advance

A: Try like this
            int MIN_BUF_SIZE_REC = AudioRecord.getMinBufferSize(8000,
                    AudioFormat.CHANNEL_CONFIGURATION_MONO,
                    AudioFormat.ENCODING_PCM_16BIT);
            AudioRecord recorder = new AudioRecord(
                    MediaRecorder.AudioSource.MIC, 8000,
                    AudioFormat.CHANNEL_CONFIGURATION_MONO,
                    AudioFormat.ENCODING_PCM_16BIT, MIN_BUF_SIZE_REC);

A: This the code i used to solve the issue hope it helps
public class Chat extends Activity {
Devc devc;
byte[] bytesent, bytesgot;
private BluetoothSocket mmSocket = null;
private InputStream mmInStream;
private OutputStream mmOutStream;
Handler handler;
Button send;
TextView getmessage;
EditText sentmessage;
TextView nowsentmessage;
TextView you;
int bytes = 0;
Thread thread;
private int audioSource = MediaRecorder.AudioSource.MIC;
private int samplingRate = 44100; /* in Hz */
private int channelConfig = AudioFormat.CHANNEL_CONFIGURATION_MONO;
private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
private int bufferSize = AudioRecord.getMinBufferSize(samplingRate,
        channelConfig, audioFormat);
private int sampleNumBits = 16;
private int numChannels = 1;
AudioTrack audioPlayer;
AudioRecord recorder;
Boolean isRecording;
byte[] bytes2;

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat);
    getmessage = (TextView) findViewById(R.id.gottext);
    sentmessage = (EditText) findViewById(R.id.entertext);
    nowsentmessage = (TextView) findViewById(R.id.metext);
    you = (TextView) findViewById(R.id.you);
    send = (Button) findViewById(R.id.sent);
    bufferSize += 2048;
    recorder = new AudioRecord(audioSource, samplingRate, channelConfig,
            audioFormat, 44100);

    audioPlayer = new AudioTrack(AudioManager.STREAM_MUSIC, 44100,
            AudioFormat.CHANNEL_CONFIGURATION_MONO,
            AudioFormat.ENCODING_PCM_16BIT, bufferSize,
            AudioTrack.MODE_STREAM);

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            // display each item in a single line
        }
    };
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    mmSocket = Devc.bluetoothSocket;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

    // Get the input and output streams, using temp objects because
    // member streams are final
    try {
        tmpIn = mmSocket.getInputStream();
        tmpOut = mmSocket.getOutputStream();
    } catch (IOException e) {
    }

    mmInStream = tmpIn;
    mmOutStream = tmpOut;

    new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            recorder.startRecording();
            isRecording = true;
            while (true) {
                int readBytes = 0;
                readBytes = recorder.read(bytesent, 0, bufferSize);
                if (readBytes > 0) {
                    write(bytesent);
                    bufferSize += 2048;
                }

            }

        }
    }).start();
    new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub\
            while (true) {
                int readBytes = 0;
                try {
                    bytes = mmInStream.read(bytesgot);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                audioPlayer.write(bytesgot, 0, bytes);
                audioPlayer.play();

            }
        }
    }).start();

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    try {
        mmInStream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        mmOutStream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    cancel();
}

public void write(byte[] bytes) {
    try {

        mmOutStream.write(bytes);
        mmOutStream.flush();
    } catch (IOException e) {
    }
}

public void cancel() {
    try {
        mmSocket.close();
    } catch (IOException e) {
    }
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    cancel();
    thread.stop();
    Chat.this.finish();
    // thread.stop();
}

}

A: Check this out..i have solved same problem using this code.....
As well as I created two two inner classes for record and playback ( RecordAudio calss and PlayAudio class).
If you want more clear audio clip you can use android NoiseSuppressor .
cheers....:D
public class AltAudioRecorder extends Activity implements OnClickListener {

RecordAudio recordTask;
PlayAudio playTask;
Button startRecordingButton, stopRecordingButton, startPlaybackButton,
        stopPlaybackButton;
TextView statusText;
File recordingFile;
boolean isRecording = false;
boolean isPlaying = false;

int frequency = 8000;
int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    statusText = (TextView) this.findViewById(R.id.StatusTextView);
    startRecordingButton = (Button) this
            .findViewById(R.id.StartRecordingButton);
    stopRecordingButton = (Button) this
            .findViewById(R.id.StopRecordingButton);
    startPlaybackButton = (Button) this
            .findViewById(R.id.StartPlaybackButton);
    stopPlaybackButton = (Button) this.findViewById(R.id.StopPlaybakButton);
    startRecordingButton.setOnClickListener(this);
    stopRecordingButton.setOnClickListener(this);
    startPlaybackButton.setOnClickListener(this);
    stopPlaybackButton.setOnClickListener(this);
    stopRecordingButton.setEnabled(false);
    startPlaybackButton.setEnabled(false);
    stopPlaybackButton.setEnabled(false);

    File path = new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath()
            + "/FinalOne/src/com/example/finalone/files/");
    path.mkdirs();
    try {
        recordingFile = File.createTempFile("recording", ".pcm", path);
    } catch (IOException e) {
        throw new RuntimeException("Couldn't create file on SD card", e);
    }
}

@Override
public void onClick(View v) {
    if (v == startRecordingButton) {
        record();
    } else if (v == stopRecordingButton) {
        stopRecording();
    } else if (v == startPlaybackButton) {
        play();
    } else if (v == stopPlaybackButton) {
        stopPlaying();
    }
}

public void play() {
    startPlaybackButton.setEnabled(true);
    playTask = new PlayAudio();
    playTask.execute();
    stopPlaybackButton.setEnabled(true);
}

public void stopPlaying() {
    isPlaying = false;
    stopPlaybackButton.setEnabled(false);
    startPlaybackButton.setEnabled(true);
    }

public void record() {
    startRecordingButton.setEnabled(false);
    stopRecordingButton.setEnabled(true);
    // For Fun
    startPlaybackButton.setEnabled(true);
    recordTask = new RecordAudio();
    recordTask.execute();
    }
public void stopRecording() {
    isRecording = false;
    }


text:
Q: Read text file and move only those files to another folder I have a folder filled with 100 log files, some of them have data, some dont. I have a script that picks out the files with the data and have the names saved in a text file named "goodfiles.txt" I would like to know how i can read the files in the text file and move them to another folder. I have tried this: cat /root/testing2/goodfiles.txt | xargs mv -f /root/testing2/moved/ but it gives me an error saying
mv: Target (log1508.log) must be a directory in order to move
mv: directories or multiple files to it.
can someone please help me?

A: This is a slightly different, but conceptually simple approach (avoiding pipes):
for fileName in `cat goodfiles.txt`; do mv $fileName /root/testing2/moved/; done

A: I think it helps to remember that you can change the part that  xargs replaces using the --replace option and specify the replacement string.  Otherwise it appends the line on the end.
I was able to do roughly the same with
cat filelist |xargs --replace='{}' mv {} ./targetdir/

For you
maybe try
cat /root/testing2/goodfiles.txt |xargs --replace '{}' /root/testing2/moved

A: It looks like you're confusing the -f option of GNU mv with the -t option, which is what you want here in order to move multiple sources to a single target with xargs
   mv [OPTION]... -t DIRECTORY SOURCE...

Note that plain xargs breaks input into whitespace delimited arguments, so your command would break if any of the filenames contains whitespace. Also it is a UUOC.
So
xargs -d'\n' mv -t /root/testing2/moved/ </root/testing2/goodfiles.txt


text:
Q: How to ssh within iPython notebook? I'm attempting to SSH within an ipython notebook as follows:
%%bash

ssh myserver.something.com

However, I receive the following error:
Pseudo-terminal will not be allocated because stdin is not a terminal.

How can I SSH within an iPython notebook?

A: Use ssh -t or ssh -tt in order to force pseudo-tty allocation even if stdin is not a terminal.

A: If I understand the question, you are asking how to run a terminal from within a cell that can show the feedback from the commands given.
If this is what you are looking for then first go to your main tree at http://localhost:8888/tree and open a new terminal by clicking the new button on the right side of the screen and then Terminal. This will open a terminal at http://localhost:8888/terminals/1

While this will probably be enough for most people, if you want your terminal to be in-line you can use IFrame to show your Terminal within a cell by directing it to http://localhost:8888/terminals/1 where your terminal is located.
from IPython.display import IFrame
IFrame("http://localhost:8888/terminals/1", 900, 500)

or
%%html
<iframe src="http://localhost:8888/terminals/1", width=900, height=500></iframe>

You will now have an active in-line terminal that you can use to ssh or run any other commands


text:
Q: Split a list Python Hello I have a list containing one string that I need to split in two on the comma:
value = ['Red, Orange']

I split using :
value = value[0].split(", ")

But I get :
value[0] = "Red"

and
value[1:] = ["Orange"]

why is value[1:] a list? What can I do to get
value[1:] = "Orange"

Thanks

A: You simply do:
value[1]

without the :. This indicates to python that you are getting an element at a specific index and not a portion of the string from index 1 to the last element.
value[0] will contain "Red"
and
value[1] will contain "Orange"
What you are doing with the [:] is known as list slicing. Perhaps you should read about it so that it is clear.

A: You may write this:
value = [x for x in value[0].split(", ")]
It's called list comprehension and it will work for arbitrary number of words in value[0]


text:
Q: Order by clause, huge performance drop I run the following query:
SELECT A.ID, A.CODE, A.NAME, (SUBQUERY CALCULATING SALES)
FROM PRODUCTS A
JOIN PRODUCTSALES B ON A.ID = B.ID

The query returns 250 rows in less than a second. If I add in the end ORDER BY A.CODE or ORDER BY A.NAME the query returns in 20 seconds.
I cannot understand why it takes so long to sort 250 rows of data. This behavior is absent if the order column is an integer like A.ID.

A: The reason is because you are forcing SQL Server to return the rows in an order.

*

*Sorts can be expensive as it consumes much of the joined tables before operations can be performed

*Clustered/nonclustered indexes already provide an order by of some sort, so the optimizer can be sure of the order.
Normally, SQL Server just grabs the first 250 rows that match without any concern for order or sequential rows and it is done with the Query.
But since you are now insisting the first 250 rows be returned with a specific order, the Optimizer must now use a sort operation between the tables before grabbing the 250 requested rows.
This is why you are seeing the performance hit, since SQL Server must now load much of this matched tables into memory to process.
As for why you do not notice this on the ID column, that is because the order is at least based on a clustered index, so there already is a guaranteed sort order of some kind, so the Optimizer need not load as much to get to 250 rows.


text:
Q: Using helpers from mounted engine in parent Rails app I mounted engine to the application, and I want to use one of the engine's helper all over the parent application.
In my Dummy app I put this in Dummy's application_controller.rb:
class ApplicationController < ActionController::Base
  include Sourcebuster::CookieSettersHelper
  before_filter :set_sourcebuster_data
  helper_method :extract_sourcebuster_data

  private

    def set_sourcebuster_data
      set_sourcebuster_cookies
    end

end

And it was ok.
But when I mounted it to the real app, helper from engine just don't work.
How to load it, so it can do the stuff all over the parent app?

A: Got it.
I tried to set_sourcebuster_data inside namespaced engine (http://lvh.me:3000/sourcebuster).
before_filter in application's application_controller.rb don't work in this case.
Added it to engine's application_controller.rb, now it's doing the stuff all over the app)


text:
Q: Loading partial in a popup, what is the right way to go about it? Ok. In the users controller, on the show page, I have this
:

Also, on the users page, I have this:
<% @photos.each do |p| %>
<%=  link_to image_tag(p.image(:medium)), photo_path(p), remote: true %>
<% end %>

The above link is suppose to take the user to the photo controller's show action (_show.html.erb) which shows a larger version of the image. I would like to load this as a partial inside the
 with the id #picshow in the user page, using ajax, while making it look like a popup.
I created a show.js.erb inside of the photos directory...
$('#picshow').html('<%=j render partial: 'photos/show' %>')
loadPopup()

And I am also calling this function that I have in my application.js file so that it makes it look like a popup that fades in....FYI, fadecontent is another div I have inside the user show, which should make everything behind the popup faded.
var popupStatus = 0;

function loadPopup() {
    if(popupStatus==0) {
        $(".fadecontent").fadeIn("slow");
        $(".largepic").fadeIn("slow");
        popupStatus = 1;
    }
}

function disablePopup() {
    if(popupStatus==1) {
        $(".fadecontent").fadeOut("slow");
        $(".largepic").fadeOut("slow");
        popupStatus = 0;
    }
}

This is the photo's show controller and action:
def show

@photo = Photo.find(params[:id])
  respond_to do |format|
  format.js
    end
 end

This is what I have in the _show.html.erb in the photos controller

        <%=image_tag @photo.image(:large) %>

This is the CSS
.largepic {
    position: absolute;
    z-index: 10;
    margin: 125px auto;
    left: 15px;
    width: 930px;
    display: none;
    overflow: hidden;
    background: #ffffff;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}

.largeimage {
    padding: 18px;
}

.largeimage p {
    font-size: 75%;
    line-height: 19px;
    width: 450px;
}

Basically, I want the partial of photos/show to render as a partial in the div with the id of "picshow" while looking like a popup that can be escaped or xed out of. It has no display by default. The fadeIn in the loadPopup function makes it show.

A: Since you've mentioned that AJAX is your main concern, here is a working example.  This example initially loads the smaller image.  Upon clicking the smaller image, uses AJAX to load the larger image and on escape key resets the photo back to smaller image.  You should be able to modify it to achieve your goal.
app/views/photos/index.html.erb

    <%= render partial: 'photos/photo_image', locals: { width: 50, height: 64 } 5>

app/views/photos/_photo_image.html.erb
<%= link_to image_tag('rails.png', width: "#{width}", height: "#{height}", photo_path(1), remote: true %>

app/views/photos/show.js.erb
$('#photo-image').html("<%= escape_javascript(render partial: 'photos/photo_image', locals: { width: '110', height: '128' }) %>")

$(document).keyup(function(evt) {
    if (evt.keyCode == 27) {
        $('#photo-image').html("<%= escape_javascript(render partial: 'photos/photo_image', locals: { width: '50', height: '64' }) %>")
    }
});

app/controllers/photos_controller.rb
class PhotosController < ApplicationController
    def show
        respond_to do |format|
            format.js
        end
    end
end

I hope this solves your problem.  Please comment if you need any explanation.
Update: Your question has "Loading partial in a popup" but no where in your description you say "popup".  If you'd like to display the partial on popup, you would need to update the app/views/photos/show.js.erb.  I hope you will figure that one out.


text:
Q: Serializing an EnumerableRowCollection into a JSONResult I have the following method which is supposed to return a JSONResult so I can use it in an AJAX method with javascript and load autocomplete suggestions for a textbox. I will load this everytime a particular dropdown list changes.
[AcceptVerbs(HttpVerbs.Post), Authorize]
    private JsonResult GetSchemaNodeValues(string SchemaNodeId)
    {
        var query = @"Select ld.""Value""
        From ""LookupData"" ld, ""SchemaNode"" sn
        Where sn.""LookupTypeId"" = ld.""LookupTypeId""
        And sn.""SchemaNodeId"" = '{0}'";

        DataSet data = new DataSet();

            data = ServiceManager.GenericService.ExecuteQuery(String.Format(query, SchemaNodeId)).Data;

        var res = data.Tables[0].AsEnumerable().Select(dr => new
        {
            Value = dr["Value"].ToString()
        });

        return JsonConvert.SerializeObject(res);

    }

I get the following error under return JsonConvert.SerializeObject(res);
Error   106 Cannot implicitly convert type 'string' to 'System.Web.Mvc.JsonResult'

Is there any way to get past this?
Before this I tried using System.Web.mvc.Controller.Json(res); which returns a JSONResult from an object.
But I couldn't use it because my class is a PageDialog not a Controller so it doesn't have access to Controller's protected internal methods like JSon(). The error I got was that JSon() is inaccessible due to its protection level. The Controller class was locked and I can't make it public or create a workaround so I changed the approach using JsonConvert.SerializeObject(res);
Any suggestions would be extremely welcome.

A: private dynamic GetSchemaNodeValues(string SchemaNodeId)
{
    ...
    return data.Tables[0].AsEnumerable().Select(dr => new
    {
        Value = dr["Value"].ToString()
    });
}

or
private string GetSchemaNodeValues(string SchemaNodeId)
{
    ...
    var result = data.Tables[0].AsEnumerable().Select(dr => new
    {
        Value = dr["Value"].ToString()
    });
    return JsonConvert.SerializeObject(result);
}


text:
Q: (psuedo) Randomly generated Matrix I want to create a matrix using the following arrays:
A = [1111,2222,3333]
B = [20,25,26,27]
C = [1.5,2.6,3.7,4.5,5.4,6.7,7.2,8.8,9.0,10.0,11.0,12.2]

Each value in A need to be mapped to all values in be once (each element in A will be attached to all four values in b) and from there, I want the resulting 12,2 matrix to become a 12,3 matrix by adding array C
It should look like the following:
1111 20 1.5
1111 25 2.6
1111 26 3.7
1111 27 4.5
2222 20 5.4
2222 25 6.7
2222 26 7.2
2222 27 8.8
...........
3333 27 12.2

My first idea is to use a couple for loops, but I'm having a lot of trouble implementing the values in the 1st column
In my actual code the values will be assign as follows:
A = [random.randint(1250,14180) for x in range(len(5))]
C = [round(random.uniform(1.0,4.0),1) for x in range(len(15))]

B will be non random
B = [2000,2500,2600,2700]

A: Have a look at :
weights_h = [[random.random() for e in inputs[0]] for e in range(hiden_neurons)]

But really, you should probably use numpy.
In [9]: numpy.random.random((3, 3))
Out[9]:
array([[ 0.37052381,  0.03463207,  0.10669077],
       [ 0.05862909,  0.8515325 ,  0.79809676],
       [ 0.43203632,  0.54633635,  0.09076408]])

From:
Simple way to create matrix of random numbers

A: You may use the itertools package
import itertools

A = [1111,2222,3333]
B = [20,25,26,27]
C = [1.5,2.6,3.7,4.5,5.4,6.7,7.2,8.8,9.0,10.0,11.0,12.2]

# create the product of A and B, i.e., [(1111,20), (1111,25), ..., (3333,27)]
AB = itertools.product(A,B)

# zip with C
ABC = itertools.izip( AB, C )

# flatten sublists, since ABC is an iterator for [((1111,20),1.5), ..., ((3333,27),12,2)]
ABC = [ list(ab)+[c] for ab,c in ABC ]

print ABC

which gives
[[1111, 20, 1.5],
 [1111, 25, 2.6],
 [1111, 26, 3.7],
 [1111, 27, 4.5],
 [2222, 20, 5.4],
 [2222, 25, 6.7],
 [2222, 26, 7.2],
 [2222, 27, 8.8],
 [3333, 20, 9.0],
 [3333, 25, 10.0],
 [3333, 26, 11.0],
 [3333, 27, 12.2]]


text:
Q: Magento 2 Add to Cart : Performance testing using Jmeter We are doing performance testing on Magento 2 platform.
How should we include following URL in jMeter script
cart/ad/uenc/aHR0cHM6Ly9wcm9kLWFiYm90dC1zdG9yZS1leHRlcm5hbC1hbGIuYWJib3R0c3RvcmUuY29tLzE0LTFvemNhbi1jYXNlb2Y2LTU1MjUxLmh0bWw,/product/153/

A: You should extract this URL from a product page.
For example, see benchmark.jmx used by Magento Performance Team to measure Magento performance

A: If you want to add this in "Add to cart" request, then you don't need to add this. As you can simply add the products to the cart without adding the "uenc" to your request URL.


text:
Q: Share Count in Android I want to implement number of share count in my post. When a user clicks the share button and shares the post URL to multiple persons using another platform I want to have all the number of shares done by every user for that particular post.
Hunted several things on internet but can't fetch any feasible solution any language JAVA or KOTLIN will be preferred for solution. My posts is in the recycler view.
I tried to search for number of counts but Internet is flooded with how to share the post but not how to count the number of shares done for that particular post. Half of the time searching share comes up with solution of stock market


text:
Q: How many numbers $\in [1 .. 10^9]$ that are not of the form $ x^2, x^3$ or $x^5$? We've started with $x^2$, saying that there are $\sqrt{10^9}$ numbers that are not $\in 10^9$
i'm thinking that if we add $\sqrt[3]{10^9}$ and $\sqrt[5]{10^9}$ to $\sqrt{10^9}$ and subtract them from $10^9$, we would have gone too far and excluded too many numbers due to repeating numbers such as $2^2$,$2^3$ and $2^5$, for example.
does it even make sense to do so? aren't all numbers in $\sqrt[3]{10^9}$ and $\sqrt[5]{10^9}$ $< 10^9$ already in $\sqrt{10^9}$ ?

A: Let $a=10^9$. There are $\lfloor a^{1/2} \rfloor$ squares, $\lfloor a^{1/3}\rfloor$ cubes and $\lfloor a^{1/5}\rfloor$ $5^{th}$ powers within $1$ to $10^9$. So, the P.I.E. gives the answer to be:  $a-(\lfloor a^{1/2}\rfloor+\lfloor a^{1/3}\rfloor+\lfloor a^{1/5}\rfloor-\lfloor a^{1/6}\rfloor-\lfloor a^{1/10}\rfloor-\lfloor a^{1/15}\rfloor+\lfloor a^{1/30}\rfloor)$.


text:
Q: Integrating jQuery Image Crop into Wordpress for avatar image upload I am trying to use this plugin with my wordpress site, but have had little success.
I can select the image, and use the square select tool to make a selection. The problem arises when I try to add this cropped selection to my already existing form where I upload my avatar image. When I click submit, I am directed to a "404 page not found" page.
Obviously I have included all the accompanying scripts and have checked with Firebug that they have loaded correctly.
Here is what I have done:
<?php
    if (isset($_POST["registration_form_submit"])) {

    $counting_faults = 0;

    if ($counting_faults == 0) {

    $account_settings_displayname = preg_replace("/\s+/", " ", $_POST["account_displayname"]);
    $account_settings_displayname = str_replace("@", "", $account_settings_displayname);

    /* Enter the values into WordPress DB */
    $generate_user = wp_update_user(
                    array(
                                    'ID' => $current_user_data->data->ID,
                                    'display_name' => $account_settings_displayname,
                                    'user_email' => preg_replace("/\s+/", " ", $_POST["account_email"]),
                                    'first_name' => preg_replace("/\s+/", " ", $_POST["account_fullname"]),
                                    'description' => mysql_real_escape_string(trim($_POST["account_bio"]))
                    )
                    );

    $outcome = @array_shift(array_values($generate_user->errors));
    }

    /**
    * ******** Avatar image upload starts here *********
    */
    if (isset($_FILES["file_name"]["name"]) && $_FILES["file_name"]["name"] != "") {

    $user_id = $current_user->ID;

    /* Create the uploads folder if it doesn't exist */
    $directory_name = "wp-content/uploads/" . date("Y") . "/";
    if (! is_dir($directory_name)) {
            mkdir($directory_name, 0755);
    }

    $directory_name = "wp-content/uploads/" . date("Y") . "/" . date("m") . "/";
    if (! is_dir($directory_name)) {
            mkdir($directory_name, 0755);
    }
    $filename = $directory_name . basename($_FILES["file_name"]["tmp_name"]) . "-" . $_FILES["file_name"]["name"];

    echo $filename;

    $uploaded_file = move_uploaded_file($_FILES["file_name"]["tmp_name"], $filename);

    /* The part I need your help with -- Stars here */

    $valid_exts = array('jpeg', 'jpg', 'png', 'gif');
    $max_file_size = 200 * 1024; #200kb
   $nw = $nh = 200; # image with # height

    $ext = strtolower(pathinfo($_FILES['file_name']['tmp_name']));
    echo 'ext'.$ext;
    if (in_array($ext, $valid_exts)) {
            $path = 'uploads/' . uniqid() . '.' . $ext;
            $filename = $filename;
            $size = getimagesize($_FILES['file_name']['tmp_name']);

            $x = (int) $_POST['x'];
            $y = (int) $_POST['y'];
            $w = (int) $_POST['w'] ? $_POST['w'] : $size[0];
            $h = (int) $_POST['h'] ? $_POST['h'] : $size[1];

            $data = file_get_contents($_FILES['file_name']['tmp_name']);
            $vImg = imagecreatefromstring($data);
            $dstImg = imagecreatetruecolor($nw, $nh);
            imagecopyresampled($dstImg, $vImg, 0, 0, $x, $y, $nw, $nh, $w, $h);
            imagejpeg($dstImg, $filename);
            imagedestroy($dstImg);
            echo "";

    }

    /* The part I need your help with -- ends here */

    /* Upload the image to WP structure */
    $wp_filetype = wp_check_filetype(basename($filename), null);

    $wp_upload_dir = wp_upload_dir();

    $attachment = array(
                    'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
                    'post_mime_type' => $wp_filetype['type'],
                    'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
                    'post_content' => '',
                    'post_status' => 'inherit'
    );

    $attach_id = wp_insert_attachment($attachment, $filename);
    require_once ('wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
    wp_update_attachment_metadata($attach_id, $attach_data);
    delete_user_meta($user_id, 'wp_user_avatar');
    add_post_meta($attach_id, '_wp_attachment_wp_user_avatar', $user_id, true);
    add_user_meta($user_id, 'wp_user_avatar', $attach_id, true);
    }

    /**
    * ******** Avatar image upload ends here *********
    */
    ?>

    <form method="post" action="" name="account" id="account"   enctype="multipart/form-data">

Profile Image

<?php  echo get_avatar( $current_user->user_email, 100 ); ?>

                    <input type="hidden" id="x" name="x" />
                    <input type="hidden" id="y" name="y" />
                    <input type="hidden" id="w" name="w" />
                    <input type="hidden" id="h" name="h" />
                    <input id="uploadImage" type="file" accept="image/jpeg" name="file_name" />

                    <input class="btn" type="submit"
                            name="registration_form_submit" value="Update" />

    </form>

A: In this line, is your action="" actually/intentionally blank? Your form may be trying to call a non-existent page:
<form method="post" action="" name="account" id="account"   enctype="multipart/form-data">


text:
Q: Valgrind : Conditional jump or move depends on uninitialised value(s) occurs even I initializing the memory I am very struggle to solve this problem.
 After I initializing a allocated memory, valgrind said that "conditional jump or move depends on uninitialised value".
So, here is my code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
    int st_a;
    int st_b;
    char st_c:
    char st_d:
} TEST_ST;

int inner_func(int *a, TEST_ST *st_a)
{
    //memset(st_a, 0, sizeof(TEST_ST));
    if(a[0] > 0)
    {
        printf("inner_func: bigger than zero\n");
    }
    else
    {
        printf("inner_func: else\n");
    }

    st_a->st_a = 1;
}

int main()
{
    int *a;
    int *b;
    TEST_ST *st_a;

    a = (int *)malloc(sizeof(int) * 10);
    b = (int *)malloc(sizeof(int) * 10);
    memset(a, 0, sizeof(int) * 10);
    //memset(b, 0, sizeof(int) * 10);

    st_a = (TEST_ST *)malloc(sizeof(TEST_ST));

    a[0] = 1;

    if(a[9] > 0)
    {
        printf("Bigger than zero\n");
    }
    else
    {
        printf("Smaller than zero or equal\n");
    }

    inner_func(b, st_a);

    free(st_a);
    free(b);
    free(a);

    return 0;
}

And here is a valgrind logs.

I don't understand why valgrind said like the first line in the picture.
Anybody can help me?

A: The value you're reading was not in fact initialized.
The line in question is in the function inner_func:
if(a[0] > 0)

The a is as parameter to the function, which was called like this:
inner_func(b, st_a);

So a in the function is the same as b in main.  b points to memory returned by malloc, but that memory is never initialized.
Uncomment the line where you call memset on b.

A: Run valgrind like this and post results i'll edit with the answer but this should pinpoint where is the error:
valgrind --tool=memcheck --track-origins=yes <program_path>

A: You have assigned "char st_c:" and "char st_d:" change it to ';' instead of ':'


text:
Q: Excel - Modifying Field Value Based on Newest Field Update I'm creating a spreadsheet that will help us keep track of how many accounts are sold for that day of the month. For instance, say A1 has a value of 1, A2 has a value of 2, but then A3 reduces back to 1 because a client cancelled our service. We added one account and subtracted one account, so I would want the net number of accounts for that month to display in A30.
Is there a basic formula I can use to make this possible?

A: It sounds like your A column is calculating a running total as it is, if it increments by each sale and decrements for each cancellation, you would then just use this formula in cell A30
=INDEX(A1:A29, COUNTA(A1:A29), 1)

You could simply put in each row the number of accounts sold i.e. 1, 2 etc. and for cancellations -1, then you would just need to use
=SUM(A1:A29)

in A30 to show the net value for the day.


text:
Q: Like operator showing ERROR on SQL variable declare @schoolName varchar(max) = 'children's Garden'

select * from schools where Schoolname like @schoolName+'%'

This is my SQL query. When I store a string with an apostrophe there is error. How can I overcome this?
The variable @schoolName is coming from the code.

A: Use double apostrophes to make it valid SQL String :
declare @schoolName varchar(max) = 'children''s Garden'

select s.*
from schools s
where s.Schoolname like @schoolName + '%'


text:
Q: Observer for Sugar Orm I need to use an observer that is called when my database was modified. This exists natively with Android cursor.
It is a LoaderCallback.
How can I use this with SugarOrm? Does anyone have any examples?


text:
Q: How to find the force of the compression at the core of a planet? For example the core of the planet Jupiter, how to find out the magnitude of the force that compresses its core? and can that be thought of as the total force that holds the planet together?

A: Model the planet as an incompressible material with constant density $\rho$ and radial pressure $p(r)$ for $0\leq r\leq R$, where $R$ is the radius of the planet. The force per unit volume due to pressure is given by
$$F_p=-\nabla p(r).$$
Meanwhile, the force per unit volume due to gravity at a depth $r$ is given by Newton's law:
$$F_g=\frac{G\rho\left(\frac{4}{3}\pi r^3\rho\right)}{r^2}=\frac{4}{3} \pi  G \rho ^2 r.$$
Setting $F_p=F_g$ and integrating to find $p(r)$ along with the condition $p(R)=0$ yields
$$p(r)=\frac{2}{3} \pi  G \rho ^2 \left(R^2-r^2\right).$$
Note that the pressure is actually highest at the core, and that as you travel towards the surface, it decreases quadratically to zero. The core pressure is $p(0)=\frac{2}{3}\pi G \rho ^2 R^2$.
For nonconstant $\rho$ the answer will be slightly different, but the concept is the same.


text:
Q: Java GUI: Display Area and 8 buttons I would like to have a display area and 8 buttons.
Each Button Will display different text in the display Area.
Currently I just have the Display Area, but When I try to add A button the button overlaps the Display area.
So how can I have a display area and 8 buttons.
JPanel middlePanel = new JPanel ();
middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Display Area" ) );

// create the middle panel components

JTextArea display = new JTextArea ( 16, 58 );
display.setEditable ( false ); // set textArea non-editable
JScrollPane scroll = new JScrollPane ( display );
scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );

//Add Textarea in to middle panel
middlePanel.add ( scroll );

// My code
JFrame frame = new JFrame ();
JFrame btn  = new JFrame();
frame.add ( middlePanel );
frame.pack ();
frame.setLocationRelativeTo ( null );

JButton one = new JButton("1");
JPanel panel = new JPanel();
panel.add(one);
//btn.getContentPane().add(BorderLayout.CENTER,panel);
btn.setVisible(true);
frame.setVisible ( true );

A: Use two containers, one for the text area and one for the buttons, each with their own layout managers...
JPanel middlePanel = new JPanel (new BorderLayout());
middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Display Area" ) );

JTextArea display = new JTextArea ( 16, 58 );
display.setEditable ( false ); // set textArea non-editable
JScrollPane scroll = new JScrollPane ( display );
scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );

middlePanel.add ( scroll );

JPanel buttonPane = new JPanel(); // FlowLayout by default...
buttonPane.add(...); // Add your buttons here...

JFrame frame = new JFrame ();
frame.add ( middlePanel );
frame.add(buttonPane, BorderLayout.SOUTH);
frame.pack ();
frame.setLocationRelativeTo ( null );
frame.setVisible(true);

This is commonly known as compound layouts ;)

A: JPanel middlePanel = new JPanel ();
    middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Display Area" ) );

    // create the middle panel components

    JTextArea display = new JTextArea ( 16, 58 );
    display.setEditable ( false ); // set textArea non-editable
    JScrollPane scroll = new JScrollPane ( display );
    scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );

    //Add Textarea in to middle panel
    middlePanel.add ( scroll );
    JPanel buttonPane = new JPanel(); // FlowLayout by default...
    buttonPane.add(new JButton("1")); // Add your buttons here...
    buttonPane.add(new JButton("2"));
    buttonPane.add(new JButton("3"));
    buttonPane.add(new JButton("4"));
    // My code
    JFrame frame = new JFrame ();
    JFrame btn  = new JFrame();
    frame.add ( middlePanel );
    frame.add(buttonPane,BorderLayout.SOUTH);
    frame.pack ();
    frame.setLocationRelativeTo ( null );

    //btn.getContentPane().add(BorderLayout.CENTER,panel);
    btn.setVisible(true);
    frame.setVisible ( true );


text:
Q: java.lang.NoClassDefFoundError: javassist.util.proxy.Proxy I am getting the error java.lang.NoClassDefFoundError: javassist.util.proxy.Proxy in my app. I am using javassist version 3.12.1.GA in my app, but it does not contain this class. Does anyone know where I can download a version of the javassist JAR that has the javassist.util.proxy.Proxy class?
Thanks in advance for the help.

A: javassist.util.proxy.Proxy is available in the version 3.16.1-GA of javassist,
which can be downloaded from here.

A: u can find depency jar in Apache Central Maven Repository ,Go into the site and type javaassist in search area then u`ll see the jar list.


text:
Q: Labeling plots with images in Matlab Is there any way of labeling plots with images. For example, when I use the following:
plot(Y(:,1),Y(:,2),'o','LineWidth',2);

gname(names)

I can label each dot in a plot with a name. Is there any way to insert images instead of names?

A: It is possible, but not as convenient as gname by far. You can use the low-level version of image to insert images in your plot at arbitrary positions. Here's a simple example which puts the "Mandrill" image that comes with Matlab with its upper left corner pixel at the position (pi/2, 0):
% example plot
x = linspace(0, 2*pi, 100);
plot(x, cos(x))

% insert image
load mandrill
colormap(map)
image('CData', X, 'XData', [pi/2, pi/2 + 0.5], 'YData', [0, -0.3])

The result looks like this:

Problems with this approach:

*

*There is no interactive point-and-click facility, you have to explicitly insert and position the image labels programmatically, or program such a point-and-click facility yourself. ginput might help doing so.

*A figure window can only have one associated color map. That means if you have different images, they either all have to use the same colormap or have to be truecolor images.

*Not just the position, but also the display size of the image has to be specified in the call to image, and both are by default specified with respect to the plot's coordinate system. This makes it hard to achieve the correct aspect ratio. You can switch (temporarily) to absolute units using the axes property 'Units' , but then you have to figure out the correct position in e.g. absolute millimeters or inches. Moreover, images are usually indexed with vertical coordinates increasing from top to bottom, while plots usually have vertical coordinates increasing from bottom to top. This is the reason for the negative value -0.3 in the 'YData' property above.
Alternatively, you can insert images each in their own little axes sitting on top of the plot's axes, which makes it easy to get the right orientation and aspect ratio using axis image. You'll still have the problem though to figure out the correct position for the axes.


text:
Q: How to save checkpoints of quantise wrapped models in tensorflow model optimization? Hi I am using tensorflow and model optimisations.
This is an overview of the process:
from tensorflow_model_optimization.quantization.keras import quantise_model
model = define_model()
qat_model = quantize_model(model)
qat_model.fit(...)
qat_model.save_weights("qat_weights.h5")
... Finish for Now ...

On another run
model = define_model()
qat_model = quantize_model(model)
qat_model.load_weights("qat_weights.h5")

But when I go to qat_model.fit(...) it has to start training again from 0%
So there must be a problem with either saving or loading of the weights


text:
Q: org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)) I am new to android and ArcGIS.
I am attempting to execute the ArcGIS HelloWorld sample application on a Motorola Zoom tablet running Android 4.1.2 (API 16).
The map layer inflate process fails consistently with the following error.  The application executes successfully with the Emulator:
07-30 13:30:31.850 15409-15433/com.example.scottbing.servicearea E/ArcGIS:
url =http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer
org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
at [Source: java.io.StringReader@421ec6b0; line: 1, column: 2]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1432)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:521)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportUnexpectedChar(JsonParserMinimalBase.java:442)
at org.codehaus.jackson.impl.ReaderBasedParser._handleUnexpectedValue(ReaderBasedParser.java:1198)
at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(ReaderBasedParser.java:485)
at com.esri.core.internal.io.handler.h.a(SourceFile:206)
at com.esri.core.internal.io.handler.h.a(SourceFile:227)
at com.esri.core.internal.io.handler.h.a(SourceFile:63)
at com.esri.core.internal.tasks.ags.t.a(SourceFile:39)
at com.esri.android.map.ags.ArcGISTiledMapServiceLayer.initLayer(SourceFile:156)
at com.esri.android.map.ags.ArcGISTiledMapServiceLayer$1.run(SourceFile:132)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)

I am using the base world streets map: http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer
It looks as though the map is being sent with some sort of invalid JSON characters.  Is there away to easily correct this issue?
I am using Android Studio.
Here is the MainActivity.java
package com.example.scottbing.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import com.esri.android.map.MapView;

public class MainActivity extends Activity {

    MapView mMapView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // after the content of this activity is set
        // the map can be accessed from the layout
        mMapView = (MapView)findViewById(R.id.map);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Here is the manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.scottbing.helloworld" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:configChanges="orientation|screenSize|uiMode" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Here is the project build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://esri.bintray.com/arcgis'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url 'https://esri.bintray.com/arcgis'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Here is the app build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 15
    buildToolsVersion '19.1.0'

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }

    packagingOptions{
        exclude 'META-INF/LGPL2.1'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
        debug {
            debuggable true
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.esri.arcgis.android:arcgis-android:10.2.8-1'
}

A: You're probably getting that error because you sent it an XML when it expected a JSON.


text:
Q: iOS 64bit requirement: what's the definition of "new apps" in this case? Apple has a deadline on 1st Feb for new iOS apps to be 64bit. As far as I can find, the entire requirement text is as follows:

Starting February 1, 2015, new iOS apps uploaded to the App Store must include 64-bit support and be built with the iOS 8 SDK, included in Xcode 6 or later. To enable 64-bit in your project, we recommend using the default Xcode build setting of "Standard architectures" to build a single binary with both 32-bit and 64-bit code.

https://developer.apple.com/news/?id=10202014a
What does this mean? Is there a precedent for what "uploaded" means? Does it cover apps created in itunes connect but not yet submitted? Or apps uploaded to the new testflight beta service? Or apps in submission but not yet approved? Or apps approved but not yet released? Are there any more in-depth docs on this?

A: I think "new" indicates the first version of an App to the AppStore.
While "update" indicates any subsequent versions.
I just posted an update which was only 32bit and did not get the arm64 warning.
but did see the warning on a new app about a month ago.
The deadline for updates is june 1st
https://developer.apple.com/news/?id=12172014b


text:
Q: Function in not defined in custom jquery when using href=javascript I am trying to setup slider. When i connect jquery library just as  and connect slider code just as  with no  require([ 'jquery', 'jquery/ui'], all works fine.
But when i try to connect script through magento jquery and delete link to jquery library, script won't work and shows error Uncaught ReferenceError: slide is not defined
Also when I am trying to connect custom jquery code via requirejs-config.js i got the same error.
So how make it works through right way (with no external jquery library)?
Here is part of HTML code:
LEFT

Jquery code:
      require([ 'jquery', 'jquery/ui'], function ($){

            function slide(direction) {
                    var slider_full_width = $('.slides_box li').outerWidth() + 28;

                    if (direction == 'left') {
                        var left_sliding = parseInt($('.slides_box').css('left')) + slider_full_width;
                    } else {
                        var left_sliding = parseInt($('.slides_box').css('left')) - slider_full_width;

                    }

                    $('.slides_box:not(:animated)').animate({'left': left_sliding}, 350, function () {
                        if (direction == 'left') {
                            $('.slides_box li:first').before($('.slides_box li:last'));
                        }
                        else {
                            $('.slides_box li:last').after($('.slides_box li:first'));
                        }
                        $('.slides_box').css({'left': '0'});
                    });
                }
          });

EDIT: I have an idea why it don't work. Because after adding requirement of magento jquery it render my custom code inside $(document).ready(function() {, but javascript href works only outside of ready function. Anyway i don't know how to fix this.

A: Try following way:

LEFT


text:
Q: PHP replace spaces, comma's, dashs and ! with forward slashes So far I have :
$q = str_replace(' ','/',$q);
$q = str_replace(',','/',$q);
$q = str_replace('\-','/',$q);

but I'm not sure what I'm doing wrong because none of the PHP sites that explain the functions, include an example of every character to search for.
Note, I only want it to replace spaces, comma's ',' dashes '-', '!' with forward slashes and then another replace function to replace any '&' with 'and'.

A: Regular expression-free example:
$str = str_replace([' ', ',', '-', '!'], '/', '& String! - !');
$str = str_replace('&', 'and', $str);
echo $str;

A: Try this :
$q = preg_replace('/[\s,\-!]/', '/', $q);

$q = str_replace("&","and",$q);


text:
Q: MobileFirst 7.1 authentication Issue I have issue in authentication in mobilefirst 7.1,
 platformSourcesVersion=7.1.0.00.20151130-1648

I have all my security tests, realms , login modules ... inserted correctly,
in my auth adapter i have :
    WL.Server.setActiveUser("AuthRealm", null);
    WL.Server.setActiveUser("AuthRealm", userIdentity);

after login when i invoke WL.Client.updateUserInfo(), and i getUserInfo from realm it returns NULL,
It's like server disconnect directly after login,
authentificationConfig.xml :
  http://pastebin.com/q6JSFDmU

Login in authentication-impl.js
http://pastebin.com/sz1dcnAG

ChallengeHandler :
 http://pastebin.com/q9BsdGbF

Any help ???
Thanks

A: It turned out that i had to turn a "true" to "false" in worklight.properties
 mfp.session.independent=false

:)


text:
Q: Validate date column for PySpark dataframe I want to validate a date column for a PySpark dataframe. I know how to do it for pandas, but can't make it work for PySpark.
import pandas as pd
import datetime
from datetime import datetime
data = [['Alex',10, '2001-01-12'],['Bob',12, '2005-10-21'],['Clarke',13, '2003-12-41']]
df = pd.DataFrame(data,columns=['Name','Sale_qty', 'DOB'])
sparkDF =spark.createDataFrame(df)

def validate(date_text):
    try:
        if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'):
            raise ValueError
        return True
    except ValueError:
        return False

df = df['DOB'].apply(lambda x: validate(x))

print(df)

It works for pandas dataframe. But I can't make it work for PySpark. Getting the following error:
sparkDF = sparkDF['DOB'].apply(lambda x: validate(x))

TypeError                                 Traceback (most recent call last)
<ipython-input-83-5f5f1db1c7b3> in <module>
----> 1 sparkDF = sparkDF['DOB'].apply(lambda x: validate(x))

TypeError: 'Column' object is not callable

A: You could use the following column expression:
F.to_date('DOB', 'yyyy-M-d').isNotNull()

Full test:
from pyspark.sql import functions as F

data = [['Alex', 10, '2001-01-12'], ['Bob', 12, '2005'], ['Clarke', 13, '2003-12-41']]
df = spark.createDataFrame(data, ['Name', 'Sale_qty', 'DOB'])

validation = F.to_date('DOB', 'yyyy-M-d').isNotNull()

df.withColumn('validation', validation).show()
# +------+--------+----------+----------+
# |  Name|Sale_qty|       DOB|validation|
# +------+--------+----------+----------+
# |  Alex|      10|2001-01-12|      true|
# |   Bob|      12|      2005|     false|
# |Clarke|      13|2003-12-41|     false|
# +------+--------+----------+----------+

A: you can use a to_date() with the required source date format. It returns null where the format is incorrect, which can be used for validation.
see below example.
spark.sparkContext.parallelize([('01-12-2001',), ('2001-01-12',)]).toDF(['dob']). \
    withColumn('correct_date_format', func.to_date('dob', 'yyyy-MM-dd').isNotNull()). \
    show()

# +----------+-------------------+
# |       dob|correct_date_format|
# +----------+-------------------+
# |01-12-2001|              false|
# |2001-01-12|               true|
# +----------+-------------------+


text:
Q: Is there a formula to find the p-value from a given z-score? I know that you can use a z-table to find p-values given a z-score, however I am curious if you can calculate it without the z-table or a calculator.  Is it possible? If so, how do you do it? I've tried searching, but the only thing that came up was a post on the Actuarial Outpost, and none of the answers really addressed the question.
Note: I am curious because I want to write a Python program that will do this, and writing an entire z-table, and then searching the table for a given value seems incredibly tedious and inefficient. I am aware that the scipy library can do this, however it seems kinda lazy, and on top of that I'm just curious.
edit: The answer was actually really simple, just take the integral of the normal distribution and approximating it. However, this doesn't seem satisfying or tangible enough for me, mostly because I can't convert it to code-form (sorry for the trouble by the way). Are there any other ways?

A: There is no other way. You need a numerical method - approximating the integral f the normal, or using a program in a library or a $z$-table - which in turn depend on numerical methods.

A: You can create Taylor series approximation of the normal PDF and integrate that. There will be some error, but you can choose the number of expansion terms to minimize the error to an arbitrary threshold.


text:
Q: Why should EL functions be from Java methods with non-void return types? I have a situation in which I think it is a good idea to use an EL function that is a void java method. This is a simple jsp to update a database of people's first and last name. So, there are two text fields, name and password. The user enters them and clicks submit, and it forwards these with POST to another jsp. This jsp simply calls the EL function, let's call it "put" that takes two parameters and is derived from a java method putPerson(String, String) that gets a connection to the database and puts the first and last name in their proper places. Now, putPerson is void because all it does is put the strings in the database. So, is this bad programming practice, and if so, why? It seems to me to be a quick and elegant solution, and it works. The only problem is that you can't just call it by saying ${put(first, last)} because that prints out "<", for some reason, but that's easy enough to work around. So why do they recommend to not use EL functions with void return types?

A: Printing < would be coming from somewhere else, or is a bug in the EL parser. But either way, you should not do that in an EL function.
EL functions are meant to be utilities - for example .substring(), .join() (arrays), etc. And they are used while you are displaying the page and need some more complex presentation logic.
What you want to do is a typical story and it is done in a servlet (or any other action component, if you are using a framework).

A: The mechanism you need is older than EL - and it is called a scriptlet:
<%
    whatever.putPerson("John", "Smith");
%>

In early JSP another syntax was used to just print values (notice the equals sign):
<%=
    whatever.getVal();
%>

Because it was felt that it is easier to maintain code when there is a command / query separation, EL was introduced as a way to query model (= read properties of beans). Since scriptlets were available to cater for the rare cases when simply "running some code" would be necessary, adding such functionality to EL would have no sense: we would have two ways to achieve the very same thing and we would break the concept of EL expressions always having a value and a type.
So:

*

*using EL for calling void methods is like... uhmpf... using import for running code: it makes no sense;

*this is not a problem, since you can use the very mechanism that was made to call methods: a scriptlet.


text:
Q: How do I get an updated copy of the environment variables in between bitbucket pipeline steps? I have a script that updates keys for docker login.
If I do NOT run the script that updates keys the in a step, the docker login works perfectly.
If I run the update keys script on my local machine, the script works, and the docker login works
If I run the update keys in the pipeline build, the script works but the docker login does NOT work (because the environment variables are not being updated)
The update keys script needs to run before my docker login
How do I get an updated copy of the environment variables in between steps?
bitbucket-pipelines.yml
image: node:8.2.1

pipelines:
  default:
    - step:
        name: Update Docker Password for Login
        script:
          - npm install aws-sdk request-promise base-64
          - node build-tools/update-bb-aws-docker-login.js
    - step:
        name: Push Server to AWS Repository
        script:
          - docker login -u AWS -p $AWS_DOCKER_LOGIN https://$AWS_DOCKER_URL
          - docker build -t dev .
          - docker tag dev:latest $AWS_DOCKER_URL/dev:latest
          - docker push $AWS_DOCKER_URL/dev:latest

options:
  docker: true


text:
Q: Puppeteer: page.evaluate() returns empty object instead ISO date string According to the Puppeteer docs, page.evaluate() returns a non-serializable value. They link to the MDN docs, where it's explained what JSON.stringify() converts or not.
I'm trying to get Date values (as ISO strings), but empty object are returned. The MDN docs says the following about Date objects:

The instances of Date implement the toJSON() function by returning a string (the same as date.toISOString()). Thus, they are treated as strings.

Here an example to reproduce it:
const puppeteer = require('puppeteer'); // v5.0.0

(async () => {
    const browser = await puppeteer.launch({devtools: true});
    const page = await browser.newPage();
    await page.goto('about:blank');

    let date = await page.evaluate(() => {
        return new Date();
    });

    // Expected an ISO date string but empty object returned
    console.log(date); // Output: {}

    await browser.close();
})();

Am I missing something?

A: new Date() creates a new date object. If you want ISO date string use following,
new Date().toISOString()