本地存储financialdata
542653
def QA_SU_save_financial_files():
    
    download_financialzip()
    coll = DATABASE.financial
    coll.create_index(
        [("code", ASCENDING), ("report_date", ASCENDING)], unique=True)
    for item in os.listdir(download_path):
        if item[0:4] != 'gpcw':
            print(
                "file ", item, " is not start with gpcw , seems not a financial file , ignore!")
            continue

        date = int(item.split('.')[0][-8:])
        print('QUANTAXIS NOW SAVING {}'.format(date))
        if coll.find({'report_date': date}).count() < 3600:

            print(coll.find({'report_date': date}).count())
            data = QA_util_to_json_from_pandas(parse_filelist([item]).reset_index(
            ).drop_duplicates(subset=['code', 'report_date']).sort_index())
            # data["crawl_date"] = str(datetime.date.today())
            try:
                coll.insert_many(data, ordered=False)

            except Exception as e:
                if isinstance(e, MemoryError):
                    coll.insert_many(data, ordered=True)
                elif isinstance(e, pymongo.bulk.BulkWriteError):
                    pass
        else:
            print('ALL READY IN DATABASE')

    print('SUCCESSFULLY SAVE/UPDATE FINANCIAL DATA')
592056
private Map<String, String> buildWebPayParams(WebPayDetail webPayDetail) {

        // 公共参数
        Map<String, String> webPayParams = buildPayParams(webPayDetail, Service.WEB_PAY);

        // PC特有参数
        putIfNotEmpty(webPayParams, AlipayField.EXTER_INVOKE_IP, webPayDetail.getExterInvokeIp());
        putIfNotEmpty(webPayParams, AlipayField.ANTI_PHISHING_KEY, webPayDetail.getAntiPhishingKey());
        putIfNotEmpty(webPayParams, AlipayField.ERROR_NOTIFY_URL, webPayDetail.getErrorNotifyUrl());
        putIfNotEmpty(webPayParams, AlipayField.EXTRA_COMMON_PARAM, webPayDetail.getExtraCommonParam());

        // md5签名参数
        buildMd5SignParams(webPayParams);

        return webPayParams;
    }
237902
function(tmplText, data, settings) {
			// node.js buffer toString
			tmplText+="";
			
			if(settings){
				// 临时定义
				settings = defaults({}, settings, Et.tmplSettings);
				settings={
						script: new RegExp(settings.scriptBegin.replace(dotRegExp,"\\$1")+"([\\s\\S]+?)"+settings.scriptEnd.replace(dotRegExp,"\\$1"),"g"),
						out: new RegExp(settings.outBegin.replace(dotRegExp,"\\$1")+"([\\s\\S]+?)"+settings.outEnd.replace(dotRegExp,"\\$1"),"g"),
						escapeOut: new RegExp(settings.escapeOutBegin.replace(dotRegExp,"\\$1")+"([\\s\\S]+?)"+settings.escapeOutEnd.replace(dotRegExp,"\\$1"),"g"),
				};
			}else{
				// 模板标签
				if(
					Et.tmplSettings.scriptBegin!="%{" ||
					Et.tmplSettings.scriptEnd!="}%" ||
					Et.tmplSettings.outBegin!="{=" ||
					Et.tmplSettings.outEnd!="}" ||
					Et.tmplSettings.escapeOutBegin!="{-" ||
					Et.tmplSettings.escapeOutEnd!="}" 
				){
					cacheTmplSettings={
						script: new RegExp(Et.tmplSettings.scriptBegin.replace(dotRegExp,"\\$1")+"([\\s\\S]+?)"+Et.tmplSettings.scriptEnd.replace(dotRegExp,"\\$1"),"g"),
						out: new RegExp(Et.tmplSettings.outBegin.replace(dotRegExp,"\\$1")+"([\\s\\S]+?)"+Et.tmplSettings.outEnd.replace(dotRegExp,"\\$1"),"g"),
						escapeOut: new RegExp(Et.tmplSettings.escapeOutBegin.replace(dotRegExp,"\\$1")+"([\\s\\S]+?)"+Et.tmplSettings.escapeOutEnd.replace(dotRegExp,"\\$1"),"g"),
					};
				}
				settings=cacheTmplSettings;
			}
			
			tmplText = Et.unescape(tmplText);
			var render;
			var matcher = new RegExp([(settings.escapeOut || noMatch).source, (settings.out || noMatch).source, (settings.script || noMatch).source].join("|") + "|$", "g");
			var index = 0;
			var source = "_p+='";
			tmplText.replace(matcher, function(match, escapeOut, out, script, offset) {
				source += tmplText.slice(index, offset).replace(escaper, function(match) {
					return "\\" + escapes[match];
				});
				if(escapeOut) {
					source += "'+\n((_t=(" + escapeOut + "))==null?'':Et.escape(_t))+'";
				}
				if(out) {
					//source += "'+((_t=(" + out+ "))==null?'':_t)+'";
//					source += "'+" + out + "+'";
					source += "'+\n((_t=(" + out+ "))==null?'':_t)+'";
				}
				if(script) {
					source += "';" + script + "\n_p+='";
				}
				index = offset + match.length;
				return match;
			});
			source += "';";
			var vars=getVars(source); 
			// Script support 
			if(this.enableScript){
//				source=source.replace(scriptReg, function($0, $1){
//					return '<script>'+$1.trim()+'<\/script>'
//				})
				source=source.replace("<etj-script>",'<script>').replace("</etj-script>",'<\/script>');
			}
			// Style support, don't warp
			if(this.enableStyle){
//				source=source.replace(styleReg, function($0, $1){
//					return '<style>'+$1.trim()+'</style>';
//				})
				source=source.replace("<etj-style>",'<style>').replace("</etj-style>",'<\/style>');
			}
//			console.info(source);
			source = "'use strict';"+vars+"_t,_p='',out=function(){_p+=Array.prototype.join.call(arguments, '')};" + source + "return _p";
			try {
				render = new Function("data", "Et",  source);
			} catch (e) {
				e.source = "function anonymous(data,Et) {" + source + "}";;
				throw e;
			}
			if(data) {
				try{
					return render(data, Et);
				}catch(e){
					console.error(e);
				}
				
			}
			var template = function(data) {
				try{
					return render(data, Et);
				}catch(e){
					console.error(e);
				}
			};
			return template;
		}
