Create a new file on github

        :param file: File to create
        :return: File or self.ProxyError
773238
def put(self, file):
        
        input_ = {
            "message": file.logs,
            "author": file.author.dict(),
            "content": file.base64,
            "branch": file.branch
        }
        uri = "{api}/repos/{origin}/contents/{path}".format(
            api=self.github_api_url,
            origin=self.origin,
            path=file.path
        )
        data = self.request("PUT", uri, data=input_)

        if data.status_code == 201:
            file.pushed = True
            return file
        else:
            decoded_data = json.loads(data.content.decode("utf-8"))
            return self.ProxyError(
                data.status_code, (decoded_data, "message"),
                step="put", context={
                    "uri": uri,
                    "params": input_
                }
            )
512970
function expectedFile(file) {
  const filePath = path.resolve(__dirname, 'expected', file);
  return new File({
    path: filePath,
    cwd: __dirname,
    base: path.resolve(__dirname, 'expected', path.dirname(file)),
    contents: fs.readFileSync(filePath)
  });
}
771205
def create_or_open(file_name, initial_template_file_name, args):
    
    file = None
    if not os.path.isfile(
        os.path.join(
            args['django_application_folder'],
            file_name
        )
    ):
        # If file_name does not exists, create
        file = codecs.open(
            os.path.join(
                args['django_application_folder'],
                file_name
            ),
            'w+',
            encoding='UTF-8'
        )
        print("Creating {}".format(file_name))
        if initial_template_file_name:
            render_template_with_args_in_file(file, initial_template_file_name, **{})
    else:
        # If file exists, just load the file
        file = codecs.open(
            os.path.join(
                args['django_application_folder'],
                file_name
            ),
            'a+',
            encoding='UTF-8'
        )

    return file
536333
def get(self, file):
        
        uri = "{api}/repos/{origin}/contents/{path}".format(
            api=self.github_api_url,
            origin=self.origin,
            path=file.path
        )
        params = {
            "ref": file.branch
        }
        data = self.request("GET", uri, params=params)
        # We update the file blob because it exists and we need it for update
        if data.status_code == 200:
            data = json.loads(data.content.decode("utf-8"))
            file.blob = data["sha"]
        elif data.status_code == 404:
            pass
        else:
            decoded_data = json.loads(data.content.decode("utf-8"))
            return self.ProxyError(
                data.status_code, (decoded_data, "message"),
                step="get", context={
                    "uri": uri,
                    "params": params
                }
            )
        return file
674486
def new(path='.', template=None):
    
    path = abspath(path.rstrip(sep))
    template = template or DEFAULT_TEMPLATE_URL
    render_skeleton(
        template, path,
        include_this=['.gitignore'],
        filter_this=[
            '~*', '*.py[co]',
            '__pycache__', '__pycache__/*',
            '.git', '.git/*',
            '.hg', '.hg/*',
            '.svn', '.svn/*',
        ]
    )
    print(HELP_MSG % (path,))
1219372
def pull_request(self, file):
        
        uri = "{api}/repos/{upstream}/pulls".format(
            api=self.github_api_url,
            upstream=self.upstream,
            path=file.path
        )
        params = {
          "title": "[Proxy] {message}".format(message=file.logs),
          "body": "",
          "head": "{origin}:{branch}".format(origin=self.origin.split("/")[0], branch=file.branch),
          "base": self.master_upstream
        }
        data = self.request("POST", uri, data=params)

        if data.status_code == 201:
            return json.loads(data.content.decode("utf-8"))["html_url"]
        else:
            reply = json.loads(data.content.decode("utf-8"))
            return self.ProxyError(
                data.status_code, reply["message"],
                step="pull_request", context={
                    "uri": uri,
                    "params": params
                }
            )
53113
def new_file(self, path: str, checksum: str=None, to_archive: bool=False,
                 tags: List[models.Tag]=None) -> models.File:
        """"""
        new_file = self.File(path=path, checksum=checksum, to_archive=to_archive, tags=tags)
        return new_file
1287264
def download_from_github(fname, path):
    
    base_url = 'https://github.com/ornlneutronimaging/ImagingReso/blob/master/ImagingReso/reference_data/'
    # Add GitHub junk to the file name for downloading.
    f = fname + '?raw=true'
    url = base_url + f
    block_size = 16384
    req = urlopen(url)

    # Get file size from header
    if sys.version_info[0] < 3:
        file_size = int(req.info().getheaders('Content-Length')[0])
    else:
        file_size = req.length
    # downloaded = 0

    # Check if file already downloaded
    if os.path.exists(fname):
        if os.path.getsize(fname) == file_size:
            print("Skipping downloading '{}'".format(fname))
        else:
            overwrite = input("File size changed, overwrite '{}'? ([y]/n) ".format(fname))
            if overwrite.lower().startswith('n'):
                print("Local file '{}' kept without overwriting.".format(fname))

    # Copy file to disk
    print("Downloading '{}'... ".format(fname))
    with open(fname, 'wb') as fh:
        while True:
            chunk = req.read(block_size)
            if not chunk:
                break
            fh.write(chunk)
            # downloaded += len(chunk)
        print('')
    print('Download completed.')
    print("Unzipping '{}'... ".format(fname))

    _database_zip = zipfile.ZipFile(fname)
    _database_zip.extractall(path=path)
    print("'{}' has been unzipped and database '{}' is ready to use.".format(fname, fname.replace('.zip', '')))

    os.remove(fname)
    print("'{}' has been deleted".format(fname))
