code
stringlengths
1
18.2k
db.close_db() return import_request.response_failed("Unknown import request") @app.route('{0}/data/<file_id_hex>/<md5_hex>'.format(url_path), methods=['POST']) @meteor_app.requires_auth(roles=['import']) def import_file_data(file_id_hex, md5_hex): """ Receive a file upload, passing it to the handler if it contains the ...
def response_complete(self): """ Signal that this particular entity has been fully processed. The exporter will not send it to this target again under this particular export configuration (there is no guarantee another export configuration on the same server won't send it, or that it won't be received from another serv...
def response_continue(self): """ Signals that a partial reception of data has occurred and that the exporter should continue to send data for this entity. This should also be used if import-side caching has missed, in which case the response will direct the exporter to re-send the full data for the entity (otherwise it...
jsonify({'state': 'continue'}) else: ImportRequest.logger.debug("Sending: continue-nocache") return jsonify({'state': 'continue-nocache'})
def process_request(): """ Retrieve a CameraStatus, Event or FileRecord from the request, based on the supplied type and ID. If the type is 'cached_request' then the ID must be specified in 'cached_request_id' - if this ID is not for an entity in the cache this method will return None and clear the cache (this should o...
to this request, or None if we had an issue and there was an unexpected cache miss. """ g.request_dict = safe_load(request.get_data()) entity_type = g.request_dict['type'] entity_id = g.request_dict[entity_type]['id'] ImportRequest.logger.debug("Received request, type={0}, id={1}".format(entity_type, entity_id)) entity...
def _get_entity(entity_id): """ Uses the request context to retrieve a :class:`meteorpi_model.CameraStatus`, :class:`meteorpi_model.Event` or :class:`meteorpi_model.FileRecord` from the POSTed JSON string. :param string entity_id: The ID of a CameraStatus, Event or FileRecord contained within the request :return: The c...
def get_game(site, description="", create=False): """ get the current game, if its still active, else creates a new game, if the current time is inside the GAME_START_TIMES interval and create=True @param create: create a game, if there is no active game @returns: None if there is no active Game, and none shoul be crea...
game
def words_with_votes(self, only_topics=True): """ returns a list with words ordered by the number of votes annotated with the number of votes in the "votes" property. """ result = Word.objects.filter( bingofield__board__game__id=self.id).exclude( type=WORD_TYPE_MIDDLE) if only_topics: result = result.exclude(bingofield...
def _assign_to_null(obj, path, value, force=True): """ value IS ASSIGNED TO obj[self.path][key] path IS AN ARRAY OF PROPERTY NAMES force=False IF YOU PREFER TO use setDefault() """ try: if obj is Null: return if _get(obj, CLASS) is NullType: d = _get(obj, "__dict__") o = d[OBJ] p = d["__key__"] s = [p]+path return _ass...
def literals(choices, prefix="", suffix=""): """Create a regex from a space-separated list of literal `choices`. If provided, `prefix` and `suffix` will be attached to each choice individually. """ return "|".join(prefix + re.escape(c) + suffix for c in choices.split())
def lex(self, text, start=0): """Lexically analyze `text`. Yields pairs (`name`, `tokentext`). """ max = len(text) eaten = start s = self.state r = self.regexes toks = self.toks while eaten < max: for match in r[s].finditer(text, eaten): name = match.lastgroup tok = toks[name] toktext = match.group(name) eaten += len(t...
def new_instance(settings): """ MAKE A PYTHON INSTANCE `settings` HAS ALL THE `kwargs`, PLUS `class` ATTRIBUTE TO INDICATE THE CLASS TO CREATE """ settings = set_default({}, settings) if not settings["class"]: Log.error("Expecting 'class' attribute with fully qualified class name") # IMPORT MODULE FOR HANDLER path = se...
def get_function_by_name(full_name): """ RETURN FUNCTION """ # IMPORT MODULE FOR HANDLER path = full_name.split(".") function_name = path[-1] path = ".".join(path[:-1]) constructor = None try: temp = __import__(path, globals(), locals(), [function_name], -1) output = object.__getattribute__(temp, function_name) return ...
def extend(cls): """ DECORATOR TO ADD METHODS TO CLASSES :param cls: THE CLASS TO ADD THE METHOD TO :return: """ def extender(func): setattr(cls, get_function_name(func), func) return func return extender
def normalize_fieldsets(fieldsets): """ Make sure the keys in fieldset dictionaries are strings. Returns the normalized data. """ result = [] for name, options in fieldsets: result.append((name, normalize_dictionary(options))) return result
def normalize_dictionary(data_dict): """ Converts all the keys in "data_dict" to strings. The keys must be convertible using str(). """ for key, value in data_dict.items(): if not isinstance(key, str): del data_dict[key] data_dict[str(key)] = value return data_dict
def get_sort_field(attr, model): """ Get's the field to sort on for the given attr. Currently returns attr if it is a field on the given model. If the models has an attribute matching that name and that value has an attribute 'sort_field' than that value is used. TODO: Provide a way to sort based on a non field attribu...
def labels(self): """ Get field label for fields """ if type(self.object_list) == type([]): model = self.formset.model else: model = self.object_list.model for field in self.visible_fields: name = None if self.formset: f = self.formset.empty_form.fields.get(field, None) if f: name = f.label if name is None: name = labe...
def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 ): """Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which s...
it from your system entirely before rerunning this script." ) sys.exit(2) except ImportError: egg = download_setuptools(version, download_base, to_dir, download_delay) sys.path.insert(0, egg) import setuptools; setuptools.bootstrap_install_from = egg import pkg_resources try: pkg_resources.require("setuptools>="+versio...
def activate(request, activation_key, template_name='accounts/activate_fail.html', success_url=None, extra_context=None): """ Activate a user with an activation key. The key is a SHA1 string. When the SHA1 is found with an :class:`AccountsSignup`, the :class:`User` of that account will be activated. After a successful ...
after a successful activation. Will replace ``%(username)s`` with string formatting if supplied. If ``success_url`` is left empty, will direct to ``accounts_profile_detail`` view. :param extra_context: Dictionary containing variables which could be added to the template context. Default to an empty dictionary. """ user...
def email_confirm(request, confirmation_key, template_name='accounts/email_confirm_fail.html', success_url=None, extra_context=None): """ Confirms an email address with a confirmation key. Confirms a new email address by running :func:`User.objects.confirm_email` method. If the method returns an :class:`User` the user ...
by ``reverse`` function. :param extra_context: Dictionary of variables that are passed on to the template supplied by ``template_name``. """ user = AccountsSignup.objects.confirm_email(confirmation_key) if user: if accounts_settings.ACCOUNTS_USE_MESSAGES: messages.success(request, _('Your email address has been changed...
def direct_to_user_template(request, username, template_name, extra_context=None): """ Simple wrapper for Django's :func:`direct_to_template` view. This view is used when you want to show a template to a specific user. A wrapper for :func:`direct_to_template` where the template also has access to the user that is found...
extra_context = dict() extra_context['viewed_user'] = user extra_context['profile'] = user.get_profile() return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
def signin(request, auth_form=AuthenticationForm, template_name='accounts/signin_form.html', redirect_field_name=REDIRECT_FIELD_NAME, redirect_signin_function=signin_redirect, extra_context=None): """ Signin using email or username with password. Signs a user in by combining email/username with password. If the combina...
is set in ``REDIRECT_FIELD_NAME`` setting. :param redirect_signin_function: Function which handles the redirect. This functions gets the value of ``REDIRECT_FIELD_NAME`` and the :class:`User` who has logged in. It must return a string which specifies the URI to redirect to. :param extra_context: A dictionary containing...
redirect(reverse('accounts_disabled', kwargs={'username': user.username})) if not extra_context: extra_context = dict() extra_context.update({ 'form': form, 'next': request.GET.get(redirect_field_name), }) return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
def signout(request, next_page=accounts_settings.ACCOUNTS_REDIRECT_ON_SIGNOUT, template_name='accounts/signout.html', *args, **kwargs): """ Signs out the user and adds a success message ``You have been signed out.`` If next_page is defined you will be redirected to the URI. If not the template in template_name is used....
def email_change(request, username, email_form=ChangeEmailForm, template_name='accounts/email_form.html', success_url=None, extra_context=None): """ Change email address :param username: String of the username which specifies the current account. :param email_form: Form that will be used to change the email address. De...
to change the email address supplied by ``form``. ``account`` Instance of the ``Account`` whose email address is about to be changed. **Todo** Need to have per-object permissions, which enables users with the correct permissions to alter the email address of others. """ user = get_object_or_404(get_user_model(), userna...
def password_change(request, username, template_name='accounts/password_form.html', pass_form=PasswordChangeForm, success_url=None, extra_context=None): """ Change password of user. This view is almost a mirror of the view supplied in :func:`contrib.auth.views.password_change`, with the minor change that in this view w...
success_url: Named URL that is passed onto a :func:`reverse` function with ``username`` of the active user. Defaults to the ``accounts_password_complete`` URL. :param extra_context: Dictionary of extra variables that are passed on to the template. The ``form`` key is always used by the form supplied by ``pass_form``. *...
def profile_edit(request, username, edit_profile_form=EditProfileForm, template_name='accounts/profile_form.html', success_url=None, extra_context=None, **kwargs): """ Edit profile. Edits a profile selected by the supplied username. First checks permissions if the user is allowed to edit this profile, if denied will sh...
extra_context: Dictionary containing variables that are passed on to the ``template_name`` template. ``form`` key will always be the form used to edit the profile, and the ``profile`` key is always the edited profile. **Context** ``form`` Form that is used to alter the profile. ``profile`` Instance of the ``Profile`` t...
def profile_detail( request, username, template_name=accounts_settings.ACCOUNTS_PROFILE_DETAIL_TEMPLATE, extra_context=None, **kwargs): """ Detailed view of an user. :param username: String of the username of which the profile should be viewed. :param template_name: String representing the template name that should be ...
def account_delete(request, username, template_name=accounts_settings.ACCOUNTS_PROFILE_DETAIL_TEMPLATE, extra_context=None, **kwargs): """ Delete an account. """ user = get_object_or_404(get_user_model(), username__iexact=username) user.is_active = False user.save() return redirect(reverse('accounts_admin'))
def parse_properties(parent_index_name, parent_name, nested_path, esProperties): """ RETURN THE COLUMN DEFINITIONS IN THE GIVEN esProperties OBJECT """ columns = FlatList() for name, property in esProperties.items(): index_name = parent_index_name column_name = concat_field(parent_name, name) jx_name = column_name if p...
if cardinality is None: for cc in child_columns: cc.cardinality = None columns.extend(child_columns) if property.type in es_type_to_json_type.keys(): columns.append(Column( name=jx_name, es_index=index_name, es_column=column_name, es_type=property.type, jx_type=es_type_to_json_type[property.type], cardinality=cardinali...
def _get_best_type_from_mapping(mapping): """ THERE ARE MULTIPLE TYPES IN AN INDEX, PICK THE BEST :param mapping: THE ES MAPPING DOCUMENT :return: (type_name, mapping) PAIR (mapping.properties WILL HAVE PROPERTIES """ best_type_name = None best_mapping = None for k, m in mapping.items(): if k == "_default_": continue i...
def _merge_mapping(a, b): """ MERGE TWO MAPPINGS, a TAKES PRECEDENCE """ for name, b_details in b.items(): a_details = a[literal_field(name)] if a_details.properties and not a_details.type: a_details.type = "object" if b_details.properties and not b_details.type: b_details.type = "object" if a_details: a_details.type =...
def retro_schema(schema): """ CONVERT SCHEMA FROM 5.x to 1.x :param schema: :return: """ output = wrap({ "mappings":{ typename: { "dynamic_templates": [ retro_dynamic_template(*(t.items()[0])) for t in details.dynamic_templates ], "properties": retro_properties(details.properties) } for typename, details in schema.mapp...
def diff_schema(A, B): """ RETURN PROPERTIES IN A, BUT NOT IN B :param A: elasticsearch properties :param B: elasticsearch properties :return: (name, properties) PAIRS WHERE name IS DOT-DELIMITED PATH """ output =[] def _diff_schema(path, A, B): for k, av in A.items(): if k == "_id" and path == ".": continue # DO NOT A...
def delete_all_but_self(self): """ DELETE ALL INDEXES WITH GIVEN PREFIX, EXCEPT name """ prefix = self.settings.alias name = self.settings.index if prefix == name: Log.note("{{index_name}} will not be deleted", index_name= prefix) for a in self.cluster.get_aliases(): # MATCH <prefix>YYMMDD_HHMMSS FORMAT if re.match(re....
def is_proto(self, index): """ RETURN True IF THIS INDEX HAS NOT BEEN ASSIGNED ITS ALIAS """ for a in self.cluster.get_aliases(): if a.index == index and a.alias: return False return True
def extend(self, records): """ records - MUST HAVE FORM OF [{"value":value}, ... {"value":value}] OR [{"json":json}, ... {"json":json}] OPTIONAL "id" PROPERTY IS ALSO ACCEPTED """ if self.settings.read_only: Log.error("Index opened in read only mode, no changes allowed") lines = [] try: for r in records: if '_id' in r ...
lines) + "\n" except Exception as e: raise Log.error("can not make request body from\n{{lines|indent}}", lines=lines, cause=e) wait_for_active_shards = coalesce( self.settings.wait_for_active_shards, {"one": 1, None: None}[self.settings.consistency] ) response = self.cluster.post( self.path + "/_bulk", data=data_string...
(typed={{typed}}):\n{{line}}", params={ "status":items[i].index.status, "error":items[i].index.error, "some":len(fails) - 1, "line":strings.limit(lines[i * 2 + 1], 500 if not self.debug else 100000), "index":self.settings.index, "typed":self.settings.typed, "id":items[i].index._id } ) for i in fails ] else: i=fails[0] ...
def set_refresh_interval(self, seconds, **kwargs): """ :param seconds: -1 FOR NO REFRESH :param kwargs: ANY OTHER REQUEST PARAMETERS :return: None """ if seconds <= 0: interval = -1 else: interval = text_type(seconds) + "s" if self.cluster.version.startswith("0.90."): response = self.cluster.put( "/" + self.settings.in...
def get_index(self, index, type, alias=None, typed=None, read_only=True, kwargs=None): """ TESTS THAT THE INDEX EXISTS BEFORE RETURNING A HANDLE """ if kwargs.tjson != None: Log.error("used `typed` parameter, not `tjson`") if read_only: # GET EXACT MATCH, OR ALIAS aliases = wrap(self.get_aliases()) if index in aliases....
def get_alias(self, alias): """ RETURN REFERENCE TO ALIAS (MANY INDEXES) USER MUST BE SURE NOT TO SEND UPDATES """ aliases = self.get_aliases() if alias in aliases.alias: settings = self.settings.copy() settings.alias = alias settings.index = alias return Index(read_only=True, kwargs=settings, cluster=self) Log.error("...
def get_canonical_index(self, alias): """ RETURN THE INDEX USED BY THIS alias THIS IS ACCORDING TO THE STRICT LIFECYCLE RULES: THERE IS ONLY ONE INDEX WITH AN ALIAS """ output = jx.sort(set( i for ai in self.get_aliases() for a, i in [(ai.alias, ai.index)] if a == alias or i == alias or (re.match(re.escape(alias) + "\\...
def get_prototype(self, alias): """ RETURN ALL INDEXES THAT ARE INTENDED TO BE GIVEN alias, BUT HAVE NO ALIAS YET BECAUSE INCOMPLETE """ output = sort([ a.index for a in self.get_aliases() if re.match(re.escape(alias) + "\\d{8}_\\d{6}", a.index) and not a.alias ]) return output
def delete_all_but(self, prefix, name): """ :param prefix: INDEX MUST HAVE THIS AS A PREFIX AND THE REMAINDER MUST BE DATE_TIME :param name: INDEX WITH THIS NAME IS NOT DELETED :return: """ if prefix == name: Log.note("{{index_name}} will not be deleted", {"index_name": prefix}) for a in self.get_aliases(): # MATCH <pr...
def get_aliases(self): """ RETURN LIST OF {"alias":a, "index":i} PAIRS ALL INDEXES INCLUDED, EVEN IF NO ALIAS {"alias":Null} """ for index, desc in self.get_metadata().indices.items(): if not desc["aliases"]: yield wrap({"index": index}) elif desc['aliases'][0] == index: Log.error("should not happen") else: for a in de...
def build_homogeneisation_caracteristiques_sociales(temporary_store = None, year = None): u"""Homogénéisation des caractéristiques sociales des ménages """ assert temporary_store is not None assert year is not None # Load data bdf_survey_collection = SurveyCollection.load( collection = 'budget_des_familles', config_fil...
du ménage # exrev = 1 si les données sont bien remplies pour les revenus du ménage menage = menage[(menage.exdep == 1) & (menage.exrev == 1)] menage.rename( columns = { 'v': 'vag', 'mena': 'ident_men', 'ponderrd': 'pondmen', 'nbpers': 'npers', 'nm14a': 'nenfants', 'nbenf': 'nenfhors', 'nbact': 'nactifs', 'cohabpr': 'co...
menage.typmen[menage.typmen_ == 3] = 4 menage.typmen[menage.typmen_ == 4] = 4 menage.typmen[menage.typmen_ == 5] = 4 menage.typmen[menage.typmen_ == 6] = 2 menage.typmen[menage.typmen_ == 7] = 5 del menage['typmen_'] var_to_ints = ['couplepr', 'etamatri'] for var_to_int in var_to_ints: menage[var_to_int] = menage[var_t...
2] = 4 menage.situapr[menage.occuppr == 5] = 5 menage.situapr[menage.occuppr == 6] = 5 menage.situapr[menage.occuppr == 7] = 6 menage.situapr[menage.occuppr == 8] = 7 menage.situapr[menage.occuppr == 4] = 8 menage["typlog"] = 0 menage.typlog[menage.sitlog == 1] = 1 menage.typlog[menage.sitlog != 1] = 2 menage['stalog']...
'nbact': 'nactifs', 'nbenf1': 'nenfants', 'nbpers': 'npers', 'rev81': 'poste_coicop_421', 'typmen1': 'typmen' }, inplace = True, ) menage.ocde10 = menage.ocde10 / 10 # on met un numéro à chaque vague pour pouvoir faire un meilleur suivi des évolutions temporelles # pour le modèle de demande menage.agecj = menage.agecj....
4 menage.typmen.loc[menage.typmen_ == 4] = 4 menage.typmen.loc[menage.typmen_ == 5] = 4 menage.typmen.loc[menage.typmen_ == 6] = 2 menage.typmen.loc[menage.typmen_ == 7] = 5 del menage['typmen_'] menage.couplepr = menage.couplepr.astype('int') menage["nadultes"] = menage['npers'] - menage['nenfants'] menage.typmen = me...
== 3] = 3 menage.situapr.loc[menage.occupcpr == 2] = 4 menage.situapr.loc[menage.occupcpr == 5] = 5 menage.situapr.loc[menage.occupcpr == 6] = 5 menage.situapr.loc[menage.occupcpr == 7] = 6 menage.situapr.loc[menage.occupcpr == 8] = 7 menage.situapr.loc[menage.occupcpr == 4] = 8 menage["natiocj"] = 0 menage["natiopr"] ...
= 41 menage.dip14pr.loc[menage.dieppr == 23] = 50 menage.dip14pr.loc[menage.dieppr == 25] = 50 menage.dip14pr.loc[menage.dieppr == 27] = 50 menage.dip14pr.loc[menage.dieppr == 29] = 50 menage.dip14pr.loc[menage.dieppr == 34] = 43 menage.dip14pr.loc[menage.dieppr == 32] = 42 menage.dip14pr.loc[menage.dieppr == 36] = 42 ...
variables_to_destring = ['anais'] for variable_to_destring in variables_to_destring: individus[variable_to_destring] = individus[variable_to_destring].astype('int').copy() individus['agepr'] = year - individus.anais individus.set_index('ident_men', inplace = True) assert menage.notnull().all().all(), 'The following var...
"cs_pr" }, inplace = True, ) del menage['agpr'] menage['nadultes'] = menage.npers - menage.nenfants for person in ['pr', 'cj']: menage['natio' + person] = (menage['natio7' + person] > 2) # TODO: changer de convention ? del menage['natio7' + person] menage.agecj = menage.agecj.fillna(0) menage.nenfhors = menage.nenfhors...
menage.vag.loc[menage.vag_ == 5] = 21 menage.vag.loc[menage.vag_ == 6] = 22 del menage['vag_'] # Recodage des catégories zeat menage.zeat.loc[menage.zeat == 7] = 6 menage.zeat.loc[menage.zeat == 8] = 7 menage.zeat.loc[menage.zeat == 9] = 8 assert menage.zeat.isin(range(1, 9)).all() stalog = survey.get_values(table = "d...
# donc on le recalcule avec l'année de naissance et la vague d'enquête individus['agepr'] = year - individus.anais individus.loc[individus.vag == 6, ['agepr']] = year + 1 - individus.anais individus = individus[individus.lienpref == 00].copy() kept_variables = ['ident_men', 'etamatri', 'agepr'] individus = individus[ke...
du ménage qui ne sont pas la personne de référence et le conjoint individus = individus[(individus.lienpref != 00) & (individus.lienpref != 01)].copy() individus.sort_values(by = ['ident_men', 'ident_ind'], inplace = True) # Inspired by http://stackoverflow.com/questions/17228215/enumerate-each-row-for-each-group-in-a-...
# label var agepr "Age de la personne de référence au 31/12/${yearrawdata}" # label var agecj "Age du conjoint de la PR au 31/12/${yearrawdata}" # label var sexepr "Sexe de la personne de référence" # label var sexecj "Sexe du conjoint de la PR" # label var cs42pr "Catégorie socio-professionnelle de la PR" # label var ...
var nactifs "Nombre d'actifs dans le ménage" # label var couplepr "Vie en couple de la personne de référence" # label define typmen5 1 "Personne seule" 2 "Famille monoparentale" 3 "Couple sans enfant" # 4 "Couple avec enfants" 5 "Autre type de ménage (complexe)" # label values typmen5 typmen5 # label var typmen5 "Type ...
/// # 7 "Autre situation (handicapé)" /// # 8 "Militaire du contingent" # label values situapr occupation # label values situacj occupation # label var situapr "Situation d'activité de la personne de référence" # label var situacj "Situation d'activité du conjoint de la PR" # label define diplome 10 "Diplôme de 3ème cy...
# 50 "CAP, BEP ou diplôme de même niveau" /// # 60 "Brevet des collèges, BEPC" /// # 70 "Certificat d'études primaires" /// # 71 "Aucun diplôme" # label values dip14pr diplome # label values dip14cj diplome # label var dip14pr "Diplôme le plus élevé de la PR" # label var dip14cj "Diplôme le plus élevé du conjoint de la...
"Propriétaire ou copropriétaire" /// # 2 "Accédant à la propriété (rembourse un prêt)" /// # 3 "Locataire" /// # 4 "Sous-locataire" /// # 5 "Logé gratuitement" # label values stalog statutlogement # label var stalog "Statut d'occupation du logement" # label define viecouple 1 "Vit en couple" 2 "Ne vit pas en couple" # ...
if cs42pr=="34" # replace cs24pr=32 if cs42pr=="35" # replace cs24pr=36 if cs42pr=="37" # replace cs24pr=36 if cs42pr=="38" # replace cs24pr=41 if cs42pr=="42" # replace cs24pr=41 if cs42pr=="43" # replace cs24pr=41 if cs42pr=="44" # replace cs24pr=41 if cs42pr=="45" # replace cs24pr=46 if cs42pr=="46" # replace cs24pr...
replace cs24pr=73 if cs42pr=="75" # replace cs24pr=76 if cs42pr=="77" # replace cs24pr=76 if cs42pr=="78" # replace cs24pr=81 if cs42pr=="81" # replace cs24pr=82 if cs42pr=="83" # replace cs24pr=82 if cs42pr=="84" # replace cs24pr=82 if cs42pr=="85" # replace cs24pr=82 if cs42pr=="86" # replace cs24pr=82 if cs42pr=="**...
csp42s in csp42s_by_csp24.items(): menage.loc[menage.cs42pr.isin(csp42s), 'cs24pr'] = csp24 assert menage.cs24pr.isin(csp42s_by_csp24.keys()).all() menage['cs8pr'] = numpy.floor(menage.cs24pr / 10) assert menage.cs8pr.isin(range(1, 9)).all() variables = [ 'pondmen', 'npers', 'nenfants', 'nenfhors', 'nadultes', 'nactifs...
'strate' }, inplace = True, ) del variables menage.agecj = menage.agecj.fillna(0) # Ajout de la variable vag try: depmen = survey.get_values(table = "DEPMEN") except: depmen = survey.get_values(table = "depmen") depmen.rename(columns = {'ident_me': 'ident_men'}, inplace = True) vague = depmen[['vag', 'ident_men']].copy...
logement qui prend des valeurs différentes pour 2011 stalog['stalog'] = stalog.stalog.astype('int').copy() stalog['new_stalog'] = 0 stalog.loc[stalog.stalog == 2, 'new_stalog'] = 1 stalog.loc[stalog.stalog == 1, 'new_stalog'] = 2 stalog.loc[stalog.stalog == 4, 'new_stalog'] = 3 stalog.loc[stalog.stalog == 5, 'new_stalo...
def search_obsgroups_sql_builder(search): """ Create and populate an instance of :class:`meteorpi_db.SQLBuilder` for a given :class:`meteorpi_model.ObservationGroupSearch`. This can then be used to retrieve the results of the search, materialise them into :class:`meteorpi_model.ObservationGroup` instances etc. :param O...
def search_files_sql_builder(search): """ Create and populate an instance of :class:`meteorpi_db.SQLBuilder` for a given :class:`meteorpi_model.FileRecordSearch`. This can then be used to retrieve the results of the search, materialise them into :class:`meteorpi_model.FileRecord` instances etc. :param FileRecordSearch ...
for import / export filters if search.exclude_imported: b.where_clauses.append('NOT EXISTS (SELECT * FROM archive_observationImport i WHERE i.observationId = o.uid') if search.exclude_export_to is not None: b.where_clauses.append(""" NOT EXISTS (SELECT * FROM archive_fileExport ex INNER JOIN archive_exportConfig c ON e...
def search_metadata_sql_builder(search): """ Create and populate an instance of :class:`meteorpi_db.SQLBuilder` for a given :class:`meteorpi_model.ObservatoryMetadataSearch`. This can then be used to retrieve the results of the search, materialise them into :class:`meteorpi_model.ObservatoryMetadata` instances etc. :pa...
NOT EXISTS (SELECT * FROM archive_metadataExport ex INNER JOIN archive_exportConfig c ON ex.exportConfig = c.uid WHERE ex.metadataId = m.uid AND c.exportConfigID = %s) """) b.sql_args.append(SQLBuilder.map_value(search.exclude_export_to)) return b
def add_sql(self, value, clause): """ Add a WHERE clause to the state. :param value: The unknown to bind into the state. Uses SQLBuilder._map_value() to map this into an appropriate database compatible type. :param clause: A SQL fragment defining the restriction on the unknown value """ if value is not None: self.sql_a...
def add_set_membership(self, values, column_name): """ Append a set membership test, creating a query of the form 'WHERE name IN (?,?...?)'. :param values: A list of values, or a subclass of basestring. If this is non-None and non-empty this will add a set membership test to the state. If the supplied value is a basest...
def add_metadata_query_properties(self, meta_constraints, id_table, id_column): """ Construct WHERE clauses from a list of MetaConstraint objects, adding them to the query state. :param meta_constraints: A list of MetaConstraint objects, each of which defines a condition over metadata which must be satisfied for result...
'floatValue', '<=')) elif ct == 'greater': self.where_clauses.append(sql_template.format(id_table, id_column, 'floatValue', '>=')) elif ct == 'number_equals': self.where_clauses.append(sql_template.format(id_table, id_column, 'floatValue', '=')) elif ct == 'string_equals': self.where_clauses.append(sql_template.format(...
def get_select_sql(self, columns, order=None, limit=0, skip=0): """ Build a SELECT query based on the current state of the builder. :param columns: SQL fragment describing which columns to select i.e. 'e.obstoryID, s.statusID' :param order: Optional ordering constraint, i.e. 'e.eventTime DESC' :param limit: Optional, u...
operations such as indexing will definitely break this property unless explicitly set). :returns: A SQL SELECT query, which will make use of self.sql_args when executed. """ sql = 'SELECT ' sql += '{0} FROM {1} '.format(columns, self.tables) if len(self.where_clauses) > 0: sql += ' WHERE ' sql += ' AND '.join(self.wher...
def get_count_sql(self): """ Build a SELECT query which returns the count of items for an unlimited SELECT :return: A SQL SELECT query which returns the count of items for an unlimited query based on this SQLBuilder """ sql = 'SELECT COUNT(*) FROM ' + self.tables if len(self.where_clauses) > 0: sql += ' WHERE ' sql += ...
def wrap_setup(self, class_name, typ, with_async=False): """Described.typ = noy_wrap_typ(Described, Described.typ)""" equivalence = self.equivalence[typ] return [ (NEWLINE, '\n') , (NAME, class_name) , (OP, '.') , (NAME, equivalence) , (OP, '=') , (NAME, "%snoy_wrap_%s" % ('async_' if with_async else '', equivalence)) ...
def init(scope): """ Copy all values of scope into the class SinonGlobals Args: scope (eg. locals() or globals()) Return: SinonGlobals instance """ class SinonGlobals(object): #pylint: disable=too-few-public-methods """ A fully empty class External can push the whole `scope` into this class through global function init...
def _get_wrapper(self): """ Return: Wrapper object Raise: Exception if wrapper object cannot be found """ if self.args_type == "MODULE_FUNCTION": return getattr(self.obj, self.prop) elif self.args_type == "FUNCTION": return getattr(self.g, self.obj.__name__) elif self.args_type == "PURE": return getattr(self.pure, "fun...
def __set_type(self, obj, prop): """ Triage type based on arguments Here are four types of base: PURE, MODULE, MODULE_FUNCTION, FUNCTION Args: obj: None, FunctionType, ModuleType, Class, Instance prop: None, string """ if TypeHandler.is_pure(obj, prop): self.args_type = "PURE" self.pure = SinonBase.Pure() setattr(self....
def __check_lock(self): """ Cheking whether the inspector is wrapped or not (1) MODULE_FUNCTION: Check whether both obj/prop has __SINONLOCK__/LOCK or not (2) MODULE: Check whether obj has __SINONLOCK__ or not (3) FUNCTION: Check whether function(mock as a class) has LOCK or not Raise: lock_error: when inspector has be...
def wrap2spy(self): """ Wrapping the inspector as a spy based on the type """ if self.args_type == "MODULE_FUNCTION": self.orig_func = deepcopy(getattr(self.obj, self.prop)) setattr(self.obj, self.prop, Wrapper.wrap_spy(getattr(self.obj, self.prop))) elif self.args_type == "MODULE": setattr(self.obj, "__SINONLOCK__", T...
def unwrap(self): """ Unwrapping the inspector based on the type """ if self.args_type == "MODULE_FUNCTION": setattr(self.obj, self.prop, self.orig_func) elif self.args_type == "MODULE": delattr(self.obj, "__SINONLOCK__") elif self.args_type == "FUNCTION": setattr(CPSCOPE, self.obj.__name__, self.orig_func) elif self.a...