_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q7300
IIIFAuth.login_service_description
train
def login_service_description(self): """Login service description. The login service description _MUST_ include the token service description. The authentication pattern is indicated via the profile URI which is built using self.auth_pattern. """ label = 'Login to ' + se...
python
{ "resource": "" }
q7301
IIIFAuth.logout_service_description
train
def logout_service_description(self): """Logout service description.""" label = 'Logout from ' + self.name if (self.auth_type): label = label + ' (' + self.auth_type + ')' return({"@id": self.logout_uri, "profile": self.profile_base + 'logout', ...
python
{ "resource": "" }
q7302
IIIFAuth.access_token_response
train
def access_token_response(self, token, message_id=None): """Access token response structure. Success if token is set, otherwise (None, empty string) give error response. If message_id is set then an extra messageId attribute is set in the response to handle postMessage() responses. ...
python
{ "resource": "" }
q7303
IIIFAuth._generate_random_string
train
def _generate_random_string(self, container, length=20): """Generate a random cookie or token string not in container. The cookie or token should be secure in the sense that it should not be likely to be able guess a value. Because it is not derived from anything else, there is no vulne...
python
{ "resource": "" }
q7304
IIIFAuth.access_cookie
train
def access_cookie(self, account): """Make and store access cookie for a given account. If account is allowed then make a cookie and add it to the dict of accepted access cookies with current timestamp as the value. Return the access cookie. Otherwise return None. """ ...
python
{ "resource": "" }
q7305
IIIFAuth.access_cookie_valid
train
def access_cookie_valid(self, cookie, log_msg): """Check access cookie validity. Returns true if the access cookie is valid. The set of allowed access cookies is stored in self.access_cookies. Uses log_msg as prefix to info level log message of accetance or rejection. "...
python
{ "resource": "" }
q7306
IIIFAuth.access_token
train
def access_token(self, cookie): """Make and store access token as proxy for the access cookie. Create an access token to act as a proxy for access cookie, add it to the dict of accepted access tokens with (cookie, current timestamp) as the value. Return the access token. Return None if ...
python
{ "resource": "" }
q7307
IIIFAuth.access_token_valid
train
def access_token_valid(self, token, log_msg): """Check token validity. Returns true if the token is valid. The set of allowed access tokens is stored in self.access_tokens. Uses log_msg as prefix to info level log message of acceptance or rejection. """ if (toke...
python
{ "resource": "" }
q7308
IIIFAuthFlask.info_authn
train
def info_authn(self): """Check to see if user if authenticated for info.json. Must have Authorization header with value that has the form "Bearer TOKEN", where TOKEN is an appropriate and valid access token. """ authz_header = request.headers.get('Authorization', '[none]...
python
{ "resource": "" }
q7309
IIIFAuthFlask.image_authn
train
def image_authn(self): """Check to see if user if authenticated for image requests. Must have access cookie with an appropriate value. """ authn_cookie = request.cookies.get( self.access_cookie_name, default='[none]') return self.access_cookie_valid(authn_cookie, "im...
python
{ "resource": "" }
q7310
IIIFAuthFlask.logout_handler
train
def logout_handler(self, **args): """Handler for logout button. Delete cookies and return HTML that immediately closes window """ response = make_response( "<html><script>window.close();</script></html>", 200, {'Content-Type': "text/html"}) response.set_c...
python
{ "resource": "" }
q7311
IIIFManipulatorNetpbm.find_binaries
train
def find_binaries(cls, tmpdir=None, shellsetup=None, pnmdir=None): """Set instance variables for directory and binary locations. FIXME - should accept params to set things other than defaults. """ cls.tmpdir = ('/tmp' if (tmpdir is None) else tmpdir) # Shell setup command (e.g s...
python
{ "resource": "" }
q7312
IIIFManipulatorNetpbm.do_first
train
def do_first(self): """Create PNM file from input image file.""" pid = os.getpid() self.basename = os.path.join(self.tmpdir, 'iiif_netpbm_' + str(pid)) outfile = self.basename + '.pnm' # Convert source file to pnm filetype = self.file_type(self.srcfile) if (filety...
python
{ "resource": "" }
q7313
IIIFManipulatorNetpbm.file_type
train
def file_type(self, file): """Use python-magic to determine file type. Returns 'png' or 'jpg' on success, nothing on failure. """ try: magic_text = magic.from_file(file) if (isinstance(magic_text, bytes)): # In python2 and travis python3 (?!) deco...
python
{ "resource": "" }
q7314
IIIFManipulatorNetpbm.image_size
train
def image_size(self, pnmfile): """Get width and height of pnm file. simeon@homebox src>pnmfile /tmp/214-2.png /tmp/214-2.png:PPM raw, 100 by 100 maxval 255 """ pout = os.popen(self.shellsetup + self.pnmfile + ' ' + pnmfile, 'r') pnmfileout = pout.read(200) pout....
python
{ "resource": "" }
q7315
IIIFManipulatorNetpbm.shell_call
train
def shell_call(self, shellcmd): """Shell call with necessary setup first.""" return(subprocess.call(self.shellsetup + shellcmd, shell=True))
python
{ "resource": "" }
q7316
IIIFManipulatorNetpbm.cleanup
train
def cleanup(self): """Clean up any temporary files.""" for file in glob.glob(self.basename + '*'): os.unlink(file)
python
{ "resource": "" }
q7317
IIIFError.image_server_response
train
def image_server_response(self, api_version=None): """Response, code and headers for image server error response. api_version selects the format (XML of 1.0). The return value is a tuple of response - body of HTTP response status - the HTTP status code headers - a ...
python
{ "resource": "" }
q7318
IIIFError.as_xml
train
def as_xml(self): """XML representation of the error to be used in HTTP response. This XML format follows the IIIF Image API v1.0 specification, see <http://iiif.io/api/image/1.0/#error> """ # Build tree spacing = ("\n" if (self.pretty_xml) else "") root = Elemen...
python
{ "resource": "" }
q7319
IIIFError.as_txt
train
def as_txt(self): """Text rendering of error response. Designed for use with Image API version 1.1 and above where the error response is suggested to be text or html but not otherwise specified. Intended to provide useful information for debugging. """ s = "IIIF Image Se...
python
{ "resource": "" }
q7320
IIIFAuthGoogle.login_handler
train
def login_handler(self, config=None, prefix=None, **args): """OAuth starts here, redirect user to Google.""" params = { 'response_type': 'code', 'client_id': self.google_api_client_id, 'redirect_uri': self.scheme_host_port_prefix( 'http', config.host, ...
python
{ "resource": "" }
q7321
IIIFAuthGoogle.google_get_token
train
def google_get_token(self, config, prefix): """Make request to Google API to get token.""" params = { 'code': self.request_args_get( 'code', default=''), 'client_id': self.google_api_client_id, 'client_secret': self.google_api_client_se...
python
{ "resource": "" }
q7322
IIIFAuthGoogle.google_get_data
train
def google_get_data(self, config, response): """Make request to Google API to get profile data for the user.""" params = { 'access_token': response['access_token'], } payload = urlencode(params) url = self.google_api_url + 'userinfo?' + payload req = Request(u...
python
{ "resource": "" }
q7323
IIIFManipulator.compliance_uri
train
def compliance_uri(self): """Compliance URI based on api_version. Value is based on api_version and complicance_level, will be None if either are unset/unrecognized. The assumption here is that the api_version and level are orthogonal, override this method if that isn't true. ...
python
{ "resource": "" }
q7324
IIIFManipulator.derive
train
def derive(self, srcfile=None, request=None, outfile=None): """Do sequence of manipulations for IIIF to derive output image. Named argments: srcfile -- source image file request -- IIIFRequest object with parsed parameters outfile -- output image file. If set the the output file...
python
{ "resource": "" }
q7325
IIIFManipulator.do_region
train
def do_region(self, x, y, w, h): """Null implementation of region selection.""" if (x is not None): raise IIIFError(code=501, parameter="region", text="Null manipulator supports only region=/full/.")
python
{ "resource": "" }
q7326
IIIFManipulator.do_quality
train
def do_quality(self, quality): """Null implementation of quality.""" if (self.api_version >= '2.0'): if (quality != "default"): raise IIIFError(code=501, parameter="default", text="Null manipulator supports only quality=default.") else:...
python
{ "resource": "" }
q7327
IIIFManipulator.do_format
train
def do_format(self, format): """Null implementation of format selection. This is the last step, this null implementation does not accept any specification of a format because we don't even know what the input format is. """ if (format is not None): raise IIIF...
python
{ "resource": "" }
q7328
IIIFManipulator.region_to_apply
train
def region_to_apply(self): """Return the x,y,w,h parameters to extract given image width and height. Assume image width and height are available in self.width and self.height, and self.request is IIIFRequest object Expected use: (x,y,w,h) = self.region_to_apply() if...
python
{ "resource": "" }
q7329
IIIFManipulator.size_to_apply
train
def size_to_apply(self): """Calculate size of image scaled using size parameters. Assumes current image width and height are available in self.width and self.height, and self.request is IIIFRequest object. Formats are: w, ,h w,h pct:p !w,h full max Returns (None,None) if no sc...
python
{ "resource": "" }
q7330
IIIFManipulator.quality_to_apply
train
def quality_to_apply(self): """Value of quality parameter to use in processing request. Simple substitution of 'native' or 'default' if no quality parameter is specified. """ if (self.request.quality is None): if (self.api_version <= '1.1'): return('n...
python
{ "resource": "" }
q7331
IIIFManipulator.scale_factors
train
def scale_factors(self, tile_width, tile_height=None): """Return a set of scale factors for given tile and window size. Gives a set of scale factors, starting at 1, and in multiples of 2. Largest scale_factor is so that one tile will cover the entire image (self.width,self.height). ...
python
{ "resource": "" }
q7332
PixelGen.color
train
def color(self, n): """Color of pixel that reached limit after n iterations. Returns a color tuple for use with PIL, tending toward red as we tend toward self.max_iter iterations. """ red = int(n * self.shade_factor) if (red > 255): red = 255 return (...
python
{ "resource": "" }
q7333
PixelGen.mpixel
train
def mpixel(self, z, n=0): """Iteration in Mandlebrot coordinate z.""" z = z * z + self.c if (abs(z) > 2.0): return self.color(n) n += 1 if (n > self.max_iter): return None return self.mpixel(z, n)
python
{ "resource": "" }
q7334
static_partial_tile_sizes
train
def static_partial_tile_sizes(width, height, tilesize, scale_factors): """Generator for partial tile sizes for zoomed in views. Positional arguments: width -- width of full size image height -- height of full size image tilesize -- width and height of tiles scale_factors -- iterable of scale fa...
python
{ "resource": "" }
q7335
static_full_sizes
train
def static_full_sizes(width, height, tilesize): """Generator for scaled-down full image sizes. Positional arguments: width -- width of full size image height -- height of full size image tilesize -- width and height of tiles Yields [sw,sh], the size for each full-region tile that is less than ...
python
{ "resource": "" }
q7336
IIIFStatic.parse_extra
train
def parse_extra(self, extra): """Parse extra request parameters to IIIFRequest object.""" if extra.startswith('/'): extra = extra[1:] r = IIIFRequest(identifier='dummy', api_version=self.api_version) r.parse_url(extra) if (r.info): ...
python
{ "resource": "" }
q7337
IIIFStatic.get_osd_config
train
def get_osd_config(self, osd_version): """Select appropriate portion of config. If the version requested is not supported the raise an exception with a helpful error message listing the versions supported. """ if (osd_version in self.osd_config): return(self.osd_conf...
python
{ "resource": "" }
q7338
IIIFStatic.generate
train
def generate(self, src=None, identifier=None): """Generate static files for one source image.""" self.src = src self.identifier = identifier # Get image details and calculate tiles im = self.manipulator_klass() im.srcfile = self.src im.set_max_image_pixels(self.ma...
python
{ "resource": "" }
q7339
IIIFStatic.generate_tile
train
def generate_tile(self, region, size): """Generate one tile for this given region, size of this image.""" r = IIIFRequest(identifier=self.identifier, api_version=self.api_version) if (region == 'full'): r.region_full = True else: r.region_x...
python
{ "resource": "" }
q7340
IIIFStatic.generate_file
train
def generate_file(self, r, undistorted=False): """Generate file for IIIFRequest object r from this image. FIXME - Would be nicer to have the test for an undistorted image request based on the IIIFRequest object, and then know whether to apply canonicalization or not. Logically ...
python
{ "resource": "" }
q7341
IIIFStatic.setup_destination
train
def setup_destination(self): """Setup output directory based on self.dst and self.identifier. Returns the output directory name on success, raises and exception on failure. """ # Do we have a separate identifier? if (not self.identifier): # No separate identi...
python
{ "resource": "" }
q7342
IIIFStatic.write_html
train
def write_html(self, html_dir='/tmp', include_osd=False, osd_width=500, osd_height=500): """Write HTML test page using OpenSeadragon for the tiles generated. Assumes that the generate(..) method has already been called to set up identifier etc. Parameters: html_dir ...
python
{ "resource": "" }
q7343
get_value
train
def get_value(key, obj, default=missing): """Helper for pulling a keyed value off various types of objects""" if isinstance(key, int): return _get_value_for_key(key, obj, default) return _get_value_for_keys(key.split('.'), obj, default)
python
{ "resource": "" }
q7344
validate_headers
train
def validate_headers(spec, data): """Validates headers data and creates the config objects""" validated_data = { spec.VERSION: data[spec.VERSION], spec.KIND: data[spec.KIND], } if data.get(spec.LOGGING): validated_data[spec.LOGGING] = LoggingConfig.from_dict( data[sp...
python
{ "resource": "" }
q7345
validate
train
def validate(spec, data): """Validates the data and creates the config objects""" data = copy.deepcopy(data) validated_data = {} def validate_keys(section, config, section_data): if not isinstance(section_data, dict) or section == spec.MODEL: return extra_args = [key for ke...
python
{ "resource": "" }
q7346
ExperimentSchema.validate_replicas
train
def validate_replicas(self, data): """Validate distributed experiment""" environment = data.get('environment') if environment and environment.replicas: validate_replicas(data.get('framework'), environment.replicas)
python
{ "resource": "" }
q7347
GroupSpecification.get_experiment_spec
train
def get_experiment_spec(self, matrix_declaration): """Returns an experiment spec for this group spec and the given matrix declaration.""" parsed_data = Parser.parse(self, self._data, matrix_declaration) del parsed_data[self.HP_TUNING] validator.validate(spec=self, data=parsed_data) ...
python
{ "resource": "" }
q7348
GroupSpecification.get_build_spec
train
def get_build_spec(self): """Returns a build spec for this group spec.""" if BaseSpecification.BUILD not in self._data: return None return BuildConfig.from_dict(self._data[BaseSpecification.BUILD])
python
{ "resource": "" }
q7349
HPTuningSchema.validate_matrix
train
def validate_matrix(self, data): """Validates matrix data and creates the config objects""" is_grid_search = ( data.get('grid_search') is not None or (data.get('grid_search') is None and data.get('random_search') is None and data.get('hyperband') is None...
python
{ "resource": "" }
q7350
TableOne._generate_remark_str
train
def _generate_remark_str(self, end_of_line = '\n'): """ Generate a series of remarks that the user should consider when interpreting the summary statistics. """ warnings = {} msg = '{}'.format(end_of_line) # generate warnings for continuous variables if s...
python
{ "resource": "" }
q7351
TableOne._detect_categorical_columns
train
def _detect_categorical_columns(self,data): """ Detect categorical columns if they are not specified. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- likely_cat : list List of va...
python
{ "resource": "" }
q7352
TableOne._std
train
def _std(self,x): """ Compute standard deviation with ddof degrees of freedom """ return np.nanstd(x.values,ddof=self._ddof)
python
{ "resource": "" }
q7353
TableOne._tukey
train
def _tukey(self,x,threshold): """ Count outliers according to Tukey's rule. Where Q1 is the lower quartile and Q3 is the upper quartile, an outlier is an observation outside of the range: [Q1 - k(Q3 - Q1), Q3 + k(Q3 - Q1)] k = 1.5 indicates an outlier k = 3.0 i...
python
{ "resource": "" }
q7354
TableOne._outliers
train
def _outliers(self,x): """ Compute number of outliers """ outliers = self._tukey(x, threshold = 1.5) return np.size(outliers)
python
{ "resource": "" }
q7355
TableOne._far_outliers
train
def _far_outliers(self,x): """ Compute number of "far out" outliers """ outliers = self._tukey(x, threshold = 3.0) return np.size(outliers)
python
{ "resource": "" }
q7356
TableOne._create_cat_describe
train
def _create_cat_describe(self,data): """ Describe the categorical data. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- df_cat : pandas DataFrame Summarise the categorical variab...
python
{ "resource": "" }
q7357
TableOne._create_significance_table
train
def _create_significance_table(self,data): """ Create a table containing p-values for significance tests. Add features of the distributions and the p-values to the dataframe. Parameters ---------- data : pandas DataFrame The input dataset. Re...
python
{ "resource": "" }
q7358
TableOne._create_cont_table
train
def _create_cont_table(self,data): """ Create tableone for continuous data. Returns ---------- table : pandas DataFrame A table summarising the continuous variables. """ # remove the t1_summary level table = self.cont_describe[['t1_summary']]....
python
{ "resource": "" }
q7359
TableOne._create_cat_table
train
def _create_cat_table(self,data): """ Create table one for categorical data. Returns ---------- table : pandas DataFrame A table summarising the categorical variables. """ table = self.cat_describe['t1_summary'].copy() # add the total count of...
python
{ "resource": "" }
q7360
TableOne._create_row_labels
train
def _create_row_labels(self): """ Take the original labels for rows. Rename if alternative labels are provided. Append label suffix if label_suffix is True. Returns ---------- labels : dictionary Dictionary, keys are original column name, values are final la...
python
{ "resource": "" }
q7361
bandwidth_factor
train
def bandwidth_factor(nbr_data_pts, deriv_order=0): ''' Scale factor for one-dimensional plug-in bandwidth selection. ''' if deriv_order == 0: return (3.0*nbr_data_pts/4)**(-1.0/5) if deriv_order == 2: return (7.0*nbr_data_pts/4)**(-1.0/9) raise ValueError('Not implemented f...
python
{ "resource": "" }
q7362
make_html_tag
train
def make_html_tag(tag, text=None, **params): """Create an HTML tag string. tag The HTML tag to use (e.g. 'a', 'span' or 'div') text The text to enclose between opening and closing tag. If no text is specified then only the opening tag is returned. Example:: make_html_t...
python
{ "resource": "" }
q7363
Page._range
train
def _range(self, link_map, radius): """ Return range of linked pages to substiture placeholder in pattern """ leftmost_page = max(self.first_page, (self.page - radius)) rightmost_page = min(self.last_page, (self.page + radius)) nav_items = [] # Create a link to ...
python
{ "resource": "" }
q7364
Page.default_link_tag
train
def default_link_tag(item): """ Create an A-HREF tag that points to another page. """ text = item["value"] target_url = item["href"] if not item["href"] or item["type"] in ("span", "current_page"): if item["attrs"]: text = make_html_tag("span"...
python
{ "resource": "" }
q7365
PerceptronTagger.tag
train
def tag(self, corpus, tokenize=True): '''Tags a string `corpus`.''' # Assume untokenized corpus has \n between sentences and ' ' between words s_split = SentenceTokenizer().tokenize if tokenize else lambda t: t.split('\n') w_split = WordTokenizer().tokenize if tokenize else lambda s: s.s...
python
{ "resource": "" }
q7366
PerceptronTagger.train
train
def train(self, sentences, save_loc=None, nr_iter=5): '''Train a model from sentences, and save it at ``save_loc``. ``nr_iter`` controls the number of Perceptron training iterations. :param sentences: A list of (words, tags) tuples. :param save_loc: If not ``None``, saves a pickled mode...
python
{ "resource": "" }
q7367
PerceptronTagger.load
train
def load(self, loc): '''Load a pickled model.''' try: w_td_c = pickle.load(open(loc, 'rb')) except IOError: msg = ("Missing trontagger.pickle file.") raise MissingCorpusError(msg) self.model.weights, self.tagdict, self.classes = w_td_c self.mod...
python
{ "resource": "" }
q7368
PerceptronTagger._normalize
train
def _normalize(self, word): '''Normalization used in pre-processing. - All words are lower cased - Digits in the range 1800-2100 are represented as !YEAR; - Other digits are represented as !DIGITS :rtype: str ''' if '-' in word and word[0] != '-': re...
python
{ "resource": "" }
q7369
PerceptronTagger._make_tagdict
train
def _make_tagdict(self, sentences): '''Make a tag dictionary for single-tag words.''' counts = defaultdict(lambda: defaultdict(int)) for words, tags in sentences: for word, tag in zip(words, tags): counts[word][tag] += 1 self.classes.add(tag) f...
python
{ "resource": "" }
q7370
train
train
def train(nr_iter, examples): '''Return an averaged perceptron model trained on ``examples`` for ``nr_iter`` iterations. ''' model = AveragedPerceptron() for i in range(nr_iter): random.shuffle(examples) for features, class_ in examples: scores = model.predict(features) ...
python
{ "resource": "" }
q7371
RtpPacket.decode
train
def decode(self, byteStream): """Decode the RTP packet.""" self.header = bytearray(byteStream[:HEADER_SIZE]) self.payload = byteStream[HEADER_SIZE:]
python
{ "resource": "" }
q7372
RtpPacket.timestamp
train
def timestamp(self): """Return timestamp.""" timestamp = self.header[4] << 24 | self.header[5] << 16 | self.header[6] << 8 | self.header[7] return int(timestamp)
python
{ "resource": "" }
q7373
preview_stream
train
def preview_stream(stream): """ Display stream in an OpenCV window until "q" key is pressed """ # together with waitkeys later, helps to close the video window effectively _cv2.startWindowThread() for frame in stream.frame_generator(): if frame is not None: _cv2.imshow('Video', ...
python
{ "resource": "" }
q7374
printrec
train
def printrec(recst): """ Pretty-printing rtsp strings """ try: recst = recst.decode('UTF-8') except AttributeError: pass recs=[ x for x in recst.split('\r\n') if x ] for rec in recs: print(rec) print("\n")
python
{ "resource": "" }
q7375
get_resources
train
def get_resources(connection): """ Do an RTSP-DESCRIBE request, then parse out available resources from the response """ resp = connection.describe(verbose=False).split('\r\n') resources = [x.replace('a=control:','') for x in resp if (x.find('control:') != -1 and x[-1] != '*' )] return resources
python
{ "resource": "" }
q7376
FFmpegClient.fetch_image
train
def fetch_image(self,rtsp_server_uri = _source,timeout_secs = 15): """ Fetch a single frame using FFMPEG. Convert to PIL Image. Slow. """ self._check_ffmpeg() cmd = "ffmpeg -rtsp_transport tcp -i {} -loglevel quiet -frames 1 -f image2pipe -".format(rtsp_server_uri) #stdout = _s...
python
{ "resource": "" }
q7377
Client.setupMovie
train
def setupMovie(self): """Setup button handler.""" if self.state == self.INIT: self.sendRtspRequest(self.SETUP)
python
{ "resource": "" }
q7378
Client.exitClient
train
def exitClient(self): """Teardown button handler.""" self.sendRtspRequest(self.TEARDOWN) #self.handler() os.remove(CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT) # Delete the cache image from video rate = float(self.counter/self.frameNbr) print('-'*60 + "\nRTP Packet Loss Rate :" + str(...
python
{ "resource": "" }
q7379
Client.pauseMovie
train
def pauseMovie(self): """Pause button handler.""" if self.state == self.PLAYING: self.sendRtspRequest(self.PAUSE)
python
{ "resource": "" }
q7380
Client.updateMovie
train
def updateMovie(self, imageFile): """Update the image file as video frame in the GUI.""" try: photo = ImageTk.PhotoImage(Image.open(imageFile)) #stuck here !!!!!! except: print("photo error") print('-'*60) traceback.print_exc(file=sys.stdout) print('-'*60) self.label.confi...
python
{ "resource": "" }
q7381
Client.sendRtspRequest
train
def sendRtspRequest(self, requestCode): """Send RTSP request to the server.""" #------------- # TO COMPLETE #------------- # Setup request if requestCode == self.SETUP and self.state == self.INIT: threading.Thread(target=self.recvRtspReply).start() # Update RTSP sequence number. ...
python
{ "resource": "" }
q7382
Client.recvRtspReply
train
def recvRtspReply(self): """Receive RTSP reply from the server.""" while True: reply = self.rtspSocket.recv(1024) if reply: self.parseRtspReply(reply) # Close the RTSP socket upon requesting Teardown if self.requestSent == self.TEARDOWN: self.rtspSocket.shutdown(socket....
python
{ "resource": "" }
q7383
Client.parseRtspReply
train
def parseRtspReply(self, data): print("Parsing Received Rtsp data...") """Parse the RTSP reply from the server.""" lines = data.split('\n') seqNum = int(lines[1].split(' ')[1]) # Process only if the server reply's sequence number is the same as the request's if seqNum == self.rtspSeq: se...
python
{ "resource": "" }
q7384
LocalVideoFeed.preview
train
def preview(self): """ Blocking function. Opens OpenCV window to display stream. """ win_name = 'Camera' cv2.namedWindow(win_name, cv2.WINDOW_AUTOSIZE) cv2.moveWindow(win_name,20,20) self.open() while(self.isOpened()): cv2.imshow(win_name,self._stream.read()[1...
python
{ "resource": "" }
q7385
Client.createWidgets
train
def createWidgets(self): """Build GUI.""" # Create Setup button self.setup = Button(self.master, width=20, padx=3, pady=3) self.setup["text"] = "Setup" self.setup["command"] = self.setupMovie self.setup.grid(row=1, column=0, padx=2, pady=2) # Create Play button self.start = Button(self....
python
{ "resource": "" }
q7386
Client.playMovie
train
def playMovie(self): """Play button handler.""" if self.state == self.READY: # Create a new thread to listen for RTP packets print "Playing Movie" threading.Thread(target=self.listenRtp).start() self.playEvent = threading.Event() self.playEvent.clear() self.sendRtspRequest(se...
python
{ "resource": "" }
q7387
Client.writeFrame
train
def writeFrame(self, data): """Write the received frame to a temp image file. Return the image file.""" cachename = CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT try: file = open(cachename, "wb") except: print "file open error" try: file.write(data) except: pr...
python
{ "resource": "" }
q7388
Client.handler
train
def handler(self): """Handler on explicitly closing the GUI window.""" self.pauseMovie() if tkMessageBox.askokcancel("Quit?", "Are you sure you want to quit?"): self.exitClient() else: # When the user presses cancel, resume playing. #self.playMovie() print "Playing Movie" threadi...
python
{ "resource": "" }
q7389
ChatThreadParser.skip
train
def skip(self): """ Eats through the input iterator without recording the content. """ for pos, element in self.element_iter: tag, class_attr = _tag_and_class_attr(element) if tag == "div" and "thread" in class_attr and pos == "end": break
python
{ "resource": "" }
q7390
MessageHtmlParser.should_record_thread
train
def should_record_thread(self, participants): """ Determines if the thread should be parsed based on the participants and the filter given. For example, if the filter states ['jack', 'billy joe'], then only threads with exactly two participants (excluding the owner of th...
python
{ "resource": "" }
q7391
MessageHtmlParser.parse_thread
train
def parse_thread(self, participants, element_iter, require_flush): """ Parses a thread with appropriate CLI feedback. :param participants: The participants in this thread. :param element_iter: The XML iterator to parse the data from. :param require_flush: Whether the iterator ne...
python
{ "resource": "" }
q7392
LegacyMessageHtmlParser.parse_impl
train
def parse_impl(self): """ Parses the HTML content as a stream. This is far less memory intensive than loading the entire HTML file into memory, like BeautifulSoup does. """ # Cast to str to ensure not unicode under Python 2, as the parser # doesn't like that. ...
python
{ "resource": "" }
q7393
messages
train
def messages(path, thread, fmt, nocolor, timezones, utc, noprogress, resolve, directory): """ Conversion of Facebook chat history. """ with colorize_output(nocolor): try: chat_history = _process_history( path=path, thread=thread, timezones=timezones, u...
python
{ "resource": "" }
q7394
stats
train
def stats(path, fmt, nocolor, timezones, utc, noprogress, most_common, resolve, length): """Analysis of Facebook chat history.""" with colorize_output(nocolor): try: chat_history = _process_history( path=path, thread='', timezones=timezones, utc=utc, noprogres...
python
{ "resource": "" }
q7395
set_stream_color
train
def set_stream_color(stream, disabled): """ Remember what our original streams were so that we can colorize them separately, which colorama doesn't seem to natively support. """ original_stdout = sys.stdout original_stderr = sys.stderr init(strip=disabled) if stream != original_std...
python
{ "resource": "" }
q7396
FacebookNameResolver._manual_lookup
train
def _manual_lookup(self, facebook_id, facebook_id_string): """ People who we have not communicated with in a long time will not appear in the look-ahead cache that Facebook keeps. We must manually resolve them. :param facebook_id: Profile ID of the user to lookup. :retur...
python
{ "resource": "" }
q7397
get_exporter
train
def get_exporter(obj, name): """ Get an exporter for the :param obj: object to export :type obj: :class:`Component <cqparts.Component>` :param name: registered name of exporter :type name: :class:`str` :return: an exporter instance of the given type :rtype: :class:`Exporter` :raises...
python
{ "resource": "" }
q7398
get_importer
train
def get_importer(cls, name): """ Get an importer for the given registered type. :param cls: class to import :type cls: :class:`type` :param name: registered name of importer :type name: :class:`str` :return: an importer instance of the given type :rtype: :class:`Importer` :raises Ty...
python
{ "resource": "" }
q7399
BunningsProductSpider.parse
train
def parse(self, response): """Parse pagenated list of products""" # Check if page is out of range no_more_products = re.search( r'No matching products were found', response.css('div.paged-results').extract_first(), flags=re.I ) if no_more_prod...
python
{ "resource": "" }