994267
def extract_data(self):
        """"""
        self.time_axis = []
        self.cpu_axis = []
        self.mem_axis = []
        self.timestamp_list = []
        plot_data = self.data.get("plot_data", [])
        # 按照时间分割线，划分成几段数据，取其中的最值
        for i in plot_data:
            timestamp = i["timestamp"]
            self.timestamp_list.append(timestamp)
            timestamp = round(timestamp, 1)
            cpu_percent = i["cpu_percent"]
            mem_gb_num = i["mem_gb_num"]
            date = datetime.fromtimestamp(timestamp)
            # 添加坐标轴
            self.time_axis.append(date)
            self.cpu_axis.append(cpu_percent)
            self.mem_axis.append(mem_gb_num)

        # 获取各种方法执行过程中的cpu和内存极值:
        self.get_each_method_maximun_cpu_mem()
1207076
public function getDBData() {
        $data = [];
        $fields = $this->getFields();
        foreach ($fields as $field => $type) {
            $value = $this->$field;
            if ($value === null) {
                continue;
            }
            $oldValue = $this->_db_data[ $field ];
            if (is_array($type)) {
                $type = $type[ 'type' ];
            }
            if ($type == 'json' && !is_string($value)) {
                $value = json_encode($value);
            }
            //值没有变不保存
            if ($value == $oldValue && $oldValue != null) {
                continue;
            }

            if ($value === 'null') {
                $value = null;
                $this->$field = null;
            } else if ($type == 'int') {
                $value = (int)$value;
            } else if ($type == 'float') {
                $value = (float)$value;
            } else if ($type == 'time' || $type == 'date') {
                $time = (int)$value;
                if ($time . "" != $value) {
                    $value = strtotime($value);
                }
            } else if ($type == 'attach_s') {
                if (is_string($value)) {
                    $attach = [['url' => $value]];
                } else {
                    $attach = $value;
                }
                $values = [];
                foreach ($attach as $item) {
                    $type = 'default';
                    if (key_exists('type', $item)) {
                        $type = $item[ 'type' ];
                    }
                    $url = $item[ 'url' ];
                    $domian = Storage::getStorage($type)->getDomain();
                    if ($domian) {
                        $url = str_replace($domian, "", $url);
                    }
                    $item[ 'url' ] = $url;
                    $values[] = $item;
                }
                $value = json_encode($values);
                if ($value == $oldValue && $oldValue != null) {
                    continue;
                }
            } else if ($type == 'attach' || $type == 'attach_i') {
                if (is_string($value)) {
                    $item = ['url' => $value];
                } else {
                    $item = $value;
                }
                $type = 'default';
                if (key_exists('type', $item)) {
                    $type = $item[ 'type' ];
                }
                $url = $item[ 'url' ];
                $domian = Storage::getStorage($type)->getDomain();
                if ($domian) {
                    $url = str_replace($domian, "", $url);
                }
                $item[ 'url' ] = $url;
                $item = [$item];
                $value = json_encode($item);
                if ($value == $oldValue && $oldValue != null) {
                    continue;
                }
            }
            $data[ $field ] = $value;
        }
        return $data;
    }
102353
def query_positions(self, accounts):
        
        try:
            data = self.call("positions", {'client': accounts})
            if data is not None:
                cash_part = data.get('subAccounts', {}).get('人民币', False)
                if cash_part:
                    cash_available = cash_part.get('可用金额', cash_part.get('可用'))

                position_part = data.get('dataTable', False)
                if position_part:
                    res = data.get('dataTable', False)
                    if res:
                        hold_headers = res['columns']
                        hold_headers = [
                            cn_en_compare[item] for item in hold_headers
                        ]
                        hold_available = pd.DataFrame(
                            res['rows'],
                            columns=hold_headers
                        )
                if len(hold_available) == 1 and hold_available.amount[0] in [
                        None,
                        '',
                        0
                ]:
                    hold_available = pd.DataFrame(
                        data=None,
                        columns=hold_headers
                    )
                return {
                    'cash_available':
                    cash_available,
                    'hold_available':
                    hold_available.assign(
                        amount=hold_available.amount.apply(float)
                    ).loc[:,
                          ['code',
                           'amount']].set_index('code').amount
                }
            else:
                print(data)
                return False, 'None ACCOUNT'
        except:
            return False
