Send apidoc files from the apidoc folder to the browser.
        :param path: the apidoc file.
7128
def __send_static_file(self, path=None):
        

        if not path:
            path = 'index.html'

        file_name = join(self.folder_path, path)

        # the api_project.js has the absolute url
        # hard coded so we replace them by the current url.
        if self.dynamic_url and path == 'api_project.js':
            return self.__send_api_file(file_name)

        if self.allow_absolute_url and path == 'main.js':
            return self.__send_main_file(file_name)

        # Any other apidoc file is treated as a normal static file
        return self.app.send_static_file(file_name)
354854
def add_put(self, path: str, handler: _WebHandler,
                **kwargs: Any) -> AbstractRoute:
        
        return self.add_route(hdrs.METH_PUT, path, handler, **kwargs)
133499
def call_api(self, path, **kwargs):
        '''
        
        '''
        if 'key' not in kwargs:
            kwargs['key'] = self.api_key
        req = requests.get('{0}{1}'.format(self.base_url, path), params=kwargs)

        if req.status_code != requests.codes.ok:
            req.raise_for_status()

        return req.json()
740670
function sendFile(imagePath) {
      response.set(headers);
      response.download(imagePath, request.query.filename);
    }
437656
function sendImg ({ path, res }) {
  res.writeHead(STATUS_OK, {
    'Content-Type': 'image/png'
  })
  fs.createReadStream(path).pipe(res)
}
250485
def get_drive_api_from_file(path):
    
    f = open(path)
    credentials = client.OAuth2Credentials.from_json(f.read())
    return _get_drive_api(credentials)
446541
private void respondWithFile(ChannelHandlerContext ctx, HttpRequest request, String requestPath)
		throws IOException, ParseException {

		// make sure we request the "index.html" in case there is a directory request
		if (requestPath.endsWith("/")) {
			requestPath = requestPath + "index.html";
		}

		if (!requestPath.contains(".")) { // we assume that the path ends in either .html or .js
			requestPath = requestPath + ".json";
		}

		// convert to absolute path
		final File file = new File(rootPath, requestPath);

		if (!file.exists()) {
			// file does not exist. Try to load it with the classloader
			ClassLoader cl = HistoryServerStaticFileServerHandler.class.getClassLoader();

			try (InputStream resourceStream = cl.getResourceAsStream("web" + requestPath)) {
				boolean success = false;
				try {
					if (resourceStream != null) {
						URL root = cl.getResource("web");
						URL requested = cl.getResource("web" + requestPath);

						if (root != null && requested != null) {
							URI rootURI = new URI(root.getPath()).normalize();
							URI requestedURI = new URI(requested.getPath()).normalize();

							// Check that we don't load anything from outside of the
							// expected scope.
							if (!rootURI.relativize(requestedURI).equals(requestedURI)) {
								LOG.debug("Loading missing file from classloader: {}", requestPath);
								// ensure that directory to file exists.
								file.getParentFile().mkdirs();
								Files.copy(resourceStream, file.toPath());

								success = true;
							}
						}
					}
				} catch (Throwable t) {
					LOG.error("error while responding", t);
				} finally {
					if (!success) {
						LOG.debug("Unable to load requested file {} from classloader", requestPath);
						HandlerUtils.sendErrorResponse(
							ctx,
							request,
							new ErrorResponseBody("File not found."),
							NOT_FOUND,
							Collections.emptyMap());
						return;
					}
				}
			}
		}

		if (!file.exists() || file.isHidden() || file.isDirectory() || !file.isFile()) {
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("File not found."),
				NOT_FOUND,
				Collections.emptyMap());
			return;
		}

		if (!file.getCanonicalFile().toPath().startsWith(rootPath.toPath())) {
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("File not found."),
				NOT_FOUND,
				Collections.emptyMap());
			return;
		}

		// cache validation
		final String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
		if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
			SimpleDateFormat dateFormatter = new SimpleDateFormat(StaticFileServerHandler.HTTP_DATE_FORMAT, Locale.US);
			Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

			// Only compare up to the second because the datetime format we send to the client
			// does not have milliseconds
			long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
			long fileLastModifiedSeconds = file.lastModified() / 1000;
			if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
				if (LOG.isDebugEnabled()) {
					LOG.debug("Responding 'NOT MODIFIED' for file '" + file.getAbsolutePath() + '\'');
				}

				StaticFileServerHandler.sendNotModified(ctx);
				return;
			}
		}

		if (LOG.isDebugEnabled()) {
			LOG.debug("Responding with file '" + file.getAbsolutePath() + '\'');
		}

		// Don't need to close this manually. Netty's DefaultFileRegion will take care of it.
		final RandomAccessFile raf;
		try {
			raf = new RandomAccessFile(file, "r");
		} catch (FileNotFoundException e) {
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("File not found."),
				NOT_FOUND,
				Collections.emptyMap());
			return;
		}

		try {
			long fileLength = raf.length();

			HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
			StaticFileServerHandler.setContentTypeHeader(response, file);

			// the job overview should be updated as soon as possible
			if (!requestPath.equals("/joboverview.json")) {
				StaticFileServerHandler.setDateAndCacheHeaders(response, file);
			}
			if (HttpHeaders.isKeepAlive(request)) {
				response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
			}
			HttpHeaders.setContentLength(response, fileLength);

			// write the initial line and the header.
			ctx.write(response);

			// write the content.
			ChannelFuture lastContentFuture;
			if (ctx.pipeline().get(SslHandler.class) == null) {
				ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
				lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
			} else {
				lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
					ctx.newProgressivePromise());
				// HttpChunkedInput will write the end marker (LastHttpContent) for us.
			}

			// close the connection, if no keep-alive is needed
			if (!HttpHeaders.isKeepAlive(request)) {
				lastContentFuture.addListener(ChannelFutureListener.CLOSE);
			}
		} catch (Exception e) {
			raf.close();
			LOG.error("Failed to serve file.", e);
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("Internal server error."),
				INTERNAL_SERVER_ERROR,
				Collections.emptyMap());
		}
	}
