Restore instance from URL
195044
def instance_from_url(url, user=None):
    
    # XXX: This circular dependency will be removed then filter_queryset_for_user
    # will be moved to model manager method
    from waldur_core.structure.managers import filter_queryset_for_user

    url = clear_url(url)
    match = resolve(url)
    model = get_model_from_resolve_match(match)
    queryset = model.objects.all()
    if user is not None:
        queryset = filter_queryset_for_user(model.objects.all(), user)
    return queryset.get(**match.kwargs)
279517
private void restoreInstanceDirectoryFromPath(Path source, String instanceRocksDBPath) throws IOException {

		FileSystem fileSystem = source.getFileSystem();

		final FileStatus[] fileStatuses = fileSystem.listStatus(source);

		if (fileStatuses == null) {
			throw new IOException("Cannot list file statues. Directory " + source + " does not exist.");
		}

		for (FileStatus fileStatus : fileStatuses) {
			final Path filePath = fileStatus.getPath();
			final String fileName = filePath.getName();
			File restoreFile = new File(source.getPath(), fileName);
			File targetFile = new File(instanceRocksDBPath, fileName);
			if (fileName.endsWith(SST_FILE_SUFFIX)) {
				// hardlink'ing the immutable sst-files.
				Files.createLink(targetFile.toPath(), restoreFile.toPath());
			} else {
				// true copy for all other files.
				Files.copy(restoreFile.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
			}
		}
	}
589069
public void restoreOriginal() {
    if (original == null) {
      throw new IllegalStateException("Original EbeanServer instance is null");
    }
    if (original.getName() == null) {
      throw new IllegalStateException("Original EbeanServer name is null");
    }

    // restore the original EbeanServer back
    Ebean.mock(original.getName(), original, true);
  }
995213
void restoreAllInstances() {

		// instancesMngr() instead of this.instancesMngr (for unit tests).
		this.logger.fine( "Restoring all the instance states from the current target handlers." );
		for( ManagedApplication ma : this.applicationMngr.getManagedApplications()) {

			// Build a new snapshot on every loop
			List<TargetHandler> snapshot = this.defaultTargetHandlerResolver.getTargetHandlersSnapshot();
			for( TargetHandler targetHandler : snapshot )
				instancesMngr().restoreInstanceStates( ma, targetHandler );
		}
	}
44541
def restore_session(self):
        

        session = [foundations.strings.to_string(path)
                   for path in self.__settings.get_key(self.__settings_section, "session").toStringList()
                   if foundations.common.path_exists(path)]

        LOGGER.debug("> Restoring session :'{0}'.".format(session))
        success = True
        for path in session:
            if os.path.isfile(path):
                success *= self.load_file(path)
            else:
                success *= self.add_project(path)
        return success
1069015
def from_url(cls, url, filename=None, chunk_size=CHUNK_SIZE):
        
        pipe = _WebPipe(url, chunk_size=chunk_size)
        if filename is None:
            filename = pipe.name

        return cls(pipe, filename, chunk_size)
1007661
function ( uri ) {
		var obj    = {},
		    parsed = {};

		if ( uri === undefined ) {
			uri = !server ? location.href : "";
		}

		if ( !server ) {
			obj = document.createElement( "a" );
			obj.href = uri;
		}
		else {
			obj = url.parse( uri );
		}

		if ( server ) {
			utility.iterate( obj, function ( v, k ) {
				if ( v === null ) {
					obj[k] = undefined;
				}
			});
		}

		parsed = {
			auth     : server ? null : regex.auth.exec( uri ),
			protocol : obj.protocol || "http:",
			hostname : obj.hostname || "localhost",
			port     : obj.port ? number.parse( obj.port, 10 ) : "",
			pathname : obj.pathname,
			search   : obj.search   || "",
			hash     : obj.hash     || "",
			host     : obj.host     || "localhost"
		};

		// 'cause IE is ... IE; required for data.batch()
		if ( client.ie ) {
			if ( parsed.protocol === ":" ) {
				parsed.protocol = location.protocol;
			}

			if ( string.isEmpty( parsed.hostname ) ) {
				parsed.hostname = location.hostname;
			}

			if ( string.isEmpty( parsed.host ) ) {
				parsed.host = location.host;
			}

			if ( parsed.pathname.charAt( 0 ) !== "/" ) {
				parsed.pathname = "/" + parsed.pathname;
			}
		}

		parsed.auth  = obj.auth || ( parsed.auth === null ? "" : parsed.auth[1] );
		parsed.href  = obj.href || ( parsed.protocol + "//" + ( string.isEmpty( parsed.auth ) ? "" : parsed.auth + "@" ) + parsed.host + parsed.pathname + parsed.search + parsed.hash );
		parsed.path  = obj.path || parsed.pathname + parsed.search;
		parsed.query = utility.queryString( null, parsed.search );

		return parsed;
	}
354916
def restore
      return unless File.exist?(Setting[:histfile])

      File.readlines(Setting[:histfile]).reverse_each { |l| push(l.chomp) }
    end
446070
def restore(self, request, *args, **kwargs):
        
        paths = request.path_info.split('/')
        object_id_index = paths.index("restore") - 2
        object_id = paths[object_id_index]

        obj = super(VersionedAdmin, self).get_object(request, object_id)
        obj.restore()
        admin_wordIndex = object_id_index - 3
        path = "/%s" % ("/".join(paths[admin_wordIndex:object_id_index]))

        opts = self.model._meta
        msg_dict = {
            'name': force_text(opts.verbose_name),
            'obj': format_html('<a href="{}">{}</a>',
                               urlquote(request.path), obj),
        }

        msg = format_html(_('The {name} "{obj}" was restored successfully.'),
                          **msg_dict)
        self.message_user(request, msg, messages.SUCCESS)
        return HttpResponseRedirect(path)
343316
def reconstruct_url(environ, port):
    
    # From WSGI spec, PEP 333
    url = environ.get('PATH_INFO', '')
    if not url.startswith(('http://', 'https://')):
        url = '%s://%s%s' % (
            environ['wsgi.url_scheme'],
            environ['HTTP_HOST'],
            url
        )
    # Fix ;arg=value in url
    if '%3B' in url:
        url, arg = url.split('%3B', 1)
        url = ';'.join([url, arg.replace('%3D', '=')])
    # Stick query string back in
    try:
        query_string = environ['QUERY_STRING']
    except KeyError:
        pass
    else:
        url += '?' + query_string

    parsed = urlparse(url)
    replaced = parsed._replace(netloc="localhost:{}".format(port))
    url = urlunparse(replaced)
    environ['reconstructed_url'] = url
    return url
104721
def from_url(cls, url, **kwargs):
        """"""
        url = urllib3.util.parse_url(url)
        if url.host:
            kwargs.setdefault('host', url.host)

        if url.port:
            kwargs.setdefault('port', url.port)

        if url.scheme == 'https':
            kwargs.setdefault('connection_class', urllib3.HTTPSConnectionPool)

        return cls(**kwargs)
831207
def deleted(self, instance):
        
        self.session_manager.delete(instance, commit=True)
        return '', HTTPStatus.NO_CONTENT
1262158
def RestoreSnapshot(self,name=None):
		

		if not len(self.data['details']['snapshots']):  raise(clc.CLCException("No snapshots exist"))
		if name is None:  name = self.GetSnapshots()[0]

		name_links = [obj['links'] for obj in self.data['details']['snapshots'] if obj['name']==name][0]
		return(clc.v2.Requests(clc.v2.API.Call('POST',
											   [obj['href'] for obj in name_links if obj['rel']=='restore'][0],
											   session=self.session),
							   alias=self.alias,
							   session=self.session))
193935
function (url) {
        url = _.trimStart(url);
        var pathVariables,
            p = {
                raw: url
            };

        // extract the protocol
        p.protocol = _.get(url.match(regexes.extractProtocol), GET_1);
        _.isString(p.protocol) && (url = url.substr(p.protocol.length + 3)); // remove that damn protocol from url

        // extract the host
        p.host = _.get(url.match(regexes.extractHost), GET_1);

        // if host exists there are a lot you can extract from it
        if (_.isString(p.host)) {
            url = url.substr(p.host.length); // remove host from url

            if ((p.auth = _.get(p.host.match(regexes.extractHostAuth), GET_1))) {
                p.host = p.host.substr(p.auth.length + 1); // remove auth from host
                p.auth = p.auth.split(AUTH_SEPARATOR);
                p.auth = {
                    user: p.auth[0],
                    password: p.auth[1]
                };
            }

            // extract the port from the host
            p.port = _.get(p.host.match(regexes.extractPort), GET_1);
            p.port && (p.host = p.host.substring(0, p.host.length - p.port.length - 1)); // remove port from url

            p.host = _.trim(p.host, DOMAIN_SEPARATOR).split(regexes.splitDomain); // split host by subdomains
        }

        // extract the path
        p.path = _.get(url.match(regexes.extractPath), GET_0);
        if (_.isString(p.path)) {
            url = url.substr(p.path.length);
            p.path && (p.path = p.path.replace(regexes.trimPath, MATCH_1)); // remove leading slash for valid path
            // if path is blank string, we set it to undefined, if '/' then single blank string array
            p.path = p.path ? (p.path === PATH_SEPARATOR ? [E] : p.path.split(PATH_SEPARATOR)) : undefined;
        }

        // extract the query string
        p.query = _.get(url.match(regexes.extractQuery), GET_1);
        _.isString(p.query) && ((url = url.substr(p.query.length + 1)), (p.query = QueryParam.parse(p.query)));

        // extract the hash
        p.hash = _.get(url.match(regexes.extractSearch), GET_1);

        // extract path variables
        pathVariables = _.transform(p.path, function (res, segment) {
            // check if the segment has path variable prefix followed by the variable name.
            if (_.startsWith(segment, PATH_VARIABLE_IDENTIFIER) && segment !== PATH_VARIABLE_IDENTIFIER) {
                res.push({ key: segment.slice(1) }); // remove path variable prefix.
            }
        }, []);
        p.variable = pathVariables.length ? pathVariables : undefined;

        return p;
    }
548123
function it_retains_the_original_state_of_the_instance_duplicated_with_a_new_host()
    {
        $original_uri = (string) $this->getWrappedObject();

        $new_host = $this->withHost("quux.qux");

        $this->__toString()->shouldReturn($original_uri);
    }
237274
def restore(self, remotepath):
		''' 
		'''
		rpath = get_pcs_path(remotepath)
		# by default, only 1000 items, more than that sounds a bit crazy
		pars = {
			'method' : 'listrecycle' }

		self.pd("Searching for fs_id to restore")
		return self.__get(pcsurl + 'file', pars, self.__restore_search_act, rpath)
1027628
private void restoreFromSession(IExtendedRequest extRequest, HttpServletRequest req, String reqURL) {
		HttpSession postparamsession = req.getSession(false);
		if (postparamsession == null) {
			return;
		}
		String previousReq = (String) postparamsession.getAttribute(INITIAL_URL);
		if (previousReq != null && previousReq.equals(reqURL)) {
			try {
				if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
					Tr.debug(tc, "Found the session, restoring POST parameters.");
				}
				extRequest.setMethod("POST");
				Map paramValues = (Map) postparamsession.getAttribute(PARAM_VALUES);

				if (paramValues != null && !paramValues.isEmpty()) {
					if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
						Tr.debug(tc, "Restoring POST paramameters for URL : " + reqURL);
					}
					extRequest.setInputStreamData((HashMap) paramValues);
				}
			} catch (IOException exc) {
				if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
					Tr.debug(tc, "IOException restoring POST parameters onto a cookie: ", new Object[] { exc });
				}
			}
		} else if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
			Tr.debug(tc, "Parameters NOT restored. Original URL : " + previousReq + " req. URL : " + reqURL);
		}

		postparamsession.setAttribute(INITIAL_URL, null);
		postparamsession.setAttribute(PARAM_NAMES, null);
		postparamsession.setAttribute(PARAM_VALUES, null);
	}