Inserts news for account
		Accepts:
			- event_type
			- cid
			- access_string (of buyer)
			- buyer_pubkey
			- buyer address
			- owner address
			- price
			- offer type
			- coin ID
		Returns:
			- dict with result
513470
async def insert_news(self, **params):
		
		logging.debug("\n\n [+] -- Setting news debugging.  ")
		if params.get("message"):
			params = json.loads(params.get("message", "{}"))
		
		if not params:
			return {"error":400, "reason":"Missed required fields"}
		logging.debug("   ***      Params")
		event_type = params.get("event_type")
		cid = params.get("cid")

		access_string = params.get("access_string")

		buyer_pubkey = params.get("buyer_pubkey")

		buyer_address = params.get("buyer_address")

		owneraddr = params.get("owneraddr")

		price = params.get("price")

		offer_type = int(params.get("offer_type", -1))

		coinid = params.get("coinid").upper()

		try:
			coinid = coinid.replace("TEST", "")
		except:
			pass

		logging.debug("\n **   Coinid")
		logging.debug(coinid)

		# Get address of content owner and check if it exists
		if coinid in settings.bridges.keys():
			self.account.blockchain.setendpoint(settings.bridges[coinid])
		else:
			return {"error":400, "reason": "Invalid coin ID"}

		owneraddr = await self.account.blockchain.ownerbycid(cid=cid)

		# Get sellers account
		seller = await getaccountbywallet(wallet=owneraddr)
		if "error" in seller.keys():
			return seller

		# Connect to news table 
		news_collection = self.database[settings.NEWS]

		# Get sellers price
		self.account.blockchain.setendpoint(settings.bridges[coinid])
		if offer_type == 1:
			seller_price = await self.account.blockchain.getwriteprice(cid=cid)
		elif offer_type == 0:
			seller_price = await self.account.blockchain.getreadprice(cid=cid)

		
		row = {"offer_type": self.account.ident_offer[offer_type], 
				"buyer_address":buyer_address,
				"cid":cid,
				"access_string":access_string,
				"buyer_pubkey": buyer_pubkey,
				"seller_price": seller_price,
				"buyer_price": price,
				"account_id": seller["id"],
				"event_type": event_type,
				"coinid":coinid}

		logging.debug("\n **  Inserting row")
		logging.debug(row)
		
		# Update counter inside accounts table
		database = client[settings.DBNAME]
		collection = database[settings.ACCOUNTS]
		await collection.find_one_and_update(
						{"id": int(seller["id"])},
						{"$inc": {"news_count": 1}})
		await collection.find_one({"id":int(seller["id"])})
		
		# Insert data to news table
		await news_collection.insert_one(row)

		logging.debug("\n ** Fresh news")
		fresh = await collection.find_one({"buyer_address":buyer_address,
												"cid":cid})
		logging.debug(fresh)

		return {"result":"ok"}
442850
def submit(para_temp)
      parameters = {
          "service" => "batch_trans_notify",
          "partner" => NewAlipay.partner,
          "notify_url" => para_temp[:notify_url],
          "email" => NewAlipay.seller_email,
          "account_name" => NewAlipay.account_name,
          "pay_date" => Time.new.strftime('%Y-%m-%d'),
          "batch_no" => random_trade_no(24),
          "batch_fee" => para_temp[:batch_fee],
          "batch_num" => para_temp[:batch_num],
          "detail_data" => para_temp[:detail_data],
          "_input_charset" => "utf-8"
      }
      parameters = parameters.merge({buyer_account_name: para_temp[:buyer_account_name]}) if para_temp[:buyer_account_name]

      signing_str_array = parameters.inject([]) { |memo, (key, v)| memo << "#{key}=#{v}"; memo }
      sorted_signing_str_array = signing_str_array.sort! { |m, n| m.to_s <=> n.to_s }
      sign = Digest::MD5.hexdigest(sorted_signing_str_array.join('&')+NewAlipay.key)

      sorted_signing_str_array << "sign=#{sign}" << 'sign_type=MD5'

      yield parameters.symbolize_keys.merge({:sign => sign, :sign_type => 'MD5'}) if block_given?

      "#{ALIPAY_GATEWAY_NEW}#{sorted_signing_str_array.join('&')}"
    end
