Utility code for moving database files to a (presumably local)
	working location for improved performance and reduced fileserver
	load.
177231
def get_connection_filename(filename, tmp_path = None, replace_file = False, verbose = False):
	
	def mktmp(path, suffix = ".sqlite", verbose = False):
		with temporary_files_lock:
			# make sure the clean-up signal traps are installed
			install_signal_trap()
			# create the remporary file and replace it's
			# unlink() function
			temporary_file = tempfile.NamedTemporaryFile(suffix = suffix, dir = path if path != "_CONDOR_SCRATCH_DIR" else os.getenv("_CONDOR_SCRATCH_DIR"))
			def new_unlink(self, orig_unlink = temporary_file.unlink):
				# also remove a -journal partner, ignore all errors
				try:
					orig_unlink("%s-journal" % self)
				except:
					pass
				orig_unlink(self)
			temporary_file.unlink = new_unlink
			filename = temporary_file.name
			# hang onto reference to prevent its removal
			temporary_files[filename] = temporary_file
		if verbose:
			print >>sys.stderr, "using '%s' as workspace" % filename
		# mkstemp() ignores umask, creates all files accessible
		# only by owner;  we should respect umask.  note that
		# os.umask() sets it, too, so we have to set it back after
		# we know what it is
		umsk = os.umask(0777)
		os.umask(umsk)
		os.chmod(filename, 0666 & ~umsk)
		return filename

	def truncate(filename, verbose = False):
		if verbose:
			print >>sys.stderr, "'%s' exists, truncating ..." % filename,
		try:
			fd = os.open(filename, os.O_WRONLY | os.O_TRUNC)
		except Exception as e:
			if verbose:
				print >>sys.stderr, "cannot truncate '%s': %s" % (filename, str(e))
			return
		os.close(fd)
		if verbose:
			print >>sys.stderr, "done."

	def cpy(srcname, dstname, verbose = False):
		if verbose:
			print >>sys.stderr, "copying '%s' to '%s' ..." % (srcname, dstname),
		shutil.copy2(srcname, dstname)
		if verbose:
			print >>sys.stderr, "done."
		try:
			# try to preserve permission bits.  according to
			# the documentation, copy() and copy2() are
			# supposed preserve them but don't.  maybe they
			# don't preserve them if the destination file
			# already exists?
			shutil.copystat(srcname, dstname)
		except Exception as e:
			if verbose:
				print >>sys.stderr, "warning: ignoring failure to copy permission bits from '%s' to '%s': %s" % (filename, target, str(e))

	database_exists = os.access(filename, os.F_OK)

	if tmp_path is not None:
		# for suffix, can't use splitext() because it only keeps
		# the last bit, e.g. won't give ".xml.gz" but just ".gz"
		target = mktmp(tmp_path, suffix = ".".join(os.path.split(filename)[-1].split(".")[1:]), verbose = verbose)
		if database_exists:
			if replace_file:
				# truncate database so that if this job
				# fails the user won't think the database
				# file is valid
				truncate(filename, verbose = verbose)
			else:
				# need to copy existing database to work
				# space for modifications
				i = 1
				while True:
					try:
						cpy(filename, target, verbose = verbose)
					except IOError as e:
						import errno
						import time
						if e.errno not in (errno.EPERM, errno.ENOSPC):
							# anything other
							# than out-of-space
							# is a real error
							raise
						if i < 5:
							if verbose:
								print >>sys.stderr, "warning: attempt %d: %s, sleeping and trying again ..." % (i, errno.errorcode[e.errno])
							time.sleep(10)
							i += 1
							continue
						if verbose:
							print >>sys.stderr, "warning: attempt %d: %s: working with original file '%s'" % (i, errno.errorcode[e.errno], filename)
						with temporary_files_lock:
							del temporary_files[target]
						target = filename
					break
	else:
		with temporary_files_lock:
			if filename in temporary_files:
				raise ValueError("file '%s' appears to be in use already as a temporary database file and is to be deleted" % filename)
		target = filename
		if database_exists and replace_file:
			truncate(target, verbose = verbose)

	del mktmp
	del truncate
	del cpy

	return target
