function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def clear_peak(self):
self.peak = []
if self.peak_item:
self.peak_item.setPath(QPainterPath()) | jopohl/urh | [
9230,
807,
9230,
35,
1459539787
] |
def __init__(self, cwd):
self._newcwd = cwd
self._oldcwd = None | ikalnytskyi/kostyor-openstack-ansible | [
3,
4,
3,
3,
1479227243
] |
def __exit__(self, *args):
if self._newcwd:
os.chdir(self._oldcwd) | ikalnytskyi/kostyor-openstack-ansible | [
3,
4,
3,
3,
1479227243
] |
def _run_playbook_impl(playbook, hosts_fn=None, cwd=None, ignore_errors=False):
# Unfortunately, there's no good way to get the options instance
# with proper defaults since it's generated by argparse inside
# PlaybookCLI. Due to the fact that the options can't be empty
# and must contain proper values we have not choice but extract
# them from PlaybookCLI instance.
playbook_cli = PlaybookCLI(['to-be-stripped', playbook])
playbook_cli.parse()
options = playbook_cli.options
# Get others required options.
loader = DataLoader()
variable_manager = VariableManager()
inventory = Inventory(loader, variable_manager)
variable_manager.set_inventory(inventory)
variable_manager.extra_vars = _get_user_settings(loader)
# Limit playbook execution to hosts returned by 'hosts_fn'.
if hosts_fn is not None:
inventory.subset([
host.get_vars()['inventory_hostname']
for host in hosts_fn(inventory)
])
# Finally, we can create a playbook executor and run the playbook.
executor = PlaybookExecutor(
playbooks=[playbook],
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords={}
)
# Some playbooks may rely on current working directory, so better allow
# to change it before execution.
with _setcwd(cwd):
exitcode = executor.run()
# Celery treats exceptions from task as way to mark it failed. So let's
# throw one to do so in case return code is not zero.
if all([not ignore_errors, exitcode is not None, exitcode != 0]):
raise Exception('Playbook "%s" has been finished with errors. '
'Exit code is "%d".' % (playbook, exitcode))
return exitcode | ikalnytskyi/kostyor-openstack-ansible | [
3,
4,
3,
3,
1479227243
] |
def _run_playbook(playbook, cwd=None, ignore_errors=False):
return _run_playbook_impl(
playbook,
cwd=cwd,
ignore_errors=ignore_errors
) | ikalnytskyi/kostyor-openstack-ansible | [
3,
4,
3,
3,
1479227243
] |
def _run_playbook_for(playbook, hosts, service, cwd=None, ignore_errors=False):
return _run_playbook_impl(
playbook,
lambda inv: base.get_component_hosts_on_nodes(inv, service, hosts),
cwd=cwd,
ignore_errors=ignore_errors
) | ikalnytskyi/kostyor-openstack-ansible | [
3,
4,
3,
3,
1479227243
] |
def prepare_step(self, *args, **kwargs):
"""Prepare build environment (skip loaded of dependencies)."""
kwargs['load_tc_deps_modules'] = False
super(CrayToolchain, self).prepare_step(*args, **kwargs) | eth-cscs/production | [
48,
41,
48,
3,
1479828835
] |
def get_colour_names():
"""Get a dictionary of all known colour names."""
from collections import OrderedDict
return OrderedDict(sorted(_colours.items(), key=lambda t: t[0])) | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def is_rgb(value):
"""Check for valid RGB tuple value.
Parameters
----------
value : iterable of length 3 (e.g. [255, 0, 0])
the value to be checked
Returns
-------
valid : bool
whether the value is valid or not
"""
if not len(value) == 3:
return False
elif False in [isinstance(x, int) for x in value]:
return False
elif False in [0 <= x <= 255 for x in value]:
return False
else:
return True | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def is_name(value):
"""Check for valid colour name value.
Parameters
----------
value : str (e.g. "red")
the value to be checked
Returns
-------
valid : bool
whether the value is valid or not
"""
if not value in _colours.keys():
return False
else:
return True | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def is_hex(value):
"""Check for valid Hex triplet value.
Parameters
----------
value : string (e.g. "#FF0000")
the value to be checked
Returns
-------
valid : bool
whether the value is valid or not
"""
if not isinstance(value, str):
return False
value = value.lstrip("#")
if len(value) != 6:
return False
else:
for x in value.upper():
if x not in "0123456789ABCDEF":
return False
return True | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def is_hsv(value):
"""Check for valid HSV tuple value.
Parameters
----------
value : iterable of length 3 (e.g. [0, 100, 100])
the value to be checked
Returns
-------
valid : bool
whether the value is valid or not
"""
if not len(value) == 3:
return False
elif False in [isinstance(x, int) for x in value]:
return False
elif not 0 <= value[0] <= 360:
return False
elif False in [0 <= x <= 100 for x in value[1:]]:
return False
else:
return True | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def is_hsl(value):
"""Check for valid HSL tuple value.
Parameters
----------
value : iterable of length 3 (e.g. [0, 100, 50])
the value to be checked
Returns
-------
valid : bool
whether the value is valid or not
"""
return Colour.is_hsv(value) | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def is_colour(value):
"""Check for valid colour value.
Parameters
----------
value : any type
the value to be checked
Returns
-------
valid : bool
whether the value is valid or not
"""
return Colour.is_rgb(value) or\
Colour.is_name(value) or \
Colour.is_hex(value) or \
Colour.is_hsv(value) or\
Colour.is_hsl(value) | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def __str__(self):
return "Colour(red={0}, green={1}, blue={2})".format(self._rgb[0],
self._rgb[1],
self._rgb[2]) | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def __ne__(self, other):
return self._rgb != other._rgb | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def __len__(self):
return len(self._rgb) | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def rgb(self):
"""Getter for colour in RGB format [red, green, blue]."""
return self._rgb | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def rgb(self, value):
"""Setter for colour in RGB format [red, green, blue]."""
if Colour.is_rgb(value):
self._rgb = tuple(value)
else:
raise ValueError("'{0}' is not a valid RGB colour!".format(value)) | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def hex(self):
"""Getter for colour in Hex format "#RRGGBB"."""
return '#{:02X}{:02X}{:02X}'.format(self._rgb[0],
self._rgb[1],
self._rgb[2]) | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def hex(self, value):
"""Setter for colour in Hex format "#RRGGBB"."""
if Colour.is_hex(value):
c = value.lstrip("#")
self._rgb = tuple(int(c[i:i + 2], 16) for i in (0, 2, 4))
else:
raise ValueError("'{0}' is not a valid Hex colour!".format(value)) | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def name(self):
"""Getter for colour name (if available)."""
for name, rgb in _colours.items():
if rgb == self.rgb:
return name
return None | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def name(self, value):
"""Setter for colour name."""
if Colour.is_name(value):
self._rgb = _colours[value.lower()]
else:
raise ValueError("'{0}' is not a valid colour name!".format(value)) | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def hsv(self):
"""Getter for colour in HSV format [hue, saturation, value]."""
hsv = colorsys.rgb_to_hsv(*divide(self.rgb, 255.0))
rtn = list(multiply([hsv[0]], 360))
rtn.extend(multiply(hsv[1:], 100))
return rtn | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def hsv(self, value):
"""Setter for colour in HSV format [hue, saturation, value]."""
if Colour.is_hsv(value):
hsv = list(divide([value[0]], 360))
hsv.extend(divide(value[1:], 100))
self._rgb = multiply(colorsys.hsv_to_rgb(*hsv), 255)
else:
raise ValueError("'{0}' is not a valid HSV colour!".format(value)) | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def hsl(self):
"""Getter for colour in HSL format [hue, saturation, lightness]."""
hsl = colorsys.rgb_to_hls(*divide(self.rgb, 255.0))
rtn = list(multiply([hsl[0]], 360))
rtn.extend(multiply(hsl[1:], 100))
return rtn | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def hsl(self, value):
"""Setter for colour in HSL format [hue, saturation, lightness]."""
if Colour.is_hsv(value):
hsl = list(divide([value[0]], 360))
hsl.extend(divide(value[1:], 100))
self._rgb = multiply(colorsys.hls_to_rgb(*hsl), 255)
else:
raise ValueError("'{0}' is not a valid HSL colour!".format(value)) | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def multiply(v, d):
return tuple(map(lambda x:int(round(x*d)), v)) | expyriment/expyriment | [
106,
37,
106,
6,
1375792731
] |
def __init__(self, world_list, regionset, options, backup_worlds):
Cmd.__init__(self)
self.world_list = world_list
self.regionset = regionset
self.world_names = [str(i.name) for i in self.world_list]
# if there's only one world use it
if len(self.world_list) == 1 and len(self.regionset) == 0:
self.current = world_list[0]
elif len(self.world_list) == 0 and len(self.regionset) > 0:
self.current = self.regionset
else:
self.current = None
self.options = options
self.backup_worlds = backup_worlds
self.prompt = "#-> "
self.intro = ("Minecraft Region-Fixer interactive mode.\n(Use tab to "
"autocomplete. Type help for a list of commands.)\n")
# Possible args for chunks stuff
possible_args = ""
first = True
for i in list(c.CHUNK_PROBLEMS_ARGS.values()) + ['all']:
if not first:
possible_args += ", "
possible_args += i
first = False
self.possible_chunk_args_text = possible_args
# Possible args for region stuff
possible_args = ""
first = True
for i in list(c.REGION_PROBLEMS_ARGS.values()) + ['all']:
if not first:
possible_args += ", "
possible_args += i
first = False
self.possible_region_args_text = possible_args | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def do_set(self, arg):
""" Command to change some options and variables in interactive
mode """
args = arg.split()
if len(args) > 2:
print("Error: too many parameters.")
elif len(args) == 0:
print("Write \'help set\' to see a list of all possible variables")
else:
if args[0] == "entity-limit":
if len(args) == 1:
print("entity-limit = {0}".format(self.options.entity_limit))
else:
try:
if int(args[1]) >= 0:
self.options.entity_limit = int(args[1])
print("entity-limit = {0}".format(args[1]))
print("Updating chunk status...")
self.current.rescan_entities(self.options)
else:
print("Invalid value. Valid values are positive integers and zero")
except ValueError:
print("Invalid value. Valid values are positive integers and zero")
elif args[0] == "workload":
if len(args) == 1:
if self.current:
print("Current workload:\n{0}\n".format(self.current.__str__()))
print("List of possible worlds and region-sets (determined by the command used to run region-fixer):")
number = 1
for w in self.world_list:
print(" ### world{0} ###".format(number))
number += 1
# add a tab and print
for i in w.__str__().split("\n"):
print("\t" + i)
print()
print(" ### regionset ###")
for i in self.regionset.__str__().split("\n"):
print("\t" + i)
print("\n(Use \"set workload world1\" or name_of_the_world or regionset to choose one)")
else:
a = args[1]
if len(a) == 6 and a[:5] == "world" and int(a[-1]) >= 1:
# get the number and choos the correct world from the list
number = int(args[1][-1]) - 1
try:
self.current = self.world_list[number]
print("workload = {0}".format(self.current.world_path))
except IndexError:
print("This world is not in the list!")
elif a in self.world_names:
for w in self.world_list:
if w.name == args[1]:
self.current = w
print("workload = {0}".format(self.current.world_path))
break
else:
print("This world name is not on the list!")
elif args[1] == "regionset":
if len(self.regionset):
self.current = self.regionset
print("workload = set of region files")
else:
print("The region set is empty!")
else:
print("Invalid world number, world name or regionset.")
elif args[0] == "processes":
if len(args) == 1:
print("processes = {0}".format(self.options.processes))
else:
try:
if int(args[1]) > 0:
self.options.processes = int(args[1])
print("processes = {0}".format(args[1]))
else:
print("Invalid value. Valid values are positive integers.")
except ValueError:
print("Invalid value. Valid values are positive integers.")
elif args[0] == "verbose":
if len(args) == 1:
print("verbose = {0}".format(str(self.options.verbose)))
else:
if args[1] == "True":
self.options.verbose = True
print("verbose = {0}".format(args[1]))
elif args[1] == "False":
self.options.verbose = False
print("verbose = {0}".format(args[1]))
else:
print("Invalid value. Valid values are True and False.")
else:
print("Invalid argument! Write \'help set\' to see a list of valid variables.") | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def do_current_workload(self, arg):
""" Prints the info of the current workload """
if len(arg) == 0:
if self.current:
print(self.current)
else:
print("No world/region-set is set! Use \'set workload\' to set a world/regionset to work with.")
else:
print("This command doesn't use any arguments.") | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def do_count_chunks(self, arg):
""" Counts the number of chunks with the given problem and
prints the result """
if self.current and self.current.scanned:
if len(arg.split()) == 0:
print("Possible counters are: {0}".format(self.possible_chunk_args_text))
elif len(arg.split()) > 1:
print("Error: too many parameters.")
else:
if arg in list(c.CHUNK_PROBLEMS_ARGS.values()) or arg == 'all':
total = self.current.count_chunks(None)
for problem, status_text, a in c.CHUNK_PROBLEMS_ITERATOR:
if arg == 'all' or arg == a:
n = self.current.count_chunks(problem)
print("Chunks with status \'{0}\': {1}".format(status_text, n))
print("Total chunks: {0}".format(total))
else:
print("Unknown counter.")
else:
print("The world hasn't be scanned (or it needs a rescan). Use \'scan\' to scan it.") | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def do_count_all(self, arg):
""" Print all the counters for chunks and regions. """
if self.current and self.current.scanned:
if len(arg.split()) > 0:
print("This command doesn't requiere any arguments")
else:
print("{0:#^60}".format("Chunk problems:"))
self.do_count_chunks('all')
print("\n")
print("{0:#^60}".format("Region problems:"))
self.do_count_regions('all')
else:
print("The world hasn't be scanned (or it needs a rescan). Use \'scan\' to scan it.") | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def do_remove_chunks(self, arg):
if self.current and self.current.scanned:
if len(arg.split()) == 0:
print("Possible arguments are: {0}".format(self.possible_chunk_args_text))
elif len(arg.split()) > 1:
print("Error: too many parameters.")
else:
if arg in list(c.CHUNK_PROBLEMS_ARGS.values()) or arg == 'all':
for problem, status_text, a in c.CHUNK_PROBLEMS_ITERATOR:
if arg == 'all' or arg == a:
n = self.current.remove_problematic_chunks(problem)
if n:
self.current.scanned = False
print("Removed {0} chunks with status \'{1}\'.\n".format(n, status_text))
else:
print("Unknown argument.")
else:
print("The world hasn't be scanned (or it needs a rescan). Use \'scan\' to scan it.") | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def do_replace_regions(self, arg):
el = self.options.entity_limit
de = self.options.delete_entities
if self.current and self.current.scanned:
if len(arg.split()) == 0:
print("Possible arguments are: {0}".format(self.possible_region_args_text))
elif len(arg.split()) > 1:
print("Error: too many parameters.")
else:
if arg in list(c.REGION_PROBLEMS_ARGS.values()) or arg == 'all':
for problem, status_text, a in c.REGION_PROBLEMS_ITERATOR:
if arg == 'all' or arg == a:
n = self.current.replace_problematic_regions(self.backup_worlds, problem, el, de)
if n:
self.current.scanned = False
print("\nReplaced {0} regions with status \'{1}\'.".format(n, status_text))
else:
print("Unknown argument.")
else:
print("The world hasn't be scanned (or it needs a rescan). Use \'scan\' to scan it.") | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def do_quit(self, arg):
print("Quitting.")
return True | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def do_EOF(self, arg):
print("Quitting.")
return True | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def complete_arg(self, text, possible_args):
l = []
for arg in possible_args:
if text in arg and arg.find(text) == 0:
l.append(arg + " ")
return l | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def complete_count_chunks(self, text, line, begidx, endidx):
possible_args = list(c.CHUNK_PROBLEMS_ARGS.values()) + ['all']
return self.complete_arg(text, possible_args) | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def complete_replace_chunks(self, text, line, begidx, endidx):
possible_args = list(c.CHUNK_PROBLEMS_ARGS.values()) + ['all']
return self.complete_arg(text, possible_args) | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def complete_remove_regions(self, text, line, begidx, endidx):
possible_args = list(c.REGION_PROBLEMS_ARGS.values()) + ['all']
return self.complete_arg(text, possible_args) | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def help_set(self):
print("\nSets some variables used for the scan in interactive mode. "
"If you run this command without an argument for a variable "
"you can see the current state of the variable. You can set:\n"
" verbose\n"
"If True prints a line per scanned region file instead of "
"showing a progress bar.\n"
" entity-limit\n"
"If a chunk has more than this number of entities it will be "
"added to the list of chunks with too many entities problem.\n"
" processes"
"Number of cores used while scanning the world.\n"
" workload\n"
"If you input a few worlds you can choose wich one will be "
"scanned using this command.\n") | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def help_scan(self):
print("\nScans the current world set or the region set.\n") | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def help_remove_entities(self):
print("\nRemove all the entities in chunks that have more than entity-limit entities.")
print()
print("This chunks are the ones with status \'too many entities\'.\n") | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def help_replace_chunks(self):
print("\nReplaces bad chunks with the given status using the backups directories.")
print()
print("Exampe: \"replace_chunks corrupted\"")
print()
print("this will replace the corrupted chunks with the given backups.")
print()
print("Possible status are: {0}\n".format(self.possible_chunk_args_text))
print()
print("Note: after replacing any chunks you have to rescan the world.\n") | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def help_remove_regions(self):
print("\nRemoves regions with the given status.")
print()
print("Example: \'remove_regions too-small\'")
print()
print("this will remove the region files with status \'too-small\'.")
print()
print("Possible status are: {0}".format(self.possible_region_args_text))
print()
print("Note: after removing any regions you have to rescan the world.\n") | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def help_summary(self):
print("\nPrints a summary of all the problems found in the current workload.\n") | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def help_EOF(self):
print("\nQuits interactive mode, exits region-fixer. Same as \'quit\' and \'exit\' commands\n") | Fenixin/Minecraft-Region-Fixer | [
476,
94,
476,
14,
1302184845
] |
def get_source_ip(my_request):
try:
# First check for an X-Forwarded-For header provided by a proxy / router e.g. on Heroku
source_ip = my_request.headers['X-Forwarded-For']
except KeyError:
try:
# First check for an X-Forwarded-For header provided by a proxy / router e.g. on Heroku
source_ip = my_request.headers['X-Client-IP']
except KeyError:
# If that header is not present, attempt to get the Source IP address from the request itself
source_ip = my_request.remote_addr
g.source_ip = source_ip
return source_ip | open-ods/open-ods | [
3,
2,
3,
18,
1446219918
] |
def get_request_id(my_request):
try:
request_id = my_request.headers['X-Request-Id']
except KeyError:
request_id = str(uuid.uuid4())
g.request_id = request_id
return request_id | open-ods/open-ods | [
3,
2,
3,
18,
1446219918
] |
def print_(arg):
"""
Args:
arg: la valeur à afficher
Returns: la valeur à afficher ainsi qu'une série de '-', afin d'espacer l'affichage
"""
print(arg)
print("-------------------------------------") | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def __init__(self, nom_table):
super().__init__()
self.nom_table = nom_table | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def __init__(self, y, site_web, identifiant, mdp, categorie, objet, nom_table):
self.position = y
self.objet = objet
self.nom_site = site_web
self.nom_mdp = mdp
self.nom_cat = categorie
self.nom_table = nom_table
self.ligne = QtWidgets.QHBoxLayout()
self.site_web =QtWidgets.QLabel()
self.site_web.setAlignment(QtCore.Qt.AlignCenter)
self.site_web.setObjectName("site_web")
self.site_web.setText(site_web)
self.ligne.addWidget(self.site_web)
self.identifiant = LineEditWithFocusOut(self.nom_table)
self.identifiant.setAlignment(QtCore.Qt.AlignCenter)
self.identifiant.setObjectName('identifiant')
self.identifiant.id = y
if identifiant is None or identifiant == "":
self.identifiant.setPlaceholderText("Ajouter un pseudo")
else:
self.identifiant.setText(identifiant)
self.ligne.addWidget(self.identifiant)
self.mdp = QtWidgets.QComboBox()
self.mdp.setObjectName("mdp")
self.afficher_combo_pwd() # affichage des éléments de la combobox en fonction de la bdd
self.ligne.addWidget(self.mdp)
self.categorie = QtWidgets.QComboBox()
self.categorie.setObjectName("categorie")
self.afficher_combo_cat() # affichage des éléments de la combobox en fonction de la bdd
self.ligne.addWidget(self.categorie)
self.ligne.setStretch(0, 2)
self.ligne.setStretch(1, 2)
self.ligne.setStretch(2, 2)
self.ligne.setStretch(3, 2)
self.categorie.currentIndexChanged.connect(self.changement_cat)
self.mdp.currentIndexChanged.connect(self.changement_pwd) | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def changement_pwd(self):
requete ="SELECT mdp FROM sites_reconnus_"+self.nom_table+" WHERE rowid=?"
ancien_mdp = toliste(bdd_select(requete, (self.position+1,)))[0]
# On ajoute le site_web sous le mdp correspondant
requete= "UPDATE sites_reconnus_"+self.nom_table+" SET mdp=? WHERE rowid=?"
nouveau_mdp = self.mdp.currentText()
bdd_update(requete, (nouveau_mdp , self.position +1))
print("Mdp changée en"+ nouveau_mdp)
for k in range(len(self.objet.pwds)):
if(self.objet.pwds[k].nom == nouveau_mdp):
liste_label_name =[]
for element in self.objet.pwds[k].labels:
liste_label_name.append(element.text())
if(nouveau_mdp not in liste_label_name):
self.objet.pwds[k].label(self.site_web.text())
break
# On met à jour le groupBox de l'ancienn mdp
for k in range(len(self.objet.pwds)):
if(self.objet.pwds[k].nom == ancien_mdp):
for label in self.objet.pwds[k].labels:
label.deleteLater()
self.objet.pwds[k].labels = []
requete ="SELECT site_web FROM sites_reconnus_"+self.nom_table+" WHERE mdp=?"
sites_lies= toliste(bdd_select(requete, (ancien_mdp,)))
self.objet.pwds[k].affichage_sites_lies(sites_lies)
for pwd in self.objet.pwds:
if(pwd.nom == ancien_mdp):
pwd.update_color_groupBox()
elif(pwd.nom == nouveau_mdp):
pwd.update_color_groupBox() | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def afficher_combo_pwd(self):
requete= "SELECT mdp FROM mdps_"+self.nom_table+""
tab = bdd_select(requete)
result = []
for k in range(len(tab)):
result.append(tab[k][0])
self.mdp.addItem(self.nom_mdp)
for pwd in result:
if pwd and pwd != self.nom_mdp:
self.mdp.addItem(pwd)
if(self.nom_mdp and self.nom_mdp != ""):
self.mdp.addItem("") | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def __init__(self, position, nom, sites_lies, objet, nom_table):
self.position = position
self.nom = nom
self.sites_lies = sites_lies
self.objet = objet
self.nom_table =nom_table
self.ligne = QtWidgets.QHBoxLayout()
self.pushButton = QtWidgets.QPushButton()
self.pushButton.setMinimumSize(QtCore.QSize(24, 24))
self.groupBox = QtWidgets.QGroupBox()
self.colorHEX = "#757575"
self.labels = [] # contiendra la liste des labels (noms des sites liés)
self.groupBox.setGeometry(QtCore.QRect(20, 50, 91, 50))
font = QtGui.QFont()
font.setPointSize(11)
self.groupBox.setFont(font)
self.groupBox.setObjectName("groupBox")
self.verticalLayout_groupBox = QtWidgets.QVBoxLayout(self.groupBox)
self.verticalLayout_groupBox.setObjectName("verticalLayout_groupBox")
self.ligne.addWidget(self.groupBox)
self.ligne.addWidget(self.pushButton)
self.ligne.setStretch(0, 20)
self.ligne.setStretch(1, 1)
self.affichage_sites_lies(sites_lies)
# Evènement
self.pushButton.clicked.connect(self.msgbox) | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def msgbtn(self, buttonClicked):
if(buttonClicked.text() == "Oui"):
self.suppression() | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def affichage_sites_lies(self, site_lies):
pass | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def __init__(self, position, nom, sites_lies, objet, nom_table):
# On exécute Ligne.__init__()
super().__init__(position, nom, sites_lies, objet, nom_table)
# On ajoute d'autres attributs/propriétés
self.ligne.setObjectName("ligne_categorie")
self.groupBox.setObjectName("groupBox_cat")
self.groupBox.setTitle(nom)
self.pushButton.setObjectName("pushButton_cat") | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def affichage_sites_lies(self, sites_lies):
for site in sites_lies:
label = QtWidgets.QLabel() | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def suppression_bdd(self):
requete = "DELETE FROM categories_"+self.nom_table +" WHERE nom_categorie=?"
bdd_delete(requete, (self.nom,))
print("Categorie supprimée: "+ self.nom) | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def ajout_combobox(self):
for k in range(len(self.objet.sites)):
self.objet.sites[k].categorie.addItem(self.nom) | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def __init__(self, position, nom, sites_lies, objet, nom_table):
super().__init__(position, nom, sites_lies, objet, nom_table)
self.ligne.setObjectName("ligne_pwd")
self.groupBox.setObjectName("groupBox_pwd")
self.groupBox.setTitle(nom)
self.pushButton.setObjectName("pushButton_pwd")
# On modifie la couleur de la groupBox_pwd
self.update_color_groupBox() | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def affichage_sites_lies(self, sites_lies):
for site in sites_lies:
self.label(site) | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def create_text_label(self, couleur, site):
texte = "<font size='5' font-style='' color="+couleur+">•</font> "
for lettre in site:
texte += lettre
return(texte) | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def update_color_groupBox(self):
colorGroupBox = self.colorHEX
if(self.labels != []):
if(self.labels[0].colorHEX != "#fff"):
colorGroupBox = self.labels[0].colorHEX
b = 1
for label in self.labels:
if(label.colorHEX != colorGroupBox):
b=0
if(not b):
colorGroupBox = "#757575"
else:
colorGroupBox = "#757575" | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def getColor_label(self, site):
"""En paramètre le site, retourne un tableau de couleur [RGB, HEX] (associée à la categorie
éventuellement assignées
"""
requete = "SELECT categorie FROM sites_reconnus_"+self.nom_table+" WHERE site_web=?"
categorie = toliste(bdd_select(requete, (site,)))[0]
tab = ["rgb(255,255,255)","#fff"]
for k in range(len(self.objet.cats)):
if(self.objet.cats[k].nom == categorie):
tab[0] = self.objet.cats[k].colorRGB
tab[1] = self.objet.cats[k].colorHEX
return(tab) | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def suppression_affichage(self):
# suppression combobox
for k in range(len(self.objet.sites)):
if self.objet.sites[k].mdp.currentText() == self.nom:
# si le mdp supprimée était celui du site, alors on change le change en le choix vide:""
if self.objet.sites[k].mdp.findText("") == -1:
# si il n'y a pas le choix vide "", on l'ajoute
self.objet.sites[k].mdp.addItem("")
self.objet.sites[k].mdp.setCurrentIndex(self.objet.sites[k].mdp.findText(""))
index = self.objet.sites[k].mdp.findText(self.nom)
self.objet.sites[k].mdp.removeItem(index)
# destruction des layouts dans la scroll_area
self.objet.scrollAreaWidgetContents_pwd.deleteLater()
# on vide les attributs
self.objet.pwds = []
# On en recrée un vide
self.objet.scrollAreaWidgetContents_pwd = QtWidgets.QWidget()
self.objet.scrollAreaWidgetContents_pwd.setGeometry(QtCore.QRect(0, 0, 177, 767))
self.objet.scrollAreaWidgetContents_pwd.setObjectName("scrollAreaWidgetContents_cat")
self.objet.verticalLayout_2 = QtWidgets.QVBoxLayout(self.objet.scrollAreaWidgetContents_pwd)
self.objet.verticalLayout_2.setObjectName("verticalLayout_3")
self.objet.scrollArea_pwd.setWidget(self.objet.scrollAreaWidgetContents_pwd)
# on relance la méthode d'affichage des mdps_"+self.nom_table+"
self.objet.afficher_pwds() | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def __init__(self, fenetre):
self.setupUi(fenetre)
self.ajouter_cat.setPlaceholderText("Ajouter une catégorie")
self.ajouter_pwd.setPlaceholderText("Ajouter un mot de passe")
self.lineEdit_ajout_site.setPlaceholderText("Ajouter un site web")
# Evènements
self.ajouter_cat.returnPressed.connect(self.check_if_exist_cat)
self.ajouter_pwd.returnPressed.connect(self.check_if_exist_pwd)
self.lineEdit_ajout_site.returnPressed.connect(self.check_new_site)
self.pushButton_ajout_site.clicked.connect(self.check_new_site)
self.sites = []
self.cats = []
self.pwds = [] | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def setupMenu(self):
self.aide_url = "https://github.com/MindPass/Code/wiki/Aide"
self.apropos_url ="https://github.com/MindPass/Code"
self.actionObtenir_de_l_aide.triggered.connect(self.ouvrirAide)
self.actionA_propos_de_MindPass.triggered.connect(self.ouvrirApropos)
"""
self.actionMode_deux_lettres.triggered.connect(self.check_deux_lettres)
self.actionMode_complet.triggered.connect(self.check_complet)
self.menuAffichage()
""" | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def check_deux_lettres(self):
self.actionMode_deux_lettres.setChecked(True)
self.actionMode_complet.setChecked(False)
self.menuAffichage() | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def menuAffichage(self):
if(self.actionMode_deux_lettres.isChecked()):
self.affichage_deux_lettres()
else:
self.affichage_complet() | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def affichage_complet(self):
for pwd in self.pwds:
pwd.update_title(pwd.nom)
for site in self.sites:
site.update_pwd_combobox(1) | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def ouvrirAide(self):
self.openURL(self.aide_url) | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def openURL(self, given_url):
url = QtCore.QUrl(given_url)
if not QtGui.QDesktopServices.openUrl(url):
QtGui.QMessageBox.warning(self, "Open Url", "Could not open url") | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def actualiser_couleur(self):
nb_cat = len(self.cats)
for i in range(nb_cat):
self.cats[i].setColor(i, nb_cat) | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def ajouter_categorie(self):
requete ="INSERT INTO categories_"+self.nom_table +" (nom_categorie) VALUES(?)"
bdd_insert(requete, (self.ajouter_cat.displayText(),))
#ajout dans les combobox
for k in range(len(self.sites)):
self.sites[k].categorie.addItem(self.ajouter_cat.displayText())
# ajout de la catégorie dans la scrollArea Categories
self.ajouter_ligne_categorie(len(self.cats), self.ajouter_cat.displayText())
print("Catégorie ajoutée : "+ str(self.ajouter_cat.displayText()))
self.ajouter_cat.setText("") | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def check_if_exist_pwd(self):
"""
Vérifier que le pwd en question n'est pas déjà dans la base de donnée
"""
if self.ajouter_pwd.displayText() != "":
requete = "SELECT mdp FROM mdps_"+self.nom_table+" WHERE mdp=?"
pwds_table = bdd_select(requete, (self.ajouter_pwd.displayText(),))
conditions = not pwds_table or pwds_table[0][0] != self.ajouter_pwd.displayText()
if conditions:
self.ajouter_password() | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def ajouter_password(self):
requete = "INSERT INTO mdps_"+self.nom_table+" (mdp) VALUES(?)"
bdd_insert(requete, (self.ajouter_pwd.displayText(),))
#ajout dans les combobox
for k in range(len(self.sites)):
self.sites[k].mdp.addItem(self.ajouter_pwd.displayText())
# ajout dans la ScrollArea Passwords
self.ajouter_ligne_pwd(len(self.pwds), self.ajouter_pwd.displayText())
print("Password ajoutée : " + self.ajouter_pwd.displayText())
self.ajouter_pwd.setText("") | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def actualiser_couleur_pwd(self):
# destruction des layouts dans la scroll_area
self.scrollAreaWidgetContents_pwd.deleteLater()
# on vide les attributs
self.pwds = []
# On en recrée un vide
self.scrollAreaWidgetContents_pwd = QtWidgets.QWidget()
self.scrollAreaWidgetContents_pwd.setGeometry(QtCore.QRect(0, 0, 177, 767))
self.scrollAreaWidgetContents_pwd.setObjectName("scrollAreaWidgetContents_cat")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents_pwd)
self.verticalLayout_2.setObjectName("verticalLayout_3")
self.scrollArea_pwd.setWidget(self.scrollAreaWidgetContents_pwd)
# on relance la méthode d'affichage des mdps_"+self.nom_table+"
self.afficher_pwds() | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def check_new_site(self):
requete = "SELECT site_web FROM sites_reconnus_"+self.nom_table+""
sites_web = toliste(bdd_select(requete))
if(self.lineEdit_ajout_site.text() not in sites_web and self.lineEdit_ajout_site.text() != ""):
requete = "INSERT INTO sites_reconnus_"+self.nom_table+" VALUES(?,?,?,?,?)"
valeurs =("",self.lineEdit_ajout_site.text(),"", "", "")
bdd_insert(requete, valeurs)
self.sites.append(LigneSite(len(self.sites), self.lineEdit_ajout_site.text(), "", "", "", self, self.nom_table))
self.verticalLayout.addLayout(self.sites[len(self.sites)-1].ligne)
self.lineEdit_ajout_site.setText("") | MindPass/Code | [
4,
1,
4,
1,
1450227435
] |
def __init__(self, jds, mags, magerrs, splitup=True, deltat=0.000001, sort=True, stab=False,
stabext=300.0, stabgap = 30.0, stabstep = 5.0, stabmagerr = -2.0, stabrampsize = 0, stabrampfact = 1.0):
"""
Constructor
Always leave splitup and sort on True ! Only if you know that you are already
sorted you can skip them.
You cannot specify a mask, I do this myself. (could be done in principle). | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def splitup(self):
"""
TO WRITE !!!
We avoid that two points get the same jds...
Note that this might change the order of the jds,
but only of very close ones, so one day it would be ok to leave the mags as they are. | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def sort(self):
"""
Absolutely mandatory, called in the constructor.
"""
sortedindices = np.argsort(self.jds)
self.jds = self.jds[sortedindices]
self.mags = self.mags[sortedindices]
self.magerrs = self.magerrs[sortedindices]
self.mask = self.mask[sortedindices]
self.validate() | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def validate(self):
"""
We check that the datapoint jds are increasing strictly :
"""
first = self.jds[:-1]
second = self.jds[1:]
if not np.alltrue(np.less(first,second)): # Not less_equal ! Strictly increasing !
raise RuntimeError, "These datapoints don't have strcitly increasing jds !" | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def rmstab(self):
"""
Deletes all stabilization points
"""
self.jds = self.jds[self.mask]
self.mags = self.mags[self.mask]
self.magerrs = self.magerrs[self.mask]
self.mask = np.ones(len(self.jds), dtype=np.bool) | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def putstab(self):
"""
Runs only if stab is True.
I will :
add datapoints (new jds, new mags, new magerrs)
modify the mask = False for all those new datapoints.
"""
if self.stab == True: | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def calcstabmagerr(self):
"""
Computes the mag err of the stabilisation points.
"""
if self.stabmagerr >= 0.0:
return self.stabmagerr
else:
return - self.stabmagerr * np.median(self.magerrs) | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def addgappts(self):
"""
We add stabilization points with low weights into the season gaps
to avoid those big excursions of the splines.
This is done by a linear interpolation across the gaps.
""" | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def addextpts(self):
"""
We add stabilization points at both extrema of the lightcurves
This is done by "repeating" the extremal points, and a ramp in the magerrs
""" | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def getmaskbounds(self):
"""
Returns the upper and lower bounds of the regions containing stabilization points.
This is used when placing knots, so to put fewer knots in these regions.
Crazy stuff...
""" | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def ntrue(self):
"""
Returns the number of real datapoints (skipping stabilization points)
"""
return np.sum(self.mask) | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def __init__(self, datapoints, t = None, c = None, k = 3, bokeps = 2.0, boktests = 5, bokwindow = None, plotcolour="black"):
"""
t : all the knots (not only internal ones !)
c : corresponding coeffs
k : degree : default = cubic splines k=3 -> "order = 4" ???
whatever ... 3 means that you can differentiate twice at the knots. | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def __str__(self):
"""
Returns a string with:
* degree
* knot placement
* number of intervals | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def copy(self):
"""
Returns a "deep copy" of the spline.
"""
return pythoncopy.deepcopy(self) | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def shifttime(self, timeshift):
"""
Hard-shifts your spline along the time axis.
By "hard-shift", I mean that unlike for a lightcurve, the spline will not know that it was shifted !
It's up to you to be sure that you want to move it.
We shift both the datapoints and the knots.
"""
self.t += timeshift
self.datapoints.jds += timeshift | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def updatedp(self, newdatapoints, dpmethod="stretch"):
""" | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def uniknots(self, nint, n=True):
"""
Uniform distribution of internal knots across the datapoints (including any stab points).
We don't make a difference between stab and real points. | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def resetc(self):
"""
Sets all coeffs to 0.0 -- if you want to start again your fit, keeping the knot positions.
"""
self.c = np.zeros(len(self.t)) | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
def reset(self):
"""
Calls uniknots, i.e. resets both coeffs and knot positions, keeping the same number of knots.
"""
self.uniknots(self.getnint() ,n=True) | COSMOGRAIL/PyCS | [
4,
4,
4,
14,
1454429374
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.