save index_day

    Arguments:
        engine {[type]} -- [description]

    Keyword Arguments:
        client {[type]} -- [description] (default: {DATABASE})
357503
def QA_SU_save_index_day(engine, client=DATABASE):
    

    engine = select_save_engine(engine)
    engine.QA_SU_save_index_day(client=client)
1235356
def ensure_index(self, key_or_list, cache_for=300, **kwargs):
        
        warnings.warn("ensure_index is deprecated. Use create_index instead.",
                      DeprecationWarning, stacklevel=2)
        # The types supported by datetime.timedelta.
        if not (isinstance(cache_for, integer_types) or
                isinstance(cache_for, float)):
            raise TypeError("cache_for must be an integer or float.")

        if "drop_dups" in kwargs:
            kwargs["dropDups"] = kwargs.pop("drop_dups")

        if "bucket_size" in kwargs:
            kwargs["bucketSize"] = kwargs.pop("bucket_size")

        keys = helpers._index_list(key_or_list)
        name = kwargs.setdefault("name", helpers._gen_index_name(keys))

        # Note that there is a race condition here. One thread could
        # check if the index is cached and be preempted before creating
        # and caching the index. This means multiple threads attempting
        # to create the same index concurrently could send the index
        # to the server two or more times. This has no practical impact
        # other than wasted round trips.
        if not self.__database.client._cached(self.__database.name,
                                              self.__name, name):
            self.__create_index(keys, kwargs)
            self.__database.client._cache_index(self.__database.name,
                                                self.__name, name, cache_for)
            return name
        return None
510403
def init_db(sqlalchemy_url):
    
    engine = create_engine(sqlalchemy_url)
    start = time.time()
    metadata.create_all(engine)
    return time.time() - start
729245
def save(self, force=False):
        
        from time import time

        # Since the DBs can get rather large, we don't want to save them every
        # single time a method is called. Instead, we only save them at the
        # frequency specified in the global settings file.
        from datetime import datetime
        savefreq = TaskDB.get_option("savefreq", 2, int)
        
        if self.lastsave is not None:
            delta = (datetime.fromtimestamp(time()) -
                     datetime.fromtimestamp(self.lastsave)) 
            elapsed = int(delta.total_seconds()/60)
        else:
            elapsed = savefreq + 1

        if elapsed > savefreq or force:
            if not writeable:
                #We still overwrite the lastsave value so that this message doesn't
                #keep getting output for every :meth:`record` call.
                self.lastsave = time()
                msg.std("Skipping database write to disk by setting.", 2)
                return

            import json
            try:
                entities, compkeys = _json_clean(self.entities)
                jdb = {"entities": entities,
                       "compkeys": compkeys,
                       "uuids": self.uuids}
                with open(self.dbpath, 'w') as f:
                    json.dump(jdb, f)
            except: # pragma: no cover
                from acorn.msg import err
                import sys
                raise
                err("{}: {}".format(*sys.exc_info()[0:2]))

            self.lastsave = time()
725273
def prepare(self, engine, mode, items) -> None:
        
        self.tx_id = str(uuid.uuid4()).replace("-", "")
        self.engine = engine
        self.mode = mode
        self.items = items
        self._prepare_request()
20342
def QA_SU_save_etf_list(engine, client=DATABASE):
    

    engine = select_save_engine(engine)
    engine.QA_SU_save_etf_list(client=client)
576142
def save(self):
        '''
        
        '''
        client = self._new_api_client()
        params = {'id': self.id} if hasattr(self, 'id') else {}
        action =  'patch' if hasattr(self, 'id') else 'post'
        saved_model = client.make_request(self, action, url_params=params, post_data=self._to_json)
        self.__init__(**saved_model._to_dict)
1076436
def dump_orm_object_as_insert_sql(engine: Engine,
                                  obj: object,
                                  fileobj: TextIO) -> None:
    
    # literal_query = make_literal_query_fn(engine.dialect)
    insp = inspect(obj)
    # insp: an InstanceState
    # http://docs.sqlalchemy.org/en/latest/orm/internals.html#sqlalchemy.orm.state.InstanceState  # noqa
    # insp.mapper: a Mapper
    # http://docs.sqlalchemy.org/en/latest/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper  # noqa

    # Don't do this:
    #   table = insp.mapper.mapped_table
    # Do this instead. The method above gives you fancy data types like list
    # and Arrow on the Python side. We want the bog-standard datatypes drawn
    # from the database itself.
    meta = MetaData(bind=engine)
    table_name = insp.mapper.mapped_table.name
    # log.debug("table_name: {}", table_name)
    table = Table(table_name, meta, autoload=True)
    # log.debug("table: {}", table)

    # NewRecord = quick_mapper(table)
    # columns = table.columns.keys()
    query = select(table.columns)
    # log.debug("query: {}", query)
    for orm_pkcol in insp.mapper.primary_key:
        core_pkcol = table.columns.get(orm_pkcol.name)
        pkval = getattr(obj, orm_pkcol.name)
        query = query.where(core_pkcol == pkval)
    # log.debug("query: {}", query)
    cursor = engine.execute(query)
    row = cursor.fetchone()  # should only be one...
    row_dict = dict(row)
    # log.debug("obj: {}", obj)
    # log.debug("row_dict: {}", row_dict)
    statement = table.insert(values=row_dict)
    # insert_str = literal_query(statement)
    insert_str = get_literal_query(statement, bind=engine)
    writeline_nl(fileobj, insert_str)