1034328
private function copyDatabase()
    {
        // get all files in database/migrations and database/seeds
        // if one already exist in desired location
        // flag and ask to override or not

        $sourceDatabase = $this->basePath . "database" . $this->ds;
        $destinationMigrations = database_path('migrations');
        $destinationSeeds = database_path('seeds');

        // copy files from source to destination
        $search = "{$this->baseNamespace}\Migrations;";
        $this->copyFilesFromSource($sourceDatabase . 'migrations', $destinationMigrations, $search,
            "");

        $search = "{$this->baseNamespace}\Seeds;";
        $this->copyFilesFromSource($sourceDatabase . 'seeds', $destinationSeeds, $search, "");
    }
123198
def _copy_database_data_clientside(self, tables, source, destination):
        """"""
        # Retrieve database rows
        rows = self.get_database_rows(tables, source)

        # Retrieve database columns
        cols = self.get_database_columns(tables, source)

        # Validate rows and columns
        for r in list(rows.keys()):
            assert r in tables
        for c in list(cols.keys()):
            assert c in tables

        # Change database to destination
        self.change_db(destination)

        # Get insert queries
        insert_queries = self._get_insert_commands(rows, cols)

        # Execute insert queries
        self._execute_insert_commands(insert_queries)
1050920
def move(srcpath, dstpath, overwrite=True):
    """"""
    # TODO: (JRR@201612230924) Consider adding smarter checks to prevent files ending up with directory names; e.g. if dstpath directory does not exist.
    if not op.exists(srcpath):
        return False
    if srcpath == dstpath:
        return True
    if op.isfile(srcpath) and op.isdir(dstpath):
        verfunc = op.isfile
        verpath = op.join(dstpath, op.basename(srcpath))
    elif op.isfile(srcpath):
        verfunc = op.isfile
        verpath = dstpath
        makedirs(dstpath)
    elif op.isdir(srcpath) and op.isdir(dstpath):
        verfunc = op.isdir
        verpath = op.join(dstpath, op.basename(srcpath))
    elif op.isdir(srcpath):
        verfunc = op.isdir
        verpath = dstpath
    else:
        return False
    if op.isfile(verpath):
        if not overwrite:
            return False
        else:
            # On Windows, filename case is ignored so the following check will
            # prevent unintentionally deleting the srcpath before moving.
            if "nt" == os.name and srcpath.lower() == dstpath.lower():
                pass
            elif not delete(verpath):
                return False
    try:
        shutil.move(srcpath, dstpath)
    except:
        return False
    return verfunc(verpath)
976664
def cli(
    paths,
    dbname,
    separator,
    quoting,
    skip_errors,
    replace_tables,
    table,
    extract_column,
    date,
    datetime,
    datetime_format,
    primary_key,
    fts,
    index,
    shape,
    filename_column,
    no_index_fks,
    no_fulltext_fks,
):
    
    # make plural for more readable code:
    extract_columns = extract_column
    del extract_column

    if extract_columns:
        click.echo("extract_columns={}".format(extract_columns))
    if dbname.endswith(".csv"):
        raise click.BadParameter("dbname must not end with .csv")
    if "." not in dbname:
        dbname += ".db"

    db_existed = os.path.exists(dbname)

    conn = sqlite3.connect(dbname)

    dataframes = []
    csvs = csvs_from_paths(paths)
    sql_type_overrides = None
    for name, path in csvs.items():
        try:
            df = load_csv(path, separator, skip_errors, quoting, shape)
            df.table_name = table or name
            if filename_column:
                df[filename_column] = name
                if shape:
                    shape += ",{}".format(filename_column)
            sql_type_overrides = apply_shape(df, shape)
            apply_dates_and_datetimes(df, date, datetime, datetime_format)
            dataframes.append(df)
        except LoadCsvError as e:
            click.echo("Could not load {}: {}".format(path, e), err=True)

    click.echo("Loaded {} dataframes".format(len(dataframes)))

    # Use extract_columns to build a column:(table,label) dictionary
    foreign_keys = {}
    for col in extract_columns:
        bits = col.split(":")
        if len(bits) == 3:
            foreign_keys[bits[0]] = (bits[1], bits[2])
        elif len(bits) == 2:
            foreign_keys[bits[0]] = (bits[1], "value")
        else:
            foreign_keys[bits[0]] = (bits[0], "value")

    # Now we have loaded the dataframes, we can refactor them
    created_tables = {}
    refactored = refactor_dataframes(
        conn, dataframes, foreign_keys, not no_fulltext_fks
    )
    for df in refactored:
        # This is a bit trickier because we need to
        # create the table with extra SQL for foreign keys
        if replace_tables and table_exists(conn, df.table_name):
            drop_table(conn, df.table_name)
        if table_exists(conn, df.table_name):
            df.to_sql(df.table_name, conn, if_exists="append", index=False)
        else:
            to_sql_with_foreign_keys(
                conn,
                df,
                df.table_name,
                foreign_keys,
                sql_type_overrides,
                primary_keys=primary_key,
                index_fks=not no_index_fks,
            )
            created_tables[df.table_name] = df
        if index:
            for index_defn in index:
                add_index(conn, df.table_name, index_defn)

    # Create FTS tables
    if fts:
        fts_version = best_fts_version()
        if not fts_version:
            conn.close()
            raise click.BadParameter(
                "Your SQLite version does not support any variant of FTS"
            )
        # Check that columns make sense
        for table, df in created_tables.items():
            for fts_column in fts:
                if fts_column not in df.columns:
                    raise click.BadParameter(
                        'FTS column "{}" does not exist'.format(fts_column)
                    )

        generate_and_populate_fts(conn, created_tables.keys(), fts, foreign_keys)

    conn.close()

    if db_existed:
        click.echo(
            "Added {} CSV file{} to {}".format(
                len(csvs), "" if len(csvs) == 1 else "s", dbname
            )
        )
    else:
        click.echo(
            "Created {} from {} CSV file{}".format(
                dbname, len(csvs), "" if len(csvs) == 1 else "s"
            )
        )
