hexsha stringlengths 40 40 | size int64 5 2.06M | ext stringclasses 10 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 248 | max_stars_repo_name stringlengths 5 125 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 248 | max_issues_repo_name stringlengths 5 125 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 248 | max_forks_repo_name stringlengths 5 125 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 2.06M | avg_line_length float64 1 1.02M | max_line_length int64 3 1.03M | alphanum_fraction float64 0 1 | count_classes int64 0 1.6M | score_classes float64 0 1 | count_generators int64 0 651k | score_generators float64 0 1 | count_decorators int64 0 990k | score_decorators float64 0 1 | count_async_functions int64 0 235k | score_async_functions float64 0 1 | count_documentation int64 0 1.04M | score_documentation float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ba247ac7c75341abffe46b2c862326f4b1bcfefb | 275 | py | Python | COPS.py | abphilip-codes/Codechef_Practice | 21fd52e03df8a0f72a08b0e2a0b48dbd508aac95 | [
"MIT"
] | 2 | 2021-07-26T03:32:24.000Z | 2021-07-31T02:32:14.000Z | COPS.py | abphilip-codes/Codechef_Practice | 21fd52e03df8a0f72a08b0e2a0b48dbd508aac95 | [
"MIT"
] | null | null | null | COPS.py | abphilip-codes/Codechef_Practice | 21fd52e03df8a0f72a08b0e2a0b48dbd508aac95 | [
"MIT"
] | 1 | 2021-07-14T17:45:33.000Z | 2021-07-14T17:45:33.000Z | # https://www.codechef.com/problems/COPS
for T in range(int(input())):
M,x,y=map(int,input().split())
m,a = list(map(int,input().split())),list(range(1,101))
for i in m:
for j in range(i-x*y,i+1+x*y):
if(j in a): a.remove(j)
print(len(a)) | 30.555556 | 59 | 0.552727 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 40 | 0.145455 |
ba25057c6b3ececb19513f93d3dbe767448d9d9b | 458 | py | Python | Python Fundamentals/Regular Expressions/More Exercise/Task02_03.py | IvanTodorovBG/SoftUni | 7b667f6905d9f695ab1484efbb02b6715f6d569e | [
"MIT"
] | 1 | 2022-03-16T10:23:04.000Z | 2022-03-16T10:23:04.000Z | Python Fundamentals/Regular Expressions/More Exercise/Task02_03.py | IvanTodorovBG/SoftUni | 7b667f6905d9f695ab1484efbb02b6715f6d569e | [
"MIT"
] | null | null | null | Python Fundamentals/Regular Expressions/More Exercise/Task02_03.py | IvanTodorovBG/SoftUni | 7b667f6905d9f695ab1484efbb02b6715f6d569e | [
"MIT"
] | null | null | null | import re
data = input()
pattern = r"%([A-Z][a-z]+)%([^|$%.]+)?<(\w+)>([^|$%.]+)?\|(\d+)\|([^|$%.0-9]+)?([0-9]+(\.[0-9]+)?)\$"
total_income = 0
while data != "end of shift":
for match in re.finditer(pattern, data):
print(f"{match.group(1)}: {match.group(3)} - {int(match.group(5)) * float(match.group(7)):.2f}")
total_income += int(match.group(5)) * float(match.group(7))
data = input()
print(f"Total income: {total_income:.2f}")
| 30.533333 | 104 | 0.528384 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 229 | 0.5 |
ba26e1fd3bf707b269e72c095f6fc249a64b024e | 319 | py | Python | sky/migrations/0008_remove_news_label.py | eethan1/IMnight2018_Backend | 39780f737e57763fdfb171c4687a375d3c5a4bb0 | [
"Apache-2.0"
] | null | null | null | sky/migrations/0008_remove_news_label.py | eethan1/IMnight2018_Backend | 39780f737e57763fdfb171c4687a375d3c5a4bb0 | [
"Apache-2.0"
] | null | null | null | sky/migrations/0008_remove_news_label.py | eethan1/IMnight2018_Backend | 39780f737e57763fdfb171c4687a375d3c5a4bb0 | [
"Apache-2.0"
] | 4 | 2018-01-27T06:01:41.000Z | 2018-02-21T12:18:35.000Z | # Generated by Django 2.0 on 2018-02-24 11:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('sky', '0007_auto_20180224_1120'),
]
operations = [
migrations.RemoveField(
model_name='news',
name='label',
),
]
| 17.722222 | 45 | 0.583072 | 236 | 0.739812 | 0 | 0 | 0 | 0 | 0 | 0 | 88 | 0.275862 |
ba2734de58f77351686c44deeb925ba874e74299 | 8,884 | py | Python | mealpy/utils/visualize/linechart.py | thieu1995/mealpy | 7694c18e1514909f6727163a3e0899dd36822867 | [
"MIT"
] | 162 | 2020-08-31T10:13:06.000Z | 2022-03-31T09:38:19.000Z | mealpy/utils/visualize/linechart.py | thieu1995/mealpy | 7694c18e1514909f6727163a3e0899dd36822867 | [
"MIT"
] | 51 | 2020-09-13T10:46:31.000Z | 2022-03-30T06:12:08.000Z | mealpy/utils/visualize/linechart.py | thieu1995/mealpy | 7694c18e1514909f6727163a3e0899dd36822867 | [
"MIT"
] | 58 | 2020-09-12T13:29:18.000Z | 2022-03-31T09:38:21.000Z | #!/usr/bin/env python
# ------------------------------------------------------------------------------------------------------%
# Created by "Thieu" at 17:12, 09/07/2021 %
# %
# Email: nguyenthieu2102@gmail.com %
# Homepage: https://www.researchgate.net/profile/Nguyen_Thieu2 %
# Github: https://github.com/thieu1995 %
# ------------------------------------------------------------------------------------------------------%
import platform
from matplotlib import pyplot as plt
from numpy import arange
from pathlib import Path
import re
LIST_LINESTYLES = [
'-', # solid line style
'--', # dashed line style
'-.', # dash-dot line style
':', # point marker
's', # square marker
'*', # star marker
'p', # pentagon marker
'+', # plus marker
'x', # x marker
'd', # thin diamond marker
]
LIST_COLORS = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728',
'#9467bd', '#8c564b', '#e377c2', '#7f7f7f',
'#bcbd22', '#17becf']
def __clean_filename__(filename):
chars_to_remove = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", ":", ",", "<", ">", ";", "+", "|"]
regular_expression = '[' + re.escape(''.join(chars_to_remove)) + ']'
temp = filename.encode("ascii", "ignore")
fname = temp.decode() # Removed all non-ascii characters
fname = re.sub(regular_expression, '', fname) # Removed all special characters
fname.replace("_", "-") # Replaced _ by -
return fname
def __check_filepath__(filename):
filename.replace("\\", "/") # For better handling the parent folder
if "/" in filename:
list_names = filename.split("/")[:-1] # Remove last element because it is filename
filepath = "/".join(list_names)
print(f"Fucking for real? {filepath}")
Path(filepath).mkdir(parents=True, exist_ok=True)
return filename
def _draw_line_(data=None, title=None, linestyle='-', color='b', x_label="#Iteration", y_label="Function Value",
filename=None, exts=(".png", ".pdf"), verbose=True):
x = arange(0, len(data))
y = data
plt.title(title)
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.plot(x, y, linestyle=linestyle, color=color,)
plt.legend() # show a legend on the plot
if filename is not None:
filepath = __check_filepath__(__clean_filename__(filename))
for idx, ext in enumerate(exts):
plt.savefig(f"{filepath}{ext}", bbox_inches='tight')
if platform.system() != "Linux" and verbose:
plt.show()
plt.close()
def _draw_multi_line_(data=None, title=None, list_legends=None, list_styles=None, list_colors=None,
x_label="#Iteration", y_label="Function Value", filename=None, exts=(".png", ".pdf"), verbose=True):
x = arange(0, len(data[0]))
for idx, y in enumerate(data):
plt.plot(x, y, label=list_legends[idx], markerfacecolor=list_colors[idx], linestyle=list_styles[idx])
plt.title(title)
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.legend() # show a legend on the plot
if filename is not None:
filepath = __check_filepath__(__clean_filename__(filename))
for idx, ext in enumerate(exts):
plt.savefig(f"{filepath}{ext}", bbox_inches='tight')
if platform.system() != "Linux" and verbose:
plt.show()
plt.close()
def _draw_multi_line_in_same_figure_(data=None, title=None, list_legends=None, list_styles=None, list_colors=None,
x_label="#Iteration", y_label="Objective", filename=None, exts=(".png", ".pdf"), verbose=True):
n_lines = len(data)
len_lines = len(data[0])
x = arange(0, len_lines)
if n_lines == 1:
fig, ax = plt.subplots()
if list_legends is None:
ax.plot(x, data[0])
else:
ax.plot(x, data[0], label=list_legends[0])
ax.set_title(title)
elif n_lines > 1:
fig, ax_list = plt.subplots(n_lines, sharex=True)
fig.suptitle(title)
for idx, ax in enumerate(ax_list):
if list_legends is None:
ax.plot(x, data[idx], markerfacecolor=list_colors[idx], linestyle=list_styles[idx])
else:
ax.plot(x, data[idx], label=list_legends[idx], markerfacecolor=list_colors[idx], linestyle=list_styles[idx])
ax.set_ylabel(f"Objective {idx + 1}")
if idx == (n_lines - 1):
ax.set_xlabel(x_label)
if filename is not None:
filepath = __check_filepath__(__clean_filename__(filename))
for idx, ext in enumerate(exts):
plt.savefig(f"{filepath}{ext}", bbox_inches='tight')
if platform.system() != "Linux" and verbose:
plt.show()
plt.close()
def export_convergence_chart(data=None, title="Convergence Chart", linestyle='-', color='b', x_label="#Iteration",
y_label="Function Value", filename="convergence_chart", exts=(".png", ".pdf"), verbose=True):
_draw_line_(data, title=title, linestyle=linestyle, color=color, x_label=x_label, y_label=y_label,
filename=filename, exts=exts, verbose=verbose)
def export_explore_exploit_chart(data=None, title="Exploration vs Exploitation Percentages", list_legends=("Exploration %", "Exploitation %"),
list_styles=('-', '-'), list_colors=('blue', 'orange'), x_label="#Iteration", y_label="Percentage",
filename="explore_exploit_chart", exts=(".png", ".pdf"), verbose=True):
_draw_multi_line_(data=data, title=title, list_legends=list_legends, list_styles=list_styles, list_colors=list_colors,
x_label=x_label, y_label=y_label, filename=filename, exts=exts, verbose=verbose)
def export_diversity_chart(data=None, title='Diversity Measurement Chart', list_legends=None,
list_styles=None, list_colors=None, x_label="#Iteration", y_label="Diversity Measurement",
filename="diversity_chart", exts=(".png", ".pdf"), verbose=True):
if list_styles is None:
list_styles = LIST_LINESTYLES[:len(data)]
if list_colors is None:
list_colors = LIST_COLORS[:len(data)]
_draw_multi_line_(data=data, title=title, list_legends=list_legends, list_styles=list_styles, list_colors=list_colors,
x_label=x_label, y_label=y_label, filename=filename, exts=exts, verbose=verbose)
def export_objectives_chart(data=None, title="Objectives chart", list_legends=None, list_styles=None, list_colors=None,
x_label="#Iteration", y_label="Function Value", filename="Objective-chart", exts=(".png", ".pdf"), verbose=True):
if list_styles is None:
list_styles = LIST_LINESTYLES[:len(data)]
if list_colors is None:
list_colors = LIST_COLORS[:len(data)]
_draw_multi_line_in_same_figure_(data=data, title=title, list_legends=list_legends, list_styles=list_styles, list_colors=list_colors,
x_label=x_label, y_label=y_label, filename=filename, exts=exts, verbose=verbose)
def export_trajectory_chart(data=None, n_dimensions=1, title="Trajectory of some first agents after generations", list_legends=None,
list_styles=None, list_colors=None, x_label="#Iteration", y_label="X1",
filename="1d_trajectory", exts=(".png", ".pdf"), verbose=True):
if list_styles is None:
list_styles = LIST_LINESTYLES[:len(data)]
if list_colors is None:
list_colors = LIST_COLORS[:len(data)]
if n_dimensions == 1:
x = arange(0, len(data[0]))
for idx, y in enumerate(data):
plt.plot(x, y, label=list_legends[idx], markerfacecolor=list_colors[idx], linestyle=list_styles[idx])
elif n_dimensions == 2:
for idx, point in enumerate(data):
plt.plot(point[0], point[1], label=list_legends[idx], markerfacecolor=list_colors[idx], linestyle=list_styles[idx])
plt.title(title)
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.legend() # show a legend on the plot
if filename is not None:
filepath = __check_filepath__(__clean_filename__(filename))
for idx, ext in enumerate(exts):
plt.savefig(f"{filepath}{ext}", bbox_inches='tight')
if platform.system() != "Linux" and verbose:
plt.show()
plt.close()
| 44.199005 | 142 | 0.582058 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,183 | 0.245723 |
ba273db5f7c2ad5232a853fc86d336a611f90e78 | 1,109 | py | Python | graphs/functions/scores.py | CSI-BennettUniversity/Sample-Project-1 | 23197352372b7ad00a026683477b5a95a4178e35 | [
"MIT"
] | 5 | 2020-07-30T16:47:30.000Z | 2021-02-15T16:44:59.000Z | graphs/functions/scores.py | CSI-BennettUniversity/Sample-Project-1 | 23197352372b7ad00a026683477b5a95a4178e35 | [
"MIT"
] | 4 | 2021-06-04T23:42:41.000Z | 2021-09-11T03:17:12.000Z | graphs/functions/scores.py | CSI-BennettUniversity/Sample-Project-1 | 23197352372b7ad00a026683477b5a95a4178e35 | [
"MIT"
] | 7 | 2020-07-05T14:29:17.000Z | 2021-06-05T14:34:20.000Z | import json
from interactions.models import (
SelfAnswerGroup,
)
def update_dict_with_score(valid_dict: list) -> list:
""" Updates the dict (from single and multiple_result_view) with
the scores of each user present in the list, by calculating their
``answer_choice`` and multiplying them with corresponding
question factors. """
for dictionary in valid_dict:
answer_group = SelfAnswerGroup.objects.get(
pk=dictionary['answer_group_pk']
)
scores = answer_group.scores
dictionary.update({'score': scores})
return valid_dict
def update_percentage_deviation(valid_dict: list) -> list:
for dictionary in valid_dict:
if dictionary['master']:
focus = dictionary['score'] # type: dict
for dictionary in valid_dict:
score = dictionary['score']
deviation_dict = {}
for subclass in score:
deviation = abs(score[subclass]-focus[subclass])
deviation_dict.update({subclass: deviation})
dictionary.update({'deviation': deviation_dict})
return valid_dict
| 29.972973 | 69 | 0.671776 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 291 | 0.262399 |
ba2ae5c00bc2049ab803532fa3e9a36db8f45a24 | 288 | py | Python | authenticationApp/EmailHandler.py | George-Okumu/IReporter-Django | 5962984ce0069cdf048dbf91686377568a7cf55b | [
"MIT"
] | null | null | null | authenticationApp/EmailHandler.py | George-Okumu/IReporter-Django | 5962984ce0069cdf048dbf91686377568a7cf55b | [
"MIT"
] | 1 | 2021-10-06T20:15:11.000Z | 2021-10-06T20:15:11.000Z | authenticationApp/EmailHandler.py | George-Okumu/IReporter-Django | 5962984ce0069cdf048dbf91686377568a7cf55b | [
"MIT"
] | null | null | null | from django.core.mail import EmailMessage, message
class EmailHandlerClass:
@staticmethod
def sendEmail(data):
email = EmailMessage(subject=data['email_subject'], body=data['email_body'], to=[data['email_to']])
email.send()
# email.send()
| 32 | 107 | 0.638889 | 219 | 0.760417 | 0 | 0 | 190 | 0.659722 | 0 | 0 | 51 | 0.177083 |
ba2b10e7983f50e892222f03799fc1c092cbda9b | 495 | py | Python | checkdns.py | delcacho/DataSciencePlatform | c19ac4c1aba54bafc0fed05cc534bb447ab3b631 | [
"BSD-3-Clause"
] | null | null | null | checkdns.py | delcacho/DataSciencePlatform | c19ac4c1aba54bafc0fed05cc534bb447ab3b631 | [
"BSD-3-Clause"
] | null | null | null | checkdns.py | delcacho/DataSciencePlatform | c19ac4c1aba54bafc0fed05cc534bb447ab3b631 | [
"BSD-3-Clause"
] | null | null | null | from area53 import route53
from boto.route53.exception import DNSServerError
from kubernetes import client, config
from datetime import datetime
import socket
import time
# Ensure cluster is running
consec = 0
while consec < 10:
try:
ip = socket.gethostbyname("http://api.k8s.dev.bayescluster.com")
cpnsec += 1
print("Successful resolution! :)")
except Exception as e:
consec = 0
print(e)
print("Error in DNS lookup. Gonna sleep for a while...")
time.sleep(10)
| 23.571429 | 68 | 0.717172 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 140 | 0.282828 |
ba2b2f46854a6061db7ab4dc16a1519a9222534e | 2,339 | py | Python | config/urls.py | ISI-MIP/isimip | c2a78c727337e38f3695031e00afd607da7d6dcb | [
"MIT"
] | null | null | null | config/urls.py | ISI-MIP/isimip | c2a78c727337e38f3695031e00afd607da7d6dcb | [
"MIT"
] | null | null | null | config/urls.py | ISI-MIP/isimip | c2a78c727337e38f3695031e00afd607da7d6dcb | [
"MIT"
] | null | null | null | from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views import defaults as default_views
from wagtail.admin import urls as wagtailadmin_urls
from wagtail.core import urls as wagtail_urls
from wagtail.documents import urls as wagtaildocs_urls
from wagtail.contrib.sitemaps.views import sitemap
from isi_mip.climatemodels import urls as climatemodels_urls
from isi_mip.invitation import urls as invitations_urls
from isi_mip.contrib.views import export_users
urlpatterns = [
url(r'^styleguide/', include("isi_mip.styleguide.urls", namespace="styleguide")),
url(r'^sitemap\.xml$', sitemap),
url(r'^admin/export/users/$', export_users, name='export_users'),
url(r'^admin/', include(admin.site.urls)),
url(r'^auth/', include('django.contrib.auth.urls')),
url(r'^blog/', include('blog.urls', namespace="blog")),
url(r'^cms/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
url(r'^models/', include(climatemodels_urls, namespace='climatemodels')),
url(r'^accounts/', include(invitations_urls, namespace='accounts')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Serve static and media files from development server
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# This allows the error pages to be debugged during development, just visit
# these url in browser to see how these error pages look like.
urlpatterns += [
url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception("Bad Request!")}),
url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception("Permission Denied")}),
url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception("Page not Found")}),
url(r'^500/$', default_views.server_error),
]
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
urlpatterns += [
url(r'', include(wagtail_urls)),
] | 41.767857 | 110 | 0.734929 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 575 | 0.245832 |
ba2c60c5a4a95231943f7de20a48e3d6d869c8ea | 31,645 | py | Python | eyesore/decision_graph/graph.py | twizmwazin/hacrs | 3c9386b0fa5f5ea6b93b2bc8b3c4eed6abceec6a | [
"BSD-2-Clause"
] | 2 | 2019-11-07T02:55:40.000Z | 2021-12-30T01:37:43.000Z | eyesore/decision_graph/graph.py | twizmwazin/hacrs | 3c9386b0fa5f5ea6b93b2bc8b3c4eed6abceec6a | [
"BSD-2-Clause"
] | null | null | null | eyesore/decision_graph/graph.py | twizmwazin/hacrs | 3c9386b0fa5f5ea6b93b2bc8b3c4eed6abceec6a | [
"BSD-2-Clause"
] | 2 | 2019-09-27T12:01:50.000Z | 2019-10-09T21:39:52.000Z | from collections import defaultdict, namedtuple
import re
class DiGraph(object):
"""Implementation of directed graph"""
# Stand for a cell in a dot node rendering
DotCellDescription = namedtuple("DotCellDescription",
["text", "attr"])
def __init__(self):
self._nodes = set()
self._edges = []
# N -> Nodes N2 with a edge (N -> N2)
self._nodes_succ = {}
# N -> Nodes N2 with a edge (N2 -> N)
self._nodes_pred = {}
self._node_attrs = {}
self._edge_attrs = {}
def __repr__(self):
out = []
for node in self._nodes:
out.append(str(node))
for src, dst in self._edges:
out.append("%s -> %s" % (src, dst))
return '\n'.join(out)
def nodes(self):
return self._nodes
def edges(self):
return self._edges
def merge(self, graph):
"""Merge the current graph with @graph
@graph: DiGraph instance
"""
for node in graph._nodes:
self.add_node(node)
for edge in graph._edges:
self.add_edge(*edge)
def __add__(self, graph):
"""Wrapper on `.merge`"""
self.merge(graph)
return self
def copy(self):
"""Copy the current graph instance"""
graph = self.__class__()
return graph + self
def __eq__(self, graph):
if not isinstance(graph, self.__class__):
return False
return all((self._nodes == graph.nodes(),
sorted(self._edges) == sorted(graph.edges())))
def add_node(self, node):
"""Add the node @node to the graph.
If the node was already present, return False.
Otherwise, return True
"""
if node in self._nodes:
return False
self._nodes.add(node)
self._nodes_succ[node] = []
self._nodes_pred[node] = []
return True
def del_node(self, node):
"""Delete the @node of the graph; Also delete every edge to/from this
@node"""
if node in self._nodes:
self._nodes.remove(node)
for pred in self.predecessors(node):
self.del_edge(pred, node)
for succ in self.successors(node):
self.del_edge(node, succ)
def add_edge(self, src, dst):
if not src in self._nodes:
self.add_node(src)
if not dst in self._nodes:
self.add_node(dst)
self._edges.append((src, dst))
self._nodes_succ[src].append(dst)
self._nodes_pred[dst].append(src)
def add_uniq_edge(self, src, dst):
"""Add an edge from @src to @dst if it doesn't already exist"""
if (src not in self._nodes_succ or
dst not in self._nodes_succ[src]):
self.add_edge(src, dst)
def del_edge(self, src, dst):
self._edges.remove((src, dst))
self._nodes_succ[src].remove(dst)
self._nodes_pred[dst].remove(src)
def predecessors_iter(self, node):
if not node in self._nodes_pred:
raise StopIteration
for n_pred in self._nodes_pred[node]:
yield n_pred
def predecessors(self, node):
return [x for x in self.predecessors_iter(node)]
def successors_iter(self, node):
if not node in self._nodes_succ:
raise StopIteration
for n_suc in self._nodes_succ[node]:
yield n_suc
def successors(self, node):
return [x for x in self.successors_iter(node)]
def leaves_iter(self):
for node in self._nodes:
if not self._nodes_succ[node]:
yield node
def leaves(self):
return [x for x in self.leaves_iter()]
def heads_iter(self):
for node in self._nodes:
if not self._nodes_pred[node]:
yield node
def heads(self):
return [x for x in self.heads_iter()]
def find_path(self, src, dst, cycles_count=0, done=None):
if done is None:
done = {}
if dst in done and done[dst] > cycles_count:
return [[]]
if src == dst:
return [[src]]
out = []
for node in self.predecessors(dst):
done_n = dict(done)
done_n[dst] = done_n.get(dst, 0) + 1
for path in self.find_path(src, node, cycles_count, done_n):
if path and path[0] == src:
out.append(path + [dst])
return out
def nodeid(self, node):
"""
Returns uniq id for a @node
@node: a node of the graph
"""
return hash(node) & 0xFFFFFFFFFFFFFFFF
def node2lines(self, node):
"""
Returns an iterator on cells of the dot @node.
A DotCellDescription or a list of DotCellDescription are accepted
@node: a node of the graph
"""
yield self.DotCellDescription(text=str(node), attr={})
def node_attr(self, node):
"""
Returns a dictionary of the @node's attributes
@node: a node of the graph
"""
return {}
def edge_attr(self, src, dst):
"""
Return a dictionary of attributes for the edge between @src and @dst
@src: the source node of the edge
@dst: the destination node of the edge
"""
return {}
@staticmethod
def _fix_chars(token):
return "&#%04d;" % ord(token.group())
@staticmethod
def _attr2str(default_attr, attr):
return ' '.join('%s="%s"' % (name, value)
for name, value in
dict(default_attr,
**attr).iteritems())
def dot(self):
"""Render dot graph with HTML"""
escape_chars = re.compile('[' + re.escape('{}') + '&|<>' + ']')
td_attr = {'align': 'left'}
nodes_attr = {'shape': 'Mrecord',
'fontname': 'Courier New'}
out = ["digraph asm_graph {"]
# Generate basic nodes
out_nodes = []
for node in self.nodes():
node_id = self.nodeid(node)
out_node = '%s [\n' % node_id
out_node += self._attr2str(nodes_attr, self.node_attr(node))
out_node += 'label =<<table border="0" cellborder="0" cellpadding="3">'
node_html_lines = []
for lineDesc in self.node2lines(node):
out_render = ""
if isinstance(lineDesc, self.DotCellDescription):
lineDesc = [lineDesc]
for col in lineDesc:
out_render += "<td %s>%s</td>" % (
self._attr2str(td_attr, col.attr),
escape_chars.sub(self._fix_chars, str(col.text)))
node_html_lines.append(out_render)
node_html_lines = ('<tr>' +
('</tr><tr>').join(node_html_lines) +
'</tr>')
out_node += node_html_lines + "</table>> ];"
out_nodes.append(out_node)
out += out_nodes
# Generate links
for src, dst in self.edges():
attrs = self.edge_attr(src, dst)
attrs = ' '.join('%s="%s"' % (name, value)
for name, value in attrs.iteritems())
out.append('%s -> %s' % (self.nodeid(src), self.nodeid(dst)) +
'[' + attrs + '];')
out.append("}")
return '\n'.join(out)
@staticmethod
def _reachable_nodes(head, next_cb):
"""Generic algorithm to compute all nodes reachable from/to node
@head"""
todo = {head}
reachable = set()
while todo:
node = todo.pop()
if node in reachable:
continue
reachable.add(node)
yield node
for next_node in next_cb(node):
todo.add(next_node)
def reachable_sons(self, head):
"""Compute all nodes reachable from node @head. Each son is an
immediate successor of an arbitrary, already yielded son of @head"""
return self._reachable_nodes(head, self.successors_iter)
def reachable_parents(self, leaf):
"""Compute all parents of node @leaf. Each parent is an immediate
predecessor of an arbitrary, already yielded parent of @leaf"""
return self._reachable_nodes(leaf, self.predecessors_iter)
@staticmethod
def _compute_generic_dominators(head, reachable_cb, prev_cb, next_cb):
"""Generic algorithm to compute either the dominators or postdominators
of the graph.
@head: the head/leaf of the graph
@reachable_cb: sons/parents of the head/leaf
@prev_cb: return predecessors/succesors of a node
@next_cb: return succesors/predecessors of a node
"""
nodes = set(reachable_cb(head))
dominators = {}
for node in nodes:
dominators[node] = set(nodes)
dominators[head] = set([head])
todo = set(nodes)
while todo:
node = todo.pop()
# Heads state must not be changed
if node == head:
continue
# Compute intersection of all predecessors'dominators
new_dom = None
for pred in prev_cb(node):
if not pred in nodes:
continue
if new_dom is None:
new_dom = set(dominators[pred])
new_dom.intersection_update(dominators[pred])
# We are not a head to we have at least one dominator
assert(new_dom is not None)
new_dom.update(set([node]))
# If intersection has changed, add sons to the todo list
if new_dom == dominators[node]:
continue
dominators[node] = new_dom
for succ in next_cb(node):
todo.add(succ)
return dominators
def compute_dominators(self, head):
"""Compute the dominators of the graph"""
return self._compute_generic_dominators(head,
self.reachable_sons,
self.predecessors_iter,
self.successors_iter)
def compute_postdominators(self, leaf):
"""Compute the postdominators of the graph"""
return self._compute_generic_dominators(leaf,
self.reachable_parents,
self.successors_iter,
self.predecessors_iter)
@staticmethod
def _walk_generic_dominator(node, gen_dominators, succ_cb):
"""Generic algorithm to return an iterator of the ordered list of
@node's dominators/post_dominator.
The function doesn't return the self reference in dominators.
@node: The start node
@gen_dominators: The dictionary containing at least node's
dominators/post_dominators
@succ_cb: return predecessors/succesors of a node
"""
# Init
done = set()
if node not in gen_dominators:
# We are in a branch which doesn't reach head
return
node_gen_dominators = set(gen_dominators[node])
todo = set([node])
# Avoid working on itself
node_gen_dominators.remove(node)
# For each level
while node_gen_dominators:
new_node = None
# Worklist pattern
while todo:
node = todo.pop()
if node in done:
continue
if node in node_gen_dominators:
new_node = node
break
# Avoid loops
done.add(node)
# Look for the next level
for pred in succ_cb(node):
todo.add(pred)
# Return the node; it's the next starting point
assert(new_node is not None)
yield new_node
node_gen_dominators.remove(new_node)
todo = set([new_node])
def walk_dominators(self, node, dominators):
"""Return an iterator of the ordered list of @node's dominators
The function doesn't return the self reference in dominators.
@node: The start node
@dominators: The dictionary containing at least node's dominators
"""
return self._walk_generic_dominator(node,
dominators,
self.predecessors_iter)
def walk_postdominators(self, node, postdominators):
"""Return an iterator of the ordered list of @node's postdominators
The function doesn't return the self reference in postdominators.
@node: The start node
@postdominators: The dictionary containing at least node's
postdominators
"""
return self._walk_generic_dominator(node,
postdominators,
self.successors_iter)
def compute_immediate_dominators(self, head):
"""Compute the immediate dominators of the graph"""
dominators = self.compute_dominators(head)
idoms = {}
for node in dominators:
for predecessor in self.walk_dominators(node, dominators):
if predecessor in dominators[node] and node != predecessor:
idoms[node] = predecessor
break
return idoms
def compute_dominance_frontier(self, head):
"""
Compute the dominance frontier of the graph
Source: Cooper, Keith D., Timothy J. Harvey, and Ken Kennedy.
"A simple, fast dominance algorithm."
Software Practice & Experience 4 (2001), p. 9
"""
idoms = self.compute_immediate_dominators(head)
frontier = {}
for node in idoms:
if self._nodes_pred[node] >= 2:
for predecessor in self.predecessors_iter(node):
runner = predecessor
if runner not in idoms:
continue
while runner != idoms[node]:
if runner not in frontier:
frontier[runner] = set()
frontier[runner].add(node)
runner = idoms[runner]
return frontier
def _walk_generic_first(self, head, flag, succ_cb):
"""
Generic algorithm to compute breadth or depth first search
for a node.
@head: the head of the graph
@flag: denotes if @todo is used as queue or stack
@succ_cb: returns a node's predecessors/successors
:return: next node
"""
todo = [head]
done = set()
while todo:
node = todo.pop(flag)
if node in done:
continue
done.add(node)
for succ in succ_cb(node):
todo.append(succ)
yield node
def walk_breadth_first_forward(self, head):
"""Performs a breadth first search on the graph from @head"""
return self._walk_generic_first(head, 0, self.successors_iter)
def walk_depth_first_forward(self, head):
"""Performs a depth first search on the graph from @head"""
return self._walk_generic_first(head, -1, self.successors_iter)
def walk_breadth_first_backward(self, head):
"""Performs a breadth first search on the reversed graph from @head"""
return self._walk_generic_first(head, 0, self.predecessors_iter)
def walk_depth_first_backward(self, head):
"""Performs a depth first search on the reversed graph from @head"""
return self._walk_generic_first(head, -1, self.predecessors_iter)
def has_loop(self):
"""Return True if the graph contains at least a cycle"""
todo = list(self.nodes())
# tested nodes
done = set()
# current DFS nodes
current = set()
while todo:
node = todo.pop()
if node in done:
continue
if node in current:
# DFS branch end
for succ in self.successors_iter(node):
if succ in current:
return True
# A node cannot be in current AND in done
current.remove(node)
done.add(node)
else:
# Launch DFS from node
todo.append(node)
current.add(node)
todo += self.successors(node)
return False
def compute_natural_loops(self, head):
"""
Computes all natural loops in the graph.
Source: Aho, Alfred V., Lam, Monica S., Sethi, R. and Jeffrey Ullman.
"Compilers: Principles, Techniques, & Tools, Second Edition"
Pearson/Addison Wesley (2007), Chapter 9.6.6
:param head: head of the graph
:return: yield a tuple of the form (back edge, loop body)
"""
for a, b in self.compute_back_edges(head):
body = self._compute_natural_loop_body(b, a)
yield ((b, a), body)
def compute_back_edges(self, head):
"""
Computes all back edges from a node to a
dominator in the graph.
:param head: head of graph
:return: yield a back edge
"""
dominators = self.compute_dominators(head)
# traverse graph
for node in self.walk_depth_first_forward(head):
for successor in self.successors_iter(node):
# check for a back edge to a dominator
if successor in dominators[node]:
edge = (node, successor)
yield edge
def _compute_natural_loop_body(self, head, leaf):
"""
Computes the body of a natural loop by a depth-first
search on the reversed control flow graph.
:param head: leaf of the loop
:param leaf: header of the loop
:return: set containing loop body
"""
todo = [leaf]
done = {head}
while todo:
node = todo.pop()
if node in done:
continue
done.add(node)
for predecessor in self.predecessors_iter(node):
todo.append(predecessor)
return done
def compute_strongly_connected_components(self):
"""
Partitions the graph into strongly connected components.
Iterative implementation of Gabow's path-based SCC algorithm.
Source: Gabow, Harold N.
"Path-based depth-first search for strong and biconnected components."
Information Processing Letters 74.3 (2000), pp. 109--110
The iterative implementation is inspired by Mark Dickinson's
code:
http://code.activestate.com/recipes/
578507-strongly-connected-components-of-a-directed-graph/
:return: yield a strongly connected component
"""
stack = []
boundaries = []
counter = len(self.nodes())
# init index with 0
index = {v: 0 for v in self.nodes()}
# state machine for worklist algorithm
VISIT, HANDLE_RECURSION, MERGE = 0, 1, 2
NodeState = namedtuple('NodeState', ['state', 'node'])
for node in self.nodes():
# next node if node was already visited
if index[node]:
continue
todo = [NodeState(VISIT, node)]
done = set()
while todo:
current = todo.pop()
if current.node in done:
continue
# node is unvisited
if current.state == VISIT:
stack.append(current.node)
index[current.node] = len(stack)
boundaries.append(index[current.node])
todo.append(NodeState(MERGE, current.node))
# follow successors
for successor in self.successors_iter(current.node):
todo.append(NodeState(HANDLE_RECURSION, successor))
# iterative handling of recursion algorithm
elif current.state == HANDLE_RECURSION:
# visit unvisited successor
if index[current.node] == 0:
todo.append(NodeState(VISIT, current.node))
else:
# contract cycle if necessary
while index[current.node] < boundaries[-1]:
boundaries.pop()
# merge strongly connected component
else:
if index[current.node] == boundaries[-1]:
boundaries.pop()
counter += 1
scc = set()
while index[current.node] <= len(stack):
popped = stack.pop()
index[popped] = counter
scc.add(popped)
done.add(current.node)
yield scc
class DiGraphSimplifier(object):
"""Wrapper on graph simplification passes.
Instance handle passes lists.
"""
def __init__(self):
self.passes = []
def enable_passes(self, passes):
"""Add @passes to passes to applied
@passes: sequence of function (DiGraphSimplifier, DiGraph) -> None
"""
self.passes += passes
def apply_simp(self, graph):
"""Apply enabled simplifications on graph @graph
@graph: DiGraph instance
"""
while True:
new_graph = graph.copy()
for simp_func in self.passes:
simp_func(self, new_graph)
if new_graph == graph:
break
graph = new_graph
return new_graph
def __call__(self, graph):
"""Wrapper on 'apply_simp'"""
return self.apply_simp(graph)
class MatchGraphJoker(object):
"""MatchGraphJoker are joker nodes of MatchGraph, that is to say nodes which
stand for any node. Restrictions can be added to jokers.
If j1, j2 and j3 are MatchGraphJoker, one can quickly build a matcher for
the pattern:
|
+----v----+
| (j1) |
+----+----+
|
+----v----+
| (j2) |<---+
+----+--+-+ |
| +------+
+----v----+
| (j3) |
+----+----+
|
v
Using:
>>> matcher = j1 >> j2 >> j3
>>> matcher += j2 >> j2
Or:
>>> matcher = j1 >> j2 >> j2 >> j3
"""
def __init__(self, restrict_in=True, restrict_out=True, filt=None,
name=None):
"""Instanciate a MatchGraphJoker, with restrictions
@restrict_in: (optional) if set, the number of predecessors of the
matched node must be the same than the joker node in the
associated MatchGraph
@restrict_out: (optional) counterpart of @restrict_in for successors
@filt: (optional) function(node) -> boolean for filtering candidate node
@name: (optional) helper for displaying the current joker
"""
if filt is None:
filt = lambda node: True
self.filt = filt
if name is None:
name = str(id(self))
self._name = name
self.restrict_in = restrict_in
self.restrict_out = restrict_out
def __rshift__(self, joker):
"""Helper for describing a MatchGraph from @joker
J1 >> J2 stands for an edge going to J2 from J1
@joker: MatchGraphJoker instance
"""
assert isinstance(joker, MatchGraphJoker)
graph = MatchGraph()
graph.add_node(self)
graph.add_node(joker)
graph.add_edge(self, joker)
# For future "A >> B" idiom construction
graph._last_node = joker
return graph
def __str__(self):
info = []
if not self.restrict_in:
info.append("In:*")
if not self.restrict_out:
info.append("Out:*")
return "Joker %s %s" % (self._name,
"(%s)" % " ".join(info) if info else "")
class MatchGraph(DiGraph):
"""MatchGraph intends to be the counterpart of MatchExpr, but for DiGraph
This class provides API to match a given DiGraph pattern, with addidionnal
restrictions.
The implemented algorithm is a naive approach.
The recommended way to instanciate a MatchGraph is the use of
MatchGraphJoker.
"""
def __init__(self, *args, **kwargs):
super(MatchGraph, self).__init__(*args, **kwargs)
# Construction helper
self._last_node = None
# Construction helpers
def __rshift__(self, joker):
"""Construction helper, adding @joker to the current graph as a son of
_last_node
@joker: MatchGraphJoker instance"""
assert isinstance(joker, MatchGraphJoker)
assert isinstance(self._last_node, MatchGraphJoker)
self.add_node(joker)
self.add_edge(self._last_node, joker)
self._last_node = joker
return self
def __add__(self, graph):
"""Construction helper, merging @graph with self
@graph: MatchGraph instance
"""
assert isinstance(graph, MatchGraph)
# Reset helpers flag
self._last_node = None
graph._last_node = None
# Merge graph into self
for node in graph.nodes():
self.add_node(node)
for edge in graph.edges():
self.add_edge(*edge)
return self
# Graph matching
def _check_node(self, candidate, expected, graph, partial_sol=None):
"""Check if @candidate can stand for @expected in @graph, given @partial_sol
@candidate: @graph's node
@expected: MatchGraphJoker instance
@graph: DiGraph instance
@partial_sol: (optional) dictionary of MatchGraphJoker -> @graph's node
standing for a partial solution
"""
# Avoid having 2 different joker for the same node
if partial_sol and candidate in partial_sol.values():
return False
# Check lambda filtering
if not expected.filt(candidate):
return False
# Check arity
# If filter_in/out, then arity must be the same
# Otherwise, arity of the candidate must be at least equal
if ((expected.restrict_in == True and
len(self.predecessors(expected)) != len(graph.predecessors(candidate))) or
(expected.restrict_in == False and
len(self.predecessors(expected)) > len(graph.predecessors(candidate)))):
return False
if ((expected.restrict_out == True and
len(self.successors(expected)) != len(graph.successors(candidate))) or
(expected.restrict_out == False and
len(self.successors(expected)) > len(graph.successors(candidate)))):
return False
# Check edges with partial solution if any
if not partial_sol:
return True
for pred in self.predecessors(expected):
if (pred in partial_sol and
partial_sol[pred] not in graph.predecessors(candidate)):
return False
for succ in self.successors(expected):
if (succ in partial_sol and
partial_sol[succ] not in graph.successors(candidate)):
return False
# All checks OK
return True
def _propagate_sol(self, node, partial_sol, graph, todo, propagator):
"""
Try to extend the current @partial_sol by propagating the solution using
@propagator on @node.
New solutions are added to @todo
"""
real_node = partial_sol[node]
for candidate in propagator(self, node):
# Edge already in the partial solution, skip it
if candidate in partial_sol:
continue
# Check candidate
for candidate_real in propagator(graph, real_node):
if self._check_node(candidate_real, candidate, graph,
partial_sol):
temp_sol = partial_sol.copy()
temp_sol[candidate] = candidate_real
if temp_sol not in todo:
todo.append(temp_sol)
@staticmethod
def _propagate_successors(graph, node):
"""Propagate through @node successors in @graph"""
return graph.successors_iter(node)
@staticmethod
def _propagate_predecessors(graph, node):
"""Propagate through @node predecessors in @graph"""
return graph.predecessors_iter(node)
def match(self, graph):
"""Naive subgraph matching between graph and self.
Iterator on matching solution, as dictionary MatchGraphJoker -> @graph
@graph: DiGraph instance
In order to obtained correct and complete results, @graph must be
connected.
"""
# Partial solution: nodes corrects, edges between these nodes corrects
# A partial solution is a dictionary MatchGraphJoker -> @graph's node
todo = list() # Dictionnaries containing partial solution
done = list() # Aleady computed partial solutions
# Elect first candidates
to_match = next(iter(self._nodes))
for node in graph.nodes():
if self._check_node(node, to_match, graph):
to_add = {to_match: node}
if to_add not in todo:
todo.append(to_add)
while todo:
# When a partial_sol is computed, if more precise partial solutions
# are found, they will be added to 'todo'
# -> using last entry of todo first performs a "depth first"
# approach on solutions
# -> the algorithm may converge faster to a solution, a desired
# behavior while doing graph simplification (stopping after one
# sol)
partial_sol = todo.pop()
# Avoid infinite loop and recurrent work
if partial_sol in done:
continue
done.append(partial_sol)
# If all nodes are matching, this is a potential solution
if len(partial_sol) == len(self._nodes):
yield partial_sol
continue
# Find node to tests using edges
for node in partial_sol:
self._propagate_sol(node, partial_sol, graph, todo,
MatchGraph._propagate_successors)
self._propagate_sol(node, partial_sol, graph, todo,
MatchGraph._propagate_predecessors)
raise StopIteration
| 34.173866 | 87 | 0.545679 | 31,575 | 0.997788 | 9,442 | 0.298373 | 4,149 | 0.131111 | 0 | 0 | 10,863 | 0.343277 |
ba2df7bb990808dc2a091788ac5a88823c2f2250 | 9,466 | py | Python | variation/multiplex.py | FCG-LLC/snmpsim | a55ecde4cde65d2364ea334ab85df4cd1bb21f3b | [
"BSD-2-Clause"
] | null | null | null | variation/multiplex.py | FCG-LLC/snmpsim | a55ecde4cde65d2364ea334ab85df4cd1bb21f3b | [
"BSD-2-Clause"
] | null | null | null | variation/multiplex.py | FCG-LLC/snmpsim | a55ecde4cde65d2364ea334ab85df4cd1bb21f3b | [
"BSD-2-Clause"
] | 1 | 2019-12-16T09:51:38.000Z | 2019-12-16T09:51:38.000Z | #
# This file is part of snmpsim software.
#
# Copyright (c) 2010-2017, Ilya Etingof <etingof@gmail.com>
# License: http://snmpsim.sf.net/license.html
#
# Managed value variation module: simulate a live Agent using
# a series of snapshots.
#
import os, time, bisect
from pyasn1.compat.octets import str2octs
from pysnmp.proto import rfc1902
from snmpsim.record.snmprec import SnmprecRecord
from snmpsim.record.search.file import searchRecordByOid, getRecord
from snmpsim.record.search.database import RecordIndex
from snmpsim import confdir
from snmpsim.mltsplit import split
from snmpsim import log
from snmpsim import error
def init(**context):
if context['options']:
for k, v in [split(x, ':') for x in split(context['options'], ',')]:
if k == 'addon':
if k in moduleContext:
moduleContext[k].append(v)
else:
moduleContext[k] = [v]
else:
moduleContext[k] = v
if context['mode'] == 'variating':
moduleContext['booted'] = time.time()
elif context['mode'] == 'recording':
if 'dir' not in moduleContext:
raise error.SnmpsimError('SNMP snapshots directory not specified')
if not os.path.exists(moduleContext['dir']):
log.msg('multiplex: creating %s...' % moduleContext['dir'])
os.makedirs(moduleContext['dir'])
if 'iterations' in moduleContext:
moduleContext['iterations'] = max(0, int(moduleContext['iterations']) - 1)
if 'period' in moduleContext:
moduleContext['period'] = float(moduleContext['period'])
else:
moduleContext['period'] = 10.0
moduleContext['ready'] = True
def variate(oid, tag, value, **context):
if 'settings' not in recordContext:
recordContext['settings'] = dict([split(x, '=') for x in split(value, ',')])
if 'dir' not in recordContext['settings']:
log.msg('multiplex: snapshot directory not specified')
return context['origOid'], tag, context['errorStatus']
recordContext['settings']['dir'] = recordContext['settings']['dir'].replace(
'/', os.path.sep
)
if recordContext['settings']['dir'][0] != os.path.sep:
for x in confdir.data:
d = os.path.join(x, recordContext['settings']['dir'])
if os.path.exists(d):
break
else:
log.msg('multiplex: directory %s not found' % recordContext['settings']['dir'])
return context['origOid'], tag, context['errorStatus']
else:
d = recordContext['settings']['dir']
recordContext['dirmap'] = dict(
[(int(os.path.basename(x).split(os.path.extsep)[0]), os.path.join(d, x)) for x in os.listdir(d) if
x[-7:] == 'snmprec']
)
recordContext['keys'] = list(
recordContext['dirmap'].keys()
)
recordContext['bounds'] = (
min(recordContext['keys']), max(recordContext['keys'])
)
if 'period' in recordContext['settings']:
recordContext['settings']['period'] = float(recordContext['settings']['period'])
else:
recordContext['settings']['period'] = 60.0
if 'wrap' in recordContext['settings']:
recordContext['settings']['wrap'] = bool(recordContext['settings']['wrap'])
else:
recordContext['settings']['wrap'] = False
if 'control' in recordContext['settings']:
recordContext['settings']['control'] = rfc1902.ObjectName(
recordContext['settings']['control']
)
log.msg('multiplex: using control OID %s for subtree %s, time-based multiplexing disabled' % (
recordContext['settings']['control'], oid))
recordContext['ready'] = True
if 'ready' not in recordContext:
return context['origOid'], tag, context['errorStatus']
if oid not in moduleContext:
moduleContext[oid] = {}
if context['setFlag']:
if 'control' in recordContext['settings'] and \
recordContext['settings']['control'] == context['origOid']:
fileno = int(context['origValue'])
if fileno >= len(recordContext['keys']):
log.msg('multiplex: .snmprec file number %s over limit of %s' % (fileno, len(recordContext['keys'])))
return context['origOid'], tag, context['errorStatus']
moduleContext[oid]['fileno'] = fileno
log.msg('multiplex: switched to file #%s (%s)' % (
recordContext['keys'][fileno], recordContext['dirmap'][recordContext['keys'][fileno]]))
return context['origOid'], tag, context['origValue']
else:
return context['origOid'], tag, context['errorStatus']
if 'control' in recordContext['settings']:
if 'fileno' not in moduleContext[oid]:
moduleContext[oid]['fileno'] = 0
if not context['nextFlag'] and \
recordContext['settings']['control'] == context['origOid']:
return context['origOid'], tag, rfc1902.Integer32(moduleContext[oid]['fileno'])
else:
timeslot = (time.time() - moduleContext['booted']) % (
recordContext['settings']['period'] * len(recordContext['dirmap']))
fileslot = int(timeslot / recordContext['settings']['period']) + recordContext['bounds'][0]
fileno = bisect.bisect(recordContext['keys'], fileslot) - 1
if 'fileno' not in moduleContext[oid] or \
moduleContext[oid]['fileno'] < fileno or \
recordContext['settings']['wrap']:
moduleContext[oid]['fileno'] = fileno
datafile = recordContext['dirmap'][
recordContext['keys'][moduleContext[oid]['fileno']]
]
if 'datafile' not in moduleContext[oid] or \
moduleContext[oid]['datafile'] != datafile:
if 'datafileobj' in moduleContext[oid]:
moduleContext[oid]['datafileobj'].close()
moduleContext[oid]['datafileobj'] = RecordIndex(
datafile, SnmprecRecord()
).create()
moduleContext[oid]['datafile'] = datafile
log.msg('multiplex: switching to data file %s for %s' % (datafile, context['origOid']))
text, db = moduleContext[oid]['datafileobj'].getHandles()
textOid = str(rfc1902.OctetString('.'.join(['%s' % x for x in context['origOid']])))
try:
line = moduleContext[oid]['datafileobj'].lookup(textOid)
except KeyError:
offset = searchRecordByOid(context['origOid'], text, SnmprecRecord())
exactMatch = False
else:
offset, subtreeFlag, prevOffset = line.split(str2octs(','))
exactMatch = True
text.seek(int(offset))
line, _, _ = getRecord(text) # matched line
if context['nextFlag']:
if exactMatch:
line, _, _ = getRecord(text)
else:
if not exactMatch:
return context['origOid'], tag, context['errorStatus']
if not line:
return context['origOid'], tag, context['errorStatus']
try:
oid, value = SnmprecRecord().evaluate(line)
except error.SnmpsimError:
oid, value = context['origOid'], context['errorStatus']
return oid, tag, value
def record(oid, tag, value, **context):
if 'ready' not in moduleContext:
raise error.SnmpsimError('module not initialized')
if 'started' not in moduleContext:
moduleContext['started'] = time.time()
if context['stopFlag']:
if 'file' in moduleContext:
moduleContext['file'].close()
del moduleContext['file']
else:
moduleContext['filenum'] = 0
if 'iterations' in moduleContext and moduleContext['iterations']:
log.msg('multiplex: %s iterations remaining' % moduleContext['iterations'])
moduleContext['started'] = time.time()
moduleContext['iterations'] -= 1
moduleContext['filenum'] += 1
wait = max(0, moduleContext['period'] - (time.time() - moduleContext['started']))
raise error.MoreDataNotification(period=wait)
else:
raise error.NoDataNotification()
if 'file' not in moduleContext:
if 'filenum' not in moduleContext:
moduleContext['filenum'] = 0
snmprecfile = os.path.join(moduleContext['dir'],
'%.5d%ssnmprec' % (moduleContext['filenum'],
os.path.extsep))
moduleContext['file'] = open(snmprecfile, 'wb')
log.msg('multiplex: writing into %s file...' % snmprecfile)
moduleContext['file'].write(
SnmprecRecord().format(context['origOid'], context['origValue'])
)
if not context['total']:
settings = {
'dir': moduleContext['dir'].replace(os.path.sep, '/')
}
if 'period' in moduleContext:
settings['period'] = '%.2f' % float(moduleContext['period'])
if 'addon' in moduleContext:
settings.update(
dict([split(x, '=') for x in moduleContext['addon']])
)
value = ','.join(['%s=%s' % (k, v) for k, v in settings.items()])
return str(context['startOID']), ':multiplex', value
else:
raise error.NoDataNotification()
def shutdown(**context):
pass
| 39.940928 | 117 | 0.584619 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,283 | 0.241179 |
e839fbe3bff22b6a6dd9a48e9fd2bca0767aa7c7 | 2,254 | py | Python | migrations/versions/ac4799fb0cd3_.py | anngle/t923 | 078d2c566c77afa2ca1be7663d3c23c9f0ecddac | [
"BSD-3-Clause"
] | 1 | 2021-11-28T05:46:45.000Z | 2021-11-28T05:46:45.000Z | migrations/versions/ac4799fb0cd3_.py | anngle/t923 | 078d2c566c77afa2ca1be7663d3c23c9f0ecddac | [
"BSD-3-Clause"
] | null | null | null | migrations/versions/ac4799fb0cd3_.py | anngle/t923 | 078d2c566c77afa2ca1be7663d3c23c9f0ecddac | [
"BSD-3-Clause"
] | null | null | null | """empty message
Revision ID: ac4799fb0cd3
Revises: 3b042c12d85e
Create Date: 2018-12-12 22:47:40.070151
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = 'ac4799fb0cd3'
down_revision = '3b042c12d85e'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('roles',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=80), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('roles_parents',
sa.Column('role_id', sa.Integer(), nullable=True),
sa.Column('parent_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['parent_id'], ['roles.id'], ),
sa.ForeignKeyConstraint(['role_id'], ['roles.id'], )
)
op.create_table('users_roles',
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('role_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['role_id'], ['roles.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], )
)
op.drop_table('sysconfig')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('sysconfig',
sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False),
sa.Column('web_name', mysql.VARCHAR(length=80), nullable=False),
sa.Column('web_describe', mysql.VARCHAR(length=500), nullable=True),
sa.Column('user_register', mysql.TINYINT(display_width=1), autoincrement=False, nullable=True),
sa.Column('active_site', mysql.TINYINT(display_width=1), autoincrement=False, nullable=True),
sa.Column('close_register_user_message', mysql.VARCHAR(length=500), nullable=True),
sa.Column('close_website_message', mysql.VARCHAR(length=500), nullable=True),
sa.Column('withdraw_money', mysql.TINYINT(display_width=1), autoincrement=False, nullable=True),
sa.PrimaryKeyConstraint('id'),
mysql_default_charset='utf8mb4',
mysql_engine='InnoDB'
)
op.drop_table('users_roles')
op.drop_table('roles_parents')
op.drop_table('roles')
# ### end Alembic commands ###
| 36.95082 | 100 | 0.697427 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 727 | 0.322538 |
e83a10c3bd7787fb995d7f3409fbe97fa6a48414 | 7,597 | py | Python | cisco-ios-xr/ydk/models/cisco_ios_xr/_meta/_Cisco_IOS_XR_fretta_bcm_dpa_drop_stats_oper.py | tkamata-test/ydk-py | b637e7853a8edbbd31fbc05afa3aa4110b31c5f9 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | cisco-ios-xr/ydk/models/cisco_ios_xr/_meta/_Cisco_IOS_XR_fretta_bcm_dpa_drop_stats_oper.py | tkamata-test/ydk-py | b637e7853a8edbbd31fbc05afa3aa4110b31c5f9 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | cisco-ios-xr/ydk/models/cisco_ios_xr/_meta/_Cisco_IOS_XR_fretta_bcm_dpa_drop_stats_oper.py | tkamata-test/ydk-py | b637e7853a8edbbd31fbc05afa3aa4110b31c5f9 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLIST, REFERENCE_IDENTITY_CLASS, REFERENCE_ENUM_CLASS, REFERENCE_BITS, REFERENCE_UNION
from ydk.errors import YPYError, YPYModelError
from ydk.providers._importer import _yang_ns
_meta_table = {
'Drop.Nodes.Node.NpuNumberForDropStats.NpuNumberForDropStat.DropSpecificStatsData' : {
'meta_info' : _MetaInfoClass('Drop.Nodes.Node.NpuNumberForDropStats.NpuNumberForDropStat.DropSpecificStatsData',
False,
[
_MetaInfoClassMember('drop-data', ATTRIBUTE, 'int' , None, None,
[('-2147483648', '2147483647')], [],
''' Drop ID
''',
'drop_data',
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper', True),
_MetaInfoClassMember('count', ATTRIBUTE, 'int' , None, None,
[('0', '18446744073709551615')], [],
''' count
''',
'count',
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper', False),
_MetaInfoClassMember('id', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' id
''',
'id',
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper', False),
_MetaInfoClassMember('name', ATTRIBUTE, 'str' , None, None,
[], [],
''' name
''',
'name',
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper', False),
],
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper',
'drop-specific-stats-data',
_yang_ns._namespaces['Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_fretta_bcm_dpa_drop_stats_oper'
),
},
'Drop.Nodes.Node.NpuNumberForDropStats.NpuNumberForDropStat' : {
'meta_info' : _MetaInfoClass('Drop.Nodes.Node.NpuNumberForDropStats.NpuNumberForDropStat',
False,
[
_MetaInfoClassMember('npu-id', ATTRIBUTE, 'int' , None, None,
[('-2147483648', '2147483647')], [],
''' NPU number
''',
'npu_id',
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper', True),
_MetaInfoClassMember('drop-specific-stats-data', REFERENCE_LIST, 'DropSpecificStatsData' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_fretta_bcm_dpa_drop_stats_oper', 'Drop.Nodes.Node.NpuNumberForDropStats.NpuNumberForDropStat.DropSpecificStatsData',
[], [],
''' Second argument to the module
''',
'drop_specific_stats_data',
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper', False),
],
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper',
'npu-number-for-drop-stat',
_yang_ns._namespaces['Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_fretta_bcm_dpa_drop_stats_oper'
),
},
'Drop.Nodes.Node.NpuNumberForDropStats' : {
'meta_info' : _MetaInfoClass('Drop.Nodes.Node.NpuNumberForDropStats',
False,
[
_MetaInfoClassMember('npu-number-for-drop-stat', REFERENCE_LIST, 'NpuNumberForDropStat' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_fretta_bcm_dpa_drop_stats_oper', 'Drop.Nodes.Node.NpuNumberForDropStats.NpuNumberForDropStat',
[], [],
''' All drop stats for a particular NPU
''',
'npu_number_for_drop_stat',
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper', False),
],
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper',
'npu-number-for-drop-stats',
_yang_ns._namespaces['Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_fretta_bcm_dpa_drop_stats_oper'
),
},
'Drop.Nodes.Node' : {
'meta_info' : _MetaInfoClass('Drop.Nodes.Node',
False,
[
_MetaInfoClassMember('node-name', ATTRIBUTE, 'str' , None, None,
[], ['([a-zA-Z0-9_]*\\d+/){1,2}([a-zA-Z0-9_]*\\d+)'],
''' Node ID
''',
'node_name',
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper', True),
_MetaInfoClassMember('npu-number-for-drop-stats', REFERENCE_CLASS, 'NpuNumberForDropStats' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_fretta_bcm_dpa_drop_stats_oper', 'Drop.Nodes.Node.NpuNumberForDropStats',
[], [],
''' NPU drop stats
''',
'npu_number_for_drop_stats',
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper', False),
],
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper',
'node',
_yang_ns._namespaces['Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_fretta_bcm_dpa_drop_stats_oper'
),
},
'Drop.Nodes' : {
'meta_info' : _MetaInfoClass('Drop.Nodes',
False,
[
_MetaInfoClassMember('node', REFERENCE_LIST, 'Node' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_fretta_bcm_dpa_drop_stats_oper', 'Drop.Nodes.Node',
[], [],
''' Drop stats data for a particular node
''',
'node',
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper', False),
],
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper',
'nodes',
_yang_ns._namespaces['Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_fretta_bcm_dpa_drop_stats_oper'
),
},
'Drop' : {
'meta_info' : _MetaInfoClass('Drop',
False,
[
_MetaInfoClassMember('nodes', REFERENCE_CLASS, 'Nodes' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_fretta_bcm_dpa_drop_stats_oper', 'Drop.Nodes',
[], [],
''' Drop data per node
''',
'nodes',
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper', False),
],
'Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper',
'drop',
_yang_ns._namespaces['Cisco-IOS-XR-fretta-bcm-dpa-drop-stats-oper'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_fretta_bcm_dpa_drop_stats_oper'
),
},
}
_meta_table['Drop.Nodes.Node.NpuNumberForDropStats.NpuNumberForDropStat.DropSpecificStatsData']['meta_info'].parent =_meta_table['Drop.Nodes.Node.NpuNumberForDropStats.NpuNumberForDropStat']['meta_info']
_meta_table['Drop.Nodes.Node.NpuNumberForDropStats.NpuNumberForDropStat']['meta_info'].parent =_meta_table['Drop.Nodes.Node.NpuNumberForDropStats']['meta_info']
_meta_table['Drop.Nodes.Node.NpuNumberForDropStats']['meta_info'].parent =_meta_table['Drop.Nodes.Node']['meta_info']
_meta_table['Drop.Nodes.Node']['meta_info'].parent =_meta_table['Drop.Nodes']['meta_info']
_meta_table['Drop.Nodes']['meta_info'].parent =_meta_table['Drop']['meta_info']
| 49.012903 | 258 | 0.576938 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4,176 | 0.549691 |
e83b70a19e325c708c84cceef919e66e323c5dc3 | 2,403 | py | Python | main.py | Dinxor/tstore | ff2bb229ad2169926046076022b5a37025e98877 | [
"MIT"
] | null | null | null | main.py | Dinxor/tstore | ff2bb229ad2169926046076022b5a37025e98877 | [
"MIT"
] | null | null | null | main.py | Dinxor/tstore | ff2bb229ad2169926046076022b5a37025e98877 | [
"MIT"
] | null | null | null | from tkinter import Tk, Button, Label
from threading import Thread
from queue import Queue
import configparser
import sys
import os
def init_config(path):
config.optionxform = str
config.read(path)
def maingui():
for name in tt['modules'].keys():
tt[name]['label'].config(text=str(tt[name].get('cnt', 0)),
bg=('lime' if (tt[name].get('is_working', False)) else 'white'))
root.after(1000, maingui)
def rstart(name):
if not tt[name].get('is_enable', True):
tt[name].update({'is_enable': True})
elif not tt[name].get('is_enable', False):
tt[name].update({'is_enable': True})
thread = Thread(target=eval(name), args=(tt,))
thread.daemon = True
thread.start()
def rstop(name):
if tt[name].get('is_enable', False):
tt[name].update({'is_enable': False})
if __name__ == '__main__':
root = Tk()
root.geometry('+200+200')
root.overrideredirect(0)
# uncomment for minimize
# root.iconify()
tt = {}
modules = []
if len(sys.argv) < 2:
path = './settings.ini'
else:
print(sys.argv[1])
path = './%s' % (sys.argv[1])
if not os.path.exists(path):
print('Settings file %s not found' % (path))
sys.exit()
config = configparser.ConfigParser()
init_config(path)
for section in config.sections():
tt.update({section.lower():dict(config[section])})
if section == 'MODULES':
for key in config[section]:
modules.append([key, config[section][key]])
exec('from modules.%s import %s' % (key, key))
for [name, autostart] in modules:
module = tt.get(name, {})
q = Queue()
module.update({'queue': q})
module.update({'cnt': 0})
tt.update({name: module})
for i, [name, autostart] in enumerate(modules):
module = tt.get(name, {})
Label(text=name).grid(row=i, column=0)
Button(text="Start", command=lambda x=name: rstart(x)).grid(row=i, column=1)
Button(text="Stop", command=lambda x=name: rstop(x)).grid(row=i, column=2)
label = Label(root, bg='white', text='0')
label.grid(row=i, column=3)
module.update({'label': label})
tt.update({name: module})
if autostart:
rstart(name)
root.after(100, maingui)
root.mainloop()
| 30.0375 | 97 | 0.574698 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 300 | 0.124844 |
e83c09d5b0c0d2913540a96c620e7e78f88f46ec | 1,182 | py | Python | titan/logger.py | KhaosResearch/TITAN-API | 98a66b211792f4b42680828644938b062de42579 | [
"MIT"
] | null | null | null | titan/logger.py | KhaosResearch/TITAN-API | 98a66b211792f4b42680828644938b062de42579 | [
"MIT"
] | null | null | null | titan/logger.py | KhaosResearch/TITAN-API | 98a66b211792f4b42680828644938b062de42579 | [
"MIT"
] | null | null | null | import logging.config
def configure_logging():
DEFAULT_LOGGING_CONFIG = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"basic": {
"format": "[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
}
},
"handlers": {
"console": {
"formatter": "basic",
"class": "logging.StreamHandler",
},
"rotate_file": {
"formatter": "basic",
"class": "logging.handlers.RotatingFileHandler",
"filename": "titan.log",
"encoding": "utf8",
"maxBytes": 100000,
"backupCount": 1,
},
},
"loggers": {
"": {
"level": "INFO",
"handlers": ["rotate_file"],
},
"titan": {
"level": "DEBUG",
"handlers": ["console"],
},
},
}
logging.config.dictConfig(DEFAULT_LOGGING_CONFIG)
def get_logger(module):
return logging.getLogger(module)
| 26.266667 | 81 | 0.416244 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 434 | 0.367174 |
e83cbc6b6ef32b4ad9eb6c2026f3ac57e6c46439 | 386 | py | Python | Raia2011/model/name2idx/species.py | okadalabipr/cancer_signaling | a41820c273c964c5df4d24fec2d1c60ae2cdfd72 | [
"MIT"
] | 1 | 2019-08-18T10:26:04.000Z | 2019-08-18T10:26:04.000Z | Raia2011/model/name2idx/species.py | okadalabipr/cancer_signaling | a41820c273c964c5df4d24fec2d1c60ae2cdfd72 | [
"MIT"
] | null | null | null | Raia2011/model/name2idx/species.py | okadalabipr/cancer_signaling | a41820c273c964c5df4d24fec2d1c60ae2cdfd72 | [
"MIT"
] | 3 | 2019-12-23T06:55:10.000Z | 2020-08-31T08:09:05.000Z | NAMES = [
'IL13stimulation',
'Rec',
'Rec_i',
'IL13_Rec',
'p_IL13_Rec',
'p_IL13_Rec_i',
'JAK2',
'pJAK2',
'SHP1',
'STAT5',
'pSTAT5',
'SOCS3mRNA',
'DecoyR',
'IL13_DecoyR',
'SOCS3',
'CD274mRNA',
]
for idx, name in enumerate(NAMES):
exec(
'{} = {:d}'.format(
name, idx
)
)
NUM = len(NAMES) | 14.296296 | 34 | 0.458549 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 160 | 0.414508 |
e83e35480e03fbc96372bcc220d34b49bf9a9cba | 2,149 | py | Python | OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/GL/ARB/map_buffer_range.py | JE-Chen/je_old_repo | a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5 | [
"MIT"
] | null | null | null | OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/GL/ARB/map_buffer_range.py | JE-Chen/je_old_repo | a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5 | [
"MIT"
] | null | null | null | OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/GL/ARB/map_buffer_range.py | JE-Chen/je_old_repo | a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5 | [
"MIT"
] | null | null | null | '''OpenGL extension ARB.map_buffer_range
This module customises the behaviour of the
OpenGL.raw.GL.ARB.map_buffer_range to provide a more
Python-friendly API
Overview (from the spec)
ARB_map_buffer_range expands the buffer object API to allow greater
performance when a client application only needs to write to a sub-range
of a buffer object. To that end, this extension introduces two new buffer
object features: non-serialized buffer modification and explicit sub-range
flushing for mapped buffer objects.
OpenGL requires that commands occur in a FIFO manner meaning that any
changes to buffer objects either block until the data has been processed by
the OpenGL pipeline or else create extra copies to avoid such a block. By
providing a method to asynchronously modify buffer object data, an
application is then able to manage the synchronization points themselves
and modify ranges of data contained by a buffer object even though OpenGL
might still be using other parts of it.
This extension also provides a method for explicitly flushing ranges of a
mapped buffer object so OpenGL does not have to assume that the entire
range may have been modified. Further, it allows the application to more
precisely specify its intent with respect to reading, writing, and whether
the previous contents of a mapped range of interest need be preserved
prior to modification.
Affects ARB_vertex_buffer_object, ARB_pixel_buffer_object and OpenGL 1.5
Buffer Objects.
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/ARB/map_buffer_range.txt
'''
from OpenGL import platform, constant, arrays
from OpenGL import extensions, wrapper
import ctypes
from OpenGL.raw.GL import _types, _glgets
from OpenGL.raw.GL.ARB.map_buffer_range import *
from OpenGL.raw.GL.ARB.map_buffer_range import _EXTENSION_NAME
def glInitMapBufferRangeARB():
'''Return boolean indicating whether this extension is available'''
from OpenGL import extensions
return extensions.hasGLExtension( _EXTENSION_NAME )
### END AUTOGENERATED SECTION | 42.98 | 77 | 0.790135 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,752 | 0.815263 |
e83e7031289be7e749092a0b52442c696186785d | 5,091 | py | Python | src/python/src/grpc/framework/foundation/_later_test.py | iMilind/grpc | f5b20ce8ec0c1dde684840f6ea8dcf80822bbb1d | [
"BSD-3-Clause"
] | 1 | 2021-04-24T08:18:15.000Z | 2021-04-24T08:18:15.000Z | src/python/src/grpc/framework/foundation/_later_test.py | iMilind/grpc | f5b20ce8ec0c1dde684840f6ea8dcf80822bbb1d | [
"BSD-3-Clause"
] | 3 | 2020-12-31T09:08:34.000Z | 2021-09-28T05:42:02.000Z | third_party/grpc/src/python/src/grpc/framework/foundation/_later_test.py | acidburn0zzz/kythe | 6cd4e9c81a1158de43ec783607a4d7edd9b7e4a0 | [
"Apache-2.0"
] | 1 | 2022-01-14T04:25:02.000Z | 2022-01-14T04:25:02.000Z | # Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests of the later module."""
import threading
import time
import unittest
from grpc.framework.foundation import later
TICK = 0.1
class LaterTest(unittest.TestCase):
def test_simple_delay(self):
lock = threading.Lock()
cell = [0]
return_value = object()
def computation():
with lock:
cell[0] += 1
return return_value
computation_future = later.later(TICK * 2, computation)
self.assertFalse(computation_future.done())
self.assertFalse(computation_future.cancelled())
time.sleep(TICK)
self.assertFalse(computation_future.done())
self.assertFalse(computation_future.cancelled())
with lock:
self.assertEqual(0, cell[0])
time.sleep(TICK * 2)
self.assertTrue(computation_future.done())
self.assertFalse(computation_future.cancelled())
with lock:
self.assertEqual(1, cell[0])
self.assertEqual(return_value, computation_future.result())
def test_callback(self):
lock = threading.Lock()
cell = [0]
callback_called = [False]
future_passed_to_callback = [None]
def computation():
with lock:
cell[0] += 1
computation_future = later.later(TICK * 2, computation)
def callback(outcome):
with lock:
callback_called[0] = True
future_passed_to_callback[0] = outcome
computation_future.add_done_callback(callback)
time.sleep(TICK)
with lock:
self.assertFalse(callback_called[0])
time.sleep(TICK * 2)
with lock:
self.assertTrue(callback_called[0])
self.assertTrue(future_passed_to_callback[0].done())
callback_called[0] = False
future_passed_to_callback[0] = None
computation_future.add_done_callback(callback)
with lock:
self.assertTrue(callback_called[0])
self.assertTrue(future_passed_to_callback[0].done())
def test_cancel(self):
lock = threading.Lock()
cell = [0]
callback_called = [False]
future_passed_to_callback = [None]
def computation():
with lock:
cell[0] += 1
computation_future = later.later(TICK * 2, computation)
def callback(outcome):
with lock:
callback_called[0] = True
future_passed_to_callback[0] = outcome
computation_future.add_done_callback(callback)
time.sleep(TICK)
with lock:
self.assertFalse(callback_called[0])
computation_future.cancel()
self.assertTrue(computation_future.cancelled())
self.assertFalse(computation_future.running())
self.assertTrue(computation_future.done())
with lock:
self.assertTrue(callback_called[0])
self.assertTrue(future_passed_to_callback[0].cancelled())
def test_result(self):
lock = threading.Lock()
cell = [0]
callback_called = [False]
future_passed_to_callback_cell = [None]
return_value = object()
def computation():
with lock:
cell[0] += 1
return return_value
computation_future = later.later(TICK * 2, computation)
def callback(future_passed_to_callback):
with lock:
callback_called[0] = True
future_passed_to_callback_cell[0] = future_passed_to_callback
computation_future.add_done_callback(callback)
returned_value = computation_future.result()
self.assertEqual(return_value, returned_value)
# The callback may not yet have been called! Sleep a tick.
time.sleep(TICK)
with lock:
self.assertTrue(callback_called[0])
self.assertEqual(return_value, future_passed_to_callback_cell[0].result())
if __name__ == '__main__':
unittest.main()
| 33.493421 | 80 | 0.719112 | 3,377 | 0.663327 | 0 | 0 | 0 | 0 | 0 | 0 | 1,600 | 0.31428 |
e83fb918ef967c55aa6401be077593fddf740b8a | 1,179 | py | Python | tests/test_stage.py | bytedance/raylink | cd83a4377fede1ac645037df567010f2ddac5a69 | [
"Apache-2.0"
] | 17 | 2021-10-11T06:52:09.000Z | 2022-01-12T01:04:59.000Z | tests/test_stage.py | bytedance/raylink | cd83a4377fede1ac645037df567010f2ddac5a69 | [
"Apache-2.0"
] | null | null | null | tests/test_stage.py | bytedance/raylink | cd83a4377fede1ac645037df567010f2ddac5a69 | [
"Apache-2.0"
] | 2 | 2021-10-11T08:19:04.000Z | 2021-12-04T02:48:13.000Z | from unittest import TestCase
from raylink.data.stage import GPUStage
import numpy as np
import torch
import time
class TestStage(TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.shape = [20, 1024, 1024]
cls.num = 50
cls.zero = np.zeros(cls.shape)
cls.array = [np.empty(cls.shape) for _ in range(cls.num)]
cls.stage = GPUStage(cls.zero)
def test_nothing(self):
# setup takes 1.344s
pass
def test_normal_tensor(self):
# normal copy takes 4.840s
# real time 3.496s
st = time.time()
zero = torch.tensor(self.zero).cuda()
for a in self.array:
t = torch.tensor(a).cuda()
zero += t
print(zero)
print(time.time() - st)
def test_gpu_stage(self):
# GPU stage copy takes 1.694s
# real time 0.35s
st = time.time()
zero = torch.tensor(self.zero).cuda()
for a in self.array:
self.stage.put(a)
for _ in range(self.num):
t = self.stage.acquire()
zero += t
self.stage.release()
print(zero)
print(time.time() - st)
| 26.2 | 65 | 0.554707 | 1,062 | 0.900763 | 0 | 0 | 247 | 0.2095 | 0 | 0 | 110 | 0.093299 |
e8404984e29c624bea38b2217947473bb1186bbd | 4,035 | py | Python | forgetPass.py | goyal705/Hotel-Management-System | 8ea3598915f4062a7ae65c634e656d0f25b961f0 | [
"Apache-2.0"
] | 1 | 2021-09-10T11:39:23.000Z | 2021-09-10T11:39:23.000Z | forgetPass.py | goyal705/Hotel-Management-System | 8ea3598915f4062a7ae65c634e656d0f25b961f0 | [
"Apache-2.0"
] | null | null | null | forgetPass.py | goyal705/Hotel-Management-System | 8ea3598915f4062a7ae65c634e656d0f25b961f0 | [
"Apache-2.0"
] | null | null | null | from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import mysql.connector
from login_new import Small_login_win
class Forget_pass_win:
def __init__(self, root):
self.root = root
self.root.title("Forget Password")
self.root.geometry('300x400+520+130')
self.root.maxsize(300, 400)
self.root.minsize(300, 400)
self.user_security_ques = StringVar()
self.user_security_ans = StringVar()
self.new_pass = StringVar()
self.user_name = StringVar()
label = Label(self.root, text="Forgot Password", font=("arial", 20, "bold"), fg="red")
label.place(x=38, y=10)
label_security = Label(self.root, text="Enter UserName", font=("times new roman", 15, "bold"))
label_security.place(x=70, y=50)
entry_name = ttk.Entry(self.root, font=("times new roman", 15, "bold"), textvariable=self.user_name)
entry_name.place(x=45, y=85)
label_security = Label(self.root, text="Enter Security Question", font=("times new roman", 15, "bold"))
label_security.place(x=45, y=120)
entry_security_question = ttk.Combobox(self.root, font=("times new roman", 15, "bold"), width=18,
state="readonly", textvariable=self.user_security_ques)
entry_security_question["values"] = ("Your Petname", "Your Favourite Hobby", "Your Favourite Subject")
entry_security_question.current(0)
entry_security_question.place(x=50, y=155)
label_security_answer = Label(self.root, text="Enter Security Answer", font=("times new roman", 15, "bold"))
label_security_answer.place(x=45, y=195)
entry_name = ttk.Entry(self.root, font=("times new roman", 15, "bold"), textvariable=self.user_security_ans)
entry_name.place(x=45, y=230)
label_security = Label(self.root, text="Enter New Password", font=("times new roman", 15, "bold"))
label_security.place(x=54, y=265)
entry_name = ttk.Entry(self.root, font=("times new roman", 15, "bold"), textvariable=self.new_pass, show="*")
entry_name.place(x=45, y=300)
login_btn = Button(self.root, cursor="circle", command=self.forget, fg="white", bg="red", width=20,
text="Submit Now", font=("times new roman", 10, "bold"))
login_btn.place(x=70, y=360)
def forget(self):
if self.user_security_ans.get() == "":
messagebox.showerror("Error", "Pls answer the security question", parent=self.root)
elif self.new_pass.get() == "":
messagebox.showerror("Error", "Pls enter your new password", parent=self.root)
else:
connection = mysql.connector.connect(host="localhost", username="root", password="1234",
database="tushar")
my_cur = connection.cursor()
query = "select * from user_register where UserName=%s and SecurityQuestion=%s and SecurityAnswer=%s"
value = (self.user_name.get(), self.user_security_ques.get(), self.user_security_ans.get())
my_cur.execute(query, value)
row = my_cur.fetchone()
if row is None:
messagebox.showerror("Error", "Please enter the correct values", parent=self.root)
else:
query = "update user_register set UserPassword=%s where UserName=%s"
value = (self.new_pass.get(), self.user_name.get())
my_cur.execute(query, value)
connection.commit()
connection.close()
messagebox.showinfo("Information", "Your password has been reseted please login again", parent=self.root)
self.new_window = Toplevel(self.root)
self.app = Small_login_win(self.new_window)
if __name__ == '__main__':
root = Tk()
obj = Forget_pass_win(root)
root.mainloop()
| 49.207317 | 122 | 0.607187 | 3,785 | 0.938042 | 0 | 0 | 0 | 0 | 0 | 0 | 852 | 0.211152 |
e8406c99552679a5a4646ded93380dc3a080a4b0 | 2,945 | py | Python | mmdet/models/rroi_extractors/arbox_multi_levels.py | ZZR8066/AerialDetection | 34c732b61d7df9a832a2a072e8b6abbe8031cb07 | [
"Apache-2.0"
] | 6 | 2020-07-30T02:45:35.000Z | 2022-02-08T13:47:26.000Z | mmdet/models/rroi_extractors/arbox_multi_levels.py | ZZR8066/AerialDetection_and_Segmenation | 34c732b61d7df9a832a2a072e8b6abbe8031cb07 | [
"Apache-2.0"
] | 1 | 2020-07-25T12:51:10.000Z | 2021-12-26T22:28:08.000Z | mmdet/models/rroi_extractors/arbox_multi_levels.py | ZZR8066/AerialDetection_and_Segmenation | 34c732b61d7df9a832a2a072e8b6abbe8031cb07 | [
"Apache-2.0"
] | 3 | 2020-11-09T03:11:16.000Z | 2021-11-02T09:30:39.000Z | from __future__ import division
import torch
import torch.nn as nn
from mmdet import ops
from ..registry import ROI_EXTRACTORS
import pdb
@ROI_EXTRACTORS.register_module
class ARboxMultiRoIExtractor(nn.Module):
"""Extract RoI features from a single level feature map.
If there are mulitple input feature levels, each RoI is mapped to a level
according to its scale.
Args:
roi_layer (dict): Specify RoI layer type and arguments.
out_channels (int): Output channels of RoI layers.
featmap_strides (int): Strides of input feature maps.
finest_scale (int): Scale threshold of mapping to level 0.
"""
def __init__(self,
roi_layer,
out_channels,
featmap_strides,
finest_scale=56,
w_enlarge=1.2,
h_enlarge=1.4,
ratio_max=5.0):
super(ARboxMultiRoIExtractor, self).__init__()
self.roi_layers = self.build_roi_layers(roi_layer, featmap_strides)
self.out_channels = out_channels
self.featmap_strides = featmap_strides
self.finest_scale = finest_scale
self.w_enlarge = w_enlarge
self.h_enlarge = h_enlarge
self.ratio_max = ratio_max
@property
def num_inputs(self):
"""int: Input feature map levels."""
return len(self.featmap_strides)
def init_weights(self):
pass
def build_roi_layers(self, layer_cfg, featmap_strides):
cfg = layer_cfg.copy()
layer_type = cfg.pop('type')
assert hasattr(ops, layer_type)
layer_cls = getattr(ops, layer_type)
roi_layers = nn.ModuleList(
[layer_cls(spatial_scale=1 / s, **cfg) for s in featmap_strides])
return roi_layers
def get_poolwh(self, rois, base_size):
ratios = rois[:, 3] / rois[:, 4]
assert ratios.min() >= 1.0
ratios = ratios.ceil()
ratio = ratios.max()
ratio = min(ratio, self.ratio_max)
pool_h = int(base_size)
pool_w = int(ratio * base_size)
return pool_w, pool_h
def forward(self, feats, rois):
if len(feats) == 1:
return self.roi_layers[0](feats[0], rois)
out_size = self.roi_layers[0].out_size
base_size = out_size
out_w, out_h = self.get_poolwh(rois, base_size)
num_levels = len(feats)
roi_feats=[]
for i in range(num_levels):
roi_feats_t = self.roi_layers[i](feats[i], rois, out_w, out_h)
roi_feats.append(roi_feats_t)
# max pool
feature_size = roi_feats[0].size()
roi_feats = [var.view(var.size(0),-1) for var in roi_feats]
for i in range(1, num_levels):
roi_feats[0] = torch.max(roi_feats[0], roi_feats[i])
roi_feats = roi_feats[0]
roi_feats = roi_feats.view(feature_size)
return roi_feats | 32.722222 | 77 | 0.612564 | 2,772 | 0.941256 | 0 | 0 | 2,804 | 0.952122 | 0 | 0 | 486 | 0.165025 |
e840e5bc9763698d91cf0375b1df8b3f61aea666 | 1,449 | py | Python | docs/podstawy/przyklady/ocenyfun.py | damiankarol7/python101 | 1978a9402a8fb0f20c4ca7bd542cb8d7d4501b9b | [
"MIT"
] | 44 | 2015-02-11T19:10:37.000Z | 2021-11-11T09:45:43.000Z | docs/podstawy/przyklady/ocenyfun.py | damiankarol7/python101 | 1978a9402a8fb0f20c4ca7bd542cb8d7d4501b9b | [
"MIT"
] | 9 | 2015-02-06T21:26:25.000Z | 2022-03-31T10:44:22.000Z | docs/podstawy/przyklady/ocenyfun.py | damiankarol7/python101 | 1978a9402a8fb0f20c4ca7bd542cb8d7d4501b9b | [
"MIT"
] | 172 | 2015-06-13T07:16:24.000Z | 2022-03-30T20:41:11.000Z | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Moduł ocenyfun zawiera funkcje wykorzystywane w pliku 05_oceny_03.py
"""
import math # zaimportuj moduł matematyczny
def drukuj(co, kom="Sekwencja zawiera: "):
print(kom)
for i in co:
print(i, end=" ")
def srednia(oceny):
suma = sum(oceny)
return suma / float(len(oceny))
def mediana(oceny):
"""
Jeżeli ilość ocen jest parzysta, medianą jest średnia arytmetyczna
dwóch środkowych ocen. Jesli ilość jest nieparzysta mediana równa
się elementowi środkowemu ouporządkowanej rosnąco listy ocen.
"""
oceny.sort()
if len(oceny) % 2 == 0: # parzysta ilość ocen
half = int(len(oceny) / 2)
# można tak:
# return float(oceny[half-1]+oceny[half]) / 2.0
# albo tak:
return float(sum(oceny[half - 1:half + 1])) / 2.0
else: # nieparzysta ilość ocen
return oceny[len(oceny) / 2]
def wariancja(oceny, srednia):
"""
Wariancja to suma kwadratów różnicy każdej oceny i średniej
podzielona przez ilość ocen:
sigma = (o1-s)+(o2-s)+...+(on-s) / n, gdzie:
o1, o2, ..., on - kolejne oceny,
s - średnia ocen,
n - liczba ocen.
"""
sigma = 0.0
for ocena in oceny:
sigma += (ocena - srednia)**2
return sigma / len(oceny)
def odchylenie(oceny, srednia): # pierwiastek kwadratowy z wariancji
w = wariancja(oceny, srednia)
return math.sqrt(w)
| 25.421053 | 72 | 0.619738 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 817 | 0.552774 |
e8417c90203dc931182a576771783829d860eca2 | 608 | py | Python | kubernetes_typed/client/models/v2beta2_metric_status.py | sobolevn/kubernetes-typed | 5f0a770631c73a9831fbeaeebac188e8f4a52c54 | [
"Apache-2.0"
] | 22 | 2020-12-10T13:06:02.000Z | 2022-02-13T21:58:15.000Z | kubernetes_typed/client/models/v2beta2_metric_status.py | sobolevn/kubernetes-typed | 5f0a770631c73a9831fbeaeebac188e8f4a52c54 | [
"Apache-2.0"
] | 4 | 2021-03-08T07:06:12.000Z | 2022-03-29T23:41:45.000Z | kubernetes_typed/client/models/v2beta2_metric_status.py | sobolevn/kubernetes-typed | 5f0a770631c73a9831fbeaeebac188e8f4a52c54 | [
"Apache-2.0"
] | 2 | 2021-09-05T19:18:28.000Z | 2022-03-14T02:56:17.000Z | # Code generated by `typeddictgen`. DO NOT EDIT.
"""V2beta2MetricStatusDict generated type."""
from typing import TypedDict
from kubernetes_typed.client import V2beta2ExternalMetricStatusDict, V2beta2ObjectMetricStatusDict, V2beta2PodsMetricStatusDict, V2beta2ResourceMetricStatusDict
V2beta2MetricStatusDict = TypedDict(
"V2beta2MetricStatusDict",
{
"external": V2beta2ExternalMetricStatusDict,
"object": V2beta2ObjectMetricStatusDict,
"pods": V2beta2PodsMetricStatusDict,
"resource": V2beta2ResourceMetricStatusDict,
"type": str,
},
total=False,
)
| 33.777778 | 160 | 0.761513 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 158 | 0.259868 |
e8424a7118017635f1b1c7ef3d7daf970569e6bf | 1,865 | py | Python | tests/test_env_runner.py | pistarlab/simpleland | e1d5f65ef6ffaf9e32536d46aa3a2526d3b57801 | [
"MIT"
] | 4 | 2021-08-19T21:41:34.000Z | 2022-02-03T00:44:43.000Z | tests/test_env_runner.py | pistarlab/simpleland | e1d5f65ef6ffaf9e32536d46aa3a2526d3b57801 | [
"MIT"
] | null | null | null | tests/test_env_runner.py | pistarlab/simpleland | e1d5f65ef6ffaf9e32536d46aa3a2526d3b57801 | [
"MIT"
] | null | null | null | import pytest
from landia.env import LandiaEnv, LandiaEnvSingle
import time
from landia.clock import clock
def test_env():
agent_map = {str(i):{} for i in range(4)}
env = LandiaEnv(agent_map=agent_map,dry_run=False)
start_time = time.time()
max_steps = 2000
dones = {"__all__":True}
episode_count = 0
actions = {}
all_rewards = []
for i in range(0,max_steps):
if dones.get('__all__'):
obs = env.reset()
rewards, dones, infos = {}, {'__all__':False},{}
episode_count+=1
else:
obs, rewards, dones, infos = env.step(actions)
all_rewards.extend(rewards.values())
actions = {agent_id:env.action_spaces[agent_id].sample() for agent_id in obs.keys()}
steps_per_sec = max_steps/(time.time()-start_time)
print(f"total_rewards {sum(all_rewards)}")
print(f"steps_per_sec {steps_per_sec}")
assert True
def single_run(config_filename=None):
print(f"Running config {config_filename}")
env = LandiaEnvSingle(config_filename=config_filename)
start_time = time.time()
max_steps = 2000
all_rewards = []
done=True
action=None
eps = 0
for i in range(0,max_steps):
if done:
ob = env.reset()
reward, done, info = None, False, {}
eps+=1
else:
ob, reward, done, info = env.step(action)
action = env.action_space.sample()
steps_per_sec = max_steps/(time.time()-start_time)
print(f"eps {eps}")
print(f"total_rewards {sum(all_rewards)}")
print(f"steps_per_sec {steps_per_sec}")
def test_gym_env():
single_run(config_filename="base_config.json")
single_run(config_filename="ctf.json")
single_run(config_filename="infection.json")
single_run(config_filename="forager.json")
assert True | 28.257576 | 92 | 0.631635 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 266 | 0.142627 |
e842c41ef1221729334421753ca406d26117e384 | 8,211 | py | Python | helpers/simulation_helpers/scripts/simulated_robot_driver.py | GT-RAIL/assistance_arbitration | 84d7cfb6e08f0dd23de9fa106264726f19ef82ea | [
"MIT"
] | null | null | null | helpers/simulation_helpers/scripts/simulated_robot_driver.py | GT-RAIL/assistance_arbitration | 84d7cfb6e08f0dd23de9fa106264726f19ef82ea | [
"MIT"
] | 32 | 2018-09-11T12:34:06.000Z | 2020-08-25T19:57:26.000Z | helpers/simulation_helpers/scripts/simulated_robot_driver.py | GT-RAIL/assistance_arbitration | 84d7cfb6e08f0dd23de9fa106264726f19ef82ea | [
"MIT"
] | 2 | 2020-02-21T03:16:41.000Z | 2021-08-01T17:29:43.000Z | #!/usr/bin/env python
# Simulate the /robot_driver so that interfaces to it can operate the same on
# the real robot and in simulation
from __future__ import print_function, division
from threading import Lock
import rospy
import diagnostic_updater
from diagnostic_msgs.msg import DiagnosticStatus
from fetch_driver_msgs.msg import (RobotState, ChargerState, GripperState,
JointState as FetchJointState)
from power_msgs.msg import BreakerState
from sensor_msgs.msg import JointState
from power_msgs.srv import BreakerCommand, BreakerCommandResponse
from std_srvs.srv import Trigger, TriggerResponse
# Helper function to produce diagnostic updaters
def produce_breaker_diagnostic_func(breaker):
def diagnostic_func(stat):
stat.summary(
DiagnosticStatus.OK if breaker.state == BreakerState.STATE_ENABLED else DiagnosticStatus.ERROR,
"Enabled" if breaker.state == BreakerState.STATE_ENABLED else "Disabled"
)
return stat
return diagnostic_func
# This is the class that acts as the stub to the robot driver
class SimulatedRobotDriver(object):
"""
In simulation, implement the minimum amount of logic necessary to correctly
spoof the behaviour of the robot driver
"""
BATTERY_FULL_VOLTAGE = 25
BATTERY_LOW_VOLTAGE = 19.9
BATTERY_FULL_CAPACITY = 133400
BATTERY_LOW_CAPACITY = 6000
BATTERY_CAPACITY_DECAY = 10 # Amount of capacity to lose per second
GRIPPER_JOINT_NAME = 'l_gripper_finger_joint'
def __init__(self):
# Internal parameters for the functions of this driver
self._publish_rate = 50 # Hz rate.
# The state of the arm, gripper, and base breakers
self._arm_breaker_state = BreakerState(
name="arm_breaker",
state=BreakerState.STATE_ENABLED
)
self._base_breaker_state = BreakerState(
name="base_breaker",
state=BreakerState.STATE_ENABLED
)
self._gripper_breaker_state = BreakerState(
name="gripper_breaker",
state=BreakerState.STATE_ENABLED
)
# The cached state of the robot
self._robot_state = RobotState(
ready=True,
breakers=[self._arm_breaker_state, self._base_breaker_state, self._gripper_breaker_state],
charger=ChargerState(
state=0, # Unknown what this actually is
charging_mode=2, # "Not Charging" according to the comments
battery_voltage=SimulatedRobotDriver.BATTERY_FULL_VOLTAGE,
battery_capacity=SimulatedRobotDriver.BATTERY_FULL_CAPACITY
)
)
self._robot_state_lock = Lock()
# The cached state of the gripper
self._gripper_state = GripperState(ready=True)
self._gripper_state.joints.append(FetchJointState(
name="gripper_joint",
control_mode=3, # Based on values on the robot
position=0.05, # Default start position of open
))
self._gripper_state_lock = Lock()
# Create the diagnostic updater
self._updater = diagnostic_updater.Updater()
self._updater.setHardwareID("none")
self._updater.add("arm_breaker", produce_breaker_diagnostic_func(self._arm_breaker_state))
self._updater.add("base_breaker", produce_breaker_diagnostic_func(self._base_breaker_state))
self._updater.add("gripper_breaker", produce_breaker_diagnostic_func(self._gripper_breaker_state))
# Publishers
self._robot_state_publisher = rospy.Publisher('/robot_state', RobotState, queue_size=1)
self._gripper_state_publisher = rospy.Publisher('/gripper_state', GripperState, queue_size=1)
# Subscribers
self._joint_state_sub = rospy.Subscriber('/joint_states', JointState, self._on_joint_state)
# The services to set and reset the breakers
self._arm_breaker_service = rospy.Service("/arm_breaker", BreakerCommand, self.set_arm_breaker)
self._base_breaker_service = rospy.Service("/base_breaker", BreakerCommand, self.set_base_breaker)
self._gripper_breaker_service = rospy.Service("/gripper_breaker", BreakerCommand, self.set_gripper_breaker)
# Simulation service to put the battery into low mode or not
self._battery_low_service = rospy.Service(
"~battery_to_low",
Trigger,
self._on_battery_to_level(
SimulatedRobotDriver.BATTERY_LOW_VOLTAGE, SimulatedRobotDriver.BATTERY_LOW_CAPACITY
)
)
self._battery_nominal_service = rospy.Service(
"~battery_to_nominal",
Trigger,
self._on_battery_to_level(
SimulatedRobotDriver.BATTERY_FULL_VOLTAGE, SimulatedRobotDriver.BATTERY_FULL_CAPACITY
)
)
def _on_joint_state(self, msg):
try:
idx = msg.name.index(SimulatedRobotDriver.GRIPPER_JOINT_NAME)
with self._gripper_state_lock:
self._gripper_state.joints[0].position = msg.position[idx]
self._gripper_state.joints[0].velocity = msg.velocity[idx]
self._gripper_state.joints[0].effort = msg.effort[idx]
except ValueError as e:
pass
def _on_battery_to_level(self, battery_voltage, battery_capacity):
def service_responder(req):
with self._robot_state_lock:
self._robot_state.charger.battery_voltage = battery_voltage
self._robot_state.charger.battery_capacity = battery_capacity
return TriggerResponse(success=True)
return service_responder
def _calculate_robot_state(self):
# Make sure to acquire the lock to the robot state before calling this
# function
self._robot_state.faulted = (
self._arm_breaker_state.state == BreakerState.STATE_DISABLED
or self._base_breaker_state.state == BreakerState.STATE_DISABLED
or self._gripper_breaker_state.state == BreakerState.STATE_DISABLED
)
def set_arm_breaker(self, req):
with self._robot_state_lock:
self._arm_breaker_state.state = BreakerState.STATE_ENABLED if req.enable else BreakerState.STATE_DISABLED
self._calculate_robot_state()
return BreakerCommandResponse(self._arm_breaker_state)
def set_base_breaker(self, req):
with self._robot_state_lock:
self._base_breaker_state.state = BreakerState.STATE_ENABLED if req.enable else BreakerState.STATE_DISABLED
self._calculate_robot_state()
return BreakerCommandResponse(self._base_breaker_state)
def set_gripper_breaker(self, req):
with self._gripper_state_lock:
self._gripper_state.ready = req.enable
self._gripper_state.faulted = not req.enable
with self._robot_state_lock:
self._gripper_breaker_state.state = BreakerState.STATE_ENABLED if req.enable else BreakerState.STATE_DISABLED
self._calculate_robot_state()
return BreakerCommandResponse(self._gripper_breaker_state)
def spin(self):
rate = rospy.Rate(self._publish_rate)
post = rospy.Time.now()
rate.sleep()
while not rospy.is_shutdown():
pre = rospy.Time.now()
with self._robot_state_lock:
self._robot_state.header.stamp = pre
self._robot_state.header.seq += 1
self._robot_state.charger.battery_capacity -= (
SimulatedRobotDriver.BATTERY_CAPACITY_DECAY * (pre - post).to_sec()
)
self._robot_state_publisher.publish(self._robot_state)
with self._gripper_state_lock:
self._gripper_state.header.stamp = pre
self._gripper_state.header.seq += 1
self._gripper_state_publisher.publish(self._gripper_state)
self._updater.update()
post = rospy.Time.now()
rate.sleep()
if __name__ == '__main__':
rospy.init_node('robot_driver')
driver = SimulatedRobotDriver()
driver.spin()
| 40.850746 | 121 | 0.677749 | 6,989 | 0.851175 | 0 | 0 | 0 | 0 | 0 | 0 | 1,274 | 0.155158 |
e8446ce2f4061635de45065908f670220fac78c6 | 3,012 | py | Python | docs/source/conf.py | suzil/awsstepfuncs | dd195b54bf8eaa381ea07244b276db6a1e82007b | [
"MIT"
] | 3 | 2020-11-29T18:31:50.000Z | 2021-01-14T07:46:40.000Z | docs/source/conf.py | suzil/aws-step-functions | dd195b54bf8eaa381ea07244b276db6a1e82007b | [
"MIT"
] | 54 | 2020-10-17T13:30:05.000Z | 2020-10-28T01:46:59.000Z | docs/source/conf.py | suzil/aws-step-functions | dd195b54bf8eaa381ea07244b276db6a1e82007b | [
"MIT"
] | 1 | 2021-08-04T04:40:27.000Z | 2021-08-04T04:40:27.000Z | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import sys
from pathlib import Path
import sphinx_rtd_theme # noqa: F401
from sphinx.ext import apidoc
from awsstepfuncs import __version__
current_dir = Path(__file__).parent.absolute()
base_dir = current_dir.parents[1]
code_dir = base_dir / "src" / "awsstepfuncs"
sys.path.insert(0, str(code_dir))
readme_dest = current_dir / "README.md"
readme_src = base_dir / "README.md"
if readme_dest.exists():
readme_dest.unlink()
readme_dest.symlink_to(readme_src)
# -- Project information -----------------------------------------------------
project = "awsstepfuncs"
author = "Susannah Klaneček"
copyright = "Susannah Klaneček" # noqa: A001
# The full version, including alpha/beta/rc tags
release = __version__
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"recommonmark",
"sphinx_markdown_tables",
"sphinx_rtd_theme",
"sphinx.ext.autodoc",
"sphinx.ext.coverage",
"sphinx.ext.napoleon",
]
autodoc_typehints = "description"
# recommonmark extension allows mixed filetypes
source_suffix = [".rst", ".md"]
# Add any paths that contain templates here, relative to this directory.
# templates_path = ["_templates"]
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "sphinx_rtd_theme"
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ["_static"]
def run_apidoc(_):
exclude = []
argv = [
"--doc-project",
"Code Reference",
"-M",
"-f",
"-d",
"3",
"--tocfile",
"index",
"-o",
str(current_dir / "_code_reference"),
str(code_dir),
] + exclude
apidoc.main(argv)
def setup(app):
app.connect("builder-inited", run_apidoc)
| 28.415094 | 79 | 0.658367 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,080 | 0.690113 |
e8449bc93dc7b2136a3c89b249e0217f67fedec5 | 723 | py | Python | day-07.py | analuisadev/100-Days-Of-Code | b1dafabc335cd2c3c9b1cecd50597b42d8959d4a | [
"MIT"
] | 2 | 2021-01-08T22:13:21.000Z | 2021-03-17T10:44:12.000Z | day-07.py | analuisadev/100-Days-Of-Code | b1dafabc335cd2c3c9b1cecd50597b42d8959d4a | [
"MIT"
] | null | null | null | day-07.py | analuisadev/100-Days-Of-Code | b1dafabc335cd2c3c9b1cecd50597b42d8959d4a | [
"MIT"
] | null | null | null | from random import randint
from time import sleep
print ('=' * 18)
print ('\033[1mSTONE PAPER AND SCISSORS\033[m')
print ('=' * 18)
print ('I already chose mine now missing you')
sleep (1)
computer = randint (1, 3)
player = int(input('\033[1mChoose between\033[m \033[1;33m1) Stone 2) Paper and 3) Scissors\033[m : '))
sleep(1)
if (player < computer):
print ('\033[1;33mThought about {}\033[m'.format(computer))
print ('\033[1;32mI WIN HEHE :D\033[m')
elif (player == computer):
print ('\033[1;33mThought about {}\033[m'.format(computer))
print ('\033[1;31mTIE, LET´S GO AGAIN\033[m')
else:
print ('\033[1;33mThought about {}\033[m'.format(computer))
print ('\033[1;36mYOUR LOST HAHAHA:D\033[m ')
| 36.15 | 104 | 0.658368 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 374 | 0.516575 |
e84512b0da871bd7cbe1284df91d047dbdd1a5e5 | 303 | py | Python | tmdb/three/reviews.py | Cologler/ezapi-tmdb | 6a8a1a0a3da99cb18d11f47f1b40bbffb2a16be6 | [
"MIT"
] | 4 | 2017-05-16T02:30:52.000Z | 2021-07-01T13:21:27.000Z | tmdb/three/reviews.py | Cologler/ezapi-tmdb | 6a8a1a0a3da99cb18d11f47f1b40bbffb2a16be6 | [
"MIT"
] | 4 | 2020-09-03T03:19:49.000Z | 2021-12-21T05:24:04.000Z | tmdb/three/reviews.py | Cologler/ezapi-tmdb | 6a8a1a0a3da99cb18d11f47f1b40bbffb2a16be6 | [
"MIT"
] | 3 | 2021-02-15T18:13:08.000Z | 2021-04-10T03:53:58.000Z | from .base import ENDPOINT, process_response
class ReviewsMixin:
@process_response
def get_review_details(self, review_id, **kwargs):
"""
GET /review/{review_id}
"""
url = f"{ENDPOINT}/3/review/{review_id}"
return self.make_request("GET", url, kwargs)
| 23.307692 | 54 | 0.630363 | 255 | 0.841584 | 0 | 0 | 231 | 0.762376 | 0 | 0 | 86 | 0.283828 |
e8459f0fc13fb8e816c864fc35cd8a3cb0f01468 | 739 | py | Python | app/models/domain/position.py | Chaoyingz/paper_trading | cd3af81c932e8f4b1586f2b9bf86b5b252bec896 | [
"MIT"
] | null | null | null | app/models/domain/position.py | Chaoyingz/paper_trading | cd3af81c932e8f4b1586f2b9bf86b5b252bec896 | [
"MIT"
] | null | null | null | app/models/domain/position.py | Chaoyingz/paper_trading | cd3af81c932e8f4b1586f2b9bf86b5b252bec896 | [
"MIT"
] | null | null | null | from datetime import datetime
from pydantic import Field
from app.models.base import DBModelMixin
from app.models.domain.stocks import Stock
from app.models.types import PyDecimal, PyObjectId
class Position(Stock):
"""持仓股票"""
volume: int = Field(..., description="持仓量")
available_volume: int = Field(..., description="可用量")
cost: PyDecimal = Field(..., description="持仓成本")
current_price: PyDecimal = Field(..., description="当前价格")
profit: PyDecimal = Field(..., description="利润")
first_buy_date: datetime = Field(None, description="首次持有日期")
last_sell_date: datetime = Field(None, description="最后卖出日期")
class PositionInDB(DBModelMixin, Position):
user: PyObjectId = Field(..., description="用户ID")
| 30.791667 | 64 | 0.711773 | 607 | 0.752169 | 0 | 0 | 0 | 0 | 0 | 0 | 126 | 0.156134 |
e845a7e7d6017dc01966f517fbcf29e5fc29bd30 | 2,644 | py | Python | drink_partners/middlewares/tests/test_exception_handler.py | henriquebraga/drink-partners | 4702263ae3e43ea9403cff5a72b68245d61880c7 | [
"Apache-2.0"
] | null | null | null | drink_partners/middlewares/tests/test_exception_handler.py | henriquebraga/drink-partners | 4702263ae3e43ea9403cff5a72b68245d61880c7 | [
"Apache-2.0"
] | 22 | 2020-05-02T19:32:24.000Z | 2021-10-17T21:19:46.000Z | drink_partners/middlewares/tests/test_exception_handler.py | henriquebraga/drink-partners | 4702263ae3e43ea9403cff5a72b68245d61880c7 | [
"Apache-2.0"
] | null | null | null | import json
import pytest
from aiohttp.web import HTTPGatewayTimeout
from drink_partners.contrib.exceptions import APIException
from drink_partners.contrib.response import JSONResponse
from drink_partners.middlewares.exception_handler import (
exception_handler_middleware
)
httperror_message = 'Http error message'
async def success_handler(request):
return JSONResponse(data={'data': 'data'}, status=200)
async def api_exception_handler(request):
raise APIException()
async def http_error_handler(request):
raise HTTPGatewayTimeout(reason=httperror_message)
async def unexpected_error_handler(request):
raise Exception()
class TestExceptionHandlerMiddleware:
@pytest.fixture
def request_fixture(self, make_request):
return make_request(
method='get',
url='https://www.zedelivery.com.br/',
)
async def test_returns_the_response_on_success(
self,
request_fixture
):
response = await exception_handler_middleware(
request=request_fixture,
handler=success_handler
)
assert response.status == 200
content = json.loads(response.text)
assert content == {'data': 'data'}
async def test_returns_the_error_data_on_api_exception(
self,
request_fixture
):
response = await exception_handler_middleware(
request=request_fixture,
handler=api_exception_handler
)
assert response.status == APIException.status_code
content = json.loads(response.text)
assert content['error_code'] == APIException.error_code
assert content['error_message'] == APIException.error_message
async def test_returns_the_error_data_for_httperror(self, request_fixture):
response = await exception_handler_middleware(
request=request_fixture,
handler=http_error_handler
)
assert response.status == HTTPGatewayTimeout.status_code
content = json.loads(response.text)
assert content['error_code'] == 'unexpected_error'
assert content['error_message'] == httperror_message
async def test_supress_exception_and_returns_generic_data(
self,
request_fixture
):
response = await exception_handler_middleware(
request=request_fixture,
handler=unexpected_error_handler
)
assert response.status == 500
content = json.loads(response.text)
assert content['error_code'] == 'unexpected_error'
assert content['error_message'] == 'Internal server error'
| 28.430108 | 79 | 0.693268 | 1,987 | 0.751513 | 0 | 0 | 175 | 0.066188 | 2,064 | 0.780635 | 221 | 0.083585 |
e84653cc7074215f83e285dd13f1f44ac93d694e | 899 | py | Python | tase/telegram/inline_buttons/choose_language_button.py | soran-ghaderi/Chromusic_search_engine | e811401fee39ff4cb184750fcbde55053c69453d | [
"Apache-2.0"
] | 4 | 2022-02-21T06:56:16.000Z | 2022-03-07T21:10:19.000Z | tase/telegram/inline_buttons/choose_language_button.py | soran-ghaderi/Chromusic_search_engine | e811401fee39ff4cb184750fcbde55053c69453d | [
"Apache-2.0"
] | null | null | null | tase/telegram/inline_buttons/choose_language_button.py | soran-ghaderi/Chromusic_search_engine | e811401fee39ff4cb184750fcbde55053c69453d | [
"Apache-2.0"
] | 1 | 2022-03-07T21:10:02.000Z | 2022-03-07T21:10:02.000Z | import pyrogram
from .inline_button import InlineButton
from ..telegram_client import TelegramClient
# from ..handlers import BaseHandler
from ...db import DatabaseClient, graph_models
from ...utils import _trans
class ChooseLanguageInlineButton(InlineButton):
name = "choose_language"
def on_callback_query(
self,
client: 'pyrogram.Client',
callback_query: 'pyrogram.types.CallbackQuery',
handler: 'BaseHandler',
db: 'DatabaseClient',
telegram_client: 'TelegramClient',
db_from_user: graph_models.vertices.User
):
controller, data = callback_query.data.split('->')
db.update_user_chosen_language(db_from_user, data)
text = _trans("Language change has been saved", lang_code=data)
callback_query.answer(text, show_alert=False)
callback_query.message.delete()
| 33.296296 | 71 | 0.68743 | 682 | 0.758621 | 0 | 0 | 0 | 0 | 0 | 0 | 181 | 0.201335 |
e84af8b6f01102abd58e768944863261e63306d5 | 565 | py | Python | blog/forms.py | Ukyply/Ukyply-SQLite | 3c1c550b32b2f969c8964f806bf8578fbeeb7d4b | [
"MIT"
] | null | null | null | blog/forms.py | Ukyply/Ukyply-SQLite | 3c1c550b32b2f969c8964f806bf8578fbeeb7d4b | [
"MIT"
] | null | null | null | blog/forms.py | Ukyply/Ukyply-SQLite | 3c1c550b32b2f969c8964f806bf8578fbeeb7d4b | [
"MIT"
] | null | null | null | from django import forms
from blog.models import Post
class PostForm(forms.ModelForm):
class Meta:
model= Post
fields = ('title','text')
labels = {
'title':'Söz Başy',
'text':'Hat',
}
def save_form(self, request, instance, form, change):
user = request.user
instance = form.save(commit=False)
if not change or not instance.author:
instance.author = user
instance.modified_by = user
instance.save()
form.save_m2m()
return instance
| 24.565217 | 57 | 0.569912 | 511 | 0.901235 | 0 | 0 | 0 | 0 | 0 | 0 | 43 | 0.075838 |
e84b2f2fe83a3e28896f1f56e30847e498d1d2a1 | 648 | py | Python | rules/tamper/wordpress.py | lavon321/Kunlun-M | 792548536d67f648c92324ecc153d7f206623e31 | [
"MIT"
] | 1,059 | 2020-08-06T13:32:10.000Z | 2022-03-31T07:20:27.000Z | rules/tamper/wordpress.py | lavon321/Kunlun-M | 792548536d67f648c92324ecc153d7f206623e31 | [
"MIT"
] | 87 | 2020-09-08T06:34:45.000Z | 2022-03-28T05:52:36.000Z | rules/tamper/wordpress.py | lavon321/Kunlun-M | 792548536d67f648c92324ecc153d7f206623e31 | [
"MIT"
] | 171 | 2020-08-13T11:53:47.000Z | 2022-03-30T03:23:07.000Z | # -*- coding: utf-8 -*-
"""
wordpress
~~~~
tamper for wordpress
:author: LoRexxar <LoRexxar@gmail.com>
:homepage: https://github.com/LoRexxar/Kunlun-M
:license: MIT, see LICENSE for more details.
:copyright: Copyright (c) 2017 LoRexxar. All rights reserved
"""
wordpress = {
"esc_url": [1000, 10001, 10002],
"esc_js": [1000, 10001, 10002],
"esc_html": [1000, 10001, 10002],
"esc_attr": [1000, 10001, 10002],
"esc_textarea": [1000, 10001, 10002],
"tag_escape": [1000, 10001, 10002],
"esc_sql": [1004, 1005, 1006],
"_real_escape": [1004, 1005, 1006],
}
wordpress_controlled = [] | 24 | 64 | 0.606481 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 381 | 0.587963 |
e84d152037bd2e3dced364c3e47b92c7a6bfda36 | 210 | py | Python | tests/test_utils.py | szarnyasg/pygraphblas | 7465ef6fcc77c9901869b70ddf1d77a86570c336 | [
"Apache-2.0"
] | null | null | null | tests/test_utils.py | szarnyasg/pygraphblas | 7465ef6fcc77c9901869b70ddf1d77a86570c336 | [
"Apache-2.0"
] | null | null | null | tests/test_utils.py | szarnyasg/pygraphblas | 7465ef6fcc77c9901869b70ddf1d77a86570c336 | [
"Apache-2.0"
] | null | null | null | from pygraphblas import *
def test_add_identity():
A = Matrix.sparse(INT8, 10, 10)
assert add_identity(A) == 10
A = Matrix.sparse(INT8, 10, 10)
A[5,5] = 42
assert add_identity(A) == 9
| 21 | 35 | 0.614286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
e84d4a5decc6c49e64831cb5acb6bf62262b9049 | 276 | py | Python | bentoml/paddle.py | francoisserra/BentoML | 213e9e9b39e055286f2649c733907df88e6d2503 | [
"Apache-2.0"
] | 1 | 2021-06-12T17:04:07.000Z | 2021-06-12T17:04:07.000Z | bentoml/paddle.py | francoisserra/BentoML | 213e9e9b39e055286f2649c733907df88e6d2503 | [
"Apache-2.0"
] | 4 | 2021-05-16T08:06:25.000Z | 2021-11-13T08:46:36.000Z | bentoml/paddle.py | francoisserra/BentoML | 213e9e9b39e055286f2649c733907df88e6d2503 | [
"Apache-2.0"
] | null | null | null | from ._internal.frameworks.paddle import load
from ._internal.frameworks.paddle import save
from ._internal.frameworks.paddle import load_runner
from ._internal.frameworks.paddle import import_from_paddlehub
__all__ = ["import_from_paddlehub", "load", "load_runner", "save"]
| 39.428571 | 66 | 0.822464 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 48 | 0.173913 |
e84dcacd54181e2d83fb3b996dbdf8ae1ae4b89c | 1,649 | py | Python | src/leetcode_1673_find_the_most_competitive_subsequence.py | yurirocha15/coding_practice | 952506932c47414da689454853ee745637413160 | [
"MIT"
] | 2 | 2020-12-08T13:59:10.000Z | 2021-05-01T05:07:39.000Z | src/leetcode_1673_find_the_most_competitive_subsequence.py | yurirocha15/coding_practice | 952506932c47414da689454853ee745637413160 | [
"MIT"
] | null | null | null | src/leetcode_1673_find_the_most_competitive_subsequence.py | yurirocha15/coding_practice | 952506932c47414da689454853ee745637413160 | [
"MIT"
] | 1 | 2021-05-02T17:42:02.000Z | 2021-05-02T17:42:02.000Z | # @l2g 1673 python3
# [1673] Find the Most Competitive Subsequence
# Difficulty: Medium
# https://leetcode.com/problems/find-the-most-competitive-subsequence
#
# Given an integer array nums and a positive integer k,
# return the most competitive subsequence of nums of size k.
# An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.
# We define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ,
# subsequence a has a number less than the corresponding number in b.For example,[1,3,
# 4] is more competitive than [1,3,5] because the first position they differ is at the final number,
# and 4 is less than 5.
#
# Example 1:
#
# Input: nums = [3,5,2,6], k = 2
# Output: [2,6]
# Explanation: Among the set of every possible subsequence: {[3,5],[3,2],[3,6],[5,2],[5,6],[2,6]},[2,
# 6] is the most competitive.
#
# Example 2:
#
# Input: nums = [2,4,3,3,5,4,9,6], k = 4
# Output: [2,3,3,4]
#
#
# Constraints:
#
# 1 <= nums.length <= 10^5
# 0 <= nums[i] <= 10^9
# 1 <= k <= nums.length
#
#
from typing import List
class Solution:
def mostCompetitive(self, nums: List[int], k: int) -> List[int]:
ret = nums[:k]
n = len(nums)
j = 1
for i, num in enumerate(nums[1:], 1):
while j > 0 and num < ret[j - 1] and ((n - i) >= (k - j + 1)):
j -= 1
if j < k:
ret[j] = num
j += 1
return ret
if __name__ == "__main__":
import os
import pytest
pytest.main([os.path.join("tests", "test_1673.py")])
| 28.431034 | 141 | 0.614918 | 380 | 0.230443 | 0 | 0 | 0 | 0 | 0 | 0 | 1,119 | 0.678593 |
e84df9dae610f2465c8309e92c32430fc6ed2e22 | 1,955 | py | Python | data/compress.py | Catosine/GDAS | da047fe30b5aeeb1121861458ad61fd7c171874e | [
"MIT"
] | 20 | 2019-10-10T07:13:27.000Z | 2022-03-25T11:33:16.000Z | data/compress.py | BaiYuYuan/GDAS | 5eed8101a78d223a20a43494176051298b24ac3a | [
"MIT"
] | null | null | null | data/compress.py | BaiYuYuan/GDAS | 5eed8101a78d223a20a43494176051298b24ac3a | [
"MIT"
] | 6 | 2020-04-21T14:52:02.000Z | 2021-08-05T15:00:22.000Z | # python ./data/compress.py $TORCH_HOME/ILSVRC2012/ $TORCH_HOME/ILSVRC2012-TAR tar
# python ./data/compress.py $TORCH_HOME/ILSVRC2012/ $TORCH_HOME/ILSVRC2012-ZIP zip
import os, sys
from pathlib import Path
def command(prefix, cmd):
print ('{:}{:}'.format(prefix, cmd))
os.system(cmd)
def main(source, destination, xtype):
assert source.exists(), '{:} does not exist'.format(source)
assert (source/'train').exists(), '{:}/train does not exist'.format(source)
assert (source/'val' ).exists(), '{:}/val does not exist'.format(source)
source = source.resolve()
destination = destination.resolve()
destination.mkdir(parents=True, exist_ok=True)
os.system('rm -rf {:}'.format(destination))
destination.mkdir(parents=True, exist_ok=True)
(destination/'train').mkdir(parents=True, exist_ok=True)
subdirs = list( (source / 'train').glob('n*') )
assert len(subdirs) == 1000, 'ILSVRC2012 should contain 1000 classes instead of {:}.'.format( len(subdirs) )
if xtype == 'tar' : command('', 'tar -cf {:} -C {:} val'.format(destination/'val.tar', source))
elif xtype == 'zip': command('', '(cd {:} ; zip -r {:} val)'.format(source, destination/'val.zip'))
else: raise ValueError('invalid compress type : {:}'.format(xtype))
for idx, subdir in enumerate(subdirs):
name = subdir.name
if xtype == 'tar' : command('{:03d}/{:03d}-th: '.format(idx, len(subdirs)), 'tar -cf {:} -C {:} {:}'.format(destination/'train'/'{:}.tar'.format(name), source / 'train', name))
elif xtype == 'zip': command('{:03d}/{:03d}-th: '.format(idx, len(subdirs)), '(cd {:}; zip -r {:} {:})'.format(source / 'train', destination/'train'/'{:}.zip'.format(name), name))
else: raise ValueError('invalid compress type : {:}'.format(xtype))
if __name__ == '__main__':
assert len(sys.argv) == 4, 'invalid argv : {:}'.format(sys.argv)
source, destination = Path(sys.argv[1]), Path(sys.argv[2])
main(source, destination, sys.argv[3])
| 50.128205 | 183 | 0.652174 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 659 | 0.337084 |
e84e6fa0496c3c3dbf9e461be30523e0845b42ec | 2,920 | py | Python | tests/test_fastly_logging_s3.py | Jimdo/ansible-role-fastly | c2e2675c052c9e9a7542e8d51410632a0fbae4d0 | [
"MIT"
] | 12 | 2016-06-17T15:51:10.000Z | 2021-01-22T09:15:52.000Z | tests/test_fastly_logging_s3.py | Jimdo/ansible-role-fastly | c2e2675c052c9e9a7542e8d51410632a0fbae4d0 | [
"MIT"
] | 20 | 2016-06-17T15:46:12.000Z | 2018-06-01T07:43:49.000Z | tests/test_fastly_logging_s3.py | Jimdo/ansible-role-fastly | c2e2675c052c9e9a7542e8d51410632a0fbae4d0 | [
"MIT"
] | 12 | 2016-06-17T15:51:00.000Z | 2022-03-18T18:17:17.000Z | #!/usr/bin/env python
import os
import unittest
import sys
from test_common import TestCommon
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'library'))
from fastly_service import FastlyConfiguration
class TestFastlyLoggingS3(TestCommon):
@TestCommon.vcr.use_cassette()
def test_fastly_s3s(self):
s3s_configuration = self.minimal_configuration.copy()
s3s_configuration.update({
's3s': [{
'name' : 'test_s3',
'domain' : self.FASTLY_TEST_DOMAIN,
'secret_key' : 'SECRET',
'period' : 60,
'bucket_name' : 'prod-fastly-logs',
'timestamp_format' : '%Y-%m-%dT%H:%M:%S.000',
'redundancy' : 'standard',
'access_key' : 'ACCESS_KEY',
'format' : '%{%Y-%m-%dT%H:%S.000}t %h "%r" %>s %b',
}],
})
configuration = FastlyConfiguration(s3s_configuration)
service = self.enforcer.apply_configuration(self.FASTLY_TEST_SERVICE, configuration).service
svc_conf = service.active_version.configuration
self.assertEqual(svc_conf.s3s[0].name, 'test_s3')
self.assertEqual(svc_conf.s3s[0].domain, self.FASTLY_TEST_DOMAIN)
self.assertEqual(svc_conf.s3s[0].secret_key, 'SECRET')
self.assertEqual(svc_conf.s3s[0].period, 60)
self.assertEqual(svc_conf.s3s[0].bucket_name, 'prod-fastly-logs')
self.assertEqual(svc_conf.s3s[0].timestamp_format, '%Y-%m-%dT%H:%M:%S.000')
self.assertEqual(svc_conf.s3s[0].redundancy, 'standard')
self.assertEqual(svc_conf.s3s[0].access_key, 'ACCESS_KEY')
self.assertEqual(svc_conf.s3s[0].format, '%{%Y-%m-%dT%H:%S.000}t %h "%r" %>s %b')
self.assertEqual(svc_conf, configuration)
active_version_number = service.active_version.number
service = self.enforcer.apply_configuration(self.FASTLY_TEST_SERVICE, configuration).service
self.assertEqual(service.active_version.number, active_version_number)
@TestCommon.vcr.use_cassette()
def test_fastly_s3s_remove(self):
s3s_configuration = self.minimal_configuration.copy()
s3s_configuration.update({
's3': [{
'name' : 'test_s3',
}],
})
configuration = FastlyConfiguration(s3s_configuration)
# Configure S3 logging
self.enforcer.apply_configuration(self.FASTLY_TEST_SERVICE, configuration).service
# Now apply a configuration without S3 logging
service = self.enforcer.apply_configuration(self.FASTLY_TEST_SERVICE, FastlyConfiguration(self.minimal_configuration.copy())).service
svc_conf = service.active_version.configuration
self.assertEqual(svc_conf.s3s, [])
if __name__ == '__main__':
unittest.main()
| 40 | 141 | 0.630137 | 2,651 | 0.907877 | 0 | 0 | 2,601 | 0.890753 | 0 | 0 | 471 | 0.161301 |
e84e84870d1e2d1d36aeaad23e19573cd282d144 | 1,230 | py | Python | 高频120_Lint/Reverse Nodes in k-Group.py | lixiaoruiusa/Rui7272 | fbdb87104353138d3af7f3fe2cb3c0f00ff9e449 | [
"MIT"
] | null | null | null | 高频120_Lint/Reverse Nodes in k-Group.py | lixiaoruiusa/Rui7272 | fbdb87104353138d3af7f3fe2cb3c0f00ff9e449 | [
"MIT"
] | null | null | null | 高频120_Lint/Reverse Nodes in k-Group.py | lixiaoruiusa/Rui7272 | fbdb87104353138d3af7f3fe2cb3c0f00ff9e449 | [
"MIT"
] | null | null | null | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: a ListNode
@param k: An integer
@return: a ListNode
@ O(n) time | O(1) space
"""
def reverseKGroup(self, head, k):
dummy = jump = ListNode(0)
dummy.next = left = right = head
while True:
count = 0
while right and count < k: # use r to locate the range
right = right.next
count += 1
if count == k: # if size k satisfied, reverse the inner linked list
pre = right
cur = left
for _ in range(k):
cur.next = pre
cur = cur.next
pre = cur # standard reversing
jump.next = pre
jump = left
left = right # connect two k-groups
else:
return dummy.next
'''
def reverseList(self, head):
prev = None
curr = head
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
''' | 21.964286 | 80 | 0.471545 | 886 | 0.720325 | 0 | 0 | 0 | 0 | 0 | 0 | 576 | 0.468293 |
e84f7ec1d7eb75e5b190a746b5e84c8c1dc54889 | 241 | py | Python | C21/test.py | jpch89/learningpython | 47e78041e519ecd2e00de1b32f6416b56ce2616c | [
"MIT"
] | 2 | 2020-10-20T10:18:48.000Z | 2020-12-02T09:41:18.000Z | C21/test.py | jpch89/learningpython | 47e78041e519ecd2e00de1b32f6416b56ce2616c | [
"MIT"
] | null | null | null | C21/test.py | jpch89/learningpython | 47e78041e519ecd2e00de1b32f6416b56ce2616c | [
"MIT"
] | 1 | 2020-12-02T10:03:29.000Z | 2020-12-02T10:03:29.000Z | '求平方根'
from math import sqrt
li = [2, 4, 9, 16, 25]
# for 循环版本
res = []
for i in li:
res.append(sqrt(i))
print(res)
# map 版本
print(list(map(sqrt, li)))
# 列表推导式版本
print([sqrt(i) for i in li])
# 生成器版本
print(list(sqrt(i) for i in li))
| 12.05 | 32 | 0.605809 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 84 | 0.294737 |
e84fc770fc649fef802bd411dc55a7c207a9b6f1 | 1,981 | py | Python | tests/links_tests/model_tests/yolo_tests/test_yolo_v3.py | souravsingh/chainercv | 8f76510472bc95018c183e72f37bc6c34a89969c | [
"MIT"
] | 1,600 | 2017-06-01T15:37:52.000Z | 2022-03-09T08:39:09.000Z | tests/links_tests/model_tests/yolo_tests/test_yolo_v3.py | souravsingh/chainercv | 8f76510472bc95018c183e72f37bc6c34a89969c | [
"MIT"
] | 547 | 2017-06-01T06:43:16.000Z | 2021-05-28T17:14:05.000Z | tests/links_tests/model_tests/yolo_tests/test_yolo_v3.py | souravsingh/chainercv | 8f76510472bc95018c183e72f37bc6c34a89969c | [
"MIT"
] | 376 | 2017-06-02T01:29:10.000Z | 2022-03-13T11:19:59.000Z | import numpy as np
import unittest
import chainer
from chainer import testing
from chainer.testing import attr
from chainercv.links import YOLOv3
@testing.parameterize(*testing.product({
'n_fg_class': [1, 5, 20],
}))
class TestYOLOv3(unittest.TestCase):
def setUp(self):
self.link = YOLOv3(n_fg_class=self.n_fg_class)
self.insize = 416
self.n_bbox = (13 * 13 + 26 * 26 + 52 * 52) * 3
def _check_call(self):
x = self.link.xp.array(
np.random.uniform(-1, 1, size=(1, 3, self.insize, self.insize)),
dtype=np.float32)
locs, objs, confs = self.link(x)
self.assertIsInstance(locs, chainer.Variable)
self.assertIsInstance(locs.array, self.link.xp.ndarray)
self.assertEqual(locs.shape, (1, self.n_bbox, 4))
self.assertIsInstance(objs, chainer.Variable)
self.assertIsInstance(objs.array, self.link.xp.ndarray)
self.assertEqual(objs.shape, (1, self.n_bbox))
self.assertIsInstance(confs, chainer.Variable)
self.assertIsInstance(confs.array, self.link.xp.ndarray)
self.assertEqual(confs.shape, (1, self.n_bbox, self.n_fg_class))
@attr.slow
def test_call_cpu(self):
self._check_call()
@attr.gpu
@attr.slow
def test_call_gpu(self):
self.link.to_gpu()
self._check_call()
@testing.parameterize(*testing.product({
'n_fg_class': [None, 10, 20],
'pretrained_model': ['voc0712'],
}))
class TestYOLOv3Pretrained(unittest.TestCase):
@attr.slow
def test_pretrained(self):
kwargs = {
'n_fg_class': self.n_fg_class,
'pretrained_model': self.pretrained_model,
}
if self.pretrained_model == 'voc0712':
valid = self.n_fg_class in {None, 20}
if valid:
YOLOv3(**kwargs)
else:
with self.assertRaises(ValueError):
YOLOv3(**kwargs)
testing.run_module(__name__, __file__)
| 26.413333 | 76 | 0.631499 | 1,595 | 0.805149 | 0 | 0 | 1,786 | 0.901565 | 0 | 0 | 90 | 0.045432 |
e8507d06490cbd085cac36479e442057aa3863d2 | 28,595 | py | Python | src/training/train.py | KinanZ/open_clip | 6e76ee3b3a15ee6c4a187853fd123c967721c32b | [
"MIT"
] | null | null | null | src/training/train.py | KinanZ/open_clip | 6e76ee3b3a15ee6c4a187853fd123c967721c32b | [
"MIT"
] | null | null | null | src/training/train.py | KinanZ/open_clip | 6e76ee3b3a15ee6c4a187853fd123c967721c32b | [
"MIT"
] | null | null | null | import os
import time
import json
import numpy as np
import torch
import torch.nn as nn
from sklearn import decomposition
from torch.cuda.amp import autocast
import torch.distributed as dist
import sys
sys.path.append('/misc/student/alzouabk/Thesis/self_supervised_pretraining/open_clip_thesis/src/')
from training.zero_shot import zero_shot_eval
import pdb
import wandb
import logging
def is_master(args):
return (not args.distributed) or args.gpu == 0
def get_weights(labels, class_weights):
weights = torch.ones(labels.shape[0])
for i in range(labels.shape[0]):
sample_label = torch.where(labels[i])[0]
sample_weights = []
for class_label in sample_label:
sample_weights.append(class_weights[class_label.item()])
weights[i] = max(sample_weights)
return weights
def get_loss(model, images, loss_img, loss_txt, class_weights, texts, labels, args):
image_features, text_features, logit_scale = model(images, texts)
logit_scale = logit_scale.mean()
if args.distributed and args.aggregate:
world_size = dist.get_world_size()
rank = dist.get_rank()
# We gather tensors from all gpus to get more negatives to contrast with.
gathered_image_features = [
torch.zeros_like(image_features) for _ in range(world_size)
]
gathered_text_features = [
torch.zeros_like(text_features) for _ in range(world_size)
]
gathered_labels = [
torch.zeros_like(labels) for _ in range(world_size)
]
dist.all_gather(gathered_image_features, image_features)
dist.all_gather(gathered_text_features, text_features)
dist.all_gather(gathered_labels, labels)
all_image_features = torch.cat(
[image_features]
+ gathered_image_features[:rank]
+ gathered_image_features[rank + 1:]
)
all_text_features = torch.cat(
[text_features]
+ gathered_text_features[:rank]
+ gathered_text_features[rank + 1:]
)
labels = torch.cat(
[labels]
+ gathered_labels[:rank]
+ gathered_labels[rank + 1:]
)
if args.new_model:
gathered_texts = [torch.zeros_like(texts['input_ids']) for _ in range(world_size)]
dist.all_gather(gathered_texts, texts['input_ids'])
texts = torch.cat(
[texts['input_ids']]
+ gathered_texts[:rank]
+ gathered_texts[rank + 1:]
)
else:
gathered_texts = [torch.zeros_like(texts) for _ in range(world_size)]
dist.all_gather(gathered_texts, texts)
texts = torch.cat(
[texts]
+ gathered_texts[:rank]
+ gathered_texts[rank + 1:]
)
# this is needed to send gradients back everywhere.
logits_per_image = logit_scale * all_image_features @ all_text_features.t()
logits_per_text = logits_per_image.t()
else:
logits_per_image = logit_scale * image_features @ text_features.t()
logits_per_text = logit_scale * text_features @ image_features.t()
if args.Label_grouped: # Basically supervised
ground_truth = torch.zeros(logits_per_image.shape).float()
for i in range(len(logits_per_image)):
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(labels[i], labels[j])]
ground_truth[i][mask_same] = 1
elif args.Healthy_grouped:
ground_truth = torch.eye(len(logits_per_image)).float() # logits_per_image.shape = logits_per_text.shape = ground_truth.shape = batchsize x batchsize
for i in range(len(logits_per_image)):
# instead of an eye matrix we have 1 on the diagonal and 1 if the sample from this column belongs to the healthy class
if labels[i][0] == 1:
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(labels[i], labels[j])]
ground_truth[i][mask_same] = 1
elif args.Healthy_Caption_grouped:
ground_truth = torch.eye(len(logits_per_image)).float() # logits_per_image.shape = logits_per_text.shape = ground_truth.shape = batchsize x batchsize
for i in range(len(logits_per_image)):
if labels[i][0] == 1:
# replace 0 with 1 if the sample from this column belongs the healthy class
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(labels[i], labels[j])]
ground_truth[i][mask_same] = 1
else:
# replace 0 with 1 if the sample from this column belongs the same deseased class and have the same caption
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(texts[i], texts[j])]
ground_truth[i][mask_same] = 1
elif args.Caption_grouped:
ground_truth = torch.eye(len(logits_per_image)).float() # logits_per_image.shape = logits_per_text.shape = ground_truth.shape = batchsize x batchsize
for i in range(len(logits_per_image)):
# replace 0 with 1 if the sample from this column belongs the same class and have the same caption
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(texts[i], texts[j])]
ground_truth[i][mask_same] = 1
else: # Default Clip loss
ground_truth = torch.arange(len(logits_per_image)).long()
weights = get_weights(labels, class_weights)
if args.gpu is not None:
ground_truth = ground_truth.cuda(args.gpu, non_blocking=True)
weights = weights.cuda(args.gpu, non_blocking=True)
loss_vision = loss_img(logits_per_image, ground_truth)
loss_vision = (loss_vision * weights).mean()
loss_text = loss_txt(logits_per_text, ground_truth)
loss_text = (loss_text * weights).mean()
total_loss = (loss_vision + loss_text) / 2
return total_loss
def train(model, data, epoch, optimizer, scaler, scheduler, args, tb_writer=None):
os.environ["WDS_EPOCH"] = str(epoch)
model.train()
dataloader, sampler = data['train'].dataloader, data['train'].sampler
if args.default_loss:
loss_img = nn.CrossEntropyLoss(reduction='none')
loss_txt = nn.CrossEntropyLoss(reduction='none')
else:
loss_img = nn.BCEWithLogitsLoss(reduction='none')
loss_txt = nn.BCEWithLogitsLoss(reduction='none')
if args.use_weights_1:
# class weights where the weight of a class is: 1 - (class_count / total_count)
class_weights = {0: 0.5, 1: 0.995, 2: 0.927, 3: 0.964, 4: 0.989, 5: 0.994, 6: 0.993, 7: 0.997,
8: 0.856, 9: 0.903, 10: 0.998, 11: 0.879, 12: 0.9984, 13: 0.972, 14: 0.988}
elif args.use_weights_2:
# class weights where the weight of a class is: total_count - (num_of_classes / class_count)
class_weights = {0: 0.133, 1: 14.129, 2: 0.913, 3: 1.868, 4: 6.191, 5: 10.805, 6: 9.501, 7: 26.24,
8: 0.461, 9: 0.685, 10: 32.415, 11: 0.552, 12: 30.61, 13: 2.35, 14: 5.681}
else:
class_weights = {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0, 5: 1.0, 6: 1.0, 7: 1.0,
8: 1.0, 9: 1.0, 10: 1.0, 11: 1.0, 12: 1.0, 13: 1.0, 14: 1.0}
if args.gpu is not None:
loss_img = loss_img.cuda(args.gpu)
loss_txt = loss_txt.cuda(args.gpu)
if args.distributed and sampler is not None:
sampler.set_epoch(epoch)
num_batches_per_epoch = dataloader.num_batches
end = time.time()
for i, batch in enumerate(dataloader):
step = num_batches_per_epoch * epoch + i
scheduler(step)
optimizer.zero_grad()
images, texts, labels = batch
if args.gpu is not None:
images = images.cuda(args.gpu, non_blocking=True)
labels = labels.cuda(args.gpu, non_blocking=True)
if args.new_model:
for key in texts:
texts[key] = texts[key].cuda(args.gpu, non_blocking=True)
else:
texts = texts.cuda(args.gpu, non_blocking=True)
data_time = time.time() - end
m = model.module if args.distributed or args.dp else model
# with automatic mixed precision.
if args.precision == "amp":
with autocast():
total_loss = get_loss(model, images, loss_img, loss_txt, class_weights, texts, labels, args)
scaler.scale(total_loss).backward()
scaler.step(optimizer)
scaler.update()
else:
total_loss = get_loss(model, images, loss_img, loss_txt, class_weights, texts, labels, args)
total_loss.backward()
optimizer.step()
# Note: we clamp to 4.6052 = ln(100), as in the original paper.
m.logit_scale.data = torch.clamp(m.logit_scale.data, 0, 4.6052)
batch_time = time.time() - end
end = time.time()
if is_master(args) and (i % 100) == 0:
num_samples = i * len(images) * args.world_size
samples_per_epoch = dataloader.num_samples
percent_complete = 100.0 * i / num_batches_per_epoch
logging.info(
f"Train Epoch: {epoch} [{num_samples}/{samples_per_epoch} ({percent_complete:.0f}%)]\t"
f"Loss: {total_loss.item():.6f}\tData (t) {data_time:.3f}\tBatch (t) {batch_time:.3f}"
f"\tLR: {optimizer.param_groups[0]['lr']:5f}\tlogit_scale {m.logit_scale.data:.3f}"
)
# save train loss / etc.
timestep = epoch * num_batches_per_epoch + i
log_data = {
"loss": total_loss.item(),
"data_time": data_time,
"batch_time": batch_time,
"scale": m.logit_scale.data.item(),
"lr": optimizer.param_groups[0]["lr"]
}
for name, val in log_data.items():
name = "train/" + name
if tb_writer is not None:
tb_writer.add_scalar(name, val, timestep)
if args.wandb:
wandb.log({name: val, 'step': timestep})
def evaluate(model, data, epoch, args, tb_writer=None, steps=None):
if not is_master(args):
return
model.eval()
zero_shot_metrics = zero_shot_eval(model, data, epoch, args)
dataloader = data['val'].dataloader
if args.default_loss:
loss_img = nn.CrossEntropyLoss()
loss_txt = nn.CrossEntropyLoss()
else:
loss_img = nn.BCEWithLogitsLoss()
loss_txt = nn.BCEWithLogitsLoss()
if args.gpu is not None:
loss_img = loss_img.cuda(args.gpu)
loss_txt = loss_txt.cuda(args.gpu)
cumulative_loss = 0.0
num_elements = 0.0
all_image_features, all_text_features, all_labels, all_texts = [], [], [], []
with torch.no_grad():
for batch in dataloader:
images, texts, labels = batch
if args.gpu is not None:
images = images.cuda(args.gpu, non_blocking=True)
if args.new_model:
for key in texts:
texts[key] = texts[key].cuda(args.gpu, non_blocking=True)
else:
texts = texts.cuda(args.gpu, non_blocking=True)
image_features, text_features, logit_scale = model(images, texts)
if args.new_model:
texts = texts['input_ids']
all_image_features.append(image_features)
all_text_features.append(text_features)
all_labels.append(labels)
all_texts.append(texts)
logit_scale = logit_scale.mean()
logits_per_image = logit_scale * image_features @ text_features.t()
logits_per_text = logits_per_image.t()
if args.Label_grouped:
ground_truth = torch.zeros(logits_per_image.shape).float()
for i in range(len(logits_per_image)):
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(labels[i], labels[j])]
ground_truth[i][mask_same] = 1
elif args.Healthy_grouped:
ground_truth = torch.eye(
len(logits_per_image)).float() # logits_per_image.shape = logits_per_text.shape = ground_truth.shape = batchsize x batchsize
for i in range(len(logits_per_image)):
# instead of an eye matrix we have 1 on the diagonal and 1 if the sample from this column belongs to the healthy class
if labels[i][0] == 1:
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(labels[i], labels[j])]
ground_truth[i][mask_same] = 1
elif args.Healthy_Caption_grouped:
ground_truth = torch.eye(
len(logits_per_image)).float() # logits_per_image.shape = logits_per_text.shape = ground_truth.shape = batchsize x batchsize
for i in range(len(logits_per_image)):
if labels[i][0] == 1:
# replace 0 with 1 if the sample from this column belongs the healthy class
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(labels[i], labels[j])]
ground_truth[i][mask_same] = 1
else:
# replace 0 with 1 if the sample from this column belongs the same deseased class and have the same caption
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(texts[i], texts[j])]
ground_truth[i][mask_same] = 1
elif args.Caption_grouped:
ground_truth = torch.eye(
len(logits_per_image)).float() # logits_per_image.shape = logits_per_text.shape = ground_truth.shape = batchsize x batchsize
for i in range(len(logits_per_image)):
# replace 0 with 1 if the sample from this column belongs the same class and have the same caption
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(texts[i], texts[j])]
ground_truth[i][mask_same] = 1
else:
ground_truth = torch.arange(len(logits_per_image)).long()
if args.gpu is not None:
ground_truth = ground_truth.cuda(args.gpu, non_blocking=True)
total_loss = (
loss_img(logits_per_image, ground_truth)
+ loss_txt(logits_per_text, ground_truth)
) / 2
batch_size = len(images)
cumulative_loss += total_loss * batch_size
num_elements += batch_size
if args.custom_eval:
metrics = get_metrics_custom(torch.cat(all_image_features),
torch.cat(all_text_features), torch.cat(all_labels), torch.cat(all_texts))
elif args.custom_eval_no_healthy:
metrics = get_metrics_custom_no_healthy(torch.cat(all_image_features),torch.cat(all_text_features), torch.cat(all_labels), torch.cat(all_texts))
else:
metrics = get_metrics(torch.cat(all_image_features), torch.cat(all_text_features))
loss = cumulative_loss / num_elements
metrics.update(
**{"val_loss": loss.item(), "epoch": epoch, "num_elements": num_elements}
)
metrics.update(zero_shot_metrics)
logging.info(
f"Eval Epoch: {epoch} "
+ "\t".join([f"{k}: {v:.4f}" for k, v in metrics.items()])
)
if args.save_logs:
if tb_writer is not None:
for name, val in metrics.items():
tb_writer.add_scalar(f"val/{name}", val, epoch)
if args.t_sne and epoch % 10 == 0:
all_labels_onehot = torch.cat(all_labels)
all_labels_int = []
for index in range(all_labels_onehot.shape[0]):
all_labels_int.append(onehot_to_int(all_labels_onehot[index]))
all_image_features = torch.cat(all_image_features).cpu().detach().numpy()
all_text_features = torch.cat(all_text_features).cpu().detach().numpy()
pca = decomposition.PCA(n_components=36)
pca.fit(all_image_features)
all_image_features = pca.transform(all_image_features)
pca.fit(all_text_features)
all_text_features = pca.transform(all_text_features)
tb_writer.add_embedding(mat=all_image_features, metadata=all_labels_int,
global_step=epoch, tag='val_image_features')
tb_writer.add_embedding(mat=all_text_features, metadata=all_labels_int,
global_step=epoch, tag='val_text_features')
if args.wandb:
for name, val in metrics.items():
wandb.log({f"val/{name}": val, 'epoch': epoch})
if args.save_logs:
with open(os.path.join(args.checkpoint_path, "results.jsonl"), "a+") as f:
f.write(json.dumps(metrics))
f.write("\n")
return metrics
def evaluate_train(model, data, epoch, args, tb_writer=None, steps=None):
if not is_master(args):
return
model.eval()
zero_shot_metrics = zero_shot_eval(model, data, epoch, args)
dataloader = data['train'].dataloader
if args.default_loss:
loss_img = nn.CrossEntropyLoss()
loss_txt = nn.CrossEntropyLoss()
else:
loss_img = nn.BCEWithLogitsLoss()
loss_txt = nn.BCEWithLogitsLoss()
if args.gpu is not None:
loss_img = loss_img.cuda(args.gpu)
loss_txt = loss_txt.cuda(args.gpu)
cumulative_loss = 0.0
num_elements = 0.0
all_image_features, all_text_features, all_labels, all_texts = [], [], [], []
with torch.no_grad():
for batch in dataloader:
images, texts, labels = batch
if args.gpu is not None:
images = images.cuda(args.gpu, non_blocking=True)
if args.new_model:
for key in texts:
texts[key] = texts[key].cuda(args.gpu, non_blocking=True)
else:
texts = texts.cuda(args.gpu, non_blocking=True)
image_features, text_features, logit_scale = model(images, texts)
if args.new_model:
texts = texts['input_ids']
all_image_features.append(image_features)
all_text_features.append(text_features)
all_labels.append(labels)
all_texts.append(texts)
logit_scale = logit_scale.mean()
logits_per_image = logit_scale * image_features @ text_features.t()
logits_per_text = logits_per_image.t()
if args.Label_grouped:
ground_truth = torch.zeros(logits_per_image.shape).float()
for i in range(len(logits_per_image)):
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(labels[i], labels[j])]
ground_truth[i][mask_same] = 1
elif args.Healthy_grouped:
ground_truth = torch.eye(len(logits_per_image)).float() # logits_per_image.shape = logits_per_text.shape = ground_truth.shape = batchsize x batchsize
for i in range(len(logits_per_image)):
# instead of an eye matrix we have 1 on the diagonal and 1 if the sample from this column belongs to the healthy class
if labels[i][0] == 1:
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(labels[i], labels[j])]
ground_truth[i][mask_same] = 1
elif args.Healthy_Caption_grouped:
ground_truth = torch.eye(len(logits_per_image)).float() # logits_per_image.shape = logits_per_text.shape = ground_truth.shape = batchsize x batchsize
for i in range(len(logits_per_image)):
if labels[i][0] == 1:
#replace 0 with 1 if the sample from this column belongs the healthy class
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(labels[i], labels[j])]
ground_truth[i][mask_same] = 1
else:
# replace 0 with 1 if the sample from this column belongs the same deseased class and have the same caption
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(texts[i], texts[j])]
ground_truth[i][mask_same] = 1
elif args.Caption_grouped:
ground_truth = torch.eye(len(logits_per_image)).float() # logits_per_image.shape = logits_per_text.shape = ground_truth.shape = batchsize x batchsize
for i in range(len(logits_per_image)):
# replace 0 with 1 if the sample from this column belongs the same class and have the same caption
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(texts[i], texts[j])]
ground_truth[i][mask_same] = 1
else:
ground_truth = torch.arange(len(logits_per_image)).long()
if args.gpu is not None:
ground_truth = ground_truth.cuda(args.gpu, non_blocking=True)
total_loss = (
loss_img(logits_per_image, ground_truth)
+ loss_txt(logits_per_text, ground_truth)
) / 2
batch_size = len(images)
cumulative_loss += total_loss * batch_size
num_elements += batch_size
if args.custom_eval:
metrics = get_metrics_custom(torch.cat(all_image_features),
torch.cat(all_text_features), torch.cat(all_labels), torch.cat(all_texts))
elif args.custom_eval_no_healthy:
metrics = get_metrics_custom_no_healthy(torch.cat(all_image_features),torch.cat(all_text_features), torch.cat(all_labels), torch.cat(all_texts))
else:
metrics = get_metrics(torch.cat(all_image_features), torch.cat(all_text_features))
loss = cumulative_loss / num_elements
metrics.update(
**{"train_loss": loss.item(), "epoch": epoch, "num_elements": num_elements}
)
metrics.update(zero_shot_metrics)
logging.info(
f"Eval Train Epoch: {epoch} "
+ "\t".join([f"{k}: {v:.4f}" for k, v in metrics.items()])
)
if args.save_logs:
if tb_writer is not None:
for name, val in metrics.items():
tb_writer.add_scalar(f"train_eval/{name}", val, epoch)
if args.t_sne and epoch % 10 == 0:
all_labels_onehot = torch.cat(all_labels)
all_labels_int = []
for index in range(all_labels_onehot.shape[0]):
all_labels_int.append(onehot_to_int(all_labels_onehot[index]))
all_image_features = torch.cat(all_image_features).cpu().detach().numpy()
all_text_features = torch.cat(all_text_features).cpu().detach().numpy()
pca = decomposition.PCA(n_components=36)
pca.fit(all_image_features)
all_image_features = pca.transform(all_image_features)
pca.fit(all_text_features)
all_text_features = pca.transform(all_text_features)
tb_writer.add_embedding(mat=all_image_features, metadata=all_labels_int,
global_step=epoch, tag='train_image_features')
tb_writer.add_embedding(mat=all_text_features, metadata=all_labels_int,
global_step=epoch, tag='train_text_features')
if args.wandb:
for name, val in metrics.items():
wandb.log({f"train_eval/{name}": val, 'epoch': epoch})
if args.save_logs:
with open(os.path.join(args.checkpoint_path, "train_results.jsonl"), "a+") as f:
f.write(json.dumps(metrics))
f.write("\n")
return metrics
def get_metrics(image_features, text_features):
metrics = {}
logits_per_image = image_features @ text_features.t()
logits_per_text = logits_per_image.t()
logits = {"image_to_text": logits_per_image, "text_to_image": logits_per_text}
ground_truth = (
torch.arange(len(text_features)).view(-1, 1).to(logits_per_image.device)
)
for name, logit in logits.items():
ranking = torch.argsort(logit, descending=True)
preds = torch.where(ranking == ground_truth)[1]
preds = preds.detach().cpu().numpy()
metrics[f"{name}_mean_rank"] = preds.mean() + 1
metrics[f"{name}_median_rank"] = np.floor(np.median(preds)) + 1
for k in [1, 5, 10]:
metrics[f"{name}_R@{k}"] = np.mean(preds < k)
return metrics
def get_metrics_custom(image_features, text_features, labels, texts):
metrics = {}
logits_per_image = image_features @ text_features.t()
logits_per_text = logits_per_image.t()
logits = {"image_to_text": logits_per_image, "text_to_image": logits_per_text}
ground_truth = torch.eye(
len(logits_per_text)).float().to(logits_per_image.device) # logits_per_image.shape = logits_per_text.shape = ground_truth.shape = batchsize x batchsize
for i in range(len(logits_per_text)):
if labels[i][0] == 1:
# replace 0 with 1 if the sample from this column belongs the healthy class
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(labels[i], labels[j])]
ground_truth[i][mask_same] = 1
else:
# replace 0 with 1 if the sample from this column belongs the same deseased class and have the same caption
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(texts[i], texts[j])]
ground_truth[i][mask_same] = 1
for name, logit in logits.items():
ranking = torch.argsort(logit, descending=True).to(logits_per_image.device)
preds = torch.zeros(len(logits_per_text)).to(logits_per_image.device)
for j in range(len(logits_per_text)):
ground_truth_sample = torch.where(ground_truth[j])[0].view(-1, 1).to(logits_per_image.device)
preds[j] = torch.min(torch.where(ranking[j] == ground_truth_sample)[1])
preds = preds.detach().cpu().numpy()
metrics[f"{name}_mean_rank"] = preds.mean() + 1
metrics[f"{name}_median_rank"] = np.floor(np.median(preds)) + 1
for k in [1, 5, 10]:
metrics[f"{name}_R@{k}"] = np.mean(preds < k)
return metrics
def get_metrics_custom_no_healthy(image_features, text_features, labels, texts):
metrics = {}
logits_per_image = image_features @ text_features.t()
logits_per_text = logits_per_image.t()
logits = {"image_to_text": logits_per_image, "text_to_image": logits_per_text}
ground_truth = torch.eye(
len(logits_per_text)).float().to(logits_per_image.device) # logits_per_image.shape = logits_per_text.shape = ground_truth.shape = batchsize x batchsize
for i in range(len(logits_per_text)):
mask_same = [j for j in range(len(logits_per_image)) if torch.equal(texts[i], texts[j])]
ground_truth[i][mask_same] = 1
for name, logit in logits.items():
ranking = torch.argsort(logit, descending=True).to(logits_per_image.device)
preds = torch.zeros(len(logits_per_text)).to(logits_per_image.device)
for j in range(len(logits_per_text)):
ground_truth_sample = torch.where(ground_truth[j])[0].view(-1, 1).to(logits_per_image.device)
preds[j] = torch.min(torch.where(ranking[j] == ground_truth_sample)[1])
preds = preds.detach().cpu().numpy()
metrics[f"{name}_mean_rank"] = preds.mean() + 1
metrics[f"{name}_median_rank"] = np.floor(np.median(preds)) + 1
for k in [1, 5, 10]:
metrics[f"{name}_R@{k}"] = np.mean(preds < k)
return metrics
def onehot_to_int(lst):
return [i for i, x in enumerate(lst) if x > 0]
| 45.606061 | 166 | 0.602168 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,993 | 0.13964 |
e85178ac252a4d1563a5cddd6910ff2818bf8e27 | 3,226 | py | Python | jade_utils.py | gimenete/jade-utils-sublime | 0ab6467b04a67245e773d9accf7f504c41f323f6 | [
"MIT"
] | null | null | null | jade_utils.py | gimenete/jade-utils-sublime | 0ab6467b04a67245e773d9accf7f504c41f323f6 | [
"MIT"
] | null | null | null | jade_utils.py | gimenete/jade-utils-sublime | 0ab6467b04a67245e773d9accf7f504c41f323f6 | [
"MIT"
] | null | null | null | from HTMLParser import HTMLParser
import sublime, sublime_plugin
void_elements = ["area", "base", "br", "col", "embed", "hr",
"img", "input", "keygen", "link", "menuitem",
"meta", "param", "source", "track", "wbr"]
class JadeUtilsHtml(sublime_plugin.TextCommand):
def run(self, edit):
html = sublime.get_clipboard()
for region in self.view.sel():
line = self.view.line(region)
prefix = self.view.substr(sublime.Region(line.a, region.a))
parser = HTML2JadeParser()
output = parser.convert(html, prefix)
self.view.replace(edit, sublime.Region(line.a, region.b), output)
def is_enabled(self):
return True
class HTML2JadeParser(HTMLParser):
def convert(self, html, prefix):
self.prefix = prefix
self.output = ''
self.indent = 0
self.feed(html)
return self.output
def indentation(self):
self.output += self.prefix
for i in range(self.indent):
self.output += ' '
def handle_starttag(self, tag, attrs):
nodestr = ''
nodeid = ''
nodeclasses = ''
nodeattrs = []
for attr in attrs:
name = attr[0]
value = attr[1]
if name == 'id':
nodeid = '#'+value
elif name == 'class':
classes = value.split(' ')
for clazz in classes:
nodeclasses += '.'+clazz
else:
nodeattrs.append(attr)
if tag == 'div' and (nodeid or nodeclasses or nodeattrs):
tag = ''
self.indentation()
self.output += tag
self.output += nodeid
self.output += nodeclasses
if len(nodeattrs) > 0:
self.output += '('
self.output += ', '.join([o[0]+'="'+o[1]+'"' for o in nodeattrs])
self.output += ')'
self.output += '\n'
if not tag in void_elements:
self.indent += 1
def handle_endtag(self, tag):
if not tag in void_elements:
self.indent -= 1
def handle_data(self, data):
data = data.replace('\r\n', '\n').replace('\r', '\n').strip()
for value in data.split('\n'):
if value:
self.indentation()
self.output += '| '
self.output += value
self.output += '\n'
def handle_comment(self, data):
data = data.replace('\r\n', '\n').replace('\r', '\n').strip()
for value in data.split('\n'):
if value:
self.indentation()
self.output += '//- '
self.output += value
self.output += '\n'
def handle_decl(self, decl):
if decl == 'DOCTYPE html':
self.output += 'doctype html\n'
else:
self.output += '<!'
self.output += decl
self.output += '>\n'
# def main():
# parser = HTML2JadeParser()
# output = parser.convert('<!DOCTYPE html><html class="foo"><head><title>Test</title></head>'
# '<body><div /><meta/><meta></meta><meta><meta><br><img><a>hello</a></html>')
# print output
# main() | 31.320388 | 97 | 0.50248 | 2,729 | 0.845939 | 0 | 0 | 0 | 0 | 0 | 0 | 524 | 0.16243 |
e85331900c6459687504959fb943368a54bbdd9f | 2,908 | py | Python | modules/MessageWatcher/MessageWatcher.py | ediril/BCI | f211ba70d6d75a9badff6872f86416b065f6192b | [
"BSD-2-Clause"
] | 6 | 2016-12-30T03:43:49.000Z | 2020-04-19T16:04:37.000Z | modules/MessageWatcher/MessageWatcher.py | hongweimao/BCI | 49b7e8137bd5f9d18e3efdbd94a112cde5d16c4c | [
"BSD-2-Clause"
] | 1 | 2022-03-08T09:16:10.000Z | 2022-03-08T09:16:10.000Z | modules/MessageWatcher/MessageWatcher.py | ediril/BCI | f211ba70d6d75a9badff6872f86416b065f6192b | [
"BSD-2-Clause"
] | 2 | 2015-06-16T02:46:03.000Z | 2018-12-20T20:07:59.000Z | import numpy as np
import Dragonfly_config as rc
from argparse import ArgumentParser
from ConfigParser import SafeConfigParser
from PyDragonfly import Dragonfly_Module, CMessage, copy_to_msg, copy_from_msg
from time import time
class MessageWatcher(object):
# msg_types = ['GROBOT_RAW_FEEDBACK',
# 'GROBOT_FEEDBACK',
# 'SAMPLE_GENERATED',
# 'SPM_SPIKECOUNT',
# 'EM_MOVEMENT_COMMAND',
# 'COMPOSITE_MOVEMENT_COMMAND'
# ]
def __init__(self, config_file):
self.load_config(config_file)
self.msg_nums = [eval('rc.MT_%s' % (x)) for x in self.msg_types]
self.count = np.zeros((len(self.msg_nums)), dtype=int)
self.last_time = time()
self.setup_Dragonfly()
self.run()
def load_config(self, config_file):
self.config = SafeConfigParser()
self.config.read(config_file)
self.msg_types = [x.upper() for x in self.config.options('messages')]
self.msg_types.sort()
def setup_Dragonfly(self):
server = self.config.get('Dragonfly', 'server')
self.mod = Dragonfly_Module(0, 0)
self.mod.ConnectToMMM(server)
for i in self.msg_types:
self.mod.Subscribe(eval('rc.MT_%s' % (i)))
self.mod.SendModuleReady()
print "Connected to Dragonfly at", server
def run(self):
while True:
msg = CMessage()
rcv = self.mod.ReadMessage(msg, 0.1)
if rcv == 1:
self.process_message(msg)
this_time = time()
self.diff_time = this_time - self.last_time
if self.diff_time > 1.:
self.last_time = this_time
self.write()
self.count[:] = 0
def process_message(self, in_msg):
msg_type = in_msg.GetHeader().msg_type
if not msg_type in self.msg_nums:
return
msg_idx = self.msg_nums.index(msg_type)
self.count[msg_idx] += 1
def write(self):
for msg_type, c in zip(self.msg_types, self.count):
rate = c / self.diff_time
print "%40s %5.2f Hz" % (msg_type, rate)
if (('GROBOT_RAW_FEEDBACK' in msg_type) and (rate < 48.0)):
print "Raw feedback rate is too low!"
print "Raw feedback rate is too low!"
print "Raw feedback rate is too low!"
print "Raw feedback rate is too low!"
print "window was %0.3f seconds\n" % (self.diff_time)
print ""
if __name__ == "__main__":
parser = ArgumentParser(description = "Display information about message flow")
parser.add_argument('config', metavar='config_file', type=str)
args = parser.parse_args()
print("Using config file %s" % args.config)
mw = MessageWatcher(args.config)
| 36.810127 | 83 | 0.584594 | 2,379 | 0.818088 | 0 | 0 | 0 | 0 | 0 | 0 | 591 | 0.203232 |
e85343be0e6df80e2d7f6b911a366990aea1690d | 2,858 | py | Python | Plug-and-play module/attention/CBAM/cbam.py | riciche/SimpleCVReproduction | 4075de39f9c61f1359668a413f6a5d98903fcf97 | [
"Apache-2.0"
] | 923 | 2020-01-11T06:36:53.000Z | 2022-03-31T00:26:57.000Z | Plug-and-play module/attention/CBAM/cbam.py | riciche/SimpleCVReproduction | 4075de39f9c61f1359668a413f6a5d98903fcf97 | [
"Apache-2.0"
] | 25 | 2020-02-27T08:35:46.000Z | 2022-01-25T08:54:19.000Z | Plug-and-play module/attention/CBAM/cbam.py | riciche/SimpleCVReproduction | 4075de39f9c61f1359668a413f6a5d98903fcf97 | [
"Apache-2.0"
] | 262 | 2020-01-02T02:19:40.000Z | 2022-03-23T04:56:16.000Z | import torch
import torch.nn as nn
def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes,
out_planes,
kernel_size=3,
stride=stride,
padding=1,
bias=False)
class ChannelAttention(nn.Module):
def __init__(self, in_planes, ratio=4):
super(ChannelAttention, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.max_pool = nn.AdaptiveMaxPool2d(1)
self.sharedMLP = nn.Sequential(
nn.Conv2d(in_planes, in_planes // ratio, 1, bias=False), nn.ReLU(),
nn.Conv2d(in_planes // ratio, in_planes, 1, bias=False))
self.sigmoid = nn.Sigmoid()
def forward(self, x):
avgout = self.sharedMLP(self.avg_pool(x))
maxout = self.sharedMLP(self.max_pool(x))
return self.sigmoid(avgout + maxout)
class SpatialAttention(nn.Module):
def __init__(self, kernel_size=7):
super(SpatialAttention, self).__init__()
assert kernel_size in (3, 7), "kernel size must be 3 or 7"
padding = 3 if kernel_size == 7 else 1
self.conv = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
avgout = torch.mean(x, dim=1, keepdim=True)
maxout, _ = torch.max(x, dim=1, keepdim=True)
x = torch.cat([avgout, maxout], dim=1)
x = self.conv(x)
return self.sigmoid(x)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.ca = ChannelAttention(planes)
self.sa = SpatialAttention()
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.ca(out) * out # 广播机制
out = self.sa(out) * out # 广播机制
if self.downsample is not None:
print("downsampling")
residual = self.downsample(x)
print(out.shape, residual.shape)
out += residual
out = self.relu(out)
return out
if __name__ == "__main__":
downsample = nn.Sequential(
nn.Conv2d(16, 32, kernel_size=1, stride=1, bias=False),
nn.BatchNorm2d(32))
x = torch.ones(3, 16, 32, 32)
model = BasicBlock(16, 32, stride=1, downsample=downsample)
print(model(x).shape) | 28.58 | 79 | 0.590973 | 2,266 | 0.788448 | 0 | 0 | 0 | 0 | 0 | 0 | 110 | 0.038274 |
e854017c38291bb4b2ae09b4884a064ca12c7067 | 1,339 | py | Python | nyc/dataprep/PrepareTreeData.py | lopez86/NYCDataTools | 9c860545bacd27a7a1106bba3e3d75cd0320e6df | [
"MIT"
] | null | null | null | nyc/dataprep/PrepareTreeData.py | lopez86/NYCDataTools | 9c860545bacd27a7a1106bba3e3d75cd0320e6df | [
"MIT"
] | null | null | null | nyc/dataprep/PrepareTreeData.py | lopez86/NYCDataTools | 9c860545bacd27a7a1106bba3e3d75cd0320e6df | [
"MIT"
] | null | null | null | #! /usr/bin/env python3
""" PrepareTreeData.py
Prepares the tree data a bit for inclusion into a database.
"""
import pandas as pd
import numpy as np
""" Prepare the tree data for inclusion into a database.
Args:
inname: Input file
outname: Output file
"""
def PrepareTreeData(inname='data/street_trees_2015.csv',
outname='trees_2015.csv'):
trees = pd.read_csv(inname,index_col=0)
trees = trees.drop(['state','x_sp','y_sp','zip_city',
'cncldist','st_assem','st_senate',
'problems','address'
],axis=1)
boromap = {'1':'36061','2':'36005','3':'36047','4':'36081','5':'36085'}
def map_date(date):
m = date[0:2]
d = date[3:5]
y = date[-4:]
return y + '-'+m+'-'+d
trees.created_at = trees.created_at.map(map_date)
def get_tract(boro_ct):
boro_ct = str(boro_ct)
return int(boromap[boro_ct[0]] + boro_ct[1:])
trees['tract'] = trees.boro_ct.map(get_tract)
trees = trees.drop('boro_ct',axis=1)
cols = [col for col in trees.columns]
cols.remove('boroname')
cols.append('boroname')
trees = trees.loc[:,cols]
trees.to_csv(outname)
""" Runs with default arguments"""
def main():
PrepareTreeData()
if __name__=='__main__':
main()
| 25.264151 | 75 | 0.587005 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 485 | 0.362211 |
e85442ad2e2c6b3f6e0178cb6ceb6185189e2bc3 | 11,307 | py | Python | pyqha/alphagruneisen.py | mauropalumbo75/pyqha | 3e904a0363d57c52d02d2520cabbb48c2d0df5cb | [
"MIT"
] | 10 | 2016-12-13T12:35:06.000Z | 2022-03-25T14:19:51.000Z | pyqha/alphagruneisen.py | mauropalumbo75/pyqha | 3e904a0363d57c52d02d2520cabbb48c2d0df5cb | [
"MIT"
] | null | null | null | pyqha/alphagruneisen.py | mauropalumbo75/pyqha | 3e904a0363d57c52d02d2520cabbb48c2d0df5cb | [
"MIT"
] | 3 | 2017-06-07T12:10:37.000Z | 2020-04-25T13:07:30.000Z | #encoding: UTF-8
# Copyright (C) 2016 Mauro Palumbo
# This file is distributed under the terms of the # MIT License.
# See the file `License' in the root directory of the present distribution.
"""
An earlier and now oblosete implementation of functions for computing the
thermal expansion tensor as a function
of temperature from the Gruneisein parameters, the mode contributions to the
heat capacity, the elastic tensor and the unit cell volume.
Use :py:mod:`alphagruneisenp` instead.
"""
import numpy as np
import time
import math
import sys
from .read import read_Etot, read_freq, read_freq_ext, read_elastic_constants, \
read_elastic_constants_geo, read_freq_ext_geo
from .write import write_freq, write_freq_ext, write_alphaT, write_qha_C, write_qha_CT
from .constants import RY_KBAR, K_BOLTZMANN_RY, kb1
from .fitutils import fit_anis
from .minutils import find_min, fquadratic, fquartic
from .fitfreqgrun import fitfreq, fitfreqxx, freqmingrun, rearrange_freqx
from .fitFvib import fitFvib
from .fitC import rearrange_Cx, fitCxx
from .grunc import c_qvc # This is the same routine c_qv implemented in C to speed it up
################################################################################
#
# Compute the volume given the celldms, only for ibrav=4 for now
def compute_volume(celldms,ibrav=4):
if ibrav==4:
return 0.866025404*celldms[0]*celldms[0]*celldms[2]
#return 0.866025404*celldms[0]*celldms[0]*celldms[0]*celldms[2]
################################################################################
#
# Function to calculate the mode contribution to the heat capacity at a given T
# and omega
# This is a possible bottleneck as it is implemented in Python. It would be
# better to write it in C and link it to CPython or similar
#
#
def c_qv(T,omega):
if (T<1E-9 or omega<1E-9):
return 0.0
x = omega * kb1 / T
expx = math.exp(-x) # exponential term
x2 = math.pow(x,2)
if expx>1E-3: # compute normally
return x2*K_BOLTZMANN_RY*expx/math.pow(expx-1.0,2)
else: # Taylor series
return K_BOLTZMANN_RY*expx* (x/math.pow(x-0.5*math.pow(x,2)+
0.16666666666666667*math.pow(x,3)+0.04166666666666666667*math.pow(x,4),2))
# Same as c_qv but no if. Slightly more efficient, roughly a 30% faster
def c_qv2(T,omega):
x = omega * kb1 / T
expx = math.exp(-x) # exponential term
x2 = math.pow(x,2)
return x2*K_BOLTZMANN_RY*expx/math.pow(expx-1.0,2)
################################################################################
#
# This function computes the thermal expansions alpha using the Gruneisein
# parameters
# more comments to be added
# First with min0, freq and grun T-independent
#
# More ibrav types to be implemented
def compute_alpha_grun(T,V,S,weights,freq,grun,ibrav=4):
nq = freq.shape[0] # total number of q points
modes = freq.shape[1] # number of frequency modes
alpha = np.zeros(6) # inizializations
alphaaux = np.zeros(6)
# compute the Cqv*gruneisen terms, weights for each q-point, and sum
# for each ibrav (crystalline system) proceed in the proper way
if ibrav ==1:
for iq in range(0,nq):
for mode in range(0,modes):
alphaaux[0] += c_qv(T,freq[iq,mode]) * weights[iq] * grun[0,iq,mode]
alphaaux[0] = alphaaux[0] / 3.0
alphaaux[1] = alphaaux[0]
alphaaux[2] = alphaaux[0]
if ibrav ==4:
for iq in range(0,nq):
for mode in range(0,modes):
temp = c_qvc(T,freq[iq,mode]) * weights[iq] # should be quicker with this additional variable
alphaaux[0] += temp * grun[0,iq,mode]
alphaaux[2] += temp * grun[2,iq,mode]
alphaaux[0] = alphaaux[0] / 2.0
alphaaux[1] = alphaaux[0]
else:
print ("Not implemented yet")
# multiply for the elastic compliances
for i in range(0,6):
for j in range(0,6):
alpha[i] += alphaaux[j]*S[i,j]
alpha = -alpha/V
return alpha
def compute_alpha_gruneisein(inputfileEtot,inputfileC,inputfilefreq,rangeT,typeEtot,typefreq,ibrav):
# Read the energies
celldmsx, Ex = read_Etot(inputfileEtot)
# Fit and find the minimun at 0 K
a0, chia0 = fit_anis(celldmsx, Ex, ibrav, out=True, type=typeEtot)
if chia0!=None:
min0, fmin0 = find_min(a0, ibrav, type=typeEtot, guess=guess)
# First read the elastic compliances which are need for the thermal expansions
print ("Reading elastic constants and compliances from file "+inputfileC+"...")
C, S = read_elastic_constants(inputfileC)
#print (S)
# Compute the Gruneisen parameters
weights, freq, grun = fitfreq(celldmsx, min0, inputfilefreq, ibrav, typefreq="quadratic", compute_grun=True)
# Alternatively, we can read the gruneisen parameters from files (already written before)
#weights, freq = read_freq_ext("average_freq0K")
#weights, gruntemp1 = read_freq_ext("output_grun_along_a_ext3Dfit1.0")
#weights, gruntemp2 = read_freq_ext("output_grun_along_c_ext3Dfit1.0")
#nq = gruntemp1.shape[0]
#modes = gruntemp1.shape[1]
#grun = np.zeros((6,nq,modes))
#grun[0] = gruntemp1
#grun[1] = gruntemp1
#grun[2] = gruntemp2
V=compute_volume(min0,ibrav) # eq. volume at 0 K
print ("V = ",str(V))
S = S * RY_KBAR # convert elastic compliances in (Ryd/au)^-1
alphaT= np.zeros((len(rangeT),6))
counterT=0
for T in rangeT:
alpha = compute_alpha_grun(T,V,S,weights,freq,grun)
alphaT[counterT]=alpha
counterT += 1
print ("T= "+str(T)+"\t"+str(alpha[0])+"\t"+str(alpha[2]))
write_alphaT("alpha_gruneisen",rangeT,alphaT,4)
def compute_alpha_gruneiseinT(inputfileEtot,inputfileFvib,inputfileC,inputfilefreq,typeEtot,typeFvib,typefreq,ibrav,guess):
# Read the energies
celldmsx, Ex = read_Etot(inputfileEtot)
T, minT, fminT = fitFvib(inputfileEtot,inputfileFvib,ibrav,typeEtot,typeFvib,guess)
# First read the elastic compliances which are need for the thermal expansions
print ("Reading elastic constants and compliances from file "+inputfileC+"...")
C, S = read_elastic_constants(inputfileC)
print (S)
S = S * RY_KBAR # convert elastic compliances in (Ryd/au)^-1
# get the weigths and the frequencies from files
weightsx, freqx = read_freq_ext_geo(inputfilefreq,range(1,celldmsx.shape[0]+1))
weights = weightsx[0,:]
print ("Rearranging frequencies...")
freqxx = rearrange_freqx(freqx)
print ("Done!")
del freqx
print ("Fitting frequencies...")
afreq, chifreq = fitfreqxx(celldmsx, freqxx, ibrav, True, typefreq)
print ("Done!")
alphaT= np.zeros((len(T),6))
for i in range(0,len(T)):
# Compute the Gruneisen parameters, the average frequencies and alpha at each T
V=compute_volume(minT[i],ibrav)
print ("V = ",str(V))
freq, grun = freqmingrun(afreq, minT[i], freqxx.shape[0],freqxx.shape[1], ibrav, typefreq)
#write_freq_ext(weights,freq,"average_freqPython"+str(T[i]))
#write_freq_ext(weights,grun[0],"output_grun_along_a_ext3Dfit"+str(T[i]))
#write_freq_ext(weights,grun[2],"output_grun_along_c_ext3Dfit"+str(T[i]))
alpha = compute_alpha_grun(T[i],V,S,weights,freq,grun)
print ("T= "+str(T[i]))
print (alpha)
alphaT[i,:] = alpha
write_alphaT("alpha_gruneisenT",T,alphaT,4)
################################################################################
#
# This function is only meant to test the Cqv modes. It has to be removed later...
#
def testCqv(inputfilefreq, rangeT, out="Cqvtest"):
weights, freq = read_freq_ext(inputfilefreq)
nq = freq.shape[0] # total number of q points read
modes = freq.shape[1] # number of frequency modes
for T in rangeT:
Cqv = []
for iq in range(0,nq):
Cqvq=[]
for ifreq in range(0,modes):
temp = c_qv2(T,freq[iq,ifreq])
Cqvq.append(temp)
Cqv.append(Cqvq)
Cqv = np.array(Cqv)
outT = out+str(T)
write_freq_ext(weights,Cqv,outT)
################################################################################
# An auxiliary function for fitting the elastic constant elements of Sxx
#
#
def fitS(inputfileEtot, inputpathCx, ibrav, typeSx="quadratic"):
# Read the energies (this is necessary to read the celldmsx)
celldmsx, Ex = read_Etot(inputfileEtot)
ngeo = len(Ex)
Cx, Sx = read_elastic_constants_geo(ngeo, inputpathCx)
# This function works for both C and S, here I use it for S
Sxx = rearrange_Cx(Sx,ngeo)
write_qha_C(celldmsx, Sxx, ibrav, inputpathCx) # Write the S as a function of T for reference
aS, chiS = fitCxx(celldmsx, Sxx, ibrav, True, typeSx)
return aS, chiS
def fitST(aS,mintemp,typeCx):
S = np.zeros((6,6))
for i in range(0,6):
for j in range(0,6):
if typeCx=="quadratic":
S[i,j] = fquadratic(mintemp,aS[i,j],ibrav=4)
elif typeCx=="quartic":
S[i,j] = fquartic(mintemp,aS[i,j],ibrav=4)
return S
def compute_alpha_gruneiseinCT(inputfileEtot,inputfileFvib,inputpathCx,inputfilefreq,typeEtot,typeFvib,typeSx,typefreq,ibrav,guess):
# Read the energies
celldmsx, Ex = read_Etot(inputfileEtot)
T, minT, fminT = fitFvib(inputfileEtot,inputfileFvib,ibrav,typeEtot,typeFvib,guess)
# Get the polynomial coefficients aS from fitting the elastic compliances (to be used later to get S(T))
aS, chiS = fitS(inputfileEtot, inputpathCx, ibrav, typeSx)
# Now get the polynomial coeffients afreq from fitting the frequencies (to be used later to get average frequencies and
# gruneisen parameters as a function of T)
weightsx, freqx = read_freq_ext_geo(inputfilefreq,range(1,celldmsx.shape[0]+1))
weights = weightsx[0,:]
print ("Rearranging frequencies...")
freqxx = rearrange_freqx(freqx)
print ("Done!")
del freqx
print ("Fitting frequencies...")
afreq, chifreq = fitfreqxx(celldmsx, freqxx, ibrav, True, typefreq)
print ("Done!")
alphaT= np.zeros((len(T),6))
for i in range(0,len(T)):
# Compute the Gruneisen parameters, the average frequencies and alpha at each T
V=compute_volume(minT[i],ibrav)
print ("V = ",str(V))
S = fitST(aS,minT[i],typeSx)
print (S)
S = S * RY_KBAR # convert elastic compliances in (Ryd/au)^-1
freq, grun = freqmingrun(afreq, minT[i], freqxx.shape[0],freqxx.shape[1], ibrav, typefreq)
#write_freq_ext(weights,freq,"average_freqPython"+str(T[i]))
#write_freq_ext(weights,grun[0],"output_grun_along_a_ext3Dfit"+str(T[i]))
#write_freq_ext(weights,grun[2],"output_grun_along_c_ext3Dfit"+str(T[i]))
alpha = compute_alpha_grun(T[i],V,S,weights,freq,grun)
print ("T= "+str(T[i]))
print (alpha)
alphaT[i,:] = alpha
write_alphaT("alpha_gruneisenT",T,alphaT,4)
| 36.95098 | 132 | 0.630406 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4,487 | 0.396834 |
e854eac02ff984d86165518b112aa60249a5b42e | 18 | py | Python | allennlp/tests/fixtures/plugins/project_c/allennlp_plugins/c/__init__.py | justindujardin/allennlp | c4559f3751775aa8bc018db417edc119d29d8051 | [
"Apache-2.0"
] | 1 | 2020-03-30T14:07:02.000Z | 2020-03-30T14:07:02.000Z | allennlp/tests/fixtures/plugins/project_c/allennlp_plugins/c/__init__.py | justindujardin/allennlp | c4559f3751775aa8bc018db417edc119d29d8051 | [
"Apache-2.0"
] | 123 | 2020-04-26T02:41:30.000Z | 2021-08-02T21:18:00.000Z | allennlp/tests/fixtures/plugins/project_c/allennlp_plugins/c/__init__.py | justindujardin/allennlp | c4559f3751775aa8bc018db417edc119d29d8051 | [
"Apache-2.0"
] | 2 | 2019-12-21T05:58:44.000Z | 2021-08-16T07:41:21.000Z | from c.c import C
| 9 | 17 | 0.722222 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
e85543976eb128fd6cd840908a99b6775aa2dca1 | 1,934 | py | Python | cro/fitness.py | VictorPelaez/coral-reef-optimization-algorithm | 25804fc43b735df707821008558e9410dfe4a835 | [
"MIT"
] | 21 | 2017-10-09T20:44:03.000Z | 2022-03-03T14:43:09.000Z | cro/fitness.py | VictorPelaez/coral-reef-optimization-algorithm | 25804fc43b735df707821008558e9410dfe4a835 | [
"MIT"
] | 33 | 2017-10-11T20:12:26.000Z | 2021-11-11T09:19:07.000Z | cro/fitness.py | VictorPelaez/coral-reef-optimization-algorithm | 25804fc43b735df707821008558e9410dfe4a835 | [
"MIT"
] | 5 | 2017-10-11T19:16:09.000Z | 2022-01-29T13:49:59.000Z | from __future__ import division
import numpy as np
from sklearn.utils import shuffle
from sklearn.metrics import *
"""
Module with different fitness functions implemented to be used by the CRO algorithm.
The functions' only argument must be an individual (coral) and return its fitness, a number.
The fitness might require other arguments, in that case the partial function in python's functools module is a very good option
"""
def max_ones(coral):
"""
Description: Returns the percentage of 1's in the coral. This function assumes 'coral' is a list,
it could be further improved if it was a numpy array
Input:
- coral
Output:
- fitness
"""
return 100*(sum(coral) / len(coral))
def feature_selection(coral, X, y, model,
get_prediction = lambda model, X: model.predict(X),
metric=roc_auc_score, random_seed=None):
"""
Description: Returns the fitness (given by metric) of the selected features given by coral,
when using Xt and yt for training the model clf
Input:
- coral : an individual
- X: Data input
- y: Data output
- model: instance of the model to be trained
- get_prediction: function that accepts the model and X and outputs the vector
that will be used in the metric (predictions, scores...)
- metric: metric that will be used as fitness
Output:
- fitness
"""
# offset % of data for training, the rest for testing
offset = int(X.shape[0] * 0.9)
Xs, ys = shuffle(X, y, random_state=random_seed)
Xs = np.multiply(Xs, coral)
X_train, y_train = Xs[:offset], ys[:offset]
X_test, y_test = Xs[offset:], ys[offset:]
# train model
model.fit(X_train, y_train)
# Compute metric
y_pred = get_prediction(model, X_test)
fitness = metric(y_test, y_pred)
return fitness
| 31.704918 | 127 | 0.651499 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,184 | 0.612203 |
e8569d7c3bbbd06495a3be7b58b262f1f38b3a3d | 1,518 | py | Python | lib/environment/shape.py | vyahello/snakegame-gui | 1eb23744174035f49dd0a33c48d365e8b3836178 | [
"MIT"
] | null | null | null | lib/environment/shape.py | vyahello/snakegame-gui | 1eb23744174035f49dd0a33c48d365e8b3836178 | [
"MIT"
] | null | null | null | lib/environment/shape.py | vyahello/snakegame-gui | 1eb23744174035f49dd0a33c48d365e8b3836178 | [
"MIT"
] | null | null | null | from abc import ABC, abstractmethod
from typing import Tuple, Iterable, Any
from pygame.rect import Rect
class Shape(ABC):
"""Abstract shape interface."""
@abstractmethod
def shape(self) -> Any:
pass
@abstractmethod
def top_left(self) -> Tuple:
pass
@abstractmethod
def top_right(self) -> Iterable:
pass
@abstractmethod
def size(self) -> Tuple:
pass
@abstractmethod
def bottom_right(self) -> Iterable:
pass
@abstractmethod
def bottom_left(self) -> Iterable:
pass
@abstractmethod
def inflate(self, x: int, y: int) -> Rect:
pass
class Rectangle(Shape):
"""Rectangle shape."""
def __init__(self, position: Iterable) -> None:
self._shape: Rect = Rect(position)
self._top_left: Tuple = (0, 0)
def shape(self) -> Any:
return self._shape
@property
def top_left(self) -> Tuple:
return self._top_left
@top_left.setter
def top_left(self, position: Tuple) -> None:
self._top_left = position
@property
def top_right(self) -> Iterable:
return self._shape.topright
@property
def bottom_left(self) -> Iterable:
return self._shape.bottomleft
@property
def bottom_right(self) -> Iterable:
return self._shape.bottomright
@property
def size(self) -> Tuple:
return self._shape.size
def inflate(self, x: int, y: int) -> Rect:
return self._shape.inflate(x, y)
| 20.513514 | 51 | 0.614625 | 1,407 | 0.926877 | 0 | 0 | 946 | 0.623188 | 0 | 0 | 53 | 0.034914 |
e856d28ae91acdab7a6956c6e1799773dfe4c394 | 994 | py | Python | bleak/backends/device.py | virantha/bleak | 0226cdef0af2d6bcdf5a84d87c437ed75aaa7726 | [
"MIT"
] | null | null | null | bleak/backends/device.py | virantha/bleak | 0226cdef0af2d6bcdf5a84d87c437ed75aaa7726 | [
"MIT"
] | 1 | 2019-04-01T02:31:45.000Z | 2019-04-01T02:31:45.000Z | bleak/backends/device.py | virantha/bleak | 0226cdef0af2d6bcdf5a84d87c437ed75aaa7726 | [
"MIT"
] | 1 | 2019-04-01T01:34:42.000Z | 2019-04-01T01:34:42.000Z | # -*- coding: utf-8 -*-
"""
Wrapper class for Bluetooth LE servers returned from calling
:py:meth:`bleak.discover`.
Created on 2018-04-23 by hbldh <henrik.blidh@nedomkull.com>
"""
class BLEDevice(object):
"""A simple wrapper class representing a BLE server detected during
a `discover` call.
- When using Windows backend, `details` attribute is a
`Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisement` object.
- When using Linux backend, `details` attribute is a
string path to the DBus device object.
- When using macOS backend, `details` attribute will be
something else.
"""
def __init__(self, address, name, details=None, uuids=[], manufacturer_data={}):
self.address = address
self.name = name if name else "Unknown"
self.details = details
self.uuids = uuids
self.manufacturer_data = manufacturer_data
def __str__(self):
return "{0}: {1}".format(self.address, self.name)
| 30.121212 | 84 | 0.678068 | 809 | 0.813883 | 0 | 0 | 0 | 0 | 0 | 0 | 623 | 0.626761 |
e85725f4d0132ac8d4a20d890a96acfcc728db0b | 5,144 | py | Python | jqueryui/jqueryui.py | yyuunn0044/oss-hubblemon | f90635f7b66defd1515516fcec61973fa75a6f84 | [
"Apache-2.0"
] | null | null | null | jqueryui/jqueryui.py | yyuunn0044/oss-hubblemon | f90635f7b66defd1515516fcec61973fa75a6f84 | [
"Apache-2.0"
] | null | null | null | jqueryui/jqueryui.py | yyuunn0044/oss-hubblemon | f90635f7b66defd1515516fcec61973fa75a6f84 | [
"Apache-2.0"
] | null | null | null |
#
# Hubblemon - Yet another general purpose system monitor
#
# Copyright 2015 NAVER Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
class jquery:
def __init__(self):
self.scripts = []
def render(self):
pass
def autocomplete(self, id):
ret = jquery_autocomplete(id)
self.scripts.append(ret)
return ret
def button(self, id):
ret = jquery_button(id)
self.scripts.append(ret)
return ret
def selectable(self, id):
ret = jquery_selectable(id)
self.scripts.append(ret)
return ret
def radio(self, id):
ret = jquery_radio(id)
self.scripts.append(ret)
return ret
class jscript:
def __init__(self, action):
self.action = action
def render(self):
js_template = self.get_js_template()
return js_template % (self.action)
def get_js_template(self):
js_template = '''
<script type="text/javascript">
$(function() {
%s;
});
</script>
'''
return js_template
class jqueryui:
def __init__(self, id):
self.id = id
self.target = None
def val(self, v = None):
if v is None:
return "$('#%s').val()" % (self.id)
else:
return "$('#%s').val(%s)" % (self.id, v)
def val_str(self, v = None):
if v is None:
return "$('#%s').val()" % (self.id)
else:
return "$('#%s').val('%s')" % (self.id, v)
def text(self, v = None):
if v is None:
return "$('#%s').text()" % (self.id)
else:
return "$('#%s').text(%s)" % (self.id, v)
def text_str(self, v = None):
if v is None:
return "$('#%s').text()" % (self.id)
else:
return "$('#%s').text('%s')" % (self.id, v)
class jquery_autocomplete(jqueryui):
def set(self, source, action):
self.source = source
self.action = action
def render(self):
raw_data = self.source.__repr__()
js_template = self.get_js_template()
return js_template % (self.id, raw_data, self.action, self.id)
def source(self, url):
return "$('#%s').autocomplete('option', 'source', %s);" % (self.id, url)
def get_js_template(self):
js_template = '''
<script type="text/javascript">
$(function() {
$('#%s').autocomplete({
source: %s,
minLength: 0,
select: function( event, ui ) {
%s;
return false;
}
}).focus(function(){
$(this).autocomplete('search', $(this).val())});
});
</script>
<input type="text" id="%s">
'''
return js_template
# TODO
class jquery_selectable(jqueryui):
def __init__(self, id):
self.id = id
self.select_list = []
def push_item(self, item):
self.select_list.append(item)
def render(self):
select_list = ''
for item in self.select_list:
select_list += "<li class='ui-widget-content'>%s</li>\n" % item
js_template = self.get_js_template()
id = self.id
return js_template % (id, id, id, id, id, select_list)
def get_js_template(self):
js_template = '''
<style>
#%s .ui-selecting { background: #FECA40; }
#%s .ui-selected { background: #F39814; color: white; }
#%s { list-style-type: none; margin:0; padding:0; }
.ui-widget-content { display:inline; margin: 0 0 0 0; padding: 0 0 0 0; border: 1; }
</style>
<script type="text/javascript">
$(function() {
$('#%s').selectable();
});
</script>
<ul id='%s'>
%s
</ul>
'''
return js_template
class jquery_button(jqueryui):
def __init__(self, id):
self.id = id
self.action = ''
def set_action(self, action):
self.action = action
def render(self):
js_template = self.get_js_template()
return js_template % (self.id, self.action, self.id, self.id)
def get_js_template(self):
js_template = '''
<script type="text/javascript">
$(function() {
$('#%s').button().click(
function() {
%s;
}
);
});
</script>
<button id='%s' float>%s</button>
'''
return js_template
class jquery_radio(jqueryui):
def __init__(self, id):
self.id = id
self.action = ''
self.button_list = []
def push_item(self, item):
self.button_list.append(item)
def set_action(self, action):
self.action = action
def render(self):
button_list = ''
for item in self.button_list:
button_list += "<input type='radio' id='%s' name='radio'><label for='%s'>%s</label>" % (item, item, item)
js_template = self.get_js_template()
id = self.id
return js_template % (id, id, self.action, id, button_list)
def get_js_template(self):
js_template = '''
<script type="text/javascript">
$(function() {
$('#%s').buttonset();
$('#%s :radio').click(function() {
%s;
});
});
</script>
<ul id='%s' style="display:inline">
%s
</ul>
'''
return js_template
| 21.081967 | 108 | 0.615086 | 4,480 | 0.870918 | 0 | 0 | 0 | 0 | 0 | 0 | 2,233 | 0.434098 |
e85746131b4e0732b56b704dfb01f9cc40207e1c | 3,195 | py | Python | diffrax/solver/kvaerno5.py | FedericoV/diffrax | 98b010242394491fea832e77dc94f456b48495fa | [
"Apache-2.0"
] | 377 | 2022-02-07T11:13:56.000Z | 2022-03-31T18:35:51.000Z | diffrax/solver/kvaerno5.py | FedericoV/diffrax | 98b010242394491fea832e77dc94f456b48495fa | [
"Apache-2.0"
] | 25 | 2022-02-08T23:08:11.000Z | 2022-03-30T21:21:18.000Z | diffrax/solver/kvaerno5.py | FedericoV/diffrax | 98b010242394491fea832e77dc94f456b48495fa | [
"Apache-2.0"
] | 15 | 2022-02-08T04:46:23.000Z | 2022-03-30T20:53:10.000Z | import numpy as np
from ..local_interpolation import ThirdOrderHermitePolynomialInterpolation
from .runge_kutta import AbstractESDIRK, ButcherTableau
γ = 0.26
a21 = γ
a31 = 0.13
a32 = 0.84033320996790809
a41 = 0.22371961478320505
a42 = 0.47675532319799699
a43 = -0.06470895363112615
a51 = 0.16648564323248321
a52 = 0.10450018841591720
a53 = 0.03631482272098715
a54 = -0.13090704451073998
a61 = 0.13855640231268224
a62 = 0
a63 = -0.04245337201752043
a64 = 0.02446657898003141
a65 = 0.61943039072480676
a71 = 0.13659751177640291
a72 = 0
a73 = -0.05496908796538376
a74 = -0.04118626728321046
a75 = 0.62993304899016403
a76 = 0.06962479448202728
# Predictors taken from
# https://github.com/SciML/OrdinaryDiffEq.jl/blob/54fb35870fa402fc95d665cd5f9502e2759ea436/src/tableaus/sdirk_tableaus.jl#L1444 # noqa: E501
# https://github.com/SciML/OrdinaryDiffEq.jl/blob/54fb35870fa402fc95d665cd5f9502e2759ea436/src/perform_step/kencarp_kvaerno_perform_step.jl#L1123 # noqa: E501
# This is with the exception of α21, which is mistakenly set to zero.
#
# See also /devdocs/predictor_dirk.md
α21 = 1.0
α31 = -1.366025403784441
α32 = 2.3660254037844357
α41 = -0.19650552613122207
α42 = 0.8113579546496623
α43 = 0.38514757148155954
α51 = 0.10375304369958693
α52 = 0.937994698066431
α53 = -0.04174774176601781
α61 = -0.17281112873898072
α62 = 0.6235784481025847
α63 = 0.5492326806363959
α71 = a61
α72 = a62
α73 = a63
α74 = a64
α75 = a65
α76 = γ
_kvaerno5_tableau = ButcherTableau(
a_lower=(
np.array([a21]),
np.array([a31, a32]),
np.array([a41, a42, a43]),
np.array([a51, a52, a53, a54]),
np.array([a61, a62, a63, a64, a65]),
np.array([a71, a72, a73, a74, a75, a76]),
),
a_diagonal=np.array([0, γ, γ, γ, γ, γ, γ]),
a_predictor=(
np.array([α21]),
np.array([α31, α32]),
np.array([α41, α42, α43]),
np.array([α51, α52, α53, 0]),
np.array([α61, α62, α63, 0, 0]),
np.array([α71, α72, α73, α74, α75, α76]),
),
b_sol=np.array([a71, a72, a73, a74, a75, a76, γ]),
b_error=np.array(
[a71 - a61, a72 - a62, a73 - a63, a74 - a64, a75 - a65, a76 - γ, γ]
),
c=np.array(
[0.52, 1.230333209967908, 0.8957659843500759, 0.43639360985864756, 1.0, 1.0]
),
)
class Kvaerno5(AbstractESDIRK):
r"""Kvaerno's 5/4 method.
A-L stable stiffly accurate 5th order ESDIRK method. Has an embedded 4th order
method for adaptive step sizing. Uses 7 stages.
When solving an ODE over the interval $[t_0, t_1]$, note that this method will make
some evaluations slightly past $t_1$.
??? cite "Reference"
```bibtex
@article{kvaerno2004singly,
title={Singly diagonally implicit Runge--Kutta methods with an explicit first
stage},
author={Kv{\ae}rn{\o}, Anne},
journal={BIT Numerical Mathematics},
volume={44},
number={3},
pages={489--502},
year={2004},
publisher={Springer}
}
```
"""
tableau = _kvaerno5_tableau
interpolation_cls = ThirdOrderHermitePolynomialInterpolation.from_k
def order(self, terms):
return 5
| 28.274336 | 159 | 0.662285 | 916 | 0.282367 | 0 | 0 | 0 | 0 | 0 | 0 | 1,161 | 0.357891 |
e85933c7d3c26f637e88c1e491bd5d20ff1bfd18 | 2,783 | py | Python | Hinting/Remove Zero Deltas in Selected Glyphs.py | justanotherfoundry/Glyphs-Scripts | f28aeab0224ae19ace4a86cf363e7990985199b7 | [
"Apache-2.0"
] | 283 | 2015-01-07T12:35:35.000Z | 2022-03-29T06:10:44.000Z | Hinting/Remove Zero Deltas in Selected Glyphs.py | justanotherfoundry/Glyphs-Scripts | f28aeab0224ae19ace4a86cf363e7990985199b7 | [
"Apache-2.0"
] | 203 | 2015-01-26T18:43:08.000Z | 2022-03-04T01:47:58.000Z | Hinting/Remove Zero Deltas in Selected Glyphs.py | justanotherfoundry/Glyphs-Scripts | f28aeab0224ae19ace4a86cf363e7990985199b7 | [
"Apache-2.0"
] | 96 | 2015-01-19T20:58:03.000Z | 2022-03-29T06:10:56.000Z | #MenuTitle: Remove Zero Deltas in Selected Glyphs
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__doc__="""
Goes through all layers of each selected glyph, and deletes all TT Delta Hints with an offset of zero. Detailed Report in Macro Window.
"""
def process( Layer ):
try:
count = 0
for i in reversed(range(len(Layer.hints))):
hint = Layer.hints[i]
if hint.type == TTDELTA:
elementDict = hint.elementDict()
if "settings" in elementDict:
settings = elementDict["settings"]
if settings:
for deltaType in ("deltaH","deltaV"):
if deltaType in settings:
for transformType in settings[deltaType]:
deltas = settings[deltaType][transformType]
for ppmSize in deltas:
if deltas[ppmSize] == 0:
del deltas[ppmSize]
count += 1
# clean up delta PPMs:
if len(settings[deltaType][transformType]) == 0:
del settings[deltaType][transformType]
# clean up delta directions:
if len(settings[deltaType]) == 0:
del settings[deltaType]
# clean up hints:
if not elementDict["settings"]:
del Layer.hints[i]
print(" Deleted %i zero delta%s on layer '%s'." % (
count,
"" if count == 1 else "s",
Layer.name,
))
return count
except Exception as e:
Glyphs.showMacroWindow()
import traceback
print(traceback.format_exc())
print()
print(e)
thisFont = Glyphs.font # frontmost font
selectedLayers = thisFont.selectedLayers # active layers of selected glyphs
Glyphs.clearLog() # clears log in Macro window
totalCount = 0
for selectedLayer in selectedLayers:
thisGlyph = selectedLayer.parent
print("%s:" % thisGlyph.name)
thisGlyph.beginUndo() # begin undo grouping
for thisLayer in thisGlyph.layers:
totalCount += process( thisLayer )
thisGlyph.endUndo() # end undo grouping
if totalCount:
Message(
title="%i Zero Delta%s Deleted" % (
totalCount,
"" if totalCount == 1 else "s",
),
message="Deleted %i TT delta hint%s with zero offset in %i selected glyph%s (%s%s). Detailed report in Macro Window." % (
totalCount,
"" if totalCount == 1 else "s",
len(selectedLayers),
"" if len(selectedLayers) == 1 else "s",
", ".join([l.parent.name for l in selectedLayers[:min(20,len(selectedLayers))]]),
",..." if len(selectedLayers) > 20 else "",
),
OKButton=u"👍🏻 OK",
)
else:
Message(
title="No Zero Deltas",
message="No TT delta hints with zero offset were found in selected glyph%s (%s%s)." % (
"" if len(selectedLayers) == 1 else "s",
", ".join([l.parent.name for l in selectedLayers[:min(20,len(selectedLayers))]]),
",..." if len(selectedLayers) > 20 else "",
),
OKButton=u"🍸 Cheers")
| 30.582418 | 135 | 0.648581 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 795 | 0.284742 |
e859463755edefe59830e903e437712595e190d6 | 1,210 | py | Python | env/build.py | orestisfl/docker-env | 414f04c3e69c8c4015808a34be7376fdff4b3527 | [
"MIT"
] | null | null | null | env/build.py | orestisfl/docker-env | 414f04c3e69c8c4015808a34be7376fdff4b3527 | [
"MIT"
] | null | null | null | env/build.py | orestisfl/docker-env | 414f04c3e69c8c4015808a34be7376fdff4b3527 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import re
import sys
from glob import glob
from subprocess import run
def main(args):
assert len(args) >= 1
from_image = args.pop(0)
optional = [x for x in map(str.strip, args) if x]
optional_used = set()
with open("Dockerfile", "w") as fout:
print(f"from {from_image}", file=fout)
for fname in sorted(glob("*.Dockerfile")):
if fname.startswith("optional."):
if any(x in fname for x in optional):
optional_used.add(
re.search(
r"^optional\.(\d*\.)?(\S+?)\.Dockerfile$", fname
).groups()[1]
)
else:
continue
with open(fname) as fin:
print(fin.read().strip(), file=fout)
our_tag = "orestisfl/env"
if optional_used:
our_tag += "-" + "-".join(sorted(optional_used))
our_tag += ":" + from_image.split(":", 1)[1]
with open("image", "w") as f:
print(our_tag, file=f)
return run(["docker", "build", "-t", our_tag, "."], check=True)
if __name__ == "__main__":
print(main(sys.argv[1:]), file=sys.stderr)
| 28.139535 | 76 | 0.512397 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 192 | 0.158678 |
e85a4156b1efffe030e509e2baabc4ed59503b48 | 7,426 | py | Python | tiled/database/core.py | stuartcampbell/tiled | 01c054fa4638f2595a228173ea2f2c59a6a52500 | [
"BSD-3-Clause"
] | null | null | null | tiled/database/core.py | stuartcampbell/tiled | 01c054fa4638f2595a228173ea2f2c59a6a52500 | [
"BSD-3-Clause"
] | null | null | null | tiled/database/core.py | stuartcampbell/tiled | 01c054fa4638f2595a228173ea2f2c59a6a52500 | [
"BSD-3-Clause"
] | null | null | null | import hashlib
import uuid as uuid_module
from datetime import datetime
from alembic import command
from alembic.config import Config
from alembic.runtime import migration
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import func
from .alembic_utils import temp_alembic_ini
from .base import Base
from .orm import APIKey, Identity, Principal, Role, Session
# This is the alembic revision ID of the database revision
# required by this version of Tiled.
REQUIRED_REVISION = "481830dd6c11"
# This is set of all valid revisions.
ALL_REVISIONS = {"481830dd6c11"}
def create_default_roles(engine):
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
db = SessionLocal()
db.add(
Role(
name="user",
description="Default Role for users.",
scopes=["read:metadata", "read:data", "apikeys"],
),
)
db.add(
Role(
name="admin",
description="Role with elevated privileges.",
scopes=[
"read:metadata",
"read:data",
"admin:apikeys",
"read:principals",
"metrics",
],
),
)
db.commit()
def initialize_database(engine):
# The definitions in .orm alter Base.metadata.
from . import orm # noqa: F401
# Create all tables.
Base.metadata.create_all(engine)
# Initialize Roles table.
create_default_roles(engine)
# Mark current revision.
with temp_alembic_ini(engine.url) as alembic_ini:
alembic_cfg = Config(alembic_ini)
command.stamp(alembic_cfg, "head")
class UnrecognizedDatabase(Exception):
pass
class UninitializedDatabase(Exception):
pass
class DatabaseUpgradeNeeded(Exception):
pass
def get_current_revision(engine):
with engine.begin() as conn:
context = migration.MigrationContext.configure(conn)
heads = context.get_current_heads()
if heads == ():
return None
elif len(heads) != 1:
raise UnrecognizedDatabase(
f"This database {engine.url} is stamped with an alembic revisions {heads}. "
"It looks like Tiled has been configured to connect to a database "
"already populated by some other application (not Tiled) or else "
"its database is in a corrupted state."
)
(revision,) = heads
if revision not in ALL_REVISIONS:
raise UnrecognizedDatabase(
f"The datbase {engine.url} has an unrecognized revision {revision}. "
"It may have been created by a newer version of Tiled."
)
return revision
def check_database(engine):
revision = get_current_revision(engine)
if revision is None:
raise UninitializedDatabase(
f"The database {engine.url} has no revision stamp. It may be empty. "
"It can be initialized with `initialize_database(engine)`."
)
elif revision != REQUIRED_REVISION:
raise DatabaseUpgradeNeeded(
f"The database {engine.url} has revision {revision} and "
f"needs to be upgraded to revision {REQUIRED_REVISION}."
)
def purge_expired(engine, cls):
"""
Remove expired entries.
Return reference to cls, supporting usage like
>>> db.query(purge_expired(engine, orm.APIKey))
"""
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
db = SessionLocal()
now = datetime.utcnow()
deleted = False
for obj in (
db.query(cls)
.filter(cls.expiration_time.is_not(None))
.filter(cls.expiration_time < now)
):
deleted = True
db.delete(obj)
if deleted:
db.commit()
return cls
def create_user(db, identity_provider, id):
principal = Principal(type="user")
user_role = db.query(Role).filter(Role.name == "user").first()
principal.roles.append(user_role)
db.add(principal)
db.commit()
db.refresh(principal) # Refresh to sync back the auto-generated uuid.
identity = Identity(
provider=identity_provider,
id=id,
principal_id=principal.id,
)
db.add(identity)
db.commit()
return principal
def lookup_valid_session(db, session_id):
if isinstance(session_id, int):
# Old versions of tiled used an integer sid.
# Reject any of those old sessions and force reauthentication.
return None
session = (
db.query(Session)
.filter(Session.uuid == uuid_module.UUID(hex=session_id))
.first()
)
if (
session.expiration_time is not None
and session.expiration_time < datetime.utcnow()
):
db.delete(session)
db.commit()
return None
return session
def make_admin_by_identity(db, identity_provider, id):
identity = (
db.query(Identity)
.filter(Identity.id == id)
.filter(Identity.provider == identity_provider)
.first()
)
if identity is None:
principal = create_user(db, identity_provider, id)
else:
principal = identity.principal
admin_role = db.query(Role).filter(Role.name == "admin").first()
principal.roles.append(admin_role)
db.commit()
return principal
def lookup_valid_api_key(db, secret):
"""
Look up an API key. Ensure that it is valid.
"""
now = datetime.utcnow()
hashed_secret = hashlib.sha256(secret).digest()
api_key = (
db.query(APIKey)
.filter(APIKey.first_eight == secret.hex()[:8])
.filter(APIKey.hashed_secret == hashed_secret)
.first()
)
if api_key is None:
# No match
validated_api_key = None
elif (api_key.expiration_time is not None) and (api_key.expiration_time < now):
# Match is expired. Delete it.
db.delete(api_key)
db.commit()
validated_api_key = None
elif api_key.principal is None:
# The Principal for the API key no longer exists. Delete it.
db.delete(api_key)
db.commit()
validated_api_key = None
else:
validated_api_key = api_key
return validated_api_key
def latest_principal_activity(db, principal):
"""
The most recent time this Principal has logged in with an Identity,
refreshed a Session, or used an APIKey.
Note that activity that is authenticated using an access token is not
captured here. As usual with JWTs, those requests do not interact with
this database, for performance reasons. Therefore, this may lag actual
activity by as much as the max age of an access token (default: 15
minutes).
"""
latest_identity_activity = (
db.query(func.max(Identity.latest_login))
.filter(Identity.principal_id == principal.id)
.scalar()
)
latest_session_activity = (
db.query(func.max(Session.time_last_refreshed))
.filter(Session.principal_id == principal.id)
.scalar()
)
latest_api_key_activity = (
db.query(func.max(APIKey.latest_activity))
.filter(APIKey.principal_id == principal.id)
.scalar()
)
all_activity = [
latest_identity_activity,
latest_api_key_activity,
latest_session_activity,
]
if all([t is None for t in all_activity]):
return None
return max(t for t in all_activity if t is not None)
| 28.561538 | 88 | 0.643011 | 143 | 0.019257 | 0 | 0 | 0 | 0 | 0 | 0 | 1,990 | 0.267977 |
e85a582b4835c961353024f23cb7838de54c38e5 | 24 | py | Python | torchvision/prototype/utils/__init__.py | yoshitomo-matsubara/vision | 03d11338f3faf94a0749549912593ddb8b70be17 | [
"BSD-3-Clause"
] | 12,063 | 2017-01-18T19:58:38.000Z | 2022-03-31T23:08:44.000Z | torchvision/prototype/utils/__init__.py | yoshitomo-matsubara/vision | 03d11338f3faf94a0749549912593ddb8b70be17 | [
"BSD-3-Clause"
] | 4,673 | 2017-01-18T21:30:03.000Z | 2022-03-31T20:58:33.000Z | torchvision/prototype/utils/__init__.py | yoshitomo-matsubara/vision | 03d11338f3faf94a0749549912593ddb8b70be17 | [
"BSD-3-Clause"
] | 7,132 | 2017-01-18T18:12:23.000Z | 2022-03-31T21:19:10.000Z | from . import _internal
| 12 | 23 | 0.791667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
e85b7d80337b2ce535d2c6a0de4c783b4a069765 | 13,108 | py | Python | py/models.py | ti-ginkgo/Severstal | 57f37dc61cfd910b575afa7dc51094c94e3511c0 | [
"MIT"
] | 2 | 2020-01-08T02:58:18.000Z | 2020-01-28T16:42:00.000Z | py/models.py | ti-ginkgo/Severstal | 57f37dc61cfd910b575afa7dc51094c94e3511c0 | [
"MIT"
] | null | null | null | py/models.py | ti-ginkgo/Severstal | 57f37dc61cfd910b575afa7dc51094c94e3511c0 | [
"MIT"
] | null | null | null | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
class FPAv2(nn.Module):
def __init__(self, input_dim, output_dim):
super(FPAv2, self).__init__()
self.glob = nn.Sequential(nn.AdaptiveAvgPool2d(1),
nn.Conv2d(input_dim, output_dim, kernel_size=1, bias=False))
self.down2_1 = nn.Sequential(nn.Conv2d(input_dim, input_dim, kernel_size=5, stride=2, padding=2, bias=False),
nn.BatchNorm2d(input_dim),
nn.ELU(True))
self.down2_2 = nn.Sequential(nn.Conv2d(input_dim, output_dim, kernel_size=5, padding=2, bias=False),
nn.BatchNorm2d(output_dim),
nn.ELU(True))
self.down3_1 = nn.Sequential(nn.Conv2d(input_dim, input_dim, kernel_size=3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(input_dim),
nn.ELU(True))
self.down3_2 = nn.Sequential(nn.Conv2d(input_dim, output_dim, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(output_dim),
nn.ELU(True))
self.conv1 = nn.Sequential(nn.Conv2d(input_dim, output_dim, kernel_size=1, bias=False),
nn.BatchNorm2d(output_dim),
nn.ELU(True))
def forward(self, x):
# x shape: 512, 16, 16
x_glob = self.glob(x) # 256, 1, 1
x_glob = F.upsample(x_glob, scale_factor=16, mode='bilinear', align_corners=True) # 256, 16, 16
d2 = self.down2_1(x) # 512, 8, 8
d3 = self.down3_1(d2) # 512, 4, 4
d2 = self.down2_2(d2) # 256, 8, 8
d3 = self.down3_2(d3) # 256, 4, 4
d3 = F.upsample(d3, scale_factor=2, mode='bilinear', align_corners=True) # 256, 8, 8
d2 = d2 + d3
d2 = F.upsample(d2, scale_factor=2, mode='bilinear', align_corners=True) # 256, 16, 16
x = self.conv1(x) # 256, 16, 16
x = x * d2
x = x + x_glob
return x
def conv3x3(input_dim, output_dim, rate=1):
return nn.Sequential(nn.Conv2d(input_dim, output_dim, kernel_size=3, dilation=rate, padding=rate, bias=False),
nn.BatchNorm2d(output_dim),
nn.ELU(True))
class SpatialAttention2d(nn.Module):
def __init__(self, channel):
super(SpatialAttention2d, self).__init__()
self.squeeze = nn.Conv2d(channel, 1, kernel_size=1, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
z = self.squeeze(x)
z = self.sigmoid(z)
return x * z
class GAB(nn.Module):
def __init__(self, input_dim, reduction=4):
super(GAB, self).__init__()
self.global_avgpool = nn.AdaptiveAvgPool2d(1)
self.conv1 = nn.Conv2d(input_dim, input_dim // reduction, kernel_size=1, stride=1)
self.conv2 = nn.Conv2d(input_dim // reduction, input_dim, kernel_size=1, stride=1)
self.relu = nn.ReLU(inplace=True)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
z = self.global_avgpool(x)
z = self.relu(self.conv1(z))
z = self.sigmoid(self.conv2(z))
return x * z
class Decoder(nn.Module):
def __init__(self, in_channels, channels, out_channels):
super(Decoder, self).__init__()
self.conv1 = conv3x3(in_channels, channels)
self.conv2 = conv3x3(channels, out_channels)
self.s_att = SpatialAttention2d(out_channels)
self.c_att = GAB(out_channels, 16)
def forward(self, x, e=None):
x = F.upsample(input=x, scale_factor=2, mode='bilinear', align_corners=True)
if e is not None:
x = torch.cat([x, e], 1)
x = self.conv1(x)
x = self.conv2(x)
s = self.s_att(x)
c = self.c_att(x)
output = s + c
return output
class Decoderv2(nn.Module):
def __init__(self, up_in, x_in, n_out):
super(Decoderv2, self).__init__()
up_out = x_out = n_out // 2
self.x_conv = nn.Conv2d(x_in, x_out, 1, bias=False)
self.tr_conv = nn.ConvTranspose2d(up_in, up_out, 2, stride=2)
self.bn = nn.BatchNorm2d(n_out)
self.relu = nn.ReLU(True)
self.s_att = SpatialAttention2d(n_out)
self.c_att = GAB(n_out, 16)
def forward(self, up_p, x_p):
up_p = self.tr_conv(up_p)
x_p = self.x_conv(x_p)
cat_p = torch.cat([up_p, x_p], 1)
cat_p = self.relu(self.bn(cat_p))
s = self.s_att(cat_p)
c = self.c_att(cat_p)
return s + c
class SCse(nn.Module):
def __init__(self, dim):
super(SCse, self).__init__()
self.satt = SpatialAttention2d(dim)
self.catt = GAB(dim)
def forward(self, x):
return self.satt(x) + self.catt(x)
# stage1 model
class Res34Unetv4(nn.Module):
def __init__(self, n_classes=4):
super(Res34Unetv4, self).__init__()
self.resnet = torchvision.models.resnet34(True)
self.conv1 = nn.Sequential(
self.resnet.conv1,
self.resnet.bn1,
self.resnet.relu)
self.encode2 = nn.Sequential(self.resnet.layer1,
SCse(64))
self.encode3 = nn.Sequential(self.resnet.layer2,
SCse(128))
self.encode4 = nn.Sequential(self.resnet.layer3,
SCse(256))
self.encode5 = nn.Sequential(self.resnet.layer4,
SCse(512))
self.center = nn.Sequential(FPAv2(512, 256),
nn.MaxPool2d(2, 2))
self.decode5 = Decoderv2(256, 512, 64)
self.decode4 = Decoderv2(64, 256, 64)
self.decode3 = Decoderv2(64, 128, 64)
self.decode2 = Decoderv2(64, 64, 64)
self.decode1 = Decoder(64, 32, 64)
self.logit = nn.Sequential(nn.Conv2d(320, 64, kernel_size=3, padding=1),
nn.ELU(True),
nn.Conv2d(64, n_classes, kernel_size=1, bias=False))
def forward(self, x):
# x: (batch_size, 3, 256, 256)
x = self.conv1(x) # 64, 128, 128
e2 = self.encode2(x) # 64, 128, 128
e3 = self.encode3(e2) # 128, 64, 64
e4 = self.encode4(e3) # 256, 32, 32
e5 = self.encode5(e4) # 512, 16, 16
f = self.center(e5) # 256, 8, 8
d5 = self.decode5(f, e5) # 64, 16, 16
d4 = self.decode4(d5, e4) # 64, 32, 32
d3 = self.decode3(d4, e3) # 64, 64, 64
d2 = self.decode2(d3, e2) # 64, 128, 128
d1 = self.decode1(d2) # 64, 256, 256
f = torch.cat((d1,
F.upsample(d2, scale_factor=2, mode='bilinear', align_corners=True),
F.upsample(d3, scale_factor=4, mode='bilinear', align_corners=True),
F.upsample(d4, scale_factor=8, mode='bilinear', align_corners=True),
F.upsample(d5, scale_factor=16, mode='bilinear', align_corners=True)), 1) # 320, 256, 256
logit = self.logit(f) # n_classes, 256, 256
return logit
# stage2 model
class Res34Unetv3(nn.Module):
def __init__(self, n_classes=4):
super(Res34Unetv3, self).__init__()
self.resnet = torchvision.models.resnet34(True)
self.conv1 = nn.Sequential(
self.resnet.conv1,
self.resnet.bn1,
self.resnet.relu)
self.encode2 = nn.Sequential(self.resnet.layer1,
SCse(64))
self.encode3 = nn.Sequential(self.resnet.layer2,
SCse(128))
self.encode4 = nn.Sequential(self.resnet.layer3,
SCse(256))
self.encode5 = nn.Sequential(self.resnet.layer4,
SCse(512))
self.center = nn.Sequential(FPAv2(512, 256),
nn.MaxPool2d(2, 2))
self.decode5 = Decoderv2(256, 512, 64)
self.decode4 = Decoderv2(64, 256, 64)
self.decode3 = Decoderv2(64, 128, 64)
self.decode2 = Decoderv2(64, 64, 64)
self.decode1 = Decoder(64, 32, 64)
self.dropout2d = nn.Dropout2d(0.4)
self.dropout = nn.Dropout(0.4)
self.fuse_pixel = conv3x3(320, 64)
self.logit_pixel = nn.Conv2d(64, 1, kernel_size=1, bias=False)
self.fuse_image = nn.Sequential(nn.Linear(512, 64),
nn.ELU(True))
self.logit_image = nn.Sequential(nn.Linear(64, 1),
nn.Sigmoid())
self.logit = nn.Sequential(nn.Conv2d(128, 64, kernel_size=3, padding=1, bias=False),
nn.ELU(True),
nn.Conv2d(64, n_classes, kernel_size=1, bias=False))
def forward(self, x):
# x: (batch_size, 3, 256, 256)
batch_size, c, h, w = x.shape
x = self.conv1(x) # 64, 128, 128
e2 = self.encode2(x) # 64, 128, 128
e3 = self.encode3(e2) # 128, 64, 64
e4 = self.encode4(e3) # 256, 32, 32
e5 = self.encode5(e4) # 512, 16, 16
e = F.adaptive_avg_pool2d(e5, output_size=1).view(batch_size, -1) # 512
e = self.dropout(e)
f = self.center(e5) # 256, 8, 8
d5 = self.decode5(f, e5) # 64, 16, 16
d4 = self.decode4(d5, e4) # 64, 32, 32
d3 = self.decode3(d4, e3) # 64, 64, 64
d2 = self.decode2(d3, e2) # 64, 128, 128
d1 = self.decode1(d2) # 64, 256, 256
f = torch.cat((d1,
F.upsample(d2, scale_factor=2, mode='bilinear', align_corners=True),
F.upsample(d3, scale_factor=4, mode='bilinear', align_corners=True),
F.upsample(d4, scale_factor=8, mode='bilinear', align_corners=True),
F.upsample(d5, scale_factor=16, mode='bilinear', align_corners=True)), 1) # 320, 256, 256
f = self.dropout2d(f)
# segmentation process
fuse_pixel = self.fuse_pixel(f) # 64, 256, 256
logit_pixel = self.logit_pixel(fuse_pixel) # 1, 256, 256
# classification process
fuse_image = self.fuse_image(e) # 64
logit_image = self.logit_image(fuse_image) # 1
# combine segmentation and classification
fuse = torch.cat([fuse_pixel,
F.upsample(fuse_image.view(batch_size, -1, 1, 1), scale_factor=256, mode='bilinear',
align_corners=True)], 1) # 128, 256, 256
logit = self.logit(fuse) # n_classes, 256, 256
return logit, logit_pixel, logit_image.view(-1)
# stage3 model
class Res34Unetv5(nn.Module):
def __init__(self, n_classes):
super(Res34Unetv5, self).__init__()
self.resnet = torchvision.models.resnet34(True)
self.conv1 = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False),
self.resnet.bn1,
self.resnet.relu)
self.encode2 = nn.Sequential(self.resnet.layer1,
SCse(64))
self.encode3 = nn.Sequential(self.resnet.layer2,
SCse(128))
self.encode4 = nn.Sequential(self.resnet.layer3,
SCse(256))
self.encode5 = nn.Sequential(self.resnet.layer4,
SCse(512))
self.center = nn.Sequential(FPAv2(512, 256),
nn.MaxPool2d(2, 2))
self.decode5 = Decoderv2(256, 512, 64)
self.decode4 = Decoderv2(64, 256, 64)
self.decode3 = Decoderv2(64, 128, 64)
self.decode2 = Decoderv2(64, 64, 64)
self.logit = nn.Sequential(nn.Conv2d(256, 32, kernel_size=3, padding=1),
nn.ELU(True),
nn.Conv2d(32, n_classes, kernel_size=1, bias=False))
def forward(self, x):
# x: batch_size, 3, 128, 128
x = self.conv1(x) # 64, 128, 128
e2 = self.encode2(x) # 64, 128, 128
e3 = self.encode3(e2) # 128, 64, 64
e4 = self.encode4(e3) # 256, 32, 32
e5 = self.encode5(e4) # 512, 16, 16
f = self.center(e5) # 256, 8, 8
d5 = self.decode5(f, e5) # 64, 16, 16
d4 = self.decode4(d5, e4) # 64, 32, 32
d3 = self.decode3(d4, e3) # 64, 64, 64
d2 = self.decode2(d3, e2) # 64, 128, 128
f = torch.cat((d2,
F.upsample(d3, scale_factor=2, mode='bilinear', align_corners=True),
F.upsample(d4, scale_factor=4, mode='bilinear', align_corners=True),
F.upsample(d5, scale_factor=8, mode='bilinear', align_corners=True)), 1) # 256, 128, 128
f = F.dropout2d(f, p=0.4)
logit = self.logit(f) # n_classes, 128, 128
return logit | 38.104651 | 117 | 0.537382 | 12,698 | 0.968721 | 0 | 0 | 0 | 0 | 0 | 0 | 1,078 | 0.08224 |
e85c2c9c74527b46aef466680cba313a99e7950d | 2,762 | py | Python | gameNode_test.py | rcolomina/pythonchess | 1b12ea4a1668da6c47dd39ff16d1e48af33ea2f5 | [
"MIT"
] | null | null | null | gameNode_test.py | rcolomina/pythonchess | 1b12ea4a1668da6c47dd39ff16d1e48af33ea2f5 | [
"MIT"
] | 2 | 2016-11-01T09:57:36.000Z | 2016-11-01T10:05:50.000Z | gameNode_test.py | rcolomina/pythonchess | 1b12ea4a1668da6c47dd39ff16d1e48af33ea2f5 | [
"MIT"
] | null | null | null | #!/usr/bin/python
from piece import Piece
from gameNode import GameNode
from functions import *
from minmax import MinMax
## TEST 1: GameNode cration. Generating list of movements on a game node by piece
print "TEST 1: Building a Game Node"
listPiecesWhite=[]
listPiecesBlack=[]
p1=Piece('Q',[2,1])
p2=Piece('N',[2,2])
p3=Piece('q',[1,4])
listPiecesWhite.append(p1)
listPiecesWhite.append(p2)
listPiecesBlack.append(p3)
gameNode=GameNode(listPiecesWhite,listPiecesBlack,"white")
assert(genListMovsPiece(gameNode,p3)==[[2,4],[3,4],[4,4],[1,1],[1,2],[1,3],[2,3],[3,2],[4,1]])
assert(not checkPieceMovValid(gameNode,p3,[4,2])) # Black Queen cannot move to [4,2], ilegal move
print "Checked movements for black queen: Black Queen cannot move to [4,2], ilegal move"
assert(not checkPieceMovValid(gameNode,p2,[4,4])) # White Knight cannot move to [4,4], ilegal move
print "Checked movements for white knight: White Knight cannot move to [4,4], ilegal move"
assert(not checkPieceMovValid(gameNode,p1,[2,4])) # White Queen cannot move to [2,4], White Knight in the middle
print "Checked movements for white queen: White Queen cannot move to [2,4], cose white Knight in the middle"
assert(not checkPieceMovValid(gameNode,p1,[2,2])) # White Queen cannot move to [2,2], White Knight on it
print "Checked movements for white queen: White Queen cannot move to [2,2], cose white Knight is over it"
# Game Successors
print "--"
print "TEST 2: Check whether white wins after a queen do an eat movement"
####
listPiecesWhite=[]
listPiecesBlack=[]
p1=Piece('Q',[2,1])
listPiecesWhite.append(p1)
p2=Piece('q',[1,4])
listPiecesBlack.append(p2)
gameNode=GameNode(listPiecesWhite,listPiecesBlack,"white")
print gameNode.draw()
mov=[1,1]
piece=p1
gameNodeChild=gameNode.succesGameActionMove(piece,mov)
print gameNodeChild.draw()
assert(not gameNode.checkWhiteWin())
print "Num black pieces:", gameNodeChild.numBlackPieces()
assert(gameNodeChild.numBlackPieces()==1)
#gameNodeChild.draw()
assert(not gameNodeChild.checkWhiteWin())
print "Checked that white not win"
assert(gameNodeChild.numBlackPieces()==1)
mov=[1,4] # position of black queen
piece=p2 # capturing black queen by white knight
gameNodeChild=gameNode.succesGameActionMove(piece,mov)
#gameNodeChild.draw()
#assert(gameNodeChild.checkWhiteWin())
#assert(gameNodeChild.numBlackPieces()==0)
print "--"
print "TEST 3: Generate all games nodes since a given game"
listGameNodes=genListNextGameNodesForcingColor(gameNode,"black")
assert(len(listGameNodes)==9)
print "Number for black choises is 9"
listGameNodes=genListNextGameNodesForcingColor(gameNode,"white")
assert(len(listGameNodes)==9)
print "Number for white choises is 9"
listGameNodes=genListNextGameNodes(gameNode)
#assert(len(listGameNodes)==10)
| 36.342105 | 112 | 0.763939 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,225 | 0.443519 |
e85d61e1906d246b4773a7b76f1abb85b59acc9c | 2,792 | py | Python | discordlogger.py | tjb0607/discord-logger | 5edabeadf124d7de484b3ee3cbc563567846f610 | [
"WTFPL"
] | 3 | 2018-04-20T03:05:57.000Z | 2021-04-15T23:17:43.000Z | discordlogger.py | tjb0607/discord-logger | 5edabeadf124d7de484b3ee3cbc563567846f610 | [
"WTFPL"
] | null | null | null | discordlogger.py | tjb0607/discord-logger | 5edabeadf124d7de484b3ee3cbc563567846f610 | [
"WTFPL"
] | 1 | 2021-06-01T03:50:37.000Z | 2021-06-01T03:50:37.000Z | #!/usr/bin/python3
# WARNING: Self-botting is technically against the rules, so this script could potentially get you banned.
import http.client
import json
import urllib
import time
import getpass
import os.path
import datetime
import sys
from dateutil.parser import parse
print("usage: python3 discordlogger.py <channel id>")
after = 0
channel = sys.argv[1]
if ( os.path.isfile('./.discord-' + channel + '.log.lastmessageid') ):
infile = open('./.discord-' + channel + '.log.lastmessageid', 'r')
after = int(infile.read())
infile.close()
c = http.client.HTTPSConnection('discordapp.com', 443)
## using /api/auth/login, ESPECIALLY with 2fa enabled, "will" get your account banned.
## https://github.com/hammerandchisel/discord-api-docs/issues/69#issuecomment-223886862
#email = input("Email: ")
#password = getpass.getpass("Password: ")
#token = ""
#c.request("POST", "https://discordapp.com/api/auth/login", json.dumps({"email": email, "password": password}), {"Content-type": "application/json"})
#password = ""
#response = json.loads(c.getresponse().read().decode("utf-8"))
#if "mfa" in response and "ticket" in response:
# code = input("2FA code: ")
# c.request("POST", "https://discordapp.com/api/auth/mfa/totp", json.dumps({"ticket": response["ticket"], "code": code}), {"Content-type": "application/json"})
# response = json.loads(c.getresponse().read().decode("utf-8"))
#token = response["token"]
print("""
Get your API token from Discord. This will give this script full access to your Discord account.
1. Open the console in Discord (Ctrl+Shift+I)
2. Go to the Application tab
3. Expand "Local Storage" on the left side panel
4. Select "https://discordapp.com"
5. Copy the value for Token, without the quotes.
""")
token = input("Token: ")
outfile = open("./discord-" + channel + ".log", "a")
done = 0
while done == 0:
c.request("GET", "https://discordapp.com/api/channels/" + channel + "/messages?" + urllib.parse.urlencode({"after": str(after), "limit": "50", "token": token}))
response = c.getresponse()
if response.status == 200:
messages = json.loads(response.read().decode("utf-8"))
if len(messages) > 0:
for message in reversed(messages):
outfile.write("[" + parse(message['timestamp']).astimezone(tz=None).strftime('%Y-%m-%d %H:%M:%S') + "] <" + message['author']['username'] + "> " + message['content'] + "\n")
for a in message['attachments']:
outfile.write('[[ attachment: ' + a['url'] + ' ]]\n')
after = messages[0]['id']
else:
print("Last message ID: " + after)
done = 1
else:
print("fatal error: api responded with status " + str(response.status))
done = 2
time.sleep(0.25)
outfile.close()
if done == 1:
outfile = open("./.discord-" + channel + ".log.lastmessageid", "w")
outfile.write(after)
outfile.close()
| 34.9 | 177 | 0.675501 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,699 | 0.608524 |
e85d901b9a66e6dab5e48109549c08960eee01b8 | 3,555 | py | Python | msschem/runner.py | andreas-h/mss-chem | ae91f4f5b4c19a4ff0ce8fd342fe0aed4ce2b9ab | [
"MIT"
] | null | null | null | msschem/runner.py | andreas-h/mss-chem | ae91f4f5b4c19a4ff0ce8fd342fe0aed4ce2b9ab | [
"MIT"
] | 8 | 2017-06-09T22:19:00.000Z | 2017-08-10T10:44:01.000Z | msschem/runner.py | andreas-h/mss-chem | ae91f4f5b4c19a4ff0ce8fd342fe0aed4ce2b9ab | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import datetime
import logging
import os.path
import runpy
import sys
VERBOSE = True
QUIET = False
# TODO allow parallel download of different models
# TODO allow parallel download of species (??)
def _valid_date(s):
try:
return datetime.datetime.strptime(s, "%Y-%m-%d").date()
except ValueError:
msg = "Not a valid date: '{0}'.".format(s)
raise argparse.ArgumentTypeError(msg)
def _setup_logging(level):
log = logging.getLogger('msschem')
log.setLevel(level)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
log.addHandler(ch)
def _setup_argparse():
parser = argparse.ArgumentParser(description='MSS-Chem downloader')
datagroup = parser.add_mutually_exclusive_group(required=True)
datagroup.add_argument('-m', '--model', type=str, default='',
help='Model to download')
datagroup.add_argument('-a', '--all', action='store_true',
help='Download data from all configured models')
parser.add_argument('-d', '--date', type=_valid_date,
default=datetime.date.today(),
help='Date to download data for (YYYY-MM-DD)')
parser.add_argument('-p', '--prune', type=int,
help='Delete data older than PRUNE days')
parser.add_argument('-c', '--config', type=str, default='',
help='MSS-Chem configuration file')
loggroup = parser.add_mutually_exclusive_group()
loggroup.add_argument('-q', '--quiet', action='store_true',
help='No output except for errors')
loggroup.add_argument('-v', '--verbosity', action='count', default=0,
help='Increase output verbosity (can be supplied '
'multiple times)')
return parser
def read_config(configfile):
if configfile:
configfile = os.path.expanduser(configfile)
if os.path.isfile(configfile):
try:
cfg = runpy.run_path(configfile)['datasources']
except:
raise ValueError('Cannot read configuration from file {}'
''.format(configfile))
else:
raise IOError('Configuration file {} does not exist'
''.format(configfile))
else:
from msschem_settings import datasources as cfg
return cfg
if __name__ == '__main__':
parser = _setup_argparse()
args = parser.parse_args()
if args.verbosity > 1:
loglevel = logging.DEBUG
elif args.verbosity == 1:
loglevel = logging.INFO
elif not args.quiet:
loglevel = logging.WARN
else:
loglevel = logging.ERROR
_setup_logging(loglevel)
fcinit = datetime.datetime(args.date.year, args.date.month, args.date.day)
datasources = read_config(args.config)
if args.model:
datasources[args.model].run(fcinit)
if args.prune:
try:
datasources[args.model].prune(args.prune)
except:
raise
sys.exit(0)
else:
for driver in datasources.values():
driver.run(fcinit)
if args.prune:
try:
driver.prune(args.prune)
except:
raise
sys.exit(0)
| 29.87395 | 78 | 0.587623 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 717 | 0.201688 |
e85e3de5145f8dac30242067d292b32a4de7ac35 | 609 | py | Python | oscar_mws/fulfillment/__init__.py | ButchershopCreative/django-oscar-mws | 582adc78f59578dbdf83d3ac145abc6bfc4a65ca | [
"BSD-3-Clause"
] | 12 | 2015-03-16T03:45:59.000Z | 2021-03-30T10:58:46.000Z | oscar_mws/fulfillment/__init__.py | ButchershopCreative/django-oscar-mws | 582adc78f59578dbdf83d3ac145abc6bfc4a65ca | [
"BSD-3-Clause"
] | 3 | 2016-01-05T17:45:13.000Z | 2019-04-27T12:01:53.000Z | oscar_mws/fulfillment/__init__.py | ButchershopCreative/django-oscar-mws | 582adc78f59578dbdf83d3ac145abc6bfc4a65ca | [
"BSD-3-Clause"
] | 20 | 2015-04-10T19:17:08.000Z | 2021-07-27T03:53:13.000Z | from django.utils.translation import ugettext_lazy as _
SHIPPING_STANDARD = 'Standard'
SHIPPING_EXPEDITED = 'Expedited'
SHIPPING_PRIORITY = 'Priority'
SHIPPING_SPEED_CATEGORIES = (
(SHIPPING_STANDARD, _("Standard")),
(SHIPPING_EXPEDITED, _("Expedited")),
(SHIPPING_PRIORITY, _("Priority")),
)
METHOD_CONSUMER = 'Consumer'
METHOD_REMOVAL = 'Removal'
FULFILLMENT_METHODS = (
(METHOD_CONSUMER, _("Consumer")),
(METHOD_REMOVAL, _("Removal")),
)
FILL_OR_KILL = 'FillOrKill'
FILL_ALL = 'FillAll'
FILL_ALL_AVAILABLE = 'FillAllAvailable'
class MwsFulfillmentError(BaseException):
pass
| 21 | 55 | 0.740558 | 50 | 0.082102 | 0 | 0 | 0 | 0 | 0 | 0 | 139 | 0.228243 |
e8608fa57e48149116847118e359bdf6450a3512 | 2,155 | py | Python | utils/Deque.py | FedePeralta/ASVs_Deep_Reinforcement_Learning_with_CNNs | 23b9b181499a4b06f2ca2951c002359c1959e727 | [
"MIT"
] | 4 | 2021-03-22T12:42:55.000Z | 2021-12-13T03:03:52.000Z | utils/Deque.py | FedePeralta/ASVs_Deep_Reinforcement_Learning_with_CNNs | 23b9b181499a4b06f2ca2951c002359c1959e727 | [
"MIT"
] | null | null | null | utils/Deque.py | FedePeralta/ASVs_Deep_Reinforcement_Learning_with_CNNs | 23b9b181499a4b06f2ca2951c002359c1959e727 | [
"MIT"
] | 1 | 2021-03-22T12:48:21.000Z | 2021-03-22T12:48:21.000Z | import numpy as np
from utils.Node import Node
class Deque(object):
"""Generic deque object"""
def __init__(self, max_size, dimension_of_value_attribute):
self.max_size = max_size
self.dimension_of_value_attribute = dimension_of_value_attribute
self.deque = self.initialise_deque()
self.deque_index_to_overwrite_next = 0
self.reached_max_capacity = False
self.number_experiences_in_deque = 0
def initialise_deque(self):
"""Initialises a queue of Nodes of length self.max_size"""
deque = np.array([Node(0, tuple([None for _ in range(self.dimension_of_value_attribute)])) for _ in range(self.max_size)])
return deque
def add_element_to_deque(self, new_key, new_value):
"""Adds an element to the deque and then updates the index of the next element to be overwritten and also the
amount of elements in the deque"""
self.update_deque_node_key_and_value(self.deque_index_to_overwrite_next, new_key, new_value)
self.update_number_experiences_in_deque()
self.update_deque_index_to_overwrite_next()
def update_deque_node_key_and_value(self, index, new_key, new_value):
self.update_deque_node_key(index, new_key)
self.update_deque_node_value(index, new_value)
def update_deque_node_key(self, index, new_key):
self.deque[index].update_key(new_key)
def update_deque_node_value(self, index, new_value):
self.deque[index].update_value(new_value)
def update_deque_index_to_overwrite_next(self):
"""Updates the deque index that we should write over next. When the buffer gets full we begin writing over
older experiences"""
if self.deque_index_to_overwrite_next < self.max_size - 1:
self.deque_index_to_overwrite_next += 1
else:
self.reached_max_capacity = True
self.deque_index_to_overwrite_next = 0
def update_number_experiences_in_deque(self):
"""Keeps track of how many experiences there are in the buffer"""
if not self.reached_max_capacity:
self.number_experiences_in_deque += 1 | 43.979592 | 130 | 0.716009 | 2,107 | 0.977726 | 0 | 0 | 0 | 0 | 0 | 0 | 437 | 0.202784 |
e8612671385af374097910161c09d6d0e54b699c | 14,580 | py | Python | main.py | fedegy/Practica-1-Lenguajes-Formales | d0910bbfb9c9a0fce92114ab3a0af3e8ad606855 | [
"Apache-2.0"
] | null | null | null | main.py | fedegy/Practica-1-Lenguajes-Formales | d0910bbfb9c9a0fce92114ab3a0af3e8ad606855 | [
"Apache-2.0"
] | null | null | null | main.py | fedegy/Practica-1-Lenguajes-Formales | d0910bbfb9c9a0fce92114ab3a0af3e8ad606855 | [
"Apache-2.0"
] | null | null | null | import os
from tkinter import *
from tkinter import filedialog
global archivo
archivo= []
cadena2 = []
archivo = []
global cadena_inicial
cadena_inicial = []
global lista_numeros
lista_numeros = []
global intlist
intlist= []
global numeros1
numeros1=[]
global lista_buscar2
lista_buscar2 = []
lista_buscar_numero = []
global ordenar
ordenar=[]
global lista_ordenar
lista_ordenar=[]
global ordenar_final
ordenar_final=[]
global numeros_html_2
numeros_html_2=[]
global lista2
lista2=[]
global lista_ruta
lista_ruta=[]
global lista_buscar3
lista_buscar3=[]
global lista_numeros_anidados
lista_numeros_anidados=[]
global lista_numeros_anidados_buscar
lista_numeros_anidados_buscar=[]
global intlist4
intlist4=[]
global lista_numeros2_buscar
lista_numeros2_buscar=[]
def buscar_(lista,key):
lista2=[]
flag=False
for i in range(len(lista)):
if lista[i]==key:
flag=True
lista2.append(i)
if flag==True:
print("")
else:
return "No se encontro el número"
return lista2
def ordenamiento_burbuja(lista):
n=len(lista)
for i in range(n-1):
for j in range(0,n-i-1):
if lista[j]>lista[j+1]:
lista[j],lista[j+1]=lista[j+1],lista[j]
return lista
def inicio():
while True:
print("\n")
print("\t1) Cargar Archivo de Entrada")
print("\t2) Desplegar listas ordenadas")
print("\t3) Desplegar búsquedas")
print("\t4) Desplegar todas")
print("\t5) Desplegar todas a archivos")
print("\t6. Salir")
ruta=""
global file_path
op = int(input("\tEliga una opción\n"))
if op == 1:
root=Tk()
root.fileName=filedialog.askopenfilename()
lista_ruta.append(root.fileName)
archivo = open(lista_ruta[0], 'r')
print("\t Cargando...")
print("\t Se cargo con éxito")
if op == 2:
print("\n")
archivo = open(lista_ruta[0], 'r')
for i in archivo:
try:
cadena2 = i.split("=")
numeros = cadena2[1].split(" ")
numeros2 = re.split(r' ', numeros[1])
ordenar = re.split(r',BUSCAR', numeros[1])
buscar = re.split(r'ORDENAR,', numeros[1])
if ordenar == re.split(r',BUSCAR', numeros[1]) and buscar == re.split(r'ORDENAR,', numeros[1]):
ordenar = re.split(r',BUSCAR', numeros[1])
buscar = re.split(r'ORDENAR,', numeros[1])
#buscar_numero = re.split(r', ', numeros[2])
cadena_inicial = cadena2[0].split(",")
lista_numeros = numeros[0].split(",")
lista_numeros_ordenado=numeros[0].split(",")
lista_ordenar = ordenar[0].split(",")
# lista_buscar=buscar[1].split(",")
#lista_buscar_numero = buscar_numero[0].split(",")
buscar = re.split(r' ', numeros[1])
if buscar == re.split(r' ', numeros[1]):
buscar = re.split(r' ', numeros[1])
lista_buscar2 = re.split(r'ORDENAR,', numeros[1])
"""
"""
if "ORDENAR" in ordenar:
print(cadena_inicial[0], ":", lista_numeros, " | ", "Resultado de ordenar", ":",ordenamiento_burbuja(lista_numeros_ordenado),
" ,", ordenar[0])
if "ORDENAR\n" in ordenar:
print(cadena_inicial[0], ":", lista_numeros, " | ", "Resultado de ordenar", ":",ordenamiento_burbuja(lista_numeros_ordenado),
" ,", ordenar[0])
except:
print("")
if op == 3:
print("\n")
archivo = open(lista_ruta[0], 'r')
for i in archivo:
try:
cadena2 = i.split("=")
numeros = cadena2[1].split(" ")
numeros2 = re.split(r' ', numeros[1])
ordenar = re.split(r',BUSCAR', numeros[1])
buscar = re.split(r'ORDENAR,', numeros[1])
if ordenar == re.split(r',BUSCAR', numeros[1]) and buscar == re.split(r'ORDENAR,', numeros[1]):
ordenar = re.split(r',BUSCAR', numeros[1])
buscar = re.split(r'ORDENAR,', numeros[1])
buscar_numero = re.split(r' ', numeros[2])
cadena_inicial = cadena2[0].split(",")
lista_numeros = numeros[0].split(",")
lista_ordenar = ordenar[0].split(",")
#lista_buscar=buscar[1].split(",")
lista_buscar_numero = buscar_numero[0].split(" ")
buscar = re.split(r' ', numeros[1])
if buscar == re.split(r' ', numeros[1]):
buscar = re.split(r' ', numeros[1])
lista_buscar2 = re.split(r'ORDENAR,', numeros[1])
lista_buscarnum = lista_buscar_numero[0]
intlist = [int(x) for x in lista_numeros]
if "BUSCAR" in lista_buscar2:
print(cadena_inicial[0],":", lista_numeros, " | ", " valor buscado: ", lista_buscar_numero[0], " | ","encontrado: ", str(buscar_(intlist,int(lista_buscar_numero[0]))))
except:
print("")
if op==4:
print("\n")
archivo = open(lista_ruta[0], 'r')
for i in archivo:
try:
cadena2 = i.split("=")
numeros = cadena2[1].split(" ")
numeros2 = re.split(r' ', numeros[1])
ordenar = re.split(r',BUSCAR', numeros[1])
buscar = re.split(r'ORDENAR,', numeros[1])
if ordenar == re.split(r',BUSCAR', numeros[1]) and buscar == re.split(r'ORDENAR,', numeros[1]):
ordenar = re.split(r',BUSCAR', numeros[1])
buscar = re.split(r'ORDENAR,', numeros[1])
buscar_numero = re.split(r' ', numeros[2])
cadena_inicial = cadena2[0].split(",")
lista_numeros = numeros[0].split(",")
lista_ordenar = ordenar[0].split(",")
# lista_buscar=buscar[1].split(",")
lista_buscar_numero = buscar_numero[0].split(" ")
buscar = re.split(r' ', numeros[1])
if buscar == re.split(r' ', numeros[1]):
buscar = re.split(r' ', numeros[1])
lista_buscar2 = re.split(r'ORDENAR,', numeros[1])
lista_buscarnum = lista_buscar_numero[0]
intlist = [int(x) for x in lista_numeros]
if "ORDENAR" in ordenar:
print(cadena_inicial[0], ":", lista_numeros, " | ", "Resultado de ordenar", ":", sorted(lista_numeros),
" ,", ordenar[0])
if "ORDENAR\n" in ordenar:
print(cadena_inicial[0], ":", lista_numeros, " | ", "Resultado de ordenar", ":", sorted(lista_numeros),
" ,", ordenar[0])
if "BUSCAR" in lista_buscar2:
print(cadena_inicial[0], ":",lista_numeros," | ", " valor buscado: ", lista_buscar_numero[0], " | ","encontrado: ", str(buscar_(intlist,int(lista_buscar_numero[0]))))
except:
print("")
if op==5:
print("\n")
archivo = open(lista_ruta[0], 'r')
for i in archivo:
try:
cadena2 = i.split("=")
numeros = cadena2[1].split(" ")
numeros2 = re.split(r' ', numeros[1])
ordenar = re.split(r',BUSCAR', numeros[1])
buscar = re.split(r'ORDENAR,', numeros[1])
if ordenar == re.split(r',BUSCAR', numeros[1]) and buscar == re.split(r'ORDENAR,', numeros[1]):
ordenar = re.split(r',BUSCAR', numeros[1])
buscar = re.split(r'ORDENAR,', numeros[1])
#buscar_numero = re.split(r', ', numeros[2])
cadena_inicial = cadena2[0].split(",")
lista_numeros = numeros[0].split(",")
lista_numeros_ordenado = numeros[0].split(",")
lista_ordenar = ordenar[0].split(",")
# lista_buscar=buscar[1].split(",")
#lista_buscar_numero = buscar_numero[0].split(",")
lista_numeros_busqueda=numeros[0].split(",")
buscar = re.split(r' ', numeros[1])
if buscar == re.split(r' ', numeros[1]):
buscar = re.split(r' ', numeros[1])
lista_buscar2 = re.split(r'ORDENAR,', numeros[1])
if "BUSCAR" in lista_buscar2:
lista_buscar_numero = re.split(r' ', numeros[2])
lista_buscar_numero2 = lista_buscar_numero[0].split(",")
lista_buscarnum = lista_buscar_numero[0]
except:
print("")
for j in range(len(cadena_inicial)):
ordenar_final.append(cadena_inicial[0])
if "BUSCAR" in lista_buscar2:
for numeros_buscados in range(len(lista_buscar_numero)):
lista_numeros_anidados.append(lista_buscar_numero[0])
for numero_buscar_lista in range(len(lista_buscar_numero2)):
lista_numeros_anidados_buscar.append(lista_buscar_numero2[0])
intlist4 = [int(x) for x in lista_numeros_anidados]
lista_numeros2_buscar=[int(x) for x in lista_numeros_busqueda]
numeros1.append(lista_numeros)
numeros_html_2.append(lista_numeros_ordenado)
try:
if "ORDENAR\n" in ordenar or "ORDENAR" in ordenar:
print("Generando...")
print("Creando html")
file=open("reporte0.html","w")
file.write("<!DOCTYPE HTML>"+"\n")
file.write("<html>"+"\n")
file.write("<head>"+"\n")
file.write("<link rel=stylesheet href=style.css type=text/css>")
file.write("<style>"+"\n")
file.write("table, td, th {border: 1px solid black;}table {width: 100%;border-collapse: collapse;}")
file.write("</style>"+"\n")
file.write("</head>"+"\n")
file.write("<body>"+"\n")
file.write("<h2>Práctica 1 Lenguajes Formales y de Programación</h2>"+"\n")
file.write("<table id=tabla1>"+"\n")
file.write("<thead>"+"\n")
file.write("<tr>"+"\n")
file.write("<th>Lista Original</th>"+"\n")
file.write("<th>Lista Ordenada</th>"+"\n")
file.write("</tr>"+"\n")
file.write("</thead>"+"\n")
file.write("<tbody>"+"\n")
for original in range(len(ordenar_final)):
file.write("<tr>")
file.write("<td>"+str(ordenar_final[original])+" "+str(numeros1[original])+" ORDENAR "+"</td>")
file.write("<td>"+str(ordenar_final[original])+" Ordenado "+str(ordenamiento_burbuja(numeros_html_2[original])) +"</td>")
file.write("</tr>")
file.write("</tbody>"+"\n")
file.write("</table>"+"\n")
file.write("<br/>"+"\n")
if "BUSCAR" in lista_buscar2 or "BUSCAR\n" in lista_buscar2:
#Tabla Búsquedas
file.write("<table id=tabla2>"+"\n")
file.write("<thead>"+"\n")
file.write("<tr>"+"\n")
file.write("<th>Lista a buscar</th>"+"\n")
file.write("<th>Posición</th>"+"\n")
file.write("</tr>"+"\n")
file.write("</thead>"+"\n")
file.write("<tbody>"+"\n")
for bus in range(len(lista_numeros_anidados)):
file.write("<tr>")
file.write("<td>"+str(ordenar_final[bus])+"="+str(numeros1[bus])+" "+" BUSCAR "+str(lista_numeros_anidados[bus])+"</td>")
#file.write("<td>"+str(lista_numeros_busqueda[bus])+"</td>")
file.write("<td>"+str(buscar_(numeros1[bus],str(intlist4[bus])))+"</td>")
file.write("</tr>")
file.write("</tbody>"+"\n")
file.write("</table>"+"\n")
file.write("</body>"+"\n")
file.write("</html>"+"\n")
file.close()
except:
print("")
print("Se creo el reporte html correctamente")
os.startfile("reporte0.html")
if op==6:
print("\t 201901073")
print("\t Federico David")
print("\t fede88662@gmail.com")
print("\t Lenguajes Formales y de Programación")
exit()
iniciar=inicio()
| 38.983957 | 192 | 0.446091 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,530 | 0.173418 |
e861ce569c4e7e2066044a3b9bc98fef45f652e5 | 2,237 | py | Python | examples/plot_h2o_ch4.py | ucl-exoplanets/pyexocross | 703341cd0fddafcbb04e935c89ddc9d02dda9f59 | [
"BSD-3-Clause"
] | null | null | null | examples/plot_h2o_ch4.py | ucl-exoplanets/pyexocross | 703341cd0fddafcbb04e935c89ddc9d02dda9f59 | [
"BSD-3-Clause"
] | null | null | null | examples/plot_h2o_ch4.py | ucl-exoplanets/pyexocross | 703341cd0fddafcbb04e935c89ddc9d02dda9f59 | [
"BSD-3-Clause"
] | 1 | 2021-01-15T12:54:04.000Z | 2021-01-15T12:54:04.000Z | from pyexocross.hitran.hitran import HITRANLinelist
from pyexocross.pyexocross import PyExocross
from pyexocross.exomol.exomolbroads import ExomolBroadener
import numpy as np
from pyexocross.util import create_grid_res, convert_to_wavenumber
from pyexocross.writer.hdf5writer import HDF5Writer
import matplotlib.pyplot as plt
wngrid = 10000/create_grid_res(15000,1.1,2.0)[::-1,0]
#hl_h2o = HITRANLinelist('/Users/ahmed/Documents/molecular_data/HITRAN/H2O/H2O.par')
hl_h2o= HITRANLinelist('/Users/ahmed/Documents/molecular_data/HITRAN/CH4/CH4.par')
#hl = HITRANLinelist('/Users/ahmed/Documents/molecular_data/HITRAN/CO2/12C16O2.par')
h2_h2o = ExomolBroadener(0.0209,0.027,filename='/Users/ahmed/Documents/molecular_data/HITRAN/CH4/1H2-16O__H2.broad',species='H2')
he_h2o = ExomolBroadener(0.0042,0.20,filename='/Users/ahmed/Documents/molecular_data/HITRAN/CH4/1H2-16O__He.broad',species='He')
hl_h2o.add_broadener(h2_h2o,ratio=0.704)
hl_h2o.add_broadener(he_h2o,ratio=0.121)
hl_h2o.add_self_broadener(ratio=0.1)
# h2_ch4 = ExomolBroadener(0.0603,0.5,filename='/Users/ahmed/Documents/molecular_data/HITRAN/CH4/12C-1H4__H2.broad',species='H2')
# he_ch4 = ExomolBroadener(0.0382,0.30,filename='/Users/ahmed/Documents/molecular_data/HITRAN/CH4/12C-1H4__He.broad',species='He')
# hl_ch4.add_broadener(h2_ch4,ratio=0.83)
# hl_ch4.add_broadener(he_ch4,ratio=0.17)
pyexo_h2o = PyExocross(hl_h2o)
#pyexo_ch4 = PyExocross(hl_ch4)
t = 200
p = 1.0
if __name__ == "__main__":
wn_h2o_self,xsec_h2o_self = pyexo_h2o.compute_xsec_parallel(wngrid,t,p, chunksize=1000, threshold=0.0, wing_cutoff=25.0,max_workers=2)
hl_h2o.set_broadener_ratio('self',ratio=1e-10)
wn_h2o,xsec_h2o = pyexo_h2o.compute_xsec_parallel(wngrid,t,p, chunksize=1000, threshold=0.0, wing_cutoff=25.0,max_workers=2)
#wn_ch4,xsec_ch4 = pyexo_ch4.compute_xsec(wngrid,t,p, chunksize=100, threshold=0.0, wing_cutoff=25.0)
plt.figure()
# plt.plot(wn,xsec,label='pyexo')
plt.plot(wn_h2o_self,xsec_h2o_self,label='H2O self')
plt.plot(wn_h2o,xsec_h2o,label='H2O')
#plt.plot(10000/wn_ch4,xsec_ch4,label='CH4')
plt.xlabel(r'Wavelength um')
plt.ylabel(r'Cross-section cm$^{2}$/molecule')
plt.yscale('log')
plt.legend()
plt.show()
| 45.653061 | 138 | 0.774698 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,006 | 0.449709 |
e86364a0e78b477db851ca092d4fc55c3f3c22d0 | 16,538 | py | Python | bnlp/data/conll2012.py | Nesting-Tech/zc-bnlp | 47fcf44b5cb6f4810a8bf612bb5f1bd2de94551d | [
"Apache-2.0"
] | 5 | 2019-04-03T07:35:48.000Z | 2019-04-03T07:39:12.000Z | bnlp/data/conll2012.py | Nesting-Tech/zc-bnlp | 47fcf44b5cb6f4810a8bf612bb5f1bd2de94551d | [
"Apache-2.0"
] | null | null | null | bnlp/data/conll2012.py | Nesting-Tech/zc-bnlp | 47fcf44b5cb6f4810a8bf612bb5f1bd2de94551d | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created by JoeYip on 29/03/2019
:copyright: (c) 2019 by nesting.xyz
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import operator
import re
import subprocess
import sys
import os
import tempfile
import json
import collections
import gensim
import h5py
import numpy as np
from bnlp import project_dir
from bnlp.config.bnlp_config import w2v_config_loader
from bnlp.data.const import DataSetType
from bnlp.utils import cal_tool
BEGIN_DOCUMENT_REGEX = re.compile(r"#begin document \((.*)\); part (\d+)")
COREF_RESULTS_REGEX = re.compile(
r".*Coreference: Recall: \([0-9.]+ / [0-9.]+\) ([0-9.]+)%\tPrecision: \([0-9.]+ / [0-9.]+\) ([0-9.]+)%\tF1: ([0-9.]+)%.*",
re.DOTALL)
class DocumentState(object):
def __init__(self):
self.doc_key = None
self.text = []
self.text_speakers = []
self.speakers = []
self.sentences = []
self.constituents = {}
self.const_stack = []
self.ner = {}
self.ner_stack = []
self.clusters = collections.defaultdict(list)
self.coref_stacks = collections.defaultdict(list)
def assert_empty(self):
assert self.doc_key is None
assert len(self.text) == 0
assert len(self.text_speakers) == 0
assert len(self.speakers) == 0
assert len(self.sentences) == 0
assert len(self.constituents) == 0
assert len(self.const_stack) == 0
assert len(self.ner) == 0
assert len(self.ner_stack) == 0
assert len(self.coref_stacks) == 0
assert len(self.clusters) == 0
def assert_finalizable(self):
assert self.doc_key is not None
assert len(self.text) == 0
assert len(self.text_speakers) == 0
assert len(self.speakers) > 0
assert len(self.sentences) > 0
assert len(self.constituents) > 0
assert len(self.const_stack) == 0
assert len(self.ner_stack) == 0
assert all(len(s) == 0 for s in self.coref_stacks.values())
def span_dict_to_list(self, span_dict):
return [(s, e, l) for (s, e), l in span_dict.items()]
def finalize(self):
merged_clusters = []
for c1 in self.clusters.values():
existing = None
for m in c1:
for c2 in merged_clusters:
if m in c2:
existing = c2
break
if existing is not None:
break
if existing is not None:
print("Merging clusters (shouldn't happen very often.)")
existing.update(c1)
else:
merged_clusters.append(set(c1))
merged_clusters = [list(c) for c in merged_clusters]
all_mentions = cal_tool.flatten(merged_clusters)
assert len(all_mentions) == len(set(all_mentions))
return {
"doc_key": self.doc_key,
"sentences": self.sentences,
"speakers": self.speakers,
"constituents": self.span_dict_to_list(self.constituents),
"ner": self.span_dict_to_list(self.ner),
"clusters": merged_clusters
}
def __get_doc_key(doc_id, part):
return "{}_{}".format(doc_id, int(part))
def __normalize_word(word, language):
if language == "arabic":
word = word[:word.find("#")]
if word == "/." or word == "/?":
return word[1:]
else:
return word
def __handle_bit(word_index, bit, stack, spans):
asterisk_idx = bit.find("*")
if asterisk_idx >= 0:
open_parens = bit[:asterisk_idx]
close_parens = bit[asterisk_idx + 1:]
else:
open_parens = bit[:-1]
close_parens = bit[-1]
current_idx = open_parens.find("(")
while current_idx >= 0:
next_idx = open_parens.find("(", current_idx + 1)
if next_idx >= 0:
label = open_parens[current_idx + 1:next_idx]
else:
label = open_parens[current_idx + 1:]
stack.append((word_index, label))
current_idx = next_idx
for c in close_parens:
assert c == ")"
open_index, label = stack.pop()
current_span = (open_index, word_index)
"""
if current_span in spans:
spans[current_span] += "_" + label
else:
spans[current_span] = label
"""
spans[current_span] = label
def __handle_line(line, document_state, language, labels, stats):
begin_document_match = re.match(BEGIN_DOCUMENT_REGEX, line)
if begin_document_match:
document_state.assert_empty()
document_state.doc_key = __get_doc_key(begin_document_match.group(1), begin_document_match.group(2))
return None
elif line.startswith("#end document"):
document_state.assert_finalizable()
finalized_state = document_state.finalize()
stats["num_clusters"] += len(finalized_state["clusters"])
stats["num_mentions"] += sum(len(c) for c in finalized_state["clusters"])
labels["{}_const_labels".format(language)].update(l for _, _, l in finalized_state["constituents"])
labels["ner"].update(l for _, _, l in finalized_state["ner"])
return finalized_state
else:
row = line.split()
if len(row) == 0:
stats["max_sent_len_{}".format(language)] = max(len(document_state.text),
stats["max_sent_len_{}".format(language)])
stats["num_sents_{}".format(language)] += 1
document_state.sentences.append(tuple(document_state.text))
del document_state.text[:]
document_state.speakers.append(tuple(document_state.text_speakers))
del document_state.text_speakers[:]
return None
assert len(row) >= 12
doc_key = __get_doc_key(row[0], row[1])
word = __normalize_word(row[3], language)
parse = row[5]
speaker = row[9]
ner = row[10]
coref = row[-1]
word_index = len(document_state.text) + sum(len(s) for s in document_state.sentences)
document_state.text.append(word)
document_state.text_speakers.append(speaker)
__handle_bit(word_index, parse, document_state.const_stack, document_state.constituents)
__handle_bit(word_index, ner, document_state.ner_stack, document_state.ner)
if coref != "-":
for segment in coref.split("|"):
if segment[0] == "(":
if segment[-1] == ")":
cluster_id = int(segment[1:-1])
document_state.clusters[cluster_id].append((word_index, word_index))
else:
cluster_id = int(segment[1:])
document_state.coref_stacks[cluster_id].append(word_index)
else:
cluster_id = int(segment[:-1])
start = document_state.coref_stacks[cluster_id].pop()
document_state.clusters[cluster_id].append((start, word_index))
return None
def __minimize_partition(name, language, labels, stats, extension="v4_gold_conll"):
input_path = "{}.{}.{}".format(name, language, extension)
output_path = "{}.{}.jsonlines".format(name, language)
count = 0
print("Minimizing {}".format(input_path))
with open(input_path, "r") as input_file:
with open(output_path, "w") as output_file:
document_state = DocumentState()
for line in input_file.readlines():
document = __handle_line(line, document_state, language, labels, stats)
if document is not None:
output_file.write(json.dumps(document))
output_file.write("\n")
count += 1
document_state = DocumentState()
print("Wrote {} documents to {}".format(count, output_path))
'''
将数据集拆分为dev、train、test集合
'''
def split(language, data_dir):
labels = collections.defaultdict(set)
stats = collections.defaultdict(int)
__minimize_partition(os.path.join(data_dir, DataSetType.dev.value), language, labels, stats)
__minimize_partition(os.path.join(data_dir, DataSetType.train.value), language, labels, stats)
__minimize_partition(os.path.join(data_dir, DataSetType.test.value), language, labels, stats)
def __get_char_vocab(input_filenames, output_filename, data_dir):
vocab = set()
for filename in input_filenames:
with open(os.path.join(data_dir, filename)) as f:
for line in f.readlines():
for sentence in json.loads(line)["sentences"]:
for word in sentence:
vocab.update(word)
vocab = sorted(list(vocab))
with open(os.path.join(data_dir, output_filename), "w") as f:
for char in vocab:
f.write("{}\n".format(char).encode("utf8").decode("utf8"))
print("Wrote {} characters to {}".format(len(vocab), output_filename))
'''
获取CoNLL数据集中出现的字符
'''
def get_char_vocab(language, data_dir):
__get_char_vocab(["{}.{}.jsonlines".format(partition, language) for partition in ("train", "dev", "test")],
"char_vocab.{}.txt".format(language), data_dir)
"""
过滤词向量,保留只在语料中出现的词向量
"""
def filt(language, data_dir):
words_to_keep = set() # 保存在语料中出现过的词
for partition in ("train", "dev", "test"):
json_filename = os.path.join(data_dir, "{}.{}.jsonlines".format(partition, language))
with open(json_filename) as json_file:
for line in json_file.readlines():
for sentence in json.loads(line)["sentences"]:
words_to_keep.update(sentence)
total_lines = 0
kept_lines = 0
out_filename = os.path.join(project_dir, w2v_config_loader.w2v_filter)
with open(os.path.join(project_dir, w2v_config_loader.w2v), encoding='utf-8') as in_file:
with open(out_filename, "w", encoding='utf-8') as out_file:
in_file.readline() # 跳过第一行
for line in in_file.readlines(): # 读取向量
total_lines += 1
word = line.split()[0]
if word in words_to_keep:
kept_lines += 1
out_file.write(line) # 保留只在语料中出现的词向量
print("Kept {} out of {} lines.".format(kept_lines, total_lines))
print("Wrote result to {}.".format(out_filename))
def __load_word_vec(file_path):
print("Loading word vec...")
wv = gensim.models.KeyedVectors.load_word2vec_format(file_path, binary=False, unicode_errors='ignore')
return wv
def __get_sentence_emb(word_list, wv, emb_size, max_len):
word_vec_list = list()
for word in word_list:
if word in wv:
word_vec = wv[word]
else:
word_vec = np.zeros((emb_size,))
word_vec_list.append(word_vec)
while len(word_vec_list) < max_len:
word_vec_list.append(np.zeros((emb_size,)))
return np.stack([word_vec_list, word_vec_list, word_vec_list], axis=-1)
def __do_cache(data_path, w2v, emb_size, out_file):
with open(data_path) as in_file:
for doc_num, line in enumerate(in_file.readlines()): # 遍历处理每一个文档
example = json.loads(line)
sentences = example["sentences"] # [[w1, w2...], [], ...]
max_sentence_length = max(len(s) for s in sentences)
text_len = np.array([len(s) for s in sentences])
all_sentence_lm_emb = []
for sentence in sentences:
all_features_array = __get_sentence_emb(sentence, w2v, emb_size, max_sentence_length)
all_sentence_lm_emb.append(all_features_array)
all_sentence_lm_emb = np.stack(all_sentence_lm_emb, axis=0)
if out_file:
file_key = example["doc_key"].replace("/", ":")
group = out_file.create_group(file_key)
for i, (e, l) in enumerate(zip(all_sentence_lm_emb, text_len)):
e = e[:l, :, :]
group[str(i)] = e
if doc_num % 10 == 0:
print("Cached {} documents in {}".format(doc_num + 1, data_path))
def cache_zh(data_dir):
w2v_config = w2v_config_loader.w2v_zh
w2v = __load_word_vec(os.path.join(data_dir, "..", w2v_config['path']))
with h5py.File(os.path.join(data_dir, "word2vec_zh_cache.hdf5"), "w") as out_file:
__do_cache(os.path.join(data_dir, "train.chinese.jsonlines"), w2v, w2v_config['size'], out_file)
__do_cache(os.path.join(data_dir, "dev.chinese.jsonlines"), w2v, w2v_config['size'], out_file)
print("Cache word2vec finished.")
def prepare(language, data_dir):
split(language, data_dir)
get_char_vocab(language, data_dir)
filt(language, data_dir)
def output_conll(input_file, output_file, predictions):
prediction_map = {}
for doc_key, clusters in predictions.items():
start_map = collections.defaultdict(list)
end_map = collections.defaultdict(list)
word_map = collections.defaultdict(list)
for cluster_id, mentions in enumerate(clusters):
for start, end in mentions:
if start == end:
word_map[start].append(cluster_id)
else:
start_map[start].append((cluster_id, end))
end_map[end].append((cluster_id, start))
for k, v in start_map.items():
start_map[k] = [cluster_id for cluster_id, end in sorted(v, key=operator.itemgetter(1), reverse=True)]
for k, v in end_map.items():
end_map[k] = [cluster_id for cluster_id, start in sorted(v, key=operator.itemgetter(1), reverse=True)]
prediction_map[doc_key] = (start_map, end_map, word_map)
word_index = 0
for line in input_file.readlines():
row = line.split()
if len(row) == 0:
output_file.write("\n")
elif row[0].startswith("#"):
begin_match = re.match(BEGIN_DOCUMENT_REGEX, line)
if begin_match:
doc_key = __get_doc_key(begin_match.group(1), begin_match.group(2))
start_map, end_map, word_map = prediction_map[doc_key]
word_index = 0
output_file.write(line)
output_file.write("\n")
else:
assert __get_doc_key(row[0], row[1]) == doc_key
coref_list = []
if word_index in end_map:
for cluster_id in end_map[word_index]:
coref_list.append("{})".format(cluster_id))
if word_index in word_map:
for cluster_id in word_map[word_index]:
coref_list.append("({})".format(cluster_id))
if word_index in start_map:
for cluster_id in start_map[word_index]:
coref_list.append("({}".format(cluster_id))
if len(coref_list) == 0:
row[-1] = "-"
else:
row[-1] = "|".join(coref_list)
output_file.write(" ".join(row))
output_file.write("\n")
word_index += 1
def official_conll_eval(gold_path, predicted_path, metric, official_stdout=False):
cmd = [os.path.join(project_dir, 'data', "conll-2012/scorer/v8.01/scorer.pl"), metric, gold_path, predicted_path, "none"]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
stdout, stderr = process.communicate()
process.wait()
stdout = stdout.decode("utf-8")
if stderr is not None:
print(stderr)
if official_stdout:
print("Official result for {}".format(metric))
print(stdout)
coref_results_match = re.match(COREF_RESULTS_REGEX, stdout)
recall = float(coref_results_match.group(1))
precision = float(coref_results_match.group(2))
f1 = float(coref_results_match.group(3))
return {"r": recall, "p": precision, "f": f1}
def evaluate_conll(gold_path, predictions, official_stdout=False):
with tempfile.NamedTemporaryFile(delete=False, mode="w") as prediction_file:
with open(gold_path, "r") as gold_file:
output_conll(gold_file, prediction_file, predictions)
print("Predicted conll file: {}".format(prediction_file.name))
return {m: official_conll_eval(gold_file.name, prediction_file.name, m, official_stdout) for m in
("muc", "bcub", "ceafe")}
| 36.832962 | 126 | 0.605515 | 2,464 | 0.14751 | 0 | 0 | 0 | 0 | 0 | 0 | 1,804 | 0.107998 |
e863957db27a652b3f5aa222e29cdda492c6ee48 | 646 | py | Python | docs/examples/workflow_and_job/hourly_workflow.py | Tismas/bigflow | 6a4a14616d66beeaf45700ea340c97d797a1f9e5 | [
"Apache-2.0"
] | null | null | null | docs/examples/workflow_and_job/hourly_workflow.py | Tismas/bigflow | 6a4a14616d66beeaf45700ea340c97d797a1f9e5 | [
"Apache-2.0"
] | null | null | null | docs/examples/workflow_and_job/hourly_workflow.py | Tismas/bigflow | 6a4a14616d66beeaf45700ea340c97d797a1f9e5 | [
"Apache-2.0"
] | null | null | null | from bigflow.workflow import Workflow, hourly_start_time
from datetime import datetime
from datetime import timedelta
class HourlyJob:
def __init__(self):
self.id = 'hourly_job'
def run(self, runtime):
print(f'I should process data with timestamps from: {runtime} '
f'to {datetime.strptime(runtime, "%Y-%m-%d %H:%M:%S") + timedelta(minutes=59, seconds=59)}')
hourly_workflow = Workflow(
workflow_id='hourly_workflow',
schedule_interval='@hourly',
start_time_factory=hourly_start_time,
definition=[HourlyJob()])
if __name__ == '__main__':
hourly_workflow.run('2020-01-01 00:00:00')
| 26.916667 | 106 | 0.695046 | 279 | 0.431889 | 0 | 0 | 0 | 0 | 0 | 0 | 217 | 0.335913 |
e8642331b936e08e2dbe11e2424740cd37d2e4b8 | 1,014 | py | Python | release/stubs.min/System/Windows/Forms/__init___parts/DataGridViewCellStateChangedEventArgs.py | YKato521/ironpython-stubs | b1f7c580de48528490b3ee5791b04898be95a9ae | [
"MIT"
] | null | null | null | release/stubs.min/System/Windows/Forms/__init___parts/DataGridViewCellStateChangedEventArgs.py | YKato521/ironpython-stubs | b1f7c580de48528490b3ee5791b04898be95a9ae | [
"MIT"
] | null | null | null | release/stubs.min/System/Windows/Forms/__init___parts/DataGridViewCellStateChangedEventArgs.py | YKato521/ironpython-stubs | b1f7c580de48528490b3ee5791b04898be95a9ae | [
"MIT"
] | null | null | null | class DataGridViewCellStateChangedEventArgs(EventArgs):
"""
Provides data for the System.Windows.Forms.DataGridView.CellStateChanged event.
DataGridViewCellStateChangedEventArgs(dataGridViewCell: DataGridViewCell,stateChanged: DataGridViewElementStates)
"""
@staticmethod
def __new__(self, dataGridViewCell, stateChanged):
""" __new__(cls: type,dataGridViewCell: DataGridViewCell,stateChanged: DataGridViewElementStates) """
pass
Cell = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Gets the System.Windows.Forms.DataGridViewCell that has a changed state.
Get: Cell(self: DataGridViewCellStateChangedEventArgs) -> DataGridViewCell
"""
StateChanged = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Gets the state that has changed on the cell.
Get: StateChanged(self: DataGridViewCellStateChangedEventArgs) -> DataGridViewElementStates
"""
| 26.684211 | 115 | 0.719921 | 1,012 | 0.998028 | 0 | 0 | 194 | 0.191321 | 0 | 0 | 640 | 0.631164 |
e86548e01e001f9af7049b85f9cb56452b040362 | 2,723 | py | Python | main.py | philos123/PyBacktesting | 1046e52899461003ba7e563445d7acfe1b459189 | [
"MIT"
] | 52 | 2020-12-13T23:01:03.000Z | 2022-03-09T05:54:32.000Z | main.py | philos123/PyBacktesting | 1046e52899461003ba7e563445d7acfe1b459189 | [
"MIT"
] | null | null | null | main.py | philos123/PyBacktesting | 1046e52899461003ba7e563445d7acfe1b459189 | [
"MIT"
] | 26 | 2021-03-05T12:39:39.000Z | 2022-02-21T02:32:03.000Z | #!/usr/local/bin/env python3.7
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# The MIT License (MIT)
# Copyright (c) 2020 Philippe Ostiguy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
###############################################################################
""" This is the main module which execute the program """
import indicators.regression.linear_regression as lr
import indicators.regression.mann_kendall as mk
import charting as cht
import pandas as pd
from optimize_ import Optimize
from manip_data import ManipData as md
class Main(Optimize):
def __init__(self):
super().__init__()
super().__call__()
self.cht_ = cht.Charting(self.series, self.date_name,
self.default_data, **self.indicator)
def chart_signal(self):
"""Marks signal on chart (no entry, only when the indicators trigger a signal)"""
self.cht_.chart_rsquare(list(self.indicator.keys())[0],r_square_level=self.r_square_level)
def chart_trigger(self):
"""Marks entry and exit level on chart"""
mark_up = md.pd_tolist(self.trades_track, self.entry_row)
mark_down = md.pd_tolist(self.trades_track, self.exit_row)
marks_ = {'marker_entry': {self.marker_: '^', self.color_mark: 'g', self.marker_signal: mark_up},
'marker_exit': {self.marker_: 'v', self.color_mark: 'r', self.marker_signal: mark_down}}
self.cht_.chart_marker(self.marker_signal, self.marker_, self.color_mark,**marks_)
if __name__ == '__main__':
main_ = Main()
#main_.chart_signal()
main_.chart_trigger()
t= 5 | 43.919355 | 105 | 0.673522 | 967 | 0.355123 | 0 | 0 | 0 | 0 | 0 | 0 | 1,597 | 0.586485 |
e865943b38c7fa0a91f989744dd08a3debd48239 | 400 | py | Python | ecommerce/cart/migrations/0023_auto_20210314_1656.py | MirjahonMirsaidov/ecommerce-web-app | 22d0fe5648b7acb5f819f7634abcf61b6bc12ed9 | [
"Unlicense"
] | null | null | null | ecommerce/cart/migrations/0023_auto_20210314_1656.py | MirjahonMirsaidov/ecommerce-web-app | 22d0fe5648b7acb5f819f7634abcf61b6bc12ed9 | [
"Unlicense"
] | null | null | null | ecommerce/cart/migrations/0023_auto_20210314_1656.py | MirjahonMirsaidov/ecommerce-web-app | 22d0fe5648b7acb5f819f7634abcf61b6bc12ed9 | [
"Unlicense"
] | null | null | null | # Generated by Django 3.1.2 on 2021-03-14 11:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cart', '0022_delete_sendpassword'),
]
operations = [
migrations.AlterField(
model_name='orderbeta',
name='finish_price',
field=models.PositiveIntegerField(default=0),
),
]
| 21.052632 | 57 | 0.6125 | 307 | 0.7675 | 0 | 0 | 0 | 0 | 0 | 0 | 104 | 0.26 |
e867462ed5d0f31a13de873096808bbf2b0c3e5b | 10,570 | py | Python | src/main_video.py | shortvol/sudokusolver | 15921ac0752e571c569094bf57c11ad18589d8bd | [
"MIT"
] | null | null | null | src/main_video.py | shortvol/sudokusolver | 15921ac0752e571c569094bf57c11ad18589d8bd | [
"MIT"
] | null | null | null | src/main_video.py | shortvol/sudokusolver | 15921ac0752e571c569094bf57c11ad18589d8bd | [
"MIT"
] | null | null | null | from tensorflow.keras.models import load_model
from src.extract_n_solve.extract_digits import process_extract_digits_single
from src.extract_n_solve.grid_detector_img import main_grid_detector_img
from src.extract_n_solve.grid_solver import main_solve_grid
from src.extract_n_solve.new_img_generator import *
from src.solving_objects.SudokuVideo import *
from src.useful_functions import *
from src.video_objects.WebcamVideoStream import *
def update_sudoku_lists(list_possible_grid, using_webcam=False):
for i in reversed(range(len(list_possible_grid))):
list_possible_grid[i].incr_last_apparition()
lim_time = (1 + int(using_webcam)) * (
lim_apparition_solved if list_possible_grid[i].isSolved else lim_apparition_not_solved)
if list_possible_grid[i].last_apparition > lim_time:
del list_possible_grid[i]
def look_for_already_solved_grid(im_grids_final, list_possible_grid, points_grids):
already_solved = [-1] * len(im_grids_final)
good_grids = [grid for grid in list_possible_grid if grid.isSolved]
if good_grids:
for i, points_grid in enumerate(points_grids):
for good_grid in good_grids:
if good_grid.last_apparition < lim_apparition_not_solved and good_grid.is_same_grid(points_grid):
already_solved[i] = good_grid
continue
return already_solved
thresh_apparition_conf = 1
def extract_digits_and_solve(im_grids_final, model, old_solution_list, list_possible_grid, points_grids):
# print(len(list_possible_grid))
grids_matrix = []
for im_grid_final, old_solution in zip(im_grids_final, old_solution_list):
if old_solution == -1:
grids_matrix.append(process_extract_digits_single(im_grid_final, model,
save_image_digits=False))
else:
grids_matrix.append(old_solution.grid)
if all(elem is None for elem in grids_matrix):
return None, None
grids_solved = []
for grid_matrix, old_solution, points_grid in zip(grids_matrix, old_solution_list, points_grids):
if grid_matrix is None:
grids_solved.append(None)
continue
if old_solution != -1:
grids_solved.append(old_solution.grid_solved)
else:
has_been_found = False
for sudoku in list_possible_grid:
# print("grid_matrix",grid_matrix)
# print("grids_raw",sudoku.grid_raw)
if np.array_equal(grid_matrix, sudoku.grid_raw):
has_been_found = True
sudoku.incr_nbr_apparition()
sudoku.set_limits(points_grid)
if sudoku.nbr_apparition > thresh_apparition_conf:
sudoku.isConfident = True
if not sudoku.isSolved:
sudoku.grid_solved = main_solve_grid(grid_matrix)
if sudoku.grid_solved is not None:
sudoku.isSolved = True
else:
sudoku.last_apparition = 1000 # Impossible grid .. Will be delete next time
grids_solved.append(sudoku.grid_solved)
break
if not has_been_found:
list_possible_grid.append(SudokuVideo(grid_matrix))
grids_solved.append(None)
# pass
return grids_matrix, grids_solved
def show_im_final(im_final, init_time):
add_annotation_to_image(im_final, "{:.2f} FPS".format(1 / (time.time() - init_time)), write_on_top=True)
cv2.imshow("im_final", im_final)
# def create_windows(display):
# w_window, h_window = 800, 500
# wind_names = []
# if display:
# # wind_names = ['frame_resize', 'img_lines', 'img_contour'] # ,'prepro_im'
# wind_names = ['res'] # ,'prepro_im'
# wind_names += ['im_final']
#
# for i, wind_name in enumerate(wind_names):
# cv2.namedWindow(wind_name, cv2.WINDOW_NORMAL)
# cv2.resizeWindow(wind_name, w_window, h_window)
# new_x = (i // 2) * w_window * 1.1
# new_y = (i % 2) * h_window * 1.2
# cv2.moveWindow(wind_name, int(new_x), int(new_y))
def create_windows(display):
if display:
cv2.namedWindow('res', cv2.WINDOW_NORMAL)
cv2.resizeWindow('res', 800, 800)
cv2.moveWindow('res', 900, 0)
w_window, h_window = 800, 500
cv2.namedWindow('im_final', cv2.WINDOW_NORMAL)
cv2.resizeWindow('im_final', w_window, h_window)
lim_frames_without_grid = 2
save_folder = "videos_result/"
def main_grid_detector_video(model, video_path=None, save=0, display=True):
# Initialisation
list_possible_grid, ims_filled_grid = [], None
grids_solved = None
points_grids_saved = list()
list_matrix_saved = list()
video_out_path = save_folder + 'out_process_0.mp4'
ind_save = 0
while os.path.isfile(video_out_path):
ind_save += 1
video_out_path = save_folder + 'out_process_{}.mp4'.format(ind_save)
frames_without_grid = 0
create_windows(display=display)
using_webcam = video_path is None
# Starting streaming
if using_webcam: # Use Webcam
cap = WebcamVideoStream().start()
else:
cap = cv2.VideoCapture(video_path)
output_video = None
w_vid_target, h_vid_target = get_video_save_size(cap.get(cv2.CAP_PROP_FRAME_HEIGHT),
cap.get(cv2.CAP_PROP_FRAME_WIDTH))
if save:
if not os.path.isdir(save_folder):
os.makedirs(save_folder)
output_video = cv2.VideoWriter(video_out_path, cv2.VideoWriter_fourcc(*'mp4v'), 30.0,
# (w_vid_target, h_vid_target))
(output_width, output_height))
# (1920, 1080))
while "User do not stop":
# -- Init the iteration
if cv2.waitKey(1) in keys_leave:
break
init_time = time.time()
if using_webcam:
img = cap.read()
else:
ret, img = cap.read()
if not ret:
break
img_final = my_resize(img, height=output_height)
ratio = float(img_final.shape[0]) / img.shape[0]
# Update Suodku Lists (for keeping already detected grids & deleting old ones)
update_sudoku_lists(list_possible_grid, using_webcam=using_webcam)
read_time = time.time()
logger.info("{}\nread&update_time \t{:05.2f}ms".format("-" * 20, 1000 * (read_time - init_time)))
# --- LOOKING FOR GRIDS
# Try to detect grids !
im_grids_final, points_grids, list_transform_matrix = main_grid_detector_img(img, display=display,
resized=False,
using_webcam=using_webcam)
grid_detection_time = time.time()
logger.info("grid_detect_time \t{:05.2f}ms".format(1000 * (grid_detection_time - read_time)))
if im_grids_final is None: # No grid has been found
frames_without_grid += 1
if frames_without_grid < lim_frames_without_grid and grids_solved is not None:
img_final = recreate_img_filled(img_final, ims_filled_grid,
points_grids_saved, list_matrix_saved,
ratio=ratio)
show_im_final(img_final, init_time)
if save == 1:
output_video.write(img_final)
if save == 3:
cv2.imwrite("tmp/{:03d}.jpg".format(ind_save), img)
ind_save += 1
continue
logger.debug("{} grid(s) detected".format(len(im_grids_final)))
# -- EXTRACTING GRIDS
points_grids_saved = points_grids.copy()
list_matrix_saved = list_transform_matrix.copy()
# Checking if grids has been already solved with position
old_solution_list = look_for_already_solved_grid(im_grids_final, list_possible_grid, points_grids)
# Extracting & solving
grids_matrix, grids_solved = extract_digits_and_solve(im_grids_final, model, old_solution_list,
list_possible_grid,
points_grids)
solving_time = time.time()
logger.info("solving_time \t\t{:05.2f}ms".format(1000 * (solving_time - grid_detection_time)))
if grids_solved is None:
show_im_final(img_final, init_time)
if save == 1:
output_video.write(img_final)
if save == 3:
cv2.imwrite("tmp/{:03d}.jpg".format(ind_save), img)
ind_save += 1
continue
frames_without_grid = 0
ims_filled_grid = write_solved_grids(im_grids_final, grids_matrix, grids_solved)
write_time = time.time()
logger.info("write_time \t\t{:05.2f}ms".format(1000 * (write_time - solving_time)))
img_final = recreate_img_filled(img_final, ims_filled_grid,
points_grids, list_transform_matrix, ratio=ratio)
recreation_time = time.time()
logger.info("recreation_time \t{:05.2f}ms".format(1000 * (recreation_time - write_time)))
show_im_final(img_final, init_time)
show_time = time.time()
logger.info("show_time \t\t{:05.2f}ms".format(1000 * (show_time - recreation_time)))
if save > 0:
# output_video.write(my_resize(img_final, w_vid_target))
output_video.write(img_final)
# if save == 3:
# cv2.imwrite("tmp/{:03d}.jpg".format(ind_save), frame)
# ind_save += 1
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
if save:
try:
output_video.release()
print("Saving GIF ....")
create_gif(video_out_path, save_folder)
except AttributeError:
logger.warning("Cannot release output_video")
if __name__ == '__main__':
my_model = load_model('model/my_super_model.h5')
video_p = "/media/hdd_linux/Video/sudoku1.mp4"
main_grid_detector_video(my_model, video_path=video_p,
save=1, display=True)
# main_grid_detector_video(my_model)
| 41.45098 | 113 | 0.609934 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,804 | 0.170672 |
e867d8367de7a944108e351fb3693f3fedf74024 | 178 | py | Python | adscore/__init__.py | shinyichen/ADSCore | bf0bf6487db94093144687a60390366e3ff8a136 | [
"MIT"
] | null | null | null | adscore/__init__.py | shinyichen/ADSCore | bf0bf6487db94093144687a60390366e3ff8a136 | [
"MIT"
] | 14 | 2019-08-09T15:37:40.000Z | 2022-02-17T13:22:46.000Z | adscore/__init__.py | shinyichen/ADSCore | bf0bf6487db94093144687a60390366e3ff8a136 | [
"MIT"
] | 5 | 2019-08-05T15:31:31.000Z | 2021-04-20T20:35:28.000Z | from adscore import routes
from adscore import api
from adscore import crawlers
from adscore.app import app, create_app
from adscore import tools
from adscore import flask_redis
| 25.428571 | 39 | 0.848315 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
e868df19f6af54dff01b87a764b10fb6378ce377 | 2,044 | py | Python | examples/twitter_roa/settings.py | lhaze/django-roa | 0a2de99b5ceec53c226e3c36d88cb19118c3ae72 | [
"BSD-3-Clause"
] | 31 | 2015-01-11T09:16:15.000Z | 2021-05-04T09:15:27.000Z | examples/twitter_roa/settings.py | lhaze/django-roa | 0a2de99b5ceec53c226e3c36d88cb19118c3ae72 | [
"BSD-3-Clause"
] | 8 | 2015-01-06T21:35:35.000Z | 2015-04-08T21:36:09.000Z | examples/twitter_roa/settings.py | lhaze/django-roa | 0a2de99b5ceec53c226e3c36d88cb19118c3ae72 | [
"BSD-3-Clause"
] | 18 | 2015-02-02T22:56:58.000Z | 2021-05-04T09:43:48.000Z | import os
ROOT_PATH = os.path.dirname(__file__)
TEMPLATE_DEBUG = DEBUG = True
MANAGERS = ADMINS = ()
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = os.path.join(ROOT_PATH, 'testdb.sqlite')
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
MEDIA_ROOT = ''
MEDIA_URL = ''
ADMIN_MEDIA_PREFIX = '/media/'
SECRET_KEY = '2+@4vnr#v8e273^+a)g$8%dre^dwcn#d&n#8+l6jk7r#$p&3zk'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.request",
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'urls'
TEMPLATE_DIRS = (os.path.join(ROOT_PATH, '../../templates'),)
INSTALLED_APPS = (
'django_roa',
'twitter_roa',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
)
SESSION_ENGINE = "django.contrib.sessions.backends.file"
SERIALIZATION_MODULES = {
'twitter' : 'examples.twitter_roa.serializers',
}
## ROA custom settings
ROA_MODELS = True # set to False if you'd like to develop/test locally
ROA_FORMAT = 'twitter' # json or xml
ROA_DJANGO_ERRORS = True # useful to ease debugging if you use test server
ROA_URL_OVERRIDES_DETAIL = {
'twitter_roa.tweet': lambda o: u'http://api.twitter.com/1/statuses/show/%s.json' % o.id,
'twitter_roa.user': lambda o: u'http://api.twitter.com/1/users/show.json?user_id=%s' % o.id,
}
ROA_ARGS_NAMES_MAPPING = {
'filter_id__exact': 'user_id',
}
ROA_CUSTOM_ARGS = {
'include_entities': 'false',
'skip_status': 'true',
}
## Logging settings
import logging
logging.basicConfig(level=logging.DEBUG, format="%(name)s - %(message)s")
| 30.507463 | 96 | 0.727984 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,164 | 0.569472 |
e8697173df0652e2791a64df71f2111df4f051ca | 9,314 | py | Python | allhub/all_hub.py | srinivasreddy/allhub | ff20858c9984da5c4edd5043c39eed3b6d5d693d | [
"Apache-2.0"
] | 2 | 2019-10-07T15:46:33.000Z | 2019-11-26T04:30:39.000Z | allhub/all_hub.py | srinivasreddy/allhub | ff20858c9984da5c4edd5043c39eed3b6d5d693d | [
"Apache-2.0"
] | 1 | 2020-03-09T14:44:04.000Z | 2020-03-09T14:44:04.000Z | allhub/all_hub.py | srinivasreddy/allhub | ff20858c9984da5c4edd5043c39eed3b6d5d693d | [
"Apache-2.0"
] | 2 | 2019-10-08T05:22:37.000Z | 2019-10-08T06:20:47.000Z | import os
from urllib.parse import urljoin
import requests
from allhub.activity import ActivityMixin
from allhub.orgs import OrganizationMixin
from allhub.gists import GistMixin
from allhub.oauth import OAuthMixin
from allhub.users import UsersMixin
from allhub.util import MimeType, ConflictCheck, config
from allhub.repos import RepositoryMixin
from allhub.reactions import ReactionMixin
from allhub.search import SearchMixin
from allhub.projects import ProjectsMixin
from allhub.misc import MiscellaneousMixin
from allhub.migrations import MigrationMixin
from allhub.iterator import Iterator
from allhub.interactions import InteractionLimitsMixin
from allhub.issues import IssuesMixin
from allhub.apps import AppsMixin
from allhub.git_data import GitDataMixin
from allhub.teams import TeamsMixin
from allhub.pull_requests import PullRequestsMixin
from allhub.checks import ChecksMixin
"""
The usage pattern,
```
from allhub import AllHub
all_hub = AllHub('username', 'oauth_token')
all_hub.gist_comments('gist_id')
```
For some API, like OAuth - please see oauth.py file, permits only basic authentication, in that case,
you need to set the password environment variable.
export GH_PASSWORD="mypassword"
If you are using this library as part of a third party Github app, you need to set the environment
variable GH_APP_NAME as well in order for the github to correctly log/diagnose the API requests.
export GH_APP_NAME="Grandeur"
"""
class AllHub(
GitDataMixin,
PullRequestsMixin,
TeamsMixin,
AppsMixin,
ChecksMixin,
GistMixin,
OAuthMixin,
ActivityMixin,
UsersMixin,
RepositoryMixin,
ReactionMixin,
SearchMixin,
ProjectsMixin,
OrganizationMixin,
MiscellaneousMixin,
MigrationMixin,
InteractionLimitsMixin,
IssuesMixin,
metaclass=ConflictCheck,
):
def __init__(self, username, auth_token, app_token=None, password=None):
if username is None:
raise ValueError("username cannot be None.")
if auth_token is None:
raise ValueError("auth_token cannot be None.")
self.username = username
self.auth_token = auth_token
self.app_token = app_token
self._page = 1
self._per_page = 30 # respect the default per_page given by Github API.
self.host = "https://api.github.com"
self.password = password
self.response = None
@classmethod
def build(
cls,
user_name,
auth_token,
api_version=3,
api_mime_type=MimeType.Json,
per_page=100,
password=None,
):
obj = cls(user_name, auth_token, password)
obj.per_page = per_page
obj.api_version = api_version
obj.api_mime_type = api_mime_type
return obj
def _get_headers(self):
return {
"User-Agent": os.environ.get("GH_APP_NAME", self.username),
"Authorization": "token {auth_token}".format(auth_token=self.auth_token),
"Accept": "application/vnd.github.v{version}+{mime}".format(
version=config.api_version, mime=config.api_mime_type
),
}
def get(self, url, params=None, *args, **kwargs):
raise_for_status = kwargs.pop("raise_for_status", False)
kwargs.pop(
"num_pages", None
) # throw away num_pages keyword argument which is meant for an iterator
params = params and dict(params) or {}
if "per_page" in kwargs:
params.update({"per_page": kwargs.pop("per_page", 30)})
self.per_page = params["per_page"]
if "page" in kwargs:
params.update({"page": kwargs.pop("page", 1)})
self.page = params["page"]
full_url = urljoin(self.host, url)
headers = self._get_headers()
headers.update(**kwargs)
# print(f"full url: {full_url}, headers: {headers}, params:{params}")
response = requests.get(full_url, headers=headers, params=params)
if raise_for_status:
response.raise_for_status()
# Permanent URL redirection - 301
# Temporary URL redirection - 302, 307
if response.status_code in (301, 302, 307):
return self.get(response.headers["Location"], **kwargs)
# for response codes 2xx,4xx,5xx
# just return the response
return response
def get_basic(self, url, params=None, *args, **kwargs):
raise_for_status = kwargs.pop("raise_for_status", False)
kwargs.pop(
"num_pages", None
) # throw away num_pages keyword argument which is meant for an iterator
params = params and dict(params) or {}
params.update({"per_page": self.per_page, "page": self.page})
self.page = params["page"]
self.per_page = params["per_page"]
full_url = urljoin(self.host, url)
headers = self._get_headers()
# Remove the token for Authorization
del headers["Authorization"]
password = kwargs.pop("password", None)
headers.update(**kwargs)
response = requests.get(
full_url,
headers=headers,
auth=(self.username, password or self.password or os.environ["PASSWORD"]),
params=params,
)
if raise_for_status:
response.raise_for_status()
# Permanent URL redirection - 301
# Temporary URL redirection - 302, 307
if response.status_code in (301, 302, 307):
return self.get(response.headers["Location"])
# For response codes 2xx,4xx,5xx
# Just return the response
return response
def put(self, url, params=None, *args, **kwargs):
raise_for_status = kwargs.pop("raise_for_status", False)
if params is not None:
params = dict(params)
full_url = urljoin(self.host, url)
headers = self._get_headers()
headers.update(**kwargs)
response = requests.put(full_url, headers=headers, params=params)
if raise_for_status:
response.raise_for_status()
# Permanent URL redirection - 301
# Temporary URL redirection - 302, 307
if response.status_code in (301, 302, 307):
return self.get(response.headers["Location"], **kwargs)
# for response codes 2xx,4xx,5xx
# just return the response
return response
def post(self, url, params=None, *args, **kwargs):
raise_for_status = kwargs.pop("raise_for_status", False)
if params is not None:
params = dict(params)
full_url = urljoin(self.host, url)
headers = self._get_headers()
headers.update(**kwargs)
response = requests.post(full_url, headers=headers, json=params)
if raise_for_status:
response.raise_for_status()
# Permanent URL redirection - 301
# Temporary URL redirection - 302, 307
if response.status_code in (301, 302, 307):
return self.post(response.headers["Location"], **kwargs)
# for response codes 2xx,4xx,5xx
# just return the response
return response
def patch(self, url, params=None, *args, **kwargs):
raise_for_status = kwargs.pop("raise_for_status", False)
if params is not None:
params = dict(params)
full_url = urljoin(self.host, url)
headers = self._get_headers()
headers.update(**kwargs)
response = requests.patch(full_url, headers=headers, json=params)
if raise_for_status:
response.raise_for_status()
# Permanent URL redirection - 301
# Temporary URL redirection - 302, 307
if response.status_code in (301, 302, 307):
return self.post(response.headers["Location"], **kwargs)
# for response codes 2xx,4xx,5xx
# just return the response
return response
def delete(self, url, params=None, *args, **kwargs):
raise_for_status = kwargs.pop("raise_for_status", False)
if params is not None:
params = dict(params)
full_url = urljoin(self.host, url)
headers = self._get_headers()
headers.update(**kwargs)
response = requests.delete(full_url, headers=headers, json=params)
if raise_for_status:
response.raise_for_status()
return response
@property
def per_page(self):
return self._per_page
def _check_app_token(self):
if self.app_token is None:
raise ValueError(
"You need to supply app_token to {name}(.....)."
"In order to obtain app_token see the documentation on how to generate JWT".format(
name=self.__class__.__name__
)
)
@property
def api_version(self):
return config.api_version
@property
def page(self):
return self._page
@per_page.setter
def per_page(self, value):
self._per_page = value
@page.setter
def page(self, value):
self._page = value
def iterator(self, function, *args, **kwargs):
page = kwargs.pop("page", config.page)
per_page = kwargs.pop("per_page", config.per_page)
return Iterator(self, function, per_page, page, *args, **kwargs)
| 34.753731 | 101 | 0.643118 | 7,868 | 0.84475 | 0 | 0 | 705 | 0.075693 | 0 | 0 | 2,131 | 0.228795 |
e8698ba1d6abd6a987f45f07a5c5f9894f516c4e | 1,195 | py | Python | tests/read_config.py | tyxio/txpy-azurehelper | 50b8651b84e0686030fef67a10c819ac855995b3 | [
"MIT"
] | null | null | null | tests/read_config.py | tyxio/txpy-azurehelper | 50b8651b84e0686030fef67a10c819ac855995b3 | [
"MIT"
] | null | null | null | tests/read_config.py | tyxio/txpy-azurehelper | 50b8651b84e0686030fef67a10c819ac855995b3 | [
"MIT"
] | null | null | null | import logging.config
import os
import yaml
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
def read_logging_config():
with open(os.path.join(__location__, 'logging.cfg'), 'r') as stream:
try:
logging_config = yaml.safe_load(stream)
logging.config.dictConfig(logging_config)
# do not log azure info messages
logging.getLogger(
'azure.core.pipeline.policies.http_logging_policy').setLevel(logging.WARNING)
return logging
except yaml.YAMLError as exc:
print(exc)
except Exception as ex:
print(ex)
return None
def read_azure_config():
with open(os.path.join(__location__, 'azure.cfg'), 'r') as stream:
try:
azure_config = yaml.safe_load(stream)
return \
azure_config['az_storage_connection_str'],\
azure_config['az_storage_blob_sas_url'],\
azure_config['az_storage_blob_sas_token']
except yaml.YAMLError as exc:
print(exc)
except Exception as ex:
print(ex)
return None, None, None
| 30.641026 | 93 | 0.607531 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 191 | 0.159833 |
e86af408b93b3a26d9423358c871aeb5e1c679fe | 2,523 | py | Python | engines/dotflow2/extensions/mscs_sentiment_analysis.py | NunoEdgarGFlowHub/rhizome | 6fcb77c4cc38e662cd805fc5df7845b4c97c5ea0 | [
"MIT"
] | 8 | 2018-10-30T10:11:33.000Z | 2020-12-01T05:36:19.000Z | engines/dotflow2/extensions/mscs_sentiment_analysis.py | NunoEdgarGFlowHub/rhizome | 6fcb77c4cc38e662cd805fc5df7845b4c97c5ea0 | [
"MIT"
] | 16 | 2018-10-26T00:04:11.000Z | 2021-04-30T20:59:14.000Z | engines/dotflow2/extensions/mscs_sentiment_analysis.py | SeedVault/bbot-py | b94ef5e75411ac4a214f5ac54d04ce00d9108ec0 | [
"MIT"
] | 3 | 2019-03-11T13:42:47.000Z | 2019-12-03T13:19:33.000Z |
import requests
import logging
from bbot.core import ChatbotEngine, BBotException, BBotCore, BBotExtensionException
from engines.dotflow2.chatbot_engine import DotFlow2LoggerAdapter
class DotFlow2MSCSSentimentAnalysis():
"""ChatScript DotFlow2 function"""
def __init__(self, config: dict, dotbot: dict) -> None:
"""
Initialize class
"""
self.config = config
self.dotbot = dotbot
self.bot = None
self.logger = None
self.azure_location = ''
self.azure_subscription_key = ''
self.logger_level = ''
def init(self, bot: ChatbotEngine):
"""
Initialize extension
:param bot:
:return:
"""
self.bot = bot
self.logger = DotFlow2LoggerAdapter(logging.getLogger('df2_ext.ssent_an'), self, self.bot, '$simpleSentimentAnalysis')
bot.register_dotflow2_function('simpleSentimentAnalysis', {'object': self, 'method': 'df2_simpleSentimentAnalysis', 'cost': 0.5, 'register_enabled': True})
def df2_simpleSentimentAnalysis(self, args, f_type):
"""
Detects sentiment analysis using Microsoft Cognitive Services
:param args:
:param f_type:
:return:
"""
try:
input_text = self.bot.resolve_arg(args[0], f_type)
except IndexError:
input_text = self.bot.call_dotflow2_function('input', [], 'R') # optional. default input()
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': self.azure_subscription_key,
}
payload = {
"documents": [
{
"language": "en",
"id": "1",
"text": input_text
}
]
}
self.logger.debug('Requesting sentiment analysis score to Microsoft Cognitive Services...')
r = requests.post(
f'https://{self.azure_location}.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment',
json=payload, headers=headers)
response = r.json()
self.logger.debug('Returned response: ' + str(response))
if 'error' in response:
self.logger.critical(response['error']['message'])
raise BBotExtensionException(response['error']['message'], BBotCore.FNC_RESPONSE_ERROR)
score = response['documents'][0]['score']
return score
| 32.346154 | 163 | 0.583829 | 2,337 | 0.926278 | 0 | 0 | 0 | 0 | 0 | 0 | 838 | 0.332144 |
e86b1bb58cf35277c0e77a6a3927a3bf3db53aa6 | 3,831 | py | Python | poor_trader/sample/trading_systems.py | johndpope/poor-trader-py | 097fbb10c217abe0db5a2cd55d73e0ad2990acd9 | [
"MIT"
] | 1 | 2020-03-30T19:04:39.000Z | 2020-03-30T19:04:39.000Z | poor_trader/sample/trading_systems.py | johndpope/poor-trader-py | 097fbb10c217abe0db5a2cd55d73e0ad2990acd9 | [
"MIT"
] | null | null | null | poor_trader/sample/trading_systems.py | johndpope/poor-trader-py | 097fbb10c217abe0db5a2cd55d73e0ad2990acd9 | [
"MIT"
] | null | null | null |
import os
import pandas as pd
from poor_trader import config
from poor_trader import trading
from poor_trader import systems
class CombinedIndicators(trading.TradingSystem):
def __init__(self, portfolio, systems_method_list, name='CombinedIndicators'):
super(CombinedIndicators, self).__init__(name=name)
self.portfolio = portfolio
self.market = self.portfolio.market
self.systems_method_list = systems_method_list
self.fpath = config.TRADING_SYSTEMS_PATH / '{}.pkl'.format(self.name)
self.df_indicators = pd.DataFrame()
self.init_indicators()
def init_indicators(self):
if os.path.exists(self.fpath):
self.df_indicators = pd.read_pickle(self.fpath)
else:
symbols = self.market.symbols
df_group_quotes = self.market.historical_data
df = pd.DataFrame()
for fname, df_positions in self.systems_method_list:
df_positions.columns = ['{}_{}'.format(col, fname) for col in df_positions.columns]
df = df.join(df_positions, how='outer')
self.df_indicators = df.copy()
self.df_indicators.to_pickle(self.fpath)
def get_indicators(self, trading_period, symbol, direction):
df = self.df_indicators.filter(regex='^{}_'.format(symbol))
df.columns = [col.replace('{}_'.format(symbol), '') for col in df.columns]
positions = df.loc[:trading_period].dropna().shift(1).iloc[-1]
df = pd.DataFrame()
df['Position'] = positions
direction_str = 'LONG' if direction == trading.Direction.LONG else 'SHORT'
return df[df['Position'] == direction_str]
def get_indicator_name(self, trading_period, symbol, direction):
return '_'.join(self.get_indicators(trading_period, symbol, direction).index.values)
def get_close_indicator_name(self, trading_period, symbol, open_direction):
close_direction = trading.Direction.LONG if open_direction == trading.Direction.SHORT else trading.Direction.SHORT
return self.get_indicator_name(trading_period, symbol, close_direction)
def is_long(self, trading_period, symbol):
open_position = self.portfolio.get_open_position(symbol)
if open_position.empty:
return len(self.get_indicators(trading_period, symbol, trading.Direction.LONG).index.values) > 0
return False
def is_short(self, trading_period, symbol):
open_position = self.portfolio.get_open_position(symbol)
if open_position.empty:
return len(self.get_indicators(trading_period, symbol, trading.Direction.SHORT).index.values) > 0
return False
def is_close(self, trading_period, symbol, open_trades):
short_indicators = self.get_indicator_name(trading_period, symbol, trading.Direction.SHORT)
if len(open_trades.index.values) > 1:
print(open_trades)
raise NotImplementedError
for index in open_trades.index.values:
open_indicators = open_trades.loc[index]['Indicator'].split('_')
close_indicators = short_indicators.split('_')
remaining_indicators = [_ for _ in open_indicators if _ not in close_indicators]
return len(remaining_indicators) <= 0
class Turtle(CombinedIndicators):
def __init__(self, portfolio, name='Turtle'):
symbols = portfolio.market.symbols
df_group_quotes = portfolio.df_group_quotes
super(Turtle, self).__init__(portfolio,
[systems.run_atr_channel_breakout(symbols, df_group_quotes),
systems.run_dcsma(symbols, df_group_quotes),
systems.run_slsma(symbols, df_group_quotes)],
name=name)
| 46.719512 | 122 | 0.667711 | 3,698 | 0.965283 | 0 | 0 | 0 | 0 | 0 | 0 | 116 | 0.030279 |
e86ba59b27e6dbeb36683496cd7cae2e5abddfb2 | 14,356 | py | Python | fileExplorer.py | aff3ct/PyBER | c84e1f63c193c5661ab8917a97264e4b899b7be0 | [
"MIT"
] | 10 | 2017-06-26T09:12:51.000Z | 2021-07-11T06:31:34.000Z | fileExplorer.py | aff3ct/PyBER | c84e1f63c193c5661ab8917a97264e4b899b7be0 | [
"MIT"
] | 6 | 2017-09-16T03:05:48.000Z | 2019-11-12T23:55:29.000Z | fileExplorer.py | aff3ct/PyBER | c84e1f63c193c5661ab8917a97264e4b899b7be0 | [
"MIT"
] | 5 | 2017-09-20T23:44:24.000Z | 2021-08-09T08:48:21.000Z | # The MIT License (MIT)
#
# Copyright (c) 2018 PyBER
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
import os
from data.refs.readers.aff3ct_trace_reader import aff3ctTraceReader
import subprocess
import time
import lib.pyqtgraph.pyqtgraph as pg
from lib.pyqtgraph.pyqtgraph.Qt import QtCore, QtGui, QtWidgets
from lib.pyqtgraph.pyqtgraph.dockarea import *
import numpy as np
class AdvTreeView(QtGui.QTreeView):
wBER = []
wFER = []
wBEFE = []
wThr = []
wDeta = []
fsWatcher = []
lBER = []
lFER = []
lBEFE = []
lThr = []
NoiseTypeIdx = []
Curves = []
dataBEFE = []
dataName = []
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15, 16
colors = [0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17]
lastNoise = []
paths = []
styles = [QtCore.Qt.SolidLine, QtCore.Qt.DashLine, QtCore.Qt.DotLine, QtCore.Qt.DashDotLine, QtCore.Qt.DashDotDotLine]
dashPatterns = [[1, 3, 4, 3], [2, 3, 4, 3], [1, 3, 1, 3], [4, 3, 4, 3], [3, 3, 2, 3], [4, 3, 1, 3]]
NoiseType = ["ebn0", "esn0", "mi", "rop", "ep" ]
NoiseTypeLabel = ["Eb/N0 (dB)", "Es/N0 (dB)", "Mutual Info", "Received Optical Power (dB)", "Event Probability"]
BERLegendPosition = ["BottomLeft", "BottomLeft", "BottomLeft", "BottomLeft", "BottomRight" ]
FERLegendPosition = ["BottomLeft", "BottomLeft", "BottomLeft", "BottomLeft", "BottomRight" ]
BEFELegendPosition = ["TopRight", "TopRight", "TopRight", "TopRight", "BottomRight" ]
ThrLegendPosition = ["BottomRight", "BottomRight", "BottomRight", "BottomRight", "BottomRight" ]
def __init__(self, wBER, wFER, wBEFE, wThr, wDeta):
super().__init__()
self.wBER = wBER
self.wFER = wFER
self.wBEFE = wBEFE
self.wThr = wThr
self.wDeta = wDeta
# create a legend on the plots
self.lBER = self.wBER .addLegend()
self.lFER = self.wFER .addLegend()
self.lBEFE = self.wBEFE.addLegend()
self.lThr = self.wThr .addLegend()
self.NoiseTypeIdx = 0
self.NoiseSelectedByUser = False
self.refreshing_time = time.time()
self.hideLegend()
self.doubleClicked.connect(self.openFileOrDir)
self.fsWatcher = QtCore.QFileSystemWatcher()
self.fsWatcher.fileChanged.connect(self.updateDataAndCurve)
def switchNoiseType(self):
self.NoiseTypeIdx += 1
if self.NoiseTypeIdx == len(self.NoiseType):
self.NoiseTypeIdx = 0
self.refresh()
self.setLabel()
self.NoiseSelectedByUser = True
def switchNoiseTypeRevert(self):
if self.NoiseTypeIdx == 0:
self.NoiseTypeIdx = len(self.NoiseType) -1
else:
self.NoiseTypeIdx -= 1
self.refresh()
self.setLabel()
self.NoiseSelectedByUser = True
def setLabel(self):
newLabel = self.NoiseTypeLabel[self.NoiseTypeIdx]
self.wBER .setLabel('bottom', newLabel)
self.wFER .setLabel('bottom', newLabel)
self.wBEFE.setLabel('bottom', newLabel)
self.wThr .setLabel('bottom', newLabel)
if len(self.paths):
self.showLegend()
else:
self.hideLegend()
def refresh(self):
for name in self.dataName:
self.removeLegendItem(name)
self.Curves = [[] for x in range(len(self.paths))]
self.dataBEFE = [[] for x in range(len(self.paths))]
self.dataName = [[] for x in range(len(self.paths))]
for path in self.paths:
self.updateData(path)
self.updateCurves ()
self.updateDetails()
def switchFileFilter(self):
self.model().setNameFilterDisables(not self.model().nameFilterDisables())
def openFileOrDir(self, *args):
paths = [ self.model().filePath(index) for index in args ]
if len(paths):
if sys.platform == "linux" or sys.platform == "linux2":
subprocess.call(["xdg-open", paths[0]])
elif sys.platform == "darwin":
subprocess.call(["open", paths[0]])
else:
os.startfile(paths[0])
def hideLegend(self):
# hide the legend
if self.lBER: self.lBER = self.setLegendPosition(self.lBER, "Hide")
if self.lFER: self.lFER = self.setLegendPosition(self.lFER, "Hide")
if self.lBEFE: self.lBEFE = self.setLegendPosition(self.lBEFE, "Hide")
if self.lThr: self.lThr = self.setLegendPosition(self.lThr, "Hide")
def setLegendPosition(self, legend, pos):
if pos == "BottomLeft":
legend.anchor(itemPos=(0,1), parentPos=(0,1), offset=( 10,-10))
elif pos == "BottomRight":
legend.anchor(itemPos=(1,1), parentPos=(1,1), offset=(-10,-10))
elif pos == "TopRight":
legend.anchor(itemPos=(1,0), parentPos=(1,0), offset=(-10, 10))
elif pos == "TopLeft":
legend.anchor(itemPos=(0,0), parentPos=(0,0), offset=( 10, 10))
elif pos == "Hide":
legend.anchor(itemPos=(1,0), parentPos=(1,0), offset=(100, 100))
return legend
def showLegend(self):
# display the legend
if self.lBER: self.lBER = self.setLegendPosition(self.lBER, self.BERLegendPosition [self.NoiseTypeIdx])
if self.lFER: self.lFER = self.setLegendPosition(self.lFER, self.FERLegendPosition [self.NoiseTypeIdx])
if self.lBEFE: self.lBEFE = self.setLegendPosition(self.lBEFE, self.BEFELegendPosition[self.NoiseTypeIdx])
if self.lThr: self.lThr = self.setLegendPosition(self.lThr, self.ThrLegendPosition [self.NoiseTypeIdx])
def removeLegendItem(self, name):
if self.lBER: self.lBER .removeItem(name)
if self.lFER: self.lFER .removeItem(name)
if self.lBEFE: self.lBEFE.removeItem(name)
if self.lThr: self.lThr .removeItem(name)
def getPathId(self, path):
if path in self.paths:
curId = 0
for p in self.paths:
if p == path:
return curId
else:
curId = curId +1
return -1
else:
return -1
def updateData(self, path):
pathId = self.getPathId(path)
if pathId == -1:
return
self.Curves [pathId] = aff3ctTraceReader(path)
self.dataBEFE[pathId] = [b/f for b,f in zip(self.Curves[pathId].getTrace("n_be"), self.Curves[pathId].getTrace("n_fe"))]
dataName = self.Curves[pathId].getMetadata("title")
if not dataName:
self.dataName[pathId] = "Curve " + str(pathId)
elif dataName in self.dataName:
self.dataName[pathId] = dataName + "_" + str(pathId)
else:
self.dataName[pathId] = dataName
if not self.Curves[pathId].legendKeyAvailable(self.NoiseType[self.NoiseTypeIdx]):
self.dataName[pathId] = "**" + self.dataName[pathId] + "**"
def updateCurves(self):
self.wBER .clearPlots()
self.wFER .clearPlots()
self.wBEFE.clearPlots()
self.wThr .clearPlots()
# plot the curves
for pathId in range(len(self.paths)):
icolor = self.colors[pathId % len(self.colors)]
pen = pg.mkPen(color=(icolor,8), width=2, style=QtCore.Qt.CustomDashLine)
pen.setDashPattern(self.dashPatterns[pathId % len(self.dashPatterns)])
self.removeLegendItem(self.dataName[pathId])
noiseKey = self.NoiseType[self.NoiseTypeIdx]
if self.Curves[pathId].legendKeyAvailable(noiseKey):
self.wBER. plot(x=self.Curves[pathId].getTrace(noiseKey), y=self.Curves[pathId].getTrace("be_rate"), pen=pen, symbol='x', name=self.dataName[pathId])
self.wFER. plot(x=self.Curves[pathId].getTrace(noiseKey), y=self.Curves[pathId].getTrace("fe_rate"), pen=pen, symbol='x', name=self.dataName[pathId])
self.wBEFE.plot(x=self.Curves[pathId].getTrace(noiseKey), y=self.dataBEFE[pathId], pen=pen, symbol='x', name=self.dataName[pathId])
self.wThr. plot(x=self.Curves[pathId].getTrace(noiseKey), y=self.Curves[pathId].getTrace("sim_thr"), pen=pen, symbol='x', name=self.dataName[pathId])
else:
self.wBER. plot(x=[], y=[], pen=pen, symbol='x', name=self.dataName[pathId])
self.wFER. plot(x=[], y=[], pen=pen, symbol='x', name=self.dataName[pathId])
self.wBEFE.plot(x=[], y=[], pen=pen, symbol='x', name=self.dataName[pathId])
self.wThr. plot(x=[], y=[], pen=pen, symbol='x', name=self.dataName[pathId])
def updateDataAndCurve(self, path):
if (self.refreshing_time + 0.1) < time.time(): # timer to not freeze because of several refreshes asked at the same time
self.refresh()
self.refreshing_time = time.time()
def updateDetails(self):
self.wDeta.clear()
for pathId in range(len(self.paths)):
icolor = self.colors[pathId % len(self.colors)]
path = self.paths[pathId]
# for filename in self.paths:
pen = pg.mkPen(color=(icolor,8), width=2, style=QtCore.Qt.CustomDashLine)
pen.setDashPattern(self.dashPatterns[pathId % len(self.dashPatterns)])
legendArea = DockArea()
dInfo = Dock("", size=(250,900))
legendArea.addDock(dInfo, 'bottom')
firstTitle = True;
layoutLegend = QtGui.QFormLayout()
for entry in self.Curves[pathId].SimuHeader:
if len(entry) == 3 and entry[1]:
if entry[2] == 1:
if not firstTitle:
line = QtGui.QFrame()
line.setFrameShape(QtGui.QFrame.HLine)
line.setFrameShadow(QtGui.QFrame.Sunken)
layoutLegend.addRow(line)
firstTitle = False
layoutLegend.addRow("<h3><u>" + entry[0] + "<u></h3>", QtGui.QLabel(""))
elif entry[2] == 2:
layoutLegend.addRow("<b><u>" + entry[0] + ":<u></b>", QtGui.QLabel(""))
elif entry[2] == 3:
layoutLegend.addRow("<b>" + entry[0] + "</b>: ", QtGui.QLabel(entry[1]))
# Add an horizontal line to seperate
line = QtGui.QFrame()
line.setFrameShape(QtGui.QFrame.HLine)
line.setFrameShadow(QtGui.QFrame.Plain)
layoutLegend.addRow(line)
layoutLegend.addRow("<h3><u>Metadata<u></h3>", QtGui.QLabel(""))
for entry in self.Curves[pathId].Metadata:
if entry == "doi":
url = QtGui.QLineEdit("https://doi.org/" + self.Curves[pathId].Metadata[entry])
url.setReadOnly(True)
layoutLegend.addRow("<b>" + entry + "</b>: ", url)
# if entry == "url":
# url = QtGui.QLabel(str(self.Curves[pathId].Metadata[entry]))
# url.setOpenExternalLinks(True)
# url.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByMouse | QtCore.Qt.TextSelectableByMouse)
# layoutLegend.addRow("<b>" + entry + "</b>: ", url)
# elif entry == "filename":
# url = QtGui.QLabel(str(self.Curves[pathId].Metadata[entry]))
# url.setOpenInternalLinks(True)
# url.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByMouse | QtCore.Qt.TextSelectableByMouse)
# layoutLegend.addRow("<b>" + entry + "</b>: ", url)
else:
lineEdit = QtGui.QLineEdit(self.Curves[pathId].Metadata[entry])
lineEdit.setReadOnly(True)
layoutLegend.addRow("<b>" + entry + "</b>: ", lineEdit)
wCur = QtGui.QWidget()
wCur.setLayout(layoutLegend)
sCur = QtGui.QScrollArea()
sCur.setWidget(wCur)
sCur.setWidgetResizable(True)
dInfo.addWidget(sCur)
self.wDeta.addTab(legendArea, self.dataName[pathId])
def selectionChanged(self, selected, deselected):
super().selectionChanged(selected, deselected)
newPaths = [ self.model().filePath(index) for index in self.selectedIndexes()
if not self.model().isDir(index)] # TODO: remove this restriction
pathsToRemove = []
for p in self.paths:
if p not in newPaths:
pathsToRemove.append(p)
for p in pathsToRemove:
pId = self.getPathId(p)
self.paths.pop(pId)
pathsToAdd = []
for p in newPaths:
if p not in self.paths:
pathsToAdd.append(p)
for p in pathsToAdd:
self.paths.append(p)
if len(pathsToRemove) > 0:
self.fsWatcher.removePaths(pathsToRemove)
if len(pathsToAdd) > 0:
self.fsWatcher.addPaths(pathsToAdd)
self.refresh ()
self.setLabel()
if not self.NoiseSelectedByUser:
self.autoSelectNoise()
def autoSelectNoise(self):
save = self.NoiseTypeIdx
found = False
for i in range(len(self.NoiseType)):
self.NoiseTypeIdx = i
self.refresh()
noiseKey = self.NoiseType[self.NoiseTypeIdx]
for t in self.Curves:
if t.legendKeyAvailable(noiseKey):
found = True
break;
if found:
self.setLabel()
break;
if not found:
self.NoiseTypeIdx = save
self.refresh ()
self.setLabel()
self.NoiseSelectedByUser = False
def selectFolder(self):
options = QtWidgets.QFileDialog.Options()
# options |= QtWidgets.QFileDialog.DontUseNativeDialog
# options |= QtGui.QFileDialog.ShowDirsOnly
dirPath = QtWidgets.QFileDialog.getExistingDirectory(self, "Open a folder", "", options=options)
if dirPath:
oldModel = self.model()
model = createFileSystemModel(dirPath)
self.setModel(model)
self.setRootIndex(model.index(dirPath, 0))
del oldModel
def createFileSystemModel(dirPath):
model = QtGui.QFileSystemModel()
model.setReadOnly(True)
model.setRootPath(dirPath)
model.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.AllDirs | QtCore.QDir.AllEntries | QtCore.QDir.Files)
model.setNameFilters(['*.perf', '*.dat', '*.txt', '*.data'])
model.setNameFilterDisables(False)
return model
def generatePannel(wBER, wFER, wBEFE, wThr, wDeta):
if len(sys.argv) >= 2:
os.chdir(sys.argv[1])
else:
os.chdir("./data/")
model = createFileSystemModel(QtCore.QDir.currentPath())
view = AdvTreeView(wBER, wFER, wBEFE, wThr, wDeta)
view.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
view.setModel(model)
view.hideColumn(1);
view.hideColumn(2);
view.hideColumn(3);
view.setColumnWidth(30, 1)
view.setRootIndex(model.index(QtCore.QDir.currentPath(), 0))
view.setAnimated(True)
view.setIconSize(QtCore.QSize(24,24))
view.setExpandsOnDoubleClick(False);
return view
| 33.858491 | 153 | 0.679159 | 12,010 | 0.836584 | 0 | 0 | 0 | 0 | 0 | 0 | 2,835 | 0.197478 |
e86c98c97c5408ae2e09367d971c6294affbf58a | 2,739 | py | Python | code_and_dataset/config_parser.py | pcpLiu/DeepSeqPanII | 86ce7675a1c69fd6059216d98b1e65e315ace3eb | [
"MIT"
] | 11 | 2019-10-30T12:41:56.000Z | 2021-11-17T02:45:52.000Z | code_and_dataset/config_parser.py | pcpLiu/DeepSeqPanII | 86ce7675a1c69fd6059216d98b1e65e315ace3eb | [
"MIT"
] | 2 | 2020-12-18T00:02:54.000Z | 2021-11-19T02:33:37.000Z | code_and_dataset/config_parser.py | pcpLiu/DeepSeqPanII | 86ce7675a1c69fd6059216d98b1e65e315ace3eb | [
"MIT"
] | 3 | 2020-03-09T06:25:20.000Z | 2021-08-02T11:36:46.000Z | # -*- coding: utf-8 -*-
import os
import json
import torch
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
class Config:
def __init__(self, json_file):
self.config = json.loads(open(json_file).read())
self.device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu")
self.cpu_device = torch.device("cpu")
@property
def shuffle_before_epoch_enable(self):
return self.config['Training']['shuffle_before_epoch_enable']
@property
def is_LOMO(self):
return 'test_allele' in self.config['Data']
@property
def test_allele(self):
return self.config['Data'].get('test_allele', None)
@property
def weight_decay(self):
return self.config['Training']['weight_decay']
@property
def bind_core_file(self):
return os.path.join(BASE_DIR, 'dataset', self.config['Data']['bind_core_file'])
@property
def max_len_hla_A(self):
return self.config['Data']['max_len_hla_A']
@property
def max_len_hla_B(self):
return self.config['Data']['max_len_hla_B']
@property
def max_len_pep(self):
return self.config['Data']['max_len_pep']
@property
def validation_ratio(self):
return self.config['Data']['validation_ratio']
@property
def batch_size(self):
return self.config['Training']['batch_size']
@property
def working_dir(self):
return os.path.join(BASE_DIR, self.config['Paths']['working_dir'])
@property
def data_file(self):
return os.path.join(BASE_DIR, 'dataset', self.config['Data']['data_file'])
@property
def test_file(self):
return os.path.join(BASE_DIR, 'dataset', self.config['Data']['test_file'])
@property
def model_save_path(self):
return os.path.join(self.working_dir, 'best_model.pytorch')
@property
def model_config(self):
return self.config['Model']
@property
def grad_clip(self):
return self.config['Training']['grad_clip']
@property
def start_lr(self):
return self.config['Training']['start_lr']
@property
def min_lr(self):
return self.config['Training']['min_lr']
@property
def epochs(self):
return self.config['Training']['epochs']
@property
def loss_delta(self):
return self.config['Training']['loss_delta']
@property
def seq_encode_dim(self):
return self.model_config['seq_encoding_dim']
@property
def encoding_method(self):
return self.model_config['encoding_method']
@property
def do_train(self):
return self.config['do_train']
@property
def do_test(self):
return self.config['do_test']
| 24.675676 | 87 | 0.642935 | 2,621 | 0.956919 | 0 | 0 | 2,241 | 0.818182 | 0 | 0 | 532 | 0.194231 |
e86c9f80e62f3e346afa8de91ef3822a15df1fc1 | 2,210 | py | Python | tests/test_mean_ess.py | nikopj/NonStationaryFKL | fc4f1d06b86d5f06523ea2c2b3f5c7b0ceb17098 | [
"BSD-2-Clause"
] | 35 | 2019-06-14T22:00:23.000Z | 2021-08-29T18:35:21.000Z | tests/test_mean_ess.py | nikopj/NonStationaryFKL | fc4f1d06b86d5f06523ea2c2b3f5c7b0ceb17098 | [
"BSD-2-Clause"
] | 2 | 2020-02-16T13:07:18.000Z | 2020-08-29T02:45:43.000Z | tests/test_mean_ess.py | nikopj/NonStationaryFKL | fc4f1d06b86d5f06523ea2c2b3f5c7b0ceb17098 | [
"BSD-2-Clause"
] | 7 | 2019-06-22T06:12:51.000Z | 2020-11-24T21:04:39.000Z | import unittest
import torch
import numpy as np
from spectralgp.samplers import MeanEllipticalSlice
class TestMeanEllipticalSlice(unittest.TestCase):
def test_m_ess(self, nsamples=10000):
pmean = torch.zeros(2)
pmean[0] = -2.
prior_dist = torch.distributions.MultivariateNormal(pmean, covariance_matrix=torch.eye(2))
lmean = torch.zeros(2)
lmean[0] = 2.
likelihood = torch.distributions.MultivariateNormal(lmean, covariance_matrix=torch.eye(2))
prior_inv = torch.inverse(prior_dist.covariance_matrix)
lik_inv = torch.inverse(likelihood.covariance_matrix)
true_postsigma = torch.inverse(prior_inv + lik_inv)
true_postmu = true_postsigma.matmul(prior_inv.matmul(pmean) + lik_inv.matmul(lmean))
def lfn(x):
lmean = torch.zeros(2)
lmean[0] = 2.
likelihood = torch.distributions.MultivariateNormal(lmean, covariance_matrix=torch.eye(2))
return likelihood.log_prob(x)
#lfn = lambda x: likelihood.log_prob(x)
init = torch.zeros(2)
m_ess_runner = MeanEllipticalSlice(init, prior_dist, lfn, nsamples)
samples, _ = m_ess_runner.run()
samples = samples.numpy()
samples = samples[:, int(nsamples/2):]
est_mean = np.mean(samples,1)
print(est_mean)
est_cov = np.cov(samples)
print(np.linalg.norm(est_mean - true_postmu.numpy()))
print(np.linalg.norm(est_cov - true_postsigma.numpy()))
# import matplotlib.pyplot as plt
# N = 60
# X = np.linspace(-3, 3, N)
# Y = np.linspace(-3, 4, N)
# X, Y = np.meshgrid(X, Y)
# # Pack X and Y into a single 3-dimensional array
# pos = np.empty(X.shape + (2,))
# pos[:, :, 0] = X
# pos[:, :, 1] = Y
# pos = torch.tensor(pos).float()
# posterior_dist = torch.distributions.MultivariateNormal(true_postmu, true_postsigma)
# Z = posterior_dist.log_prob(pos).numpy()
# plt.contourf(X, Y, Z)
# plt.scatter(samples[0,:], samples[1,:], color='black', alpha = 0.3)
# plt.show()
if __name__ == "__main__":
unittest.main()
| 32.985075 | 102 | 0.61629 | 2,056 | 0.930317 | 0 | 0 | 0 | 0 | 0 | 0 | 553 | 0.250226 |
e86ce796c71c5e5ab7040e934bb5c743e217f39c | 3,207 | py | Python | cfdutils/examples/onera/onera.py | acrovato/pycfdutils | bcad3b9ac3e3bb98ede549db395e0ee87716b00d | [
"Apache-2.0"
] | null | null | null | cfdutils/examples/onera/onera.py | acrovato/pycfdutils | bcad3b9ac3e3bb98ede549db395e0ee87716b00d | [
"Apache-2.0"
] | null | null | null | cfdutils/examples/onera/onera.py | acrovato/pycfdutils | bcad3b9ac3e3bb98ede549db395e0ee87716b00d | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf8 -*-
# test encoding: à-é-è-ô-ï-€
# Copyright 2020 Adrien Crovato
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Onera M6 wing
# Adrien Crovato
def inputs():
'''Inputs definition
'''
p = {}
p['File'] = 'surface_flow' # file containing the flow solution
p['Format'] = 'dat' # file format (dat = Tecplot ASCII, vtk = VTK ASCII, vtu = VTK)
p['Cuts'] = [0.01, 0.24, 0.53, 0.78, 0.96, 1.08, 1.14, 1.18] # y-coordinates of the slices
p['Tag'] = [None, None] # tag number and name if the solution is provided not only on the wing surface
p['Variable'] = 'Pressure_Coefficient' # name of variable to extract
p['AoA'] = 3.06 # angle of attack (degrees)
return p
def cLoads(p):
'''Extract several slices along the wing span and compute the sectional aerodynamic load coefficients
'''
import cfdutils.tools.vtku as vu
import cfdutils.tools.loads as lu
# Define reader
reader = vu.Reader()
reader.open(p['File'], p['Format'])
# Create slices
cutter = vu.Cutter(reader.grid)
loads = lu.Loads()
for i in range(0, len(p['Cuts'])):
cutter.cut([0., p['Cuts'][i], 0.], [0., 1., 0.], p['Tag'][0], p['Tag'][1])
pts, elems, vals = cutter.extract(2, [p['Variable']])
loads.add(p['Cuts'][i], pts, vals[p['Variable']])
# Compute loads
loads.compute(p['AoA'])
loads.display()
loads.plot()
loads.write()
def mkchdirexec(dirname, p):
'''Create a directory if it does not exist, change to it and execute
'''
import os
dir = os.path.join(os.getcwd(), dirname)
if not os.path.isdir(dir):
os.makedirs(dir)
os.chdir(dir)
p['File'] = os.path.join(os.path.split(__file__)[0], p['File']) # to get relative path to this file
cLoads(p)
os.chdir('..')
def main():
# Get inputs
p = inputs()
# Compute loads for several file formats...
# Tecplot ASCII, computed using SU2 (https://github.com/su2code/SU2/releases/tag/v7.0.6)
print('--- SU2 - surface -Tecplot ASCII ---')
p['Format'] = 'dat'
mkchdirexec('Tecplot_ASCII', p)
# VTK ASCII, computed using SU2
print('--- SU2 - surface - VTK ASCII ---')
p['Format'] = 'vtk'
mkchdirexec('VTK_ASCII', p)
# VTK binary, computed using SU2
print('--- SU2 - surface - VTK binary ---')
p['Format'] = 'vtu'
mkchdirexec('VTK_bin', p)
# VTK binary, computed using Flow v1.9.2 (https://gitlab.uliege.be/am-dept/waves/-/releases)
print('--- Flow - field - VTK binary ---')
p['File'] = 'flow'
p['Tag'] = [5, 'tag']
p['Variable'] = 'Cp'
mkchdirexec('VTK_bin2', p)
if __name__ == "__main__":
main() | 35.241758 | 106 | 0.623636 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,968 | 0.612321 |
e86e6c8cb0c671cea30bff7e2b04bc2e6c6e9109 | 1,449 | py | Python | tasklist/models.py | 10000volts/JLGLTaskList | 12f0f95d70467211710cd302592436e79929b775 | [
"MIT"
] | null | null | null | tasklist/models.py | 10000volts/JLGLTaskList | 12f0f95d70467211710cd302592436e79929b775 | [
"MIT"
] | 4 | 2021-04-08T21:39:46.000Z | 2021-06-10T20:02:01.000Z | tasklist/models.py | 10000volts/JLGLTaskList | 12f0f95d70467211710cd302592436e79929b775 | [
"MIT"
] | null | null | null | from django.db import models
from django.db.models import Q, Prefetch
from django.db import transaction
from utils.constants import TASK_STATUS, TASK_STATUS_CHOICES
class TaskList(models.Model):
name = models.CharField(verbose_name=u'任务清单名称', max_length=128, unique=True)
def __str__(self):
return self.name
class TaskManager(models.Manager):
def create_task(self, validated_data):
"""
:param validated_data: {"name": "string"}
:return:
"""
with transaction.atomic():
tl = validated_data.pop('tl')
self.check_valid(validated_data)
validated_data['status'] = TASK_STATUS.WAITING
validated_data['tl'] = tl
item = self.create(**validated_data)
return item
def check_valid(self, data):
q = self.filter(**data).exists()
if q:
raise Exception("已存在同名任务~")
class Task(models.Model):
objects = TaskManager()
name = models.CharField(verbose_name=u'任务名称', max_length=128)
status = models.PositiveSmallIntegerField(u'任务状态', default=TASK_STATUS.WAITING,
choices=TASK_STATUS_CHOICES)
tl = models.ForeignKey('tasklist.TaskList', on_delete=models.CASCADE,
related_name='task', verbose_name='任务所属清单')
def __str__(self):
return "{}:{} status:{}".format(self.tl.name, self.name, self.status) | 32.931818 | 83 | 0.628709 | 1,329 | 0.884232 | 0 | 0 | 0 | 0 | 0 | 0 | 235 | 0.156354 |
e86f19d1113cb432eba3c0d5cc2165ccc14b2af8 | 9,486 | py | Python | panel/widgets/input.py | NoamGit/panel | 4321845b327fb2f6165170939f4f633bbe234782 | [
"BSD-3-Clause"
] | 1 | 2019-10-15T13:21:20.000Z | 2019-10-15T13:21:20.000Z | panel/widgets/input.py | jonmmease/panel | c588d0dff9418bc781b0a7dc943a5ebd3ca0c4eb | [
"BSD-3-Clause"
] | null | null | null | panel/widgets/input.py | jonmmease/panel | c588d0dff9418bc781b0a7dc943a5ebd3ca0c4eb | [
"BSD-3-Clause"
] | 1 | 2019-06-04T04:17:53.000Z | 2019-06-04T04:17:53.000Z | """
The input widgets generally allow entering arbitrary information into
a text field or similar.
"""
from __future__ import absolute_import, division, unicode_literals
import ast
from base64 import b64decode, b64encode
from datetime import datetime
from six import string_types
import param
from bokeh.models.widgets import (
CheckboxGroup as _BkCheckboxGroup, ColorPicker as _BkColorPicker,
DatePicker as _BkDatePicker, Div as _BkDiv, TextInput as _BkTextInput,
Spinner as _BkSpinner)
from ..models import FileInput as _BkFileInput
from ..util import as_unicode
from .base import Widget
class TextInput(Widget):
value = param.String(default='', allow_None=True)
placeholder = param.String(default='')
_widget_type = _BkTextInput
class FileInput(Widget):
mime_type = param.String(default=None)
value = param.Parameter(default=None)
_widget_type = _BkFileInput
_rename = {'name': None, 'mime_type': None}
def _process_param_change(self, msg):
msg = super(FileInput, self)._process_param_change(msg)
if 'value' in msg:
if self.mime_type:
template = 'data:{mime};base64,{data}'
data = b64encode(msg['value'])
msg['value'] = template.format(data=data.decode('utf-8'),
mime=self.mime_type)
else:
msg['value'] = ''
return msg
def _process_property_change(self, msg):
msg = super(FileInput, self)._process_property_change(msg)
if 'value' in msg:
header, content = msg['value'].split(",", 1)
msg['mime_type'] = header.split(':')[1].split(';')[0]
msg['value'] = b64decode(content)
return msg
def save(self, filename):
"""
Saves the uploaded FileInput data to a file or BytesIO object.
Arguments
---------
filename (str): File path or file-like object
"""
if isinstance(filename, string_types):
with open(filename, 'wb') as f:
f.write(self.value)
else:
filename.write(self.value)
class StaticText(Widget):
style = param.Dict(default=None, doc="""
Dictionary of CSS property:value pairs to apply to this Div.""")
value = param.Parameter(default=None)
_widget_type = _BkDiv
_format = '<b>{title}</b>: {value}'
_rename = {'name': 'title', 'value': 'text'}
def _process_param_change(self, msg):
msg = super(StaticText, self)._process_property_change(msg)
msg.pop('title', None)
if 'value' in msg:
text = as_unicode(msg.pop('value'))
if self.name:
text = self._format.format(title=self.name, value=text)
msg['text'] = text
return msg
class DatePicker(Widget):
value = param.Date(default=None)
start = param.Date(default=None)
end = param.Date(default=None)
_widget_type = _BkDatePicker
_rename = {'start': 'min_date', 'end': 'max_date', 'name': 'title'}
def _process_property_change(self, msg):
msg = super(DatePicker, self)._process_property_change(msg)
if 'value' in msg:
msg['value'] = datetime.strptime(msg['value'][4:], '%b %d %Y')
return msg
class ColorPicker(Widget):
value = param.Color(default=None, doc="""
The selected color""")
_widget_type = _BkColorPicker
_rename = {'value': 'color', 'name': 'title'}
class Spinner(Widget):
start = param.Number(default=None, doc="""
Optional minimum allowable value""")
end = param.Number(default=None, doc="""
Optional maximum allowable value""")
value = param.Number(default=0, doc="""
The initial value of the spinner""")
step = param.Number(default=1, doc="""
The step added or subtracted to the current value""")
_widget_type = _BkSpinner
_rename = {'name': 'title', 'start': 'low', 'end': 'high'}
class LiteralInput(Widget):
"""
LiteralInput allows declaring Python literals using a text
input widget. Optionally a type may be declared.
"""
type = param.ClassSelector(default=None, class_=(type, tuple),
is_instance=True)
value = param.Parameter(default=None)
_widget_type = _BkTextInput
def __init__(self, **params):
super(LiteralInput, self).__init__(**params)
self._state = ''
self._validate(None)
self.param.watch(self._validate, 'value')
def _validate(self, event):
if self.type is None: return
new = self.value
if not isinstance(new, self.type):
if event:
self.value = event.old
types = repr(self.type) if isinstance(self.type, tuple) else self.type.__name__
raise ValueError('LiteralInput expected %s type but value %s '
'is of type %s.' %
(types, new, type(new).__name__))
def _process_property_change(self, msg):
msg = super(LiteralInput, self)._process_property_change(msg)
new_state = ''
if 'value' in msg:
value = msg.pop('value')
try:
value = ast.literal_eval(value)
except:
new_state = ' (invalid)'
value = self.value
else:
if self.type and not isinstance(value, self.type):
new_state = ' (wrong type)'
value = self.value
msg['value'] = value
msg['name'] = msg.get('title', self.name).replace(self._state, '') + new_state
self._state = new_state
self.param.trigger('name')
return msg
def _process_param_change(self, msg):
msg = super(LiteralInput, self)._process_param_change(msg)
msg.pop('type', None)
if 'value' in msg:
msg['value'] = '' if msg['value'] is None else as_unicode(msg['value'])
msg['title'] = self.name
return msg
class DatetimeInput(LiteralInput):
"""
DatetimeInput allows declaring Python literals using a text
input widget. Optionally a type may be declared.
"""
format = param.String(default='%Y-%m-%d %H:%M:%S', doc="""
Datetime format used for parsing and formatting the datetime.""")
value = param.Date(default=None)
start = param.Date(default=None)
end = param.Date(default=None)
type = datetime
def __init__(self, **params):
super(DatetimeInput, self).__init__(**params)
self.param.watch(self._validate, 'value')
self._validate(None)
def _validate(self, event):
new = self.value
if new is not None and ((self.start is not None and self.start > new) or
(self.end is not None and self.end < new)):
value = datetime.strftime(new, self.format)
start = datetime.strftime(self.start, self.format)
end = datetime.strftime(self.end, self.format)
if event:
self.value = event.old
raise ValueError('DatetimeInput value must be between {start} and {end}, '
'supplied value is {value}'.format(start=start, end=end,
value=value))
def _process_property_change(self, msg):
msg = Widget._process_property_change(self, msg)
new_state = ''
if 'value' in msg:
value = msg.pop('value')
try:
value = datetime.strptime(value, self.format)
except:
new_state = ' (invalid)'
value = self.value
else:
if value is not None and ((self.start is not None and self.start > value) or
(self.end is not None and self.end < value)):
new_state = ' (out of bounds)'
value = self.value
msg['value'] = value
msg['name'] = msg.get('title', self.name).replace(self._state, '') + new_state
self._state = new_state
return msg
def _process_param_change(self, msg):
msg = {k: v for k, v in msg.items() if k not in ('type', 'format', 'start', 'end')}
if 'value' in msg:
value = msg['value']
if value is None:
value = ''
else:
value = datetime.strftime(msg['value'], self.format)
msg['value'] = value
msg['title'] = self.name
return msg
class Checkbox(Widget):
value = param.Boolean(default=False)
_supports_embed = True
_widget_type = _BkCheckboxGroup
def _process_property_change(self, msg):
msg = super(Checkbox, self)._process_property_change(msg)
if 'active' in msg:
msg['value'] = 0 in msg.pop('active')
return msg
def _process_param_change(self, msg):
msg = super(Checkbox, self)._process_param_change(msg)
if 'value' in msg:
msg['active'] = [0] if msg.pop('value', None) else []
if 'title' in msg:
msg['labels'] = [msg.pop('title')]
return msg
def _get_embed_state(self, root, max_opts=3):
return (self, self._models[root.ref['id']][0], [False, True],
lambda x: 0 in x.active, 'active', 'cb_obj.active.indexOf(0) >= 0')
| 31.306931 | 92 | 0.577377 | 8,852 | 0.933165 | 0 | 0 | 0 | 0 | 0 | 0 | 1,805 | 0.19028 |
e86f83e01cdd8465f49434af0b31c9f7519a119a | 2,395 | py | Python | hass_apps/heaty/window_sensor.py | taste66/hass-apps | 93f03a823f0ed8b3b32be5da30c5aaf0fcb1d92a | [
"Apache-2.0"
] | null | null | null | hass_apps/heaty/window_sensor.py | taste66/hass-apps | 93f03a823f0ed8b3b32be5da30c5aaf0fcb1d92a | [
"Apache-2.0"
] | null | null | null | hass_apps/heaty/window_sensor.py | taste66/hass-apps | 93f03a823f0ed8b3b32be5da30c5aaf0fcb1d92a | [
"Apache-2.0"
] | null | null | null | """
This module implements the WindowSensor class.
"""
import typing as T
if T.TYPE_CHECKING:
# pylint: disable=cyclic-import,unused-import
from .room import Room
import observable
from .. import common
class WindowSensor:
"""A sensor for Heaty's open window detection."""
def __init__(self, entity_id: str, cfg: dict, room: "Room") -> None:
super().__init__()
self.entity_id = entity_id
self.cfg = cfg
self.room = room
self.app = room.app
self.events = observable.Observable() # type: observable.Observable
def __repr__(self) -> str:
return "<WindowSensor {}, {}>".format(
str(self), "open" if self.is_open else "closed"
)
def __str__(self) -> str:
return "W:{}".format(self.cfg.get("friendly_name", self.entity_id))
def _state_cb(
self, entity: str, attr: str,
old: T.Optional[dict], new: T.Optional[dict],
kwargs: dict
) -> None:
"""Is called when the window sensor's state has changed.
This method triggers the opened/closed event."""
self.log("State is now {}.".format(new),
level="DEBUG", prefix=common.LOG_PREFIX_INCOMING)
self.events.trigger("open_close", self, self.is_open)
def initialize(self) -> None:
"""Should be called in order to register state listeners and
timers."""
self.log("Initializing window sensor (entity_id={})."
.format(repr(self.entity_id)),
level="DEBUG")
self.log("Listening for state changes (delay={})."
.format(self.cfg["delay"]),
level="DEBUG")
self.app.listen_state(self._state_cb, self.entity_id,
duration=self.cfg["delay"])
@property
def is_open(self) -> bool:
"""Tells whether the sensor reports open or not."""
open_state = self.cfg["open_state"]
states = []
if isinstance(open_state, list):
states.extend(open_state)
else:
states.append(open_state)
return self.app.get_state(self.entity_id) in states
def log(self, msg: str, *args: T.Any, **kwargs: T.Any) -> None:
"""Prefixes the window sensor to log messages."""
msg = "[{}] {}".format(self, msg)
self.room.log(msg, *args, **kwargs)
| 31.103896 | 76 | 0.582463 | 2,178 | 0.909395 | 0 | 0 | 356 | 0.148643 | 0 | 0 | 704 | 0.293946 |
e8701257b4e01a4d26007b2cee43126dca46dedf | 837 | py | Python | common/web_client.py | newsettle/ns4_chatbot | 526b97aa31292c28d10518bbfaa7466b8ba109ee | [
"Apache-2.0"
] | 51 | 2019-03-29T11:47:55.000Z | 2021-04-16T02:40:35.000Z | common/web_client.py | piginzoo/ns4_chatbot | 526b97aa31292c28d10518bbfaa7466b8ba109ee | [
"Apache-2.0"
] | 7 | 2019-04-16T01:46:01.000Z | 2022-03-11T23:44:09.000Z | common/web_client.py | newsettle/ns4_chatbot | 526b97aa31292c28d10518bbfaa7466b8ba109ee | [
"Apache-2.0"
] | 20 | 2019-04-02T03:37:38.000Z | 2021-12-31T09:25:12.000Z | # -*- coding=utf-8 -*-
import urllib2
import json
import logger
import traceback
def send(apiUrl,data,method=None):
logger.debug("调用内部系统[%s],data[%r]",apiUrl,data)
try:
data_json = json.dumps(data)
headers = {'Content-Type': 'application/json'} # 设置数据为json格式,很重要
request = urllib2.Request(url=apiUrl, headers=headers, data=data_json)
if method is not None:
request.get_method = method
response = urllib2.urlopen(request)
result = {'code':response.getcode(),'content':response.read()}
logger.debug("调用[%s]返回结果:%r",apiUrl,result)
return result
except Exception as e:
#traceback.print_stack()
logger.exception(e,"调用内部系统[%s],data[%r],发生错误[%r]", apiUrl, data,e)
return None
if __name__ == "__main__":
logger.init_4_debug()
| 31 | 78 | 0.636798 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 252 | 0.27907 |
e8709f79e317a9c7cd2146a4a0c28214ab5b7958 | 22 | py | Python | tccli/services/wss/v20180426/__init__.py | zyh911/tencentcloud-cli | dfc5dbd660d4c60d265921c4edc630091478fc41 | [
"Apache-2.0"
] | null | null | null | tccli/services/wss/v20180426/__init__.py | zyh911/tencentcloud-cli | dfc5dbd660d4c60d265921c4edc630091478fc41 | [
"Apache-2.0"
] | null | null | null | tccli/services/wss/v20180426/__init__.py | zyh911/tencentcloud-cli | dfc5dbd660d4c60d265921c4edc630091478fc41 | [
"Apache-2.0"
] | null | null | null | version = "2018-04-26" | 22 | 22 | 0.681818 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | 0.545455 |
e872cf24716cc1672cb4cbbb521b80d4ebf01692 | 801 | py | Python | notebooks/solutions/02-ex2-solution.py | ankitaguhaoakland/ml-workshop-intro | c075e9f04b044edd37f279d204af2810187a98bd | [
"MIT"
] | 1 | 2021-03-31T14:06:26.000Z | 2021-03-31T14:06:26.000Z | notebooks/solutions/02-ex2-solution.py | ankitaguhaoakland/ml-workshop-intro | c075e9f04b044edd37f279d204af2810187a98bd | [
"MIT"
] | null | null | null | notebooks/solutions/02-ex2-solution.py | ankitaguhaoakland/ml-workshop-intro | c075e9f04b044edd37f279d204af2810187a98bd | [
"MIT"
] | null | null | null | from sklearn.datasets import load_wine
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
wine = load_wine(as_frame=True)
X, y = wine.data, wine.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, random_state=0, stratify=y
)
knn = KNeighborsClassifier()
rfc = RandomForestClassifier()
lr = LogisticRegression()
knn.fit(X_train, y_train)
rfc.fit(X_train, y_train)
lr.fit(X_train, y_train)
print("kn train: ", knn.score(X_train, y_train))
print("rf train: ", rfc.score(X_train, y_train))
print("lr train: ", lr.score(X_train, y_train))
print("kn test: ", knn.score(X_test, y_test))
print("rf test: ", rfc.score(X_test, y_test))
print("lr test: ", lr.score(X_test, y_test))
| 27.62069 | 52 | 0.755306 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 69 | 0.086142 |
e873290b82b21476d01ffb34ba0ea8df2ff20e15 | 7,055 | py | Python | API/main/migrations/0001_initial.py | Ju99ernaut/grapeflowAPI | 0d6599775e5b666ad735160b65262624fea0bf99 | [
"MIT"
] | null | null | null | API/main/migrations/0001_initial.py | Ju99ernaut/grapeflowAPI | 0d6599775e5b666ad735160b65262624fea0bf99 | [
"MIT"
] | null | null | null | API/main/migrations/0001_initial.py | Ju99ernaut/grapeflowAPI | 0d6599775e5b666ad735160b65262624fea0bf99 | [
"MIT"
] | null | null | null | # Generated by Django 3.0.3 on 2020-02-25 18:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='UserData',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('notifyInvoice', models.BooleanField(default=True)),
('notifyNews', models.BooleanField(default=True)),
('notifyFeature', models.BooleanField(default=True)),
('avatar', models.URLField(blank=True, default='', max_length=100)),
('city', models.CharField(blank=True, default='', max_length=100)),
('country', models.CharField(blank=True, default='', max_length=100)),
('created', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(default='1', on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name_plural': 'UserData',
},
),
migrations.CreateModel(
name='Project',
fields=[
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(blank=True, default='', max_length=100)),
('preview', models.URLField(blank=True, default='', max_length=100)),
('classes', models.CharField(blank=True, default='fa fa-picture-o gjs-block gjs-one-bg gjs-four-color-h', max_length=100)),
('domain', models.URLField(blank=True, default='', max_length=100)),
('published', models.BooleanField(default=False)),
('lastPublished', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(default='1', on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Page',
fields=[
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(blank=True, default='', max_length=100)),
('thumbnail', models.URLField(blank=True, default='', max_length=100)),
('favicon', models.URLField(blank=True, default='', max_length=100)),
('webclip', models.URLField(blank=True, default='', max_length=100)),
('html', models.TextField()),
('css', models.TextField()),
('js', models.TextField()),
('components', models.TextField()),
('style', models.TextField()),
('metaTitle', models.CharField(blank=True, default='', max_length=100)),
('metaDesc', models.CharField(blank=True, default='', max_length=100)),
('created', models.DateTimeField(auto_now_add=True)),
('lastSaved', models.DateTimeField(auto_now_add=True)),
('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='main.Project')),
],
options={
'ordering': ['created'],
},
),
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('plan', models.CharField(choices=[('HO', 'Hobbyist'), ('DV', 'Developer'), ('ET', 'Enterprise')], default='HO', max_length=2)),
('amt', models.FloatField()),
('active', models.BooleanField(default=False)),
('created', models.DateTimeField(auto_now_add=True)),
('expires', models.DateTimeField()),
('invoiceUrl', models.URLField(blank=True, default='', max_length=100)),
('user', models.ForeignKey(default='1', on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['created'],
},
),
migrations.CreateModel(
name='Logic',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(blank=True, default='', max_length=100)),
('category', models.CharField(blank=True, default='Extra', max_length=100)),
('description', models.TextField()),
('js', models.TextField()),
('created', models.DateTimeField(auto_now_add=True)),
('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='main.Project')),
],
options={
'ordering': ['created'],
},
),
migrations.CreateModel(
name='Block',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(blank=True, default='', max_length=100)),
('category', models.CharField(blank=True, default='Extra', max_length=100)),
('description', models.TextField()),
('html', models.TextField()),
('css', models.TextField()),
('preview', models.URLField(blank=True, default='', max_length=100)),
('classes', models.CharField(blank=True, default='gjs-fonts gjs-f-b1 gjs-block gjs-one-bg gjs-four-color-h', max_length=100)),
('created', models.DateTimeField(auto_now_add=True)),
('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='main.Project')),
],
options={
'ordering': ['created'],
},
),
migrations.CreateModel(
name='Asset',
fields=[
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('filename', models.CharField(blank=True, default='', max_length=100)),
('type', models.CharField(choices=[('IMG', 'Image'), ('SVG', 'SVG'), ('VID', 'Video')], default='IMG', max_length=3)),
('url', models.URLField(blank=True, default='', max_length=100)),
('size', models.IntegerField()),
('added', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(default='1', on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['added'],
},
),
]
| 51.875 | 144 | 0.55691 | 6,884 | 0.975762 | 0 | 0 | 0 | 0 | 0 | 0 | 1,064 | 0.150815 |
e87510c261dc5d69e5ab1b901254bf224cc53156 | 3,295 | py | Python | pyaws/utils/time.py | mwozniczak/pyaws | af8f6d64ff47fd2ef2eb9fef25680e4656523fa3 | [
"MIT"
] | null | null | null | pyaws/utils/time.py | mwozniczak/pyaws | af8f6d64ff47fd2ef2eb9fef25680e4656523fa3 | [
"MIT"
] | null | null | null | pyaws/utils/time.py | mwozniczak/pyaws | af8f6d64ff47fd2ef2eb9fef25680e4656523fa3 | [
"MIT"
] | null | null | null | """
Summary:
- Command-line Interface (CLI) Utilities Module
- Python3
Module Functions:
- convert_strtime_datetime:
Convert human-readable datetime string into a datetime object for
conducting time operations.
- convert_timedelta:
Convert a datetime duration object into human-readable components
(weeks, days, hours, etc).
- convert_dt_time:
Convert datetime objects to human-readable string output with Formatting
"""
import datetime
import inspect
import logging
from pyaws import __version__
logger = logging.getLogger(__version__)
logger.setLevel(logging.INFO)
def convert_strtime_datetime(dt_str):
""" Converts datetime isoformat string to datetime (dt) object
Args:
:dt_str (str): input string in '2017-12-30T18:48:00.353Z' form
or similar
Returns:
TYPE: datetime object
"""
dt, _, us = dt_str.partition(".")
dt = datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
us = int(us.rstrip("Z"), 10)
return dt + datetime.timedelta(microseconds=us)
def convert_timedelta(duration):
"""
Summary:
Convert duration into component time units
Args:
:duration (datetime.timedelta): time duration to convert
Returns:
days, hours, minutes, seconds | TYPE: tuple (integers)
"""
try:
days, seconds = duration.days, duration.seconds
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = (seconds % 60)
except Exception:
logger.exception(
f'{inspect.stack()[0][3]}: Input must be datetime.timedelta object'
)
return 0, 0, 0, 0
return days, hours, minutes, seconds
def convert_dt_time(duration, return_iter=False):
"""
Summary:
convert timedelta objects to human readable output
Args:
:duration (datetime.timedelta): time duration to convert
:return_iter (tuple): tuple containing time sequence
Returns:
days, hours, minutes, seconds | TYPE: tuple (integers), OR
human readable, notated units | TYPE: string
"""
try:
days, hours, minutes, seconds = convert_timedelta(duration)
if return_iter:
return days, hours, minutes, seconds
# string format conversions
if days > 0:
format_string = (
'{} day{}, {} hour{}'.format(
days, 's' if days != 1 else '', hours, 's' if hours != 1 else ''))
elif hours > 1:
format_string = (
'{} hour{}, {} minute{}'.format(
hours, 's' if hours != 1 else '', minutes, 's' if minutes != 1 else ''))
else:
format_string = (
'{} minute{}, {} sec{}'.format(
minutes, 's' if minutes != 1 else '', seconds, 's' if seconds != 1 else ''))
except AttributeError as e:
logger.exception(
'%s: Type mismatch when converting timedelta objects (Code: %s)' %
(inspect.stack()[0][3], str(e)))
raise e
except Exception as e:
logger.exception(
'%s: Unknown error when converting datetime objects (Code: %s)' %
(inspect.stack()[0][3], str(e)))
raise e
return format_string
| 32.623762 | 93 | 0.594841 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,620 | 0.491654 |
e8757496e36b307af85c05cdd4dd6a56e81063f4 | 145 | py | Python | name_translator.py | MathisBurger/timetable-updater | aa6c3180f4ae858cb2c63ccad7855f5f670c4114 | [
"MIT"
] | null | null | null | name_translator.py | MathisBurger/timetable-updater | aa6c3180f4ae858cb2c63ccad7855f5f670c4114 | [
"MIT"
] | null | null | null | name_translator.py | MathisBurger/timetable-updater | aa6c3180f4ae858cb2c63ccad7855f5f670c4114 | [
"MIT"
] | null | null | null | import json
def translate_name(name):
with open("name_translator.json", "r") as file:
data = json.load(file)
return data[name]
| 18.125 | 51 | 0.655172 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 0.172414 |
e876bb50d8ee0021ee27d7402634cce9a0b1b389 | 756 | py | Python | lista1/156_Ananagrams/156_Ananagrams.py | L30Bola/mab606 | c29a781752b1d12b0df308d604496c7ffa0c5b6e | [
"BSL-1.0"
] | null | null | null | lista1/156_Ananagrams/156_Ananagrams.py | L30Bola/mab606 | c29a781752b1d12b0df308d604496c7ffa0c5b6e | [
"BSL-1.0"
] | null | null | null | lista1/156_Ananagrams/156_Ananagrams.py | L30Bola/mab606 | c29a781752b1d12b0df308d604496c7ffa0c5b6e | [
"BSL-1.0"
] | null | null | null | #!/usr/bin/env python
import sys
import collections
listas = list(map(str.split, sys.stdin.readlines()))
entrada = [item for sublist in listas for item in sublist] # simplificando as listas, para facilitar
contador = collections.Counter()
palavras = []
for palavra in entrada:
if palavra == "#":
break
palavra_simplificada = "".join(sorted(palavra.lower()))
if len(palavra) >= 1:
contador[palavra_simplificada] += 1
palavras.append((palavra, palavra_simplificada))
lista_auxiliar_palavras = []
for palavra, palavra_simplificada in palavras:
if not palavra_simplificada in contador or contador[palavra_simplificada] < 2:
lista_auxiliar_palavras.append(palavra)
for resultado in sorted(lista_auxiliar_palavras):
print(resultado) | 29.076923 | 100 | 0.756614 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 67 | 0.088624 |
e87707daa361084b5b65d7322aabe0f103ce0c0e | 1,253 | py | Python | tests/test_evaluation.py | manslogic/rasa_core | 17c82e6be052fc147caef9a9914d06f79a944687 | [
"Apache-2.0"
] | 1 | 2018-07-03T16:04:17.000Z | 2018-07-03T16:04:17.000Z | tests/test_evaluation.py | jenish-cj/botnlufoodrest | b41aa2c7a1f6e492e10f07e67562b612b5b13a53 | [
"Apache-2.0"
] | null | null | null | tests/test_evaluation.py | jenish-cj/botnlufoodrest | b41aa2c7a1f6e492e10f07e67562b612b5b13a53 | [
"Apache-2.0"
] | 2 | 2019-02-18T07:38:26.000Z | 2021-07-17T16:24:03.000Z | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import imghdr
import os
from rasa_core.evaluate import run_story_evaluation, \
collect_story_predictions
from tests.conftest import DEFAULT_STORIES_FILE
def test_evaluation_image_creation(tmpdir, default_agent):
model_path = os.path.join(tmpdir.strpath, "model")
default_agent.persist(model_path)
img_path = os.path.join(tmpdir.strpath, "evaltion.png")
run_story_evaluation(
story_file=DEFAULT_STORIES_FILE,
policy_model_path=model_path,
nlu_model_path=None,
out_file=img_path,
max_stories=None
)
assert os.path.isfile(img_path)
assert imghdr.what(img_path) == "png"
def test_evaluation_script(tmpdir, default_agent):
model_path = os.path.join(tmpdir.strpath, "model")
default_agent.persist(model_path)
actual, preds = collect_story_predictions(
story_file=DEFAULT_STORIES_FILE,
policy_model_path=model_path,
nlu_model_path=None,
max_stories=None,
shuffle_stories=False
)
assert len(actual) == 14
assert len(preds) == 14
| 29.833333 | 59 | 0.718276 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 33 | 0.026337 |
e877b89db0bfb82ba58d14b983fc1ab24f7cf650 | 3,138 | py | Python | PlatformAgents/com/cognizant/devops/platformagents/agents/deployment/xldeploy/XLDeployAgent3.py | gauravl612/Insights | 08efd4c4fb3658ebaa9fd2d9ffd1809b83fc397c | [
"Apache-2.0"
] | 1 | 2021-04-29T11:28:37.000Z | 2021-04-29T11:28:37.000Z | PlatformAgents/com/cognizant/devops/platformagents/agents/deployment/xldeploy/XLDeployAgent3.py | gauravl612/Insights | 08efd4c4fb3658ebaa9fd2d9ffd1809b83fc397c | [
"Apache-2.0"
] | 1 | 2021-04-13T05:34:16.000Z | 2021-04-13T05:34:16.000Z | PlatformAgents/com/cognizant/devops/platformagents/agents/deployment/xldeploy/XLDeployAgent3.py | gauravl612/Insights | 08efd4c4fb3658ebaa9fd2d9ffd1809b83fc397c | [
"Apache-2.0"
] | null | null | null | #-------------------------------------------------------------------------------
# Copyright 2017 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#-------------------------------------------------------------------------------
'''
Created on May 09, 2020
@author: 368419
'''
import json
import datetime
import logging
from datetime import timedelta
from ....core.BaseAgent3 import BaseAgent
class XLDeployAgent(BaseAgent):
def process(self):
baseEndPoint = self.config.get("baseEndPoint", '')
userID = self.config.get("userID", '')
passwd = self.config.get("passwd", '')
startFrom = self.config.get("startFrom", '')
beginDate = self.tracking.get("startDate", startFrom)
listtasksurl = baseEndPoint + "/task/query?begindate=" + beginDate
tasks = self.getResponse(listtasksurl, 'GET', userID, passwd, None)
data = []
metadata ={"labels" : ["XLDEPLOY_TASKS"],"dataUpdateSupported" : True,"uniqueKey" : ["taskId"]}
latestDate = beginDate
for task in tasks:
if task["metadata"]["taskType"]=="UPGRADE" or task["metadata"]["taskType"]=="INITIAL":
injectData = {}
if len(task["metadata"]["application"]) >= 1:
injectData['application_name'] = task["metadata"]["application"]
injectData['version'] = task["metadata"]["version"]
injectData['taskType'] = task["metadata"]["taskType"]
injectData['environment_id'] = task["metadata"]["environment_id"]
injectData['state'] = task.get("state")
injectData['startDate'] = task["startDate"]
if latestDate == None:
latestDate =task["startDate"]
elif task["startDate"] > latestDate:
latestDate = task["startDate"]
injectData['completionDate'] = task["completionDate"]
injectData['user'] = task.get("owner")
injectData['taskId'] = task.get("id")
injectData['failures'] = task.get("failures")
injectData['state2'] = task.get("state2")
data.append(injectData)
latestDate= latestDate.split("T")[0]
self.tracking["startDate"] = latestDate
self.publishToolsData(data,metadata)
self.updateTrackingJson(self.tracking)
if __name__ == "__main__":
XLDeployAgent() | 42.986301 | 103 | 0.553856 | 2,156 | 0.687062 | 0 | 0 | 0 | 0 | 0 | 0 | 1,353 | 0.431166 |
e877bcdf6e8af748d44d8529353ac8f08314df2b | 1,853 | py | Python | torchsupport/structured/chunkable.py | bobelly/torchsupport | 5aa0a04f20c193ec99310f5d6a3375d2e95e740d | [
"MIT"
] | 18 | 2019-05-02T16:32:15.000Z | 2021-04-16T09:33:54.000Z | torchsupport/structured/chunkable.py | bobelly/torchsupport | 5aa0a04f20c193ec99310f5d6a3375d2e95e740d | [
"MIT"
] | 5 | 2019-10-14T13:46:49.000Z | 2021-06-08T11:48:34.000Z | torchsupport/structured/chunkable.py | bobelly/torchsupport | 5aa0a04f20c193ec99310f5d6a3375d2e95e740d | [
"MIT"
] | 12 | 2019-05-12T21:34:24.000Z | 2021-07-15T14:14:16.000Z | import torch
from torch.nn.parallel.scatter_gather import Scatter
def chunk_sizes(lengths, num_targets):
num_entities = len(lengths)
chops = num_entities // num_targets
result = [
sum(lengths[idx * chops:(idx + 1) * chops])
for idx in range(num_targets)
]
return result
def chunk_tensor(tensor, lengths, targets, dim=0):
return Scatter.apply(targets, lengths, dim, tensor)
class Chunkable():
def chunk(self, targets):
raise NotImplementedError("Abstract.")
def scatter_chunked(inputs, target_gpus, dim=0):
r"""
Slices tensors into approximately equal chunks and
distributes them across given GPUs. Duplicates
references to objects that are not tensors.
"""
def scatter_map(obj):
if isinstance(obj, Chunkable):
return obj.chunk(target_gpus)
if isinstance(obj, torch.Tensor):
return Scatter.apply(target_gpus, None, dim, obj)
if isinstance(obj, tuple) and len(obj) > 0:
return list(zip(*map(scatter_map, obj)))
if isinstance(obj, list) and len(obj) > 0:
return list(map(list, zip(*map(scatter_map, obj))))
if isinstance(obj, dict) and len(obj) > 0:
return list(map(type(obj), zip(*map(scatter_map, obj.items()))))
return [obj for targets in target_gpus]
try:
return scatter_map(inputs)
finally:
scatter_map = None
def scatter_chunked_kwargs(inputs, kwargs, target_gpus, dim=0):
r"""Scatter with support for kwargs dictionary"""
inputs = scatter_chunked(inputs, target_gpus, dim) if inputs else []
kwargs = scatter_chunked(kwargs, target_gpus, dim) if kwargs else []
if len(inputs) < len(kwargs):
inputs.extend([() for _ in range(len(kwargs) - len(inputs))])
elif len(kwargs) < len(inputs):
kwargs.extend([{} for _ in range(len(inputs) - len(kwargs))])
inputs = tuple(inputs)
kwargs = tuple(kwargs)
return inputs, kwargs
| 33.089286 | 70 | 0.699406 | 89 | 0.04803 | 0 | 0 | 0 | 0 | 0 | 0 | 218 | 0.117647 |
e879a021a202e01effe229f08a5ace1da13c48a5 | 1,030 | py | Python | viz/main.py | YoniSchirris/SimCLR-1 | 535472ac76d24d368d3bc08c17987df315e0b657 | [
"Apache-2.0"
] | 1 | 2021-12-03T12:59:39.000Z | 2021-12-03T12:59:39.000Z | viz/main.py | YoniSchirris/SimCLR-1 | 535472ac76d24d368d3bc08c17987df315e0b657 | [
"Apache-2.0"
] | null | null | null | viz/main.py | YoniSchirris/SimCLR-1 | 535472ac76d24d368d3bc08c17987df315e0b657 | [
"Apache-2.0"
] | null | null | null | import torch
from viz.visualizer import Visualizer
from modules.deepmil import Attention
from msidata.dataset_msi_features_with_patients import PreProcessedMSIFeatureDataset
from testing.logistic_regression import get_precomputed_dataloader
import argparse
from experiment import ex
from utils import post_config_hook
@ex.automain
def main(_run, _log):
args = argparse.Namespace(**_run.config)
args = post_config_hook(args, _run)
args.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Get test data to be visualized
_, test_loader = get_precomputed_dataloader(args, args.use_precomputed_features_id)
# Load model to be used
model = Attention()
# Initialize visualizer.. not necessary?
viz = Visualizer()
viz.visualize_first_patient(test_loader, model, method='deepmil')
print('done')
# for step, data in enumerate(loader):
# optimizer.zero_grad()
# x = data[0]
# y = data[1]
if __name__=="__main__":
main() | 22.391304 | 87 | 0.72233 | 0 | 0 | 0 | 0 | 663 | 0.643689 | 0 | 0 | 232 | 0.225243 |
e879fd71ea6d131c8a7d4e47e9c565b330dabbe2 | 340 | py | Python | projects/golem_e2e/tests/login/login_missing_password.py | kangchenwei/keyautotest2 | f980d46cabfc128b2099af3d33968f236923063f | [
"MIT"
] | null | null | null | projects/golem_e2e/tests/login/login_missing_password.py | kangchenwei/keyautotest2 | f980d46cabfc128b2099af3d33968f236923063f | [
"MIT"
] | null | null | null | projects/golem_e2e/tests/login/login_missing_password.py | kangchenwei/keyautotest2 | f980d46cabfc128b2099af3d33968f236923063f | [
"MIT"
] | null | null | null |
description = 'Verify the user cannot log in if password value is missing'
pages = ['login']
def test(data):
navigate(data.env.url)
send_keys(login.username_input, 'admin')
click(login.login_button)
capture('Verify the correct error message is shown')
verify_text_in_element(login.error_list, 'Password is required')
| 28.333333 | 74 | 0.735294 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 139 | 0.408824 |
e87bc8cc8dabdbfbb895c83154f1502cc87556de | 3,960 | py | Python | scripts/09-architecture-vgg.py | jmrozanec/white-bkg-classification | 3cdc8a4842ab72ce1950cdd4da5d1692f88c295b | [
"Apache-2.0"
] | 2 | 2017-04-19T14:27:42.000Z | 2021-06-30T06:40:57.000Z | scripts/09-architecture-vgg.py | jmrozanec/white-bkg-classification | 3cdc8a4842ab72ce1950cdd4da5d1692f88c295b | [
"Apache-2.0"
] | null | null | null | scripts/09-architecture-vgg.py | jmrozanec/white-bkg-classification | 3cdc8a4842ab72ce1950cdd4da5d1692f88c295b | [
"Apache-2.0"
] | null | null | null | #TFLearn bug regarding image loading: https://github.com/tflearn/tflearn/issues/180
#Monochromes img-magick: https://poizan.dk/blog/2014/02/28/monochrome-images-in-imagemagick/
#How to persist a model: https://github.com/tflearn/tflearn/blob/master/examples/basics/weights_persistence.py
from __future__ import division, print_function, absolute_import
import tflearn
from tflearn.data_utils import shuffle, to_categorical
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.normalization import local_response_normalization, batch_normalization
from tflearn.layers.estimator import regression
from tflearn.data_utils import image_preloader
train_file = '../images/sampling/dataset-splits/train-cv-1.txt'
test_file = '../images/sampling/dataset-splits/test-cv-1.txt'
from tflearn.data_preprocessing import ImagePreprocessing
import os
def vgg16(input, num_class):
x = tflearn.conv_2d(input, 64, 3, activation='relu', scope='conv1_1')
x = tflearn.conv_2d(x, 64, 3, activation='relu', scope='conv1_2')
x = tflearn.max_pool_2d(x, 2, strides=2, name='maxpool1')
x = tflearn.conv_2d(x, 128, 3, activation='relu', scope='conv2_1')
x = tflearn.conv_2d(x, 128, 3, activation='relu', scope='conv2_2')
x = tflearn.max_pool_2d(x, 2, strides=2, name='maxpool2')
x = tflearn.conv_2d(x, 256, 3, activation='relu', scope='conv3_1')
x = tflearn.conv_2d(x, 256, 3, activation='relu', scope='conv3_2')
x = tflearn.conv_2d(x, 256, 3, activation='relu', scope='conv3_3')
x = tflearn.max_pool_2d(x, 2, strides=2, name='maxpool3')
x = tflearn.conv_2d(x, 512, 3, activation='relu', scope='conv4_1')
x = tflearn.conv_2d(x, 512, 3, activation='relu', scope='conv4_2')
x = tflearn.conv_2d(x, 512, 3, activation='relu', scope='conv4_3')
x = tflearn.max_pool_2d(x, 2, strides=2, name='maxpool4')
x = tflearn.conv_2d(x, 512, 3, activation='relu', scope='conv5_1')
x = tflearn.conv_2d(x, 512, 3, activation='relu', scope='conv5_2')
x = tflearn.conv_2d(x, 512, 3, activation='relu', scope='conv5_3')
x = tflearn.max_pool_2d(x, 2, strides=2, name='maxpool5')
x = tflearn.fully_connected(x, 4096, activation='relu', scope='fc6')
x = tflearn.dropout(x, 0.5, name='dropout1')
x = tflearn.fully_connected(x, 4096, activation='relu', scope='fc7')
x = tflearn.dropout(x, 0.5, name='dropout2')
x = tflearn.fully_connected(x, num_class, activation='softmax', scope='fc8',
restore=False)
return x
channels=1
width=64
height=50
model_path = "/tmp"
# the file gen by generated by gen_files_list.py
files_list = "../images/sampling/train-imgs.txt"
from tflearn.data_utils import image_preloader
X, Y = image_preloader(files_list, image_shape=(256, 256), mode='file',
categorical_labels=True, normalize=False,
filter_channel=True)
num_classes = 2 # num of your dataset
# VGG preprocessing
img_prep = ImagePreprocessing()
img_prep.add_featurewise_zero_center(mean=[123.68, 116.779, 103.939],
per_channel=True)
# VGG Network
x = tflearn.input_data(shape=[None, 256, 256, 3], name='input',
data_preprocessing=img_prep)
softmax = vgg16(x, num_classes)
regression = tflearn.regression(softmax, optimizer='adam',
loss='categorical_crossentropy',
learning_rate=0.001, restore=False)
model = tflearn.DNN(regression, checkpoint_path='vgg-finetuning',
max_checkpoints=3, tensorboard_verbose=2,
tensorboard_dir="./logs")
# Start finetuning
model.fit(X, Y, n_epoch=10, validation_set=0.1, shuffle=True,
show_metric=True, batch_size=64, snapshot_epoch=False,
snapshot_step=200, run_id='vgg-finetuning')
model.save('your-task-model-retrained-by-vgg')
| 43.043478 | 110 | 0.690657 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 964 | 0.243434 |
e87bfc2df49be35ad4d4725f2a412dd8728e4e79 | 392 | py | Python | client.py | octoi/simple-file-transfer | 0b6f872530363751b6a6d2f1bbfd99b8ffd5fb0c | [
"MIT"
] | null | null | null | client.py | octoi/simple-file-transfer | 0b6f872530363751b6a6d2f1bbfd99b8ffd5fb0c | [
"MIT"
] | null | null | null | client.py | octoi/simple-file-transfer | 0b6f872530363751b6a6d2f1bbfd99b8ffd5fb0c | [
"MIT"
] | null | null | null | import socket
s = socket.socket()
host = input(str("Please enter the host address of the sender: "))
port = 8080
s.connect((host, port))
print(f"[+] CONNECTED TO {host}:{port}")
filename = input(str("Please enter filename for the incoming file: "))
file = open(filename, 'wb')
file_data = s.recv(1024)
file.write(file_data)
file.close()
print(f"[+] FILE SAVED SUCCESSFULLY {filename}")
| 20.631579 | 70 | 0.696429 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 172 | 0.438776 |
e87c1eb3a1fc5933ac084b08ee6c28e19afa0d6a | 3,413 | py | Python | examplesFromForkedLibraries/PhilReinholdPygrape/4 discarded/benchmarks.py | rayonde/yarn | a8259292791b3332e8521baeb6c7ee78afb53ae2 | [
"MIT"
] | 1 | 2020-07-09T13:31:21.000Z | 2020-07-09T13:31:21.000Z | examplesFromForkedLibraries/PhilReinholdPygrape/4 discarded/benchmarks.py | rayonde/yarn | a8259292791b3332e8521baeb6c7ee78afb53ae2 | [
"MIT"
] | null | null | null | examplesFromForkedLibraries/PhilReinholdPygrape/4 discarded/benchmarks.py | rayonde/yarn | a8259292791b3332e8521baeb6c7ee78afb53ae2 | [
"MIT"
] | null | null | null | import qutip as q
import numpy as np
import scipy.sparse.linalg
from pygrape.cugrape.configure_cugrape import configure, get_hmt_ops
from pygrape.cugrape.almohy import get_taylor_params
from pygrape.setups import StateTransferSetup
from pygrape.cuda_setup import CudaStateTransferSetup
def get_Hs(mode_dims, dt, numeric=False):
def destroy(n):
ops = [q.qeye(d) for d in mode_dims]
ops[n] = q.destroy(mode_dims[n])
return q.tensor(*list(reversed(ops)))
n_modes = len(mode_dims)
if numeric:
ops = map(destroy, range(n_modes))
ops = [(a, a.dag()) for a in ops]
else:
ops = get_hmt_ops(n_modes)
kerr = dt*1e-5
chi = dt*1e-3
drive = dt*1e-2
H0 = 0
Hcs = []
for i, (d, (a, ad)) in enumerate(zip(mode_dims, ops)):
if d > 2:
H0 += d*kerr/2 * (ad*ad*a*a)
for b, bd in ops[i+1:]:
H0 += d*chi * ad*a*bd*b
Hcs.append(drive*(a + ad))
Hcs.append(1j*drive*(a - ad))
if numeric:
H0 = H0.data.tocsr()
Hcs = [H.data.tocsr() for H in Hcs]
return H0, Hcs
class TimeSuite:
params = [
# mode_dims
[[[2, 20, 20], [2, 19, 20]], [[2, 2, 2, 2, 20], [2, 2, 2, 2, 19]]],
# plen
[50, 250, 2000],
# dt
[0.1, 1],
# nstate
[8, 1],
# double
[False],
# n_step
[10],
# use_gpu
[False, True],
]
def setup(self, mode_dims, plen, dt, nstate, double, n_step, use_gpu):
print('Params:', mode_dims, plen, dt, nstate, double, n_step, use_gpu)
H0, Hcs = get_Hs(mode_dims[0], dt, numeric=True)
Hnorm = scipy.sparse.linalg.norm(H0 + sum(Hcs), 1)
taylor_order, n_rep = get_taylor_params(Hnorm, 1e-8)
assert n_rep == 1, (Hnorm, taylor_order, n_rep)
nctrls = len(Hcs)
np.random.seed(12345)
psi0s, psifs = [], []
for mds in mode_dims:
dim = np.product(mds)
psi0 = np.random.randn(nstate, dim) + 1j*np.random.randn(nstate, dim)
psi0 /= np.linalg.norm(psi0, axis=1)[:,None]
psi0s.append(psi0)
psif = np.random.randn(nstate, dim) + 1j*np.random.randn(nstate, dim)
psif /= np.linalg.norm(psif, axis=1)[:,None]
psifs.append(psif)
controls = np.random.randn(nctrls, plen)
self.all_controls = np.random.randn(n_step, nctrls, plen)
self.grape_setups = []
if use_gpu:
H0, Hcs = get_Hs(mode_dims[0], dt, numeric=False)
setup = CudaStateTransferSetup(mode_dims, H0, Hcs, psi0s, psifs, taylor_order, double)
setup.init_cugrape(plen, 1)
self.grape_setups.append(setup)
else:
for mds, psi0, psif in zip(mode_dims, psi0s, psifs):
H0, Hcs = get_Hs(mds, dt, numeric=True)
setup = StateTransferSetup(H0, Hcs, psi0, psif, sparse=True, use_taylor=True)
setup.set_dtype(np.complex128 if double else np.complex64)
self.grape_setups.append(setup)
def time_run_steps(self, *args):
for ctrls in self.all_controls:
for setup in self.grape_setups:
setup.get_fids(ctrls, [], 1)
# if __name__ == '__main__':
# ts = TimeSuite()
# ts.setup(*(list(zip(*ts.params))[0]))
# ts.time_run_steps(*(list(zip(*ts.params))[0]))
| 33.460784 | 98 | 0.562848 | 2,153 | 0.630823 | 0 | 0 | 0 | 0 | 0 | 0 | 208 | 0.060943 |
e87d57d0c478e441bd8e2fe9c189947046ddeca4 | 39,545 | py | Python | fsleyes/layouts.py | pauldmccarthy/fsleyes | 453a6b91ec7763c39195814d635257e3766acf83 | [
"Apache-2.0"
] | 12 | 2018-05-05T01:36:25.000Z | 2021-09-23T20:44:08.000Z | fsleyes/layouts.py | pauldmccarthy/fsleyes | 453a6b91ec7763c39195814d635257e3766acf83 | [
"Apache-2.0"
] | 97 | 2018-05-05T02:17:23.000Z | 2022-03-29T14:58:42.000Z | fsleyes/layouts.py | pauldmccarthy/fsleyes | 453a6b91ec7763c39195814d635257e3766acf83 | [
"Apache-2.0"
] | 6 | 2017-12-09T09:02:00.000Z | 2021-03-05T18:55:13.000Z | #!/usr/bin/env python
#
# layout.py - The layout API (previously called "perspectives").
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#
"""This module provides functions for managing *layouts* - stored view and
control panel layouts for *FSLeyes*. Layouts may be persisted using the
:mod:`.settings` module. A few layouts are also *built in*, and are
defined in the :attr:`BUILT_IN_LAYOUTS` dictionary.
.. note:: Prior to FSLeyes 0.24.0, *layouts* were called *perspectives*.
The ``layouts`` module provides the following functions. These are intended
for use by the :class:`.FSLeyesFrame`, but can be used in other ways too:
.. autosummary::
:nosignatures:
getAllLayouts
loadLayout
applyLayout
saveLayout
removeLayout
serialiseLayout
deserialiseLayout
A layout defines a layout for a :class:`.FSLeyesFrame`. It specifies the
type and layout of one or more *views* (defined in the :mod:`.views` module)
and, within each view, the type and layout of one or more *controls* (defined
in the :mod:`.controls` module). See the :mod:`fsleyes` documentation for
an overview of views and controls.
All of this information is stored as a string - see the
:func:`serialiseLayout` function for details on its storage format.
"""
import functools as ft
import logging
import pkgutil
import textwrap
import importlib
import collections
import fsl.utils.settings as fslsettings
import fsleyes_widgets.utils.status as status
import fsleyes.strings as strings
import fsleyes.plugins as plugins
import fsleyes.controls as controls
import fsleyes.views as views
import fsleyes.views.viewpanel as viewpanel
import fsleyes.views.canvaspanel as canvaspanel
import fsleyes.views.plotpanel as plotpanel
import fsleyes.controls.controlpanel as controlpanel
log = logging.getLogger(__name__)
def getAllLayouts():
"""Returns a list containing the names of all saved layouts. The
returned list does not include built-in layouts - these are
accessible in the :attr:`BUILT_IN_LAYOUTS` dictionary.
"""
layouts = fslsettings.read('fsleyes.layouts', []) + \
fslsettings.read('fsleyes.perspectives', [])
uniq = []
for l in layouts:
if l not in uniq:
uniq.append(l)
return uniq
def loadLayout(frame, name, **kwargs):
"""Load the named layout, and apply it to the given
:class:`.FSLeyesFrame`. The ``kwargs`` are passed through to the
:func:`applyLayout` function.
"""
if name in BUILT_IN_LAYOUTS.keys():
log.debug('Loading built-in layout {}'.format(name))
layout = BUILT_IN_LAYOUTS[name]
else:
log.debug('Loading saved layout {}'.format(name))
layout = fslsettings.read('fsleyes.layouts.{}'.format(name), None)
if layout is None:
fslsettings.read('fsleyes.perspectives.{}'.format(name), None)
if layout is None:
raise ValueError('No layout named "{}" exists'.format(name))
log.debug('Applying layout:\n{}'.format(layout))
applyLayout(frame, name, layout, **kwargs)
def applyLayout(frame, name, layout, message=None):
"""Applies the given serialised layout string to the given
:class:`.FSLeyesFrame`.
:arg frame: The :class:`.FSLeyesFrame` instance.
:arg name: The layout name.
:arg layout: The serialised layout string.
:arg message: A message to display (using the :mod:`.status` module).
"""
import fsleyes.views.canvaspanel as canvaspanel
layout = deserialiseLayout(layout)
frameChildren = layout[0]
frameLayout = layout[1]
vpChildrens = layout[2]
vpLayouts = layout[3]
vpPanelProps = layout[4]
vpSceneProps = layout[5]
# Show a message while re-configuring the frame
if message is None:
message = strings.messages[
'layout.applyingLayout'].format(
strings.layouts.get(name, name))
status.update(message)
# Clear all existing view
# panels from the frame
frame.removeAllViewPanels()
# Add all of the view panels
# specified in the layout
for vp in frameChildren:
log.debug('Adding view panel {} to frame'.format(vp.__name__))
frame.addViewPanel(vp, defaultLayout=False)
# Apply the layout to those view panels
frame.auiManager.LoadPerspective(frameLayout)
# For each view panel, add all of the
# control panels, and lay them out
viewPanels = frame.viewPanels
for i in range(len(viewPanels)):
vp = viewPanels[ i]
children = vpChildrens[ i]
vpLayout = vpLayouts[ i]
panelProps = vpPanelProps[i]
sceneProps = vpSceneProps[i]
for child in children:
log.debug('Adding control panel {} to {}'.format(
child.__name__, type(vp).__name__))
_addControlPanel(vp, child)
vp.auiManager.LoadPerspective(vpLayout)
# Apply saved property values
# to the view panel.
for name, val in panelProps.items():
log.debug('Setting {}.{} = {}'.format(
type(vp).__name__, name, val))
vp.deserialise(name, val)
# And to its SceneOpts instance if
# it is a CanvasPanel, or its
# PlotCanvas if it is a PlotPanel
if isinstance(vp, canvaspanel.CanvasPanel): aux = vp.sceneOpts
elif isinstance(vp, plotpanel.PlotPanel): aux = vp.canvas
for name, val in sceneProps.items():
log.debug('Setting {}.{} = {}'.format(
type(aux).__name__, name, val))
aux.deserialise(name, val)
def saveLayout(frame, name):
"""Serialises the layout of the given :class:`.FSLeyesFrame` and saves
it as a layout with the given name.
"""
if name in BUILT_IN_LAYOUTS.keys():
raise ValueError('A built-in layout named "{}" '
'already exists'.format(name))
log.debug('Saving current layout with name {}'.format(name))
layout = serialiseLayout(frame)
fslsettings.write('fsleyes.layouts.{}'.format(name), layout)
_addToLayoutList(name)
log.debug('Serialised layout:\n{}'.format(layout))
def removeLayout(name):
"""Deletes the named layout. """
log.debug('Deleting layout with name {}'.format(name))
fslsettings.delete('fsleyes.layouts.{}' .format(name))
fslsettings.delete('fsleyes.perspectives.{}'.format(name))
_removeFromLayoutList(name)
def serialiseLayout(frame):
"""Serialises the layout of the given :class:`.FSLeyesFrame`, and returns
it as a string.
.. note:: This function was written against wx.lib.agw.aui.AuiManager as
it exists in wxPython 3.0.2.0.
*FSLeyes* uses a hierarchy of ``wx.lib.agw.aui.AuiManager`` instances for
its layout - the :class:`.FSLeyesFrame` uses an ``AuiManager`` to lay out
:class:`.ViewPanel` instances, and each of these ``ViewPanels`` use their
own ``AuiManager`` to lay out control panels.
The layout for a single ``AuiManager`` can be serialised to a string via
the ``AuiManager.SavePerspective`` and ``AuiManager.SavePaneInfo``
methods. One of these strings consists of:
- A name, `'layout1'` or `'layout2'`, specifying the AUI version
(this will always be at least `'layout2'` for *FSLeyes*).
- A set of key-value set of key-value pairs defining the top level
panel layout.
- A set of key-value pairs for each pane, defining its layout. the
``AuiManager.SavePaneInfo`` method returns this for a single pane.
These are all encoded in a single string, with the above components
separated with '|' characters, and the pane-level key-value pairs
separated with a ';' character. For example:
layout2|key1=value1|name=Pane1;caption=Pane 1|\
name=Pane2;caption=Pane 2|doc_size(5,0,0)=22|
This function queries each of the AuiManagers, and extracts the following:
1. A layout string for the :class:`.FSLeyesFrame`.
2. A string containing a comma-separated list of :class:`.ViewPanel`
class names, in the same order as they are specified in the frame
layout string.
3. For each ``ViewPanel``:
- A layout string for the ``ViewPanel``
- A string containing a comma-separated list of control panel
class names, in the same order as specified in the
``ViewPanel`` layout string.
Each of these pieces of information are then concatenated into a single
newline separated string.
In FSLeyes 0.35.0, the list of ``ViewPanel`` and ``ControlPanel`` class
names was changed from containing just the class names
(e.g. ``'OrthoPanel'``) to containing the fully resolved class paths
(e.g. ``'fsleyes.views.orthopanel.OrthoPanel'``). The
:func:`deserialiseLayout` function is compatible with both formats.
"""
# We'll start by defining this silly function, which
# takes an ``AuiManager`` layout string, and a list
# of the children which are being managed by the
# AuiManager, and makes sure that the order of the
# child pane layout specifications in the string is
# the same as the order of the children in the list.
#
# If the 'rename' argument is True, this function
# performs an additional step.
#
# The FSLeyesFrame gives each of its view panels a
# unique name of the form "ClassName index", where
# the 'index' is a sequentially increasing identifier
# number (so that multiple views of the same type can
# be differentiated). If the 'rename' argument to
# this function is True, these names are adjusted so
# that they begin at 1 and increase sequentially. This
# is done by the patchPanelName function, defined
# below.
#
# This name adjustment is required to handle
# situations where the indices of existing view panels
# are not sequential, as when a layout is applied, the
# view panel names given by the FSLeyesFrame must
# match the names that are specified in the layout
# string.
#
# In addition to patching the name of each panel,
# the 'rename' argument will also cause the panel
# caption (its display title) to be adjusted so that
# it is in line with the name.
def patchLayoutString(auiMgr, panels, rename=False):
layoutStr = auiMgr.SavePerspective()
# The different sections of the string
# returned by SavePerspective are
# separated with a '|' character.
sections = layoutStr.split('|')
sections = [s.strip() for s in sections]
sections = [s for s in sections if s != '']
# Here, we identify sections which specify
# the layout of a child pane, remove them,
# and patch them back in, in the order that
# the child panels are specified in the list.
pi = 0
for si, s in enumerate(sections):
if s.find('name=') > -1:
panel = panels[pi]
panelInfo = auiMgr.GetPane(panel)
panelLayout = auiMgr.SavePaneInfo(panelInfo)
pi += 1
sections[si] = panelLayout
if rename:
sections[si] = patchPanelName(sections[si], pi)
# Now the panel layouts in our layout string
# are in the same order as our list of view
# panels - we can re-join the layout string
# sections, and we're done.
return '|'.join(sections) + '|'
# The purpose of this function is described above.
def patchPanelName(layoutString, index):
# In each AUI layout section, 'key=value'
# pairs are separated with a semi-colon
kvps = layoutString.split(';')
# And each 'key=value' pair is separated
# with an equals character
kvps = [kvp.split('=') for kvp in kvps]
kvps = collections.OrderedDict(kvps)
# We need to update the indices contained
# in the 'name' and 'caption' values
name = kvps['name']
caption = kvps['caption']
# Strip off the old index
name = ' '.join(name .split()[:-1])
caption = ' '.join(caption.split()[:-1])
# Patch in the new index
name = '{} {}'.format(name, index)
caption = '{} {}'.format(caption, index)
kvps['name'] = name
kvps['caption'] = caption
# Reconstruct the layout string
kvps = ['='.join((k, v)) for k, v in kvps.items()]
kvps = ';'.join(kvps)
return kvps
# Now we can start extracting the layout information.
# We start with the FSLeyesFrame layout.
auiMgr = frame.auiManager
viewPanels = frame.viewPanels
# Generate the frame layout string, and a
# list of the children of the frame
frameLayout = patchLayoutString(auiMgr, viewPanels, True)
frameChildren = ['.'.join((type(vp).__module__, type(vp).__qualname__))
for vp in viewPanels]
frameChildren = ','.join(frameChildren)
# We are going to build a list of layout strings,
# one for each ViewPanel, and a corresponding list
# of control panels displayed on each ViewPanel.
vpLayouts = []
vpConfigs = []
for vp in viewPanels:
# Get the auiManager and layout for this view panel.
# This is a little bit complicated, as ViewPanels
# differentiate between the main 'centre' panel, and
# all other secondary (control) panels. The layout
# string needs to contain layout information for
# all of these panels, but we only care about the
# control panels.
vpAuiMgr = vp.auiManager
ctrlPanels = vp.getPanels()
centrePanel = vp.centrePanel
# As above for the frame, generate a layout
# string and a list of control panels - the
# children of the view panel.
vpLayout = patchLayoutString(vpAuiMgr, [centrePanel] + ctrlPanels)
vpChildren = ['.'.join((type(cp).__module__, type(cp).__qualname__))
for cp in ctrlPanels]
vpChildren = ','.join(vpChildren)
# Get the panel and scene settings
panelProps, sceneProps = _getPanelProps(vp)
# And turn them into comma-separated key-value pairs.
panelProps = ['{}={}'.format(k, v) for k, v in panelProps.items()]
sceneProps = ['{}={}'.format(k, v) for k, v in sceneProps.items()]
panelProps = ','.join(panelProps)
sceneProps = ','.join(sceneProps)
# Build the config string - the children,
# the panel settings and the scene settings.
vpConfig = ';'.join([vpChildren, panelProps, sceneProps])
vpLayouts.append(vpLayout)
vpConfigs.append(vpConfig)
# We serialise all of these pieces of information
# as a single newline-separated string.
layout = [frameChildren, frameLayout]
for vpConfig, vpLayout in zip(vpConfigs, vpLayouts):
layout.append(vpConfig)
layout.append(vpLayout)
# And we're done!
return '\n'.join(layout)
def deserialiseLayout(layout):
"""Deserialises a layout string which was created by the
:func:`serialiseLayout` string.
:returns: A tuple containing the following:
- A list of :class:`.ViewPanel` class types - the
children of the :class:`.FSLeyesFrame`.
- An ``aui`` layout string for the :class:`.FSLeyesFrame`
- A list of lists, one for each ``ViewPanel``, with each
list containing a collection of control panel class
types - the children of the corresponding ``ViewPanel``.
- A list of strings, one ``aui`` layout string for each
``ViewPanel``.
- A list of dictionaries, one for each ``ViewPanel``,
containing property ``{name : value}`` pairs to be
applied to the ``ViewPanel``.
- A list of dictionaries, one for each ``ViewPanel``,
containing property ``{name : value}`` pairs to be applied
to the :class:`.SceneOpts` instance associated with the
``ViewPanel``, if it is a :class:`.CanvasPanel`, or the
:class:`.PlotCanvas` instance associated with the
``ViewPanel``, if it is a :class:`.PlotPanel`.
"""
# Versions of FSLeyes prior to 1.0.0 would just
# save the view/control class name. This was
# changed in 1.0.0 so that the full path to the
# class is saved. This function aims to be
# compatible with both formats - given a class
# name, or a fully resolved class name, it will
# return the corresponding type object.
def findViewOrControl(panelname, paneltype):
# new format
if '.' in panelname:
mod, cls = panelname.rsplit('.', maxsplit=1)
mod = importlib.import_module(mod)
return getattr(mod, cls)
# make a list of all candidate types,
# then search through them for a match
panels = []
# builtins
if paneltype == 'control':
basemod = controls
basetype = (controlpanel.ControlPanel,
controlpanel.ControlToolBar)
else:
basemod = views
basetype = viewpanel.ViewPanel
mods = pkgutil.iter_modules(basemod.__path__, basemod.__name__ + '.')
for _, mod, _ in mods:
mod = importlib.import_module(mod)
for att in dir(mod):
att = getattr(mod, att)
if isinstance(att, type) and issubclass(att, basetype):
panels.append(att)
# plugins
if paneltype == 'control':
panels.extend(plugins.listControls().values())
else:
panels.extend(plugins.listViews().values())
for panel in panels:
if panel.__name__ == panelname:
return panel
raise ValueError('Unknown FSLeyes panel type: {}'.format(panelname))
findView = ft.partial(findViewOrControl, paneltype='view')
findControl = ft.partial(findViewOrControl, paneltype='control')
lines = layout.split('\n')
lines = [line.strip() for line in lines]
lines = [line for line in lines if line != '']
frameChildren = lines[0]
frameLayout = lines[1]
# The children strings are comma-separated
# class names. The frame children are ViewPanels,
# which are all defined in the fsleyes.views
# package.
frameChildren = frameChildren.split(',')
frameChildren = [fc.strip() for fc in frameChildren]
frameChildren = [fc for fc in frameChildren if fc != '']
frameChildren = [findView(fc) for fc in frameChildren]
# Collate the children/layouts for each view panel
vpChildren = []
vpLayouts = []
vpPanelProps = []
vpSceneProps = []
for i in range(len(frameChildren)):
linei = (i * 2) + 2
config = lines[linei]
layout = lines[linei + 1]
children, panelProps, sceneProps = config.split(';')
vpChildren .append(children)
vpLayouts .append(layout)
vpPanelProps .append(panelProps)
vpSceneProps .append(sceneProps)
# The ViewPanel children string is a comma-separated
# list of control panel class names. All control panels
# should be defined in the fsleyes.controls package.
for i in range(len(vpChildren)):
children = vpChildren[i].split(',')
children = [vpc.strip() for vpc in children]
children = [vpc for vpc in children if vpc != '']
children = [findControl(vpc) for vpc in children]
vpChildren[i] = children
# The panel props and scene props strings are
# comma-separated lists of 'prop=value' pairs.
# We'll turn them into a dict for convenience.
for i in range(len(vpPanelProps)):
props = vpPanelProps[i].split(',')
props = [p for p in props if p != '']
props = [p.split('=') for p in props]
vpPanelProps[i] = collections.OrderedDict(props)
for i in range(len(vpSceneProps)):
props = vpSceneProps[i].split(',')
props = [p for p in props if p != '']
props = [p.split('=') for p in props]
vpSceneProps[i] = collections.OrderedDict(props)
return (frameChildren,
frameLayout,
vpChildren,
vpLayouts,
vpPanelProps,
vpSceneProps)
def _addToLayoutList(layout):
"""Adds the given layout name to the list of saved layouts. """
layout = layout.strip()
layouts = getAllLayouts()
if layout not in layouts:
layouts.append(layout)
log.debug('Updating stored layout list: {}'.format(layout))
fslsettings.write('fsleyes.layouts', layouts)
def _removeFromLayoutList(layout):
"""Removes the given layout name from the list of saved layouts.
"""
layouts = getAllLayouts()
try: layouts.remove(layout)
except ValueError: return
log.debug('Updating stored layout list: {}'.format(layouts))
fslsettings.write('fsleyes.layouts', layouts)
def _addControlPanel(viewPanel, panelType):
"""Adds a control panel to the given :class:`.ViewPanel`.
:arg viewPanel: A :class:`.ViewPanel` instance.
:arg panelType: A control panel type.
"""
viewPanel.togglePanel(panelType)
def _getPanelProps(panel):
"""Creates and returns two dictionaries, containing properties of the given
:class:`.ViewPanel` (and its associated :class:`.SceneOpts` instance, if
it is a :class:`.CanvasPanel`, or :class:`.PlotCanvas`, if it is a
:class:`.PlotPanel`), which are to be saved as part of a seriaised
*FSLeyes* layout. The properties to be saved are listed in the
:data:`VIEWPANEL_PROPS` dictionary.
"""
if not isinstance(panel, (canvaspanel.CanvasPanel, plotpanel.PlotPanel)):
return {}, {}
panelType = type(panel).__name__
panelProps, sceneProps = VIEWPANEL_PROPS.get(panelType, ({}, {}))
if isinstance(panel, canvaspanel.CanvasPanel):
aux = panel.sceneOpts
elif isinstance(panel, plotpanel.PlotPanel):
aux = panel.canvas
panelProps = {name : panel.serialise(name) for name in panelProps}
sceneProps = {name : aux .serialise(name) for name in sceneProps}
return panelProps, sceneProps
VIEWPANEL_PROPS = {
'OrthoPanel' : [['syncLocation',
'syncOverlayOrder',
'syncOverlayDisplay',
'syncOverlayVolume',
'movieRate',
'movieAxis'],
['showCursor',
'bgColour',
'fgColour',
'cursorColour',
'cursorGap',
'showColourBar',
'colourBarLocation',
'colourBarLabelSide',
'showXCanvas',
'showYCanvas',
'showZCanvas',
'showLabels',
'labelSize',
'layout',
'xzoom',
'yzoom',
'zzoom',
'highDpi']],
'LightBoxPanel' : [['syncLocation',
'syncOverlayOrder',
'syncOverlayDisplay',
'syncOverlayVolume',
'movieRate',
'movieAxis'],
['showCursor',
'bgColour',
'fgColour',
'cursorColour',
'showColourBar',
'colourBarLocation',
'colourBarLabelSide',
'zax',
'showGridLines',
'highlightSlice',
'highDpi']],
'Scene3DPanel' : [['syncLocation',
'syncOverlayOrder',
'syncOverlayDisplay',
'syncOverlayVolume'],
['showCursor',
'bgColour',
'fgColour',
'cursorColour',
'showColourBar',
'colourBarLocation',
'colourBarLabelSide',
'occlusion',
'light',
'lightPos',
'offset',
'rotation',
'showLegend']],
'TimeSeriesPanel' : [['usePixdim',
'plotMode',
'plotMelodicICs'],
['legend',
'xAutoScale',
'yAutoScale',
'xLogScale',
'yLogScale',
'ticks',
'grid',
'gridColour',
'bgColour',
'smooth']],
'HistogramPanel' : [['histType',
'plotType'],
['legend',
'xAutoScale',
'yAutoScale',
'xLogScale',
'yLogScale',
'ticks',
'grid',
'gridColour',
'bgColour',
'smooth']],
'PowerSpectrumPanel' : [['plotMelodicICs',
'plotFrequencies'],
['legend',
'xAutoScale',
'yAutoScale',
'xLogScale',
'yLogScale',
'ticks',
'grid',
'gridColour',
'bgColour',
'smooth']]}
# The order in which properties are defined in
# a layout is the order in which they will
# be applied. This is important to remember when
# considering properties that have side effects
# (e.g. setting SceneOpts.bgColour will clobber
# SceneOpts.fgColour).
BUILT_IN_LAYOUTS = collections.OrderedDict((
('default',
textwrap.dedent("""
fsleyes.views.orthopanel.OrthoPanel
layout2|name=OrthoPanel 1;caption=Ortho View 1;state=67376064;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(5,0,0)=22|
fsleyes.controls.orthotoolbar.OrthoToolBar,fsleyes.controls.overlaydisplaytoolbar.OverlayDisplayToolBar,fsleyes.controls.overlaylistpanel.OverlayListPanel,fsleyes.controls.locationpanel.LocationPanel;syncOverlayOrder=True,syncLocation=True,syncOverlayDisplay=True,movieRate=400;colourBarLocation=top,showCursor=True,bgColour=#000000ff,layout=horizontal,colourBarLabelSide=top-left,cursorGap=False,fgColour=#ffffffff,cursorColour=#00ff00ff,showXCanvas=True,showYCanvas=True,showColourBar=False,showZCanvas=True,showLabels=True
layout2|name=Panel;caption=;state=768;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=OrthoToolBar;caption=Ortho view toolbar;state=67382012;dir=1;layer=10;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=OverlayDisplayToolBar;caption=Display toolbar;state=67382012;dir=1;layer=11;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=OverlayListPanel;caption=Overlay list;state=67373052;dir=3;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=1;minh=1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=LocationPanel;caption=Location;state=67373052;dir=3;layer=0;row=0;pos=1;prop=100000;bestw=-1;besth=-1;minw=1;minh=1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(5,0,0)=22|dock_size(3,0,0)=176|dock_size(1,10,0)=49|dock_size(1,11,0)=67|
""")), # noqa
('melodic',
textwrap.dedent("""
fsleyes.views.lightboxpanel.LightBoxPanel,fsleyes.views.timeseriespanel.TimeSeriesPanel,fsleyes.views.powerspectrumpanel.PowerSpectrumPanel
layout2|name=LightBoxPanel 1;caption=Lightbox View 1;state=67377088;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=TimeSeriesPanel 2;caption=Time series 2;state=67377148;dir=3;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=PowerSpectrumPanel 3;caption=Power spectra 3;state=67377148;dir=3;layer=0;row=0;pos=1;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(5,0,0)=22|dock_size(3,0,0)=224|
fsleyes.controls.locationpanel.LocationPanel,fsleyes.controls.overlaylistpanel.OverlayListPanel,fsleyes.plugins.controls.melodicclassificationpanel.MelodicClassificationPanel,fsleyes.controls.lightboxtoolbar.LightBoxToolBar,fsleyes.controls.overlaydisplaytoolbar.OverlayDisplayToolBar;syncLocation=True,syncOverlayOrder=True,movieRate=750,syncOverlayDisplay=True;bgColour=#000000ff,fgColour=#ffffffff,showCursor=True,cursorColour=#00ff00ff,highlightSlice=False,zax=2,showColourBar=False,showGridLines=False,colourBarLocation=top
layout2|name=Panel;caption=;state=768;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=LocationPanel;caption=Location;state=67373052;dir=3;layer=0;row=0;pos=1;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=OverlayListPanel;caption=Overlay list;state=67373052;dir=3;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=MelodicClassificationPanel;caption=Melodic IC classification;state=67373052;dir=2;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=LightBoxToolBar;caption=Lightbox view toolbar;state=67382012;dir=1;layer=10;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=OverlayDisplayToolBar;caption=Display toolbar;state=67382012;dir=1;layer=11;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(5,0,0)=22|dock_size(3,0,0)=130|dock_size(1,10,0)=45|dock_size(1,11,0)=51|dock_size(2,0,0)=402|
TimeSeriesToolBar;;
layout2|name=FigureCanvasWxAgg;caption=;state=768;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=TimeSeriesToolBar;caption=Time series toolbar;state=67382012;dir=1;layer=10;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(5,0,0)=642|dock_size(1,10,0)=36|
PowerSpectrumToolBar;;
layout2|name=FigureCanvasWxAgg;caption=;state=768;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=PowerSpectrumToolBar;caption=Plot toolbar;state=67382012;dir=1;layer=10;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(5,0,0)=642|dock_size(1,10,0)=36|
""")), # noqa
('feat',
textwrap.dedent("""
fsleyes.views.orthopanel.OrthoPanel,fsleyes.views.timeseriespanel.TimeSeriesPanel
layout2|name=OrthoPanel 1;caption=Ortho View 1;state=67377088;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=TimeSeriesPanel 2;caption=Time series 2;state=67377148;dir=3;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(5,0,0)=22|dock_size(3,0,0)=282|
fsleyes.controls.overlaylistpanel.OverlayListPanel,fsleyes.controls.overlaydisplaytoolbar.OverlayDisplayToolBar,fsleyes.controls.orthotoolbar.OrthoToolBar,fsleyes.controls.locationpanel.LocationPanel,fsleyes.plugins.controls.clusterpanel.ClusterPanel;syncLocation=True,syncOverlayOrder=True,movieRate=750,syncOverlayDisplay=True;layout=horizontal,showLabels=True,bgColour=#000000ff,fgColour=#ffffffff,showCursor=True,showZCanvas=True,cursorColour=#00ff00ff,showColourBar=False,showYCanvas=True,showXCanvas=True,colourBarLocation=top
layout2|name=Panel;caption=;state=768;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=OverlayListPanel;caption=Overlay list;state=67373052;dir=3;layer=2;row=0;pos=0;prop=87792;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=OverlayDisplayToolBar;caption=Display toolbar;state=67382012;dir=1;layer=10;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=OrthoToolBar;caption=Ortho view toolbar;state=67382012;dir=1;layer=10;row=1;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=LocationPanel;caption=Location;state=67373052;dir=3;layer=2;row=0;pos=1;prop=98544;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=ClusterPanel;caption=Cluster browser;state=67373052;dir=2;layer=1;row=0;pos=0;prop=114760;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(5,0,0)=10|dock_size(2,1,0)=566|dock_size(1,10,0)=51|dock_size(1,10,1)=36|dock_size(3,2,0)=130|
OverlayListPanel,TimeSeriesToolBar;;
layout2|name=FigureCanvasWxAgg;caption=;state=768;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=OverlayListPanel;caption=Overlay list;state=67373052;dir=4;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=TimeSeriesToolBar;caption=Time series toolbar;state=67382012;dir=1;layer=10;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(5,0,0)=642|dock_size(1,10,0)=36|dock_size(4,0,0)=206|
""")), # noqa
('ortho',
textwrap.dedent("""
fsleyes.views.orthopanel.OrthoPanel
layout2|name=OrthoPanel 1;caption=Ortho View 1;state=67376064;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(5,0,0)=22|
;syncLocation=True,syncOverlayOrder=True,syncOverlayDisplay=True;layout=horizontal,showLabels=True,bgColour=#000000ff,fgColour=#ffffffff,showCursor=True,showZCanvas=True,cursorColour=#00ff00ff,showColourBar=False,showYCanvas=True,showXCanvas=True,colourBarLocation=top
layout2|name=Panel;caption=;state=768;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(5,0,0)=22|
""")), # noqa
('3d',
textwrap.dedent("""
fsleyes.views.scene3dpanel.Scene3DPanel
layout2|name=Scene3DPanel 1;caption=3D View 1;state=67376064;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(5,0,0)=24|
;syncOverlayOrder=True,syncOverlayDisplay=True,syncLocation=True;showColourBar=False,showLegend=True,cursorColour=#00ff00ff,colourBarLocation=top,showCursor=True,colourBarLabelSide=top-left,bgColour=#9999c0ff,fgColour=#00ff00ff
layout2|name=Panel;caption=;state=768;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(5,0,0)=22|
""")), # noqa
('lightbox',
textwrap.dedent("""
fsleyes.views.lightboxpanel.LightBoxPanel
layout2|name=LightBoxPanel 1;caption=Lightbox View 1;state=67376064;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(5,0,0)=22|
;syncLocation=True,syncOverlayOrder=True,syncOverlayDisplay=True;bgColour=#000000ff,fgColour=#ffffffff,showCursor=True,cursorColour=#00ff00ff,highlightSlice=False,zax=2,showColourBar=False,showGridLines=False,colourBarLocation=top
layout2|name=Panel;caption=;state=768;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=-1;besth=-1;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(5,0,0)=10|
""")))) # noqa
| 49.185323 | 1,435 | 0.62157 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 25,281 | 0.639297 |
e87d88f77b09918a50134530b2845176e0ad517a | 6,079 | py | Python | annotation/application/document.py | seal-git/chABSA-dataset | a33b59e1101e451495735c69094d4f598d54f6f4 | [
"MIT"
] | 107 | 2018-04-10T09:13:57.000Z | 2022-03-31T15:21:20.000Z | annotation/application/document.py | seal-git/chABSA-dataset | a33b59e1101e451495735c69094d4f598d54f6f4 | [
"MIT"
] | 2 | 2018-10-27T05:47:47.000Z | 2022-02-25T10:06:43.000Z | annotation/application/document.py | seal-git/chABSA-dataset | a33b59e1101e451495735c69094d4f598d54f6f4 | [
"MIT"
] | 9 | 2018-04-11T00:59:15.000Z | 2022-02-25T11:50:33.000Z | import os
import shutil
import json
class Document():
def __init__(self,
doc_id, doc_text, edi_id, company_name,
body, topic):
self.doc_id = doc_id
self.doc_text = doc_text
self.edi_id = edi_id
self.company_name = company_name
self.body = body
self.topic = topic
def get_header(self):
return {
"document_id": self.document_id,
"document_name": self.document_name,
"doc_text": self.doc_text,
"edi_id": self.edi_id
}
@property
def document_id(self):
return self.edi_id
@property
def document_name(self):
return self.company_name
@classmethod
def load(cls, file_path):
if not os.path.isfile(file_path):
raise Exception("File {} does not found.".format(file_path))
with open(file_path, encoding="utf-8") as f:
doc = json.load(f)
doc_id = doc["doc_id"]
doc_text = doc["doc_text"]
edi_id = doc["edi_id"]
company_name = doc["company_name"]
body = doc["body"]
topic = doc["topic"]
return cls(doc_id, doc_text, edi_id, company_name, body, topic)
class Label():
def __init__(self, label, label_group="", display_name="", display_style=""):
self.label = label
self.label_group = label_group
self.display_name = display_name
self.display_style = display_style
def dumps(self):
return {
"label": self.label,
"label_group": self.label_group,
"display_name": self.display_name,
"display_style": self.display_style
}
class Annotation():
def __init__(self, target_id, target, label, label_target="", position=(), annotator="anonymous"):
self.target_id = int(target_id)
self.target = target
self.label = label
self.label_target = label_target
self.position = position
if len(self.position) > 0:
self.position = [int(i) for i in self.position]
self.annotator = annotator
def dumps(self):
a = {
"target_id": self.target_id,
"target": self.target,
"label": self.label,
"label_target": self.label_target,
"position": self.position,
"annotator": self.annotator
}
return a
@classmethod
def loads(cls, obj):
a = Annotation(
obj["target_id"],
obj["target"],
obj["label"],
obj["label_target"],
obj["position"] if "position" in obj else ()
)
if "annotator" in obj:
a.annotator = obj["annotator"]
return a
class AnnotationTask():
ANNOTATION_CLASS = Annotation
def __init__(self, document, annotations=()):
self.document = document
self.annotations = {} if len(annotations) == 0 else annotations
def get_targets(self):
raise Exception("Sub class have to specify texts for annotation")
def get_labels(self):
raise Exception("Sub class have to define label candidates")
def get_dataset(self):
dataset = {}
for target_id, target in self.get_targets():
a_s = []
if target_id in self.annotations:
a_s = [a.dumps() for a in self.annotations[target_id]]
dataset[target_id] = {
"target": target,
"annotations": a_s
}
return dataset
def save_annotations(self, target_dir, annotation_objs, annotator):
_dir = os.path.join(target_dir, self.document.document_id)
annotations = [self.ANNOTATION_CLASS.loads(a_obj)
for a_obj in annotation_objs]
if annotator:
for a in annotations:
a.annotator = annotator
if os.path.exists(_dir):
for f in os.listdir(_dir):
if f.startswith("ann__") and f.endswith("__{}.json".format(annotator)):
os.remove(os.path.join(_dir, f))
save_bucket = {}
for a in annotations:
key = (a.target_id, a.annotator)
if key not in save_bucket:
save_bucket[key] = []
save_bucket[key].append(a)
if len(save_bucket) > 0 and not os.path.exists(_dir):
os.mkdir(_dir)
for key in save_bucket:
file_name = self._make_annotation_file_name(*key)
body = {
"annotations": [a.dumps() for a in save_bucket[key]]
}
file_path = os.path.join(_dir, file_name)
with open(file_path, mode="w", encoding="utf-8") as f:
json.dump(body, f, ensure_ascii=False, indent=2)
def _make_annotation_file_name(self, target_id, annotator):
return "ann__{}__{}__{}.json".format(self.document.document_id, target_id, annotator)
@classmethod
def load(cls, target_dir, document, annotator=""):
annotations = {}
_dir = os.path.join(target_dir, document.document_id)
if os.path.exists(_dir):
for f in sorted(os.listdir(_dir)):
if not f.startswith("ann__"):
continue
if annotator and not f.endswith("__{}.json".format(annotator)):
continue
path = os.path.join(_dir, f)
with open(path, encoding="utf-8") as af:
annotation_objs = json.load(af)["annotations"]
a_list = [cls.ANNOTATION_CLASS.loads(a_obj) for a_obj in annotation_objs]
if len(a_list) > 0:
target_id = a_list[0].target_id
if target_id not in annotations:
annotations[target_id] = a_list
else:
annotations[target_id] += a_list
instance = cls(document, annotations)
return instance
| 32.335106 | 102 | 0.553216 | 6,031 | 0.992104 | 0 | 0 | 2,036 | 0.334924 | 0 | 0 | 557 | 0.091627 |