157520
def _get_lottery_detail_by_id(self, id):
        
        header = '编号 期号 开奖日期 开奖号码'.split()
        pt = PrettyTable()
        pt._set_field_names(header)

        url = QUERY_DETAIL_URL.format(id=id)
        import requests
        content = requests.get(url).text
        d = pq(content)
        if d('table.historylist'):
            # 输出彩种
            info = d('div.historyHd1 h2').text()
            print(info)
            # 输出table
            rows = d('table.historylist>tbody>tr')
            for idx, row in enumerate(rows):
                i = pq(row)
                qh = i('td:eq(0)').text().strip()
                kjrq = i('td:eq(1)').text().strip()
                hm_r = colored.red(i('td:eq(2) td.redBalls').text().strip())
                hm_g = colored.green(i('td:eq(2) td.blueBalls').text().strip())
                kjhm = ' '.join([hm_r, hm_g])
                item = [idx + 1, qh, kjrq, kjhm]
                pt.add_row(item)
            print(pt)
        elif d('table#draw_list'):
            # 输出彩种
            info = d('div.cpinfo>div.title').text()
            print(info)
            # 输出table
            rows = d('table#draw_list>tbody>tr')
            for idx, row in enumerate(rows):
                i = pq(row)
                qh = i('td.td2').text().strip()
                kjrq = i('td.td1').text().strip()
                hm_r = colored.red(i('td.td3 span.ball_1').text().strip())
                hm_g = colored.green(i('td.td3 span.ball_2').text().strip())
                kjhm = ' '.join([hm_r, hm_g])
                item = [idx + 1, qh, kjrq, kjhm]
                pt.add_row(item)
            print(pt)
        else:
            print('请联系作者')
388903
def QA_SU_save_stock_day(client=DATABASE, ui_log=None, ui_progress=None):
    '''
     
    '''
    stock_list = QA_fetch_get_stock_list().code.unique().tolist()
    coll_stock_day = client.stock_day
    coll_stock_day.create_index(
        [("code",
          pymongo.ASCENDING),
         ("date_stamp",
          pymongo.ASCENDING)]
    )
    err = []

    # saveing result

    def __gen_param(stock_list, coll_stock_day, ip_list=[]):
        results = []
        count = len(ip_list)
        total = len(stock_list)
        for item in range(len(stock_list)):
            try:
                code = stock_list[item]
                QA_util_log_info(
                    '##JOB01 Now Saving STOCK_DAY==== {}'.format(str(code)),
                    ui_log
                )

                # 首选查找数据库 是否 有 这个代码的数据
                search_cond = {'code': str(code)[0:6]}
                ref = coll_stock_day.find(search_cond)
                end_date = str(now_time())[0:10]
                ref_count = coll_stock_day.count_documents(search_cond)

                # 当前数据库已经包含了这个代码的数据， 继续增量更新
                # 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现
                if ref_count > 0:
                    # 接着上次获取的日期继续更新
                    start_date = ref[ref_count - 1]['date']
                    # print("ref[ref.count() - 1]['date'] {} {}".format(ref.count(), coll_stock_day.count_documents({'code': str(code)[0:6]})))
                else:
                    # 当前数据库中没有这个代码的股票数据， 从1990-01-01 开始下载所有的数据
                    start_date = '1990-01-01'
                QA_util_log_info(
                    'UPDATE_STOCK_DAY \n Trying updating {} from {} to {}'
                        .format(code,
                                start_date,
                                end_date),
                    ui_log
                )
                if start_date != end_date:
                    # 更新过的，不更新
                    results.extend([(code, start_date, end_date, '00', 'day', ip_list[item % count]['ip'],
                                     ip_list[item % count]['port'], item, total, ui_log, ui_progress)])
            except Exception as error0:
                print('Exception:{}'.format(error0))
                err.append(code)
        return results

    ips = get_ip_list_by_multi_process_ping(stock_ip_list, _type='stock')[:cpu_count() * 2 + 1]
    param = __gen_param(stock_list, coll_stock_day, ips)
    ps = QA_SU_save_stock_day_parallelism(processes=cpu_count() if len(ips) >= cpu_count() else len(ips),
                                          client=client, ui_log=ui_log)
    ps.add(do_saving_work, param)
    ps.run()

    if len(err) < 1:
        QA_util_log_info('SUCCESS save stock day ^_^', ui_log)
    else:
        QA_util_log_info('ERROR CODE \n ', ui_log)
        QA_util_log_info(err, ui_log)
317682
function (url, options) {
    // 首先建立连接
    options = options || {};
    options.autoReconnect = true;

    const { timestamp = true, updatedTime, createdTime } = options;

    const extendUpdate = timestamp ? extend.update(updatedTime) : extend.no();
    const extendCreate = timestamp ? extend.create(createdTime) : extend.no();

    const connect = mongo.connect(url, options);

    this.collections = () => {
      return connect.then((db) => {
        return db.collections();
      });
    };
    this.collection = (collectionName) => {
      return connect.then((db) => {
        return db.collection(collectionName);
      });
    };
    this.count = (collectionName, query, options) => {
      return this.collection(collectionName).then((collection) => {
        return collection.count(query, options);
      });
    };
    this.create = this.insert = (collectionName, data) => {
      return this.collection(collectionName).then((collection) => {
        return collection.insert(extendCreate(data));
      });
    };
    this.find = (collectionName, filter, condition, cursor) => {
      return this.collection(collectionName).then((collection) => {
        if (!cursor) {
          return collection.find(filter, condition).toArray();
        } else {
          return collection.find(filter, condition);
        }
      });
    };
    this.findOne = (collectionName, filter, condition) => {
      return this.collection(collectionName).then((collection) => {
        return collection.findOne(filter, condition);
      });
    };
    this.update = (collectionName, filter, data, options) => {
      return this.collection(collectionName).then((collection) => {
        return collection.update(filter, extendUpdate(data), Object.assign({}, { upsert: false }, options));
      });
    };
    this.updateOne = (collectionName, filter, data, options) => {
      return this.collection(collectionName).then((collection) => {
        return collection.updateOne(filter, extendUpdate(data), Object.assign({}, { upsert: true }, options));
      });
    };
    this.remove = (collectionName, filter, options) => {
      return this.collection(collectionName).then((collection) => {
        return collection.deleteMany(filter, options);
      });
    };
    this.aggregate = (collectionName, pipeline, options) => {
      return this.collection(collectionName).then((collection) => {
        return new Promise((rec, rej) => {
          collection.aggregate(pipeline, (err, res) => {
            if (err) {
              rej(err);
            } else {
              rec(res);
            }
          });
        });
      });
    };
    return this;
  }