1191911
def execute(self, conn, logical_file_name='', block_name='', run_num=-1, validFileOnly=0, migration=False):
        
	sql = ""
	wheresql = ""
	lfn_generator = ""
	run_generator = ""
        if logical_file_name and not isinstance(logical_file_name, list):
            binds = {'logical_file_name': logical_file_name}
            if int(validFileOnly) == 0:
		if migration:   #migration always call with single file and include all files no matter valid or not.
		    sql = self.sql + """ FROM {owner}FILE_LUMIS FL 
				     JOIN {owner}FILES F ON F.FILE_ID = FL.FILE_ID 
				     WHERE F.LOGICAL_FILE_NAME = :logical_file_name 
				  """.format(owner=self.owner)
		else:
		    sql = self.sql + """ , F.LOGICAL_FILE_NAME as LOGICAL_FILE_NAME FROM {owner}FILE_LUMIS FL
				    JOIN {owner}FILES F ON F.FILE_ID = FL.FILE_ID 
                                     WHERE F.LOGICAL_FILE_NAME = :logical_file_name 
                                  """.format(owner=self.owner)
            else:
                sql = self.sql + """ , F.LOGICAL_FILE_NAME as LOGICAL_FILE_NAME FROM {owner}FILE_LUMIS FL 
				     JOIN {owner}FILES F ON F.FILE_ID = FL.FILE_ID
				     JOIN {owner}DATASETS D ON  D.DATASET_ID = F.DATASET_ID
				     JOIN {owner}DATASET_ACCESS_TYPES DT ON  DT.DATASET_ACCESS_TYPE_ID = D.DATASET_ACCESS_TYPE_ID		
				     WHERE F.IS_FILE_VALID = 1 AND F.LOGICAL_FILE_NAME = :logical_file_name 
				     AND DT.DATASET_ACCESS_TYPE in ('VALID', 'PRODUCTION') 
				 """.format(owner=self.owner)
        elif logical_file_name and isinstance(logical_file_name, list):
	    sql = self.sql + """ , F.LOGICAL_FILE_NAME as LOGICAL_FILE_NAME FROM {owner}FILE_LUMIS FL JOIN {owner}FILES F ON F.FILE_ID = FL.FILE_ID """.format(owner=self.owner)	
            lfn_generator, binds = create_token_generator(logical_file_name)
            if int(validFileOnly) == 0:
                wheresql = "WHERE F.LOGICAL_FILE_NAME in (SELECT TOKEN FROM TOKEN_GENERATOR)"
            else:
		sql = sql + """ JOIN {owner}DATASETS D ON  D.DATASET_ID = F.DATASET_ID 
				JOIN {owner}DATASET_ACCESS_TYPES DT ON  DT.DATASET_ACCESS_TYPE_ID = D.DATASET_ACCESS_TYPE_ID
		            """.format(owner=self.owner)			
                wheresql = """ WHERE F.IS_FILE_VALID = 1 AND F.LOGICAL_FILE_NAME in (SELECT TOKEN FROM TOKEN_GENERATOR) 
			       AND DT.DATASET_ACCESS_TYPE in ('VALID', 'PRODUCTION')
			   """
            sql = "{lfn_generator} {sql} {wheresql}".format(lfn_generator=lfn_generator, sql=sql, wheresql=wheresql)
        elif block_name:
            binds = {'block_name': block_name}
            if int(validFileOnly) == 0:
                sql = self.sql + """ , F.LOGICAL_FILE_NAME as LOGICAL_FILE_NAME FROM {owner}FILE_LUMIS FL JOIN {owner}FILES F ON F.FILE_ID = FL.FILE_ID  
				     JOIN {owner}BLOCKS B ON B.BLOCK_ID = F.BLOCK_ID  
				     WHERE B.BLOCK_NAME = :block_name""".format(owner=self.owner)
            else:
                sql = self.sql + """ , F.LOGICAL_FILE_NAME as LOGICAL_FILE_NAME FROM {owner}FILE_LUMIS FL JOIN {owner}FILES F ON F.FILE_ID = FL.FILE_ID 
				     JOIN {owner}DATASETS D ON  D.DATASET_ID = F.DATASET_ID 
				     JOIN {owner}DATASET_ACCESS_TYPES DT ON  DT.DATASET_ACCESS_TYPE_ID = D.DATASET_ACCESS_TYPE_ID 
				     JOIN {owner}BLOCKS B ON B.BLOCK_ID = F.BLOCK_ID
				     WHERE F.IS_FILE_VALID = 1 AND B.BLOCK_NAME = :block_name 
				     AND DT.DATASET_ACCESS_TYPE in ('VALID', 'PRODUCTION')	
				""".format(owner=self.owner)
        else:
                dbsExceptionHandler('dbsException-invalid-input2', "FileLumi/List: Either logocal_file_name or block_name must be provided.", self.logger.exception, "FileLumi/List: Either logocal_file_name or block_name must be provided.")
          #
        if run_num != -1:
            run_list = []
            wheresql_run_list=''
            wheresql_run_range=''
            for r in parseRunRange(run_num):
                if isinstance(r, basestring) or isinstance(r, int) or isinstance(r, long) or isinstance(r, str):
                    run_list.append(str(r))
                if isinstance(r, run_tuple):
                    if r[0] == r[1]:
                        dbsExceptionHandler('dbsException-invalid-input2', "DBS run range must be apart at least by 1.",
			self.logger.exception, "DBS run range must be apart at least by 1.")
                    wheresql_run_range = " FL.RUN_NUM between :minrun and :maxrun "
                    binds.update({"minrun":r[0]})
                    binds.update({"maxrun":r[1]})
            #
            if run_list:
		if len(run_list) == 1:
		    wheresql_run_list = " fl.RUN_NUM = :single_run "
		    binds.update({"single_run": long(run_list[0])})

		else:
		    wheresql_run_list = " fl.RUN_NUM in (SELECT TOKEN FROM TOKEN_GENERATOR) "
                    run_generator, run_binds = create_token_generator(run_list)
                    sql =  "{run_generator}".format(run_generator=run_generator) + sql
                    binds.update(run_binds)

            if wheresql_run_range and wheresql_run_list:
                sql += " and (" + wheresql_run_range + " or " +  wheresql_run_list + " )"
            elif wheresql_run_range and not wheresql_run_list:
                sql += " and " + wheresql_run_range
            elif not wheresql_run_range and wheresql_run_list:
                sql += " and " + wheresql_run_list
        self.logger.debug(sql) 
	self.logger.debug(binds)
	if run_generator and lfn_generator:
		dbsExceptionHandler('dbsException-invalid-input2', "listFileLumiArray support single list of lfn or run_num. ",
			self.logger.exception, "listFileLumiArray support single list of lfn or run_num. ")
        cursors = self.dbi.processData(sql, binds, conn, transaction=False, returnCursor=True)
        result=[]
	file_run_lumi={}
        event_ct=False
        for i in cursors:
            result.extend(self.formatCursor(i, size=100))
        #for migration, we need flat format to load the data into another DB.
        #self.logger.error(result) 
        if migration:
            #YG 09/2015. 
	    for item in result:
		yield item
	else:
            if result and result[0]['event_count']: 
                event_ct = True
	    for i in result:
		r = i['run_num']
		f = i['logical_file_name']
                if event_ct:
                    file_run_lumi.setdefault((f, r), []).append([i['lumi_section_num'], i['event_count']])
                else:
                    file_run_lumi.setdefault((f, r), []).append(i['lumi_section_num'])
	    for k, v in file_run_lumi.iteritems():
                if event_ct:
                    lumi=[]
                    event=[]
                    for le in v:
                        lumi.append(le[0])
                        event.append(le[1])
                    yield {'logical_file_name':k[0], 'run_num':k[1], 'lumi_section_num':lumi, 'event_count':event}
                else:
                    yield {'logical_file_name':k[0], 'run_num':k[1], 'lumi_section_num':v}
        del file_run_lumi
        del result
