Fetch and merge in Marketdata for each option position
333554
def mergein_marketdata_list(cls, client, option_positions):
        
        ids = cls._extract_ids(option_positions)
        mds = OptionMarketdata.quotes_by_instrument_ids(client, ids)

        results = []
        for op in option_positions:
            # @TODO optimize this so it's better than O(n^2)
            md = [x for x in mds if x['instrument'] == op['option']][0]
            # there is no overlap in keys so this is fine
            merged_dict = dict(list(op.items()) + list(md.items()))
            results.append(merged_dict)
        return results
929957
def VcardMergeListFields(field1, field2):
    """"""
    field_dict = {}
    for f in field1 + field2:
        field_dict[str(f)] = f
    return list(field_dict.values())
413804
def trades(ctx, market, limit, start, stop):
    
    market = Market(market, bitshares_instance=ctx.bitshares)
    t = [["time", "quote", "base", "price"]]
    for trade in market.trades(limit, start=start, stop=stop):
        t.append(
            [
                str(trade["time"]),
                str(trade["quote"]),
                str(trade["base"]),
                "{:f} {}/{}".format(
                    trade["price"],
                    trade["base"]["asset"]["symbol"],
                    trade["quote"]["asset"]["symbol"],
                ),
            ]
        )
    print_table(t)
526624
function GetMarketStats($type, $options = "", $property_type = "", $location_name = "", $location_value = "") {

		$args = array();

		if (!empty($options)) {
			$args['Options'] = $options;
		}

		if (!empty($property_type)) {
			$args['PropertyTypeCode'] = $property_type;
		}

		if (!empty($location_name)) {
			$args['LocationField'] = $location_name;
			$args['LocationValue'] = $location_value;
		}

		return $this->return_first_result($this->MakeAPICall("GET", "marketstatistics/" . $type, '48h', $args));
	}
1185583
def simxGetJointPosition(clientID, jointHandle, operationMode):
    '''
    
    '''
    position = ct.c_float()
    return c_GetJointPosition(clientID, jointHandle, ct.byref(position), operationMode), position.value
268249
function (data) {
        var items = [];
        data.forEach(function (d, i) {
            if (d.includes('ITEM:') && d.length > 3) {
                var iid = data[i + 1];
                var item = {
                    item: {
                        id: Number(iid[1].trim()),
                        name: d[2].replace(/_/g, ' '),
                        price: d[3],
                        change: d[4]
                    }
                };
                items.push(item);
            }
        });
        return items;
    }
441359
def _get_price(self, data, market, field):
        
        for m in data:
            if m["symbol"] == market:
                return m[field]
552339
def trans(self, symbol='', start=0, offset=10):
        '''
        
        '''
        market = get_stock_market(symbol)

        with self.client.connect(*self.bestip):
            data = self.client.get_transaction_data(
                int(market), symbol, int(start), int(market))
            return self.client.to_df(data)
50842
function mergeOptions(parsedOptions) {
    return Object.keys(autoflowOptions).reduce(function (accum, k) {
      if (!accum[k]) accum[k] = autoflowOptions[k];
      return accum;
    }, parsedOptions);
  }
7809
function mergeOptions(...opt){
        // extract default (last argument)
        const result = opt.pop();

        // try to find first match
        while (opt.length > 0){
            // extract first argument (priority)
            const o = opt.shift();

            // value set ?
            if (typeof o !== 'undefined' && o !== null){
                return o;
            }
        }

        return result;
    }
740687
private function loadOptionValues(): void
	{
		$this->optionValues = array_merge(
			Option::getDefaults($this->moduleId),
			Option::getForModule($this->moduleId)
		);
	}
317898
function productOptionInformation( $objectAttribute, $optionID, $productItem )
    {
        $optiongroup = $objectAttribute->attribute( 'content' );

        $option = $optiongroup->findOption( false, $optionID );
        if ( $option )
        {
            return array( 'id' => $option['option_id'],
                          'name' => $option['multioption_name'],
                          'value' => $option['value'],
                          'additional_price' => $option['additional_price'] );
        }
        return null;
    }