225081
function moneySmalltoBig(n) {
    if (!_.isNumber(n) || _.isNaN(n))
        return ''

    var fraction = ['角', '分'];
    var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    var unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
    var head = n < 0 ? '欠' : '';
    n = Math.abs(n);

    var s = '';

    for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
    }
    s = s || '整';
    n = Math.floor(n);

    for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
    }
    return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
}
1318479
function financetime(tickMethods, genericFormat, index, domain, padding, outerPadding, zoomLimit, closestTicks) {
    var dateIndexMap,
        tickState = { tickFormat: tickMethods.daily[tickMethods.daily.length-1][2] },
        band = 3;

    index = index || d3_scale_linear();
    domain = domain || [new Date(0), new Date(1)];
    padding = padding === undefined ? 0.2 : padding;
    outerPadding = outerPadding === undefined ? 0.65 : outerPadding;
    zoomLimit = zoomLimit || index.domain();
    closestTicks = closestTicks || false;

    /**
     * Scales the value to domain. If the value is not within the domain, will currently brutally round the data:
     * - If before min domain, will round to 1 index value before min domain
     * - If after max domain, will round to 1 index value after min domain
     * - If within domain, but not mapped to domain value, uses d3.bisect to find nearest domain index
     *
     * This logic was not required until the domain was being updated and scales re-rendered and this line
     * https://github.com/mbostock/d3/blob/abbe1c75c16c3e9cb08b1d0872f4a19890d3bb58/src/svg/axis.js#L107 was causing error.
     * New scale generated ticks that old scale did not have, causing error during transform. To avoid error this logic
     * was added.
     *
     * @param x The value to scale
     * @param offset Apply an index offset to the mapped x (date) parameter
     * @returns {*}
     */
    function scale(x, offset) {
      var mappedIndex = dateIndexMap[+x];
      offset = offset || 0;

      // Make sure the value has been mapped, if not, determine if it's just before, round in, or just after domain
      if(mappedIndex === undefined) {
        if(domain[0] > x) mappedIndex = -1; // Less than min, round just out of domain
        else mappedIndex = d3_bisect(domain, x); // else let bisect determine where in or just after than domain it is
      }

      return index(mappedIndex + offset);
    }

    /**
     * Invert the passed range coordinate to the corresponding domain. Returns null if no valid domain available.
     *
     * @param y
     * @returns {null} If the range value cannot be mapped. eg, if range value is outside of the mapped domain
     */
    scale.invert = function(y) {
      var d = domain[scale.invertToIndex(y)];
      return d ? d : null;
    };

    /**
     * Inverts the coordinate to the corresponding domain. <b>NOTE: </b> May return values outside of the domain such
     * as negative indexes, or an index greater than what is available in the domain.
     *
     * @param y
     * @returns {number} A number representing the index in the domain the range value has been inverted to. May return
     * values outside of the domain such as negatives or value greater than domain().length-1
     */
    scale.invertToIndex = function(y) {
      return Math.round(index.invert(y));
    };

    /**
     * As the underlying structure relies on a full array, ensure the full domain is passed here,
     * not just min and max values.
     *
     * @param _ The full domain array
     * @returns {*}
     */
    scale.domain = function(_) {
      if (!arguments.length) {
        var visible = index.domain();

        if(visible[0] < 0 && visible[visible.length-1] < 0) return []; // if it's all negative return empty, nothing is visible

        visible = [
          Math.max(Math.ceil(visible[0]), 0), // If min is fraction, it is partially out of view, but still partially visible, round up (ceil)
          Math.min(Math.floor(visible[visible.length-1]), domain.length-1) // If max is fraction, is partially out of view, but still partially visible, round down (floor)
        ];
        return domain.slice(visible[0], visible[visible.length-1]+1); // Grab visible domain, inclusive
      }

      domain = _;
      return applyDomain();
    };

    function zoomed() {
      band = rangeBand(index, domain, padding);
      return scale;
    }

    function domainMap() {
      dateIndexMap = lookupIndex(domain);
    }

    function applyDomain() {
      domainMap();
      index.domain([0, domain.length-1]);
      zoomed();
      // Apply outerPadding and widen the outer edges by pulling the domain in to ensure start and end bands are fully visible
      index.domain(index.range().map(scale_widen(outerPadding, band)).map(index.invert));
      zoomLimit = index.domain(); // Capture the zoom limit after the domain has been applied
      return zoomed();
    }

    scale.copy = function() {
      return financetime(tickMethods, genericFormat, index.copy(), domain, padding, outerPadding, zoomLimit, closestTicks);
    };

    /**
     * Equivalent to d3's ordinal.rangeBand(). It could not be named rangeBand as d3 uses the method
     * to determine how axis ticks should be rendered. This scale is a hybrid ordinal and linear scale,
     * such that scale(x) returns y at center of the band as does d3.scale.linear()(x) does, whereas
     * d3.scale.ordinal()(x) returns y at the beginning of the band. When rendering svg axis, d3
     * compensates for this checking if rangeBand is defined and compensates as such.
     * @returns {number}
     */
    scale.band = function() {
      return band;
    };

    scale.outerPadding = function(_) {
      if(!arguments.length) return outerPadding;
      outerPadding = _;
      return applyDomain();
    };

    scale.padding = function(_) {
      if(!arguments.length) return padding;
      padding = _;
      return applyDomain();
    };

    scale.zoomable = function() {
      return zoomable(index, zoomed, zoomLimit);
    };

    /*
     * Ticks based heavily on d3 implementation. Attempted to implement this using composition with d3.time.scale,
     * but in the end there were sufficient differences to 'roll my own'.
     * - Different base tick steps: millis not required (yet!)
     * - State based tick formatting given the non continuous, even steps of ticks
     * - Supporting daily and intraday continuous (no gaps) plotting
     * https://github.com/mbostock/d3/blob/e03b6454294e1c0bbe3125f787df56c468658d4e/src/time/scale.js#L67
     */
    /**
     * Generates ticks as continuous as possible against the underlying domain. Where continuous time ticks
     * fall on where there is no matching domain (such as weekend or holiday day), it will be replaced with
     * the nearest domain datum ahead of the tick to keep close to continuous.
     * @param interval
     * @param steps
     * @returns {*}
     */
    scale.ticks = function(interval, steps) {
      var visibleDomain = scale.domain(),
          indexDomain = index.domain();

      if(!visibleDomain.length) return []; // Nothing is visible, no ticks to show

      var method = interval === undefined ? tickMethod(visibleDomain, indexDomain, 10) :
                    typeof interval === 'number' ? tickMethod(visibleDomain, indexDomain, interval) : null;

      tickState.tickFormat = method ? method[2] : tickMethod(visibleDomain, indexDomain, 10)[2];

      if(method) {
        interval = method[0];
        steps = method[1];
      }

      var intervalRange = interval.range(visibleDomain[0], +visibleDomain[visibleDomain.length-1]+1, steps);

      return intervalRange                                // Interval, possibly contains values not in domain
        .map(domainTicks(visibleDomain, closestTicks))    // Line up interval ticks with domain, possibly adding duplicates
        .reduce(sequentialDuplicates, []);                // Filter out duplicates, produce new 'reduced' array
    };

    function tickMethod(visibleDomain, indexDomain, count) {
      if(visibleDomain.length == 1) return genericFormat; // If we only have 1 to display, show the generic tick method

      var visibleDomainExtent = visibleDomain[visibleDomain.length-1] - visibleDomain[0],
        intraday = visibleDomainExtent/dailyStep < 1, // Determine whether we're showing daily or intraday data
        methods = intraday ? tickMethods.intraday : tickMethods.daily,
        tickSteps = intraday ? intradayTickSteps : dailyTickSteps,
        k = Math.min(Math.round(countK(visibleDomain, indexDomain)*count), count),
        target = visibleDomainExtent/k, // Adjust the target based on proportion of domain that is visible
        i = d3_bisect(tickSteps, target);

      return i == methods.length ? methods[i-1] : // Return the largest tick method
        i ? methods[target/tickSteps[i-1] < tickSteps[i]/target ? i-1 : i] : methods[i]; // Else return close approximation or first tickMethod
    }

    /**
     * By default `ticks()` will generate tick values greater than the nearest domain interval value, which may not be
     * best value, particularly for irregular intraday domains. Setting this to true will cause tick generation to choose
     * values closest to the corresponding domain value for the calculated interval.
     * @param _ Optional `boolean` value. If argument is passed, sets the value and returns this instance, if no argument, returns the current value
     */
    scale.closestTicks = function(_) {
      if(!arguments.length) return closestTicks;
      closestTicks = _;
      return scale;
    };

    /**
     * NOTE: The type of tick format returned is dependant on ticks that were generated. To obtain the correct
     * format for ticks, ensure ticks function is called first, otherwise a default tickFormat will be returned
     * which may not be the optimal representation of the current domain state.
     * @returns {Function}
     */
    scale.tickFormat = function() {
      return function(date) {
        return tickState.tickFormat(date);
      };
    };

    techan_util_rebindCallback(scale, index, zoomed, 'range');

    domainMap();
    return zoomed();
  }