886366
def serve(
    files,
    immutable,
    host,
    port,
    debug,
    reload,
    cors,
    sqlite_extensions,
    inspect_file,
    metadata,
    template_dir,
    plugins_dir,
    static,
    memory,
    config,
    version_note,
    help_config,
):
    """"""
    if help_config:
        formatter = formatting.HelpFormatter()
        with formatter.section("Config options"):
            formatter.write_dl([
                (option.name, '{} (default={})'.format(
                    option.help, option.default
                ))
                for option in CONFIG_OPTIONS
            ])
        click.echo(formatter.getvalue())
        sys.exit(0)
    if reload:
        import hupper

        reloader = hupper.start_reloader("datasette.cli.serve")
        reloader.watch_files(files)
        if metadata:
            reloader.watch_files([metadata.name])

    inspect_data = None
    if inspect_file:
        inspect_data = json.load(open(inspect_file))

    metadata_data = None
    if metadata:
        metadata_data = json.loads(metadata.read())

    click.echo("Serve! files={} (immutables={}) on port {}".format(files, immutable, port))
    ds = Datasette(
        files,
        immutables=immutable,
        cache_headers=not debug and not reload,
        cors=cors,
        inspect_data=inspect_data,
        metadata=metadata_data,
        sqlite_extensions=sqlite_extensions,
        template_dir=template_dir,
        plugins_dir=plugins_dir,
        static_mounts=static,
        config=dict(config),
        memory=memory,
        version_note=version_note,
    )
    # Force initial hashing/table counting
    ds.inspect()
    ds.app().run(host=host, port=port, debug=debug)