552404
def add_file(self, name="", hashalg="", hash="", comClasses=None, 
                 typelibs=None, comInterfaceProxyStubs=None, 
                 windowClasses=None):
        
        self.files.append(File(name, hashalg, hash, comClasses, 
                          typelibs, comInterfaceProxyStubs, windowClasses))
895643
def open(self, file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None):
        
        urn = Urn(file)
        urn_path = urn.path()

        remote_file_exists = self.check(urn_path)

        if not remote_file_exists:
            if 'r' in mode:
                raise RemoteResourceNotFound(urn_path)
        elif self.is_dir(urn_path):
            raise OptionNotValid(name='file', value=file)

        with tempfile.TemporaryDirectory() as temp_dir:
            local_path = f'{temp_dir}{os.path.sep}{file}'

            if remote_file_exists:
                self.download_file(file, local_path)
            else:
                if ('w' in mode or 'a' in mode or 'x' in mode) and os.path.sep in local_path:
                    os.makedirs(local_path.rsplit(os.path.sep, 1)[0], exist_ok=True)

            with open(file=local_path, mode=mode, buffering=buffering, encoding=encoding, errors=errors,
                      newline=newline, closefd=closefd, opener=opener) as f:
                yield f

            if 'w' in mode or 'a' in mode or 'x' in mode:
                self.upload_file(file, local_path)
1215873
def _create_update_from_file(mode='create', uuid=None, path=None):
    '''
    
    '''
    ret = {}
    if not os.path.isfile(path) or path is None:
        ret['Error'] = 'File ({0}) does not exists!'.format(path)
        return ret
    # vmadm validate create|update [-f <filename>]
    cmd = 'vmadm validate {mode} {brand} -f {path}'.format(
        mode=mode,
        brand=get(uuid)['brand'] if uuid is not None else '',
        path=path
    )
    res = __salt__['cmd.run_all'](cmd)
    retcode = res['retcode']
    if retcode != 0:
        ret['Error'] = _exit_status(retcode)
        if 'stderr' in res:
            if res['stderr'][0] == '{':
                ret['Error'] = salt.utils.json.loads(res['stderr'])
            else:
                ret['Error'] = res['stderr']
        return ret
    # vmadm create|update [-f <filename>]
    cmd = 'vmadm {mode} {uuid} -f {path}'.format(
        mode=mode,
        uuid=uuid if uuid is not None else '',
        path=path
    )
    res = __salt__['cmd.run_all'](cmd)
    retcode = res['retcode']
    if retcode != 0:
        ret['Error'] = _exit_status(retcode)
        if 'stderr' in res:
            if res['stderr'][0] == '{':
                ret['Error'] = salt.utils.json.loads(res['stderr'])
            else:
                ret['Error'] = res['stderr']
        return ret
    else:
        if res['stderr'].startswith('Successfully created VM'):
            return res['stderr'][24:]
    return True
851693
function createFile(file) {
    fs.ensureFileSync(file.name);
    fs.writeFileSync(file.name, file.source);
    return;
}
151389
public T addPyFile(String file) {
    checkNotNull(file, "file");
    builder.pyFiles.add(file);
    return self();
  }
1248019
@Override
    public void onFileCreate(File file) {
        try {
            engine.addTemplate(context.getBundle(0), file.toURI().toURL());
        } catch (MalformedURLException e) {
            LOGGER.error("Cannot compute the url of file {}", file.getAbsolutePath(), e);
        }
    }
1318251
public static FileCreationState newFile(final File file) throws IOException
	{
		FileCreationState fileCreationState = FileCreationState.ALREADY_EXISTS;
		if (!file.exists())
		{
			fileCreationState = FileCreationState.FAILED;
			newParentDirectories(file);
			if (file.createNewFile())
			{
				fileCreationState = FileCreationState.CREATED;
			}
		}
		return fileCreationState;
	}
568307
def create_card(self, note=github.GithubObject.NotSet,
                    content_id=github.GithubObject.NotSet,
                    content_type=github.GithubObject.NotSet):
        
        post_parameters = {}
        if isinstance(note, (str, unicode)):
            assert content_id is github.GithubObject.NotSet, content_id
            assert content_type is github.GithubObject.NotSet, content_type
            post_parameters = {"note": note}
        else:
            assert note is github.GithubObject.NotSet, note
            assert isinstance(content_id, int), content_id
            assert isinstance(content_type, (str, unicode)), content_type
            post_parameters = {"content_id": content_id,
                               "content_type": content_type}

        import_header = {"Accept": Consts.mediaTypeProjectsPreview}
        headers, data = self._requester.requestJsonAndCheck(
            "POST",
            self.url + "/cards",
            headers=import_header,
            input=post_parameters
        )
        return github.ProjectCard.ProjectCard(self._requester, headers,
                                              data, completed=True)
1340048
def edit(self, description=github.GithubObject.NotSet, files=github.GithubObject.NotSet):
        
        assert description is github.GithubObject.NotSet or isinstance(description, (str, unicode)), description
        assert files is github.GithubObject.NotSet or all(element is None or isinstance(element, github.InputFileContent) for element in files.itervalues()), files
        post_parameters = dict()
        if description is not github.GithubObject.NotSet:
            post_parameters["description"] = description
        if files is not github.GithubObject.NotSet:
            post_parameters["files"] = {key: None if value is None else value._identity for key, value in files.iteritems()}
        headers, data = self._requester.requestJsonAndCheck(
            "PATCH",
            self.url,
            input=post_parameters
        )
        self._useAttributes(data)