1062112
public function getData()
    {
        $this->validate('txnTime', 'fileType', 'settleDate');

        $data = array(
            'version'    => $this->getVersion(),        //版本号
            'encoding'   => $this->getEncoding(),        //编码方式
            'certId'     => $this->getCertId(),    //证书ID
            'txnType'    => '76',        //交易类型
            'signMethod' => $this->getSignMethod(),        //签名方法
            'txnSubType' => '01',        //交易子类
            'bizType'    => '000000',        //业务类型
            'accessType' => '0',        //接入类型
            'merId'      => $this->getMerId(),     //商户代码
            'settleDate' => '0119',        //清算日期
            'txnTime'    => $this->getTxnTime(),    //订单发送时间
            'fileType'   => $this->getFileType(),        //文件类型
        );

        $data = $this->filter($data);

        $data['signature'] = $this->sign($data);

        return $data;
    }
1033626
public function BGCreateShippingOrder()
        {
            // 參數初始化
            $ParamList = [
                'MerchantID' => '',
                'MerchantTradeNo' => '',
                'MerchantTradeDate' => '',
                'LogisticsType' => '',
                'LogisticsSubType' => '',
                'GoodsAmount' => 0,
                'CollectionAmount' => 0,
                'IsCollection' => IsCollection::NO,
                'GoodsName' => '',
                'SenderName' => '',
                'SenderPhone' => '',
                'SenderCellPhone' => '',
                'ReceiverName' => '',
                'ReceiverPhone' => '',
                'ReceiverCellPhone' => '',
                'ReceiverEmail' => '',
                'TradeDesc' => '',
                'ServerReplyURL' => '',
                'LogisticsC2CReplyURL' => '',
                'Remark' => '',
                'PlatformID' => '',
            ];

            // 幕後物流訂單建立不可設定Client端回覆網址(ClientReplyURL)
            if (! empty($this->Send['ClientReplyURL'])) {
                throw new Exception('ClientReplyURL should be null.');
            }

            $this->PostParams = $this->GetPostParams($this->Send, $ParamList);
            $MinAmount = 1; // 金額下限
            $MaxAmount = 20000; // 金額上限

            // 參數檢查
            $this->ValidateHashKey();
            $this->ValidateHashIV();
            $this->ValidateID('MerchantID', $this->PostParams['MerchantID'], 10);
            $this->ServiceURL = $this->GetURL('SHIPPING_ORDER');
            $this->ValidateMerchantTradeDate();
            $this->ValidateLogisticsType();
            $this->ValidateLogisticsSubType();

            // 依不同的物流類型(LogisticsType)設定專屬參數並檢查
            switch ($this->PostParams['LogisticsType']) {
                case LogisticsType::CVS:
                    $CvsParamList = [
                        'ReceiverStoreID' => '',
                        'ReturnStoreID' => '',
                    ];
                    $this->PostParams = $this->GetPostParams($this->SendExtend, $CvsParamList, $this->PostParams);

                    $this->ValidateMixTypeID('ReceiverStoreID', $this->PostParams['ReceiverStoreID'], 6);
                    $this->ValidateMixTypeID('ReturnStoreID', $this->PostParams['ReturnStoreID'], 6, true);
                    break;
                case LogisticsType::HOME:
                    $HomeParamList = [
                        'SenderZipCode' => '',
                        'SenderAddress' => '',
                        'ReceiverZipCode' => '',
                        'ReceiverAddress' => '',
                        'Temperature' => Temperature::ROOM,
                        'Distance' => Distance::SAME,
                        'Specification' => Specification::CM_60,
                        'ScheduledDeliveryTime' => '',
                        'ScheduledDeliveryDate' => '',
                        'PackageCount' => 0,
                    ];
                    $this->PostParams = $this->GetPostParams($this->SendExtend, $HomeParamList, $this->PostParams);
                    $this->PostParams['ScheduledPickupTime'] = ScheduledPickupTime::UNLIMITED;

                    $this->ValidateZipCode('SenderZipCode', $this->PostParams['SenderZipCode']);
                    $this->ValidateAddress('SenderAddress', $this->PostParams['SenderAddress'], 6, 60);
                    $this->ValidateZipCode('ReceiverZipCode', $this->PostParams['ReceiverZipCode']);
                    $this->ValidateAddress('ReceiverAddress', $this->PostParams['ReceiverAddress'], 6, 60);
                    $this->ValidateTemperature();
                    $this->ValidateDistance();
                    $this->ValidateSpecification();
                    $this->ValidateScheduledDeliveryTime(true);
                    break;
                default:
            }

            $this->ValidateAmount('GoodsAmount', $this->PostParams['GoodsAmount']);
            if (
                $this->PostParams['LogisticsSubType'] == LogisticsSubType::UNIMART ||
                $this->PostParams['LogisticsSubType'] == LogisticsSubType::UNIMART_C2C
            ) {
                // 物流子類型(LogisticsSubType)為統一超商(UNIMART)或統一超商交貨便(UNIMARTC2C)時，商品金額範圍為1~19,999元
                $MaxAmount = 19999;
            }
            if ($this->PostParams['GoodsAmount'] < $MinAmount or $this->PostParams['GoodsAmount'] > $MaxAmount) {
                throw new Exception('Invalid GoodsAmount.');
            }

            $this->ValidateIsCollection(true);
            if ($this->PostParams['IsCollection'] == IsCollection::NO) {
                // 若設定為僅配送，清除代收金額
                unset($this->PostParams['CollectionAmount']);
            } else {
                $this->ValidateAmount('CollectionAmount', $this->PostParams['CollectionAmount']);
                if ($this->PostParams['CollectionAmount'] < $MinAmount or $this->PostParams['CollectionAmount'] > $MaxAmount) {
                    throw new Exception('Invalid CollectionAmount.');
                }
            }

            if ($this->PostParams['LogisticsSubType'] == LogisticsSubType::HILIFE_C2C or $this->PostParams['LogisticsSubType'] == LogisticsSubType::UNIMART_C2C) {
                // 物流子類型(LogisticsSubType)為萊爾富店到店(HILIFEC2C)、 統一超商交貨便(UNIMARTC2C)時，不可為空
                $this->ValidateString('GoodsName', $this->PostParams['GoodsName'], 60);
            } else {
                $this->ValidateString('GoodsName', $this->PostParams['GoodsName'], 60, true);
            }

            $this->ValidateString('SenderName', $this->PostParams['SenderName'], 10);
            $this->ValidatePhoneNumber('SenderPhone', $this->PostParams['SenderPhone'], true);
            $this->ValidateCellphoneNumber('SenderCellPhone', $this->PostParams['SenderCellPhone'], true);
            if ($this->PostParams['LogisticsType'] == LogisticsType::HOME) {
                // 物流類型(LogisticsType)為宅配(Home)時，寄件人電話(SenderPhone)或寄件人手機(SenderCellPhone)不可為空
                if (empty($this->PostParams['SenderPhone']) and empty($this->PostParams['SenderCellPhone'])) {
                    throw new Exception('SenderPhone or SenderCellPhone is required when LogisticsType is Home.');
                }
            } elseif ($this->PostParams['LogisticsSubType'] == LogisticsSubType::HILIFE_C2C or $this->PostParams['LogisticsSubType'] == LogisticsSubType::UNIMART_C2C) {
                // 物流子類型(LogisticsSubType)為統一超商交貨便(UNIMARTC2C)、萊爾富店到店(HILIFEC2C)時，寄件人手機(SenderCellPhone)不可為空
                if (empty($this->PostParams['SenderCellPhone'])) {
                    throw new Exception('SenderCellPhone is required when LogisticsSubType is UNIMARTC2C or HILIFEC2C.');
                }
            }

            $this->ValidateString('ReceiverName', $this->PostParams['ReceiverName'], 10);
            $this->ValidatePhoneNumber('ReceiverPhone', $this->PostParams['ReceiverPhone'], true);
            $this->ValidateCellphoneNumber('ReceiverCellPhone', $this->PostParams['ReceiverCellPhone'], true);
            if ($this->PostParams['LogisticsType'] == LogisticsType::HOME) {
                // 物流類型(LogisticsType)為宅配(Home)時，收件人電話(ReceiverPhone)或收件人手機(ReceiverCellPhone)不可為空
                if (empty($this->PostParams['ReceiverPhone']) and empty($this->PostParams['ReceiverCellPhone'])) {
                    throw new Exception('ReceiverPhone or ReceiverCellPhone is required when LogisticsType is Home.');
                }
            } else {
                // 物流子類型(LogisticsSubType)為統一超商(UNIMART)、全家(FAMILY)、萊爾富(HILIFE)、統一超商交貨便(UNIMARTC2C)、全家超商店到店(FAMILYC2C)、萊爾富富店到店(HILIFEC2C)時，收件人手機(ReceiverCellPhone)不可為空
                if (empty($this->PostParams['ReceiverCellPhone'])) {
                    throw new Exception('ReceiverCellPhone is required.');
                }
            }

            if ($this->PostParams['LogisticsSubType'] == LogisticsSubType::ECAN and $this->PostParams['Temperature'] !== Temperature::ROOM) {
                // 物流子類型為宅配通(ECAN)時，溫層(Temperature)只能用常溫(ROOM)
                throw new Exception('Temperature should be ROOM when LogisticsSubType is ECAN.');
            }

            if ($this->PostParams['LogisticsSubType'] == LogisticsSubType::ECAN and date('Ymd', strtotime($this->PostParams['ScheduledDeliveryDate'])) < date('Ymd', strtotime('+3 day'))) {
                // 指定送達日期為該訂單建立時間 + 3 天
                throw new Exception('ScheduledDeliveryDate should be the time that create order + 3 day.');
            }

            $this->ValidateEmail('ReceiverEmail', $this->PostParams['ReceiverEmail'], 50, true);
            $this->ValidateString('TradeDesc', $this->PostParams['TradeDesc'], 200, true);
            $this->ValidateURL('ServerReplyURL', $this->PostParams['ServerReplyURL']);

            if ($this->PostParams['LogisticsSubType'] == LogisticsSubType::UNIMART_C2C) {
                // 物流子類型(LogisticsSubType)為統一超商交貨便(UNIMARTC2C)時，此欄位不可為空
                $this->ValidateURL('LogisticsC2CReplyURL', $this->PostParams['LogisticsC2CReplyURL']);
            } else {
                $this->ValidateURL('LogisticsC2CReplyURL', $this->PostParams['LogisticsC2CReplyURL'], 200, true);
            }

            $this->ValidateString('Remark', $this->PostParams['Remark'], 200, true);
            $this->ValidateID('PlatformID', $this->PostParams['PlatformID'], 10, true);

            // 物流類型(LogisticsType)為宅配(Home)且溫層(Temperature)為冷凍(0003)時，規格(Specification)不可為 150cm(0004)
            if ($this->PostParams['LogisticsType'] == LogisticsType::HOME and $this->PostParams['Temperature'] == Temperature::FREEZE) {
                if ($this->PostParams['Specification'] == Specification::CM_150) {
                    throw new Exception('Specification could not be 0004 when LogisticsType is Home and Temperature is 0003.');
                }
            }

            // 產生 CheckMacValue
            $this->PostParams['CheckMacValue'] = ECPay_CheckMacValue::generate($this->PostParams, $this->HashKey, $this->HashIV);

            // urlencode
            foreach ($this->PostParams as $key => $value) {
                $this->PostParams[$key] = urlencode($value);
            }

            // 解析回傳結果
            // 正確：1|MerchantID=XXX&MerchantTradeNo=XXX&RtnCode=XXX&RtnMsg=XXX&AllPayLogisticsID=XXX&LogisticsType=XXX&LogisticsSubType=XXX&GoodsAmount=XXX&UpdateStatusDate=XXX&ReceiverName=XXX&ReceiverPhone=XXX&ReceiverCellPhone=XXX&ReceiverEmail=XXX&ReceiverAddress=XXX&CVSPaymentNo=XXX&CVSValidationNo=XXX &CheckMacValue=XXX
            // 錯誤：0|ErrorMessage
            $Feedback = ECPay_IO::ServerPost($this->PostParams, $this->ServiceURL);
            $Pieces = explode('|', $Feedback);
            $Result = [];
            $Result['ResCode'] = $Pieces[0];
            if ($Result['ResCode']) {
                $RtnCont = [];
                parse_str($Pieces[1], $RtnCont);
                $Result = array_merge($Result, $RtnCont);
            } else {
                $Result['ErrorMessage'] = $Pieces[1];
            }

            return $Result;
        }