176873
public function moveMigrationFiles()
    {
        $databaseDirectory = base_path('Modules/'.$this->module.'/database');
        if (!$this->files->exists($databaseDirectory.'/migrations')) {
            return;
        }
        $files = $this->files->files($databaseDirectory.'/migrations');
        foreach ($files as $from) {
            $file = basename($from);
            $to = base_path('database/migrations/'.$file);
            $this->files->move($from, $to);
        }
        $this->files->deleteDirectory($databaseDirectory);
    }
769390
def LoadFile(f, table_name, conn):
  """"""
  reader = csv.reader(f)
  header = next(reader)

  columns = []
  for n in header:
    n = n.replace(' ', '')
    n = n.replace('-', '_')
    columns.append(n)

  create_columns = []
  column_types = {}
  for n in columns:
    if n in column_types:
      create_columns.append("%s %s" % (n, column_types[n]))
    else:
      create_columns.append("%s INTEGER" % (n))

  c = conn.cursor()
  try:
    c.execute("CREATE TABLE %s (%s)" % (table_name, ",".join(create_columns)))
  except sqlite.OperationalError:
    # Likely table exists
    print("table %s already exists?" % (table_name))
    for create_column in create_columns:
      try:
        c.execute("ALTER TABLE %s ADD COLUMN %s" % (table_name, create_column))
      except sqlite.OperationalError:
        # Likely it already exists
        print("column %s already exists in %s?" % (create_column, table_name))

  placeholders = ",".join(["?"] * len(columns))
  insert_values = "INSERT INTO %s (%s) VALUES (%s)" % (table_name, ",".join(columns), placeholders)

  #c.execute("BEGIN TRANSACTION;")
  for row in reader:
    if row:
      if len(row) < len(columns):
        row.extend([None] * (len(columns) - len(row)))
      c.execute(insert_values, row)
  #c.execute("END TRANSACTION;")
  conn.commit()
719619
def load_stored_proc(op, filelist):
    
    for filename in filelist:
        sqlfile = get_local_filepath(filename)
        # Capturing "file not exists" here rather than allowing
        # an exception to be thrown. Some of the rollback scripts
        # would otherwise throw unhelpful exceptions when a SQL
        # file is removed from the repo.
        if not os.path.isfile(sqlfile):
            warnings.warn(
                "Did not find %r. Continuing migration." % sqlfile,
                UserWarning,
                2
            )
            continue
        with open(sqlfile, 'r') as stored_proc:
            op.execute(stored_proc.read())