1091869
def load(self, path):
        
        with open(path) as f:
            code = f.read()
            exec(code, {}, self.__dict__)
871988
def send(path, method, content = '')

      uri = BASE_URI + path
      response = @client.fetch_protected_resource(
        :uri => uri,
        :method => method,
        :body  => content,
        :headers => {'Content-type' => 'application/json'}
      )

      check_for_errors(response)

      return response
    end
608559
def save_to_file(self, path):
        

        with open(path, 'w') as out:
            out.write(json.dumps(self.get_dict()))
574166
public boolean sendResourceFile(String path, HttpServletResponse response) throws IOException
    {
        URL url = null;
        try {
            url = ClassServiceUtility.getClassService().getResourceURL(path, baseURL, null, this.getClass().getClassLoader());
        } catch (RuntimeException e) {
            e.printStackTrace();    // ???
        }        	
        if (url == null)
            return false;   // Not found
        InputStream inStream = null;
        try {
            inStream = url.openStream();
        } catch (Exception e) {
            return false;   // Not found
        }

        // Todo may want to add cache info (using bundle lastModified).
        OutputStream writer = response.getOutputStream();
        if (response.getContentType() == null)
        {
            if (httpContext != null)
                response.setContentType(httpContext.getMimeType(path));
            else
            	response.setContentType(FileHttpContext.getDefaultMimeType(path));
        }
        copyStream(inStream, writer, true); // Ignore errors, as browsers do weird things
        writer.close();
        inStream.close();
        return true;
    }
206954
def add_path(self, path, path_filter=None):
        
        for root, _, files in os.walk(path):
            for filename in files:
                full_path_and_filename = os.path.join(root, filename)
                if path_filter is None or path_filter(full_path_and_filename):
                    relative_path_and_filename = full_path_and_filename.replace(path + '/', '')
                    with open(full_path_and_filename, 'rb') as handle:
                        self.files[relative_path_and_filename] = b64encode(handle.read()).decode('utf-8')
1242549
def file(self, path, status=200, set_content_length=True):
        
        ct, encoding = mimetypes.guess_type(path)
        if not ct:
            ct = 'application/octet-stream'
        if encoding:
            self.headers[aiohttp.hdrs.CONTENT_ENCODING] = encoding
        self.content_type = ct

        if set_content_length:
            st = os.stat(path)
            self.last_modified = st.st_mtime
            self.headers[aiohttp.hdrs.CONTENT_LENGTH] = str(st.st_size)
        else:
            self.enable_chunked_encoding()

        self.set_status(status)

        try:
            with open(path, 'rb') as fobj:
                yield from self.prepare(self._request)

                while True:
                    data = fobj.read(4096)
                    if not data:
                        break
                    yield from self.write(data)
                    yield from self.drain()

        except FileNotFoundError:
            raise aiohttp.web.HTTPNotFound()
        except PermissionError:
            raise aiohttp.web.HTTPForbidden()
496848
def POST(self, path, body, xml=True):
        
        url = self._absolute_url(path)
        headers = dict(self.headers)
        if xml:
            headers['Content-Type'] = 'application/xml'
            headers['Accept'] = 'application/xml'
        else:
            headers['Content-Type'] = 'application/json'
            headers['Accept'] = 'application/json'

        resp = requests.post(url, data=body, headers=headers, verify=self.verify_ssl)
        if resp.status_code != 200:
            raise MispTransportError('POST %s: returned status=%d', path, resp.status_code)
        return resp.content
865746
async def put(self, path=''):
        
        self.log.info("Attempt publishing to %s", path)

        if path == '' or path == '/':
            raise web.HTTPError(400, "Must provide a path for publishing")

        model = self.get_json_body()
        if model:
            await self._publish(model, path.lstrip('/'))
        else:
            raise web.HTTPError(400, "Cannot publish an empty model")
1350819
def from_url(cls, path):
        
        if os.path.isfile(path):
            with open(path) as fd:
                data = fd.read()
        else:
            try:
                response = urllib.urlopen(path)
                if response.code >= 300:
                    raise RuntimeError('Unable to load repo from %s' % path)

                data = response.read()
                response.close()
            except IOError:
                raise RuntimeError(
                    'Unable to load repo from %s (IO error)' % path
                )

        return cls(json.loads(data), path)
1076418
def addFile(self, path, msg=""):
        """"""
        item = Item.from_path(repo=self.repo, path=path)
        self.addItem(item)