349390
public function info() {
        /**
         * avatar	用户头像	String	如果没有数据的时候不会返回该数据，请做好容错	可空	https://tfsimg.alipay.com/images/partner/T1k0xiXXRnXXXXXXXX
        nick_name	用户昵称	String	如果没有数据的时候不会返回该数据，请做好容错	可空	张三
        province	省份	String	用户注册时填写的省份 如果没有数据的时候不会返回该数据，请做好容错	可空	浙江省
        city	城市	String	用户注册时填写的城市， 如果没有数据的时候不会返回该数据，请做好容错	可空	杭州
        gender	用户性别	String	M为男性，F为女性， 如果没有数据的时候不会返回该数据，请做好容错	可空	M
        user_type_value	用户类型	String	（1/2），1代表公司账户；2代表个人账户	不可空	1
        is_licence_auth	是否经过营业执照认证	String	T为通过营业执照认证，F为没有通过	不可空	T
        is_certified	是否通过实名认证	String	T是通过；F是没有实名认证	不可空	F
        is_certify_grade_a	是否A类认证	String	T表示是A类认证，F表示非A类认证，A类认证用户是指上传过身份证照片并且通过审核的支付宝用户	不可空	T
        is_student_certified	是否是学生	String	T表示是学生，F表示不是学生	不可空	T
        is_bank_auth	是否经过银行卡认证	String	T为经过银行卡认证，F为未经过银行卡认证	不可空	T
        is_mobile_auth	是否经过手机认证	String	T为经过手机认证，F为未经过手机认证	不可空	T
        alipay_user_id	当前用户的userId	String	支付宝用户的userId	不可空	2088411964574197
        user_id	已废弃，请勿使用	String	已废弃，请勿使用	不可空	已废弃，请勿使用
        user_status	用户状态（Q/T/B/W）	String	Q代表快速注册用户；T代表已认证用户；B代表被冻结账户；W代表已注册，未激活的账户	不可空	T
        is_id_auth	是否身份证认证	String	T为是身份证认证，F为非身份证认证	不可空	T
         */
        $user = (new OAuth())->info($this->get('access_token'));
        if (!is_array($user) || $user['code'] != 10000) {
            return false;
        }
        $user['username'] = $user['nick_name'];
        $user['sex'] = $user['gender'];
        $this->set($user);
        return $user;
    }