1333510
def main(database_dir, target_dir):
    """"""
    if not os.path.isdir(database_dir):
        raise click.ClickException("Database directory does not exist!")
    try:
        os.makedirs(target_dir)
    except:
        pass
    try:
        parse(database_dir, target_dir)
    except CronosException as ex:
        raise click.ClickException(ex.message)
77414
def _sincedb_update_position(self, lines=0, force_update=False):
        
        if not self._sincedb_path:
            return False

        self._line_count = self._line_count + lines
        old_count = self._line_count_sincedb
        lines = self._line_count

        current_time = int(time.time())
        if not force_update:
            if self._last_sincedb_write and current_time - self._last_sincedb_write <= self._sincedb_write_interval:
                return False

            if old_count == lines:
                return False

        self._sincedb_init()

        self._last_sincedb_write = current_time

        self._log_debug('updating sincedb to {0}'.format(lines))

        conn = sqlite3.connect(self._sincedb_path, isolation_level=None)
        cursor = conn.cursor()
        query = 'insert or replace into sincedb (fid, filename) values (:fid, :filename);'
        cursor.execute(query, {
            'fid': self._fid,
            'filename': self._filename
        })

        query = 'update sincedb set position = :position where fid = :fid and filename = :filename'
        cursor.execute(query, {
            'fid': self._fid,
            'filename': self._filename,
            'position': lines,
        })
        conn.close()

        self._line_count_sincedb = lines

        return True
1080934
@InterfaceAudience.Private
    private void upgradeOldDatabaseFiles(File dir) throws IOException {
        if (dir == null) throw new IllegalArgumentException("dir argument is null.");
        if (!dir.exists() || !dir.isDirectory() || !dir.canRead() || !dir.canWrite())
            throw new IllegalArgumentException(String.format(Locale.ENGLISH,
                    "dir[%s] might not exist, not be a directory, or not have read/write permission.", dir));

        File[] files = dir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File file, String name) {
                return name.endsWith(kV1DBExtension);
            }
        });

        // https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles(java.io.FilenameFilter)
        // returns: Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
        if (files == null)
            throw new IOException(String.format(Locale.ENGLISH,
                    "Error in File.listFiles(): dir[%s]: dir might not be directory, or i/o error occurs.", dir));

        for (File file : files) {
            String filename = file.getName();
            String name = nameOfDatabaseAtPath(filename);
            String oldDbPath = new File(dir, filename).getAbsolutePath();
            if (!upgradeDatabase(name, oldDbPath, true))
                throw new RuntimeException("Database upgrade failed for: " + name);
        }
    }
894684
def move_file(src_root_path, src_path, dst_root_path, dst_path, action = 'move')
      # Entry point
      url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/movefile"

      # Payload
      payload = {}
      payload["srcRootPath"] = src_root_path # 'app' or 'drive'
      payload["srcPath"] = src_path
      payload["destRootPath"] = dst_root_path # 'app' or 'drive'
      payload["destPath"] = dst_path
      payload["action"] = action

      # API call
      uri = URI(url)
      http = Net::HTTP.new(uri.host, uri.port)
      req = Net::HTTP::Post.new(uri.path, {
        'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
        'Content-Type' => 'application/json'
      })
      req.body = payload.to_json
      res = http.request(req)
      res.code == "200" ? true : JSON.parse(res.body)
    end
1362519
function filesPatch(oldFile, newFile, options) {
  let { diff, toFile } = utils;
  let opts = options || {};

  oldFile = toFile(oldFile, options);
  newFile = toFile(newFile, options);

  let nameA = oldFile.relative;
  let nameB = newFile.relative;

  let strA = oldFile.contents.toString();
  let strB = newFile.contents.toString();

  return diff.createTwoFilesPatch(nameA, nameB, strA, strB, opts.oldHeader, opts.newHeader, opts);
}
19644
def get_file(db_folder, file_name):
    """"""
    if not os.path.isdir(db_folder):
        return
    file_name = file_name.lower().strip()
    for cand_name in os.listdir(db_folder):
        if cand_name.lower().strip() == file_name:
            return os.path.join(db_folder, cand_name)
1300181
function moveFilesToRoot(subdir) {
  return exec(`mv ${docPath}/${subdir}/* ${docPath}`)
    .then(() => {
      exec(`rmdir ${docPath}/${subdir}`);
    })
    .catch(e => console.error(e));
}