1187351
async def create_account(self, **params):
		
		logging.debug("\n\n[+] -- Create account debugging. ")
		model = {
		"unique": ["email", "public_key"],
		"required": ("public_key",),
		"default": {"count":len(settings.AVAILABLE_COIN_ID), 
					"level":2, 
					"news_count":0, 
					"email":None},
		"optional": ("phone",)}

		message = json.loads(params.get("message", "{}"))
	
		data = {**message.get("message"), "public_key":message["public_key"]}

		# check if all required
		required = all([True if i in data.keys() else False for i in model["required"]])

		if not required:
			return {"error": 400,
					"reason":"Missed required fields"}

		# Unique constraint
		get_account = await self.collection.find_one({"public_key":data.get("public_key")})

		# Try get account with current public key
		if get_account:
			return {"error": 400,
					"reason": "Unique violation error"}

		# Reload data.
		row = {i:data[i] for i in data 
				if i in model["required"] or i in model["optional"]}
		row.update({i:model["default"][i] for i in model["default"]})
		if data.get("email"):
			row["email"] = data.get("email")
		row.update({"id":await self.autoincrement()})
		await self.collection.insert_one(row)
		account = await self.collection.find_one({"public_key":row["public_key"]})

		# Create wallets
		for coinid in coin_ids:
			database = client[coinid]
			wallet_collection = database[settings.WALLET]
			wallet = await wallet_collection.insert_one({
					"account_id": account["id"],
					"wallet": self.account.validator[coinid](account["public_key"]) 
				})
		return account
986092
def _insert(self, name, value, timestamp, intervals, **kwargs):
    '''
    
    '''
    if self._value_type in QUOTE_TYPES and not QUOTE_MATCH.match(value):
      value = "'%s'"%(value)

    for interval,config in self._intervals.items():
      timestamps = self._normalize_timestamps(timestamp, intervals, config)
      for tstamp in timestamps:
        self._insert_data(name, value, tstamp, interval, config, **kwargs)
877763
async def write_deal(self, **params):
		
		if params.get("message"):
			params = json.loads(params.get("message", "{}"))
		
		if not params:
			return {"error":400, "reason":"Missed required fields"}

		cid = int(params.get("cid", 0))
		access_type = params.get("access_type")
		buyer = params.get("buyer")
		seller = params.get("seller")
		price = params.get("price")
		coinid = params.get("coinid")

		try:
			coinid = coinid.replace("TEST", "")
		except:
			pass

		if not all([cid, access_type, buyer, seller, price]):
			return {"error":400, "reason":"Missed required fields"}

		database = client[coinid]
		collection = database[settings.DEAL]
		await collection.insert_one({
				"cid":cid,
				"access_type": access_type,
				"buyer":buyer,
				"seller":seller,
				"price":price,
				"coinid":coinid
			})
		result = await collection.find_one({"cid":cid, "buyer":buyer})

		return {i:result[i] for i in result if i != "_id"}
1253401
async def post(self, public_key):
		
		if settings.SIGNATURE_VERIFICATION:
			super().verify()

		try:
			body = json.loads(self.request.body)
		except:
			self.set_status(400)
			self.write({"error":400, "reason":"Unexpected data format. JSON required"})
			raise tornado.web.Finish
			
		if isinstance(body["message"], str):
			message = json.loads(body["message"])
		elif isinstance(body["message"], dict):
			message = body["message"]

		cid = message.get("cid")
		review = message.get("review")
		rating = message.get("rating")
		coinid = message.get("coinid")

		if not all([cid, rating, review]):
			self.set_status(400)
			self.write({"error":400, "reason":"Missed required fields"})

		if coinid in settings.bridges.keys():
			self.account.blockchain.setendpoint(settings.bridges[coinid])
		else:
			self.set_status(400)
			self.write({"error":400, "reason":"Invalid coinid"})
			raise tornado.web.Finish 

		buyer_address = self.account.validator[coinid](public_key)

		review = await self.account.blockchain.addreview(cid=int(cid),buyer_address=buyer_address,
														stars=int(rating), review=review)
		await self.account.setreview(cid=cid, txid=review["result"]["txid"], coinid=coinid)

		self.write({"cid":cid, "review":review, "rating":rating})
282739
def transaction_date(self, value):
        
        if value:
            self._transaction_date = parse(value).date() if isinstance(value, type_check) else value
260097
async def get_deals(self, **params):
		
		if params.get("message"):
			params = json.loads(params.get("message", "{}"))
		
		if not params:
			return {"error":400, "reason":"Missed required fields"}

		buyer = params.get("buyer")

		if not buyer:
			return {"error":400, "reason":"Missed public key"}

		deals = {i:[] for i in list(settings.bridges.keys())}

		for coinid in list(settings.bridges.keys()):
			database = client[coinid]
			collection = database[settings.DEAL]
			async for document in collection.find({"owner":buyer}):
				deals[coinid].append((document["cid"],document.get("txid")))
		return deals
1211892
def _insert(self, namespace, stream, events, configuration):
    
    max_items = configuration['max_items']
    for _id, event in events:
      while len(self.db[namespace][stream]) >= max_items:
        self.db[namespace][stream].pop(0)
      bisect.insort(self.db[namespace][stream], Event(_id, event))