664800
def fundarb(
        self,
        jsl_username,
        jsl_password,
        avolume=100,
        bvolume=100,
        ptype="price",
    ):
        
        session = requests.session()
        headers = {
            # pylint: disable=line-too-long
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"
        }
        session.headers.update(headers)

        logindata = dict(
            return_url="http://www.jisilu.cn/",
            user_name=jsl_username,
            password=jsl_password,
            net_auto_login="1",
            _post_type="ajax",
        )

        rep = session.post(self.__jsl_login_url, data=logindata)

        if rep.json()["err"] is not None:
            return rep.json()

        # 添加当前的ctime
        fundarb_url = self.__fundarb_url.format(ctime=int(time.time()))

        pdata = dict(
            avolume=avolume,
            bvolume=bvolume,
            ptype=ptype,
            is_search="1",
            market=["sh", "sz"],
            rp="50",
        )
        # 请求数据
        rep = session.post(fundarb_url, data=pdata)

        # 获取返回的json字符串
        fundajson = json.loads(rep.text)
        # 格式化返回的json字符串
        data = self.formatfundajson(fundajson)

        self.__fundarb = data
        return self.__fundarb
875001
private static Object getFieldValue(Class<?> cls, String fieldName, String strValue) {
		try {
			Class<?> type = Reflections.getDeclaredField(cls, fieldName).getType();
			// 是数字类型
			if (Number.class.isAssignableFrom(type)) {
				return type.getMethod("valueOf", String.class).invoke(null, strValue);
			}
			// 字符类型
			if (Character.class.isAssignableFrom(type)) {
				return strValue.charAt(0);
			}
			// 字符串类型
			if (String.class.isAssignableFrom(type)) {
				return strValue;
			}
			// 日期类型
			if (Date.class.isAssignableFrom(type)) {
				// TODO 日期类型处理
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
80011
function local(backendTplServer) {
    backendTplServer.app.get('/news/local', function(request, response) {
        // 公共的数据模型可以抽取到出来, 作为一个文件 require 进来, 防止多处重复定义数据模型的规则
        var data = Mock.mock({
            'news|10-20': [news]
        });

        // 单独修改其中的某个数据
        data.news[0].getUrls = function() {
            return [
                'http://dummyimage.com/112x74,',
                'http://dummyimage.com/112x74,',
                'http://dummyimage.com/112x74,',
                'http://dummyimage.com/112x74,'
            ]
        };

        response.render('news/local.html', data);
    });
}