995895
def select_save_engine(engine, paralleled=False):
    '''
    
    '''
    if engine in ['tushare', 'ts', 'Tushare']:
        return sts
    elif engine in ['tdx']:
        if paralleled:
            return stdx_parallelism
        else:
            return stdx
    elif engine in ['gm', 'goldenminer']:
        return sgm
    elif engine in ['jq', 'joinquant']:
        return sjq
    else:
        print('QA Error QASU.main.py call select_save_engine with parameter %s is None of  thshare, ts, Thshare, or tdx', engine)
821342
def _database_create(self, engine, database):
        
        logger.info('Creating database "%s" in "%s"', database, engine)
        database_operation(engine, 'create', database)
        url = copy(engine.url)
        url.database = database
        return str(url)
1063884
def save(**kwargs):
    '''
    
    '''

    ret = {'comment': [],
           'result': True}

    if 'test' in kwargs and kwargs['test']:
        ret['comment'] = 'Schedule would be saved.'
    else:
        try:
            eventer = salt.utils.event.get_event('minion', opts=__opts__)
            res = __salt__['event.fire']({'func': 'save_schedule'}, 'manage_schedule')
            if res:
                event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_saved', wait=30)
                if event_ret and event_ret['complete']:
                    ret['result'] = True
                    ret['comment'] = 'Schedule (non-pillar items) saved.'
                else:
                    ret['result'] = False
                    ret['comment'] = 'Failed to save schedule.'
        except KeyError:
            # Effectively a no-op, since we can't really return without an event system
            ret['comment'] = 'Event module not available. Schedule save failed.'
    return ret
467997
def QA_SU_save_future_min_all(engine, client=DATABASE):
    

    engine = select_save_engine(engine)
    engine.QA_SU_save_future_min_all(client=client)
283372
def index_exists(engine: Engine, tablename: str, indexname: str) -> bool:
    
    insp = Inspector.from_engine(engine)
    return any(i['name'] == indexname for i in insp.get_indexes(tablename))
1018175
def cli(obj, ids, query, filters):
    """"""
    client = obj['client']

    if obj['output'] == 'json':
        r = client.http.get('/alerts/history')
        click.echo(json.dumps(r['history'], sort_keys=True, indent=4, ensure_ascii=False))
    else:
        timezone = obj['timezone']
        if ids:
            query = [('id', x) for x in ids]
        elif query:
            query = [('q', query)]
        else:
            query = build_query(filters)
        alerts = client.get_history(query)

        headers = {'id': 'ID', 'updateTime': 'LAST UPDATED', 'severity': 'SEVERITY', 'status': 'STATUS',
                   'type': 'TYPE', 'customer': 'CUSTOMER', 'environment': 'ENVIRONMENT', 'service': 'SERVICE',
                   'resource': 'RESOURCE', 'group': 'GROUP', 'event': 'EVENT', 'value': 'VALUE', 'text': 'TEXT'}
        click.echo(
            tabulate([a.tabular(timezone) for a in alerts], headers=headers, tablefmt=obj['output']))
19235
def engine_data(engine):
    
    views = ("default", "main", "started", "stopped", "complete",
             "incomplete", "seeding", "leeching", "active", "messages")
    methods = [
        "throttle.global_up.rate", "throttle.global_up.max_rate",
        "throttle.global_down.rate", "throttle.global_down.max_rate",
    ]

    # Get data via multicall
    proxy = engine.open()
    calls = [dict(methodName=method, params=[]) for method in methods] \
          + [dict(methodName="view.size", params=['', view]) for view in views]
    result = proxy.system.multicall(calls, flatten=True)

    # Build result object
    data = dict(
        now         = time.time(),
        engine_id   = engine.engine_id,
        versions    = engine.versions,
        uptime      = engine.uptime,
        upload      = [result[0], result[1]],
        download    = [result[2], result[3]],
        views       = dict([(name, result[4+i])
            for i, name in enumerate(views)
        ]),
    )

    return data
284783
def special_case_mysql(self, u, kwargs):
        """"""

        kwargs['pool_recycle'] = int(u.query.pop('max_idle', 3600))

        # default to the MyISAM storage engine
        storage_engine = u.query.pop('storage_engine', 'MyISAM')
        kwargs['connect_args'] = {
            'init_command': 'SET default_storage_engine=%s' % storage_engine,
        }

        if 'use_unicode' in u.query:
            if u.query['use_unicode'] != "True":
                raise TypeError("Buildbot requires use_unicode=True " +
                                "(and adds it automatically)")
        else:
            u.query['use_unicode'] = True

        if 'charset' in u.query:
            if u.query['charset'] != "utf8":
                raise TypeError("Buildbot requires charset=utf8 " +
                                "(and adds it automatically)")
        else:
            u.query['charset'] = 'utf8'

        return u, kwargs, None
538020
def create_mysql_oursql(username, password, host, port, database, **kwargs):  # pragma: no cover
    
    return create_engine(
        _create_mysql_oursql(username, password, host, port, database),
        **kwargs
    )