528637
def put(self, event_type, event_data={}, **kwargs):
        
        event = dict(type=event_type, data=event_data)

        event["time"] = kwargs.get("time", datetime.utcnow().isoformat())

        if kwargs.get("id"):
            event["id"] = kwargs.get("id")

        data = json.dumps([event])

        r = requests.post(self.collector_url + 'event/put',
                          data=data,
                          headers={'content-type': 'application/json'})
        r.raise_for_status()

        return [event]
1213037
def serialise(self):
        
        return {
            'marketId': self.market_id,
            'totalAvailable': None,
            'isMarketDataDelayed': None,
            'lastMatchTime': None,
            'betDelay': self.market_definition.get('betDelay'),
            'version': self.market_definition.get('version'),
            'complete': self.market_definition.get('complete'),
            'runnersVoidable': self.market_definition.get('runnersVoidable'),
            'totalMatched': self.total_matched,
            'status': self.market_definition.get('status'),
            'bspReconciled': self.market_definition.get('bspReconciled'),
            'crossMatching': self.market_definition.get('crossMatching'),
            'inplay': self.market_definition.get('inPlay'),
            'numberOfWinners': self.market_definition.get('numberOfWinners'),
            'numberOfRunners': len(self.market_definition.get('runners')),
            'numberOfActiveRunners': self.market_definition.get('numberOfActiveRunners'),
            'runners': [
                runner.serialise(
                    self.market_definition_runner_dict[(runner.selection_id, runner.handicap)]
                ) for runner in self.runners
            ],
            'publishTime': self.publish_time,
            'priceLadderDefinition': self.market_definition.get('priceLadderDefinition'),
            'keyLineDescription': self.market_definition.get('keyLineDefinition'),
            'marketDefinition': self.market_definition,  # used in lightweight
        }
837564
function(bid) {
    return !!(bid && bid.params && bid.params.accountID && bid.params.slotID);
  }
696084
def QA_SU_save_deal(dealist, client=DATABASE):
    

    if isinstance(dealist, pd.DataFrame):

        collection = client.deal

        collection.create_index(
            [('account_cookie',
              ASCENDING),
             ('trade_id',
              ASCENDING)],
            unique=True
        )
        try:
            dealist = QA_util_to_json_from_pandas(dealist.reset_index())
            collection.insert_many(dealist, ordered=False)
        except Exception as e:

            pass
342343
def query(self, refund_id=None, out_refund_no=None, transaction_id=None,
              out_trade_no=None, device_info=None):
        
        data = {
            'appid': self.appid,
            'device_info': device_info,
            'transaction_id': transaction_id,
            'out_trade_no': out_trade_no,
            'out_refund_no': out_refund_no,
            'refund_id': refund_id,
        }
        return self._post('pay/refundquery', data=data)
1063240
def accept(self):
        '''
        
        '''
        result = dict(self.python_data)
        for field in self.fields:
            if field.writable:
                result.update(field.accept())
            else:
                # readonly field
                field.set_raw_value(self.form.raw_data,
                                    field.from_python(result[field.name]))
        self.clean_value = self.conv.accept(result)
        return {self.name: self.clean_value}
561026
def bids_to_you(self):
        '''
        
        '''
        headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/team_news.phtml',"User-Agent": user_agent}
        req = self.session.get('http://'+self.domain+'/exchangemarket.phtml?viewoffers_x=',headers=headers).content
        soup = BeautifulSoup(req)
        table = []
        for i in soup.find('table',{'class','tablecontent03'}).find_all('tr')[1:]:
            player,owner,team,price,bid_date,trans_date,status = self._parse_bid_table(i)
            table.append([player,owner,team,price,bid_date,trans_date,status])
        return table
301738
async def get_offers(self, **params):
		
		if params.get("message"):
			params = json.loads(params.get("message", "{}"))
		
		if not params:
			return {"error":400, "reason":"Missed required fields"}

		cid = params.get("cid")
		public_key = params.get("public_key")
		coinid = params.get("coinid")


		# Get all input offers by cid
		if cid and coinid:
			cid = int(cid)
			database = client[coinid]
			offer_collection = database[settings.OFFER]
			content_collection = database[settings.CONTENT]

			offers = [{i:document[i] for i in document if i == "confirmed"} 
						async for document in offer_collection.find({"cid":cid, "confirmed":None})]

		# Get all output users offers
		elif not cid:
			database = client[coinid]
			offer_collection = database[settings.OFFER]
			offers = [{i:document[i] for i in document if i == "confirmed"} 
						async for document in offer_collection.find({"public_key":public_key, 
																	"confirmed":None})]

		# Return list with offers
		return offers