function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
list
def is_good_for_setup(self): """checks if the objects rotatePivot, scalePivot, rotatePivotTranslate and scalePivotTranslate is not connected to anything """ attributes = [ "rotatePivot", "scalePivot", "rotatePivotTranslate", "scalePivotTranslate", ] for attrStr in attributes: connections = self._object.attr(attrStr).connections() if len(connections) > 0: return False return True
eoyilmaz/anima
[ 119, 27, 119, 3, 1392807749 ]
def setup_pivot(): """setups pivot switching for selected objects""" for piv_switcher in get_one_switcher(): piv_switcher.setup()
eoyilmaz/anima
[ 119, 27, 119, 3, 1392807749 ]
def test (*args, *kwargs): print args, kwargs
theodox/mGui
[ 117, 23, 117, 15, 1392580211 ]
def test (*args, *kwargs): print "args:", args print "kwargs:", kwargs
theodox/mGui
[ 117, 23, 117, 15, 1392580211 ]
def __init__(self, **data): self._handlers = set() '''Set list of handlers callables. Use a set to avoid multiple calls on one handler''' self.data = data self.data['event'] = self
theodox/mGui
[ 117, 23, 117, 15, 1392580211 ]
def _remove_handler(self, handler): """ Remove a handler. Ignores handlers that are not present. """ stash = None if isinstance(handler, tuple): handler, stash = handler try: delattr(stash, '_sh_{}'.format(id(handler))) except AttributeError: pass wr = get_weak_reference(handler) delenda = [h for h in self._handlers if h == wr] self._handlers = self._handlers.difference(set(delenda)) return self
theodox/mGui
[ 117, 23, 117, 15, 1392580211 ]
def _fire(self, *args, **kwargs): """ Call all handlers. Any decayed references will be purged. """ delenda = [] for handler in self._handlers: try: handler(*args, **self.metadata(kwargs)) except DeadReferenceError: delenda.append(handler) self._handlers = self._handlers.difference(set(delenda))
theodox/mGui
[ 117, 23, 117, 15, 1392580211 ]
def __del__(self): print 'event expired'
theodox/mGui
[ 117, 23, 117, 15, 1392580211 ]
def _fire(self, *args, **kwargs): """ Call all handlers. Any decayed references will be purged. """ delenda = [] for handler in self._handlers: try: maya.utils.executeDeferred(partial(handler, *args, **self.metadata(kwargs))) except DeadReferenceError: delenda.append(handler) self._handlers = self._handlers.difference(set(delenda))
theodox/mGui
[ 117, 23, 117, 15, 1392580211 ]
def __init__(self, f): self.function = f.im_func self.referent = weakref.ref(f.im_self) self._ref_name = f.im_func.__name__ self.ID = id(f.im_self) ^ id(f.im_func.__name__)
theodox/mGui
[ 117, 23, 117, 15, 1392580211 ]
def __eq__(self, other): if not hasattr(other, 'ID'): return False return self.ID == other.ID
theodox/mGui
[ 117, 23, 117, 15, 1392580211 ]
def __init__(self, f): self.function = weakref.ref(f) self.ID = id(f) self._ref_name = getattr(f, '__name__', "'unnamed'")
theodox/mGui
[ 117, 23, 117, 15, 1392580211 ]
def __eq__(self, other): if not hasattr(other, 'ID'): return False return self.ID == other.ID
theodox/mGui
[ 117, 23, 117, 15, 1392580211 ]
def get_weak_reference(f): """ Returns a WeakMethodFree or a WeakMethodBound for the supplied function, as appropriate """ try: f.im_func except AttributeError: return WeakMethodFree(f) return WeakMethodBound(f)
theodox/mGui
[ 117, 23, 117, 15, 1392580211 ]
def wrapper(*_, **__): return fn()
theodox/mGui
[ 117, 23, 117, 15, 1392580211 ]
def help(self,letter='az',typ='mt'): """ generic help Parameters ---------- txt : string 'mb' | 'mt' mb :members mt :methods """ members = [ x for x in self.__dict__.keys() if x not in dict.__dict__ ] lmeth = [ x for x in np.sort(dir(self)) if x not in dict.__dict__] if typ=='mb': print(np.sort(self.__dict__.keys())) if typ=='mt': for s in lmeth: if s not in members: if s[0]!='_': if len(letter)>1: if (s[0]>=letter[0])&(s[0]<letter[1]): try: doc = eval('self.'+s+'.__doc__').split('\n') print(s+': '+ doc[0]) except: pass else: if (s[0]==letter[0]): try: doc = eval('self.'+s+'.__doc__').split('\n') print(s+': '+ doc[0]) except: pass
pylayers/pylayers
[ 152, 102, 152, 115, 1346426390 ]
def __init__(self): self.mapped_emails = {} self.mapped_names = {} self.generated_emails = set() self.generated_names = set()
ENCODE-DCC/encoded
[ 104, 54, 104, 70, 1354841541 ]
def replace_non_pi_names(self, dictrows): for row in dictrows: if row.get('job_title') != 'PI': if 'first_name' in row: row['first_name'] = random.choice(self.random_words).capitalize() if 'last_name' in row: row['last_name'] = self._random_name() yield row
ENCODE-DCC/encoded
[ 104, 54, 104, 70, 1354841541 ]
def _replace_emails(self, matchobj): found = matchobj.group(0) new, original = self.mapped_emails.get(found.lower(), (None, None)) if new is not None: if found != original: raise ValueError( "Case mismatch for %s, %s" % (found, original)) return new new = self._random_email() self.mapped_emails[found.lower()] = (new, found) return new
ENCODE-DCC/encoded
[ 104, 54, 104, 70, 1354841541 ]
def set_existing_key_value(**kw): def component(dictrows): for row in dictrows: for k, v in kw.items(): if k in row: row[k] = v yield row return component
ENCODE-DCC/encoded
[ 104, 54, 104, 70, 1354841541 ]
def component(dictrows): for row in dictrows: if not all(row[k] == v if k in row else False for k, v in kw.items()): yield row
ENCODE-DCC/encoded
[ 104, 54, 104, 70, 1354841541 ]
def extract_pipeline(): return [ skip_rows_with_all_falsey_value('test'), skip_rows_with_all_key_value(test='skip'), skip_rows_with_all_falsey_value('test'), skip_rows_missing_all_keys('uuid'), drop_rows_with_all_key_value(_skip=True), ]
ENCODE-DCC/encoded
[ 104, 54, 104, 70, 1354841541 ]
def run(pipeline, inpath, outpath): for item_type in ORDER: source = read_single_sheet(inpath, item_type) fieldnames = [k for k in source.fieldnames if ':ignore' not in k] with open(os.path.join(outpath, item_type + '.tsv'), 'wb') as out: writer = csv.DictWriter(out, fieldnames, dialect='excel-tab', extrasaction='ignore') writer.writeheader() writer.writerows(combine(source, pipeline))
ENCODE-DCC/encoded
[ 104, 54, 104, 70, 1354841541 ]
def negate(grads): """Negates the gradients. Args: grads: A numpy array of grads to use. Returns: The negated gradients. """ return -grads
raghakot/keras-vis
[ 2947, 669, 2947, 117, 1478906854 ]
def invert(grads): """Inverts the gradients. Args: grads: A numpy array of grads to use. Returns: The inverted gradients. """ return 1. / (grads + K.epsilon())
raghakot/keras-vis
[ 2947, 669, 2947, 117, 1478906854 ]
def small_values(grads): """Can be used to highlight small gradient values. Args: grads: A numpy array of grads to use. Returns: The modified gradients that highlight small values. """ return absolute(invert(grads))
raghakot/keras-vis
[ 2947, 669, 2947, 117, 1478906854 ]
def test_error_code(self): self.assertEqual(-1000, WeChatErrorCode.SYSTEM_ERROR.value) self.assertEqual(42001, WeChatErrorCode.EXPIRED_ACCESS_TOKEN.value) self.assertEqual(48001, WeChatErrorCode.UNAUTHORIZED_API.value)
wechatpy/wechatpy
[ 3364, 745, 3364, 44, 1410527008 ]
def get_categories(self) -> List[int]: res = [] for t in list(VehicleCategory): if self in t.value: res.append(t) return res
hasadna/anyway
[ 69, 235, 69, 293, 1386619033 ]
def to_type_code(db_val: Union[float, int]) -> int: """Values read from DB may arrive as float, and empty values come as nan""" if isinstance(db_val, float): if math.isnan(db_val): return VehicleType.OTHER_AND_UNKNOWN.value else: return int(db_val) elif isinstance(db_val, int): return db_val else: logging.error( f"VehicleType.fo_type_code: unknown value: {db_val}({type(db_val)})" ". returning OTHER_AND_UNKNOWN" ) return VehicleType.OTHER_AND_UNKNOWN.value
hasadna/anyway
[ 69, 235, 69, 293, 1386619033 ]
def get_codes(self) -> List[int]: """returns VehicleType codes of category""" category_vehicle_types = { VehicleCategory.PROFESSIONAL_DRIVER: [ VehicleType.TRUCK_UPTO_4, VehicleType.PICKUP_UPTO_4, VehicleType.TRUCK_4_TO_10, VehicleType.TRUCK_12_TO_16, VehicleType.TRUCK_16_TO_34, VehicleType.TRUCK_ABOVE_34, VehicleType.BUS, VehicleType.TAXI, VehicleType.WORK, VehicleType.TRACTOR, VehicleType.MINIBUS, VehicleType.TRUCK_3_5_TO_10, VehicleType.TRUCK_10_TO_12, ], VehicleCategory.PRIVATE_DRIVER: [ VehicleType.CAR, VehicleType.MOTORCYCLE_UPTO_50, VehicleType.MOTORCYCLE_50_TO_250, VehicleType.MOTORCYCLE_250_TO_500, VehicleType.MOTORCYCLE_ABOVE_500, ], VehicleCategory.LIGHT_ELECTRIC: [ VehicleType.ELECTRIC_SCOOTER, VehicleType.MOBILITY_SCOOTER, VehicleType.ELECTRIC_BIKE, ], VehicleCategory.CAR: [VehicleType.CAR, VehicleType.TAXI], VehicleCategory.LARGE: [ VehicleType.TRUCK_UPTO_4, VehicleType.PICKUP_UPTO_4, VehicleType.TRUCK_4_TO_10, VehicleType.TRUCK_12_TO_16, VehicleType.TRUCK_16_TO_34, VehicleType.TRUCK_ABOVE_34, VehicleType.BUS, VehicleType.WORK, VehicleType.TRACTOR, VehicleType.MINIBUS, VehicleType.TRUCK_3_5_TO_10, VehicleType.TRUCK_10_TO_12, ], VehicleCategory.MOTORCYCLE: [ VehicleType.MOTORCYCLE_UPTO_50, VehicleType.MOTORCYCLE_50_TO_250, VehicleType.MOTORCYCLE_250_TO_500, VehicleType.MOTORCYCLE_ABOVE_500, ], VehicleCategory.BICYCLE_AND_SMALL_MOTOR: [ VehicleType.BIKE, VehicleType.ELECTRIC_SCOOTER, VehicleType.ELECTRIC_BIKE, ], VehicleCategory.OTHER: [ VehicleType.BIKE, VehicleType.TRAIN, VehicleType.OTHER_AND_UNKNOWN, ], } return list(map(lambda x: x.value, category_vehicle_types[self]))
hasadna/anyway
[ 69, 235, 69, 293, 1386619033 ]
def get_english_display_name(self): english_vehicle_type_display_names = { VehicleCategory.PROFESSIONAL_DRIVER: "professional driver", VehicleCategory.PRIVATE_DRIVER: "private driver", VehicleCategory.LIGHT_ELECTRIC: "light electric vehicles", VehicleCategory.CAR: "private car", VehicleCategory.LARGE: "large vehicle", VehicleCategory.MOTORCYCLE: "motorcycle", VehicleCategory.BICYCLE_AND_SMALL_MOTOR: "bicycle and small motor vehicles", VehicleCategory.OTHER: "other vehicle", } try: return english_vehicle_type_display_names[self] except (KeyError, TypeError): logging.exception(f"VehicleType.get_display_name: {self}: no display string defined") return "no display name defined"
hasadna/anyway
[ 69, 235, 69, 293, 1386619033 ]
def read_image_from_stream(stream): try: arr = np.asarray(bytearray(stream.read()), dtype=np.uint8) image = cv2.imdecode(arr, cv2.IMREAD_COLOR) height, width = image.shape[:2] if height <= 0 or width <= 0: raise Exception('Invalid image file from stream') except: raise Exception('Invalid image file from stream') return image
meerkat-cv/annotator-supreme
[ 5, 1, 5, 15, 1497297407 ]
def read_image_b64(base64_string): dec = base64.b64decode(base64_string) npimg = np.fromstring(dec, dtype=np.uint8) cvimg = cv2.imdecode(npimg, cv2.IMREAD_COLOR) return cvimg
meerkat-cv/annotator-supreme
[ 5, 1, 5, 15, 1497297407 ]
def parse_content_type(request): """ This function is used to extract the content type from the header. """ try: content_type = request.headers['content-type'] except: raise error_views.InvalidParametersError('No Content-Type provided') json_type = 'application/json' data_type = 'multipart/form-data' lower_content_type = content_type.lower() if lower_content_type.find(json_type) >= 0: return json_type elif lower_content_type.find(data_type) >= 0: return data_type else: raise error_views.InvalidParametersError('Invalid Content-Type')
meerkat-cv/annotator-supreme
[ 5, 1, 5, 15, 1497297407 ]
def create_db(self): try: return MongoDB(database='iptestdb', _connection=c) except Exception: raise SkipTest("Couldn't connect to mongodb")
mattvonrocketstein/smash
[ 12, 1, 12, 10, 1321798817 ]
def __init__( self, plotly_name="color", parent_name="heatmapgl.hoverlabel.font", **kwargs
plotly/plotly.py
[ 13052, 2308, 13052, 1319, 1385013188 ]
def runtests(): # set verbosity to 2 to see each test unittest.TextTestRunner(verbosity=1, buffer=True).run(suite)
wanqizhu/mtg-python-engine
[ 29, 14, 29, 1, 1501541949 ]
def parse_args():
kahst/BirdCLEF2017
[ 38, 13, 38, 4, 1494853753 ]
def changeSampleRate(sig, rate): duration = sig.shape[0] / rate time_old = np.linspace(0, duration, sig.shape[0]) time_new = np.linspace(0, duration, int(sig.shape[0] * 44100 / rate)) interpolator = interpolate.interp1d(time_old, sig.T) new_audio = interpolator(time_new).T sig = np.round(new_audio).astype(sig.dtype)
kahst/BirdCLEF2017
[ 38, 13, 38, 4, 1494853753 ]
def getMagSpec(sig, rate, winlen, winstep, NFFT): #get frames winfunc = lambda x:np.ones((x,)) frames = psf.sigproc.framesig(sig, winlen*rate, winstep*rate, winfunc)
kahst/BirdCLEF2017
[ 38, 13, 38, 4, 1494853753 ]
def getMultiSpec(path, seconds=5, overlap=2, minlen=1, winlen=0.05, winstep=0.0097, NFFT=840): #open wav file (rate,sig) = wave.read(path) #adjust to different sample rates if rate != 44100: sig, rate = changeSampleRate(sig, rate) #split signal with overlap sig_splits = [] for i in xrange(0, len(sig), int((seconds - overlap) * rate)): split = sig[i:i + seconds * rate] if len(split) >= minlen * rate: sig_splits.append(split) #is signal too short for segmentation? if len(sig_splits) == 0: sig_splits.append(sig) #calculate spectrogram for every split for sig in sig_splits: #preemphasis sig = psf.sigproc.preemphasis(sig, coeff=0.95) #get spec magspec = getMagSpec(sig, rate, winlen, winstep, NFFT) #get rid of high frequencies h, w = magspec.shape[:2] magspec = magspec[h - 256:, :] #normalize in [0, 1] magspec -= magspec.min(axis=None) magspec /= magspec.max(axis=None) #fix shape to 512x256 pixels without distortion magspec = magspec[:256, :512] temp = np.zeros((256, 512), dtype="float32") temp[:magspec.shape[0], :magspec.shape[1]] = magspec magspec = temp.copy() magspec = cv2.resize(magspec, (512, 256))
kahst/BirdCLEF2017
[ 38, 13, 38, 4, 1494853753 ]
def buildModel(mtype=1): print "BUILDING MODEL TYPE", mtype, "..." #default settings (Model 1) filters = 64 first_stride = 2 last_filter_multiplier = 16 #specific model type settings (see working notes for details) if mtype == 2: first_stride = 1 elif mtype == 3: filters = 32 last_filter_multiplier = 8 #input layer net = l.InputLayer((None, IM_DIM, IM_SIZE[1], IM_SIZE[0])) #conv layers net = l.batch_norm(l.Conv2DLayer(net, num_filters=filters, filter_size=7, pad='same', stride=first_stride, W=init.HeNormal(gain=INIT_GAIN), nonlinearity=NONLINEARITY)) net = l.MaxPool2DLayer(net, pool_size=2) if mtype == 2: net = l.batch_norm(l.Conv2DLayer(net, num_filters=filters, filter_size=5, pad='same', stride=1, W=init.HeNormal(gain=INIT_GAIN), nonlinearity=NONLINEARITY)) net = l.MaxPool2DLayer(net, pool_size=2) net = l.batch_norm(l.Conv2DLayer(net, num_filters=filters * 2, filter_size=5, pad='same', stride=1, W=init.HeNormal(gain=INIT_GAIN), nonlinearity=NONLINEARITY)) net = l.MaxPool2DLayer(net, pool_size=2) net = l.batch_norm(l.Conv2DLayer(net, num_filters=filters * 4, filter_size=3, pad='same', stride=1, W=init.HeNormal(gain=INIT_GAIN), nonlinearity=NONLINEARITY)) net = l.MaxPool2DLayer(net, pool_size=2) net = l.batch_norm(l.Conv2DLayer(net, num_filters=filters * 8, filter_size=3, pad='same', stride=1, W=init.HeNormal(gain=INIT_GAIN), nonlinearity=NONLINEARITY)) net = l.MaxPool2DLayer(net, pool_size=2) net = l.batch_norm(l.Conv2DLayer(net, num_filters=filters * last_filter_multiplier, filter_size=3, pad='same', stride=1, W=init.HeNormal(gain=INIT_GAIN), nonlinearity=NONLINEARITY)) net = l.MaxPool2DLayer(net, pool_size=2) print "\tFINAL POOL OUT SHAPE:", l.get_output_shape(net) #dense layers net = l.batch_norm(l.DenseLayer(net, 512, W=init.HeNormal(gain=INIT_GAIN), nonlinearity=NONLINEARITY)) net = l.batch_norm(l.DenseLayer(net, 512, W=init.HeNormal(gain=INIT_GAIN), nonlinearity=NONLINEARITY)) #Classification Layer if MULTI_LABEL: net = l.DenseLayer(net, NUM_CLASSES, nonlinearity=nonlinearities.sigmoid, W=init.HeNormal(gain=1)) else: net = l.DenseLayer(net, NUM_CLASSES, nonlinearity=nonlinearities.softmax, W=init.HeNormal(gain=1)) print "...DONE!" #model stats print "MODEL HAS", (sum(hasattr(layer, 'W') for layer in l.get_all_layers(net))), "WEIGHTED LAYERS" print "MODEL HAS", l.count_params(net), "PARAMS" return net
kahst/BirdCLEF2017
[ 38, 13, 38, 4, 1494853753 ]
def loadParams(epoch, filename=None): print "IMPORTING MODEL PARAMS...", net_filename = MODEL_PATH + filename with open(net_filename, 'rb') as f: params = pickle.load(f) l.set_all_param_values(NET, params) print "DONE!"
kahst/BirdCLEF2017
[ 38, 13, 38, 4, 1494853753 ]
def getPredictionFuntion(net): net_output = l.get_output(net, deterministic=True) print "COMPILING THEANO TEST FUNCTION...", start = time.time() test_net = theano.function([l.get_all_layers(NET)[0].input_var], net_output, allow_input_downcast=True) print "DONE! (", int(time.time() - start), "s )" return test_net
kahst/BirdCLEF2017
[ 38, 13, 38, 4, 1494853753 ]
def predictionPooling(p): #You can test different prediction pooling strategies here #We only use average pooling p_pool = np.mean(p, axis=0) return p_pool
kahst/BirdCLEF2017
[ 38, 13, 38, 4, 1494853753 ]
def predict(img): #transpose image if dim=3 try: img = np.transpose(img, (2, 0, 1)) except: pass #reshape image img = img.reshape(-1, IM_DIM, IM_SIZE[1], IM_SIZE[0]) #calling the test function returns the net output prediction = TEST_NET(img)[0] return prediction
kahst/BirdCLEF2017
[ 38, 13, 38, 4, 1494853753 ]
def testFile(path, spec_overlap=4, num_results=5, confidence_threshold=0.01): #time start = time.time()
kahst/BirdCLEF2017
[ 38, 13, 38, 4, 1494853753 ]
def __init__(self, enum, **kwargs): self.enum = enum choices = ( (self.get_choice_value(enum_value), enum_value.label) for _, enum_value in enum.choices() ) super(EnumField, self).__init__(choices, **kwargs)
5monkeys/django-enumfield
[ 195, 46, 195, 8, 1359628484 ]
def to_internal_value(self, data): if isinstance(data, six.string_types) and data.isdigit(): data = int(data) try: value = self.enum.get(data).value except AttributeError: # .get() returned None if not self.required: raise serializers.SkipField() self.fail("invalid_choice", input=data) return value
5monkeys/django-enumfield
[ 195, 46, 195, 8, 1359628484 ]
def get_choice_value(self, enum_value): return enum_value.name
5monkeys/django-enumfield
[ 195, 46, 195, 8, 1359628484 ]
def __init__( self, plotly_name="tickformat", parent_name="scattercarpet.marker.colorbar", **kwargs
plotly/python-api
[ 13052, 2308, 13052, 1319, 1385013188 ]
def compute_fourier(phases,nh=10,pow_phase=False): '''Compute Fourier amplitudes from an array of pulse phases phases should be [0,1.0) nh is the number of harmonics (1 = fundamental only) Returns: cos and sin component arrays, unless pow_phase is True then returns Fourier power (Leahy normalized) and phase arrays DC bin is not computed or returned ''' phis = 2.0*np.pi*phases # Convert phases to radians n = len(phis) c = np.asarray([(np.cos(k*phis)).sum() for k in range(1,nh+1)])/n s = np.asarray([(np.sin(k*phis)).sum() for k in range(1,nh+1)])/n c *= 2.0 s *= 2.0 if pow_phase: # CHECK! There could be errors here! # These should be Leahy normalized powers fourier_pow = (n/2)*(c**2+s**2) fourier_phases = np.arctan2(s,c) return n,fourier_pow,fourier_phases else: return n,c,s
paulray/NICERsoft
[ 15, 17, 15, 8, 1491322025 ]
def evaluate_chi2(hist,model): # Question here is whether error should be sqrt(data) or sqrt(model) return ((hist-model)**2/model).sum()
paulray/NICERsoft
[ 15, 17, 15, 8, 1491322025 ]
def get_num_filters(layer): """Determines the number of filters within the given `layer`. Args: layer: The keras layer to use. Returns: Total number of filters within `layer`. For `keras.layers.Dense` layer, this is the total number of outputs. """ # Handle layers with no channels. if K.ndim(layer.output) == 2: return K.int_shape(layer.output)[-1] channel_idx = 1 if K.image_data_format() == 'channels_first' else -1 return K.int_shape(layer.output)[channel_idx]
raghakot/keras-vis
[ 2947, 669, 2947, 117, 1478906854 ]
def __init__(self): self.header_fields = [] self._header_index = {} self.entries = {}
kmichel/po-localization
[ 5, 1, 5, 1, 1410389851 ]
def add_header_field(self, field, value): if field in self._header_index: self.header_fields[self._header_index[field]] = (field, value) else: self._header_index[field] = len(self.header_fields) self.header_fields.append((field, value))
kmichel/po-localization
[ 5, 1, 5, 1, 1410389851 ]
def dump(self, fp, include_locations=True, prune_obsoletes=False): needs_blank_line = False if len(self.header_fields): print('msgid ""', file=fp) print('msgstr ""', file=fp) for field, value in self.header_fields: print(r'"{}: {}\n"'.format(field, value), file=fp) needs_blank_line = True nplurals = self.get_nplurals() for entry in sorted(self.entries.values(), key=get_entry_sort_key): if needs_blank_line: print('', file=fp) needs_blank_line = entry.dump( fp, nplurals, include_locations=include_locations, prune_obsolete=prune_obsoletes)
kmichel/po-localization
[ 5, 1, 5, 1, 1410389851 ]
def get_catalog(self): catalog = {} for entry in self.entries.values(): entry.fill_catalog(catalog) return catalog
kmichel/po-localization
[ 5, 1, 5, 1, 1410389851 ]
def __init__(self, message, plural=None, context=None): self.message = message self.plural = plural self.context = context self.locations = [] self.translations = {}
kmichel/po-localization
[ 5, 1, 5, 1, 1410389851 ]
def add_location(self, filename, lineno): self.locations.append((filename, lineno))
kmichel/po-localization
[ 5, 1, 5, 1, 1410389851 ]
def add_plural_translation(self, index, translation): self.translations[index] = translation
kmichel/po-localization
[ 5, 1, 5, 1, 1410389851 ]
def dump(self, fp, nplurals=None, include_locations=True, prune_obsolete=False): """ If plural, shows exactly 'nplurals' plurals if 'nplurals' is not None, else shows at least min_nplurals. All plural index are ordered and consecutive, missing entries are displayed with an empty string. """ if not len(self.locations): if prune_obsolete or all(translation == '' for index, translation in self.translations.items()): return False else: print('#. obsolete entry', file=fp) if include_locations and len(self.locations): print('#: {}'.format(' '.join('{}:{}'.format(*location) for location in self.locations)), file=fp) if self.context is not None: print('msgctxt {}'.format(multiline_escape(self.context)), file=fp) print('msgid {}'.format(multiline_escape(self.message)), file=fp) if self.plural is not None: print('msgid_plural {}'.format(multiline_escape(self.plural)), file=fp) if nplurals is None: nplurals = self.get_suggested_nplurals() for index in range(nplurals): print('msgstr[{}] {}'.format(index, multiline_escape(self.translations.get(index, ''))), file=fp) else: print('msgstr {}'.format(multiline_escape(self.translations.get(0, ''))), file=fp) return True
kmichel/po-localization
[ 5, 1, 5, 1, 1410389851 ]
def multiline_escape(string): if EMBEDDED_NEWLINE_MATCHER.search(string): lines = string.split('\n') return ( '""\n' + '\n'.join('"{}\\n"'.format(escape(line)) for line in lines[:-1]) + ('\n"{}"'.format(escape(lines[-1])) if len(lines[-1]) else "")) else: return '"{}"'.format(escape(string))
kmichel/po-localization
[ 5, 1, 5, 1, 1410389851 ]
def __init__( self, plotly_name="ticklen", parent_name="treemap.marker.colorbar", **kwargs
plotly/python-api
[ 13052, 2308, 13052, 1319, 1385013188 ]
def __init__(self, infile, outfile): threading.Thread.__init__(self) self.infile = infile self.outfile = outfile
CajetanP/code-learning
[ 1, 2, 1, 31, 1488493028 ]
def __init__(self,value): self.value = value
CajetanP/code-learning
[ 1, 2, 1, 31, 1488493028 ]
def __init__( self, plotly_name="tickvals", parent_name="parcoords.dimension", **kwargs
plotly/python-api
[ 13052, 2308, 13052, 1319, 1385013188 ]
def __init__(self, log_file_name=None, log_level=logging.INFO): full_log_path_and_name = KhanLogger.default_log_path_with_unique_name(log_file_name) self.logger = KhanLogger(file_path_and_name=full_log_path_and_name, level=log_level)
thorwhalen/ut
[ 4, 3, 4, 24, 1426246351 ]
def __init__(self, name): super(VFModule, self).__init__(name) self.vf = torch._C._VariableFunctions
ryfeus/lambda-packs
[ 1086, 234, 1086, 13, 1476901359 ]
def dynamics(x, u, dt): """ Returns next state given last state x, wrench u, and timestep dt. """ # Rotation matrix (orientation, converts body to world) R = np.array([ [np.cos(x[2]), -np.sin(x[2]), 0], [np.sin(x[2]), np.cos(x[2]), 0], [ 0, 0, 1] ]) # Construct drag coefficients based on our motion signs D = np.copy(D_neg) for i, v in enumerate(x[3:]): if v >= 0: D[i] = D_pos[i] # Heading controller trying to keep us car-like vw = R[:2, :2].dot(x[3:5]) ang = np.arctan2(vw[1], vw[0]) c = np.cos(x[2]) s = np.sin(x[2]) cg = np.cos(ang) sg = np.sin(ang) u[2] = magic_rudder*np.arctan2(sg*c - cg*s, cg*c + sg*s) # Actuator saturation u = B.dot(np.clip(invB.dot(u), -thrust_max, thrust_max)) # M*vdot + D*v = u and pdot = R*v xdot = np.concatenate((R.dot(x[3:]), invM*(u - D*x[3:]))) # First-order integrate xnext = x + xdot*dt # Impose not driving backwards if xnext[3] < 0: xnext[3] = abs(x[3]) # # Impose not turning in place # xnext[5] = np.clip(np.abs(xnext[3]/velmax_pos[0]), 0, 1) * xnext[5] return xnext
jnez71/lqRRT
[ 76, 27, 76, 3, 1474718253 ]
def lqr(x, u): """ Returns cost-to-go matrix S and policy matrix K given local state x and effort u. """ R = np.array([ [np.cos(x[2]), -np.sin(x[2]), 0], [np.sin(x[2]), np.cos(x[2]), 0], [ 0, 0, 1] ]) K = np.hstack((kp.dot(R.T), kd)) return (S, K)
jnez71/lqRRT
[ 76, 27, 76, 3, 1474718253 ]
def gen_ss(seed, goal, buff=[ss_start]*4): """ Returns a sample space given a seed state, goal state, and buffer. """ return [(min([seed[0], goal[0]]) - buff[0], max([seed[0], goal[0]]) + buff[1]), (min([seed[1], goal[1]]) - buff[2], max([seed[1], goal[1]]) + buff[3]), (-np.pi, np.pi), (0.9*velmax_pos[0], velmax_pos[0]), (-abs(velmax_neg[1]), velmax_pos[1]), (-abs(velmax_neg[2]), velmax_pos[2])]
jnez71/lqRRT
[ 76, 27, 76, 3, 1474718253 ]
def get_version(): """Return the version of extras that we are building.""" version = '.'.join( str(component) for component in extras.__version__[0:3]) return version
testing-cabal/extras
[ 4, 6, 4, 3, 1351326273 ]
def __init__(self, value=0.0, *args, **kw_args): """Initialises a new 'ActivePowerLimit' instance. @param value: Value of active power limit. """ #: Value of active power limit. self.value = value super(ActivePowerLimit, self).__init__(*args, **kw_args)
rwl/PyCIM
[ 68, 33, 68, 7, 1238978196 ]
def error_404(e): """ - Displays the 404 error page. """ error_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('404.html'))).content).decode("utf-8") # Done return render_template_string(error_page)
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def error_403(e): """ - Displays the 404 error page. """ error_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('403.html'))).content).decode("utf-8") # Done return render_template_string(error_page)
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def start(): #WORKS """ - The starting page. - Redirects to login page if not logged in. - Redirects to dashboard if logged in. """ logged_in = False if 'user' in session: logged_in = True is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": return redirect(url_for('dashboard')) most_viewed_video_IDs = ((requests.get('http://127.0.0.1:8080/get-most-viewed')).content).decode("utf-8") # Done most_viewed = {} most_viewed_video_IDs = ast.literal_eval(most_viewed_video_IDs) for ID in most_viewed_video_IDs: title = ((requests.get(url='http://127.0.0.1:8080/title/{}'.format(ID))).content).decode("utf-8") # Done views = ((requests.get(url='http://127.0.0.1:8080/views/{}'.format(ID))).content).decode("utf-8") # Done uploader = ((requests.get(url='http://127.0.0.1:8080/uploader/{}'.format(ID))).content).decode("utf-8") # Done details = [title, views, uploader] most_viewed.update({ID : details}) homepage = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('homepage.html'))).content).decode("utf-8") # Done return render_template_string(homepage, logged_in = logged_in, most_viewed = most_viewed)
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def login_form(): #WORKS """ In GET request, - Redirects to dashboard if logged in. - Displays login form if not logged in. """ if request.method == 'GET': login_error = request.args.get('l_error', False) if 'user' in session: return redirect(url_for("start")) else: login_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('login.html'))).content).decode("utf-8") # Done return render_template_string(login_page, loginError = login_error) """ In POST request - Gets data from form. - Validates user credentials. """ if request.method == 'POST': if 'user' in session: return redirect(url_for('dashboard')) username = (request.form['username']).lower().strip() password = (request.form['password']) is_valid_user = ((requests.post(url='http://127.0.0.1:8080/is-valid-user', data={'username' : username, 'password' : password})).content).decode("utf-8") # Done if is_valid_user == "True": session['user'] = username return redirect(url_for("start")) else: return redirect(url_for("login_form", l_error = True))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def signup_form(): #WORKS """ In GET request - Displays sign up page. """ if request.method == 'GET': if 'user' in session: return redirect(url_for('start')) signup_error = request.args.get('s_error', False) signup_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('signup.html'))).content).decode("utf-8") # Done return render_template_string(signup_page, signupError = signup_error) """ In POST request - Gets data from form. - Checks if username is not already present. - Adds to database if not present. - Redirects to dashboard. """ if request.method == 'POST': username = (request.form['username']).lower().strip() password = (request.form['password']) is_valid_username = ((requests.get(url='http://127.0.0.1:8080/is-valid-username/{}'.format(username))).content).decode("utf-8") # Done if is_valid_username == "False": requests.post(url='http://127.0.0.1:8080/add-user', data={'username' : username, 'password' : password}) # Done session['user'] = username return redirect(url_for("start")) else: return redirect(url_for("signup_form", s_error = True))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def password_update_form(): #WORKS """ In GET request - Redirects to login page if not logged in. - Displays the password update form. """ if request.method == 'GET': u_error = request.args.get('u_error', False) if 'user' not in session: return redirect(url_for('login_form')) is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) password_update_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('password_update.html'))).content).decode("utf-8") # Done if u_error == False: return render_template_string(password_update_page) else: return render_template_string(password_update_page, update_error = True) """ In POST request - Gets the old and new passwords. - Checks the old password. - If it matches the stored password, password is updated. - Otherwise, error is thrown. """ if request.method == 'POST': if 'user' not in session: return redirect(url_for('login_form')) is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) username = session['user'] old_password = request.form['oldPassword'] new_password = request.form['newPassword'] done = (requests.post(url='http://127.0.0.1:8080/update-password', data={'username' : username, 'old_password' : old_password, 'new_password' : new_password}).content).decode("utf-8") # Done if done == "True": return redirect(url_for('start')) else: return redirect(url_for('password_update_form', u_error = True))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def delete_own_account(): #WORKS """ In GET request - Displays confirmation page. """ if request.method == 'GET': if 'user' not in session: return redirect(url_for('login_form')) is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) confirmation_error = request.args.get('c_error', False) confirmation_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('account_delete_confirm.html'))).content).decode("utf-8") # Done if confirmation_error == False: return render_template_string(confirmation_page) else: return render_template_string(confirmation_page, c_error = True) """ In POST request - Deletes the user credentials from the database. - Redirects to login page. """ if request.method == 'POST': if 'user' not in session: return redirect(url_for('login_form')) is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) username = session['user'] password = request.form['password'] is_deleted = ((requests.post(url='http://127.0.0.1:8080/delete-user', data={'username' : username, 'password' : password})).content).decode("utf-8") # Done if is_deleted == "True": session.pop('user', None) return redirect(url_for("login_form")) else: return redirect(url_for('delete_own_account', c_error = True))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def logout_user(): #WORKS """ - Removes user from session. - Redirects to login page. """ session.pop('user', None) return redirect(url_for("start"))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def dashboard(): #WORKS """ - Redirects to login page if not logged in. - Displays dashboard page if logged in. """ if request.method == 'GET': if 'user' not in session: return redirect(url_for("login_form")) else: is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": user_count = (requests.get(url='http://127.0.0.1:8080/user-count').content).decode("utf-8") # Done video_count = (requests.get(url='http://127.0.0.1:8080/video-count').content).decode("utf-8") # Done view_count = (requests.get(url='http://127.0.0.1:8080/view-count').content).decode("utf-8") # Done flag_count = (requests.get(url='http://127.0.0.1:8080/flag-count').content).decode("utf-8") # Done admin_dashboard = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('administrator_dashboard.html'))).content).decode("utf-8") # Done return render_template_string(admin_dashboard, user_count = user_count, video_count = video_count, view_count = view_count, flag_count = flag_count) else: username = session['user'] video_count = (requests.get(url='http://127.0.0.1:8080/user-video-count/{}'.format(username)).content).decode("utf-8") # Done view_count = (requests.get(url='http://127.0.0.1:8080/user-view-count/{}'.format(username)).content).decode("utf-8") # Done best_vid_ID = (requests.get(url='http://127.0.0.1:8080/user-best-video/{}'.format(username)).content).decode("utf-8") # Done best_vid_title = ((requests.get(url='http://127.0.0.1:8080/title/{}'.format(best_vid_ID))).content).decode("utf-8") # Done fav_vid_ID = (requests.get(url='http://127.0.0.1:8080/user-fav-video/{}'.format(username)).content).decode("utf-8") # Done fav_vid_title = ((requests.get(url='http://127.0.0.1:8080/title/{}'.format(fav_vid_ID))).content).decode("utf-8") # Done user_dashboard = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('user_dashboard.html'))).content).decode("utf-8") # Done return render_template_string(user_dashboard, username = session['user'], view_count = view_count, video_count = video_count, high_video_ID = best_vid_ID, high_title = best_vid_title, fav_video_ID = fav_vid_ID, fav_title = fav_vid_title)
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def upload_form(): #WORKS """ In GET request - Displays upload form. """ if request.method == 'GET': if 'user' not in session: return redirect(url_for('login_form')) is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) upload_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('upload.html'))).content).decode("utf-8") return render_template_string(upload_page) """ In POST request - Accepts video from user. """ if request.method == 'POST': if 'user' not in session: return redirect(url_for('login_form')) is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) file = request.files['file'] username = session['user'] title = request.form['title'] if file and allowed_file(file.filename): video_ID = ((requests.post(url='http://127.0.0.1:8080/upload', data={'username' : username, 'title' : title, 'file' : base64.b64encode(file.read())})).content).decode("utf-8") # Done return redirect(url_for('watch_video', v = video_ID)) else: return redirect(url_for('upload_form'))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def delete_own_video(): """ In GET request - Redirects to login page if not logged in. - If the uploader and current user are the same, it deletes the video. - Redirects to dashboard. """ if request.method == 'GET': if 'user' not in session: return redirect(url_for('login_form')) is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) d_error = request.args.get('d_error', False) video_ID = request.args.get('video_ID') title = ((requests.get('http://127.0.0.1:8080/title/{}'.format(video_ID))).content).decode("utf-8") # Done uploader = ((requests.get('http://127.0.0.1:8080/uploader/{}'.format(video_ID))).content).decode("utf-8") # Done if uploader == 'Error getting username': abort(404) username = session['user'] if username != uploader: abort(403) else: video_delete_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('video_delete_confirmation.html'))).content).decode("utf-8") return render_template_string(video_delete_page, video_ID = video_ID, title = title, c_error = d_error) """ In POST request - Accepts password from form. - Checks if the user is valid. - Deletes the video. """ if request.method == 'POST': if 'user' not in session: abort(403) is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) username = session['user'] password = request.form['password'] video_ID = request.form['video_ID'] is_deleted = ((requests.post(url='http://127.0.0.1:8080/delete-video', data={'username' : username, 'password' : password, 'video_ID' : video_ID})).content).decode("utf-8") # Done if is_deleted == "True": return redirect(url_for('my_videos')) else: return redirect(url_for('delete_own_video', video_ID = video_ID, d_error = True))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def watch_video(): #WORKS """ In GET request - Plays the video with the corresponding video ID. """ if request.method == 'GET': if 'user' in session: is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) video_ID = request.args.get('v', None) if video_ID == None: return redirect(url_for('dashboard')) is_available = ((requests.get(url='http://127.0.0.1:8080/is-available/{}'.format(video_ID))).content).decode("utf-8") if is_available == "False": abort(404) requests.post(url='http://127.0.0.1:8080/update-count', data={'video_ID' : video_ID}) # Done vid_title = ((requests.get(url='http://127.0.0.1:8080/title/{}'.format(video_ID))).content).decode("utf-8") # Done vid_uploader = ((requests.get(url='http://127.0.0.1:8080/uploader/{}'.format(video_ID))).content).decode("utf-8") # Done vid_views = ((requests.get(url='http://127.0.0.1:8080/views/{}'.format(video_ID))).content).decode("utf-8") # Done vid_upload_date = ((requests.get(url='http://127.0.0.1:8080/upload-date/{}'.format(video_ID))).content).decode("utf-8") # Done video_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('video.html'))).content).decode("utf-8") # Done random_vids = {} random_video_IDs = ((requests.get('http://127.0.0.1:8080/get-random/{}'.format(video_ID))).content).decode("utf-8") # Done random_video_IDs = ast.literal_eval(random_video_IDs) for ID in random_video_IDs: title = ((requests.get(url='http://127.0.0.1:8080/title/{}'.format(ID))).content).decode("utf-8") # Done views = ((requests.get(url='http://127.0.0.1:8080/views/{}'.format(ID))).content).decode("utf-8") # Done uploader = ((requests.get(url='http://127.0.0.1:8080/uploader/{}'.format(ID))).content).decode("utf-8") # Done details = [title, views, uploader] random_vids.update({ID : details}) if 'user' in session: username = session['user'] requests.post(url='http://127.0.0.1:8080/update-watched', data={'username' : username, 'video_ID' : video_ID}) # Done username = session['user'] return render_template_string(video_page, random_vids = random_vids, video_ID = video_ID, title = vid_title, uploader = vid_uploader, views = vid_views, vid_upload_date = vid_upload_date, logged_in = True, username = username) else: return render_template_string(video_page, random_vids = random_vids, video_ID = video_ID, title = vid_title, uploader = vid_uploader, views = vid_views, vid_upload_date = vid_upload_date)
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def search_videos(): """ In POST request - Accepts the search key from the user. """ if request.method == 'POST': if 'user' in session: is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) search_key = request.form['search'] return redirect(url_for('results', search_query = search_key))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def results(): """ In GET request - Displays the search results. """ if request.method == 'GET': logged_in = False if 'user' in session: logged_in = True is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) search_key = request.args.get('search_query', None) if search_key == None: return redirect('dashboard') results = ((requests.get(url='http://127.0.0.1:8080/fuzzy/{}'.format(search_key))).content).decode("utf-8") # Done result_dict = {} results = ast.literal_eval(results) for ID in results: title = ((requests.get(url='http://127.0.0.1:8080/title/{}'.format(ID))).content).decode("utf-8") # Done views = ((requests.get(url='http://127.0.0.1:8080/views/{}'.format(ID))).content).decode("utf-8") # Done uploader = ((requests.get(url='http://127.0.0.1:8080/uploader/{}'.format(ID))).content).decode("utf-8") # Done details = [title, views, uploader] result_dict.update({ID : details}) search_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('search.html'))).content).decode("utf-8") return render_template_string(search_page, results = result_dict, search = search_key, logged_in = logged_in)
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def random_video(): """ In GET request - Selects a random video from the database and redirects to the page of the video. """ if request.method == 'GET': if 'user' in session: is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) random_video_ID = ((requests.get(url='http://127.0.0.1:8080/random').content)).decode("utf-8") # Done return redirect(url_for('watch_video', v = random_video_ID))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def watched_videos(): """ In GET request - Displays a page of all videos watched by the user in the WATCHED tables. """ if request.method == 'GET': if 'user' not in session: return redirect(url_for('login_form')) is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) username = session['user'] watched_IDs = ((requests.get(url='http://127.0.0.1:8080/watched/{}'.format(username))).content).decode("utf-8") # Done watched_IDs = ast.literal_eval(watched_IDs) watched_dictionary = {} for ID in watched_IDs: title = ((requests.get(url='http://127.0.0.1:8080/title/{}'.format(ID))).content).decode("utf-8") # Done views = ((requests.get(url='http://127.0.0.1:8080/views/{}'.format(ID))).content).decode("utf-8") # Done uploader = ((requests.get(url='http://127.0.0.1:8080/uploader/{}'.format(ID))).content).decode("utf-8") # Done watched_dictionary.update({ID : [title, views, uploader]}) watched_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('watched.html'))).content).decode("utf-8") return render_template_string(watched_page, watched = watched_dictionary)
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def user_videos(username): """ In GET request - Displays a page of all videos uploaded by the user in the VIDEOS table. """ if request.method == 'GET': if 'user' in session: is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) if username == session['user']: return redirect(url_for('my_videos')) is_user_present = ((requests.get(url='http://127.0.0.1:8080/is-user-present/{}'.format(username))).content).decode("utf-8") # Done if is_user_present == "False": abort(404) uploaded_IDs = ((requests.get(url='http://127.0.0.1:8080/uploaded/{}'.format(username))).content).decode("utf-8") # Done uploaded_IDs = ast.literal_eval(uploaded_IDs) uploaded_dictionary = {} for ID in uploaded_IDs: title = ((requests.get(url='http://127.0.0.1:8080/title/{}'.format(ID))).content).decode("utf-8") # Done views = ((requests.get(url='http://127.0.0.1:8080/views/{}'.format(ID))).content).decode("utf-8") # Done uploaded_dictionary.update({ID : [title, views]}) user_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('user.html'))).content).decode("utf-8") logged_in = False if 'user' in session: logged_in = True return render_template_string(user_page, logged_in = logged_in, username = username, user_videos = uploaded_dictionary)
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def my_videos(): """ In GET request - Returns a page of videos uploaded by the logged in user. """ if request.method == 'GET': if 'user' not in session: return redirect(url_for('login_form')) is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) username = session['user'] uploaded_IDs = ((requests.get(url='http://127.0.0.1:8080/uploaded/{}'.format(username))).content).decode("utf-8") # Done uploaded_IDs = ast.literal_eval(uploaded_IDs) uploaded_dictionary = {} for ID in uploaded_IDs: title = ((requests.get(url='http://127.0.0.1:8080/title/{}'.format(ID))).content).decode("utf-8") # Done views = ((requests.get(url='http://127.0.0.1:8080/views/{}'.format(ID))).content).decode("utf-8") # Done uploaded_dictionary.update({ID : [title, views]}) my_videos_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('my_videos.html'))).content).decode("utf-8") # Done return render_template_string(my_videos_page, username = username, user_videos = uploaded_dictionary)
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def flag_video(): """ In GET request - Flags the video. - Redirects to home page. """ if request.method == 'GET': if 'user' not in session: return redirect('login_form') is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) video_ID = request.args.get('v') username = session['user'] requests.post(url='http://127.0.0.1:8080/flag', data={'video_ID' : video_ID, 'username' : username}) return redirect(url_for('start'))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def favourites(): """ In GET request - Displays a list of favourite videos. """ if request.method == 'GET': if 'user' in session: is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": abort(403) username = session['user'] fav_list = (requests.get(url='http://127.0.0.1:8080/favourites/{}'.format(username)).content).decode("utf-8") fav_list = ast.literal_eval(fav_list) fav_dicttionary = {} for ID in fav_list: title = ((requests.get(url='http://127.0.0.1:8080/title/{}'.format(ID))).content).decode("utf-8") # Done views = ((requests.get(url='http://127.0.0.1:8080/views/{}'.format(ID))).content).decode("utf-8") # Done uploader = ((requests.get(url='http://127.0.0.1:8080/uploader/{}'.format(ID))).content).decode("utf-8") # Done fav_dicttionary.update({ID : [title, views, uploader]}) favourites_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('favourite.html'))).content).decode("utf-8") # Done return render_template_string(favourites_page, fav = fav_dicttionary) else: return redirect(url_for('login_form'))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def add_admin(): """ In GET request - Displays the add administrator page. """ if request.method == 'GET': if 'user' in session: is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": add_admin_page = (requests.get(url='http://127.0.0.1:8080/html/{}'.format('add_admin.html')).content).decode("utf-8") # Done name_error = request.args.get('name_error', False) pass_error = request.args.get('pass_error', False) return render_template_string(add_admin_page, nameError = name_error, passError = pass_error) else: abort(403) else: return redirect(url_for('login_form')) """ In POST request - Checks if the administrator credentials are valid. - Checks if the new username is not already taken. - Adds the new administrator to the ADMINS table. """ if request.method == 'POST': if 'user' in session: is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": admin_password = request.form['admin_password'] new_username = request.form['new_username'] new_password = request.form['new_password'] is_valid_admin = (requests.post(url='http://127.0.0.1:8080/is-valid-user', data={'username' : session['user'], 'password' : admin_password}).content).decode("utf-8") # Done if is_valid_admin == "True": is_valid_username = (requests.get(url='http://127.0.0.1:8080/is-valid-username/{}'.format(new_username)).content).decode("utf-8") # Done if is_valid_username == "False": requests.post(url='http://127.0.0.1:8080/add-admin', data={'username' : new_username, 'password' : new_password}) return redirect(url_for('dashboard')) else: return redirect(url_for('add_admin', name_error = True)) else: return redirect(url_for('add_admin', pass_error = True)) else: abort(403) else: return redirect(url_for('login_form'))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def flagged_videos(): """ In GET request - Displays all the flagged videos. """ if request.method == 'GET': if 'user' in session: is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": flagged_IDs = ((requests.get(url='http://127.0.0.1:8080/flagged')).content).decode("utf-8") # Done flagged_IDs = ast.literal_eval(flagged_IDs) flagged_dictionary = {} for ID in flagged_IDs: title = ((requests.get(url='http://127.0.0.1:8080/title/{}'.format(ID))).content).decode("utf-8") # Done views = ((requests.get(url='http://127.0.0.1:8080/views/{}'.format(ID))).content).decode("utf-8") # Done uploader = ((requests.get(url='http://127.0.0.1:8080/uploader/{}'.format(ID))).content).decode("utf-8") # Done flagger = ((requests.get(url='http://127.0.0.1:8080/flagger/{}'.format(ID))).content).decode("utf-8") # Done flagged_dictionary.update({ID : [title, views, uploader, flagger]}) flagged_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('flagged.html'))).content).decode("utf-8") # Done return render_template_string(flagged_page, flagged_videos = flagged_dictionary) else: abort(403) else: return redirect(url_for('login_form'))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def admin_delete_video(): """ In GET request - Deletes the video with the corresponding video ID. """ if request.method == 'GET': if 'user' in session: is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": video_ID = request.args.get('video_ID') requests.post(url='http://127.0.0.1:8080/admin-delete-video', data={'video_ID' : video_ID}) return redirect(url_for('flagged_videos')) else: abort(403) else: return redirect(url_for('login_form'))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def admin_list_users(): """ In GET request - Displays a list of users. """ if request.method == 'GET': if 'user' in session: is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": user_list = (requests.get(url='http://127.0.0.1:8080/user-list').content).decode("utf-8") user_list = ast.literal_eval(user_list) user_dictionary = {} for username in user_list: num_videos = (requests.get(url='http://127.0.0.1:8080/num-videos/{}'.format(username)).content).decode("utf-8") num_flagged = (requests.get(url='http://127.0.0.1:8080/num-flags/{}'.format(username)).content).decode("utf-8") user_dictionary.update({username : [num_videos, num_flagged]}) users_page = (requests.get(url='http://127.0.0.1:8080/html/{}'.format('user_list.html')).content).decode("utf-8") return render_template_string(users_page, user_dict = user_dictionary) else: abort(403) else: return redirect(url_for('login_form'))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def admin_delete_user(username): """ In GET request - Deletes the user with the corresponding username. """ if request.method == 'GET': if 'user' in session: is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": requests.post(url='http://127.0.0.1:8080/admin-delete-user', data={'username' : username}) return redirect(url_for('admin_list_users')) else: abort(403) else: return redirect(url_for('login_form'))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]
def admin_review_video(): """ In GET request - The administrator can watch the video. - Delete the video. - Remove the flag. """ if request.method == 'GET': if 'user' in session: is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done if is_admin == "True": video_ID = request.args.get('v') vid_title = ((requests.get(url='http://127.0.0.1:8080/title/{}'.format(video_ID))).content).decode("utf-8") # Done vid_uploader = ((requests.get(url='http://127.0.0.1:8080/uploader/{}'.format(video_ID))).content).decode("utf-8") # Done vid_views = ((requests.get(url='http://127.0.0.1:8080/views/{}'.format(video_ID))).content).decode("utf-8") # Done video_page = ((requests.get(url='http://127.0.0.1:8080/html/{}'.format('review.html'))).content).decode("utf-8") # Done return render_template_string(video_page, video_ID = video_ID, title = vid_title, uploader = vid_uploader, views = vid_views) else: abort(403) else: return redirect(url_for('login_form'))
sharadbhat/Video-Sharing-Platform
[ 74, 30, 74, 5, 1507245196 ]