867335
function optionToItinerary (option, query) {
  const itin = {
    duration: option.time,
    legs: [],
    walkTime: 0,
    waitingTime: 0
  }

  // access leg
  if (option.access && option.access.length > 0) {
    if (option.access[0].mode === 'BICYCLE_RENT') {
      let status = 'WALK_ON'
      const walkOnEdges = []
      const bikeEdges = []
      const walkOffEdges = []
      let onStationName
      let walkOnTime = 0
      let offStationName
      let walkOffTime = 0
      option.access[0].streetEdges.forEach(edge => {
        // check if we're returning the bike
        if (edge.bikeRentalOffStation) {
          status = 'WALK_OFF'
          offStationName = edge.bikeRentalOffStation.name
        }

        if (status === 'WALK_ON') {
          walkOnEdges.push(edge)
          walkOnTime += edge.distance
        } else if (status === 'BIKE') {
          bikeEdges.push(edge)
        } else if (status === 'WALK_OFF') {
          walkOffEdges.push(edge)
          walkOffTime += edge.distance
        }

        // check if we're picking up the bike
        if (edge.bikeRentalOnStation) {
          status = 'BIKE'
          onStationName = edge.bikeRentalOnStation.name
        }
      })

      itin.walkTime += (walkOnTime + walkOffTime)

      // create the 'on' walk leg
      itin.legs.push({
        mode: 'WALK',
        duration: walkOnTime,
        transitLeg: false,
        from: {
          name: locationString(query && query.from.name, 'Destination')
        },
        to: {
          name: onStationName
        }
      })

      // create the bike leg
      itin.legs.push({
        mode: 'BICYCLE_RENT',
        duration: option.time - walkOnTime - walkOffTime,
        transitLeg: false,
        from: {
          name: onStationName
        },
        to: {
          name: offStationName
        }
      })

      // create the 'off' walk leg
      itin.legs.push({
        mode: 'WALK',
        duration: walkOffTime,
        transitLeg: false,
        from: {
          name: offStationName
        },
        to: {
          name: locationString(query && query.to.name, 'Destination')
        }
      })
    } else {
      itin.legs.push(accessToLeg(option.access[0], query && query.from.name, option.transit ? null : query && query.to.name))
      if (option.access[0].mode === 'WALK') itin.walkTime += option.access[0].time
    }
  }

  // transit legs
  if (option.transit) {
    option.transit.forEach(transit => {
      itin.legs.push({
        transitLeg: true,
        mode: transit.mode,
        from: {
          name: transit.fromName
        },
        to: {
          name: transit.toName
        },
        routes: transit.routes,
        duration: transit.rideStats.avg,
        averageWait: transit.waitStats.avg
      })
      itin.waitingTime += transit.waitStats.avg
    })
  }

  // egress leg
  if (option.egress && option.egress.length > 0) {
    // find the origin name, for transit trips
    const origin = option.transit ? option.transit[option.transit.length - 1].toName : null

    itin.legs.push(accessToLeg(option.egress[0], origin, query && query.to.name))
    if (option.egress[0].mode === 'WALK') itin.walkTime += option.egress[0].time
  }

  // construct summary
  if (option.transit) {
    itin.summary = 'Transit'
  } else {
    if (option.modes.length === 1 && option.modes[0] === 'bicycle') itin.summary = 'Bicycle'
    else if (option.modes.length === 1 && option.modes[0] === 'walk') itin.summary = 'Walk'
    else if (option.modes.indexOf('bicycle_rent') !== -1) itin.summary = 'Bikeshare'
  }

  return itin
}
367244
function getDeeplyMergedValues(value1, value2) {
  if (isArray(value2)) {
    return !isArray(value1) ? value2 : mergeDeepArrays(value1, value2); // eslint-disable-line no-use-before-define
  }

  if (isObject(value2)) {
    return !isObject(value1) ? value2 : mergeDeepObjects(value1, value2); //eslint-disable-line no-use-before-define
  }

  return value2;
}
1145873
function findExistingStock(next) {
      // prepare criteria by _id or fields
      let criteria = _.merge({}, _stock);
      criteria = (
        criteria._id ?
        _.pick(criteria, '_id') :
        _.pick(criteria, 'owner', 'item')
      );
      Stock.findOne(criteria, next);
    }
49557
def frame(self):
        
        rows = []
        pricer = self.pricer
        pos = open_val = pid = 0
        for txn in self.trades:
            # These values always get copied
            qty = txn.qty
            premium = pricer.get_premium(qty, txn.px, ts=txn.ts)
            if pos == 0:  # Open position
                side = qty > 0 and Action.Buy or Action.SellShort
                open_val = premium
                pid += 1
                side = side
                intent = Intent.Open
                pos = qty
            elif pos + qty == 0:  # close position
                side = qty > 0 and Action.Cover or Action.Sell
                open_val = 0
                side = side
                intent = Intent.Close
                pos = 0
            elif is_increase(pos, qty):
                side = txn.qty > 0 and Action.Buy or Action.SellShort
                open_val += premium
                pos += qty
                intent = Intent.Increase
                side = side
            else:  # decrease - no worries about split since iterator takes care of it
                side = txn.qty > 0 and Action.Cover or Action.Sell
                open_val *= ((pos + qty) / pos)
                pos += qty
                intent = Intent.Decrease
                side = side

            # Get rid of anything but the date
            dt = txn.ts.to_period('B').to_timestamp()
            rows.append([dt, txn.ts, pid, txn.tid, txn.qty, txn.px, txn.fees, premium, open_val, pos, intent, side])

        df = pd.DataFrame.from_records(rows, columns=[TC.DT, TC.TS, TC.PID, TC.TID, TC.QTY, TC.PX, TC.FEES, TC.PREMIUM,
                                                      TC.OPEN_VAL, TC.POS, TC.INTENT, TC.ACTION])
        df.index.name = 'seq'
        return df
1286738
def _fetch_stock_data(self, stock_list):
        """"""
        res = super()._fetch_stock_data(stock_list)

        with_stock = []
        for stock, resp in zip(stock_list, res):
            if resp is not None:
                with_stock.append((stock, resp))
        return with_stock