max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
notebooks/102-BDP-try-timeseries.py
zeou1/maggot_models
0
6620551
#%% import pandas as pd import numpy as np from graspy.embed import ClassicalMDS import seaborn as sns from sklearn.metrics import pairwise_distances data_loc = "maggot_models/data/external/17-08-26L6-allC-cl.csv" ts_df = pd.read_csv(data_loc, index_col=None) ts_mat = ts_df.values.T # %% [markdown] # # corr_mat = pairwise_distances(ts_mat, metric="correlation") # %% [markdown] # # sns.clustermap(corr_mat) # %% [markdown] # # from graspy.plot import pairplot mds = ClassicalMDS(dissimilarity="precomputed") embed = mds.fit_transform(corr_mat) pairplot(embed)
#%% import pandas as pd import numpy as np from graspy.embed import ClassicalMDS import seaborn as sns from sklearn.metrics import pairwise_distances data_loc = "maggot_models/data/external/17-08-26L6-allC-cl.csv" ts_df = pd.read_csv(data_loc, index_col=None) ts_mat = ts_df.values.T # %% [markdown] # # corr_mat = pairwise_distances(ts_mat, metric="correlation") # %% [markdown] # # sns.clustermap(corr_mat) # %% [markdown] # # from graspy.plot import pairplot mds = ClassicalMDS(dissimilarity="precomputed") embed = mds.fit_transform(corr_mat) pairplot(embed)
en
0.289781
#%% # %% [markdown] # # # %% [markdown] # # # %% [markdown] # #
2.316686
2
pychron/processing/analyses/view/regression_view.py
ASUPychron/pychron
31
6620552
# =============================================================================== # Copyright 2018 ross # # 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. # =============================================================================== from chaco.plot_containers import HPlotContainer from enable.component_editor import ComponentEditor from traits.api import HasTraits, Instance, Any from traitsui.api import View, UItem from pychron.core.helpers.formatting import format_percent_error, errorfmt from pychron.graph.stacked_graph import StackedGraph from pychron.graph.stacked_regression_graph import StackedRegressionGraph from pychron.graph.tools.regression_inspector import RegressionInspectorTool from pychron.pychron_constants import PLUSMINUS class AnalysisRegressionInspectorTool(RegressionInspectorTool): analysis = Any def assemble_lines(self): lines = super(AnalysisRegressionInspectorTool, self).assemble_lines() an = self.analysis a = an.age ef = errorfmt(a, an.age_err) ef_wo_j = errorfmt(a, an.age_err_wo_j) lines.insert(0, "Date={:0.4f} {}{} w/o_J={}".format(a, PLUSMINUS, ef, ef_wo_j)) return lines class AnalysisRegressionGraph(StackedRegressionGraph): analysis = Any def regression_inspector_factory(self, line): tool = AnalysisRegressionInspectorTool(component=line, analysis=self.analysis) return tool class RegressionView(HasTraits): name = "Regressions" container = Instance(HPlotContainer) analysis = Any def initialize(self, an): an.load_raw_data() self.analysis = an self.setup_graph(an) def setup_graph(self, an): container = HPlotContainer() container_dict = {"spacing": 5, "stack_order": "top_to_bottom"} sg = StackedGraph(container_dict=container_dict) bg = AnalysisRegressionGraph(container_dict=container_dict, analysis=an) ig = AnalysisRegressionGraph(container_dict=container_dict, analysis=an) isos = an.sorted_values(reverse=False) sisos = [iso for iso in isos if iso.sniff.offset_xs.shape[0]] for i, iso in enumerate(sisos): sniff = iso.sniff p = sg.new_plot(ytitle=iso.name, xtitle="Time (s)", title="Equilibration") sg.add_axis_tool(p, p.x_axis) sg.add_axis_tool(p, p.y_axis) sg.new_series(sniff.offset_xs, sniff.ys, marker="circle", type="scatter") sg.set_y_limits(pad="0.1", plotid=i) sg.set_x_limits(min_=0, max_=max(sniff.offset_xs) * 1.05, plotid=i) iisos = [iso for iso in isos if iso.offset_xs.shape[0]] baselines = [] for i, iso in enumerate(iisos): if iso.baseline.offset_xs.shape[0]: baselines.append(iso.baseline) p = ig.new_plot( ytitle="{}({})".format(iso.name, iso.detector), xtitle="Time (s)", title="Isotope", ) ig.add_axis_tool(p, p.x_axis) ig.add_axis_tool(p, p.y_axis) ig.new_series( iso.offset_xs, iso.ys, display_filter_bounds=True, filter_outliers_dict=iso.filter_outliers_dict, color="blue", type="scatter", fit=iso.efit, ) ig.set_regressor(iso.regressor, i) ig.set_y_limits(pad="0.1", plotid=i) ig.set_x_limits(min_=0, max_=max(iso.offset_xs) * 1.05, plotid=i) ig.refresh() ig.on_trait_change(self.handle_regression, "regression_results") for i, baseline in enumerate(baselines): p = bg.new_plot( ytitle=baseline.detector, xtitle="Time (s)", title="Baseline" ) bg.add_axis_tool(p, p.x_axis) bg.add_axis_tool(p, p.y_axis) bg.new_series( baseline.offset_xs, baseline.ys, filter_outliers_dict=baseline.filter_outliers_dict, display_filter_bounds=True, color="red", type="scatter", fit=baseline.efit, ) bg.set_regressor(baseline.regressor, i) bg.set_y_limits(pad="0.1", plotid=i) bg.set_x_limits(pad="0.025", plotid=i) bg.refresh() container.add(sg.plotcontainer) container.add(ig.plotcontainer) container.add(bg.plotcontainer) self.container = container def handle_regression(self, new): if new: for plot, regressor in new: for k, iso in self.analysis.isotopes.items(): yt = plot.y_axis.title if k == yt or "{}({})".format(iso.name, iso.detector) == yt: iso.set_fit(regressor.get_fit_dict()) break self.analysis.calculate_age(force=True) self.analysis.analysis_view.refresh() def traits_view(self): v = View( UItem("container", style="custom", editor=ComponentEditor()), resizable=True ) return v # ============= EOF =============================================
# =============================================================================== # Copyright 2018 ross # # 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. # =============================================================================== from chaco.plot_containers import HPlotContainer from enable.component_editor import ComponentEditor from traits.api import HasTraits, Instance, Any from traitsui.api import View, UItem from pychron.core.helpers.formatting import format_percent_error, errorfmt from pychron.graph.stacked_graph import StackedGraph from pychron.graph.stacked_regression_graph import StackedRegressionGraph from pychron.graph.tools.regression_inspector import RegressionInspectorTool from pychron.pychron_constants import PLUSMINUS class AnalysisRegressionInspectorTool(RegressionInspectorTool): analysis = Any def assemble_lines(self): lines = super(AnalysisRegressionInspectorTool, self).assemble_lines() an = self.analysis a = an.age ef = errorfmt(a, an.age_err) ef_wo_j = errorfmt(a, an.age_err_wo_j) lines.insert(0, "Date={:0.4f} {}{} w/o_J={}".format(a, PLUSMINUS, ef, ef_wo_j)) return lines class AnalysisRegressionGraph(StackedRegressionGraph): analysis = Any def regression_inspector_factory(self, line): tool = AnalysisRegressionInspectorTool(component=line, analysis=self.analysis) return tool class RegressionView(HasTraits): name = "Regressions" container = Instance(HPlotContainer) analysis = Any def initialize(self, an): an.load_raw_data() self.analysis = an self.setup_graph(an) def setup_graph(self, an): container = HPlotContainer() container_dict = {"spacing": 5, "stack_order": "top_to_bottom"} sg = StackedGraph(container_dict=container_dict) bg = AnalysisRegressionGraph(container_dict=container_dict, analysis=an) ig = AnalysisRegressionGraph(container_dict=container_dict, analysis=an) isos = an.sorted_values(reverse=False) sisos = [iso for iso in isos if iso.sniff.offset_xs.shape[0]] for i, iso in enumerate(sisos): sniff = iso.sniff p = sg.new_plot(ytitle=iso.name, xtitle="Time (s)", title="Equilibration") sg.add_axis_tool(p, p.x_axis) sg.add_axis_tool(p, p.y_axis) sg.new_series(sniff.offset_xs, sniff.ys, marker="circle", type="scatter") sg.set_y_limits(pad="0.1", plotid=i) sg.set_x_limits(min_=0, max_=max(sniff.offset_xs) * 1.05, plotid=i) iisos = [iso for iso in isos if iso.offset_xs.shape[0]] baselines = [] for i, iso in enumerate(iisos): if iso.baseline.offset_xs.shape[0]: baselines.append(iso.baseline) p = ig.new_plot( ytitle="{}({})".format(iso.name, iso.detector), xtitle="Time (s)", title="Isotope", ) ig.add_axis_tool(p, p.x_axis) ig.add_axis_tool(p, p.y_axis) ig.new_series( iso.offset_xs, iso.ys, display_filter_bounds=True, filter_outliers_dict=iso.filter_outliers_dict, color="blue", type="scatter", fit=iso.efit, ) ig.set_regressor(iso.regressor, i) ig.set_y_limits(pad="0.1", plotid=i) ig.set_x_limits(min_=0, max_=max(iso.offset_xs) * 1.05, plotid=i) ig.refresh() ig.on_trait_change(self.handle_regression, "regression_results") for i, baseline in enumerate(baselines): p = bg.new_plot( ytitle=baseline.detector, xtitle="Time (s)", title="Baseline" ) bg.add_axis_tool(p, p.x_axis) bg.add_axis_tool(p, p.y_axis) bg.new_series( baseline.offset_xs, baseline.ys, filter_outliers_dict=baseline.filter_outliers_dict, display_filter_bounds=True, color="red", type="scatter", fit=baseline.efit, ) bg.set_regressor(baseline.regressor, i) bg.set_y_limits(pad="0.1", plotid=i) bg.set_x_limits(pad="0.025", plotid=i) bg.refresh() container.add(sg.plotcontainer) container.add(ig.plotcontainer) container.add(bg.plotcontainer) self.container = container def handle_regression(self, new): if new: for plot, regressor in new: for k, iso in self.analysis.isotopes.items(): yt = plot.y_axis.title if k == yt or "{}({})".format(iso.name, iso.detector) == yt: iso.set_fit(regressor.get_fit_dict()) break self.analysis.calculate_age(force=True) self.analysis.analysis_view.refresh() def traits_view(self): v = View( UItem("container", style="custom", editor=ComponentEditor()), resizable=True ) return v # ============= EOF =============================================
en
0.748896
# =============================================================================== # Copyright 2018 ross # # 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. # =============================================================================== # ============= EOF =============================================
1.838742
2
src/connect4.py
ScrypticLabs/iWriter
0
6620553
<filename>src/connect4.py """ An interactive game that is short but fun. This game can be played several times without dedicating too much of your personal time. It doesn’t require very accurate eye tracking, as selecting what column to place the chip in only requires the x-coordinates. In general, the selection of the columns is based on gaze and dwell. """ from pygame import * from connect4Images import * from random import randint class connect4: def __init__(self, screen): "Initializes the class of connect4" self.screen = screen self.gameBoard = [['_', '_', '_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_', '_', '_']] self.currentTurn = 1 self.winner = "" self.backgroundValue = True self.countBlue = 0 self.countPurple = 0 self.connect4boardRect = Rect(350, 15, 1260, 840) self.cursor = 0 self.mb = 0 self.dwell_delay = 0 self.maxDelay = 100 def getActivity(self, gazePos, old_gazePos): """Gets the user activity of each piece""" if self.connect4boardRect.collidepoint(gazePos) or ((gazePos[1]-15)//140 < 6 and (gazePos[0]-350)//140 < 9): if self.dwell_delay < self.maxDelay: self.dwell_delay += 1 else: if self.dwell_delay > 0: self.dwell_delay -= 1 def performAction(self, gazePos, old_gazePos): """Sets clicked to True when there is user activity for a certain duration""" self.getActivity(gazePos, old_gazePos) if self.dwell_delay == self.maxDelay: self.mb = 1 self.cursor = gazePos self.dwell_delay = 0 else: self.mb = 0 def main(self, cursor, mb): "Call this in while loop to run all needed components of the game" if self.backgroundValue == True: self.screen.blit(background, (0, -400)) self.drawboard() self.backgroundValue = False if mb == 1: self.drawboard() self.gameplay(cursor, mb) self.checkwinner() self.gameover(cursor) def text(self, screen, text, size, color, location): "Used to display text on the screen" screen.blit(font.Font("Fonts/HelveticaNeue-Light.otf", size).render(str(text), True, color), location) def drawboard(self): "Draws the connect4 board and the chips on the screen" cover = Surface((1920, 1080), SRCALPHA) self.screen.blit(board, (350, 15)) for x in range(9): for y in range(6): if self.gameBoard[y][x] == "B": draw.circle(cover, (35, 107, 172, 230), (420+(x*140), 85+(y*140)), 60) elif self.gameBoard[y][x] == "P": draw.circle(cover, (123, 43, 157, 230), (420+(x*140), 85+(y*140)), 60) self.screen.blit(cover, (0, 0)) def gameplay(self, cursor, mb): "This function does the move for the artificial inteeligence and also display the user and artififcial intelligences move" if self.currentTurn == 1: clickX = (cursor[0]-350)//140 if self.currentTurn == 2: clickX = randint(0, 8) for y in range(0, 6): if self.gameBoard[y][clickX] != "_": break elif self.gameBoard[y][clickX] == "_": if self.currentTurn == 1: self.gameBoard[y][clickX] = "B" elif self.currentTurn == 2: self.gameBoard[y][clickX] = "P" self.gameBoard[y-1][clickX] = "_" self.drawboard() display.flip() for row in self.gameBoard: self.countBlue += row.count("B") self.countPurple += row.count("P") if self.currentTurn == 1: if (self.countBlue - self.countPurple) == 1: self.currentTurn = 2 elif self.currentTurn == 2: if (self.countPurple - self.countBlue) == 0: self.currentTurn = 1 self.countBlue = 0 self.countPurple = 0 def checkwinner(self): "Checks to see if any of the players have won. if yes which one" for y in range(6): for x in range(9): if self.gameBoard[y][x] != "_": if x < 6 and y < 3: if self.gameBoard[y][x] == self.gameBoard[y+1][x+1] == self.gameBoard[y+2][x+2] == self.gameBoard[y+3][y+3]: self.winner = self.gameBoard[y][x] if x < 6: if self.gameBoard[y][x] == self.gameBoard[y][x+1] == self.gameBoard[y][x+2] == self.gameBoard[y][x+3]: self.winner = self.gameBoard[y][x] if y < 3: if self.gameBoard[y][x] == self.gameBoard[y+1][x] == self.gameBoard[y+2][x] == self.gameBoard[y+3][x]: self.winner = self.gameBoard[y][x] def gameover(self, cursor): "Displays the gameover screen and the user gets to chose whether or not they want to play again" if self.winner != "": cover = Surface((1260, 840), SRCALPHA) draw.rect(cover, (0, 0, 0, 225), (0, 0, 1260, 840)) self.screen.blit(cover, (350, 15)) if self.winner == "P": self.text(self.screen, "Purple Won", 160, (255, 255, 255), (640, 30)) if self.winner == "B": self.text(self.screen, "Blue Won", 160, (255, 255, 255), (645, 30)) self.screen.blit(button, (810, 300)) self.text(self.screen, "Play Again", 60, (255, 255, 255), (850, 315)) againRect = Rect(825, 315, 320, 80) if againRect.collidepoint(cursor): connect4.__init__(self, self.screen)
<filename>src/connect4.py """ An interactive game that is short but fun. This game can be played several times without dedicating too much of your personal time. It doesn’t require very accurate eye tracking, as selecting what column to place the chip in only requires the x-coordinates. In general, the selection of the columns is based on gaze and dwell. """ from pygame import * from connect4Images import * from random import randint class connect4: def __init__(self, screen): "Initializes the class of connect4" self.screen = screen self.gameBoard = [['_', '_', '_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_', '_', '_']] self.currentTurn = 1 self.winner = "" self.backgroundValue = True self.countBlue = 0 self.countPurple = 0 self.connect4boardRect = Rect(350, 15, 1260, 840) self.cursor = 0 self.mb = 0 self.dwell_delay = 0 self.maxDelay = 100 def getActivity(self, gazePos, old_gazePos): """Gets the user activity of each piece""" if self.connect4boardRect.collidepoint(gazePos) or ((gazePos[1]-15)//140 < 6 and (gazePos[0]-350)//140 < 9): if self.dwell_delay < self.maxDelay: self.dwell_delay += 1 else: if self.dwell_delay > 0: self.dwell_delay -= 1 def performAction(self, gazePos, old_gazePos): """Sets clicked to True when there is user activity for a certain duration""" self.getActivity(gazePos, old_gazePos) if self.dwell_delay == self.maxDelay: self.mb = 1 self.cursor = gazePos self.dwell_delay = 0 else: self.mb = 0 def main(self, cursor, mb): "Call this in while loop to run all needed components of the game" if self.backgroundValue == True: self.screen.blit(background, (0, -400)) self.drawboard() self.backgroundValue = False if mb == 1: self.drawboard() self.gameplay(cursor, mb) self.checkwinner() self.gameover(cursor) def text(self, screen, text, size, color, location): "Used to display text on the screen" screen.blit(font.Font("Fonts/HelveticaNeue-Light.otf", size).render(str(text), True, color), location) def drawboard(self): "Draws the connect4 board and the chips on the screen" cover = Surface((1920, 1080), SRCALPHA) self.screen.blit(board, (350, 15)) for x in range(9): for y in range(6): if self.gameBoard[y][x] == "B": draw.circle(cover, (35, 107, 172, 230), (420+(x*140), 85+(y*140)), 60) elif self.gameBoard[y][x] == "P": draw.circle(cover, (123, 43, 157, 230), (420+(x*140), 85+(y*140)), 60) self.screen.blit(cover, (0, 0)) def gameplay(self, cursor, mb): "This function does the move for the artificial inteeligence and also display the user and artififcial intelligences move" if self.currentTurn == 1: clickX = (cursor[0]-350)//140 if self.currentTurn == 2: clickX = randint(0, 8) for y in range(0, 6): if self.gameBoard[y][clickX] != "_": break elif self.gameBoard[y][clickX] == "_": if self.currentTurn == 1: self.gameBoard[y][clickX] = "B" elif self.currentTurn == 2: self.gameBoard[y][clickX] = "P" self.gameBoard[y-1][clickX] = "_" self.drawboard() display.flip() for row in self.gameBoard: self.countBlue += row.count("B") self.countPurple += row.count("P") if self.currentTurn == 1: if (self.countBlue - self.countPurple) == 1: self.currentTurn = 2 elif self.currentTurn == 2: if (self.countPurple - self.countBlue) == 0: self.currentTurn = 1 self.countBlue = 0 self.countPurple = 0 def checkwinner(self): "Checks to see if any of the players have won. if yes which one" for y in range(6): for x in range(9): if self.gameBoard[y][x] != "_": if x < 6 and y < 3: if self.gameBoard[y][x] == self.gameBoard[y+1][x+1] == self.gameBoard[y+2][x+2] == self.gameBoard[y+3][y+3]: self.winner = self.gameBoard[y][x] if x < 6: if self.gameBoard[y][x] == self.gameBoard[y][x+1] == self.gameBoard[y][x+2] == self.gameBoard[y][x+3]: self.winner = self.gameBoard[y][x] if y < 3: if self.gameBoard[y][x] == self.gameBoard[y+1][x] == self.gameBoard[y+2][x] == self.gameBoard[y+3][x]: self.winner = self.gameBoard[y][x] def gameover(self, cursor): "Displays the gameover screen and the user gets to chose whether or not they want to play again" if self.winner != "": cover = Surface((1260, 840), SRCALPHA) draw.rect(cover, (0, 0, 0, 225), (0, 0, 1260, 840)) self.screen.blit(cover, (350, 15)) if self.winner == "P": self.text(self.screen, "Purple Won", 160, (255, 255, 255), (640, 30)) if self.winner == "B": self.text(self.screen, "Blue Won", 160, (255, 255, 255), (645, 30)) self.screen.blit(button, (810, 300)) self.text(self.screen, "Play Again", 60, (255, 255, 255), (850, 315)) againRect = Rect(825, 315, 320, 80) if againRect.collidepoint(cursor): connect4.__init__(self, self.screen)
en
0.96475
An interactive game that is short but fun. This game can be played several times without dedicating too much of your personal time. It doesn’t require very accurate eye tracking, as selecting what column to place the chip in only requires the x-coordinates. In general, the selection of the columns is based on gaze and dwell. Gets the user activity of each piece Sets clicked to True when there is user activity for a certain duration
3.576135
4
hummingbot/strategy/discovery/discovery_market_pair.py
TritumDigitalAssets/hummingbot
2
6620554
#!/usr/bin/env python from typing import ( NamedTuple, Awaitable ) import pandas as pd from hummingbot.market.market_base import MarketBase class DiscoveryMarketPair(NamedTuple): """ Specifies a pair of markets for discovery """ market_1: MarketBase market_1_fetch_market_info: Awaitable[pd.DataFrame] market_2: MarketBase market_2_fetch_market_info: Awaitable[pd.DataFrame] def __repr__(self) -> str: return f"DiscoveryMarketPair({self.market_1.name}, {self.market_2.name})"
#!/usr/bin/env python from typing import ( NamedTuple, Awaitable ) import pandas as pd from hummingbot.market.market_base import MarketBase class DiscoveryMarketPair(NamedTuple): """ Specifies a pair of markets for discovery """ market_1: MarketBase market_1_fetch_market_info: Awaitable[pd.DataFrame] market_2: MarketBase market_2_fetch_market_info: Awaitable[pd.DataFrame] def __repr__(self) -> str: return f"DiscoveryMarketPair({self.market_1.name}, {self.market_2.name})"
en
0.474411
#!/usr/bin/env python Specifies a pair of markets for discovery
2.725059
3
projecteuler/9.py
m00nb0w/oghma
0
6620555
<reponame>m00nb0w/oghma #!/bin/python3 import sys t = int(input().strip()) for a0 in range(t): n = int(input().strip()) res = -1 for a in range(1, n // 3 + 1): b = (n - (a * n) / (n - a)) / 2 if (int(b) == b): b = int(b) c = n - a - b if a < b and b < c: res = max(res, a * b * c) print(res)
#!/bin/python3 import sys t = int(input().strip()) for a0 in range(t): n = int(input().strip()) res = -1 for a in range(1, n // 3 + 1): b = (n - (a * n) / (n - a)) / 2 if (int(b) == b): b = int(b) c = n - a - b if a < b and b < c: res = max(res, a * b * c) print(res)
ru
0.16812
#!/bin/python3
2.895765
3
sk.py
zeroby0/lms-stalker
1
6620556
#!/usr/bin/env python from __future__ import print_function # https://github.com/zeroby0/lms-stalker # <NAME> import requests from bs4 import BeautifulSoup import warnings import datetime, time, os, json warnings.filterwarnings("ignore") class stlk: def pack_db(self): # too lazy to find python commands os.system("cat " + self.DB_FILE + " | python -mjson.tool > ./public/db.pack.json") os.system("cd ./public && zip db.pack.json.zip db.pack.json") # cd ing to avoid unpacking to folder os.system("cd ./public && tar -czf db.pack.json.tar.gz db.pack.json") # os.system("cp -r ./public/. /var/www/stalk/") # serving files with nginx def set_db(self): with open( self.DB_FILE, 'w') as f: json.dump( self.DB , f) def get_db(self): with open( self.DB_FILE ) as dbase_file: dbase = json.load(dbase_file) return dbase def create_db(self): if not os.path.exists( self.DB_FILE ): template = {} with open( self.DB_FILE, 'w') as f: json.dump(template, f) def __init__(self,username, password,DB_FILE = "./db.json"): self.username = username self.password = password self.DB_FILE = DB_FILE self.create_db() self.DB = self.get_db() def log_user(self, id): if not self.DB.has_key(id): self.DB[id] = {"time_array": []} self.DB[id]["time_array"].append( "{:%d %m, %Y, %H %M %S}".format(datetime.datetime.now()) ) def scan(self): payload = { 'username': self.username, 'password': self.password } self.DB["0nline"] = [{"Last checked at" : "{:%d %m, %Y, %H %M %S}".format(datetime.datetime.now()) }] with requests.Session() as s: p = s.post('https://lms.iiitb.ac.in/moodle/login/index.php', data=payload,verify=False) r = s.get('https://lms.iiitb.ac.in/moodle/my/',verify=False) soup=BeautifulSoup(r.text) g_data=soup.find_all("div",{"class":"user"}) print("\n[") for i in g_data: if i.text in [ "imt2015524 <NAME>"]: continue # Put your ID here print(" " + i.text + ",") self.log_user(i.text) self.DB["0nline"].append(i.text) self.set_db() # self.pack_db() # current_list[i.text] = datetime.datetime.now() # ,i.find_all("a")[0]['title'] // for time def stalk(self): while True: try: self.scan() print("]") self.pack_db() print("____________________________________________________"); time.sleep(60) except: print("Error occured, retrying") stk = stlk("Roll Number", "Password") stk.stalk()
#!/usr/bin/env python from __future__ import print_function # https://github.com/zeroby0/lms-stalker # <NAME> import requests from bs4 import BeautifulSoup import warnings import datetime, time, os, json warnings.filterwarnings("ignore") class stlk: def pack_db(self): # too lazy to find python commands os.system("cat " + self.DB_FILE + " | python -mjson.tool > ./public/db.pack.json") os.system("cd ./public && zip db.pack.json.zip db.pack.json") # cd ing to avoid unpacking to folder os.system("cd ./public && tar -czf db.pack.json.tar.gz db.pack.json") # os.system("cp -r ./public/. /var/www/stalk/") # serving files with nginx def set_db(self): with open( self.DB_FILE, 'w') as f: json.dump( self.DB , f) def get_db(self): with open( self.DB_FILE ) as dbase_file: dbase = json.load(dbase_file) return dbase def create_db(self): if not os.path.exists( self.DB_FILE ): template = {} with open( self.DB_FILE, 'w') as f: json.dump(template, f) def __init__(self,username, password,DB_FILE = "./db.json"): self.username = username self.password = password self.DB_FILE = DB_FILE self.create_db() self.DB = self.get_db() def log_user(self, id): if not self.DB.has_key(id): self.DB[id] = {"time_array": []} self.DB[id]["time_array"].append( "{:%d %m, %Y, %H %M %S}".format(datetime.datetime.now()) ) def scan(self): payload = { 'username': self.username, 'password': self.password } self.DB["0nline"] = [{"Last checked at" : "{:%d %m, %Y, %H %M %S}".format(datetime.datetime.now()) }] with requests.Session() as s: p = s.post('https://lms.iiitb.ac.in/moodle/login/index.php', data=payload,verify=False) r = s.get('https://lms.iiitb.ac.in/moodle/my/',verify=False) soup=BeautifulSoup(r.text) g_data=soup.find_all("div",{"class":"user"}) print("\n[") for i in g_data: if i.text in [ "imt2015524 <NAME>"]: continue # Put your ID here print(" " + i.text + ",") self.log_user(i.text) self.DB["0nline"].append(i.text) self.set_db() # self.pack_db() # current_list[i.text] = datetime.datetime.now() # ,i.find_all("a")[0]['title'] // for time def stalk(self): while True: try: self.scan() print("]") self.pack_db() print("____________________________________________________"); time.sleep(60) except: print("Error occured, retrying") stk = stlk("Roll Number", "Password") stk.stalk()
en
0.509616
#!/usr/bin/env python # https://github.com/zeroby0/lms-stalker # <NAME> # too lazy to find python commands # cd ing to avoid unpacking to folder # os.system("cp -r ./public/. /var/www/stalk/") # serving files with nginx # Put your ID here # self.pack_db() # current_list[i.text] = datetime.datetime.now() # ,i.find_all("a")[0]['title'] // for time
2.337272
2
edmunds/gae/gaetestcase.py
LowieHuyghe/edmunds-python
4
6620557
from edmunds.foundation.testing.testcase import TestCase import sys def gae_can_run(): return sys.version_info < (3, 0) if gae_can_run(): from google.appengine.ext import testbed class GaeTestCase(TestCase): @staticmethod def can_run(): """ Check if can run test :return: Boolean """ return gae_can_run() def set_up(self): """ Set up the test case """ if not self.can_run(): self.skip("Google Cloud SDK doesn't run in Python 3+") self.testbed = testbed.Testbed() self.testbed.activate() super(GaeTestCase, self).set_up() def tear_down(self): """ Tear down the test case """ super(GaeTestCase, self).tear_down() try: self.testbed.deactivate() except testbed.NotActivatedError: pass
from edmunds.foundation.testing.testcase import TestCase import sys def gae_can_run(): return sys.version_info < (3, 0) if gae_can_run(): from google.appengine.ext import testbed class GaeTestCase(TestCase): @staticmethod def can_run(): """ Check if can run test :return: Boolean """ return gae_can_run() def set_up(self): """ Set up the test case """ if not self.can_run(): self.skip("Google Cloud SDK doesn't run in Python 3+") self.testbed = testbed.Testbed() self.testbed.activate() super(GaeTestCase, self).set_up() def tear_down(self): """ Tear down the test case """ super(GaeTestCase, self).tear_down() try: self.testbed.deactivate() except testbed.NotActivatedError: pass
en
0.383316
Check if can run test :return: Boolean Set up the test case Tear down the test case
2.420376
2
corehq/apps/app_manager/translations.py
bglar/commcare-hq
1
6620558
from lxml import etree import copy from openpyxl.shared.exc import InvalidFileException from corehq.apps.app_manager.exceptions import ( FormNotFoundException, ModuleNotFoundException, ) from corehq.apps.app_manager.util import save_xform from corehq.apps.app_manager.xform import namespaces, WrappedNode from dimagi.utils.excel import WorkbookJSONReader, HeaderValueError from django.contrib import messages from django.utils.translation import ugettext as _ def process_bulk_app_translation_upload(app, f): """ Process the bulk upload file for the given app. We return these message tuples instead of calling them now to allow this function to be used independently of request objects. :param app: :param f: :return: Returns a list of message tuples. The first item in each tuple is a function like django.contrib.messages.error, and the second is a string. """ def none_or_unicode(val): return unicode(val) if val is not None else val msgs = [] headers = expected_bulk_app_sheet_headers(app) expected_sheets = {h[0]: h[1] for h in headers} processed_sheets = set() try: workbook = WorkbookJSONReader(f) except (HeaderValueError, InvalidFileException) as e: msgs.append( (messages.error, _("App Translation Failed! " + str(e))) ) return msgs for sheet in workbook.worksheets: # sheet.__iter__ can only be called once, so cache the result rows = [row for row in sheet] # Convert every key and value to a string for i in xrange(len(rows)): rows[i] = {unicode(k): none_or_unicode(v) for k, v in rows[i].iteritems()} # CHECK FOR REPEAT SHEET if sheet.worksheet.title in processed_sheets: msgs.append(( messages.error, 'Sheet "%s" was repeated. Only the first ' + 'occurrence has been processed' % sheet.worksheet.title )) continue # CHECK FOR BAD SHEET NAME expected_columns = expected_sheets.get(sheet.worksheet.title, None) if expected_columns is None: msgs.append(( messages.error, 'Skipping sheet "%s", did not recognize title' % sheet.worksheet.title )) continue # CHECK FOR MISSING KEY COLUMN if sheet.worksheet.title == "Modules and Forms": # Several columns on this sheet could be used to uniquely identify # rows. Using sheet_name for now, but unique_id could also be used. if expected_columns[1] not in sheet.headers: msgs.append(( messages.error, 'Skipping sheet "%s", could not find "%s" column' % (sheet.worksheet.title, expected_columns[1]) )) continue elif expected_columns[0] == "case_property": # It's a module sheet if (expected_columns[0] not in sheet.headers or expected_columns[1] not in sheet.headers): msgs.append(( messages.error, 'Skipping sheet "%s", could not find case_property' ' or list_or_detail column.' % sheet.worksheet.title )) continue else: # It's a form sheet if expected_columns[0] not in sheet.headers: msgs.append(( messages.error, 'Skipping sheet "%s", could not find label column' % sheet.worksheet.title )) continue processed_sheets.add(sheet.worksheet.title) # CHECK FOR MISSING COLUMNS missing_cols = set(expected_columns) - set(sheet.headers) if len(missing_cols) > 0: msgs.append(( messages.warning, 'Sheet "%s" has less columns than expected. ' 'Sheet will be processed but the following' ' translations will be unchanged: %s' % (sheet.worksheet.title, " ,".join(missing_cols)) )) # CHECK FOR EXTRA COLUMNS extra_cols = set(sheet.headers) - set(expected_columns) if len(extra_cols) > 0: msgs.append(( messages.warning, 'Sheet "%s" has unrecognized columns. ' 'Sheet will be processed but ignoring the following columns: %s' % (sheet.worksheet.title, " ,".join(extra_cols)) )) # NOTE: At the moment there is no missing row detection. # This could be added if we want though # (it is not that bad if a user leaves out a row) if sheet.worksheet.title == "Modules_and_forms": # It's the first sheet ms = process_modules_and_forms_sheet(rows, app) msgs.extend(ms) elif sheet.headers[0] == "case_property": # It's a module sheet ms = update_case_list_translations(sheet, rows, app) msgs.extend(ms) else: # It's a form sheet ms = update_form_translations(sheet, rows, missing_cols, app) msgs.extend(ms) msgs.append( (messages.success, _("App Translations Updated!")) ) return msgs def expected_bulk_app_sheet_headers(app): ''' Returns lists representing the expected structure of bulk app translation excel file uploads. The list will be in the form: [ ["sheetname", ["column name1", "column name 2"]], ["sheet2 name", [...]], ... ] :param app: :return: ''' languages_list = ['default_' + l for l in app.langs] audio_lang_list = ['audio_' + l for l in app.langs] image_lang_list = ['image_' + l for l in app.langs] video_lang_list = ['video_' + l for l in app.langs] headers = [] # Add headers for the first sheet headers.append( ["Modules_and_forms", ['Type', 'sheet_name'] + languages_list + ['label_for_cases_%s' % l for l in app.langs] + ['icon_filepath', 'audio_filepath', 'unique_id']] ) for mod_index, module in enumerate(app.get_modules()): module_string = "module" + str(mod_index + 1) headers.append([module_string, ['case_property', 'list_or_detail'] + languages_list]) for form_index, form in enumerate(module.get_forms()): form_string = module_string + "_form" + str(form_index + 1) headers.append([ form_string, ["label"] + languages_list + audio_lang_list + image_lang_list + video_lang_list ]) return headers def process_modules_and_forms_sheet(rows, app): """ Modify the translations and media references for the modules and forms in the given app as per the data provided in rows. This does not save the changes to the database. :param rows: :param app: :return: Returns a list of message tuples. The first item in each tuple is a function like django.contrib.messages.error, and the second is a string. """ msgs = [] for row in rows: identifying_text = row.get('sheet_name', '').split('_') if len(identifying_text) not in (1, 2): msgs.append(( messages.error, 'Invalid sheet_name "%s", skipping row.' % row.get( 'sheet_name', '' ) )) continue module_index = int(identifying_text[0].replace("module", "")) - 1 try: document = app.get_module(module_index) except ModuleNotFoundException: msgs.append(( messages.error, 'Invalid module in row "%s", skipping row.' % row.get( 'sheet_name' ) )) continue if len(identifying_text) == 2: form_index = int(identifying_text[1].replace("form", "")) - 1 try: document = document.get_form(form_index) except FormNotFoundException: msgs.append(( messages.error, 'Invalid form in row "%s", skipping row.' % row.get( 'sheet_name' ) )) continue for lang in app.langs: translation = row['default_%s' % lang] if translation: document.name[lang] = translation else: if lang in document.name: del document.name[lang] if (has_at_least_one_translation(row, 'label_for_cases', app.langs) and hasattr(document, 'case_label')): for lang in app.langs: translation = row['label_for_cases_%s' % lang] if translation: document.case_label[lang] = translation else: if lang in document.case_label: del document.case_label[lang] image = row.get('icon_filepath', None) audio = row.get('audio_filepath', None) if image == '': image = None if audio == '': audio = None document.media_image = image document.media_audio = audio return msgs def update_form_translations(sheet, rows, missing_cols, app): """ Modify the translations of a form given a sheet of translation data. This does not save the changes to the DB. :param sheet: a WorksheetJSONReader :param rows: The rows of the sheet (we can't get this from the sheet because sheet.__iter__ can only be called once) :param missing_cols: :param app: :return: Returns a list of message tuples. The first item in each tuple is a function like django.contrib.messages.error, and the second is a string. """ msgs = [] mod_text, form_text = sheet.worksheet.title.split("_") module_index = int(mod_text.replace("module", "")) - 1 form_index = int(form_text.replace("form", "")) - 1 form = app.get_module(module_index).get_form(form_index) if form.source: xform = form.wrapped_xform() else: # This Form doesn't have an xform yet. It is empty. # Tell the user this? return msgs itext = xform.itext_node assert(itext.exists()) # Make language nodes for each language if they don't yet exist # # Currently operating under the assumption that every xForm has at least # one translation element, that each translation element has a text node # for each question and that each text node has a value node under it template_translation_el = None # Get a translation element to be used as a template for new elements for lang in app.langs: trans_el = itext.find("./{f}translation[@lang='%s']" % lang) if trans_el.exists(): template_translation_el = trans_el assert(template_translation_el is not None) # Add missing translation elements for lang in app.langs: trans_el = itext.find("./{f}translation[@lang='%s']" % lang) if not trans_el.exists(): new_trans_el = copy.deepcopy(template_translation_el.xml) new_trans_el.set('lang', lang) if lang != app.langs[0]: # If the language isn't the default language new_trans_el.attrib.pop('default', None) else: new_trans_el.set('default', '') itext.xml.append(new_trans_el) # Update the translations for lang in app.langs: translation_node = itext.find("./{f}translation[@lang='%s']" % lang) assert(translation_node.exists()) for row in rows: label_id = row['label'] text_node = translation_node.find("./{f}text[@id='%s']" % label_id) if not text_node.exists(): msgs.append(( messages.warning, "Unrecognized translation label {0} in sheet {1}. That row" " has been skipped". format(label_id, sheet.worksheet.title) )) continue # Add or remove translations for trans_type in ['default', 'audio', 'image', 'video']: if trans_type == 'default': attributes = None value_node = next( n for n in text_node.findall("./{f}value") if 'form' not in n.attrib ) else: attributes = {'form': trans_type} value_node = text_node.find( "./{f}value[@form='%s']" % trans_type ) col_key = get_col_key(trans_type, lang) new_translation = row[col_key] if not new_translation and col_key not in missing_cols: # If the cell corresponding to the label for this question # in this language is empty, fall back to another language for l in app.langs: fallback = row[get_col_key(trans_type, l)] if fallback: new_translation = fallback break if new_translation: # Create the node if it does not already exist if not value_node.exists(): e = etree.Element( "{f}value".format(**namespaces), attributes ) text_node.xml.append(e) value_node = WrappedNode(e) # Update the translation value_node.xml.text = new_translation else: # Remove the node if it already exists if value_node.exists(): value_node.xml.getparent().remove(value_node.xml) save_xform(app, form, etree.tostring(xform.xml, encoding="unicode")) return msgs def update_case_list_translations(sheet, rows, app): """ Modify the translations of a module case list and detail display properties given a sheet of translation data. The properties in the sheet must be in the exact same order that they appear in the bulk app translation download. This function does not save the modified app to the database. :param sheet: :param rows: The rows of the sheet (we can't get this from the sheet because sheet.__iter__ can only be called once) :param app: :return: Returns a list of message tuples. The first item in each tuple is a function like django.contrib.messages.error, and the second is a string. """ # The list might contain DetailColumn instances in them that have exactly # the same attributes (but are in different positions). Therefore we must # match sheet rows to DetailColumns by position. msgs = [] module_index = int(sheet.worksheet.title.replace("module", "")) - 1 module = app.get_module(module_index) # It is easier to process the translations if mapping rows are nested under # their respective DetailColumns condensed_rows = [] i = 0 while i < len(rows): if rows[i]['case_property'].endswith(" (ID Mapping Text)"): # Cut off the id mapping text rows[i]['case_property'] = rows[i]['case_property'].split(" ")[0] # Construct a list of mapping rows mappings = [] j = 1 while (i + j < len(rows) and rows[i + j]['case_property'].endswith(" (ID Mapping Value)")): # Cut off the id mapping value part rows[i + j]['case_property'] = \ rows[i + j]['case_property'].split(" ")[0] mappings.append(rows[i + j]) j += 1 rows[i]['mappings'] = mappings condensed_rows.append(rows[i]) i += j else: condensed_rows.append(rows[i]) i += 1 list_rows = [ row for row in condensed_rows if row['list_or_detail'] == 'list' ] detail_rows = [ row for row in condensed_rows if row['list_or_detail'] == 'detail' ] short_details = list(module.case_details.short.get_columns()) long_details = list(module.case_details.long.get_columns()) # Check length of lists for expected_list, received_list, word in [ (short_details, list_rows, "list"), (long_details, detail_rows, "detail") ]: if len(expected_list) != len(received_list): msgs.append(( messages.error, "Expected {0} case {3} properties in sheet {2}, found {1}. " "No case list or detail properties for sheet {2} were " "updated".format( len(expected_list), len(received_list), sheet.worksheet.title, word ) )) if msgs: return msgs # Update the translations for row, detail in \ zip(list_rows, short_details) + zip(detail_rows, long_details): # Check that names match (user is not allowed to change property in the # upload). Mismatched names indicate the user probably botched the sheet. if row.get('case_property', None) != detail.field: msgs.append(( messages.error, 'A row in sheet {sheet} has an unexpected value of "{field}" ' 'in the case_property column. Case properties must appear in ' 'the same order as they do in the bulk app translation ' 'download. No translations updated for this row.'.format( sheet=sheet.worksheet.title, field=row.get('case_property', "") ) )) continue # The logic for updating a mapping and updating a MappingItem and a # DetailColumn is almost the same. So, we smush the two together. for index, translation_row in enumerate([row] + row.get("mappings", [])): ok_to_delete_translations = has_at_least_one_translation( translation_row, 'default', app.langs) if ok_to_delete_translations: for lang in app.langs: translation = translation_row['default_%s' % lang] if index == 0: # For DetailColumns language_dict = detail.header else: # For MappingItems language_dict = detail['enum'][index - 1].value if translation: language_dict[lang] = translation else: if lang in language_dict: del language_dict[lang] else: msgs.append(( messages.error, "You must provide at least one translation" + " of the case property '%s'" % translation_row['case_property'] + " (ID Mapping Value)" if index != 0 else "" )) return msgs def has_at_least_one_translation(row, prefix, langs): """ Returns true if the given row has at least one translation. >>> has_at_least_one_translation( {'default_en': 'Name', 'case_property': 'name'}, 'default', ['en', 'fra'] ) true >>> has_at_least_one_translation( {'case_property': 'name'}, 'default', ['en', 'fra'] ) false :param row: :param prefix: :param langs: :return: """ return bool(filter(None, [row[prefix + '_' + l] for l in langs])) def get_col_key(translation_type, language): ''' Returns the name of the column in the bulk app translation spreadsheet given the translation type and language :param translation_type: What is being translated, i.e. 'default' or 'image' :param language: :return: ''' return "%s_%s" % (translation_type, language)
from lxml import etree import copy from openpyxl.shared.exc import InvalidFileException from corehq.apps.app_manager.exceptions import ( FormNotFoundException, ModuleNotFoundException, ) from corehq.apps.app_manager.util import save_xform from corehq.apps.app_manager.xform import namespaces, WrappedNode from dimagi.utils.excel import WorkbookJSONReader, HeaderValueError from django.contrib import messages from django.utils.translation import ugettext as _ def process_bulk_app_translation_upload(app, f): """ Process the bulk upload file for the given app. We return these message tuples instead of calling them now to allow this function to be used independently of request objects. :param app: :param f: :return: Returns a list of message tuples. The first item in each tuple is a function like django.contrib.messages.error, and the second is a string. """ def none_or_unicode(val): return unicode(val) if val is not None else val msgs = [] headers = expected_bulk_app_sheet_headers(app) expected_sheets = {h[0]: h[1] for h in headers} processed_sheets = set() try: workbook = WorkbookJSONReader(f) except (HeaderValueError, InvalidFileException) as e: msgs.append( (messages.error, _("App Translation Failed! " + str(e))) ) return msgs for sheet in workbook.worksheets: # sheet.__iter__ can only be called once, so cache the result rows = [row for row in sheet] # Convert every key and value to a string for i in xrange(len(rows)): rows[i] = {unicode(k): none_or_unicode(v) for k, v in rows[i].iteritems()} # CHECK FOR REPEAT SHEET if sheet.worksheet.title in processed_sheets: msgs.append(( messages.error, 'Sheet "%s" was repeated. Only the first ' + 'occurrence has been processed' % sheet.worksheet.title )) continue # CHECK FOR BAD SHEET NAME expected_columns = expected_sheets.get(sheet.worksheet.title, None) if expected_columns is None: msgs.append(( messages.error, 'Skipping sheet "%s", did not recognize title' % sheet.worksheet.title )) continue # CHECK FOR MISSING KEY COLUMN if sheet.worksheet.title == "Modules and Forms": # Several columns on this sheet could be used to uniquely identify # rows. Using sheet_name for now, but unique_id could also be used. if expected_columns[1] not in sheet.headers: msgs.append(( messages.error, 'Skipping sheet "%s", could not find "%s" column' % (sheet.worksheet.title, expected_columns[1]) )) continue elif expected_columns[0] == "case_property": # It's a module sheet if (expected_columns[0] not in sheet.headers or expected_columns[1] not in sheet.headers): msgs.append(( messages.error, 'Skipping sheet "%s", could not find case_property' ' or list_or_detail column.' % sheet.worksheet.title )) continue else: # It's a form sheet if expected_columns[0] not in sheet.headers: msgs.append(( messages.error, 'Skipping sheet "%s", could not find label column' % sheet.worksheet.title )) continue processed_sheets.add(sheet.worksheet.title) # CHECK FOR MISSING COLUMNS missing_cols = set(expected_columns) - set(sheet.headers) if len(missing_cols) > 0: msgs.append(( messages.warning, 'Sheet "%s" has less columns than expected. ' 'Sheet will be processed but the following' ' translations will be unchanged: %s' % (sheet.worksheet.title, " ,".join(missing_cols)) )) # CHECK FOR EXTRA COLUMNS extra_cols = set(sheet.headers) - set(expected_columns) if len(extra_cols) > 0: msgs.append(( messages.warning, 'Sheet "%s" has unrecognized columns. ' 'Sheet will be processed but ignoring the following columns: %s' % (sheet.worksheet.title, " ,".join(extra_cols)) )) # NOTE: At the moment there is no missing row detection. # This could be added if we want though # (it is not that bad if a user leaves out a row) if sheet.worksheet.title == "Modules_and_forms": # It's the first sheet ms = process_modules_and_forms_sheet(rows, app) msgs.extend(ms) elif sheet.headers[0] == "case_property": # It's a module sheet ms = update_case_list_translations(sheet, rows, app) msgs.extend(ms) else: # It's a form sheet ms = update_form_translations(sheet, rows, missing_cols, app) msgs.extend(ms) msgs.append( (messages.success, _("App Translations Updated!")) ) return msgs def expected_bulk_app_sheet_headers(app): ''' Returns lists representing the expected structure of bulk app translation excel file uploads. The list will be in the form: [ ["sheetname", ["column name1", "column name 2"]], ["sheet2 name", [...]], ... ] :param app: :return: ''' languages_list = ['default_' + l for l in app.langs] audio_lang_list = ['audio_' + l for l in app.langs] image_lang_list = ['image_' + l for l in app.langs] video_lang_list = ['video_' + l for l in app.langs] headers = [] # Add headers for the first sheet headers.append( ["Modules_and_forms", ['Type', 'sheet_name'] + languages_list + ['label_for_cases_%s' % l for l in app.langs] + ['icon_filepath', 'audio_filepath', 'unique_id']] ) for mod_index, module in enumerate(app.get_modules()): module_string = "module" + str(mod_index + 1) headers.append([module_string, ['case_property', 'list_or_detail'] + languages_list]) for form_index, form in enumerate(module.get_forms()): form_string = module_string + "_form" + str(form_index + 1) headers.append([ form_string, ["label"] + languages_list + audio_lang_list + image_lang_list + video_lang_list ]) return headers def process_modules_and_forms_sheet(rows, app): """ Modify the translations and media references for the modules and forms in the given app as per the data provided in rows. This does not save the changes to the database. :param rows: :param app: :return: Returns a list of message tuples. The first item in each tuple is a function like django.contrib.messages.error, and the second is a string. """ msgs = [] for row in rows: identifying_text = row.get('sheet_name', '').split('_') if len(identifying_text) not in (1, 2): msgs.append(( messages.error, 'Invalid sheet_name "%s", skipping row.' % row.get( 'sheet_name', '' ) )) continue module_index = int(identifying_text[0].replace("module", "")) - 1 try: document = app.get_module(module_index) except ModuleNotFoundException: msgs.append(( messages.error, 'Invalid module in row "%s", skipping row.' % row.get( 'sheet_name' ) )) continue if len(identifying_text) == 2: form_index = int(identifying_text[1].replace("form", "")) - 1 try: document = document.get_form(form_index) except FormNotFoundException: msgs.append(( messages.error, 'Invalid form in row "%s", skipping row.' % row.get( 'sheet_name' ) )) continue for lang in app.langs: translation = row['default_%s' % lang] if translation: document.name[lang] = translation else: if lang in document.name: del document.name[lang] if (has_at_least_one_translation(row, 'label_for_cases', app.langs) and hasattr(document, 'case_label')): for lang in app.langs: translation = row['label_for_cases_%s' % lang] if translation: document.case_label[lang] = translation else: if lang in document.case_label: del document.case_label[lang] image = row.get('icon_filepath', None) audio = row.get('audio_filepath', None) if image == '': image = None if audio == '': audio = None document.media_image = image document.media_audio = audio return msgs def update_form_translations(sheet, rows, missing_cols, app): """ Modify the translations of a form given a sheet of translation data. This does not save the changes to the DB. :param sheet: a WorksheetJSONReader :param rows: The rows of the sheet (we can't get this from the sheet because sheet.__iter__ can only be called once) :param missing_cols: :param app: :return: Returns a list of message tuples. The first item in each tuple is a function like django.contrib.messages.error, and the second is a string. """ msgs = [] mod_text, form_text = sheet.worksheet.title.split("_") module_index = int(mod_text.replace("module", "")) - 1 form_index = int(form_text.replace("form", "")) - 1 form = app.get_module(module_index).get_form(form_index) if form.source: xform = form.wrapped_xform() else: # This Form doesn't have an xform yet. It is empty. # Tell the user this? return msgs itext = xform.itext_node assert(itext.exists()) # Make language nodes for each language if they don't yet exist # # Currently operating under the assumption that every xForm has at least # one translation element, that each translation element has a text node # for each question and that each text node has a value node under it template_translation_el = None # Get a translation element to be used as a template for new elements for lang in app.langs: trans_el = itext.find("./{f}translation[@lang='%s']" % lang) if trans_el.exists(): template_translation_el = trans_el assert(template_translation_el is not None) # Add missing translation elements for lang in app.langs: trans_el = itext.find("./{f}translation[@lang='%s']" % lang) if not trans_el.exists(): new_trans_el = copy.deepcopy(template_translation_el.xml) new_trans_el.set('lang', lang) if lang != app.langs[0]: # If the language isn't the default language new_trans_el.attrib.pop('default', None) else: new_trans_el.set('default', '') itext.xml.append(new_trans_el) # Update the translations for lang in app.langs: translation_node = itext.find("./{f}translation[@lang='%s']" % lang) assert(translation_node.exists()) for row in rows: label_id = row['label'] text_node = translation_node.find("./{f}text[@id='%s']" % label_id) if not text_node.exists(): msgs.append(( messages.warning, "Unrecognized translation label {0} in sheet {1}. That row" " has been skipped". format(label_id, sheet.worksheet.title) )) continue # Add or remove translations for trans_type in ['default', 'audio', 'image', 'video']: if trans_type == 'default': attributes = None value_node = next( n for n in text_node.findall("./{f}value") if 'form' not in n.attrib ) else: attributes = {'form': trans_type} value_node = text_node.find( "./{f}value[@form='%s']" % trans_type ) col_key = get_col_key(trans_type, lang) new_translation = row[col_key] if not new_translation and col_key not in missing_cols: # If the cell corresponding to the label for this question # in this language is empty, fall back to another language for l in app.langs: fallback = row[get_col_key(trans_type, l)] if fallback: new_translation = fallback break if new_translation: # Create the node if it does not already exist if not value_node.exists(): e = etree.Element( "{f}value".format(**namespaces), attributes ) text_node.xml.append(e) value_node = WrappedNode(e) # Update the translation value_node.xml.text = new_translation else: # Remove the node if it already exists if value_node.exists(): value_node.xml.getparent().remove(value_node.xml) save_xform(app, form, etree.tostring(xform.xml, encoding="unicode")) return msgs def update_case_list_translations(sheet, rows, app): """ Modify the translations of a module case list and detail display properties given a sheet of translation data. The properties in the sheet must be in the exact same order that they appear in the bulk app translation download. This function does not save the modified app to the database. :param sheet: :param rows: The rows of the sheet (we can't get this from the sheet because sheet.__iter__ can only be called once) :param app: :return: Returns a list of message tuples. The first item in each tuple is a function like django.contrib.messages.error, and the second is a string. """ # The list might contain DetailColumn instances in them that have exactly # the same attributes (but are in different positions). Therefore we must # match sheet rows to DetailColumns by position. msgs = [] module_index = int(sheet.worksheet.title.replace("module", "")) - 1 module = app.get_module(module_index) # It is easier to process the translations if mapping rows are nested under # their respective DetailColumns condensed_rows = [] i = 0 while i < len(rows): if rows[i]['case_property'].endswith(" (ID Mapping Text)"): # Cut off the id mapping text rows[i]['case_property'] = rows[i]['case_property'].split(" ")[0] # Construct a list of mapping rows mappings = [] j = 1 while (i + j < len(rows) and rows[i + j]['case_property'].endswith(" (ID Mapping Value)")): # Cut off the id mapping value part rows[i + j]['case_property'] = \ rows[i + j]['case_property'].split(" ")[0] mappings.append(rows[i + j]) j += 1 rows[i]['mappings'] = mappings condensed_rows.append(rows[i]) i += j else: condensed_rows.append(rows[i]) i += 1 list_rows = [ row for row in condensed_rows if row['list_or_detail'] == 'list' ] detail_rows = [ row for row in condensed_rows if row['list_or_detail'] == 'detail' ] short_details = list(module.case_details.short.get_columns()) long_details = list(module.case_details.long.get_columns()) # Check length of lists for expected_list, received_list, word in [ (short_details, list_rows, "list"), (long_details, detail_rows, "detail") ]: if len(expected_list) != len(received_list): msgs.append(( messages.error, "Expected {0} case {3} properties in sheet {2}, found {1}. " "No case list or detail properties for sheet {2} were " "updated".format( len(expected_list), len(received_list), sheet.worksheet.title, word ) )) if msgs: return msgs # Update the translations for row, detail in \ zip(list_rows, short_details) + zip(detail_rows, long_details): # Check that names match (user is not allowed to change property in the # upload). Mismatched names indicate the user probably botched the sheet. if row.get('case_property', None) != detail.field: msgs.append(( messages.error, 'A row in sheet {sheet} has an unexpected value of "{field}" ' 'in the case_property column. Case properties must appear in ' 'the same order as they do in the bulk app translation ' 'download. No translations updated for this row.'.format( sheet=sheet.worksheet.title, field=row.get('case_property', "") ) )) continue # The logic for updating a mapping and updating a MappingItem and a # DetailColumn is almost the same. So, we smush the two together. for index, translation_row in enumerate([row] + row.get("mappings", [])): ok_to_delete_translations = has_at_least_one_translation( translation_row, 'default', app.langs) if ok_to_delete_translations: for lang in app.langs: translation = translation_row['default_%s' % lang] if index == 0: # For DetailColumns language_dict = detail.header else: # For MappingItems language_dict = detail['enum'][index - 1].value if translation: language_dict[lang] = translation else: if lang in language_dict: del language_dict[lang] else: msgs.append(( messages.error, "You must provide at least one translation" + " of the case property '%s'" % translation_row['case_property'] + " (ID Mapping Value)" if index != 0 else "" )) return msgs def has_at_least_one_translation(row, prefix, langs): """ Returns true if the given row has at least one translation. >>> has_at_least_one_translation( {'default_en': 'Name', 'case_property': 'name'}, 'default', ['en', 'fra'] ) true >>> has_at_least_one_translation( {'case_property': 'name'}, 'default', ['en', 'fra'] ) false :param row: :param prefix: :param langs: :return: """ return bool(filter(None, [row[prefix + '_' + l] for l in langs])) def get_col_key(translation_type, language): ''' Returns the name of the column in the bulk app translation spreadsheet given the translation type and language :param translation_type: What is being translated, i.e. 'default' or 'image' :param language: :return: ''' return "%s_%s" % (translation_type, language)
en
0.796781
Process the bulk upload file for the given app. We return these message tuples instead of calling them now to allow this function to be used independently of request objects. :param app: :param f: :return: Returns a list of message tuples. The first item in each tuple is a function like django.contrib.messages.error, and the second is a string. # sheet.__iter__ can only be called once, so cache the result # Convert every key and value to a string # CHECK FOR REPEAT SHEET # CHECK FOR BAD SHEET NAME # CHECK FOR MISSING KEY COLUMN # Several columns on this sheet could be used to uniquely identify # rows. Using sheet_name for now, but unique_id could also be used. # It's a module sheet # It's a form sheet # CHECK FOR MISSING COLUMNS # CHECK FOR EXTRA COLUMNS # NOTE: At the moment there is no missing row detection. # This could be added if we want though # (it is not that bad if a user leaves out a row) # It's the first sheet # It's a module sheet # It's a form sheet Returns lists representing the expected structure of bulk app translation excel file uploads. The list will be in the form: [ ["sheetname", ["column name1", "column name 2"]], ["sheet2 name", [...]], ... ] :param app: :return: # Add headers for the first sheet Modify the translations and media references for the modules and forms in the given app as per the data provided in rows. This does not save the changes to the database. :param rows: :param app: :return: Returns a list of message tuples. The first item in each tuple is a function like django.contrib.messages.error, and the second is a string. Modify the translations of a form given a sheet of translation data. This does not save the changes to the DB. :param sheet: a WorksheetJSONReader :param rows: The rows of the sheet (we can't get this from the sheet because sheet.__iter__ can only be called once) :param missing_cols: :param app: :return: Returns a list of message tuples. The first item in each tuple is a function like django.contrib.messages.error, and the second is a string. # This Form doesn't have an xform yet. It is empty. # Tell the user this? # Make language nodes for each language if they don't yet exist # # Currently operating under the assumption that every xForm has at least # one translation element, that each translation element has a text node # for each question and that each text node has a value node under it # Get a translation element to be used as a template for new elements # Add missing translation elements # If the language isn't the default language # Update the translations # Add or remove translations # If the cell corresponding to the label for this question # in this language is empty, fall back to another language # Create the node if it does not already exist # Update the translation # Remove the node if it already exists Modify the translations of a module case list and detail display properties given a sheet of translation data. The properties in the sheet must be in the exact same order that they appear in the bulk app translation download. This function does not save the modified app to the database. :param sheet: :param rows: The rows of the sheet (we can't get this from the sheet because sheet.__iter__ can only be called once) :param app: :return: Returns a list of message tuples. The first item in each tuple is a function like django.contrib.messages.error, and the second is a string. # The list might contain DetailColumn instances in them that have exactly # the same attributes (but are in different positions). Therefore we must # match sheet rows to DetailColumns by position. # It is easier to process the translations if mapping rows are nested under # their respective DetailColumns # Cut off the id mapping text # Construct a list of mapping rows # Cut off the id mapping value part # Check length of lists # Update the translations # Check that names match (user is not allowed to change property in the # upload). Mismatched names indicate the user probably botched the sheet. # The logic for updating a mapping and updating a MappingItem and a # DetailColumn is almost the same. So, we smush the two together. # For DetailColumns # For MappingItems Returns true if the given row has at least one translation. >>> has_at_least_one_translation( {'default_en': 'Name', 'case_property': 'name'}, 'default', ['en', 'fra'] ) true >>> has_at_least_one_translation( {'case_property': 'name'}, 'default', ['en', 'fra'] ) false :param row: :param prefix: :param langs: :return: Returns the name of the column in the bulk app translation spreadsheet given the translation type and language :param translation_type: What is being translated, i.e. 'default' or 'image' :param language: :return:
2.115909
2
scripts/hf_create_train_test.py
myutman/contracode
115
6620559
<reponame>myutman/contracode<filename>scripts/hf_create_train_test.py from pathlib import Path import numpy as np import pandas as pd import pickle import gzip from tqdm.auto import tqdm DATA_PICKLE_PATH = Path("data/codesearchnet_javascript/javascript_augmented.pickle.gz") CACHE_PATH = Path("data/hf_data/augmented_pretrain_data_df.parquet") TRAIN_OUT_PATH = Path("/data/paras/augmented_pretrain_df.train.pickle.gz") TEST_OUT_PATH = Path("/data/paras/augmented_pretrain_df.test.pickle.gz") TRAIN_OUT_TXT_PATH = Path("/data/paras/augmented_pretrain_df.train.txt") TEST_OUT_TXT_PATH = Path("/data/paras/augmented_pretrain_df.test.txt") if __name__ == "__main__": if CACHE_PATH.exists(): print("Loading from cache") df = pd.read_parquet(CACHE_PATH) else: print("Loading from pickle") with gzip.open(DATA_PICKLE_PATH) as f: data = pickle.load(f) flattened_data = [] for idx, x in enumerate(tqdm(data)): for item in x: flattened_data.append(dict(data_idx=idx, text=item)) df = pd.DataFrame(flattened_data) del data, flattened_data print("Saving cache file of dataframe") df.to_parquet(str(CACHE_PATH.resolve()), engine="pyarrow") data_idxs = np.asarray(list(set(df["data_idx"]))) np.random.shuffle(data_idxs) test_idxs, train_idxs = data_idxs[:10000], data_idxs[10000:] train_df = df[df["data_idx"].isin(train_idxs)].sample(frac=1).reset_index(drop=True) test_df = df[df["data_idx"].isin(test_idxs)].sample(frac=1).reset_index(drop=True) print("Saving train data") train_df.to_pickle(TRAIN_OUT_PATH) print("Saving test data") test_df.to_pickle(TEST_OUT_PATH) train_txt = train_df["text"].tolist() test_txt = test_df["text"].tolist() print("Saving train text") with TRAIN_OUT_TXT_PATH.open("w") as f: f.write("\n".join(train_txt)) print("Saving test text") with TEST_OUT_TXT_PATH.open("w") as f: f.write("\n".join(test_txt))
from pathlib import Path import numpy as np import pandas as pd import pickle import gzip from tqdm.auto import tqdm DATA_PICKLE_PATH = Path("data/codesearchnet_javascript/javascript_augmented.pickle.gz") CACHE_PATH = Path("data/hf_data/augmented_pretrain_data_df.parquet") TRAIN_OUT_PATH = Path("/data/paras/augmented_pretrain_df.train.pickle.gz") TEST_OUT_PATH = Path("/data/paras/augmented_pretrain_df.test.pickle.gz") TRAIN_OUT_TXT_PATH = Path("/data/paras/augmented_pretrain_df.train.txt") TEST_OUT_TXT_PATH = Path("/data/paras/augmented_pretrain_df.test.txt") if __name__ == "__main__": if CACHE_PATH.exists(): print("Loading from cache") df = pd.read_parquet(CACHE_PATH) else: print("Loading from pickle") with gzip.open(DATA_PICKLE_PATH) as f: data = pickle.load(f) flattened_data = [] for idx, x in enumerate(tqdm(data)): for item in x: flattened_data.append(dict(data_idx=idx, text=item)) df = pd.DataFrame(flattened_data) del data, flattened_data print("Saving cache file of dataframe") df.to_parquet(str(CACHE_PATH.resolve()), engine="pyarrow") data_idxs = np.asarray(list(set(df["data_idx"]))) np.random.shuffle(data_idxs) test_idxs, train_idxs = data_idxs[:10000], data_idxs[10000:] train_df = df[df["data_idx"].isin(train_idxs)].sample(frac=1).reset_index(drop=True) test_df = df[df["data_idx"].isin(test_idxs)].sample(frac=1).reset_index(drop=True) print("Saving train data") train_df.to_pickle(TRAIN_OUT_PATH) print("Saving test data") test_df.to_pickle(TEST_OUT_PATH) train_txt = train_df["text"].tolist() test_txt = test_df["text"].tolist() print("Saving train text") with TRAIN_OUT_TXT_PATH.open("w") as f: f.write("\n".join(train_txt)) print("Saving test text") with TEST_OUT_TXT_PATH.open("w") as f: f.write("\n".join(test_txt))
none
1
2.454115
2
Python/task1-3/c2/blur.py
QH17/QHimage
4
6620560
<filename>Python/task1-3/c2/blur.py<gh_stars>1-10 #均值滤波函数 import cv2 img = cv2.imread("2.jpg") ######################################################################### #cv2.blur( # InputArray src, 输入的图像 # OutputArray dst, 输出的图像 # Size Ksize, 卷积核大小 # Point Anchor = (-1,-1), 锚点坐标 # int borderType=BORDER_DEFAULT 边界类型 # ) # #将核的锚点放在该特定位置的像素上,同时,核内的其他值与该像素邻域的各像素重合; #将核内各值与相应像素值相乘,并将乘积相加; #将所得结果放到与锚点对应的像素上; #对图像所有像素重复上述过程。 # ######################################################################### dst = cv2.blur(img,(5,5)) cv2.imshow("before", img) cv2.imshow("after", dst) cv2.waitKey(0)
<filename>Python/task1-3/c2/blur.py<gh_stars>1-10 #均值滤波函数 import cv2 img = cv2.imread("2.jpg") ######################################################################### #cv2.blur( # InputArray src, 输入的图像 # OutputArray dst, 输出的图像 # Size Ksize, 卷积核大小 # Point Anchor = (-1,-1), 锚点坐标 # int borderType=BORDER_DEFAULT 边界类型 # ) # #将核的锚点放在该特定位置的像素上,同时,核内的其他值与该像素邻域的各像素重合; #将核内各值与相应像素值相乘,并将乘积相加; #将所得结果放到与锚点对应的像素上; #对图像所有像素重复上述过程。 # ######################################################################### dst = cv2.blur(img,(5,5)) cv2.imshow("before", img) cv2.imshow("after", dst) cv2.waitKey(0)
zh
0.653718
#均值滤波函数 ######################################################################### #cv2.blur( # InputArray src, 输入的图像 # OutputArray dst, 输出的图像 # Size Ksize, 卷积核大小 # Point Anchor = (-1,-1), 锚点坐标 # int borderType=BORDER_DEFAULT 边界类型 # ) # #将核的锚点放在该特定位置的像素上,同时,核内的其他值与该像素邻域的各像素重合; #将核内各值与相应像素值相乘,并将乘积相加; #将所得结果放到与锚点对应的像素上; #对图像所有像素重复上述过程。 # #########################################################################
3.576786
4
src/merry/__init__.py
miguelgrinberg/merry
140
6620561
<filename>src/merry/__init__.py from functools import wraps import inspect import logging getargspec = None if getattr(inspect, 'getfullargspec', None): getargspec = inspect.getfullargspec else: # this one is deprecated in Python 3, but available in Python 2 getargspec = inspect.getargspec class _Namespace: pass class Merry(object): """Initialze merry. :param logger_name: the logger name to use. The default is ``'merry'``. :param debug: set to ``True`` to enable debug mode, which causes all errors to bubble up so that a debugger can catch them. The default is ``False``. """ def __init__(self, logger_name='merry', debug=False): self.logger = logging.getLogger(logger_name) self.g = _Namespace() self.debug = debug self.except_ = {} self.force_debug = [] self.force_handle = [] self.else_ = None self.finally_ = None def _try(self, f): """Decorator that wraps a function in a try block. Example usage:: @merry._try def my_function(): # do something here """ @wraps(f) def wrapper(*args, **kwargs): ret = None try: ret = f(*args, **kwargs) # note that if the function returned something, the else clause # will be skipped. This is a similar behavior to a normal # try/except/else block. if ret is not None: return ret except Exception as e: # find the best handler for this exception handler = None for c in self.except_.keys(): if isinstance(e, c): if handler is None or issubclass(c, handler): handler = c # if we don't have any handler, we let the exception bubble up if handler is None: raise e # log exception self.logger.exception('[merry] Exception caught') # if in debug mode, then bubble up to let a debugger handle debug = self.debug if handler in self.force_debug: debug = True elif handler in self.force_handle: debug = False if debug: raise e # invoke handler if len(getargspec(self.except_[handler])[0]) == 0: return self.except_[handler]() else: return self.except_[handler](e) else: # if we have an else handler, call it now if self.else_ is not None: return self.else_() finally: # if we have a finally handler, call it now if self.finally_ is not None: alt_ret = self.finally_() if alt_ret is not None: ret = alt_ret return ret return wrapper def _except(self, *args, **kwargs): """Decorator that registers a function as an error handler for one or more exception classes. Example usage:: @merry._except(RuntimeError) def runtime_error_handler(e): print('runtime error:', str(e)) :param args: the list of exception classes to be handled by the decorated function. :param kwargs: configuration arguments. Pass ``debug=True`` to enable debug mode for this handler, which bubbles up all exceptions. Pass ``debug=False`` to prevent the error from bubbling up, even if debug mode is enabled globally. """ def decorator(f): for e in args: self.except_[e] = f d = kwargs.get('debug', None) if d: self.force_debug.append(e) elif d is not None: self.force_handle.append(e) return f return decorator def _else(self, f): """Decorator to define the ``else`` clause handler. Example usage:: @merry._else def else_handler(): print('no exceptions were raised') """ self.else_ = f return f def _finally(self, f): """Decorator to define the ``finally`` clause handler. Example usage:: @merry._finally def finally_handler(): print('clean up') """ self.finally_ = f return f
<filename>src/merry/__init__.py from functools import wraps import inspect import logging getargspec = None if getattr(inspect, 'getfullargspec', None): getargspec = inspect.getfullargspec else: # this one is deprecated in Python 3, but available in Python 2 getargspec = inspect.getargspec class _Namespace: pass class Merry(object): """Initialze merry. :param logger_name: the logger name to use. The default is ``'merry'``. :param debug: set to ``True`` to enable debug mode, which causes all errors to bubble up so that a debugger can catch them. The default is ``False``. """ def __init__(self, logger_name='merry', debug=False): self.logger = logging.getLogger(logger_name) self.g = _Namespace() self.debug = debug self.except_ = {} self.force_debug = [] self.force_handle = [] self.else_ = None self.finally_ = None def _try(self, f): """Decorator that wraps a function in a try block. Example usage:: @merry._try def my_function(): # do something here """ @wraps(f) def wrapper(*args, **kwargs): ret = None try: ret = f(*args, **kwargs) # note that if the function returned something, the else clause # will be skipped. This is a similar behavior to a normal # try/except/else block. if ret is not None: return ret except Exception as e: # find the best handler for this exception handler = None for c in self.except_.keys(): if isinstance(e, c): if handler is None or issubclass(c, handler): handler = c # if we don't have any handler, we let the exception bubble up if handler is None: raise e # log exception self.logger.exception('[merry] Exception caught') # if in debug mode, then bubble up to let a debugger handle debug = self.debug if handler in self.force_debug: debug = True elif handler in self.force_handle: debug = False if debug: raise e # invoke handler if len(getargspec(self.except_[handler])[0]) == 0: return self.except_[handler]() else: return self.except_[handler](e) else: # if we have an else handler, call it now if self.else_ is not None: return self.else_() finally: # if we have a finally handler, call it now if self.finally_ is not None: alt_ret = self.finally_() if alt_ret is not None: ret = alt_ret return ret return wrapper def _except(self, *args, **kwargs): """Decorator that registers a function as an error handler for one or more exception classes. Example usage:: @merry._except(RuntimeError) def runtime_error_handler(e): print('runtime error:', str(e)) :param args: the list of exception classes to be handled by the decorated function. :param kwargs: configuration arguments. Pass ``debug=True`` to enable debug mode for this handler, which bubbles up all exceptions. Pass ``debug=False`` to prevent the error from bubbling up, even if debug mode is enabled globally. """ def decorator(f): for e in args: self.except_[e] = f d = kwargs.get('debug', None) if d: self.force_debug.append(e) elif d is not None: self.force_handle.append(e) return f return decorator def _else(self, f): """Decorator to define the ``else`` clause handler. Example usage:: @merry._else def else_handler(): print('no exceptions were raised') """ self.else_ = f return f def _finally(self, f): """Decorator to define the ``finally`` clause handler. Example usage:: @merry._finally def finally_handler(): print('clean up') """ self.finally_ = f return f
en
0.769538
# this one is deprecated in Python 3, but available in Python 2 Initialze merry. :param logger_name: the logger name to use. The default is ``'merry'``. :param debug: set to ``True`` to enable debug mode, which causes all errors to bubble up so that a debugger can catch them. The default is ``False``. Decorator that wraps a function in a try block. Example usage:: @merry._try def my_function(): # do something here # note that if the function returned something, the else clause # will be skipped. This is a similar behavior to a normal # try/except/else block. # find the best handler for this exception # if we don't have any handler, we let the exception bubble up # log exception # if in debug mode, then bubble up to let a debugger handle # invoke handler # if we have an else handler, call it now # if we have a finally handler, call it now Decorator that registers a function as an error handler for one or more exception classes. Example usage:: @merry._except(RuntimeError) def runtime_error_handler(e): print('runtime error:', str(e)) :param args: the list of exception classes to be handled by the decorated function. :param kwargs: configuration arguments. Pass ``debug=True`` to enable debug mode for this handler, which bubbles up all exceptions. Pass ``debug=False`` to prevent the error from bubbling up, even if debug mode is enabled globally. Decorator to define the ``else`` clause handler. Example usage:: @merry._else def else_handler(): print('no exceptions were raised') Decorator to define the ``finally`` clause handler. Example usage:: @merry._finally def finally_handler(): print('clean up')
2.804784
3
create_django_project/utils.py
ZendaInnocent/create-django-project
0
6620562
from pathlib import Path import re def read_secret_key(settings_file: Path): settings = settings_file.read_text() pattern = re.compile(r"secret_key", re.IGNORECASE) results = [line for line in settings.rsplit('\n') if pattern.findall(line)] secret_key = results[0].split(' = ')[1] return secret_key
from pathlib import Path import re def read_secret_key(settings_file: Path): settings = settings_file.read_text() pattern = re.compile(r"secret_key", re.IGNORECASE) results = [line for line in settings.rsplit('\n') if pattern.findall(line)] secret_key = results[0].split(' = ')[1] return secret_key
none
1
2.929866
3
babysage/__init__.py
ayemos/babysage
5
6620563
<gh_stars>1-10 # -*- coding: utf-8 -*- """Top-level package for Babysage.""" __author__ = """ayemos""" __email__ = '<EMAIL>' __version__ = '0.1.0'
# -*- coding: utf-8 -*- """Top-level package for Babysage.""" __author__ = """ayemos""" __email__ = '<EMAIL>' __version__ = '0.1.0'
en
0.63091
# -*- coding: utf-8 -*- Top-level package for Babysage. ayemos
0.866212
1
sme_material_apps/proponentes/migrations/0015_auto_20200813_1611.py
luizhpriotto/piloto_apresentacao
0
6620564
<reponame>luizhpriotto/piloto_apresentacao # Generated by Django 2.2.9 on 2020-08-13 19:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('proponentes', '0014_auto_20200812_1620'), ] operations = [ migrations.AddField( model_name='anexo', name='data_validade', field=models.DateField(blank=True, null=True), ), migrations.AddField( model_name='tipodocumento', name='tem_data_validade', field=models.BooleanField(default=False), ), ]
# Generated by Django 2.2.9 on 2020-08-13 19:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('proponentes', '0014_auto_20200812_1620'), ] operations = [ migrations.AddField( model_name='anexo', name='data_validade', field=models.DateField(blank=True, null=True), ), migrations.AddField( model_name='tipodocumento', name='tem_data_validade', field=models.BooleanField(default=False), ), ]
en
0.801212
# Generated by Django 2.2.9 on 2020-08-13 19:11
1.497339
1
python/hackerrank/combinations/main.py
imjoseangel/sandbox
0
6620565
<filename>python/hackerrank/combinations/main.py<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from itertools import combinations def main(): n, m = input().split() for item in range(1, int(m) + 1): print(*[''.join(i) for i in combinations(sorted(n), int(item))], sep='\n') if __name__ == '__main__': main()
<filename>python/hackerrank/combinations/main.py<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from itertools import combinations def main(): n, m = input().split() for item in range(1, int(m) + 1): print(*[''.join(i) for i in combinations(sorted(n), int(item))], sep='\n') if __name__ == '__main__': main()
en
0.352855
#!/usr/bin/env python # -*- coding: utf-8 -*-
3.330702
3
jpype/_jio.py
rbprogrammer/jpype
0
6620566
#***************************************************************************** # Copyright 2017 <NAME> # # 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. # #***************************************************************************** from . import _jclass from . import JavaException import sys as _sys if _sys.version > '3': pass def _closeableExit(self,exception_type, exception_value, traceback): info = _sys.exc_info() try: self.close() except JavaException as jex: # Eat the second exception if we are already handling one. if (info[0]==None): raise jex pass def _closeableEnter(self): return self class CloseableCustomizer(object): _METHODS = { '__enter__': _closeableEnter, '__exit__': _closeableExit, } def canCustomize(self, name, jc): if name == 'java.io.Closeable': return True return False def customize(self, name, jc, bases, members): members.update(CloseableCustomizer._METHODS) _jclass.registerClassCustomizer(CloseableCustomizer())
#***************************************************************************** # Copyright 2017 <NAME> # # 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. # #***************************************************************************** from . import _jclass from . import JavaException import sys as _sys if _sys.version > '3': pass def _closeableExit(self,exception_type, exception_value, traceback): info = _sys.exc_info() try: self.close() except JavaException as jex: # Eat the second exception if we are already handling one. if (info[0]==None): raise jex pass def _closeableEnter(self): return self class CloseableCustomizer(object): _METHODS = { '__enter__': _closeableEnter, '__exit__': _closeableExit, } def canCustomize(self, name, jc): if name == 'java.io.Closeable': return True return False def customize(self, name, jc, bases, members): members.update(CloseableCustomizer._METHODS) _jclass.registerClassCustomizer(CloseableCustomizer())
en
0.750441
#***************************************************************************** # Copyright 2017 <NAME> # # 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. # #***************************************************************************** # Eat the second exception if we are already handling one.
2.131315
2
asyncfileserver/tests/unit/model/test_confirm_put_queue.py
tarc/echo_server
1
6620567
<filename>asyncfileserver/tests/unit/model/test_confirm_put_queue.py import asyncio import aiounittest from asyncfileserver.model.confirm_put_queue import ConfirmPutQueue from asyncfileserver.tests.unit.model.fake_async_queue import FakeAsyncQueue class AllowAll(object): async def should_put(self, item): # Release control back to event loop to simulate more properly an async # call. await asyncio.sleep(0) return True class AllowSome(object): def __init__(self, items): self._items = items self._index = 0 async def should_put(self, item): await asyncio.sleep(0) if self._index >= len(self._items): return False if item == self._items[self._index]: self._index = self._index + 1 return True return False class TestConfirmPutQueue(aiounittest.AsyncTestCase): @staticmethod async def _compose_get_task_done(queue): item = await queue.get() queue.task_done() return item def get_event_loop(self): return asyncio.get_event_loop() async def test_allow_all_arbiter(self): allow_all = AllowAll() queue = [] fake_queue = FakeAsyncQueue(queue) confirm_queue = ConfirmPutQueue(allow_all, fake_queue) singular_item = bytearray(b'') put_task = asyncio.create_task(confirm_queue.put(singular_item)) get_task = asyncio.create_task( self._compose_get_task_done(confirm_queue)) _, same_element = await asyncio.gather(put_task, get_task) self.assertEqual(same_element, b'') async def test_allow_some_elements(self): allowed_bytes = [bytes([i]) for i in (1, 3, 5, 7, 9)] allowed_bytearrays = [bytearray(i) for i in allowed_bytes] allow_some = AllowSome(allowed_bytearrays) queue = [] fake_queue = FakeAsyncQueue(queue) confirm_queue = ConfirmPutQueue(allow_some, fake_queue) put_tasks = [asyncio.create_task( confirm_queue.put(bytearray([i]))) for i in range(10)] get_tasks = [asyncio.create_task( self._compose_get_task_done(confirm_queue)) for _ in range(5)] * results, = await asyncio.gather(* get_tasks, * put_tasks) self.assertEqual(results[0:5], allowed_bytes)
<filename>asyncfileserver/tests/unit/model/test_confirm_put_queue.py import asyncio import aiounittest from asyncfileserver.model.confirm_put_queue import ConfirmPutQueue from asyncfileserver.tests.unit.model.fake_async_queue import FakeAsyncQueue class AllowAll(object): async def should_put(self, item): # Release control back to event loop to simulate more properly an async # call. await asyncio.sleep(0) return True class AllowSome(object): def __init__(self, items): self._items = items self._index = 0 async def should_put(self, item): await asyncio.sleep(0) if self._index >= len(self._items): return False if item == self._items[self._index]: self._index = self._index + 1 return True return False class TestConfirmPutQueue(aiounittest.AsyncTestCase): @staticmethod async def _compose_get_task_done(queue): item = await queue.get() queue.task_done() return item def get_event_loop(self): return asyncio.get_event_loop() async def test_allow_all_arbiter(self): allow_all = AllowAll() queue = [] fake_queue = FakeAsyncQueue(queue) confirm_queue = ConfirmPutQueue(allow_all, fake_queue) singular_item = bytearray(b'') put_task = asyncio.create_task(confirm_queue.put(singular_item)) get_task = asyncio.create_task( self._compose_get_task_done(confirm_queue)) _, same_element = await asyncio.gather(put_task, get_task) self.assertEqual(same_element, b'') async def test_allow_some_elements(self): allowed_bytes = [bytes([i]) for i in (1, 3, 5, 7, 9)] allowed_bytearrays = [bytearray(i) for i in allowed_bytes] allow_some = AllowSome(allowed_bytearrays) queue = [] fake_queue = FakeAsyncQueue(queue) confirm_queue = ConfirmPutQueue(allow_some, fake_queue) put_tasks = [asyncio.create_task( confirm_queue.put(bytearray([i]))) for i in range(10)] get_tasks = [asyncio.create_task( self._compose_get_task_done(confirm_queue)) for _ in range(5)] * results, = await asyncio.gather(* get_tasks, * put_tasks) self.assertEqual(results[0:5], allowed_bytes)
en
0.843479
# Release control back to event loop to simulate more properly an async # call.
2.456002
2
uncertaintorch/models/resnet3d.py
jcreinhold/uncertaintorch
1
6620568
#!/usr/bin/env python # -*- coding: utf-8 -*- """ resnet3d 3d resnet model (backbone for deeplabv3) Author: <NAME> (<EMAIL>) Created on: December 31, 2019 """ __all__ = ['ResNet3d', 'resnet3d18', 'resnet3d34', 'resnet3d50', 'resnet3d101'] import torch from torch import nn import torch.nn.functional as F BASE_WIDTH = 32 EXPANSION = 2 def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Sequential(nn.ReplicationPad3d(dilation), nn.Conv3d(in_planes, out_planes, kernel_size=3, stride=stride, groups=groups, bias=False, dilation=dilation)) def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv3d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) class Bottleneck(nn.Module): expansion = EXPANSION __constants__ = ['downsample'] def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=BASE_WIDTH, dilation=1, norm_layer=None): super(Bottleneck, self).__init__() if norm_layer is None: norm_layer = nn.BatchNorm3d width = int(planes * (base_width / BASE_WIDTH)) * groups # Both self.conv2 and self.downsample layers downsample the input when stride != 1 self.conv1 = conv1x1(inplanes, width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, planes * self.expansion) self.bn3 = norm_layer(planes * self.expansion) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: identity = self.downsample(x) out += identity out = self.relu(out) return out class ResNet3d(nn.Module): def __init__(self, block, layers, zero_init_residual=False, groups=1, width_per_group=BASE_WIDTH, replace_stride_with_dilation=None, norm_layer=None, in_channels=1, dropout_rate=0., bayesian=False): super(ResNet3d, self).__init__() if norm_layer is None: norm_layer = nn.BatchNorm3d self._norm_layer = norm_layer self.p = dropout_rate self.bayesian = bayesian self.inplanes = BASE_WIDTH self.dilation = 1 if replace_stride_with_dilation is None: # each element in the tuple indicates if we should replace # the 2x2 stride with a dilated convolution instead replace_stride_with_dilation = [False, False, False] if len(replace_stride_with_dilation) != 3: raise ValueError("replace_stride_with_dilation should be None " "or a 3-element tuple, got {}".format(replace_stride_with_dilation)) self.groups = groups self.base_width = width_per_group self.conv1 = nn.Sequential(nn.ReplicationPad3d(3), nn.Conv3d(in_channels, self.inplanes, kernel_size=7, stride=2, bias=False)) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool3d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, BASE_WIDTH, layers[0]) self.layer2 = self._make_layer(block, BASE_WIDTH*2, layers[1], stride=2, dilate=replace_stride_with_dilation[0]) self.layer3 = self._make_layer(block, BASE_WIDTH*(2 if replace_stride_with_dilation[0] else 4), layers[2], stride=2, dilate=replace_stride_with_dilation[1]) self.layer4 = self._make_layer(block, BASE_WIDTH*(2 if replace_stride_with_dilation[1] else 8), layers[3], stride=2, dilate=replace_stride_with_dilation[2]) for m in self.modules(): if isinstance(m, nn.Conv3d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, (nn.BatchNorm3d, nn.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) # Zero-initialize the last BN in each residual branch, # so that the residual branch starts with zeros, and each residual block behaves like an identity. # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 if zero_init_residual: for m in self.modules(): if isinstance(m, Bottleneck): nn.init.constant_(m.bn3.weight, 0) def dropout(self, x): use_dropout = self.training or self.bayesian return F.dropout3d(x, self.p, training=use_dropout, inplace=False) def _make_layer(self, block, planes, blocks, stride=1, dilate=False): norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( conv1x1(self.inplanes, planes * block.expansion, stride), norm_layer(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, self.groups, self.base_width, previous_dilation, norm_layer)) self.inplanes = planes * block.expansion for _ in range(1, blocks): layers.append(block(self.inplanes, planes, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) return nn.Sequential(*layers) def _forward_impl(self, x): # See note [TorchScript super()] x = self.conv1(x) x = self.bn1(x) x = self.relu(x) start = x.clone() x = self.maxpool(x) x = self.layer1(x) mid = x.clone() x = self.dropout(x) x = self.dropout(self.layer2(x)) x = self.dropout(self.layer3(x)) x = self.dropout(self.layer4(x)) return x, start, mid def forward(self, x): return self._forward_impl(x) def resnet3d18(**kwargs): return ResNet3d(Bottleneck, [2, 2, 2, 2], **kwargs) def resnet3d34(**kwargs): return ResNet3d(Bottleneck, [3, 4, 6, 3], **kwargs) def resnet3d50(**kwargs): return ResNet3d(Bottleneck, [3, 4, 6, 3], **kwargs) def resnet3d101(**kwargs): return ResNet3d(Bottleneck, [3, 4, 23, 3], **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ resnet3d 3d resnet model (backbone for deeplabv3) Author: <NAME> (<EMAIL>) Created on: December 31, 2019 """ __all__ = ['ResNet3d', 'resnet3d18', 'resnet3d34', 'resnet3d50', 'resnet3d101'] import torch from torch import nn import torch.nn.functional as F BASE_WIDTH = 32 EXPANSION = 2 def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Sequential(nn.ReplicationPad3d(dilation), nn.Conv3d(in_planes, out_planes, kernel_size=3, stride=stride, groups=groups, bias=False, dilation=dilation)) def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv3d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) class Bottleneck(nn.Module): expansion = EXPANSION __constants__ = ['downsample'] def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=BASE_WIDTH, dilation=1, norm_layer=None): super(Bottleneck, self).__init__() if norm_layer is None: norm_layer = nn.BatchNorm3d width = int(planes * (base_width / BASE_WIDTH)) * groups # Both self.conv2 and self.downsample layers downsample the input when stride != 1 self.conv1 = conv1x1(inplanes, width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, planes * self.expansion) self.bn3 = norm_layer(planes * self.expansion) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: identity = self.downsample(x) out += identity out = self.relu(out) return out class ResNet3d(nn.Module): def __init__(self, block, layers, zero_init_residual=False, groups=1, width_per_group=BASE_WIDTH, replace_stride_with_dilation=None, norm_layer=None, in_channels=1, dropout_rate=0., bayesian=False): super(ResNet3d, self).__init__() if norm_layer is None: norm_layer = nn.BatchNorm3d self._norm_layer = norm_layer self.p = dropout_rate self.bayesian = bayesian self.inplanes = BASE_WIDTH self.dilation = 1 if replace_stride_with_dilation is None: # each element in the tuple indicates if we should replace # the 2x2 stride with a dilated convolution instead replace_stride_with_dilation = [False, False, False] if len(replace_stride_with_dilation) != 3: raise ValueError("replace_stride_with_dilation should be None " "or a 3-element tuple, got {}".format(replace_stride_with_dilation)) self.groups = groups self.base_width = width_per_group self.conv1 = nn.Sequential(nn.ReplicationPad3d(3), nn.Conv3d(in_channels, self.inplanes, kernel_size=7, stride=2, bias=False)) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool3d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, BASE_WIDTH, layers[0]) self.layer2 = self._make_layer(block, BASE_WIDTH*2, layers[1], stride=2, dilate=replace_stride_with_dilation[0]) self.layer3 = self._make_layer(block, BASE_WIDTH*(2 if replace_stride_with_dilation[0] else 4), layers[2], stride=2, dilate=replace_stride_with_dilation[1]) self.layer4 = self._make_layer(block, BASE_WIDTH*(2 if replace_stride_with_dilation[1] else 8), layers[3], stride=2, dilate=replace_stride_with_dilation[2]) for m in self.modules(): if isinstance(m, nn.Conv3d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, (nn.BatchNorm3d, nn.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) # Zero-initialize the last BN in each residual branch, # so that the residual branch starts with zeros, and each residual block behaves like an identity. # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 if zero_init_residual: for m in self.modules(): if isinstance(m, Bottleneck): nn.init.constant_(m.bn3.weight, 0) def dropout(self, x): use_dropout = self.training or self.bayesian return F.dropout3d(x, self.p, training=use_dropout, inplace=False) def _make_layer(self, block, planes, blocks, stride=1, dilate=False): norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( conv1x1(self.inplanes, planes * block.expansion, stride), norm_layer(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, self.groups, self.base_width, previous_dilation, norm_layer)) self.inplanes = planes * block.expansion for _ in range(1, blocks): layers.append(block(self.inplanes, planes, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) return nn.Sequential(*layers) def _forward_impl(self, x): # See note [TorchScript super()] x = self.conv1(x) x = self.bn1(x) x = self.relu(x) start = x.clone() x = self.maxpool(x) x = self.layer1(x) mid = x.clone() x = self.dropout(x) x = self.dropout(self.layer2(x)) x = self.dropout(self.layer3(x)) x = self.dropout(self.layer4(x)) return x, start, mid def forward(self, x): return self._forward_impl(x) def resnet3d18(**kwargs): return ResNet3d(Bottleneck, [2, 2, 2, 2], **kwargs) def resnet3d34(**kwargs): return ResNet3d(Bottleneck, [3, 4, 6, 3], **kwargs) def resnet3d50(**kwargs): return ResNet3d(Bottleneck, [3, 4, 6, 3], **kwargs) def resnet3d101(**kwargs): return ResNet3d(Bottleneck, [3, 4, 23, 3], **kwargs)
en
0.799535
#!/usr/bin/env python # -*- coding: utf-8 -*- resnet3d 3d resnet model (backbone for deeplabv3) Author: <NAME> (<EMAIL>) Created on: December 31, 2019 3x3 convolution with padding 1x1 convolution # Both self.conv2 and self.downsample layers downsample the input when stride != 1 # each element in the tuple indicates if we should replace # the 2x2 stride with a dilated convolution instead # Zero-initialize the last BN in each residual branch, # so that the residual branch starts with zeros, and each residual block behaves like an identity. # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 # See note [TorchScript super()]
2.261712
2
lab/refactoring/rename_method.py
Tanner-York-Make-School/SPD-2.31-Testing-and-Architecture
0
6620569
<reponame>Tanner-York-Make-School/SPD-2.31-Testing-and-Architecture<filename>lab/refactoring/rename_method.py """ By <NAME> Rename Method Reference: https://parade.com/1039985/marynliles/pick-up-lines/ """ def calc_area_under_grapg(graph): """Calculate the area under the input graph.""" # bla bla bla. pass ##################### def get_largest_value(li): """Returns the largest value in the given list""" m = li[0] for value in li: if value > m: m = value return m li = [5, -1, 43, 32, 87, -100] print(get_largest_value(li)) ############################ def extract_words(sentence): """Extracts the words from a given sentence and returns them in an array""" words = sentence[0:].split(' ') return words print(extract_words('If you were a vegetable, you’d be a ‘cute-cumber.'))
""" By <NAME> Rename Method Reference: https://parade.com/1039985/marynliles/pick-up-lines/ """ def calc_area_under_grapg(graph): """Calculate the area under the input graph.""" # bla bla bla. pass ##################### def get_largest_value(li): """Returns the largest value in the given list""" m = li[0] for value in li: if value > m: m = value return m li = [5, -1, 43, 32, 87, -100] print(get_largest_value(li)) ############################ def extract_words(sentence): """Extracts the words from a given sentence and returns them in an array""" words = sentence[0:].split(' ') return words print(extract_words('If you were a vegetable, you’d be a ‘cute-cumber.'))
en
0.50696
By <NAME> Rename Method Reference: https://parade.com/1039985/marynliles/pick-up-lines/ Calculate the area under the input graph. # bla bla bla. ##################### Returns the largest value in the given list ############################ Extracts the words from a given sentence and returns them in an array
3.813578
4
homeworks/ilya_nilov/hw05/level01.py
tgrx/Z22
0
6620570
<filename>homeworks/ilya_nilov/hw05/level01.py def summa(nmbr1, nmbr2): return nmbr1 + nmbr2
<filename>homeworks/ilya_nilov/hw05/level01.py def summa(nmbr1, nmbr2): return nmbr1 + nmbr2
none
1
2.189461
2
python/258.add-digits.py
stavanmehta/leetcode
0
6620571
class Solution: def addDigits(self, num: int) -> int:
class Solution: def addDigits(self, num: int) -> int:
none
1
2.135362
2
tess/data/tess_file_format.py
LithiumSR/tess
0
6620572
<gh_stars>0 import os import tempfile import keras from joblib import dump, load class TessFileUtils: @staticmethod def save(filename, model): model_tmp, schema_tmp, pca_tmp = [tempfile.NamedTemporaryFile(delete=False, prefix='tesstmp_') for x in range(3)] from tess.model.neural_model import TessNeuralModel from tess.model.svr_model import TessSVRModel if isinstance(model, TessNeuralModel): mode = 0 model.model.save(model_tmp.name) elif isinstance(model, TessSVRModel): mode = 1 dump(model.model, model_tmp.name) else: raise AttributeError('Invalid model class') dump(model.schema, schema_tmp.name) if model.use_reduction: dump(model.pca, pca_tmp.name) tmp_files = [model_tmp, schema_tmp, pca_tmp] with open(filename, 'wb') as fo: fo.write(int.to_bytes(mode, 8, 'little')) for el in tmp_files: fo.write(int.to_bytes(os.stat(el.name).st_size, 8, 'little')) for el in tmp_files: fi = open(el.name, 'rb') b = fi.read(256) while b: fo.write(b) b = fi.read(256) fi.close() if isinstance(model, TessNeuralModel): fo.write(int.to_bytes(model.epochs, 8, 'little')) fo.write(int.to_bytes(model.batch_size, 8, 'little')) for el in tmp_files: os.remove(el.name) @staticmethod def load(filename, model): with open(filename, 'rb') as fi: mode, model_len, schema_len, pca_len = [int.from_bytes(fi.read(x), 'little') for x in [8, 8, 8, 8]] from tess.model.neural_model import TessNeuralModel from tess.model.svr_model import TessSVRModel if (mode == 0 and not isinstance(model, TessNeuralModel)) or ( mode == 1 and not isinstance(model, TessSVRModel) or mode not in [0, 1]): raise AttributeError("Model mismatch when restoring") model.use_reduction = pca_len > 0 model_tmp, schema_tmp, pca_tmp = [tempfile.NamedTemporaryFile(delete=False, prefix='tesstmp_') for x in range(3)] tmp_files = [(model_len, model_tmp), (schema_len, schema_tmp), (pca_len, pca_tmp)] for el in tmp_files: with open(el[1].name, 'wb') as fo: written_bytes = 0 while written_bytes < el[0]: fo.write(fi.read(1)) written_bytes += 1 if isinstance(model, TessNeuralModel): model.epochs = int.from_bytes(fi.read(8), 'little') model.batch_size = int.from_bytes(fi.read(8), 'little') model.model = keras.models.load_model(model_tmp) elif mode == 1: model.model = load(model_tmp) model.schema = load(schema_tmp) if model.use_reduction: model.pca = load(pca_tmp) for el in tmp_files: os.remove(el[1].name)
import os import tempfile import keras from joblib import dump, load class TessFileUtils: @staticmethod def save(filename, model): model_tmp, schema_tmp, pca_tmp = [tempfile.NamedTemporaryFile(delete=False, prefix='tesstmp_') for x in range(3)] from tess.model.neural_model import TessNeuralModel from tess.model.svr_model import TessSVRModel if isinstance(model, TessNeuralModel): mode = 0 model.model.save(model_tmp.name) elif isinstance(model, TessSVRModel): mode = 1 dump(model.model, model_tmp.name) else: raise AttributeError('Invalid model class') dump(model.schema, schema_tmp.name) if model.use_reduction: dump(model.pca, pca_tmp.name) tmp_files = [model_tmp, schema_tmp, pca_tmp] with open(filename, 'wb') as fo: fo.write(int.to_bytes(mode, 8, 'little')) for el in tmp_files: fo.write(int.to_bytes(os.stat(el.name).st_size, 8, 'little')) for el in tmp_files: fi = open(el.name, 'rb') b = fi.read(256) while b: fo.write(b) b = fi.read(256) fi.close() if isinstance(model, TessNeuralModel): fo.write(int.to_bytes(model.epochs, 8, 'little')) fo.write(int.to_bytes(model.batch_size, 8, 'little')) for el in tmp_files: os.remove(el.name) @staticmethod def load(filename, model): with open(filename, 'rb') as fi: mode, model_len, schema_len, pca_len = [int.from_bytes(fi.read(x), 'little') for x in [8, 8, 8, 8]] from tess.model.neural_model import TessNeuralModel from tess.model.svr_model import TessSVRModel if (mode == 0 and not isinstance(model, TessNeuralModel)) or ( mode == 1 and not isinstance(model, TessSVRModel) or mode not in [0, 1]): raise AttributeError("Model mismatch when restoring") model.use_reduction = pca_len > 0 model_tmp, schema_tmp, pca_tmp = [tempfile.NamedTemporaryFile(delete=False, prefix='tesstmp_') for x in range(3)] tmp_files = [(model_len, model_tmp), (schema_len, schema_tmp), (pca_len, pca_tmp)] for el in tmp_files: with open(el[1].name, 'wb') as fo: written_bytes = 0 while written_bytes < el[0]: fo.write(fi.read(1)) written_bytes += 1 if isinstance(model, TessNeuralModel): model.epochs = int.from_bytes(fi.read(8), 'little') model.batch_size = int.from_bytes(fi.read(8), 'little') model.model = keras.models.load_model(model_tmp) elif mode == 1: model.model = load(model_tmp) model.schema = load(schema_tmp) if model.use_reduction: model.pca = load(pca_tmp) for el in tmp_files: os.remove(el[1].name)
none
1
2.431567
2
process_videos.py
NeelayS/pose_tracking
0
6620573
<reponame>NeelayS/pose_tracking import os from os.path import exists, join import argparse import json from visualize import visualize def generate_tracklets(results_list): tracklets = {} for frame in results_list: person = frame["idx"] if not person in tracklets.keys(): tracklets[person] = {} keypoints = frame["keypoints"] coordinate = [ (keypoints[3 * i], keypoints[3 * i + 1]) for i in range(len(keypoints) // 3) ] confidence_score = [keypoints[3 * i + 2] for i in range(len(keypoints) // 3)] overall_score = frame["score"] if not "coordinates" in tracklets[person].keys(): tracklets[person]["coordinates"] = [] tracklets[person]["confidence_scores"] = [] tracklets[person]["overall_scores"] = [] tracklets[person]["coordinates"].append(coordinate) tracklets[person]["confidence_scores"].append(confidence_score) tracklets[person]["overall_scores"].append(overall_score) for person in tracklets.keys(): tracklets[person]["avg_overall_score"] = sum( tracklets[person]["overall_scores"] ) / len(tracklets[person]["overall_scores"]) return tracklets if __name__ == "__main__": parser = argparse.ArgumentParser( description="Script to generate tracklets from all videos in a directory" ) parser.add_argument( "--indir", type=str, required=True, help="Should point to directory containing all the trimmed videos", ) parser.add_argument( "--outdir", type=str, required=True, help="Location where all the output files should be saved", ) parser.add_argument( "--threshold", type=float, default=2.75, help="Threshold score for filtering videos", ) parser.add_argument( "--visualize", type=bool, default=True, help="Whether to the visualize the tracklets for videos which pass the filters", ) parser.add_argument( "--min_time_fraction", type=float, default=0.2, help="Min fraction of time the person must be present in the video to be considered", ) parser.add_argument( "--n_people", type=int, default=5, help="Top k people to be stored for the videos on which performance is suitable", ) parser.add_argument( "--n_cat_videos", type=int, default=5, help="No. of videos of each category required", ) parser.add_argument( "--detbatch", type=int, default=5, help="detection batch size PER GPU" ) parser.add_argument( "--posebatch", type=int, default=10, help="pose estimation maximum batch size PER GPU", ) parser.add_argument( "--gpus", type=str, dest="gpus", default="0", help="choose which cuda device to use by index and input comma to use multi gpus, e.g. 0,1,2,3. (input -1 for cpu only)", ) parser.add_argument( "--qsize", type=int, dest="qsize", default=32, help="the length of result buffer, where reducing it will lower requirement of cpu memory", ) args = parser.parse_args() ckpt = "pretrained_models/fast_421_res152_256x192.pth" cfg = "configs/coco/resnet/256x192_res152_lr1e-3_1x-duc.yaml" if not exists(args.outdir): # print("The output directory doesn't exist. Creating it.") for name in ["AP_results", "tracklets", "videos"]: os.makedirs(join(args.outdir, name), exist_ok=True) os.mkdir(join(args.outdir, "AP_results", "all")) os.mkdir(join(args.outdir, "AP_results", "filtered")) for category in os.listdir(args.indir): if not exists(join(args.outdir, "tracklets", category)): os.mkdir(join(args.outdir, "tracklets", category)) if not exists(join(args.outdir, "videos", category)): os.mkdir(join(args.outdir, "videos", category)) if not exists(join(args.outdir, "AP_results", "all", category)): os.makedirs(join(args.outdir, "AP_results", "all", category)) if not exists(join(args.outdir, "AP_results", "filtered", category)): os.makedirs(join(args.outdir, "AP_results", "filtered", category)) category_count = 0 for video in os.listdir(join(args.indir, category)): if exists( join(args.outdir, "AP_results", "all", category, video[:-4] + ".json") ): print( f"The results for video {category}/{video[:-4]} exist already. Moving to next\n" ) continue if category_count == args.n_cat_videos: break video_path = join(args.indir, category, video) results_path = join(args.outdir, "AP_results", "all", category) print(f"Processing video {category}/{video}") command = f"python scripts/demo_inference.py --checkpoint {ckpt} --cfg {cfg} --video {video_path} --outdir {results_path} --gpus {args.gpus} --detbatch {args.detbatch} --posebatch {args.posebatch} --qsize {args.qsize} --pose_track" os.system(command) try: file_handle = open(join(results_path, "alphapose-results.json")) except: print("There was a problem with processing this video. Moving to next") continue results_list = json.load(file_handle) file_handle.close() tracklets = generate_tracklets(results_list) n_frames = len(results_list) min_frames = int(n_frames * args.min_time_fraction) filtered_persons = { person: tracklets[person]["avg_overall_score"] for person in tracklets.keys() if len(tracklets[person]["overall_scores"]) > min_frames } if not filtered_persons or len(filtered_persons.keys()) < 2: print( "This video is not suitable to be a part of the dataset. Moving to next\n" ) os.rename( join(results_path, "alphapose-results.json"), join(results_path, video[:-4] + ".json"), ) continue sorted_filtered_persons = { person: score for person, score in sorted( filtered_persons.items(), key=lambda item: item[1], reverse=True ) } is_video_suitable = 1 for person in list(sorted_filtered_persons.keys())[:2]: if not sorted_filtered_persons[person] >= args.threshold: is_video_suitable = 0 break if is_video_suitable: print("This video is suitable to be a part of the dataset\n") try: person_ids = list(sorted_filtered_persons.keys())[: args.n_people] except: person_ids = sorted_filtered_persons.keys() filtered_tracklets = { person: tracklet for person, tracklet in tracklets.items() if person in person_ids } filtered_results_list = [ person for person in results_list if person["idx"] in person_ids ] tracklets_json = json.dumps(filtered_tracklets) tracklets_file_handle = open( join( args.outdir, "tracklets", category, "tracklets_" + video[:-4] + ".json", ), "w", ) tracklets_file_handle.write(tracklets_json) tracklets_file_handle.close() results_json = json.dumps(filtered_results_list) results_file_handle = open( join( args.outdir, "AP_results", "filtered", category, "filtered_" + video[:-4] + ".json", ), "w", ) results_file_handle.write(results_json) results_file_handle.close() if args.visualize: visualize( filtered_results_list, video_path, join(args.outdir, "videos", category, video[:-4] + ".mp4"), ) category_count += 1 else: print( "This video is not suitable to be a part of the dataset. Moving to next\n" ) os.rename( join(results_path, "alphapose-results.json"), join(results_path, video[:-4] + ".json"), )
import os from os.path import exists, join import argparse import json from visualize import visualize def generate_tracklets(results_list): tracklets = {} for frame in results_list: person = frame["idx"] if not person in tracklets.keys(): tracklets[person] = {} keypoints = frame["keypoints"] coordinate = [ (keypoints[3 * i], keypoints[3 * i + 1]) for i in range(len(keypoints) // 3) ] confidence_score = [keypoints[3 * i + 2] for i in range(len(keypoints) // 3)] overall_score = frame["score"] if not "coordinates" in tracklets[person].keys(): tracklets[person]["coordinates"] = [] tracklets[person]["confidence_scores"] = [] tracklets[person]["overall_scores"] = [] tracklets[person]["coordinates"].append(coordinate) tracklets[person]["confidence_scores"].append(confidence_score) tracklets[person]["overall_scores"].append(overall_score) for person in tracklets.keys(): tracklets[person]["avg_overall_score"] = sum( tracklets[person]["overall_scores"] ) / len(tracklets[person]["overall_scores"]) return tracklets if __name__ == "__main__": parser = argparse.ArgumentParser( description="Script to generate tracklets from all videos in a directory" ) parser.add_argument( "--indir", type=str, required=True, help="Should point to directory containing all the trimmed videos", ) parser.add_argument( "--outdir", type=str, required=True, help="Location where all the output files should be saved", ) parser.add_argument( "--threshold", type=float, default=2.75, help="Threshold score for filtering videos", ) parser.add_argument( "--visualize", type=bool, default=True, help="Whether to the visualize the tracklets for videos which pass the filters", ) parser.add_argument( "--min_time_fraction", type=float, default=0.2, help="Min fraction of time the person must be present in the video to be considered", ) parser.add_argument( "--n_people", type=int, default=5, help="Top k people to be stored for the videos on which performance is suitable", ) parser.add_argument( "--n_cat_videos", type=int, default=5, help="No. of videos of each category required", ) parser.add_argument( "--detbatch", type=int, default=5, help="detection batch size PER GPU" ) parser.add_argument( "--posebatch", type=int, default=10, help="pose estimation maximum batch size PER GPU", ) parser.add_argument( "--gpus", type=str, dest="gpus", default="0", help="choose which cuda device to use by index and input comma to use multi gpus, e.g. 0,1,2,3. (input -1 for cpu only)", ) parser.add_argument( "--qsize", type=int, dest="qsize", default=32, help="the length of result buffer, where reducing it will lower requirement of cpu memory", ) args = parser.parse_args() ckpt = "pretrained_models/fast_421_res152_256x192.pth" cfg = "configs/coco/resnet/256x192_res152_lr1e-3_1x-duc.yaml" if not exists(args.outdir): # print("The output directory doesn't exist. Creating it.") for name in ["AP_results", "tracklets", "videos"]: os.makedirs(join(args.outdir, name), exist_ok=True) os.mkdir(join(args.outdir, "AP_results", "all")) os.mkdir(join(args.outdir, "AP_results", "filtered")) for category in os.listdir(args.indir): if not exists(join(args.outdir, "tracklets", category)): os.mkdir(join(args.outdir, "tracklets", category)) if not exists(join(args.outdir, "videos", category)): os.mkdir(join(args.outdir, "videos", category)) if not exists(join(args.outdir, "AP_results", "all", category)): os.makedirs(join(args.outdir, "AP_results", "all", category)) if not exists(join(args.outdir, "AP_results", "filtered", category)): os.makedirs(join(args.outdir, "AP_results", "filtered", category)) category_count = 0 for video in os.listdir(join(args.indir, category)): if exists( join(args.outdir, "AP_results", "all", category, video[:-4] + ".json") ): print( f"The results for video {category}/{video[:-4]} exist already. Moving to next\n" ) continue if category_count == args.n_cat_videos: break video_path = join(args.indir, category, video) results_path = join(args.outdir, "AP_results", "all", category) print(f"Processing video {category}/{video}") command = f"python scripts/demo_inference.py --checkpoint {ckpt} --cfg {cfg} --video {video_path} --outdir {results_path} --gpus {args.gpus} --detbatch {args.detbatch} --posebatch {args.posebatch} --qsize {args.qsize} --pose_track" os.system(command) try: file_handle = open(join(results_path, "alphapose-results.json")) except: print("There was a problem with processing this video. Moving to next") continue results_list = json.load(file_handle) file_handle.close() tracklets = generate_tracklets(results_list) n_frames = len(results_list) min_frames = int(n_frames * args.min_time_fraction) filtered_persons = { person: tracklets[person]["avg_overall_score"] for person in tracklets.keys() if len(tracklets[person]["overall_scores"]) > min_frames } if not filtered_persons or len(filtered_persons.keys()) < 2: print( "This video is not suitable to be a part of the dataset. Moving to next\n" ) os.rename( join(results_path, "alphapose-results.json"), join(results_path, video[:-4] + ".json"), ) continue sorted_filtered_persons = { person: score for person, score in sorted( filtered_persons.items(), key=lambda item: item[1], reverse=True ) } is_video_suitable = 1 for person in list(sorted_filtered_persons.keys())[:2]: if not sorted_filtered_persons[person] >= args.threshold: is_video_suitable = 0 break if is_video_suitable: print("This video is suitable to be a part of the dataset\n") try: person_ids = list(sorted_filtered_persons.keys())[: args.n_people] except: person_ids = sorted_filtered_persons.keys() filtered_tracklets = { person: tracklet for person, tracklet in tracklets.items() if person in person_ids } filtered_results_list = [ person for person in results_list if person["idx"] in person_ids ] tracklets_json = json.dumps(filtered_tracklets) tracklets_file_handle = open( join( args.outdir, "tracklets", category, "tracklets_" + video[:-4] + ".json", ), "w", ) tracklets_file_handle.write(tracklets_json) tracklets_file_handle.close() results_json = json.dumps(filtered_results_list) results_file_handle = open( join( args.outdir, "AP_results", "filtered", category, "filtered_" + video[:-4] + ".json", ), "w", ) results_file_handle.write(results_json) results_file_handle.close() if args.visualize: visualize( filtered_results_list, video_path, join(args.outdir, "videos", category, video[:-4] + ".mp4"), ) category_count += 1 else: print( "This video is not suitable to be a part of the dataset. Moving to next\n" ) os.rename( join(results_path, "alphapose-results.json"), join(results_path, video[:-4] + ".json"), )
en
0.90069
# print("The output directory doesn't exist. Creating it.")
2.731653
3
web/blueprints/Login.py
arashmjr/ClubHouseFollowers
0
6620574
<filename>web/blueprints/Login.py<gh_stars>0 from flask import Blueprint from flask import request from seviceLayer.core.ServiceProvider import ServiceProvider from web.dtos.BaseResponse import BaseError, BaseResponse from web.utils.Localization import MessageIds from flask import jsonify from flask_api import status Login = Blueprint('Login', __name__) @Login.route('/Login', methods=['POST']) def login(): json = request.get_json() try: service = ServiceProvider().make_login_service() token = service.login_user(json) response = BaseResponse({"access token": token}, True, MessageIds.SUCCESS) return jsonify(response.serialize()), status.HTTP_201_CREATED except ValueError: response = BaseError(MessageIds.ERROR_BAD_JSON) return jsonify(response.serialize()), status.HTTP_400_BAD_REQUEST
<filename>web/blueprints/Login.py<gh_stars>0 from flask import Blueprint from flask import request from seviceLayer.core.ServiceProvider import ServiceProvider from web.dtos.BaseResponse import BaseError, BaseResponse from web.utils.Localization import MessageIds from flask import jsonify from flask_api import status Login = Blueprint('Login', __name__) @Login.route('/Login', methods=['POST']) def login(): json = request.get_json() try: service = ServiceProvider().make_login_service() token = service.login_user(json) response = BaseResponse({"access token": token}, True, MessageIds.SUCCESS) return jsonify(response.serialize()), status.HTTP_201_CREATED except ValueError: response = BaseError(MessageIds.ERROR_BAD_JSON) return jsonify(response.serialize()), status.HTTP_400_BAD_REQUEST
none
1
2.484155
2
PySRCG/src/GenModes/points.py
apampuch/PySRCG
0
6620575
from abc import ABC from src.GenModes.gen_mode import GenMode class Points(GenMode, ABC): def __init__(self): super().__init__() self.starting_skills_max = 6 def get_generated_value(self, key): pass def update_karma_label(self, tab): pass def setup_ui_elements(self): pass def serialize(self): pass def update_total(self, amount, key): pass def point_purchase_allowed(self, amount, key): """Ignore key since we draw from the same pool.""" pass
from abc import ABC from src.GenModes.gen_mode import GenMode class Points(GenMode, ABC): def __init__(self): super().__init__() self.starting_skills_max = 6 def get_generated_value(self, key): pass def update_karma_label(self, tab): pass def setup_ui_elements(self): pass def serialize(self): pass def update_total(self, amount, key): pass def point_purchase_allowed(self, amount, key): """Ignore key since we draw from the same pool.""" pass
en
0.953159
Ignore key since we draw from the same pool.
2.418746
2
test.py
okutani-t/python-code
0
6620576
<reponame>okutani-t/python-code # -*- coding: utf-8 -*- import random i = random.randint(1,101) if i<50: print"これは50より小さい"+ str(i) + "です。残念!" else: print"50より大きい"+ str(i) + "です。やったね!"
# -*- coding: utf-8 -*- import random i = random.randint(1,101) if i<50: print"これは50より小さい"+ str(i) + "です。残念!" else: print"50より大きい"+ str(i) + "です。やったね!"
en
0.769321
# -*- coding: utf-8 -*-
3.431012
3
pyogp/lib/base/helpers.py
grobertson/PyOGP.lib.Base
0
6620577
<reponame>grobertson/PyOGP.lib.Base """ Contributors can be viewed at: http://svn.secondlife.com/svn/linden/projects/2008/pyogp/lib/base/trunk/CONTRIBUTORS.txt $LicenseInfo:firstyear=2008&license=apachev2$ Copyright 2009, Linden Research, Inc. Licensed under the Apache License, Version 2.0. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 or in http://svn.secondlife.com/svn/linden/projects/2008/pyogp/lib/base/LICENSE.txt $/LicenseInfo$ """ # standard python libs from logging import getLogger import time import struct import math # related from llbase import llsd try: from eventlet import api as eventlet except ImportError: import eventlet # pyogp from pyogp.lib.base.exc import DataParsingError, DeserializationFailed # initialize loggin logger = getLogger('...utilities.helpers') class Helpers(object): """ contains useful helper functions """ @staticmethod def bytes_to_hex(data): """ converts bytes to hex format """ #from binascii import hexlify #return hex_string #hex_string = hexlify(data) return ''.join(["%02X " % ord(x) for x in data]).strip() @staticmethod def bytes_to_ascii(data): " converts bytes to ascii format " from binascii import b2a_uu ascii_string = b2a_uu(data) return ascii_string @staticmethod def hex_to_ascii(data): " converts bytes to ascii format " from binascii import unhexlify try: ascii_string = unhexlify(data) except TypeError, error: raise DataParsingError('hex_to_ascii failure: \'%s\': processing data: \'%s\'' % (error, data)) return ascii_string @staticmethod def bytes_to_base64(data): " converts bytes to ascii format " from binascii import b2a_base64 base64_string = b2a_base64(data) return base64_string @staticmethod def packed_u16_to_float(bytes, offset, lower, upper): """ Extract float packed as u16 in a byte buffer """ U16MAX = 65535 OOU16MAX = 1.0/U16MAX u16 = struct.unpack('<H', bytes[offset:offset+2])[0] val = u16 * OOU16MAX delta = upper - lower val *= delta val += lower max_error = delta * OOU16MAX if math.fabs(val) < max_error: val = 0.0 return val @staticmethod def packed_u8_to_float(bytes, offset, lower, upper): """ Extract float packed as u8 in a byte buffer """ U8MAX = 255 OOU8MAX = 1.0/U8MAX u8 = struct.unpack('<B', bytes[offset:offset+1])[0] val = u8 * OOU8MAX delta = upper - lower val *= delta val += lower max_error = delta * OOU8MAX if math.fabs(val) < max_error: val = 0.0 return val @staticmethod def pack_quaternion_to_vector3(quaternion): """ pack a normalized quaternion (tuple) into a vector3 (tuple) """ if quaternion[3] >= 0: return (quaternion[0], quaternion[1], quaternion[2]) else: return (-quaternion[0], -quaternion[1], -quaternion[2]) @staticmethod def int_to_bytes(data): """ converts an int to a string of bytes """ return struct.pack('BBBB', data % 256, (data >> 8) % 256, (data >> 16) % 256, (data >> 24) % 256) # ~~~~~~~~~ # Callbacks # ~~~~~~~~~ @staticmethod def log_packet(packet, _object): """ default logging function for packets """ logger.info("Object %s is monitoring packet type %s: \n%s" % (type(_object), packet.name, packet.data())) @staticmethod def log_event_queue_data(data, _object): """ default logging function for event queue data events """ logger.info("Object %s is monitoring event queue data event %s: \n%s" % (type(_object), data.name, data.__dict__)) @staticmethod def null_packet_handler(packet, _object): """ just a null event handler for watching aka fully parsing specific packets """ pass class ListLLSDSerializer(object): """adapter for serializing a list to LLSD An example: >>> d=['ChatSessionRequest', 'CopyInventoryFromNotecard'] >>> serializer = ListLLSDSerializer(d) >>> serializer.serialize() '<?xml version="1.0" ?><llsd><array><string>ChatSessionRequest</string><string>CopyInventoryFromNotecard</string></array></llsd>' >>> serializer.content_type 'application/llsd+xml' """ def __init__(self, context): self.context = context def serialize(self): """convert the payload to LLSD""" return llsd.format_xml(self.context) @property def content_type(self): """return the content type of this serializer""" return "application/llsd+xml" class DictLLSDSerializer(object): """adapter for serializing a dictionary to LLSD An example: >>> d={'foo':'bar', 'test':1234} >>> serializer = DictLLSDSerializer(d) >>> serializer.serialize() '<?xml version="1.0" ?><llsd><map><key>test</key><integer>1234</integer><key>foo</key><string>bar</string></map></llsd>' >>> serializer.content_type 'application/llsd+xml' """ def __init__(self, context): self.context = context def serialize(self): """convert the payload to LLSD""" return llsd.format_xml(self.context) @property def content_type(self): """return the content type of this serializer""" return "application/llsd+xml" class LLSDDeserializer(object): """utility for deserializing LLSD data The deserialization component is defined as a utility because the input data can be a string or a file. It might be possible to define this as an adapter on a string but a string is too generic for this. So that's why it is a utility. You can use it like this: >>> s='<?xml version="1.0" ?><llsd><map><key>test</key><integer>1234</integer><key>foo</key><string>bar</string></map></llsd>' We use queryUtility because this returns None instead of an exception when a utility is not registered. We use the content type we received as the name of the utility. Another option would of course be to subclas string to some LLSDString class and use an adapter. We then would need some factory for generating the LLSDString class from whatever came back from the HTTP call. So here is how you use that utility: >>> deserializer = LLSDDeserializer() >>> llsd = deserializer.deserialize(s) >>> llsd {'test': 1234, 'foo': 'bar'} We can also test this with some non-LLSD string: >>> llsd = deserializer.deserialize_string('mumpitz') # this is not LLSD Traceback (most recent call last): ... DeserializationFailed: deserialization failed for 'mumpitz', reason: 'invalid token at index 0: 109' >>> llsd = deserializer.deserialize_string('barfoo') Traceback (most recent call last): ... DeserializationFailed: deserialization failed for 'barfoo', reason: 'random horrible binary format not supported' """ def deserialize(self, data): """ convenience class to handle a variety of inputs """ if type(data) == str: return self.deserialize_string(data) # won't handle another case until we need to def deserialize_string(self, data): """ deserialize a string """ try: r = llsd.parse(data) except llsd.LLSDParseError, e: raise DeserializationFailed(data, str(e)) if r==False: raise DeserializationFailed(data, 'result was False') return r def deserialize_file(self, fp): """ deserialize a file """ data = fp.read() return self.deserialize_string(data) class Wait(object): """ a simple timer that blocks a calling routine for the specified number of seconds done since we were writing timing loops in test scripts repeatedly returns True when it's done """ def __init__(self, duration): self.duration = int(duration) # let's be nice and enabled a kill switch self.enabled = False self.run() def run(self): now = time.time() start = now self.enabled = True while self.enabled and now - start < self.duration: try: eventlet.sleep() now = time.time() except AssertionError: pass return True def stop(self): self.enabled = False
""" Contributors can be viewed at: http://svn.secondlife.com/svn/linden/projects/2008/pyogp/lib/base/trunk/CONTRIBUTORS.txt $LicenseInfo:firstyear=2008&license=apachev2$ Copyright 2009, Linden Research, Inc. Licensed under the Apache License, Version 2.0. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 or in http://svn.secondlife.com/svn/linden/projects/2008/pyogp/lib/base/LICENSE.txt $/LicenseInfo$ """ # standard python libs from logging import getLogger import time import struct import math # related from llbase import llsd try: from eventlet import api as eventlet except ImportError: import eventlet # pyogp from pyogp.lib.base.exc import DataParsingError, DeserializationFailed # initialize loggin logger = getLogger('...utilities.helpers') class Helpers(object): """ contains useful helper functions """ @staticmethod def bytes_to_hex(data): """ converts bytes to hex format """ #from binascii import hexlify #return hex_string #hex_string = hexlify(data) return ''.join(["%02X " % ord(x) for x in data]).strip() @staticmethod def bytes_to_ascii(data): " converts bytes to ascii format " from binascii import b2a_uu ascii_string = b2a_uu(data) return ascii_string @staticmethod def hex_to_ascii(data): " converts bytes to ascii format " from binascii import unhexlify try: ascii_string = unhexlify(data) except TypeError, error: raise DataParsingError('hex_to_ascii failure: \'%s\': processing data: \'%s\'' % (error, data)) return ascii_string @staticmethod def bytes_to_base64(data): " converts bytes to ascii format " from binascii import b2a_base64 base64_string = b2a_base64(data) return base64_string @staticmethod def packed_u16_to_float(bytes, offset, lower, upper): """ Extract float packed as u16 in a byte buffer """ U16MAX = 65535 OOU16MAX = 1.0/U16MAX u16 = struct.unpack('<H', bytes[offset:offset+2])[0] val = u16 * OOU16MAX delta = upper - lower val *= delta val += lower max_error = delta * OOU16MAX if math.fabs(val) < max_error: val = 0.0 return val @staticmethod def packed_u8_to_float(bytes, offset, lower, upper): """ Extract float packed as u8 in a byte buffer """ U8MAX = 255 OOU8MAX = 1.0/U8MAX u8 = struct.unpack('<B', bytes[offset:offset+1])[0] val = u8 * OOU8MAX delta = upper - lower val *= delta val += lower max_error = delta * OOU8MAX if math.fabs(val) < max_error: val = 0.0 return val @staticmethod def pack_quaternion_to_vector3(quaternion): """ pack a normalized quaternion (tuple) into a vector3 (tuple) """ if quaternion[3] >= 0: return (quaternion[0], quaternion[1], quaternion[2]) else: return (-quaternion[0], -quaternion[1], -quaternion[2]) @staticmethod def int_to_bytes(data): """ converts an int to a string of bytes """ return struct.pack('BBBB', data % 256, (data >> 8) % 256, (data >> 16) % 256, (data >> 24) % 256) # ~~~~~~~~~ # Callbacks # ~~~~~~~~~ @staticmethod def log_packet(packet, _object): """ default logging function for packets """ logger.info("Object %s is monitoring packet type %s: \n%s" % (type(_object), packet.name, packet.data())) @staticmethod def log_event_queue_data(data, _object): """ default logging function for event queue data events """ logger.info("Object %s is monitoring event queue data event %s: \n%s" % (type(_object), data.name, data.__dict__)) @staticmethod def null_packet_handler(packet, _object): """ just a null event handler for watching aka fully parsing specific packets """ pass class ListLLSDSerializer(object): """adapter for serializing a list to LLSD An example: >>> d=['ChatSessionRequest', 'CopyInventoryFromNotecard'] >>> serializer = ListLLSDSerializer(d) >>> serializer.serialize() '<?xml version="1.0" ?><llsd><array><string>ChatSessionRequest</string><string>CopyInventoryFromNotecard</string></array></llsd>' >>> serializer.content_type 'application/llsd+xml' """ def __init__(self, context): self.context = context def serialize(self): """convert the payload to LLSD""" return llsd.format_xml(self.context) @property def content_type(self): """return the content type of this serializer""" return "application/llsd+xml" class DictLLSDSerializer(object): """adapter for serializing a dictionary to LLSD An example: >>> d={'foo':'bar', 'test':1234} >>> serializer = DictLLSDSerializer(d) >>> serializer.serialize() '<?xml version="1.0" ?><llsd><map><key>test</key><integer>1234</integer><key>foo</key><string>bar</string></map></llsd>' >>> serializer.content_type 'application/llsd+xml' """ def __init__(self, context): self.context = context def serialize(self): """convert the payload to LLSD""" return llsd.format_xml(self.context) @property def content_type(self): """return the content type of this serializer""" return "application/llsd+xml" class LLSDDeserializer(object): """utility for deserializing LLSD data The deserialization component is defined as a utility because the input data can be a string or a file. It might be possible to define this as an adapter on a string but a string is too generic for this. So that's why it is a utility. You can use it like this: >>> s='<?xml version="1.0" ?><llsd><map><key>test</key><integer>1234</integer><key>foo</key><string>bar</string></map></llsd>' We use queryUtility because this returns None instead of an exception when a utility is not registered. We use the content type we received as the name of the utility. Another option would of course be to subclas string to some LLSDString class and use an adapter. We then would need some factory for generating the LLSDString class from whatever came back from the HTTP call. So here is how you use that utility: >>> deserializer = LLSDDeserializer() >>> llsd = deserializer.deserialize(s) >>> llsd {'test': 1234, 'foo': 'bar'} We can also test this with some non-LLSD string: >>> llsd = deserializer.deserialize_string('mumpitz') # this is not LLSD Traceback (most recent call last): ... DeserializationFailed: deserialization failed for 'mumpitz', reason: 'invalid token at index 0: 109' >>> llsd = deserializer.deserialize_string('barfoo') Traceback (most recent call last): ... DeserializationFailed: deserialization failed for 'barfoo', reason: 'random horrible binary format not supported' """ def deserialize(self, data): """ convenience class to handle a variety of inputs """ if type(data) == str: return self.deserialize_string(data) # won't handle another case until we need to def deserialize_string(self, data): """ deserialize a string """ try: r = llsd.parse(data) except llsd.LLSDParseError, e: raise DeserializationFailed(data, str(e)) if r==False: raise DeserializationFailed(data, 'result was False') return r def deserialize_file(self, fp): """ deserialize a file """ data = fp.read() return self.deserialize_string(data) class Wait(object): """ a simple timer that blocks a calling routine for the specified number of seconds done since we were writing timing loops in test scripts repeatedly returns True when it's done """ def __init__(self, duration): self.duration = int(duration) # let's be nice and enabled a kill switch self.enabled = False self.run() def run(self): now = time.time() start = now self.enabled = True while self.enabled and now - start < self.duration: try: eventlet.sleep() now = time.time() except AssertionError: pass return True def stop(self): self.enabled = False
en
0.651251
Contributors can be viewed at: http://svn.secondlife.com/svn/linden/projects/2008/pyogp/lib/base/trunk/CONTRIBUTORS.txt $LicenseInfo:firstyear=2008&license=apachev2$ Copyright 2009, Linden Research, Inc. Licensed under the Apache License, Version 2.0. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 or in http://svn.secondlife.com/svn/linden/projects/2008/pyogp/lib/base/LICENSE.txt $/LicenseInfo$ # standard python libs # related # pyogp # initialize loggin contains useful helper functions converts bytes to hex format #from binascii import hexlify #return hex_string #hex_string = hexlify(data) Extract float packed as u16 in a byte buffer Extract float packed as u8 in a byte buffer pack a normalized quaternion (tuple) into a vector3 (tuple) converts an int to a string of bytes # ~~~~~~~~~ # Callbacks # ~~~~~~~~~ default logging function for packets default logging function for event queue data events just a null event handler for watching aka fully parsing specific packets adapter for serializing a list to LLSD An example: >>> d=['ChatSessionRequest', 'CopyInventoryFromNotecard'] >>> serializer = ListLLSDSerializer(d) >>> serializer.serialize() '<?xml version="1.0" ?><llsd><array><string>ChatSessionRequest</string><string>CopyInventoryFromNotecard</string></array></llsd>' >>> serializer.content_type 'application/llsd+xml' convert the payload to LLSD return the content type of this serializer adapter for serializing a dictionary to LLSD An example: >>> d={'foo':'bar', 'test':1234} >>> serializer = DictLLSDSerializer(d) >>> serializer.serialize() '<?xml version="1.0" ?><llsd><map><key>test</key><integer>1234</integer><key>foo</key><string>bar</string></map></llsd>' >>> serializer.content_type 'application/llsd+xml' convert the payload to LLSD return the content type of this serializer utility for deserializing LLSD data The deserialization component is defined as a utility because the input data can be a string or a file. It might be possible to define this as an adapter on a string but a string is too generic for this. So that's why it is a utility. You can use it like this: >>> s='<?xml version="1.0" ?><llsd><map><key>test</key><integer>1234</integer><key>foo</key><string>bar</string></map></llsd>' We use queryUtility because this returns None instead of an exception when a utility is not registered. We use the content type we received as the name of the utility. Another option would of course be to subclas string to some LLSDString class and use an adapter. We then would need some factory for generating the LLSDString class from whatever came back from the HTTP call. So here is how you use that utility: >>> deserializer = LLSDDeserializer() >>> llsd = deserializer.deserialize(s) >>> llsd {'test': 1234, 'foo': 'bar'} We can also test this with some non-LLSD string: >>> llsd = deserializer.deserialize_string('mumpitz') # this is not LLSD Traceback (most recent call last): ... DeserializationFailed: deserialization failed for 'mumpitz', reason: 'invalid token at index 0: 109' >>> llsd = deserializer.deserialize_string('barfoo') Traceback (most recent call last): ... DeserializationFailed: deserialization failed for 'barfoo', reason: 'random horrible binary format not supported' convenience class to handle a variety of inputs # won't handle another case until we need to deserialize a string deserialize a file a simple timer that blocks a calling routine for the specified number of seconds done since we were writing timing loops in test scripts repeatedly returns True when it's done # let's be nice and enabled a kill switch
2.071093
2
osgar/drivers/test_rosmsg.py
robotika/osgar
12
6620578
<gh_stars>10-100 import unittest from unittest.mock import MagicMock from osgar.drivers.rosmsg import (ROSMsgParser, parse_volatile, parse_bucket, parse_topic) class ROSMsgParserTest(unittest.TestCase): def test_parse_volatile(self): data = b"<\x00\x00\x00\x8c\x00\x00\x009\x00\x00\x00\x00'\xb9)\x17\x00\x00\x00" + \ b"scout_1/volatile_sensor\x08\x00\x00\x00methanol\n\x00\x00\x00\x01\xfb\xde`?" self.assertEqual(parse_volatile(data), ['methanol', 0.8784024119377136, 10]) def test_parse_bucket(self): data = b'\x16\x00\x00\x00\n\x00\x00\x00sulfur_dio\x1b\x00\x00\x00\xd3\xa7\xabA' self.assertEqual(parse_bucket(data), ['sulfur_dio', 27, 21.456945419311523]) def test_parse_bin(self): data = b'\x82\x00\x00\x00\x03\x00\x00\x00ice\x06\x00\x00\x00ethene\x07\x00\x00\x00methane\x0b\x00\x00\x00carbon_mono\n\x00\x00\x00carbon_dio\x07\x00\x00\x00ammonia\x0c\x00\x00\x00hydrogen_sul\n\x00\x00\x00sulfur_dio\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' self.assertEqual(parse_topic('srcp2_msgs/HaulerMsg', data), [['ice', 'ethene', 'methane', 'carbon_mono', 'carbon_dio', 'ammonia', 'hydrogen_sul', 'sulfur_dio'], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]) def test_parse_score_qual2(self): data = b'\x87\x00\x00\x00\x03\x00\x00\x00ice\x06\x00\x00\x00ethene\x07\x00\x00\x00methane' + \ b'\x08\x00\x00\x00carbon_mono\n\x00\x00\x00carbon_dio\x07\x00\x00\x00ammonia\x0c\x00\x00\x00' + \ b'hydrogen_sul\n\x00\x00\x00sulfur_dio\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + \ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + \ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00' self.assertEqual(parse_topic('srcp2_msgs/Qual2ScoringMsg', data), [0, 0]) def test_radio(self): data = b'radio X30F60R [0, 100, 30]\n' bus = MagicMock() r = ROSMsgParser(config={}, bus=bus) r.slot_raw(timestamp=None, data=data) bus.publish.assert_called_with('radio', [b'X30F60R', b'[0, 100, 30]\n']) def test_publish_desired_speed(self): data = b'\x08\x00\x00\x00\x02\x00\x00\x00\x00\x06\x81\x14' # clock as 8 bytes bus = MagicMock() r = ROSMsgParser(config={}, bus=bus) r.slot_raw(timestamp=None, data=data) bus.publish.assert_called_with('sim_time_sec', 2) clock_data = b'\x08\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00' # clock 3s r.slot_raw(timestamp=None, data=clock_data) bus.publish.assert_called_with('sim_time_sec', 3) # initially desired speed is None -> no cmd r.slot_desired_speed(timestamp=None, data=[0, 0]) r.slot_raw(timestamp=None, data=clock_data) # ... asserting that the last call has been made in a particular way bus.publish.assert_called_with('cmd', b'cmd_vel 0.000000 0.000000') # after update from 3D desired speed only extended cmd_vel_3d should be used r.slot_desired_speed_3d(timestamp=None, data=[[1, 2, 3], [4, 5, 6]]) r.slot_raw(timestamp=None, data=clock_data) bus.publish.assert_called_with('cmd', b'cmd_vel_3d 1.000000 2.000000 3.000000 4.000000 5.000000 6.000000') def test_publish_undefined_desired_speed(self): # for the drone it is important not to send any command until the very first desired speed is received pass # vim: expandtab sw=4 ts=4
import unittest from unittest.mock import MagicMock from osgar.drivers.rosmsg import (ROSMsgParser, parse_volatile, parse_bucket, parse_topic) class ROSMsgParserTest(unittest.TestCase): def test_parse_volatile(self): data = b"<\x00\x00\x00\x8c\x00\x00\x009\x00\x00\x00\x00'\xb9)\x17\x00\x00\x00" + \ b"scout_1/volatile_sensor\x08\x00\x00\x00methanol\n\x00\x00\x00\x01\xfb\xde`?" self.assertEqual(parse_volatile(data), ['methanol', 0.8784024119377136, 10]) def test_parse_bucket(self): data = b'\x16\x00\x00\x00\n\x00\x00\x00sulfur_dio\x1b\x00\x00\x00\xd3\xa7\xabA' self.assertEqual(parse_bucket(data), ['sulfur_dio', 27, 21.456945419311523]) def test_parse_bin(self): data = b'\x82\x00\x00\x00\x03\x00\x00\x00ice\x06\x00\x00\x00ethene\x07\x00\x00\x00methane\x0b\x00\x00\x00carbon_mono\n\x00\x00\x00carbon_dio\x07\x00\x00\x00ammonia\x0c\x00\x00\x00hydrogen_sul\n\x00\x00\x00sulfur_dio\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' self.assertEqual(parse_topic('srcp2_msgs/HaulerMsg', data), [['ice', 'ethene', 'methane', 'carbon_mono', 'carbon_dio', 'ammonia', 'hydrogen_sul', 'sulfur_dio'], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]) def test_parse_score_qual2(self): data = b'\x87\x00\x00\x00\x03\x00\x00\x00ice\x06\x00\x00\x00ethene\x07\x00\x00\x00methane' + \ b'\x08\x00\x00\x00carbon_mono\n\x00\x00\x00carbon_dio\x07\x00\x00\x00ammonia\x0c\x00\x00\x00' + \ b'hydrogen_sul\n\x00\x00\x00sulfur_dio\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + \ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + \ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00' self.assertEqual(parse_topic('srcp2_msgs/Qual2ScoringMsg', data), [0, 0]) def test_radio(self): data = b'radio X30F60R [0, 100, 30]\n' bus = MagicMock() r = ROSMsgParser(config={}, bus=bus) r.slot_raw(timestamp=None, data=data) bus.publish.assert_called_with('radio', [b'X30F60R', b'[0, 100, 30]\n']) def test_publish_desired_speed(self): data = b'\x08\x00\x00\x00\x02\x00\x00\x00\x00\x06\x81\x14' # clock as 8 bytes bus = MagicMock() r = ROSMsgParser(config={}, bus=bus) r.slot_raw(timestamp=None, data=data) bus.publish.assert_called_with('sim_time_sec', 2) clock_data = b'\x08\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00' # clock 3s r.slot_raw(timestamp=None, data=clock_data) bus.publish.assert_called_with('sim_time_sec', 3) # initially desired speed is None -> no cmd r.slot_desired_speed(timestamp=None, data=[0, 0]) r.slot_raw(timestamp=None, data=clock_data) # ... asserting that the last call has been made in a particular way bus.publish.assert_called_with('cmd', b'cmd_vel 0.000000 0.000000') # after update from 3D desired speed only extended cmd_vel_3d should be used r.slot_desired_speed_3d(timestamp=None, data=[[1, 2, 3], [4, 5, 6]]) r.slot_raw(timestamp=None, data=clock_data) bus.publish.assert_called_with('cmd', b'cmd_vel_3d 1.000000 2.000000 3.000000 4.000000 5.000000 6.000000') def test_publish_undefined_desired_speed(self): # for the drone it is important not to send any command until the very first desired speed is received pass # vim: expandtab sw=4 ts=4
en
0.95475
# clock as 8 bytes # clock 3s # initially desired speed is None -> no cmd # ... asserting that the last call has been made in a particular way # after update from 3D desired speed only extended cmd_vel_3d should be used # for the drone it is important not to send any command until the very first desired speed is received # vim: expandtab sw=4 ts=4
2.567743
3
src/PyEvalJS/runtime.py
Satireven/PyEvalJS
0
6620579
<reponame>Satireven/PyEvalJS<filename>src/PyEvalJS/runtime.py import sys import json from ctypes import * from .error import JSError from .utils import get_lib_path class Runtime: def __init__(self): self.chakraCore = CDLL(get_lib_path()) self._mcode = ["""var replace = function(k,v) { if (typeof v === 'function') { return Function.prototype.toString.call(v) } else if (v === undefined ) { return null } else { return v } };"""] self._count = 0 self._init_runtime() self._init_context() # call DllMain manually on non-Windows if sys.platform != "win32": # Attach process self.chakraCore.DllMain(0, 1, 0) # Attach main thread self.chakraCore.DllMain(0, 2, 0) def _init_runtime(self): self.runtime = c_void_p() self.chakraCore.JsCreateRuntime(0, 0, byref(self.runtime)) def _init_context(self): self.context = c_void_p() self.chakraCore.JsCreateContext(self.runtime, byref(self.context)) self.chakraCore.JsSetCurrentContext(self.context) def __del__(self): # Dispose runtime self.chakraCore.JsDisposeRuntime(self.runtime) def _get_exception(self): exception = c_void_p() self.chakraCore.JsGetAndClearException(byref(exception)) exception_id = c_void_p() self.chakraCore.JsCreatePropertyId(b"message", 7, byref(exception_id)) value = c_void_p() self.chakraCore.JsGetProperty(exception, exception_id, byref(value)) return self._js_value_to_str(value) def _js_value_to_str(self,jsResult): # Convert script result to String in JavaScript; redundant if script returns a String resultJSString = c_void_p() self.chakraCore.JsConvertValueToString(jsResult, byref(resultJSString)) stringLength = c_size_t() # Get buffer size needed for the result string self.chakraCore.JsCopyString(resultJSString, 0, 0, byref(stringLength)) resultSTR = create_string_buffer(stringLength.value + 1); # buffer is big enough to store the result # Get String from JsValueRef self.chakraCore.JsCopyString(resultJSString, byref(resultSTR), stringLength.value + 1, 0) # Set `null-ending` to the end resultSTRLastByte = (c_char * stringLength.value).from_address(addressof(resultSTR)) resultSTRLastByte = '\0' return resultSTR.value.decode('utf8') def eval(self,script): self._count += 1 if self._count == 5: # Reset Context Incase exploied self._init_context() self._count = 0 script = '\n'.join(self._mcode)+'''\nJSON.stringify(eval(%s),replace);'''%repr(script) script = create_string_buffer(script.encode('UTF-16')) fname = c_void_p() # create JsValueRef from filename self.chakraCore.JsCreateString("", 0, byref(fname)) scriptSource = c_void_p() # Create ArrayBuffer from script source self.chakraCore.JsCreateExternalArrayBuffer(script, len(script), 0, 0, byref(scriptSource)) jsResult = c_void_p() # Run the script. err = self.chakraCore.JsRun(scriptSource, 0 , fname, 0x02, byref(jsResult)) if err == 0: return json.loads(self._js_value_to_str(jsResult)) # js exception elif err == 196609: raise JSError(self._get_exception()) # other error else: raise Exception(jsResult) def set_variable(self,name,value): self.eval("var %s = %s" % (name, json.dumps(value))) return True def get_variable(self,name): value = self.eval("JSON.stringify((() => %s)())" % name) return json.loads(value) def require(self,js_file): with open(js_file,'r',encoding='utf-8',errors='ignore') as f: self._mcode.append(f.read()) def compile(self,script): '''Add some function to the context. But not Running, wait for Call.If you want to run it,just eval it.''' self._mcode.append(script) def call(self,identifier,*args): args = json.dumps(args) return self.eval("%s.apply(this, %s)"%(identifier, args)) def call_for_each(self,identifier,*args): '''Call the same function for each item in the list''' args = json.dumps(args) script = '''function callForEverybody(bodys) { return bodys.map(x => %s(x));} callForEverybody.apply(this,%s);'''%(identifier,args) return self.eval(script)
import sys import json from ctypes import * from .error import JSError from .utils import get_lib_path class Runtime: def __init__(self): self.chakraCore = CDLL(get_lib_path()) self._mcode = ["""var replace = function(k,v) { if (typeof v === 'function') { return Function.prototype.toString.call(v) } else if (v === undefined ) { return null } else { return v } };"""] self._count = 0 self._init_runtime() self._init_context() # call DllMain manually on non-Windows if sys.platform != "win32": # Attach process self.chakraCore.DllMain(0, 1, 0) # Attach main thread self.chakraCore.DllMain(0, 2, 0) def _init_runtime(self): self.runtime = c_void_p() self.chakraCore.JsCreateRuntime(0, 0, byref(self.runtime)) def _init_context(self): self.context = c_void_p() self.chakraCore.JsCreateContext(self.runtime, byref(self.context)) self.chakraCore.JsSetCurrentContext(self.context) def __del__(self): # Dispose runtime self.chakraCore.JsDisposeRuntime(self.runtime) def _get_exception(self): exception = c_void_p() self.chakraCore.JsGetAndClearException(byref(exception)) exception_id = c_void_p() self.chakraCore.JsCreatePropertyId(b"message", 7, byref(exception_id)) value = c_void_p() self.chakraCore.JsGetProperty(exception, exception_id, byref(value)) return self._js_value_to_str(value) def _js_value_to_str(self,jsResult): # Convert script result to String in JavaScript; redundant if script returns a String resultJSString = c_void_p() self.chakraCore.JsConvertValueToString(jsResult, byref(resultJSString)) stringLength = c_size_t() # Get buffer size needed for the result string self.chakraCore.JsCopyString(resultJSString, 0, 0, byref(stringLength)) resultSTR = create_string_buffer(stringLength.value + 1); # buffer is big enough to store the result # Get String from JsValueRef self.chakraCore.JsCopyString(resultJSString, byref(resultSTR), stringLength.value + 1, 0) # Set `null-ending` to the end resultSTRLastByte = (c_char * stringLength.value).from_address(addressof(resultSTR)) resultSTRLastByte = '\0' return resultSTR.value.decode('utf8') def eval(self,script): self._count += 1 if self._count == 5: # Reset Context Incase exploied self._init_context() self._count = 0 script = '\n'.join(self._mcode)+'''\nJSON.stringify(eval(%s),replace);'''%repr(script) script = create_string_buffer(script.encode('UTF-16')) fname = c_void_p() # create JsValueRef from filename self.chakraCore.JsCreateString("", 0, byref(fname)) scriptSource = c_void_p() # Create ArrayBuffer from script source self.chakraCore.JsCreateExternalArrayBuffer(script, len(script), 0, 0, byref(scriptSource)) jsResult = c_void_p() # Run the script. err = self.chakraCore.JsRun(scriptSource, 0 , fname, 0x02, byref(jsResult)) if err == 0: return json.loads(self._js_value_to_str(jsResult)) # js exception elif err == 196609: raise JSError(self._get_exception()) # other error else: raise Exception(jsResult) def set_variable(self,name,value): self.eval("var %s = %s" % (name, json.dumps(value))) return True def get_variable(self,name): value = self.eval("JSON.stringify((() => %s)())" % name) return json.loads(value) def require(self,js_file): with open(js_file,'r',encoding='utf-8',errors='ignore') as f: self._mcode.append(f.read()) def compile(self,script): '''Add some function to the context. But not Running, wait for Call.If you want to run it,just eval it.''' self._mcode.append(script) def call(self,identifier,*args): args = json.dumps(args) return self.eval("%s.apply(this, %s)"%(identifier, args)) def call_for_each(self,identifier,*args): '''Call the same function for each item in the list''' args = json.dumps(args) script = '''function callForEverybody(bodys) { return bodys.map(x => %s(x));} callForEverybody.apply(this,%s);'''%(identifier,args) return self.eval(script)
en
0.433278
var replace = function(k,v) { if (typeof v === 'function') { return Function.prototype.toString.call(v) } else if (v === undefined ) { return null } else { return v } }; # call DllMain manually on non-Windows # Attach process # Attach main thread # Dispose runtime # Convert script result to String in JavaScript; redundant if script returns a String # Get buffer size needed for the result string # buffer is big enough to store the result # Get String from JsValueRef # Set `null-ending` to the end # Reset Context Incase exploied \nJSON.stringify(eval(%s),replace); # create JsValueRef from filename # Create ArrayBuffer from script source # Run the script. # js exception # other error Add some function to the context. But not Running, wait for Call.If you want to run it,just eval it. Call the same function for each item in the list function callForEverybody(bodys) { return bodys.map(x => %s(x));} callForEverybody.apply(this,%s);
1.945695
2
tests/test_qa4sm_named_attrs.py
wpreimes/qa4sm-reader
0
6620580
<reponame>wpreimes/qa4sm-reader # -*- coding: utf-8 -*- from qa4sm_reader.handlers import QA4SMNamedAttributes from tests.test_qa4sm_attrs import test_attributes import unittest class TestQA4SMNamedAttributes(unittest.TestCase): def setUp(self) -> None: attrs = test_attributes() self.ismn = QA4SMNamedAttributes(id=6, short_name='ISMN', global_attrs=attrs) self.c3s17 = QA4SMNamedAttributes(id=1, short_name='C3S', global_attrs=attrs) self.c3s18 = QA4SMNamedAttributes(id=2, short_name='C3S', global_attrs=attrs) self.smos = QA4SMNamedAttributes(id=3, short_name='SMOS', global_attrs=attrs) self.smap = QA4SMNamedAttributes(id=4, short_name='SMAP', global_attrs=attrs) self.ascat = QA4SMNamedAttributes(id=5, short_name='ASCAT', global_attrs=attrs) def test_eq(self): assert self.ismn != self.ascat assert self.ismn == self.ismn assert self.ascat == self.ascat def test_names(self): assert self.ismn.pretty_name() == 'ISMN' assert self.ismn.pretty_version() == '20180712 mini testset' assert self.c3s17.pretty_name() == 'C3S' assert self.c3s17.pretty_version() == 'v201706' assert self.c3s18.pretty_name() == 'C3S' assert self.c3s18.pretty_version() == 'v201812' assert self.smos.pretty_name() == 'SMOS IC' assert self.smos.pretty_version() == 'V.105 Ascending' assert self.smap.pretty_name() == 'SMAP level 3' assert self.smap.pretty_version() == 'v5 PM/ascending' assert self.ascat.pretty_name() == 'H-SAF ASCAT SSM CDR' assert self.ascat.pretty_version() == 'H113' if __name__ == '__main__': suite = unittest.TestSuite() suite.addTest(TestQA4SMNamedAttributes("test_eq")) runner = unittest.TextTestRunner() runner.run(suite)
# -*- coding: utf-8 -*- from qa4sm_reader.handlers import QA4SMNamedAttributes from tests.test_qa4sm_attrs import test_attributes import unittest class TestQA4SMNamedAttributes(unittest.TestCase): def setUp(self) -> None: attrs = test_attributes() self.ismn = QA4SMNamedAttributes(id=6, short_name='ISMN', global_attrs=attrs) self.c3s17 = QA4SMNamedAttributes(id=1, short_name='C3S', global_attrs=attrs) self.c3s18 = QA4SMNamedAttributes(id=2, short_name='C3S', global_attrs=attrs) self.smos = QA4SMNamedAttributes(id=3, short_name='SMOS', global_attrs=attrs) self.smap = QA4SMNamedAttributes(id=4, short_name='SMAP', global_attrs=attrs) self.ascat = QA4SMNamedAttributes(id=5, short_name='ASCAT', global_attrs=attrs) def test_eq(self): assert self.ismn != self.ascat assert self.ismn == self.ismn assert self.ascat == self.ascat def test_names(self): assert self.ismn.pretty_name() == 'ISMN' assert self.ismn.pretty_version() == '20180712 mini testset' assert self.c3s17.pretty_name() == 'C3S' assert self.c3s17.pretty_version() == 'v201706' assert self.c3s18.pretty_name() == 'C3S' assert self.c3s18.pretty_version() == 'v201812' assert self.smos.pretty_name() == 'SMOS IC' assert self.smos.pretty_version() == 'V.105 Ascending' assert self.smap.pretty_name() == 'SMAP level 3' assert self.smap.pretty_version() == 'v5 PM/ascending' assert self.ascat.pretty_name() == 'H-SAF ASCAT SSM CDR' assert self.ascat.pretty_version() == 'H113' if __name__ == '__main__': suite = unittest.TestSuite() suite.addTest(TestQA4SMNamedAttributes("test_eq")) runner = unittest.TextTestRunner() runner.run(suite)
en
0.769321
# -*- coding: utf-8 -*-
2.205387
2
memegen/meme_template.py
WalterSimoncini/memegen-api
0
6620581
from enum import Enum class MemeTemplate(str, Enum): DRAKE = "drake"
from enum import Enum class MemeTemplate(str, Enum): DRAKE = "drake"
none
1
2.536753
3
helper_code/concatenate_videos.py
BrancoLab/escape-analysis
0
6620582
<gh_stars>0 ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' -----------# Display a saved video -------------------------------- ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' import cv2 import numpy as np import glob # ------------------------------------------ # Select video file name and folder location # ------------------------------------------ save_folder = 'D:\\data\\Summary Plots\\videos\\' ''' SV1 - visualization ''' # file_loc = 'D:\\data\\Paper\\Circle wall down dark\\' # mouse_names = ['CA4030'] # save_name = 'SV1 real.mp4' ''' SV2 - homing vector ''' # file_loc = 'D:\\data\\Paper\\Circle wall up\\' # mouse_names = ['CA3482', 'CA7190', 'CA7170'] #, 'CA3210'] # 'CA3471', 'CA3483', # save_name = 'SV1.mp4' ''' SV3 - obstacle ''' # file_loc1 = 'D:\\data\\Paper\\Circle wall down\\' # file_loc2 = 'D:\\data\\Paper\\Circle lights on off (baseline)\\' # # file_locs = [file_loc1, file_loc2, file_loc2, file_loc2, file_loc1, file_loc1, file_loc2, file_loc2] # # mouse_names = ['CA6940', 'CA7503', 'CA8110', 'CA8140', 'CA3400', 'CA3151', 'CA7491', 'CA8190'] # file_locs = [file_loc1, file_loc2, file_loc2, file_loc1, file_loc1, file_loc2] # file_loc2, file_loc2, # mouse_names = ['CA6940', 'CA7503','CA8110', 'CA3400', 'CA3380'] # 'CA7491', 'CA8140', 'CA8190', # save_name = 'SV_trial1.mp4' # # file_locs = [file_loc1, file_loc1, file_loc1] # file_loc2, file_loc2, # mouse_names = ['CA3400', 'CA3410','CA3380'] # 'CA7491', 'CA8140', 'CA8190', # save_name = 'SV_trial3.mp4' ''' SV4 - wall up ''' # file_loc = 'D:\\data\\Paper\\Circle wall up\\' # mouse_names = ['CA3210', 'CA3471', 'CA7170','CA7190'] # save_name = 'SV4.mp4' ''' SV5 - dark ''' # file_loc = 'D:\\data\\Paper\\Circle wall down dark\\' # mouse_names = ['CA8180','CA8792','CA8462','CA8794'] # save_name = 'SV5.mp4' # file_loc = 'D:\\data\\Paper\\Circle wall down (dark non naive)\\' # mouse_names = ['CA3720','CA8541','CA3740','CA8551'] # save_name = 'SV5II.mp4' ''' SV6 - wall down ''' # file_loc = 'D:\\data\\Paper\\Circle wall down\\' # mouse_names = ['CA3380', 'CA3410', 'CA3400','CA6950', 'CA3390', 'CA3151'] # save_name = 'SV6.mp4' file_loc1 = 'D:\\data\\Paper\\Circle wall down\\' file_loc2 = 'D:\\data\\Paper\\Circle wall down (no baseline)\\' mouse_names = ['CA3151', 'CA3410', 'CA3410', 'CA6970','CA3390','CA3390'] file_locs = [file_loc1, file_loc1, file_loc1, file_loc2, file_loc1, file_loc1] save_name = 'SV6 II.mp4' ''' SV7 - wall left ''' # file_loc = 'D:\\data\\Paper\\Square wall moves left\\' # mouse_names = ['CA6950', 'CA8180', 'CA8180', 'CA7501', 'CA6990', 'CA7220'] # save_name = 'SV7.mp4' ''' SV8 - food ''' # file_loc = 'D:\\data\\Paper\\Circle food wall down\\' # mouse_names = ['CA8380','CA8380', 'CA8390', 'CA8360'] # save_name = 'SV8.mp4' # mouse_names = ['CA8380', 'CA8370', 'CA8360', 'CA8360'] # save_name = 'SV8 II.mp4' save_fps = 30 color = True # more options show_video = True display_frame_rate = 1000 # set up video writer fourcc_data = cv2.VideoWriter_fourcc(*"XVID") # LJPG for lossless, XVID for compressed data_video = cv2.VideoWriter(save_folder + save_name, fourcc_data, save_fps, (720, 720), color) # loop across all videos for m, mouse in enumerate(mouse_names): # vids to concatenate # vid_paths = glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[:2] # 2 # vid_paths = [glob.glob(file_locs[m] + mouse + '\\' + '*vid (DLC)*')[0]] # 3 # vid_paths = [glob.glob(file_locs[m] + mouse + '\\' + '*vid (DLC)*')[2]] # 3 II # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[3]] # 4 # if not mouse == 'CA8792' and not mouse == 'CA8180': vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[3]] # 5 I # else: vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[1]] # 5 I # if m==0: i = 2 # elif m == 1: i = 4 # elif m == 2: i = 3 # elif m == 3: i = 1 # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[i]] # 5 II # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[3]] # 6 if m==0: i = 4 elif m == 1: i = 6 elif m == 2: i = 7 elif m == 3: i = 1 elif m == 4: i = 5 elif m == 5: i = 6 vid_paths = [glob.glob(file_locs[m] + mouse + '\\' + '*vid (DLC)*')[i]] # 6 II # if m==0: i = 1 # elif m == 1: i = 2 # elif m == 2: i = 3 # elif m == 3: i = 3 # elif m == 4: i = 2 # elif m == 5: i = 2 # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[i]] # 7 # if m==0: i = 6 # elif m == 1: i = 10 # elif m == 2: i = 6 # elif m == 3: i = 7 # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[i]] # 8 # if m==0: i = 18 # elif m == 1: i = 17 # elif m == 2: i = 15 # elif m == 3: i = 19 # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[i]] # 8 II for vid_path in vid_paths: # --------------------------- # Play video and save video # --------------------------- vid = cv2.VideoCapture(vid_path) while True: ret, frame = vid.read() # read the frame frame_num = vid.get(cv2.CAP_PROP_POS_FRAMES) if ret: # write the new video data_video.write(frame) # display the video if show_video: cv2.imshow('movie', frame) if cv2.waitKey(int(1000 / display_frame_rate)) & 0xFF == ord('q'): break # if can't read the video else: break # close the video files vid.release() data_video.release() print('done')
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' -----------# Display a saved video -------------------------------- ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' import cv2 import numpy as np import glob # ------------------------------------------ # Select video file name and folder location # ------------------------------------------ save_folder = 'D:\\data\\Summary Plots\\videos\\' ''' SV1 - visualization ''' # file_loc = 'D:\\data\\Paper\\Circle wall down dark\\' # mouse_names = ['CA4030'] # save_name = 'SV1 real.mp4' ''' SV2 - homing vector ''' # file_loc = 'D:\\data\\Paper\\Circle wall up\\' # mouse_names = ['CA3482', 'CA7190', 'CA7170'] #, 'CA3210'] # 'CA3471', 'CA3483', # save_name = 'SV1.mp4' ''' SV3 - obstacle ''' # file_loc1 = 'D:\\data\\Paper\\Circle wall down\\' # file_loc2 = 'D:\\data\\Paper\\Circle lights on off (baseline)\\' # # file_locs = [file_loc1, file_loc2, file_loc2, file_loc2, file_loc1, file_loc1, file_loc2, file_loc2] # # mouse_names = ['CA6940', 'CA7503', 'CA8110', 'CA8140', 'CA3400', 'CA3151', 'CA7491', 'CA8190'] # file_locs = [file_loc1, file_loc2, file_loc2, file_loc1, file_loc1, file_loc2] # file_loc2, file_loc2, # mouse_names = ['CA6940', 'CA7503','CA8110', 'CA3400', 'CA3380'] # 'CA7491', 'CA8140', 'CA8190', # save_name = 'SV_trial1.mp4' # # file_locs = [file_loc1, file_loc1, file_loc1] # file_loc2, file_loc2, # mouse_names = ['CA3400', 'CA3410','CA3380'] # 'CA7491', 'CA8140', 'CA8190', # save_name = 'SV_trial3.mp4' ''' SV4 - wall up ''' # file_loc = 'D:\\data\\Paper\\Circle wall up\\' # mouse_names = ['CA3210', 'CA3471', 'CA7170','CA7190'] # save_name = 'SV4.mp4' ''' SV5 - dark ''' # file_loc = 'D:\\data\\Paper\\Circle wall down dark\\' # mouse_names = ['CA8180','CA8792','CA8462','CA8794'] # save_name = 'SV5.mp4' # file_loc = 'D:\\data\\Paper\\Circle wall down (dark non naive)\\' # mouse_names = ['CA3720','CA8541','CA3740','CA8551'] # save_name = 'SV5II.mp4' ''' SV6 - wall down ''' # file_loc = 'D:\\data\\Paper\\Circle wall down\\' # mouse_names = ['CA3380', 'CA3410', 'CA3400','CA6950', 'CA3390', 'CA3151'] # save_name = 'SV6.mp4' file_loc1 = 'D:\\data\\Paper\\Circle wall down\\' file_loc2 = 'D:\\data\\Paper\\Circle wall down (no baseline)\\' mouse_names = ['CA3151', 'CA3410', 'CA3410', 'CA6970','CA3390','CA3390'] file_locs = [file_loc1, file_loc1, file_loc1, file_loc2, file_loc1, file_loc1] save_name = 'SV6 II.mp4' ''' SV7 - wall left ''' # file_loc = 'D:\\data\\Paper\\Square wall moves left\\' # mouse_names = ['CA6950', 'CA8180', 'CA8180', 'CA7501', 'CA6990', 'CA7220'] # save_name = 'SV7.mp4' ''' SV8 - food ''' # file_loc = 'D:\\data\\Paper\\Circle food wall down\\' # mouse_names = ['CA8380','CA8380', 'CA8390', 'CA8360'] # save_name = 'SV8.mp4' # mouse_names = ['CA8380', 'CA8370', 'CA8360', 'CA8360'] # save_name = 'SV8 II.mp4' save_fps = 30 color = True # more options show_video = True display_frame_rate = 1000 # set up video writer fourcc_data = cv2.VideoWriter_fourcc(*"XVID") # LJPG for lossless, XVID for compressed data_video = cv2.VideoWriter(save_folder + save_name, fourcc_data, save_fps, (720, 720), color) # loop across all videos for m, mouse in enumerate(mouse_names): # vids to concatenate # vid_paths = glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[:2] # 2 # vid_paths = [glob.glob(file_locs[m] + mouse + '\\' + '*vid (DLC)*')[0]] # 3 # vid_paths = [glob.glob(file_locs[m] + mouse + '\\' + '*vid (DLC)*')[2]] # 3 II # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[3]] # 4 # if not mouse == 'CA8792' and not mouse == 'CA8180': vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[3]] # 5 I # else: vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[1]] # 5 I # if m==0: i = 2 # elif m == 1: i = 4 # elif m == 2: i = 3 # elif m == 3: i = 1 # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[i]] # 5 II # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[3]] # 6 if m==0: i = 4 elif m == 1: i = 6 elif m == 2: i = 7 elif m == 3: i = 1 elif m == 4: i = 5 elif m == 5: i = 6 vid_paths = [glob.glob(file_locs[m] + mouse + '\\' + '*vid (DLC)*')[i]] # 6 II # if m==0: i = 1 # elif m == 1: i = 2 # elif m == 2: i = 3 # elif m == 3: i = 3 # elif m == 4: i = 2 # elif m == 5: i = 2 # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[i]] # 7 # if m==0: i = 6 # elif m == 1: i = 10 # elif m == 2: i = 6 # elif m == 3: i = 7 # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[i]] # 8 # if m==0: i = 18 # elif m == 1: i = 17 # elif m == 2: i = 15 # elif m == 3: i = 19 # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[i]] # 8 II for vid_path in vid_paths: # --------------------------- # Play video and save video # --------------------------- vid = cv2.VideoCapture(vid_path) while True: ret, frame = vid.read() # read the frame frame_num = vid.get(cv2.CAP_PROP_POS_FRAMES) if ret: # write the new video data_video.write(frame) # display the video if show_video: cv2.imshow('movie', frame) if cv2.waitKey(int(1000 / display_frame_rate)) & 0xFF == ord('q'): break # if can't read the video else: break # close the video files vid.release() data_video.release() print('done')
en
0.552523
-----------# Display a saved video -------------------------------- # ------------------------------------------ # Select video file name and folder location # ------------------------------------------ SV1 - visualization # file_loc = 'D:\\data\\Paper\\Circle wall down dark\\' # mouse_names = ['CA4030'] # save_name = 'SV1 real.mp4' SV2 - homing vector # file_loc = 'D:\\data\\Paper\\Circle wall up\\' # mouse_names = ['CA3482', 'CA7190', 'CA7170'] #, 'CA3210'] # 'CA3471', 'CA3483', # save_name = 'SV1.mp4' SV3 - obstacle # file_loc1 = 'D:\\data\\Paper\\Circle wall down\\' # file_loc2 = 'D:\\data\\Paper\\Circle lights on off (baseline)\\' # # file_locs = [file_loc1, file_loc2, file_loc2, file_loc2, file_loc1, file_loc1, file_loc2, file_loc2] # # mouse_names = ['CA6940', 'CA7503', 'CA8110', 'CA8140', 'CA3400', 'CA3151', 'CA7491', 'CA8190'] # file_locs = [file_loc1, file_loc2, file_loc2, file_loc1, file_loc1, file_loc2] # file_loc2, file_loc2, # mouse_names = ['CA6940', 'CA7503','CA8110', 'CA3400', 'CA3380'] # 'CA7491', 'CA8140', 'CA8190', # save_name = 'SV_trial1.mp4' # # file_locs = [file_loc1, file_loc1, file_loc1] # file_loc2, file_loc2, # mouse_names = ['CA3400', 'CA3410','CA3380'] # 'CA7491', 'CA8140', 'CA8190', # save_name = 'SV_trial3.mp4' SV4 - wall up # file_loc = 'D:\\data\\Paper\\Circle wall up\\' # mouse_names = ['CA3210', 'CA3471', 'CA7170','CA7190'] # save_name = 'SV4.mp4' SV5 - dark # file_loc = 'D:\\data\\Paper\\Circle wall down dark\\' # mouse_names = ['CA8180','CA8792','CA8462','CA8794'] # save_name = 'SV5.mp4' # file_loc = 'D:\\data\\Paper\\Circle wall down (dark non naive)\\' # mouse_names = ['CA3720','CA8541','CA3740','CA8551'] # save_name = 'SV5II.mp4' SV6 - wall down # file_loc = 'D:\\data\\Paper\\Circle wall down\\' # mouse_names = ['CA3380', 'CA3410', 'CA3400','CA6950', 'CA3390', 'CA3151'] # save_name = 'SV6.mp4' SV7 - wall left # file_loc = 'D:\\data\\Paper\\Square wall moves left\\' # mouse_names = ['CA6950', 'CA8180', 'CA8180', 'CA7501', 'CA6990', 'CA7220'] # save_name = 'SV7.mp4' SV8 - food # file_loc = 'D:\\data\\Paper\\Circle food wall down\\' # mouse_names = ['CA8380','CA8380', 'CA8390', 'CA8360'] # save_name = 'SV8.mp4' # mouse_names = ['CA8380', 'CA8370', 'CA8360', 'CA8360'] # save_name = 'SV8 II.mp4' # more options # set up video writer # LJPG for lossless, XVID for compressed # loop across all videos # vids to concatenate # vid_paths = glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[:2] # 2 # vid_paths = [glob.glob(file_locs[m] + mouse + '\\' + '*vid (DLC)*')[0]] # 3 # vid_paths = [glob.glob(file_locs[m] + mouse + '\\' + '*vid (DLC)*')[2]] # 3 II # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[3]] # 4 # if not mouse == 'CA8792' and not mouse == 'CA8180': vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[3]] # 5 I # else: vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[1]] # 5 I # if m==0: i = 2 # elif m == 1: i = 4 # elif m == 2: i = 3 # elif m == 3: i = 1 # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[i]] # 5 II # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[3]] # 6 # 6 II # if m==0: i = 1 # elif m == 1: i = 2 # elif m == 2: i = 3 # elif m == 3: i = 3 # elif m == 4: i = 2 # elif m == 5: i = 2 # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[i]] # 7 # if m==0: i = 6 # elif m == 1: i = 10 # elif m == 2: i = 6 # elif m == 3: i = 7 # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[i]] # 8 # if m==0: i = 18 # elif m == 1: i = 17 # elif m == 2: i = 15 # elif m == 3: i = 19 # vid_paths = [glob.glob(file_loc + mouse + '\\' + '*vid (DLC)*')[i]] # 8 II # --------------------------- # Play video and save video # --------------------------- # read the frame # write the new video # display the video # if can't read the video # close the video files
1.969091
2
reprod.py
YBRua/DataMiningProject
0
6620583
<reponame>YBRua/DataMiningProject import copy import pickle import random import itertools import torch import torch.nn as nn import torch.nn.functional as F import numpy from typing import Dict, List from torch.utils.data import DataLoader, IterableDataset from freq_counter import FreqCounter from argparse import ArgumentParser from baseline.metric import batch_ndcg_torch, batched_average_precision, batched_hit_ratio, batched_reciprocal_rank import data_io from common import * from metrics import MAP, NDCG, HR, RR, Loss def parse_args(): parser = ArgumentParser() parser.add_argument( '--epoch', '-e', type=int, default=20, help='Number of training epoches') parser.add_argument( '--batchsize', '-b', type=int, default=64, help='Batch size') parser.add_argument( '--dataset', '-d', choices=['bookcross', 'music'], default='bookcross', help='Dataset, can be one of bobookcrossok or music') parser.add_argument( '--device', type=str, default='cuda:0', help='PyTorch style device to run the model') return parser.parse_args() def prepare_dataset(dataset: str): assert dataset in ['bookcross', 'music'], f'Invalid dataset: {dataset}' train_raw = data_io.load_rating_file_as_matrix(f'data/{dataset}.train.rating') train_smp = data_io.load_train_entries(f'data/{dataset}.train.rating') test = data_io.load_test_entries(f'data/{dataset}', False) if dataset == 'bookcross': feature_dict_path = 'data/book_info_bookcross' user_feat_path = 'data/user_hist_withinfo_bookcross' else: feature_dict_path = 'data/song_info_music_HK' user_feat_path = 'data/user_hist_withinfo_music_HK' features_dict = pickle.load(open(feature_dict_path, 'rb')) user_features_dict = pickle.load(open(user_feat_path, 'rb')) return train_raw, train_smp, test, features_dict, user_features_dict class SelfAttention(nn.Module): def __init__(self, nhead, i, kq, v): super().__init__() self.attn_k = nn.Linear(i, kq, bias=False) self.attn_q = nn.Linear(i, kq, bias=False) self.attn_v = nn.Linear(i, v, bias=False) self.nhead = nhead def forward(self, x): # x: ...ni k = self.attn_k(x).reshape(*x.shape[:-1], self.nhead, -1) q = self.attn_q(x).reshape(*x.shape[:-1], self.nhead, -1) v = self.attn_v(x).reshape(*x.shape[:-1], self.nhead, -1) attn = torch.softmax( torch.einsum("...nhd,...mhd->...nmh", k, q) / k.shape[-1] ** 0.5, -2 ) return torch.einsum("...nmh,...mhd->...nhd", attn, v).flatten(-2) class SAF(nn.Module): def __init__(self): super().__init__() self.user_embed = nn.Embedding(90000, 300) self.item_embed = nn.Embedding(90000, 300) with torch.no_grad(): self.user_embed.weight.uniform_(-0.05, 0.05) self.item_embed.weight.uniform_(-0.05, 0.05) self.attn = SelfAttention(5, 300, 600, 600) self.drop = nn.Dropout(0.4) self.proj = nn.Linear(600, 300) self.linear = nn.Linear(300, 1) self.norm = nn.LayerNorm(300) def encode(self, user_features, item_features): # bNMd item = self.item_embed(item_features) # bL4d user = self.user_embed(user_features).mean(2) # bLd user = user.unsqueeze(1).repeat(1, item.shape[1], 1, 1) # bNLd sa_pre = torch.cat([user, item], 2) # bN (L+M) d sa_post = self.norm(self.proj(self.attn(sa_pre)) + sa_pre).mean(-2) # bNd return sa_post def forward(self, user_ids, item_ids, user_features, item_features, labels=None): sa_post = self.encode(user_features, item_features) return self.linear(self.drop(sa_post)).squeeze() class RankingAwareNet(nn.Module): def __init__(self, encoder: SAF): super().__init__() self.encoder = encoder self.impf = nn.Sequential( nn.Linear(300, 1024), nn.LayerNorm(1024), nn.ReLU(), ) self.cls = nn.Sequential( nn.Dropout(), nn.Linear(1324, 1) ) def forward(self, user_ids, item_ids, user_features, item_features, labels=None): with torch.no_grad(): sa_post = self.encoder.encode(user_features, item_features) impf = self.impf(sa_post).max(-2)[0].unsqueeze(-2).repeat(1, sa_post.shape[1], 1) pf = torch.cat([impf, sa_post], dim=-1) return self.cls(pf).squeeze() def get_train_instances(train, ufd, ifd): user_input, item_input, labels = [], [], [] user_ids = [] item_ids = [] for (u, i) in train.keys(): user_ids.append(u) item_ids.append(i) user_input.append(numpy.array(ufd[u]).reshape(-1, 4)) item_input.append(numpy.array(ifd[i][:4])[None]) if train[(u, i)] == 1: labels.append(1) if train[(u, i)] == -1: labels.append(0) return [*zip(user_ids, item_ids, user_input, item_input, labels)] class Rekommand(IterableDataset): def __init__( self, entries: List[data_io.TestEntry], item_feature_dict: Dict[int, List[int]], user_feature_dict: Dict[int, List[int]], pos_per_entry: int = 5, neg_per_entry: int = 50, background_neg_samples: int = 0, full: bool = False ) -> None: super().__init__() self.full = full self.ppe = pos_per_entry self.npe = neg_per_entry self.bns = background_neg_samples self.entries = entries self.ifd = item_feature_dict self.ufd = user_feature_dict self.valid_items = list(self.ifd.keys()) self.cum_weights = [*itertools.accumulate(map( lambda x: len(x.positives) + len(x.negatives), self.entries ))] def __iter__(self): rng = len(self.entries) if self.full else 2 ** 30 for i in range(rng): entry = self.entries[i] if self.full else\ random.choices(self.entries, cum_weights=self.cum_weights, k=1)[0] entry = copy.deepcopy(entry) if not self.full: if not len(entry.positives): continue entry.positives = random.choices(entry.positives, k=self.ppe) # entry.negatives = random.choices(entry.negatives, k=self.npe) entry.negatives = random.choices(self.valid_items, k=self.npe) items = numpy.array(list(entry.positives) + list(entry.negatives)) item_features = numpy.array([self.ifd[x][:4] for x in items]) user_features = numpy.array(self.ufd[entry.id]).reshape(-1, 4) labels = numpy.concatenate([ numpy.ones_like(entry.positives), numpy.zeros_like(entry.negatives) ]) randperm = numpy.random.permutation(len(items)) yield entry.id, items[randperm], user_features, item_features[randperm], labels[randperm] def __length_hint__(self): return len(self.entries) if self.full else 2 * len(self.entries) def main(): args = parse_args() DEVICE = torch.device(args.device) BATCH_SIZE = args.batchsize EPOCHES = args.epoch train_raw, train_smp, test, features_dict, user_features_dict = prepare_dataset(args.dataset) target = FreqCounter(train_smp) train_smp = Rekommand(train_smp, features_dict, user_features_dict) test = Rekommand(test, features_dict, user_features_dict, full=True) train_loader_smp = DataLoader(train_smp, BATCH_SIZE, num_workers=4) test_loader = DataLoader(test, BATCH_SIZE, num_workers=1) val_stats = run_epoch( target, test_loader, [ Loss(), RR(5), MAP(3), MAP(5), NDCG(3), NDCG(5), HR(3), HR(5) ], 1 ) print(val_stats) model = RankingAwareNet(SAF()).to(DEVICE) target = RankingAwareNet(SAF()).to(DEVICE) enc_opt = torch.optim.Adam(model.encoder.parameters()) opt = torch.optim.Adam(model.parameters()) best_acc = -1 train = get_train_instances(train_raw, user_features_dict, features_dict) for epoch in range(EPOCHES): train_loader = DataLoader(train, BATCH_SIZE, num_workers=2, shuffle=True) ent_stats = run_epoch(model.encoder, train_loader, [Loss()], epoch, enc_opt) train_sub = TruncatedIter(train_loader_smp, train_smp.__length_hint__() // BATCH_SIZE + 1) frt_stats = run_epoch(model, train_sub, [Loss()], epoch, opt) lerp = epoch / (epoch + 1) with torch.no_grad(): target.load_state_dict(merge_state_dicts([ scale_state_dict(target.state_dict(), lerp), scale_state_dict(model.state_dict(), 1 - lerp) ])) val_stats = run_epoch( target, test_loader, [ Loss(), RR(5), MAP(3), MAP(5), NDCG(3), NDCG(5), HR(3), HR(5) ], epoch ) if epoch == 0: write_log( "epoch", "encoder_loss", "finetune_loss", "val_loss", "val_rr@5", "val_map@3", "val_map@5", "val_ndcg@3", "val_ndcg@5", "val_hr@3", "val_hr@5" ) write_log( epoch, ent_stats['Loss'], frt_stats['Loss'], val_stats['Loss'], val_stats['RR@5'], val_stats['MAP@3'], val_stats['MAP@5'], val_stats['NDCG@3'], val_stats['NDCG@5'], val_stats['HR@3'], val_stats['HR@5'] ) if val_stats['NDCG@3'] > best_acc: best_acc = val_stats['NDCG@3'] torch.save(model.state_dict(), "e2e.dat") print("New best!") if __name__ == "__main__": main()
import copy import pickle import random import itertools import torch import torch.nn as nn import torch.nn.functional as F import numpy from typing import Dict, List from torch.utils.data import DataLoader, IterableDataset from freq_counter import FreqCounter from argparse import ArgumentParser from baseline.metric import batch_ndcg_torch, batched_average_precision, batched_hit_ratio, batched_reciprocal_rank import data_io from common import * from metrics import MAP, NDCG, HR, RR, Loss def parse_args(): parser = ArgumentParser() parser.add_argument( '--epoch', '-e', type=int, default=20, help='Number of training epoches') parser.add_argument( '--batchsize', '-b', type=int, default=64, help='Batch size') parser.add_argument( '--dataset', '-d', choices=['bookcross', 'music'], default='bookcross', help='Dataset, can be one of bobookcrossok or music') parser.add_argument( '--device', type=str, default='cuda:0', help='PyTorch style device to run the model') return parser.parse_args() def prepare_dataset(dataset: str): assert dataset in ['bookcross', 'music'], f'Invalid dataset: {dataset}' train_raw = data_io.load_rating_file_as_matrix(f'data/{dataset}.train.rating') train_smp = data_io.load_train_entries(f'data/{dataset}.train.rating') test = data_io.load_test_entries(f'data/{dataset}', False) if dataset == 'bookcross': feature_dict_path = 'data/book_info_bookcross' user_feat_path = 'data/user_hist_withinfo_bookcross' else: feature_dict_path = 'data/song_info_music_HK' user_feat_path = 'data/user_hist_withinfo_music_HK' features_dict = pickle.load(open(feature_dict_path, 'rb')) user_features_dict = pickle.load(open(user_feat_path, 'rb')) return train_raw, train_smp, test, features_dict, user_features_dict class SelfAttention(nn.Module): def __init__(self, nhead, i, kq, v): super().__init__() self.attn_k = nn.Linear(i, kq, bias=False) self.attn_q = nn.Linear(i, kq, bias=False) self.attn_v = nn.Linear(i, v, bias=False) self.nhead = nhead def forward(self, x): # x: ...ni k = self.attn_k(x).reshape(*x.shape[:-1], self.nhead, -1) q = self.attn_q(x).reshape(*x.shape[:-1], self.nhead, -1) v = self.attn_v(x).reshape(*x.shape[:-1], self.nhead, -1) attn = torch.softmax( torch.einsum("...nhd,...mhd->...nmh", k, q) / k.shape[-1] ** 0.5, -2 ) return torch.einsum("...nmh,...mhd->...nhd", attn, v).flatten(-2) class SAF(nn.Module): def __init__(self): super().__init__() self.user_embed = nn.Embedding(90000, 300) self.item_embed = nn.Embedding(90000, 300) with torch.no_grad(): self.user_embed.weight.uniform_(-0.05, 0.05) self.item_embed.weight.uniform_(-0.05, 0.05) self.attn = SelfAttention(5, 300, 600, 600) self.drop = nn.Dropout(0.4) self.proj = nn.Linear(600, 300) self.linear = nn.Linear(300, 1) self.norm = nn.LayerNorm(300) def encode(self, user_features, item_features): # bNMd item = self.item_embed(item_features) # bL4d user = self.user_embed(user_features).mean(2) # bLd user = user.unsqueeze(1).repeat(1, item.shape[1], 1, 1) # bNLd sa_pre = torch.cat([user, item], 2) # bN (L+M) d sa_post = self.norm(self.proj(self.attn(sa_pre)) + sa_pre).mean(-2) # bNd return sa_post def forward(self, user_ids, item_ids, user_features, item_features, labels=None): sa_post = self.encode(user_features, item_features) return self.linear(self.drop(sa_post)).squeeze() class RankingAwareNet(nn.Module): def __init__(self, encoder: SAF): super().__init__() self.encoder = encoder self.impf = nn.Sequential( nn.Linear(300, 1024), nn.LayerNorm(1024), nn.ReLU(), ) self.cls = nn.Sequential( nn.Dropout(), nn.Linear(1324, 1) ) def forward(self, user_ids, item_ids, user_features, item_features, labels=None): with torch.no_grad(): sa_post = self.encoder.encode(user_features, item_features) impf = self.impf(sa_post).max(-2)[0].unsqueeze(-2).repeat(1, sa_post.shape[1], 1) pf = torch.cat([impf, sa_post], dim=-1) return self.cls(pf).squeeze() def get_train_instances(train, ufd, ifd): user_input, item_input, labels = [], [], [] user_ids = [] item_ids = [] for (u, i) in train.keys(): user_ids.append(u) item_ids.append(i) user_input.append(numpy.array(ufd[u]).reshape(-1, 4)) item_input.append(numpy.array(ifd[i][:4])[None]) if train[(u, i)] == 1: labels.append(1) if train[(u, i)] == -1: labels.append(0) return [*zip(user_ids, item_ids, user_input, item_input, labels)] class Rekommand(IterableDataset): def __init__( self, entries: List[data_io.TestEntry], item_feature_dict: Dict[int, List[int]], user_feature_dict: Dict[int, List[int]], pos_per_entry: int = 5, neg_per_entry: int = 50, background_neg_samples: int = 0, full: bool = False ) -> None: super().__init__() self.full = full self.ppe = pos_per_entry self.npe = neg_per_entry self.bns = background_neg_samples self.entries = entries self.ifd = item_feature_dict self.ufd = user_feature_dict self.valid_items = list(self.ifd.keys()) self.cum_weights = [*itertools.accumulate(map( lambda x: len(x.positives) + len(x.negatives), self.entries ))] def __iter__(self): rng = len(self.entries) if self.full else 2 ** 30 for i in range(rng): entry = self.entries[i] if self.full else\ random.choices(self.entries, cum_weights=self.cum_weights, k=1)[0] entry = copy.deepcopy(entry) if not self.full: if not len(entry.positives): continue entry.positives = random.choices(entry.positives, k=self.ppe) # entry.negatives = random.choices(entry.negatives, k=self.npe) entry.negatives = random.choices(self.valid_items, k=self.npe) items = numpy.array(list(entry.positives) + list(entry.negatives)) item_features = numpy.array([self.ifd[x][:4] for x in items]) user_features = numpy.array(self.ufd[entry.id]).reshape(-1, 4) labels = numpy.concatenate([ numpy.ones_like(entry.positives), numpy.zeros_like(entry.negatives) ]) randperm = numpy.random.permutation(len(items)) yield entry.id, items[randperm], user_features, item_features[randperm], labels[randperm] def __length_hint__(self): return len(self.entries) if self.full else 2 * len(self.entries) def main(): args = parse_args() DEVICE = torch.device(args.device) BATCH_SIZE = args.batchsize EPOCHES = args.epoch train_raw, train_smp, test, features_dict, user_features_dict = prepare_dataset(args.dataset) target = FreqCounter(train_smp) train_smp = Rekommand(train_smp, features_dict, user_features_dict) test = Rekommand(test, features_dict, user_features_dict, full=True) train_loader_smp = DataLoader(train_smp, BATCH_SIZE, num_workers=4) test_loader = DataLoader(test, BATCH_SIZE, num_workers=1) val_stats = run_epoch( target, test_loader, [ Loss(), RR(5), MAP(3), MAP(5), NDCG(3), NDCG(5), HR(3), HR(5) ], 1 ) print(val_stats) model = RankingAwareNet(SAF()).to(DEVICE) target = RankingAwareNet(SAF()).to(DEVICE) enc_opt = torch.optim.Adam(model.encoder.parameters()) opt = torch.optim.Adam(model.parameters()) best_acc = -1 train = get_train_instances(train_raw, user_features_dict, features_dict) for epoch in range(EPOCHES): train_loader = DataLoader(train, BATCH_SIZE, num_workers=2, shuffle=True) ent_stats = run_epoch(model.encoder, train_loader, [Loss()], epoch, enc_opt) train_sub = TruncatedIter(train_loader_smp, train_smp.__length_hint__() // BATCH_SIZE + 1) frt_stats = run_epoch(model, train_sub, [Loss()], epoch, opt) lerp = epoch / (epoch + 1) with torch.no_grad(): target.load_state_dict(merge_state_dicts([ scale_state_dict(target.state_dict(), lerp), scale_state_dict(model.state_dict(), 1 - lerp) ])) val_stats = run_epoch( target, test_loader, [ Loss(), RR(5), MAP(3), MAP(5), NDCG(3), NDCG(5), HR(3), HR(5) ], epoch ) if epoch == 0: write_log( "epoch", "encoder_loss", "finetune_loss", "val_loss", "val_rr@5", "val_map@3", "val_map@5", "val_ndcg@3", "val_ndcg@5", "val_hr@3", "val_hr@5" ) write_log( epoch, ent_stats['Loss'], frt_stats['Loss'], val_stats['Loss'], val_stats['RR@5'], val_stats['MAP@3'], val_stats['MAP@5'], val_stats['NDCG@3'], val_stats['NDCG@5'], val_stats['HR@3'], val_stats['HR@5'] ) if val_stats['NDCG@3'] > best_acc: best_acc = val_stats['NDCG@3'] torch.save(model.state_dict(), "e2e.dat") print("New best!") if __name__ == "__main__": main()
en
0.322257
# x: ...ni # bNMd # bL4d # bLd # bNLd # bN (L+M) d # bNd # entry.negatives = random.choices(entry.negatives, k=self.npe)
2.04019
2
alexa/fetcher.py
InfernapeXavier/song-match
0
6620584
<filename>alexa/fetcher.py from pathlib import Path # python3 only from spotipy.oauth2 import SpotifyClientCredentials import spotipy import sys from dotenv import load_dotenv # Loading Spotify API Data from Env load_dotenv() # spotipy credentials manager sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) def songFetcher(artistName): # Fetches top 10 songs by artistName # Query to getartist URI results = sp.search(q='artist:' + artistName, type='artist') items = results['artists']['items'] if len(items) > 0: artist = items[0] urn = artist['uri'] # Query to fetch top tracks response = sp.artist_top_tracks(urn) trackList = [] for track in response['tracks']: trackList.append(track['name']) return trackList def getIndex(score): if score == '111': return 0 if score == '112': return 1 if score == '121': return 2 if score == '122': return 3 if score == '211': return 4 if score == '212': return 5 if score == '221': return 6 if score == '222': return 7
<filename>alexa/fetcher.py from pathlib import Path # python3 only from spotipy.oauth2 import SpotifyClientCredentials import spotipy import sys from dotenv import load_dotenv # Loading Spotify API Data from Env load_dotenv() # spotipy credentials manager sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) def songFetcher(artistName): # Fetches top 10 songs by artistName # Query to getartist URI results = sp.search(q='artist:' + artistName, type='artist') items = results['artists']['items'] if len(items) > 0: artist = items[0] urn = artist['uri'] # Query to fetch top tracks response = sp.artist_top_tracks(urn) trackList = [] for track in response['tracks']: trackList.append(track['name']) return trackList def getIndex(score): if score == '111': return 0 if score == '112': return 1 if score == '121': return 2 if score == '122': return 3 if score == '211': return 4 if score == '212': return 5 if score == '221': return 6 if score == '222': return 7
en
0.757608
# python3 only # Loading Spotify API Data from Env # spotipy credentials manager # Fetches top 10 songs by artistName # Query to getartist URI # Query to fetch top tracks
2.98893
3
demo/models/function/non_null_count.py
renovate-tests/django-check-constraint
1
6620585
from django.db.models import Func, SmallIntegerField, TextField from django.db.models.functions import Cast class NotNullCount(Func): function = "non_null_count" def __init__(self, *expressions, **extra): filter_exp = [ Cast(exp, TextField()) for exp in expressions if isinstance(exp, str) ] if "output_field" not in extra: extra["output_field"] = SmallIntegerField() if len(expressions) < 2: raise ValueError("NotNullCount must take at least two expressions") super().__init__(*filter_exp, **extra) def as_sqlite(self, compiler, connection, **extra_context): connection.ops.check_expression_support(self) sql_parts = [] params = [] for arg in self.source_expressions: arg_sql, arg_params = compiler.compile(arg) sql_parts.append(arg_sql) params.extend(arg_params) data = {**self.extra, **extra_context} data["template"] = "%(function)s(%(expressions)s)" arg_joiner = self.arg_joiner data["function"] = self.function data["expressions"] = data["field"] = arg_joiner.join(sql_parts) template = data["template"] return template % data, params
from django.db.models import Func, SmallIntegerField, TextField from django.db.models.functions import Cast class NotNullCount(Func): function = "non_null_count" def __init__(self, *expressions, **extra): filter_exp = [ Cast(exp, TextField()) for exp in expressions if isinstance(exp, str) ] if "output_field" not in extra: extra["output_field"] = SmallIntegerField() if len(expressions) < 2: raise ValueError("NotNullCount must take at least two expressions") super().__init__(*filter_exp, **extra) def as_sqlite(self, compiler, connection, **extra_context): connection.ops.check_expression_support(self) sql_parts = [] params = [] for arg in self.source_expressions: arg_sql, arg_params = compiler.compile(arg) sql_parts.append(arg_sql) params.extend(arg_params) data = {**self.extra, **extra_context} data["template"] = "%(function)s(%(expressions)s)" arg_joiner = self.arg_joiner data["function"] = self.function data["expressions"] = data["field"] = arg_joiner.join(sql_parts) template = data["template"] return template % data, params
none
1
2.451294
2
battlebuild.py
manhon95/QMG_bot
0
6620586
<gh_stars>0 import telegram import sqlite3 import function import thread_lock import status_handler from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, MessageHandler, Filters #------------------------------------------Battle------------------------------------------ def battle_info(bot, country, space_list, card_id, lock_id, session): print('battle info') print(space_list) db = sqlite3.connect(session.get_db_dir()) name_list = function.get_name_list(space_list, db) print(name_list) session.space_list_buffer = space_list chat_id = db.execute("select playerid from country where id = :country;", {'country':country}).fetchall() text = 'Choose a space to battle' keyboard = [] for space in name_list: piece_list = db.execute("select country.name from piece inner join country on piece.control = country.id where piece.location = :location and piece.type != 'air';", {'location':space[0]}).fetchall() if len(piece_list) == 0: keyboard.append([InlineKeyboardButton(space[1] + " - empty", callback_data="['battle', '{}', {}, {}, {}]".format(country, space[0], card_id, lock_id))]) else: button = space[1] + " - " for piece in piece_list: button += piece[0] + " " keyboard.append([InlineKeyboardButton(button, callback_data="['battle', '{}', {}, {}, {}]".format(country, space[0], card_id, lock_id))]) keyboard.append([InlineKeyboardButton('Pass', callback_data="['battle', '{}', 'pass', {}, {}]".format(country, card_id, lock_id))]) reply_markup = InlineKeyboardMarkup(keyboard) return chat_id[0][0], text, reply_markup def battle_cb(bot, query, query_list, session): db = sqlite3.connect(session.get_db_dir()) if query_list[2] == 'confirm': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) battle(bot, query_list[1], query_list[3], query_list[4], query_list[5], session) session.release_lock(query_list[-1]) elif query_list[2] == 'pass': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) session.release_lock(query_list[-1]) else: if query_list[2] == 'back': info = battle_info(bot, query_list[1] , session.space_list_buffer, query_list[3], query_list[-1], session) text = info[1] reply_markup = info[2] else: location = db.execute("select name from space where spaceid = :id", {'id':query_list[2]}).fetchall() text = 'Battle ' + location[0][0] + ':' piece_list = db.execute("select country.name, piece.pieceid from piece inner join country on piece.control = country.id where piece.location = :location and piece.type != 'air';", {'location':query_list[2]}).fetchall() if len(piece_list) == 0: keyboard = [[InlineKeyboardButton('Confirm', callback_data="['battle', '{}', 'confirm', 0, {}, {}, {}]".format(query_list[1], query_list[2], query_list[3], query_list[-1]))], [InlineKeyboardButton('Back', callback_data="['battle', '{}', 'back', {}, {}]".format(query_list[1], query_list[3], query_list[-1]))]] elif len(piece_list) == 1: keyboard = [[InlineKeyboardButton('Confirm', callback_data="['battle', '{}', 'confirm', {}, {}, {}, {}]".format(query_list[1], piece_list[0][1], query_list[2], query_list[3], query_list[-1]))], [InlineKeyboardButton('Back', callback_data="['battle', '{}', 'back', {}, {}]".format(query_list[1], query_list[3], query_list[-1]))]] else: keyboard = [[InlineKeyboardButton(piece[0], callback_data="['battle', '{}', 'confirm', {}, {}, {}, {}]".format(query_list[1], piece[1], query_list[2], query_list[3], query_list[-1]))] for piece in piece_list] keyboard.append([InlineKeyboardButton('Back', callback_data="['battle', '{}', 'back', {}, {}]".format(query_list[1], query_list[3], query_list[-1]))]) reply_markup = InlineKeyboardMarkup(keyboard) bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=text, reply_markup=reply_markup) db.commit() def battle(bot, active_country, piece, space, card_id, session): db = sqlite3.connect(session.get_db_dir()) function.updatesupply(db) space_name = db.execute("select distinct name from space where spaceid = :space;", {'space':space}).fetchall() active_country_name = db.execute("select name from country where id = :country;", {'country':active_country}).fetchall() passive_country = db.execute("select control from piece where pieceid = :piece;", {'piece':piece}).fetchall() group_chat = db.execute("select chatid from game;").fetchall() if piece == 0: db.execute("update piece set location = :space where pieceid = :piece;", {'space':space, 'piece':piece}) db.commit() text =" Empty space " + space_name[0][0] + " is battled by " + active_country_name[0][0] else: country_name = db.execute("select id, name from country where id = (select control from piece where pieceid = :piece);", {'piece':piece}).fetchall() status_handler.status_battle_handler(bot, active_country, country_name[0][0], space, session) if db.execute("select noremove from piece where pieceid = :piece;", {'piece':piece}).fetchall()[0][0] == 0: db.execute("update piece set location = 'none' where pieceid = :piece;", {'piece':piece}) db.commit() text = country_name[0][1] + " piece in " + space_name[0][0] + " is battled by " + active_country_name[0][0] else: text = country_name[0][1] + " piece in " + space_name[0][0] + " is not removed" bot.send_message(chat_id = group_chat[0][0], text = text) function.updatecontrol(bot, db) lock_id = session.add_lock() status_handler.send_status_card(bot, active_country, 'Battle', lock_id, session, passive_country_id = passive_country[0][0], piece_id = piece, space_id = space, card_id = card_id) import air air.check_reposition(bot, session) db.commit() #------------------------------------------Remove------------------------------------------ class remove_obj(): def __init__(self, country, space_list, card_id, lock_id, piece_type, session): self.remove_id = len(session.remove_list) self.country = country self.space_list = space_list self.card_id = card_id self.lock_id = lock_id self.piece_type = piece_type self.space_id = None self.piece_list = None self.piece_id = None text = "remove buffer add: " info_list = {"remove_id":self.remove_id, "country":country, "space_list":space_list, "card_id":card_id, "lock_id":lock_id, "piece_type":piece_type} for info in info_list: if info_list[info] != None: text += " [" + info + ": " + str(info_list[info]) + "]" print(text) def remove_info(self, session): db = sqlite3.connect(session.get_db_dir()) print('remove info') print(self.space_list) name_list = function.get_name_list(self.space_list, db) chat_id = db.execute("select playerid from country where id = :country;", {'country':self.country}).fetchall() text = 'Choose a space to remove' keyboard = [[InlineKeyboardButton(space[1], callback_data="['remove', {}, {}]".format(space[0], self.remove_id))] for space in name_list] keyboard.append([InlineKeyboardButton('Pass', callback_data="['remove','pass', {}]".format(self.remove_id))]) reply_markup = InlineKeyboardMarkup(keyboard) return chat_id[0][0], text, reply_markup def remove_cb(self, bot, query, query_list, session): db = sqlite3.connect(session.get_db_dir()) if query_list[1] == 'confirm': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) self.piece_id = query_list[2] remove(bot, self.country, self.piece_id, self.space_id, self.card_id, session) session.release_lock(self.lock_id) session.remove_list.pop(self.remove_id) elif query_list[1] == 'pass': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) session.release_lock(self.lock_id) session.remove_list.pop(self.remove_id) else: if query_list[1] == 'back': self.space_id = None info = self.remove_info(session) text = info[2] reply_markup = info[3] else: self.space_id = query_list[1] location = db.execute("select name from space where spaceid = :id", {'id':self.space_id}).fetchall() text = 'Remove ' + location[0][0] + ':' if self.piece_type == 'all': self.piece_list = db.execute("select country.name, piece.pieceid, piece.type from piece inner join country on piece.control = country.id where piece.location = :location;", {'location':self.space_id}).fetchall() else: self.piece_list = db.execute("select country.name, piece.pieceid, piece.type from piece inner join country on piece.control = country.id where piece.location = :location and piece.type = :type;", {'location':self.space_id, 'type':self.piece_type}).fetchall() if len(self.piece_list) == 0: keyboard = [[InlineKeyboardButton('Confirm', callback_data="['remove', 'confirm', 0, {}]".format(self.remove_id))], [InlineKeyboardButton('Back', callback_data="['remove', 'back', {}]".format(self.remove_id))]] elif len(self.piece_list) == 1: keyboard = [[InlineKeyboardButton('Confirm', callback_data="['remove', 'confirm', {}, {}]".format(self.piece_list[0][1], self.remove_id))], [InlineKeyboardButton('Back', callback_data="['remove', 'back', {}]".format(self.remove_id))]] else: keyboard = [[InlineKeyboardButton(piece[0] + function.piece_type_name[piece[2]], callback_data="['remove', 'confirm', {}, {}]".format(piece[1], self.remove_id))] for piece in self.piece_list] keyboard.append([InlineKeyboardButton('Back', callback_data="['remove', 'back', {}]".format((self.remove_id)))]) reply_markup = InlineKeyboardMarkup(keyboard) bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=text, reply_markup=reply_markup) def remove(bot, active_country, piece, space, card_id, session): db = sqlite3.connect(session.get_db_dir()) function.updatesupply(db) space_name = db.execute("select distinct name from space where spaceid = :space;", {'space':space}).fetchall() piece_type = db.execute("select type from piece where pieceid = :piece;", {'piece':piece}).fetchall() active_country_name = db.execute("select name from country where id = :country;", {'country':active_country}).fetchall() group_chat = db.execute("select chatid from game;").fetchall() if piece == 0: db.execute("update piece set location = :space where pieceid = :piece;", {'space':space, 'piece':piece}) db.commit() text =" Empty space " + space_name[0][0] + " is removed by " + active_country_name[0][0] else: country_name = db.execute("select name from country where id = (select control from piece where pieceid = :piece);", {'piece':piece}).fetchall() if db.execute("select noremove from piece where pieceid = :piece;", {'piece':piece}).fetchall()[0][0] == 0: db.execute("update piece set location = 'none' where pieceid = :piece;", {'piece':piece}) db.commit() text = country_name[0][0] + " " + function.piece_type_name[piece_type[0][0]] + " in " + space_name[0][0] + " is removed by " + active_country_name[0][0] else: text = country_name[0][0] + " piece in " + space_name[0][0] + " is not removed" bot.send_message(chat_id = group_chat[0][0], text = text) function.updatecontrol(bot, db) lock_id = session.add_lock() status_handler.send_status_card(bot, active_country, 'Remove', lock_id, session, piece_id = piece, space_id = space, card_id = card_id) import air air.check_reposition(bot, session) db.commit() #------------------------------------------Self_Remove------------------------------------------ class self_remove(): def __init__(self, country, space_list, card_id, lock_id, piece_type, session): self.self_remove_id = len(session.self_remove_list) self.country = country self.space_list = space_list self.card_id = card_id self.lock_id = lock_id self.piece_type = piece_type self.space_id = None self.piece_list = None self.piece_id = None text = "self_remove buffer add: " info_list = {"self_remove_id":self.self_remove_id, "country":country, "space_list":space_list, "card_id":card_id, "lock_id":lock_id, "piece_type":piece_type} for info in info_list: if info_list[info] != None: text += " [" + info + ": " + str(info_list[info]) + "]" print(text) def self_remove_info(self, session): db = sqlite3.connect(session.get_db_dir()) print('self_remove info') print(self.space_list) name_list = function.get_name_list(self.space_list, db) print(name_list) chat_id = db.execute("select playerid from country where id = :country;", {'country':self.country}).fetchall() text = 'Choose a space to remove' keyboard = [[InlineKeyboardButton(space[1], callback_data="['self_remove', {}, {}]".format(space[0], self.self_remove_id))] for space in name_list] #keyboard.append([InlineKeyboardButton('Pass', callback_data="['self_remove','pass', {}]".format(self.self_remove_id))]) reply_markup = InlineKeyboardMarkup(keyboard) return chat_id[0][0], text, reply_markup def self_remove_cb(self, bot, query, query_list, session): db = sqlite3.connect(session.get_db_dir()) if query_list[1] == 'confirm': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) self.piece_id = query_list[2] remove(bot, self.country, self.piece_id, self.space_id, self.card_id, session) session.release_lock(self.lock_id) session.self_remove_list.pop(self.self_remove_id) elif query_list[1] == 'pass': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) session.release_lock(self.lock_id) session.self_remove_list.pop(self.self_remove_id) else: if query_list[1] == 'back': self.space_id = None info = self.self_remove_info(session) text = info[1] reply_markup = info[2] else: self.space_id = query_list[1] location = db.execute("select name from space where spaceid = :id", {'id':self.space_id}).fetchall() text = 'Remove ' + location[0][0] + ':' if self.piece_type == 'all': self.piece_list = db.execute("select pieceid, type from piece where location = :location and control = :country;", {'location':self.space_id, 'country':self.country}).fetchall() else: self.piece_list = db.execute("select pieceid, type from piece where location = :location and type = :type and control = :country;", {'location':self.space_id, 'type':self.piece_type, 'country':self.country}).fetchall() if len(self.piece_list) == 1: keyboard = [[InlineKeyboardButton('Confirm', callback_data="['self_remove', 'confirm', {}, {}]".format(self.piece_list[0][0], self.self_remove_id))], [InlineKeyboardButton('Back', callback_data="['self_remove', 'back', {}]".format(self.self_remove_id))]] else: keyboard = [[InlineKeyboardButton(function.piece_type_name[piece[1]], callback_data="['self_remove', 'confirm', {}, {}]".format(piece[0], self.self_remove_id))] for piece in self.piece_list] keyboard.append([InlineKeyboardButton('Back', callback_data="['self_remove', 'back', {}]".format((self.self_remove_id)))]) reply_markup = InlineKeyboardMarkup(keyboard) bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=text, reply_markup=reply_markup) db.commit() #------------------------------------------Move------------------------------------------ class move_obj(): def __init__(self, country, space_list, card_id, lock_id, piece_type, session): self.move_id = len(session.move_list) self.country = country self.space_list = space_list self.card_id = card_id self.lock_id = lock_id self.piece_type = piece_type self.space_id = None self.piece_list = None self.piece_id = None text = "move buffer add: " info_list = {"move_id":self.move_id, "country":country, "space_list":space_list, "card_id":card_id, "lock_id":lock_id, "piece_type":piece_type} for info in info_list: if info_list[info] != None: text += " [" + info + ": " + str(info_list[info]) + "]" print(text) def move_info(self, db): print('move info') print(self.space_list) name_list = function.get_name_list(self.space_list, db) print(name_list) chat_id = db.execute("select playerid from country where id = :country;", {'country':self.country}).fetchall() text = 'Pick up a piece:' keyboard = [[InlineKeyboardButton(space[1], callback_data="['move', {}, {}]".format(space[0], self.move_id))] for space in name_list] keyboard.append([InlineKeyboardButton('Pass', callback_data="['move','pass', {}]".format(self.move_id))]) reply_markup = InlineKeyboardMarkup(keyboard) return chat_id[0][0], text, reply_markup def move_cb(self, bot, query, query_list, session): db = sqlite3.connect(session.get_db_dir()) if query_list[1] == 'confirm': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) self.piece_id = query_list[3] move(bot, self.country, self.piece_id, self.space_id, session) session.release_lock(self.lock_id) session.move_list.pop(self.move_id) elif query_list[1] == 'pass': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) session.release_lock(self.lock_id) session.move_list.pop(self.move_id) else: if query_list[1] == 'back': self.space_id = None info = self.move_info(db) text = info[2] reply_markup = info[3] else: self.space_id = query_list[1] location = db.execute("select name from space where spaceid = :id", {'id':self.space_id}).fetchall() text = 'Pick up piece in ' + location[0][0] + ':' if self.piece_type == 'all': self.piece_list = db.execute("select pieceid, type from piece where location = :location;", {'location':self.space_id}).fetchall() else: self.piece_list = db.execute("select pieceid from piece where location = :location and type = :type;", {'location':self.space_id, 'type':self.piece_type}).fetchall() if len(self.piece_list) == 1: keyboard = [[InlineKeyboardButton('Confirm', callback_data="['move', 'confirm', {}, {}]".format(self.piece_list[0][0], self.move_id))], [InlineKeyboardButton('Back', callback_data="['move', 'back', {}]".format(self.move_id))]] else: keyboard = [[InlineKeyboardButton(piece[1], callback_data="['move', 'confirm', {}, {}]".format(piece[1], self.move_id))] for piece in self.piece_list] keyboard.append([InlineKeyboardButton('Back', callback_data="['move', 'back', {}]".format((self.move_id)))]) reply_markup = InlineKeyboardMarkup(keyboard) bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=text, reply_markup=reply_markup) db.commit() def move(bot, active_country, piece, space, session): db = sqlite3.connect(session.get_db_dir()) function.updatesupply(db) space_name = db.execute("select distinct name from space where spaceid = :space;", {'space':space}).fetchall() active_country_name = db.execute("select name from country where id = :country;", {'country':active_country}).fetchall() group_chat = db.execute("select chatid from game;").fetchall() country_name = db.execute("select name from country where id = (select control from piece where pieceid = :piece);", {'piece':piece}).fetchall() db.execute("update piece set location = 'none' where pieceid = :piece;", {'piece':piece}) db.commit() text = country_name[0][0] + " piece in " + space_name[0][0] + " is picked up by " + active_country_name[0][0] function.updatecontrol(bot, db) import air air.check_reposition(bot, session) bot.send_message(chat_id = group_chat[0][0], text = text) #------------------------------------------Build------------------------------------------ def build_info(bot, country, space_list, card_id, lock_id, session): print('build info') print(space_list) db = sqlite3.connect(session.get_db_dir()) name_list = function.get_name_list(space_list, db) print(name_list) session.space_list_buffer = space_list remain_army_count = db.execute("select count(*) from piece where control = :country and type = 'army' and location = 'none';", {'country':country}).fetchall()[0][0] remain_navy_count = db.execute("select count(*) from piece where control = :country and type = 'navy' and location = 'none';", {'country':country}).fetchall()[0][0] remain_air_count = db.execute("select count(*) from piece where control = :country and type = 'air' and location = 'none';", {'country':country}).fetchall()[0][0] chat_id = db.execute("select playerid from country where id = :country;", {'country':country}).fetchall() text = "Choose a space to build\n" text += "Remain army:" + str(remain_army_count) + "\n" text += "Remain navy:" + str(remain_navy_count) + "\n" text += "Remain air force:" + str(remain_air_count) + "\n" keyboard = [[InlineKeyboardButton(space[1], callback_data="['build', '{}', {}, {}, {}]".format(country, space[0], card_id, lock_id))] for space in name_list] keyboard.append([InlineKeyboardButton('Pass', callback_data="['build', '{}', 'pass', {}, {}]".format(country, card_id, lock_id))]) reply_markup = InlineKeyboardMarkup(keyboard) return chat_id[0][0], text, reply_markup def build_cb(bot, query, query_list, session): db = sqlite3.connect(session.get_db_dir()) if query_list[2] == 'confirm': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) build(bot,query_list[1], query_list[3], query_list[4], session) session.release_lock(query_list[-1]) elif query_list[2] == 'pass': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) session.release_lock(query_list[-1]) else: if query_list[2] == 'back': info = build_info(bot, query_list[1] , session.space_list_buffer, query_list[3], query_list[-1], session) text = info[1] reply_markup = info[2] else: location = db.execute("select name from space where spaceid = :id", {'id':query_list[2]}).fetchall() text = 'Build in ' + location[0][0] + ':' keyboard = [[InlineKeyboardButton('Confirm', callback_data="['build', '{}', 'confirm', {}, {}, {}]".format(query_list[1], query_list[2], query_list[3], query_list[-1]))], [InlineKeyboardButton('Back', callback_data="['build', '{}', 'back', {}, {}]".format(query_list[1], query_list[3], query_list[-1]))]] reply_markup = InlineKeyboardMarkup(keyboard) bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text = text, reply_markup = reply_markup) db.commit() def build(bot, active_country, space, card_id, session): db = sqlite3.connect(session.get_db_dir()) space_info = db.execute("select distinct name, type from space where spaceid = :space;", {'space':space}).fetchall() active_country_name = db.execute("select name from country where id = :country;", {'country':active_country}).fetchall() group_chat = db.execute("select chatid from game;").fetchall() if over_build_handler(bot, active_country, space_info[0][1], session): text = active_country_name[0][0] + " do not remove piece to build" bot.send_message(chat_id = group_chat[0][0], text = text) else: status_handler.status_build_handler(bot, active_country, session) piece = db.execute("select min(pieceid) from piece where location = 'none' and control = :country and type = :piece_type;", {'country':active_country, 'piece_type':function.terrain2type[space_info[0][1]]}).fetchall() db.execute("update piece set location = :location where pieceid = :piece;", {'location':space, 'piece':piece[0][0]}) text = active_country_name[0][0] + " build in " + space_info[0][0] bot.send_message(chat_id = group_chat[0][0], text = text) function.updatecontrol(bot, db) function.updatesupply(db) lock_id = session.add_lock() status_handler.send_status_card(bot, active_country, 'Build', lock_id, session, piece_id = piece[0][0], space_id = space, card_id = card_id) import air air.check_reposition(bot, session) db.commit() #------------------------------------------Recuit------------------------------------------ def recuit_info(bot, country, space_list, card_id, lock_id, session): print('recuit info') print(space_list) db = sqlite3.connect(session.get_db_dir()) name_list = function.get_name_list(space_list, db) print(name_list) remain_army_count = db.execute("select count(*) from piece where control = :country and type = 'army' and location = 'none';", {'country':country}).fetchall()[0][0] remain_navy_count = db.execute("select count(*) from piece where control = :country and type = 'navy' and location = 'none';", {'country':country}).fetchall()[0][0] remain_air_count = db.execute("select count(*) from piece where control = :country and type = 'air' and location = 'none';", {'country':country}).fetchall()[0][0] session.space_list_buffer = space_list chat_id = db.execute("select playerid from country where id = :country;", {'country':country}).fetchall() text = "Choose a space to recuit\n" text += "Remain army:" + str(remain_army_count) + "\n" text += "Remain navy:" + str(remain_navy_count) + "\n" text += "Remain air force:" + str(remain_air_count) + "\n" keyboard = [[InlineKeyboardButton(space[1], callback_data="['recuit', '{}', {}, {}, {}]".format(country, space[0], card_id, lock_id))] for space in name_list] keyboard.append([InlineKeyboardButton('Pass', callback_data="['recuit', '{}', 'pass', {}, {}]".format(country, card_id, lock_id))]) reply_markup = InlineKeyboardMarkup(keyboard) return chat_id[0][0], text, reply_markup def recuit_cb(bot, query, query_list, session): db = sqlite3.connect(session.get_db_dir()) if query_list[2] == 'confirm': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) recuit(bot,query_list[1], query_list[3], query_list[4], session) session.release_lock(query_list[-1]) elif query_list[2] == 'pass': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) session.release_lock(query_list[-1]) else: if query_list[2] == 'back': info = recuit_info(bot, query_list[1] , session.space_list_buffer, query_list[3], query_list[-1], session) text = info[1] reply_markup = info[2] else: location = db.execute("select name from space where spaceid = :id", {'id':query_list[2]}).fetchall() text = 'Recuit in ' + location[0][0] + ':' keyboard = [[InlineKeyboardButton('Confirm', callback_data="['recuit', '{}', 'confirm', {}, {}, {}]".format(query_list[1], query_list[2], query_list[3], query_list[-1]))], [InlineKeyboardButton('Back', callback_data="['recuit', '{}', 'back', {}, {}]".format(query_list[1], query_list[3], query_list[-1]))]] reply_markup = InlineKeyboardMarkup(keyboard) bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text = text, reply_markup = reply_markup) db.commit() def recuit(bot, active_country, space, card_id, session): db = sqlite3.connect(session.get_db_dir()) space_info = db.execute("select distinct name, type from space where spaceid = :space;", {'space':space}).fetchall() active_country_name = db.execute("select name from country where id = :country;", {'country':active_country}).fetchall() group_chat = db.execute("select chatid from game;").fetchall() if over_build_handler(bot, active_country, space_info[0][1], session): text = active_country_name[0][0] + " do not remove piece to recuit" bot.send_message(chat_id = group_chat[0][0], text = text) else: status_handler.status_recuit_handler(bot, active_country, session) piece = db.execute("select min(pieceid) from piece where location = 'none' and control = :country and type = :piece_type;", {'country':active_country, 'piece_type':function.terrain2type[space_info[0][1]]}).fetchall() db.execute("update piece set location = :location where pieceid = :piece;", {'location':space, 'piece':piece[0][0]}) text = active_country_name[0][0] + " recuit in " + space_info[0][0] bot.send_message(chat_id = group_chat[0][0], text = text) function.updatecontrol(bot, db) function.updatesupply(db) lock_id = session.add_lock() status_handler.send_status_card(bot, active_country, 'Recruit', lock_id, session, piece_id = piece[0][0], space_id = space, card_id = card_id) import air air.check_reposition(bot, session) db.commit() #------------------------------------------Over_Build_Handler------------------------------------------ def over_build_handler(bot, active_country, space_type, session): db = sqlite3.connect(session.get_db_dir()) if db.execute("select count(*) from piece where location = 'none' and control = :country and type = :piece_type;", {'country':active_country, 'piece_type':function.terrain2type[space_type]}).fetchall()[0][0] == 0: lock_id = session.add_lock() space_list = function.control_space_list(active_country, db, space_type = space_type) session.self_remove_list.append(self_remove(active_country, space_list, None, lock_id, function.terrain2type[space_type], session)) self_remove_id = len(session.self_remove_list)-1 info = session.self_remove_list[self_remove_id].self_remove_info(session) bot.send_message(chat_id = info[0], text = info[1], reply_markup = info[2]) session.thread_lock(lock_id) return (db.execute("select count(*) from piece where location = 'none' and control = :country and type = :piece_type;", {'country':active_country, 'piece_type':function.terrain2type[space_type]}).fetchall()[0][0] == 0) #------------------------------------------Restore------------------------------------------ def restore(bot, piece, space, session): db = sqlite3.connect(session.get_db_dir()) space_info = db.execute("select distinct name, type from space where spaceid = :space;", {'space':space}).fetchall() group_chat = db.execute("select chatid from game;").fetchall() db.execute("update piece set location = :location where pieceid = :piece;", {'location':space, 'piece':piece}) function.updatecontrol(bot, db) import air air.check_reposition(bot, session) text = "Piece in " + space_info[0][0] + " not removed" bot.send_message(chat_id = group_chat[0][0], text = text) db.commit()
import telegram import sqlite3 import function import thread_lock import status_handler from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, MessageHandler, Filters #------------------------------------------Battle------------------------------------------ def battle_info(bot, country, space_list, card_id, lock_id, session): print('battle info') print(space_list) db = sqlite3.connect(session.get_db_dir()) name_list = function.get_name_list(space_list, db) print(name_list) session.space_list_buffer = space_list chat_id = db.execute("select playerid from country where id = :country;", {'country':country}).fetchall() text = 'Choose a space to battle' keyboard = [] for space in name_list: piece_list = db.execute("select country.name from piece inner join country on piece.control = country.id where piece.location = :location and piece.type != 'air';", {'location':space[0]}).fetchall() if len(piece_list) == 0: keyboard.append([InlineKeyboardButton(space[1] + " - empty", callback_data="['battle', '{}', {}, {}, {}]".format(country, space[0], card_id, lock_id))]) else: button = space[1] + " - " for piece in piece_list: button += piece[0] + " " keyboard.append([InlineKeyboardButton(button, callback_data="['battle', '{}', {}, {}, {}]".format(country, space[0], card_id, lock_id))]) keyboard.append([InlineKeyboardButton('Pass', callback_data="['battle', '{}', 'pass', {}, {}]".format(country, card_id, lock_id))]) reply_markup = InlineKeyboardMarkup(keyboard) return chat_id[0][0], text, reply_markup def battle_cb(bot, query, query_list, session): db = sqlite3.connect(session.get_db_dir()) if query_list[2] == 'confirm': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) battle(bot, query_list[1], query_list[3], query_list[4], query_list[5], session) session.release_lock(query_list[-1]) elif query_list[2] == 'pass': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) session.release_lock(query_list[-1]) else: if query_list[2] == 'back': info = battle_info(bot, query_list[1] , session.space_list_buffer, query_list[3], query_list[-1], session) text = info[1] reply_markup = info[2] else: location = db.execute("select name from space where spaceid = :id", {'id':query_list[2]}).fetchall() text = 'Battle ' + location[0][0] + ':' piece_list = db.execute("select country.name, piece.pieceid from piece inner join country on piece.control = country.id where piece.location = :location and piece.type != 'air';", {'location':query_list[2]}).fetchall() if len(piece_list) == 0: keyboard = [[InlineKeyboardButton('Confirm', callback_data="['battle', '{}', 'confirm', 0, {}, {}, {}]".format(query_list[1], query_list[2], query_list[3], query_list[-1]))], [InlineKeyboardButton('Back', callback_data="['battle', '{}', 'back', {}, {}]".format(query_list[1], query_list[3], query_list[-1]))]] elif len(piece_list) == 1: keyboard = [[InlineKeyboardButton('Confirm', callback_data="['battle', '{}', 'confirm', {}, {}, {}, {}]".format(query_list[1], piece_list[0][1], query_list[2], query_list[3], query_list[-1]))], [InlineKeyboardButton('Back', callback_data="['battle', '{}', 'back', {}, {}]".format(query_list[1], query_list[3], query_list[-1]))]] else: keyboard = [[InlineKeyboardButton(piece[0], callback_data="['battle', '{}', 'confirm', {}, {}, {}, {}]".format(query_list[1], piece[1], query_list[2], query_list[3], query_list[-1]))] for piece in piece_list] keyboard.append([InlineKeyboardButton('Back', callback_data="['battle', '{}', 'back', {}, {}]".format(query_list[1], query_list[3], query_list[-1]))]) reply_markup = InlineKeyboardMarkup(keyboard) bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=text, reply_markup=reply_markup) db.commit() def battle(bot, active_country, piece, space, card_id, session): db = sqlite3.connect(session.get_db_dir()) function.updatesupply(db) space_name = db.execute("select distinct name from space where spaceid = :space;", {'space':space}).fetchall() active_country_name = db.execute("select name from country where id = :country;", {'country':active_country}).fetchall() passive_country = db.execute("select control from piece where pieceid = :piece;", {'piece':piece}).fetchall() group_chat = db.execute("select chatid from game;").fetchall() if piece == 0: db.execute("update piece set location = :space where pieceid = :piece;", {'space':space, 'piece':piece}) db.commit() text =" Empty space " + space_name[0][0] + " is battled by " + active_country_name[0][0] else: country_name = db.execute("select id, name from country where id = (select control from piece where pieceid = :piece);", {'piece':piece}).fetchall() status_handler.status_battle_handler(bot, active_country, country_name[0][0], space, session) if db.execute("select noremove from piece where pieceid = :piece;", {'piece':piece}).fetchall()[0][0] == 0: db.execute("update piece set location = 'none' where pieceid = :piece;", {'piece':piece}) db.commit() text = country_name[0][1] + " piece in " + space_name[0][0] + " is battled by " + active_country_name[0][0] else: text = country_name[0][1] + " piece in " + space_name[0][0] + " is not removed" bot.send_message(chat_id = group_chat[0][0], text = text) function.updatecontrol(bot, db) lock_id = session.add_lock() status_handler.send_status_card(bot, active_country, 'Battle', lock_id, session, passive_country_id = passive_country[0][0], piece_id = piece, space_id = space, card_id = card_id) import air air.check_reposition(bot, session) db.commit() #------------------------------------------Remove------------------------------------------ class remove_obj(): def __init__(self, country, space_list, card_id, lock_id, piece_type, session): self.remove_id = len(session.remove_list) self.country = country self.space_list = space_list self.card_id = card_id self.lock_id = lock_id self.piece_type = piece_type self.space_id = None self.piece_list = None self.piece_id = None text = "remove buffer add: " info_list = {"remove_id":self.remove_id, "country":country, "space_list":space_list, "card_id":card_id, "lock_id":lock_id, "piece_type":piece_type} for info in info_list: if info_list[info] != None: text += " [" + info + ": " + str(info_list[info]) + "]" print(text) def remove_info(self, session): db = sqlite3.connect(session.get_db_dir()) print('remove info') print(self.space_list) name_list = function.get_name_list(self.space_list, db) chat_id = db.execute("select playerid from country where id = :country;", {'country':self.country}).fetchall() text = 'Choose a space to remove' keyboard = [[InlineKeyboardButton(space[1], callback_data="['remove', {}, {}]".format(space[0], self.remove_id))] for space in name_list] keyboard.append([InlineKeyboardButton('Pass', callback_data="['remove','pass', {}]".format(self.remove_id))]) reply_markup = InlineKeyboardMarkup(keyboard) return chat_id[0][0], text, reply_markup def remove_cb(self, bot, query, query_list, session): db = sqlite3.connect(session.get_db_dir()) if query_list[1] == 'confirm': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) self.piece_id = query_list[2] remove(bot, self.country, self.piece_id, self.space_id, self.card_id, session) session.release_lock(self.lock_id) session.remove_list.pop(self.remove_id) elif query_list[1] == 'pass': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) session.release_lock(self.lock_id) session.remove_list.pop(self.remove_id) else: if query_list[1] == 'back': self.space_id = None info = self.remove_info(session) text = info[2] reply_markup = info[3] else: self.space_id = query_list[1] location = db.execute("select name from space where spaceid = :id", {'id':self.space_id}).fetchall() text = 'Remove ' + location[0][0] + ':' if self.piece_type == 'all': self.piece_list = db.execute("select country.name, piece.pieceid, piece.type from piece inner join country on piece.control = country.id where piece.location = :location;", {'location':self.space_id}).fetchall() else: self.piece_list = db.execute("select country.name, piece.pieceid, piece.type from piece inner join country on piece.control = country.id where piece.location = :location and piece.type = :type;", {'location':self.space_id, 'type':self.piece_type}).fetchall() if len(self.piece_list) == 0: keyboard = [[InlineKeyboardButton('Confirm', callback_data="['remove', 'confirm', 0, {}]".format(self.remove_id))], [InlineKeyboardButton('Back', callback_data="['remove', 'back', {}]".format(self.remove_id))]] elif len(self.piece_list) == 1: keyboard = [[InlineKeyboardButton('Confirm', callback_data="['remove', 'confirm', {}, {}]".format(self.piece_list[0][1], self.remove_id))], [InlineKeyboardButton('Back', callback_data="['remove', 'back', {}]".format(self.remove_id))]] else: keyboard = [[InlineKeyboardButton(piece[0] + function.piece_type_name[piece[2]], callback_data="['remove', 'confirm', {}, {}]".format(piece[1], self.remove_id))] for piece in self.piece_list] keyboard.append([InlineKeyboardButton('Back', callback_data="['remove', 'back', {}]".format((self.remove_id)))]) reply_markup = InlineKeyboardMarkup(keyboard) bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=text, reply_markup=reply_markup) def remove(bot, active_country, piece, space, card_id, session): db = sqlite3.connect(session.get_db_dir()) function.updatesupply(db) space_name = db.execute("select distinct name from space where spaceid = :space;", {'space':space}).fetchall() piece_type = db.execute("select type from piece where pieceid = :piece;", {'piece':piece}).fetchall() active_country_name = db.execute("select name from country where id = :country;", {'country':active_country}).fetchall() group_chat = db.execute("select chatid from game;").fetchall() if piece == 0: db.execute("update piece set location = :space where pieceid = :piece;", {'space':space, 'piece':piece}) db.commit() text =" Empty space " + space_name[0][0] + " is removed by " + active_country_name[0][0] else: country_name = db.execute("select name from country where id = (select control from piece where pieceid = :piece);", {'piece':piece}).fetchall() if db.execute("select noremove from piece where pieceid = :piece;", {'piece':piece}).fetchall()[0][0] == 0: db.execute("update piece set location = 'none' where pieceid = :piece;", {'piece':piece}) db.commit() text = country_name[0][0] + " " + function.piece_type_name[piece_type[0][0]] + " in " + space_name[0][0] + " is removed by " + active_country_name[0][0] else: text = country_name[0][0] + " piece in " + space_name[0][0] + " is not removed" bot.send_message(chat_id = group_chat[0][0], text = text) function.updatecontrol(bot, db) lock_id = session.add_lock() status_handler.send_status_card(bot, active_country, 'Remove', lock_id, session, piece_id = piece, space_id = space, card_id = card_id) import air air.check_reposition(bot, session) db.commit() #------------------------------------------Self_Remove------------------------------------------ class self_remove(): def __init__(self, country, space_list, card_id, lock_id, piece_type, session): self.self_remove_id = len(session.self_remove_list) self.country = country self.space_list = space_list self.card_id = card_id self.lock_id = lock_id self.piece_type = piece_type self.space_id = None self.piece_list = None self.piece_id = None text = "self_remove buffer add: " info_list = {"self_remove_id":self.self_remove_id, "country":country, "space_list":space_list, "card_id":card_id, "lock_id":lock_id, "piece_type":piece_type} for info in info_list: if info_list[info] != None: text += " [" + info + ": " + str(info_list[info]) + "]" print(text) def self_remove_info(self, session): db = sqlite3.connect(session.get_db_dir()) print('self_remove info') print(self.space_list) name_list = function.get_name_list(self.space_list, db) print(name_list) chat_id = db.execute("select playerid from country where id = :country;", {'country':self.country}).fetchall() text = 'Choose a space to remove' keyboard = [[InlineKeyboardButton(space[1], callback_data="['self_remove', {}, {}]".format(space[0], self.self_remove_id))] for space in name_list] #keyboard.append([InlineKeyboardButton('Pass', callback_data="['self_remove','pass', {}]".format(self.self_remove_id))]) reply_markup = InlineKeyboardMarkup(keyboard) return chat_id[0][0], text, reply_markup def self_remove_cb(self, bot, query, query_list, session): db = sqlite3.connect(session.get_db_dir()) if query_list[1] == 'confirm': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) self.piece_id = query_list[2] remove(bot, self.country, self.piece_id, self.space_id, self.card_id, session) session.release_lock(self.lock_id) session.self_remove_list.pop(self.self_remove_id) elif query_list[1] == 'pass': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) session.release_lock(self.lock_id) session.self_remove_list.pop(self.self_remove_id) else: if query_list[1] == 'back': self.space_id = None info = self.self_remove_info(session) text = info[1] reply_markup = info[2] else: self.space_id = query_list[1] location = db.execute("select name from space where spaceid = :id", {'id':self.space_id}).fetchall() text = 'Remove ' + location[0][0] + ':' if self.piece_type == 'all': self.piece_list = db.execute("select pieceid, type from piece where location = :location and control = :country;", {'location':self.space_id, 'country':self.country}).fetchall() else: self.piece_list = db.execute("select pieceid, type from piece where location = :location and type = :type and control = :country;", {'location':self.space_id, 'type':self.piece_type, 'country':self.country}).fetchall() if len(self.piece_list) == 1: keyboard = [[InlineKeyboardButton('Confirm', callback_data="['self_remove', 'confirm', {}, {}]".format(self.piece_list[0][0], self.self_remove_id))], [InlineKeyboardButton('Back', callback_data="['self_remove', 'back', {}]".format(self.self_remove_id))]] else: keyboard = [[InlineKeyboardButton(function.piece_type_name[piece[1]], callback_data="['self_remove', 'confirm', {}, {}]".format(piece[0], self.self_remove_id))] for piece in self.piece_list] keyboard.append([InlineKeyboardButton('Back', callback_data="['self_remove', 'back', {}]".format((self.self_remove_id)))]) reply_markup = InlineKeyboardMarkup(keyboard) bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=text, reply_markup=reply_markup) db.commit() #------------------------------------------Move------------------------------------------ class move_obj(): def __init__(self, country, space_list, card_id, lock_id, piece_type, session): self.move_id = len(session.move_list) self.country = country self.space_list = space_list self.card_id = card_id self.lock_id = lock_id self.piece_type = piece_type self.space_id = None self.piece_list = None self.piece_id = None text = "move buffer add: " info_list = {"move_id":self.move_id, "country":country, "space_list":space_list, "card_id":card_id, "lock_id":lock_id, "piece_type":piece_type} for info in info_list: if info_list[info] != None: text += " [" + info + ": " + str(info_list[info]) + "]" print(text) def move_info(self, db): print('move info') print(self.space_list) name_list = function.get_name_list(self.space_list, db) print(name_list) chat_id = db.execute("select playerid from country where id = :country;", {'country':self.country}).fetchall() text = 'Pick up a piece:' keyboard = [[InlineKeyboardButton(space[1], callback_data="['move', {}, {}]".format(space[0], self.move_id))] for space in name_list] keyboard.append([InlineKeyboardButton('Pass', callback_data="['move','pass', {}]".format(self.move_id))]) reply_markup = InlineKeyboardMarkup(keyboard) return chat_id[0][0], text, reply_markup def move_cb(self, bot, query, query_list, session): db = sqlite3.connect(session.get_db_dir()) if query_list[1] == 'confirm': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) self.piece_id = query_list[3] move(bot, self.country, self.piece_id, self.space_id, session) session.release_lock(self.lock_id) session.move_list.pop(self.move_id) elif query_list[1] == 'pass': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) session.release_lock(self.lock_id) session.move_list.pop(self.move_id) else: if query_list[1] == 'back': self.space_id = None info = self.move_info(db) text = info[2] reply_markup = info[3] else: self.space_id = query_list[1] location = db.execute("select name from space where spaceid = :id", {'id':self.space_id}).fetchall() text = 'Pick up piece in ' + location[0][0] + ':' if self.piece_type == 'all': self.piece_list = db.execute("select pieceid, type from piece where location = :location;", {'location':self.space_id}).fetchall() else: self.piece_list = db.execute("select pieceid from piece where location = :location and type = :type;", {'location':self.space_id, 'type':self.piece_type}).fetchall() if len(self.piece_list) == 1: keyboard = [[InlineKeyboardButton('Confirm', callback_data="['move', 'confirm', {}, {}]".format(self.piece_list[0][0], self.move_id))], [InlineKeyboardButton('Back', callback_data="['move', 'back', {}]".format(self.move_id))]] else: keyboard = [[InlineKeyboardButton(piece[1], callback_data="['move', 'confirm', {}, {}]".format(piece[1], self.move_id))] for piece in self.piece_list] keyboard.append([InlineKeyboardButton('Back', callback_data="['move', 'back', {}]".format((self.move_id)))]) reply_markup = InlineKeyboardMarkup(keyboard) bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=text, reply_markup=reply_markup) db.commit() def move(bot, active_country, piece, space, session): db = sqlite3.connect(session.get_db_dir()) function.updatesupply(db) space_name = db.execute("select distinct name from space where spaceid = :space;", {'space':space}).fetchall() active_country_name = db.execute("select name from country where id = :country;", {'country':active_country}).fetchall() group_chat = db.execute("select chatid from game;").fetchall() country_name = db.execute("select name from country where id = (select control from piece where pieceid = :piece);", {'piece':piece}).fetchall() db.execute("update piece set location = 'none' where pieceid = :piece;", {'piece':piece}) db.commit() text = country_name[0][0] + " piece in " + space_name[0][0] + " is picked up by " + active_country_name[0][0] function.updatecontrol(bot, db) import air air.check_reposition(bot, session) bot.send_message(chat_id = group_chat[0][0], text = text) #------------------------------------------Build------------------------------------------ def build_info(bot, country, space_list, card_id, lock_id, session): print('build info') print(space_list) db = sqlite3.connect(session.get_db_dir()) name_list = function.get_name_list(space_list, db) print(name_list) session.space_list_buffer = space_list remain_army_count = db.execute("select count(*) from piece where control = :country and type = 'army' and location = 'none';", {'country':country}).fetchall()[0][0] remain_navy_count = db.execute("select count(*) from piece where control = :country and type = 'navy' and location = 'none';", {'country':country}).fetchall()[0][0] remain_air_count = db.execute("select count(*) from piece where control = :country and type = 'air' and location = 'none';", {'country':country}).fetchall()[0][0] chat_id = db.execute("select playerid from country where id = :country;", {'country':country}).fetchall() text = "Choose a space to build\n" text += "Remain army:" + str(remain_army_count) + "\n" text += "Remain navy:" + str(remain_navy_count) + "\n" text += "Remain air force:" + str(remain_air_count) + "\n" keyboard = [[InlineKeyboardButton(space[1], callback_data="['build', '{}', {}, {}, {}]".format(country, space[0], card_id, lock_id))] for space in name_list] keyboard.append([InlineKeyboardButton('Pass', callback_data="['build', '{}', 'pass', {}, {}]".format(country, card_id, lock_id))]) reply_markup = InlineKeyboardMarkup(keyboard) return chat_id[0][0], text, reply_markup def build_cb(bot, query, query_list, session): db = sqlite3.connect(session.get_db_dir()) if query_list[2] == 'confirm': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) build(bot,query_list[1], query_list[3], query_list[4], session) session.release_lock(query_list[-1]) elif query_list[2] == 'pass': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) session.release_lock(query_list[-1]) else: if query_list[2] == 'back': info = build_info(bot, query_list[1] , session.space_list_buffer, query_list[3], query_list[-1], session) text = info[1] reply_markup = info[2] else: location = db.execute("select name from space where spaceid = :id", {'id':query_list[2]}).fetchall() text = 'Build in ' + location[0][0] + ':' keyboard = [[InlineKeyboardButton('Confirm', callback_data="['build', '{}', 'confirm', {}, {}, {}]".format(query_list[1], query_list[2], query_list[3], query_list[-1]))], [InlineKeyboardButton('Back', callback_data="['build', '{}', 'back', {}, {}]".format(query_list[1], query_list[3], query_list[-1]))]] reply_markup = InlineKeyboardMarkup(keyboard) bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text = text, reply_markup = reply_markup) db.commit() def build(bot, active_country, space, card_id, session): db = sqlite3.connect(session.get_db_dir()) space_info = db.execute("select distinct name, type from space where spaceid = :space;", {'space':space}).fetchall() active_country_name = db.execute("select name from country where id = :country;", {'country':active_country}).fetchall() group_chat = db.execute("select chatid from game;").fetchall() if over_build_handler(bot, active_country, space_info[0][1], session): text = active_country_name[0][0] + " do not remove piece to build" bot.send_message(chat_id = group_chat[0][0], text = text) else: status_handler.status_build_handler(bot, active_country, session) piece = db.execute("select min(pieceid) from piece where location = 'none' and control = :country and type = :piece_type;", {'country':active_country, 'piece_type':function.terrain2type[space_info[0][1]]}).fetchall() db.execute("update piece set location = :location where pieceid = :piece;", {'location':space, 'piece':piece[0][0]}) text = active_country_name[0][0] + " build in " + space_info[0][0] bot.send_message(chat_id = group_chat[0][0], text = text) function.updatecontrol(bot, db) function.updatesupply(db) lock_id = session.add_lock() status_handler.send_status_card(bot, active_country, 'Build', lock_id, session, piece_id = piece[0][0], space_id = space, card_id = card_id) import air air.check_reposition(bot, session) db.commit() #------------------------------------------Recuit------------------------------------------ def recuit_info(bot, country, space_list, card_id, lock_id, session): print('recuit info') print(space_list) db = sqlite3.connect(session.get_db_dir()) name_list = function.get_name_list(space_list, db) print(name_list) remain_army_count = db.execute("select count(*) from piece where control = :country and type = 'army' and location = 'none';", {'country':country}).fetchall()[0][0] remain_navy_count = db.execute("select count(*) from piece where control = :country and type = 'navy' and location = 'none';", {'country':country}).fetchall()[0][0] remain_air_count = db.execute("select count(*) from piece where control = :country and type = 'air' and location = 'none';", {'country':country}).fetchall()[0][0] session.space_list_buffer = space_list chat_id = db.execute("select playerid from country where id = :country;", {'country':country}).fetchall() text = "Choose a space to recuit\n" text += "Remain army:" + str(remain_army_count) + "\n" text += "Remain navy:" + str(remain_navy_count) + "\n" text += "Remain air force:" + str(remain_air_count) + "\n" keyboard = [[InlineKeyboardButton(space[1], callback_data="['recuit', '{}', {}, {}, {}]".format(country, space[0], card_id, lock_id))] for space in name_list] keyboard.append([InlineKeyboardButton('Pass', callback_data="['recuit', '{}', 'pass', {}, {}]".format(country, card_id, lock_id))]) reply_markup = InlineKeyboardMarkup(keyboard) return chat_id[0][0], text, reply_markup def recuit_cb(bot, query, query_list, session): db = sqlite3.connect(session.get_db_dir()) if query_list[2] == 'confirm': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) recuit(bot,query_list[1], query_list[3], query_list[4], session) session.release_lock(query_list[-1]) elif query_list[2] == 'pass': bot.delete_message(chat_id = query.message.chat_id, message_id = query.message.message_id) session.release_lock(query_list[-1]) else: if query_list[2] == 'back': info = recuit_info(bot, query_list[1] , session.space_list_buffer, query_list[3], query_list[-1], session) text = info[1] reply_markup = info[2] else: location = db.execute("select name from space where spaceid = :id", {'id':query_list[2]}).fetchall() text = 'Recuit in ' + location[0][0] + ':' keyboard = [[InlineKeyboardButton('Confirm', callback_data="['recuit', '{}', 'confirm', {}, {}, {}]".format(query_list[1], query_list[2], query_list[3], query_list[-1]))], [InlineKeyboardButton('Back', callback_data="['recuit', '{}', 'back', {}, {}]".format(query_list[1], query_list[3], query_list[-1]))]] reply_markup = InlineKeyboardMarkup(keyboard) bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text = text, reply_markup = reply_markup) db.commit() def recuit(bot, active_country, space, card_id, session): db = sqlite3.connect(session.get_db_dir()) space_info = db.execute("select distinct name, type from space where spaceid = :space;", {'space':space}).fetchall() active_country_name = db.execute("select name from country where id = :country;", {'country':active_country}).fetchall() group_chat = db.execute("select chatid from game;").fetchall() if over_build_handler(bot, active_country, space_info[0][1], session): text = active_country_name[0][0] + " do not remove piece to recuit" bot.send_message(chat_id = group_chat[0][0], text = text) else: status_handler.status_recuit_handler(bot, active_country, session) piece = db.execute("select min(pieceid) from piece where location = 'none' and control = :country and type = :piece_type;", {'country':active_country, 'piece_type':function.terrain2type[space_info[0][1]]}).fetchall() db.execute("update piece set location = :location where pieceid = :piece;", {'location':space, 'piece':piece[0][0]}) text = active_country_name[0][0] + " recuit in " + space_info[0][0] bot.send_message(chat_id = group_chat[0][0], text = text) function.updatecontrol(bot, db) function.updatesupply(db) lock_id = session.add_lock() status_handler.send_status_card(bot, active_country, 'Recruit', lock_id, session, piece_id = piece[0][0], space_id = space, card_id = card_id) import air air.check_reposition(bot, session) db.commit() #------------------------------------------Over_Build_Handler------------------------------------------ def over_build_handler(bot, active_country, space_type, session): db = sqlite3.connect(session.get_db_dir()) if db.execute("select count(*) from piece where location = 'none' and control = :country and type = :piece_type;", {'country':active_country, 'piece_type':function.terrain2type[space_type]}).fetchall()[0][0] == 0: lock_id = session.add_lock() space_list = function.control_space_list(active_country, db, space_type = space_type) session.self_remove_list.append(self_remove(active_country, space_list, None, lock_id, function.terrain2type[space_type], session)) self_remove_id = len(session.self_remove_list)-1 info = session.self_remove_list[self_remove_id].self_remove_info(session) bot.send_message(chat_id = info[0], text = info[1], reply_markup = info[2]) session.thread_lock(lock_id) return (db.execute("select count(*) from piece where location = 'none' and control = :country and type = :piece_type;", {'country':active_country, 'piece_type':function.terrain2type[space_type]}).fetchall()[0][0] == 0) #------------------------------------------Restore------------------------------------------ def restore(bot, piece, space, session): db = sqlite3.connect(session.get_db_dir()) space_info = db.execute("select distinct name, type from space where spaceid = :space;", {'space':space}).fetchall() group_chat = db.execute("select chatid from game;").fetchall() db.execute("update piece set location = :location where pieceid = :piece;", {'location':space, 'piece':piece}) function.updatecontrol(bot, db) import air air.check_reposition(bot, session) text = "Piece in " + space_info[0][0] + " not removed" bot.send_message(chat_id = group_chat[0][0], text = text) db.commit()
pt
0.083994
#------------------------------------------Battle------------------------------------------ #------------------------------------------Remove------------------------------------------ #------------------------------------------Self_Remove------------------------------------------ #keyboard.append([InlineKeyboardButton('Pass', callback_data="['self_remove','pass', {}]".format(self.self_remove_id))]) #------------------------------------------Move------------------------------------------ #------------------------------------------Build------------------------------------------ #------------------------------------------Recuit------------------------------------------ #------------------------------------------Over_Build_Handler------------------------------------------ #------------------------------------------Restore------------------------------------------
2.662015
3
AGV_emotions_attack/attacks_emotions/agv/log.py
Ellyuca/AGV-Project
0
6620587
class Log(object): def __init__(self, path, append=False): self.f_log = open(path,"w" if not append else "a+") def log(self, *args): self.f_log.write(*args) self.f_log.write("\n") self.f_log.flush() def close(self): self.f_log.close() def __del__(self): self.f_log.close()
class Log(object): def __init__(self, path, append=False): self.f_log = open(path,"w" if not append else "a+") def log(self, *args): self.f_log.write(*args) self.f_log.write("\n") self.f_log.flush() def close(self): self.f_log.close() def __del__(self): self.f_log.close()
none
1
3.314954
3
tests/test_converter.py
vyahello/calorie-counter
5
6620588
<reponame>vyahello/calorie-counter<filename>tests/test_converter.py import os import pytest from counter.converter import csv_to_json from counter.writer import write_to_file _path: str = f"{os.path.join(os.path.dirname(__file__), 'test.csv')}" @pytest.fixture(scope="module", autouse=True) def setup_data() -> None: write_to_file( _path, ( "Category,Item,Serving Size,Calories,Calories from Fat," "Total Fat,Total Fat (% Daily Value),Saturated Fat\n" "Breakfast,Egg McMuffin,4.8 oz (136 g),300,120,13,20,5\n" "Breakfast,Egg White Delight,4.8 oz (135 g),250,70,8,12,3\n" ), mode="a", ) yield os.remove(_path) def test_csv_to_json() -> None: assert ( csv_to_json(_path) == '{"Egg McMuffin [4.8 oz / 136 g]": "300", ' '"Egg White Delight [4.8 oz / 135 g]": "250"}' )
import os import pytest from counter.converter import csv_to_json from counter.writer import write_to_file _path: str = f"{os.path.join(os.path.dirname(__file__), 'test.csv')}" @pytest.fixture(scope="module", autouse=True) def setup_data() -> None: write_to_file( _path, ( "Category,Item,Serving Size,Calories,Calories from Fat," "Total Fat,Total Fat (% Daily Value),Saturated Fat\n" "Breakfast,Egg McMuffin,4.8 oz (136 g),300,120,13,20,5\n" "Breakfast,Egg White Delight,4.8 oz (135 g),250,70,8,12,3\n" ), mode="a", ) yield os.remove(_path) def test_csv_to_json() -> None: assert ( csv_to_json(_path) == '{"Egg McMuffin [4.8 oz / 136 g]": "300", ' '"Egg White Delight [4.8 oz / 135 g]": "250"}' )
none
1
2.430977
2
tests/utils/testAType.py
DedeKite/wxPlotLab
6
6620589
<reponame>DedeKite/wxPlotLab # -*-coding:Utf-8 -* import unittest from mplotlab.utils.abctypes import LIST,\ STRING,\ COLOR,\ INT,\ BOOL import numpy as np class TestAType(unittest.TestCase): def test_LIST(self): ali = LIST() l = ali.getBase() l.append(BOOL(False)) l.append(INT(36)) msg=ali.tostringxml("mylist") msgRef=\ """<root><mylist type="LIST">"""+\ """<elem type="BOOL">0</elem>"""+\ """<elem type="INT">36</elem>"""+\ """</mylist></root>""" self.assertEqual(msgRef, msg) if __name__ == '__main__': unittest.main()
# -*-coding:Utf-8 -* import unittest from mplotlab.utils.abctypes import LIST,\ STRING,\ COLOR,\ INT,\ BOOL import numpy as np class TestAType(unittest.TestCase): def test_LIST(self): ali = LIST() l = ali.getBase() l.append(BOOL(False)) l.append(INT(36)) msg=ali.tostringxml("mylist") msgRef=\ """<root><mylist type="LIST">"""+\ """<elem type="BOOL">0</elem>"""+\ """<elem type="INT">36</elem>"""+\ """</mylist></root>""" self.assertEqual(msgRef, msg) if __name__ == '__main__': unittest.main()
en
0.303203
# -*-coding:Utf-8 -* <root><mylist type="LIST"> <elem type="BOOL">0</elem> <elem type="INT">36</elem> </mylist></root>
3.076659
3
bot.py
thinkzink/idiomata-bot
0
6620590
#!/usr/bin/env python # -*- coding: utf-8 -*- """Simple Bot to reply to Telegram messages. This is built on the API wrapper, see echobot2.py to see the same example built on the telegram.ext bot framework. This program is dedicated to the public domain under the CC0 license. """ import logging import telegram import mielke_tokenizer as tok import lang_id from telegram.error import NetworkError, Unauthorized from time import sleep from collections import defaultdict update_id = None user_stats = defaultdict(lambda: UserStats()) lang_ider = lang_id.WordCountBasedLanguageID() class UserStats(): def __init__(self): self.words_written = 0 self.words_in_lang = defaultdict(lambda: 0) def main(): """Run the bot.""" global update_id # Telegram Bot Authorization Token with open('token.txt', 'r') as f: token = f.readline().strip() bot = telegram.Bot(token) # get the first pending update_id, this is so we can skip over it in case # we get an "Unauthorized" exception. try: update_id = bot.get_updates()[0].update_id except IndexError: update_id = None logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') while True: try: echo(bot) except NetworkError: sleep(1) except Unauthorized: # The user has removed or blocked the bot. update_id += 1 def echo(bot): """Echo the message the user sent.""" global update_id # Request updates after the last update_id for update in bot.get_updates(offset=update_id, timeout=10): update_id = update.update_id + 1 if update.message: # your bot can receive updates without messages # Reply to the message user = update.effective_user text = update.message.text entities = update.message.parse_entities() # Parse mentions if '@IdiomataBot' in entities.values(): if 'my score' in text: my_sum = float(sum(user_stats[user.id].words_in_lang.values())) my_cnts = [(cnt/my_sum, word) for (word, cnt) in user_stats[user.id].words_in_lang.items() if cnt/my_sum > 0.01] my_cnts.sort(reverse=True) words_in_lang_string = ', '.join([f'{cnt*100:.1f}% words in {lang}' for (cnt, lang) in my_cnts]) update.message.reply_text(f'{user.first_name} has written {words_in_lang_string}') else: update.message.reply_text('Sorry, I couldn\'t recognize that command') # Parse normal messages else: tokenized_message = tok.tokenize(str(text)).split() user_stats[user.id].words_written += len(tokenized_message) words = user_stats[user.id].words_written word_langs = lang_ider.id_words(tokenized_message, id_type='name') print(tokenized_message) print(word_langs) for word_lang in word_langs: user_stats[user.id].words_in_lang[word_lang] += 1 if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- """Simple Bot to reply to Telegram messages. This is built on the API wrapper, see echobot2.py to see the same example built on the telegram.ext bot framework. This program is dedicated to the public domain under the CC0 license. """ import logging import telegram import mielke_tokenizer as tok import lang_id from telegram.error import NetworkError, Unauthorized from time import sleep from collections import defaultdict update_id = None user_stats = defaultdict(lambda: UserStats()) lang_ider = lang_id.WordCountBasedLanguageID() class UserStats(): def __init__(self): self.words_written = 0 self.words_in_lang = defaultdict(lambda: 0) def main(): """Run the bot.""" global update_id # Telegram Bot Authorization Token with open('token.txt', 'r') as f: token = f.readline().strip() bot = telegram.Bot(token) # get the first pending update_id, this is so we can skip over it in case # we get an "Unauthorized" exception. try: update_id = bot.get_updates()[0].update_id except IndexError: update_id = None logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') while True: try: echo(bot) except NetworkError: sleep(1) except Unauthorized: # The user has removed or blocked the bot. update_id += 1 def echo(bot): """Echo the message the user sent.""" global update_id # Request updates after the last update_id for update in bot.get_updates(offset=update_id, timeout=10): update_id = update.update_id + 1 if update.message: # your bot can receive updates without messages # Reply to the message user = update.effective_user text = update.message.text entities = update.message.parse_entities() # Parse mentions if '@IdiomataBot' in entities.values(): if 'my score' in text: my_sum = float(sum(user_stats[user.id].words_in_lang.values())) my_cnts = [(cnt/my_sum, word) for (word, cnt) in user_stats[user.id].words_in_lang.items() if cnt/my_sum > 0.01] my_cnts.sort(reverse=True) words_in_lang_string = ', '.join([f'{cnt*100:.1f}% words in {lang}' for (cnt, lang) in my_cnts]) update.message.reply_text(f'{user.first_name} has written {words_in_lang_string}') else: update.message.reply_text('Sorry, I couldn\'t recognize that command') # Parse normal messages else: tokenized_message = tok.tokenize(str(text)).split() user_stats[user.id].words_written += len(tokenized_message) words = user_stats[user.id].words_written word_langs = lang_ider.id_words(tokenized_message, id_type='name') print(tokenized_message) print(word_langs) for word_lang in word_langs: user_stats[user.id].words_in_lang[word_lang] += 1 if __name__ == '__main__': main()
en
0.732829
#!/usr/bin/env python # -*- coding: utf-8 -*- Simple Bot to reply to Telegram messages. This is built on the API wrapper, see echobot2.py to see the same example built on the telegram.ext bot framework. This program is dedicated to the public domain under the CC0 license. Run the bot. # Telegram Bot Authorization Token # get the first pending update_id, this is so we can skip over it in case # we get an "Unauthorized" exception. # The user has removed or blocked the bot. Echo the message the user sent. # Request updates after the last update_id # your bot can receive updates without messages # Reply to the message # Parse mentions # Parse normal messages
3.119707
3
dask_cuda/explicit_comms/dataframe/merge.py
Ethyling/dask-cuda
0
6620591
<gh_stars>0 import asyncio from collections import defaultdict from toolz import first from dask import dataframe as dd from dask.dataframe.core import _concat from dask.dataframe.shuffle import partitioning_index, shuffle_group from distributed.client import get_client, wait from distributed.protocol import to_serialize from .. import comms async def send_df(ep, df): if df is None: return await ep.write(None) else: return await ep.write([to_serialize(df)]) async def recv_df(ep): ret = await ep.read() if ret is None: return None else: return ret[0] async def send_bins(eps, bins): futures = [] for rank, ep in eps.items(): futures.append(send_df(ep, bins[rank])) await asyncio.gather(*futures) async def recv_bins(eps, bins): futures = [] for ep in eps.values(): futures.append(recv_df(ep)) bins.extend(await asyncio.gather(*futures)) async def exchange_and_concat_bins(rank, eps, bins): ret = [bins[rank]] await asyncio.gather(recv_bins(eps, ret), send_bins(eps, bins)) return _concat([df for df in ret if df is not None]) def df_concat(df_parts): """Making sure df_parts is a single dataframe or None""" if len(df_parts) == 0: return None elif len(df_parts) == 1: return df_parts[0] else: return _concat(df_parts) async def broadcast(rank, root_rank, eps, df=None): if rank == root_rank: await asyncio.gather(*[send_df(ep, df) for ep in eps.values()]) return df else: return await recv_df(eps[root_rank]) def partition_by_hash(df, columns, n_chunks, ignore_index=False): """Splits dataframe into partitions The partitions is determined by the hash value of the rows in `columns`. Parameters ---------- df: DataFrame columns: label or list Column names on which to split the dataframe npartition: int Number of partitions ignore_index : bool, default False Set True to ignore the index of `df` Returns ------- out: Dict[int, DataFrame] A dictionary mapping integers in {0..npartition} to dataframes. """ if df is None: return [None] * n_chunks # Hashing `columns` in `df` and assign it to the "_partitions" column df["_partitions"] = partitioning_index(df[columns], n_chunks) # Split `df` based on the hash values in the "_partitions" column try: # For Dask < 2.17 compatibility ret = shuffle_group(df, "_partitions", 0, n_chunks, n_chunks, ignore_index) except TypeError: ret = shuffle_group( df, "_partitions", 0, n_chunks, n_chunks, ignore_index, n_chunks ) # Let's remove the partition column and return the partitions del df["_partitions"] for df in ret.values(): del df["_partitions"] return ret async def hash_join(n_chunks, rank, eps, left_table, right_table, left_on, right_on): left_bins = partition_by_hash(left_table, left_on, n_chunks, ignore_index=True) left_df = exchange_and_concat_bins(rank, eps, left_bins) right_bins = partition_by_hash(right_table, right_on, n_chunks, ignore_index=True) left_df = await left_df right_df = await exchange_and_concat_bins(rank, eps, right_bins) return left_df.merge(right_df, left_on=left_on, right_on=right_on) async def single_partition_join( n_chunks, rank, eps, left_table, right_table, left_on, right_on, single_table, single_rank, ): if single_table == "left": left_table = await broadcast(rank, single_rank, eps, left_table) else: assert single_table == "right" right_table = await broadcast(rank, single_rank, eps, right_table) return left_table.merge(right_table, left_on=left_on, right_on=right_on) async def local_df_merge(s, workers, dfs_nparts, dfs_parts, left_on, right_on): """Worker job that merge local DataFrames Parameters ---------- s: dict Worker session state workers: set Set of ranks of all the participants dfs_nparts: list of dict List of dict that for each worker rank specifices the number of partitions that worker has. If the worker doesn't have any partitions, it is excluded from the dict. E.g. `dfs_nparts[0][1]` is how many partitions of the "left" dataframe worker 1 has. dfs_parts: list of lists of Dataframes List of inputs, which in this case are two dataframe lists. left_on : str or list of str Column to join on in the left DataFrame. right_on : str or list of str Column to join on in the right DataFrame. Returns ------- df: DataFrame Merged dataframe """ assert s["rank"] in workers # Trimming such that all participanting workers get a rank within 0..len(workers) trim_map = {} for i in range(s["nworkers"]): if i in workers: trim_map[i] = len(trim_map) rank = trim_map[s["rank"]] eps = {trim_map[i]: s["eps"][trim_map[i]] for i in workers if i != s["rank"]} df1 = df_concat(dfs_parts[0]) df2 = df_concat(dfs_parts[1]) if len(dfs_nparts[0]) == 1 and len(dfs_nparts[1]) == 1: return df1.merge(df2, left_on=left_on, right_on=right_on) elif len(dfs_nparts[0]) == 1: return await single_partition_join( len(workers), rank, eps, df1, df2, left_on, right_on, "left", trim_map[ next(iter(dfs_nparts[0])) ], # Extracting the only key in `dfs_nparts[0]` ) elif len(dfs_nparts[1]) == 1: return await single_partition_join( len(workers), rank, eps, df1, df2, left_on, right_on, "right", trim_map[ next(iter(dfs_nparts[1])) ], # Extracting the only key in `dfs_nparts[1]` ) else: return await hash_join(len(workers), rank, eps, df1, df2, left_on, right_on) def extract_ddf_partitions(ddf): """ Returns the mapping: worker -> [list of futures]""" client = get_client() delayed_ddf = ddf.to_delayed() parts = client.compute(delayed_ddf) wait(parts) key_to_part = dict([(str(part.key), part) for part in parts]) ret = defaultdict(list) # Map worker -> [list of futures] for key, workers in client.who_has(parts).items(): worker = first( workers ) # If multiple workers have the part, we pick the first worker ret[worker].append(key_to_part[key]) return ret def submit_dataframe_operation(comms, coroutine, df_list, extra_args=()): """Submit an operation on a list of Dask dataframe Parameters ---------- coroutine: coroutine The function to run on each worker. df_list: list of Dask.dataframe.Dataframe Input dataframes extra_args: tuple Extra function input Returns ------- dataframe: dask.dataframe.DataFrame The resulting dataframe """ df_parts_list = [] for df in df_list: df_parts_list.append(extract_ddf_partitions(df)) # Let's create a dict for each dataframe that specifices the # number of partitions each worker has world = set() dfs_nparts = [] for df_parts in df_parts_list: nparts = {} for rank, worker in enumerate(comms.worker_addresses): npart = len(df_parts.get(worker, [])) if npart > 0: nparts[rank] = npart world.add(rank) dfs_nparts.append(nparts) # Submit `coroutine` on each worker given the df_parts that # belong the specific worker as input ret = [] for rank, worker in enumerate(comms.worker_addresses): if rank in world: dfs = [] for df_parts in df_parts_list: dfs.append(df_parts.get(worker, [])) ret.append( comms.submit(worker, coroutine, world, dfs_nparts, dfs, *extra_args) ) wait(ret) return dd.from_delayed(ret) def merge(left, right, on=None, left_on=None, right_on=None): """Merge two DataFrames using explicit-comms. This is an explicit-comms version of Dask's Dataframe.merge() that only supports "inner" joins. Requires an activate client. Notice ------ As a side effect, this operation concatenate all partitions located on the same worker thus npartitions of the returned dataframe equals number of workers. Parameters ---------- left: dask.dataframe.DataFrame right: dask.dataframe.DataFrame on : str or list of str Column or index level names to join on. These must be found in both DataFrames. left_on : str or list of str Column to join on in the left DataFrame. right_on : str or list of str Column to join on in the right DataFrame. Returns ------- df: dask.dataframe.DataFrame Merged dataframe """ # Making sure that the "on" arguments are list of column names if on: on = [on] if isinstance(on, str) else list(on) if left_on: left_on = [left_on] if isinstance(left_on, str) else list(left_on) if right_on: right_on = [right_on] if isinstance(right_on, str) else list(right_on) if left_on is None: left_on = on if right_on is None: right_on = on if not (left_on and right_on): raise ValueError( "Some combination of the on, left_on, and right_on arguments must be set" ) return submit_dataframe_operation( comms.default_comms(), local_df_merge, df_list=(left, right), extra_args=(left_on, right_on), )
import asyncio from collections import defaultdict from toolz import first from dask import dataframe as dd from dask.dataframe.core import _concat from dask.dataframe.shuffle import partitioning_index, shuffle_group from distributed.client import get_client, wait from distributed.protocol import to_serialize from .. import comms async def send_df(ep, df): if df is None: return await ep.write(None) else: return await ep.write([to_serialize(df)]) async def recv_df(ep): ret = await ep.read() if ret is None: return None else: return ret[0] async def send_bins(eps, bins): futures = [] for rank, ep in eps.items(): futures.append(send_df(ep, bins[rank])) await asyncio.gather(*futures) async def recv_bins(eps, bins): futures = [] for ep in eps.values(): futures.append(recv_df(ep)) bins.extend(await asyncio.gather(*futures)) async def exchange_and_concat_bins(rank, eps, bins): ret = [bins[rank]] await asyncio.gather(recv_bins(eps, ret), send_bins(eps, bins)) return _concat([df for df in ret if df is not None]) def df_concat(df_parts): """Making sure df_parts is a single dataframe or None""" if len(df_parts) == 0: return None elif len(df_parts) == 1: return df_parts[0] else: return _concat(df_parts) async def broadcast(rank, root_rank, eps, df=None): if rank == root_rank: await asyncio.gather(*[send_df(ep, df) for ep in eps.values()]) return df else: return await recv_df(eps[root_rank]) def partition_by_hash(df, columns, n_chunks, ignore_index=False): """Splits dataframe into partitions The partitions is determined by the hash value of the rows in `columns`. Parameters ---------- df: DataFrame columns: label or list Column names on which to split the dataframe npartition: int Number of partitions ignore_index : bool, default False Set True to ignore the index of `df` Returns ------- out: Dict[int, DataFrame] A dictionary mapping integers in {0..npartition} to dataframes. """ if df is None: return [None] * n_chunks # Hashing `columns` in `df` and assign it to the "_partitions" column df["_partitions"] = partitioning_index(df[columns], n_chunks) # Split `df` based on the hash values in the "_partitions" column try: # For Dask < 2.17 compatibility ret = shuffle_group(df, "_partitions", 0, n_chunks, n_chunks, ignore_index) except TypeError: ret = shuffle_group( df, "_partitions", 0, n_chunks, n_chunks, ignore_index, n_chunks ) # Let's remove the partition column and return the partitions del df["_partitions"] for df in ret.values(): del df["_partitions"] return ret async def hash_join(n_chunks, rank, eps, left_table, right_table, left_on, right_on): left_bins = partition_by_hash(left_table, left_on, n_chunks, ignore_index=True) left_df = exchange_and_concat_bins(rank, eps, left_bins) right_bins = partition_by_hash(right_table, right_on, n_chunks, ignore_index=True) left_df = await left_df right_df = await exchange_and_concat_bins(rank, eps, right_bins) return left_df.merge(right_df, left_on=left_on, right_on=right_on) async def single_partition_join( n_chunks, rank, eps, left_table, right_table, left_on, right_on, single_table, single_rank, ): if single_table == "left": left_table = await broadcast(rank, single_rank, eps, left_table) else: assert single_table == "right" right_table = await broadcast(rank, single_rank, eps, right_table) return left_table.merge(right_table, left_on=left_on, right_on=right_on) async def local_df_merge(s, workers, dfs_nparts, dfs_parts, left_on, right_on): """Worker job that merge local DataFrames Parameters ---------- s: dict Worker session state workers: set Set of ranks of all the participants dfs_nparts: list of dict List of dict that for each worker rank specifices the number of partitions that worker has. If the worker doesn't have any partitions, it is excluded from the dict. E.g. `dfs_nparts[0][1]` is how many partitions of the "left" dataframe worker 1 has. dfs_parts: list of lists of Dataframes List of inputs, which in this case are two dataframe lists. left_on : str or list of str Column to join on in the left DataFrame. right_on : str or list of str Column to join on in the right DataFrame. Returns ------- df: DataFrame Merged dataframe """ assert s["rank"] in workers # Trimming such that all participanting workers get a rank within 0..len(workers) trim_map = {} for i in range(s["nworkers"]): if i in workers: trim_map[i] = len(trim_map) rank = trim_map[s["rank"]] eps = {trim_map[i]: s["eps"][trim_map[i]] for i in workers if i != s["rank"]} df1 = df_concat(dfs_parts[0]) df2 = df_concat(dfs_parts[1]) if len(dfs_nparts[0]) == 1 and len(dfs_nparts[1]) == 1: return df1.merge(df2, left_on=left_on, right_on=right_on) elif len(dfs_nparts[0]) == 1: return await single_partition_join( len(workers), rank, eps, df1, df2, left_on, right_on, "left", trim_map[ next(iter(dfs_nparts[0])) ], # Extracting the only key in `dfs_nparts[0]` ) elif len(dfs_nparts[1]) == 1: return await single_partition_join( len(workers), rank, eps, df1, df2, left_on, right_on, "right", trim_map[ next(iter(dfs_nparts[1])) ], # Extracting the only key in `dfs_nparts[1]` ) else: return await hash_join(len(workers), rank, eps, df1, df2, left_on, right_on) def extract_ddf_partitions(ddf): """ Returns the mapping: worker -> [list of futures]""" client = get_client() delayed_ddf = ddf.to_delayed() parts = client.compute(delayed_ddf) wait(parts) key_to_part = dict([(str(part.key), part) for part in parts]) ret = defaultdict(list) # Map worker -> [list of futures] for key, workers in client.who_has(parts).items(): worker = first( workers ) # If multiple workers have the part, we pick the first worker ret[worker].append(key_to_part[key]) return ret def submit_dataframe_operation(comms, coroutine, df_list, extra_args=()): """Submit an operation on a list of Dask dataframe Parameters ---------- coroutine: coroutine The function to run on each worker. df_list: list of Dask.dataframe.Dataframe Input dataframes extra_args: tuple Extra function input Returns ------- dataframe: dask.dataframe.DataFrame The resulting dataframe """ df_parts_list = [] for df in df_list: df_parts_list.append(extract_ddf_partitions(df)) # Let's create a dict for each dataframe that specifices the # number of partitions each worker has world = set() dfs_nparts = [] for df_parts in df_parts_list: nparts = {} for rank, worker in enumerate(comms.worker_addresses): npart = len(df_parts.get(worker, [])) if npart > 0: nparts[rank] = npart world.add(rank) dfs_nparts.append(nparts) # Submit `coroutine` on each worker given the df_parts that # belong the specific worker as input ret = [] for rank, worker in enumerate(comms.worker_addresses): if rank in world: dfs = [] for df_parts in df_parts_list: dfs.append(df_parts.get(worker, [])) ret.append( comms.submit(worker, coroutine, world, dfs_nparts, dfs, *extra_args) ) wait(ret) return dd.from_delayed(ret) def merge(left, right, on=None, left_on=None, right_on=None): """Merge two DataFrames using explicit-comms. This is an explicit-comms version of Dask's Dataframe.merge() that only supports "inner" joins. Requires an activate client. Notice ------ As a side effect, this operation concatenate all partitions located on the same worker thus npartitions of the returned dataframe equals number of workers. Parameters ---------- left: dask.dataframe.DataFrame right: dask.dataframe.DataFrame on : str or list of str Column or index level names to join on. These must be found in both DataFrames. left_on : str or list of str Column to join on in the left DataFrame. right_on : str or list of str Column to join on in the right DataFrame. Returns ------- df: dask.dataframe.DataFrame Merged dataframe """ # Making sure that the "on" arguments are list of column names if on: on = [on] if isinstance(on, str) else list(on) if left_on: left_on = [left_on] if isinstance(left_on, str) else list(left_on) if right_on: right_on = [right_on] if isinstance(right_on, str) else list(right_on) if left_on is None: left_on = on if right_on is None: right_on = on if not (left_on and right_on): raise ValueError( "Some combination of the on, left_on, and right_on arguments must be set" ) return submit_dataframe_operation( comms.default_comms(), local_df_merge, df_list=(left, right), extra_args=(left_on, right_on), )
en
0.750216
Making sure df_parts is a single dataframe or None Splits dataframe into partitions The partitions is determined by the hash value of the rows in `columns`. Parameters ---------- df: DataFrame columns: label or list Column names on which to split the dataframe npartition: int Number of partitions ignore_index : bool, default False Set True to ignore the index of `df` Returns ------- out: Dict[int, DataFrame] A dictionary mapping integers in {0..npartition} to dataframes. # Hashing `columns` in `df` and assign it to the "_partitions" column # Split `df` based on the hash values in the "_partitions" column # For Dask < 2.17 compatibility # Let's remove the partition column and return the partitions Worker job that merge local DataFrames Parameters ---------- s: dict Worker session state workers: set Set of ranks of all the participants dfs_nparts: list of dict List of dict that for each worker rank specifices the number of partitions that worker has. If the worker doesn't have any partitions, it is excluded from the dict. E.g. `dfs_nparts[0][1]` is how many partitions of the "left" dataframe worker 1 has. dfs_parts: list of lists of Dataframes List of inputs, which in this case are two dataframe lists. left_on : str or list of str Column to join on in the left DataFrame. right_on : str or list of str Column to join on in the right DataFrame. Returns ------- df: DataFrame Merged dataframe # Trimming such that all participanting workers get a rank within 0..len(workers) # Extracting the only key in `dfs_nparts[0]` # Extracting the only key in `dfs_nparts[1]` Returns the mapping: worker -> [list of futures] # Map worker -> [list of futures] # If multiple workers have the part, we pick the first worker Submit an operation on a list of Dask dataframe Parameters ---------- coroutine: coroutine The function to run on each worker. df_list: list of Dask.dataframe.Dataframe Input dataframes extra_args: tuple Extra function input Returns ------- dataframe: dask.dataframe.DataFrame The resulting dataframe # Let's create a dict for each dataframe that specifices the # number of partitions each worker has # Submit `coroutine` on each worker given the df_parts that # belong the specific worker as input Merge two DataFrames using explicit-comms. This is an explicit-comms version of Dask's Dataframe.merge() that only supports "inner" joins. Requires an activate client. Notice ------ As a side effect, this operation concatenate all partitions located on the same worker thus npartitions of the returned dataframe equals number of workers. Parameters ---------- left: dask.dataframe.DataFrame right: dask.dataframe.DataFrame on : str or list of str Column or index level names to join on. These must be found in both DataFrames. left_on : str or list of str Column to join on in the left DataFrame. right_on : str or list of str Column to join on in the right DataFrame. Returns ------- df: dask.dataframe.DataFrame Merged dataframe # Making sure that the "on" arguments are list of column names
2.388116
2
Deep Count.py
fatih-iver-2016400264/Intro-to-Computer-Science-with-Python
0
6620592
<reponame>fatih-iver-2016400264/Intro-to-Computer-Science-with-Python<gh_stars>0 # Deep Count # The built-in len operator outputs the number of top-level elements in a List, # but not the total number of elements. For this question, your goal is to count # the total number of elements in a list, including all of the inner lists. # Define a procedure, deep_count, that takes as input a list, and outputs the # total number of elements in the list, including all elements in lists that it # contains. # For this procedure, you will need a way to test if a value is a list. We have # provided a procedure, is_list(p) that does this: def is_list(p): return isinstance(p, list) # It is not necessary to understand how is_list works. It returns True if the # input is a List, and returns False otherwise. def deep_count(p): total = 0 for elem in p: if is_list(elem): total += 1 total += deep_count(elem) else: total += 1 return total print (deep_count([1, 2, 3])) #>>> 3 # The empty list still counts as an element of the outer list print (deep_count([1, [], 3])) #>>> 3 print (deep_count([1, [1, 2, [3, 4]]])) #>>> 7 print (deep_count([[[[[[[[1, 2, 3]]]]]]]])) #>>> 10
# Deep Count # The built-in len operator outputs the number of top-level elements in a List, # but not the total number of elements. For this question, your goal is to count # the total number of elements in a list, including all of the inner lists. # Define a procedure, deep_count, that takes as input a list, and outputs the # total number of elements in the list, including all elements in lists that it # contains. # For this procedure, you will need a way to test if a value is a list. We have # provided a procedure, is_list(p) that does this: def is_list(p): return isinstance(p, list) # It is not necessary to understand how is_list works. It returns True if the # input is a List, and returns False otherwise. def deep_count(p): total = 0 for elem in p: if is_list(elem): total += 1 total += deep_count(elem) else: total += 1 return total print (deep_count([1, 2, 3])) #>>> 3 # The empty list still counts as an element of the outer list print (deep_count([1, [], 3])) #>>> 3 print (deep_count([1, [1, 2, [3, 4]]])) #>>> 7 print (deep_count([[[[[[[[1, 2, 3]]]]]]]])) #>>> 10
en
0.878094
# Deep Count # The built-in len operator outputs the number of top-level elements in a List, # but not the total number of elements. For this question, your goal is to count # the total number of elements in a list, including all of the inner lists. # Define a procedure, deep_count, that takes as input a list, and outputs the # total number of elements in the list, including all elements in lists that it # contains. # For this procedure, you will need a way to test if a value is a list. We have # provided a procedure, is_list(p) that does this: # It is not necessary to understand how is_list works. It returns True if the # input is a List, and returns False otherwise. #>>> 3 # The empty list still counts as an element of the outer list #>>> 3 #>>> 7 #>>> 10
4.380731
4
_solutions/pandas/import-export/pandas_readjson_a.py
sages-pl/2022-01-pythonsqlalchemy-aptiv
0
6620593
<reponame>sages-pl/2022-01-pythonsqlalchemy-aptiv result = pd.read_json(DATA)
result = pd.read_json(DATA)
none
1
1.782552
2
app/app/test.py
shashanksri99/recipe-app-api
0
6620594
from django.test import TestCase from app.calc import add, substract class CalcTest(TestCase): def test_add_numbers(self): """ Test that two numbers are added together """ self.assertEqual(add(3, 8), 11) def test_subtract_numbers(self): """ This will substract two numbers and return the result """ self.assertEqual(substract(8, 3), 5)
from django.test import TestCase from app.calc import add, substract class CalcTest(TestCase): def test_add_numbers(self): """ Test that two numbers are added together """ self.assertEqual(add(3, 8), 11) def test_subtract_numbers(self): """ This will substract two numbers and return the result """ self.assertEqual(substract(8, 3), 5)
en
0.910617
Test that two numbers are added together This will substract two numbers and return the result
3.331411
3
30 Days of Code Challenges/Day 3: Intro to Conditional Statements.py
ArchieR7/HackerRank
2
6620595
<reponame>ArchieR7/HackerRank import sys N = int(input().strip()) if N % 2 == 1 or 6 <= N <= 20: print("Weird") else : print("Not Weird")
import sys N = int(input().strip()) if N % 2 == 1 or 6 <= N <= 20: print("Weird") else : print("Not Weird")
none
1
3.645151
4
src/repo.py
Jpfonseca/Blockchain_auction_management
0
6620596
import hashlib import os, datetime, sys, json, base64, re, copy import random import string from os import listdir from ast import literal_eval from socket import * from blockchain import * from logging import DEBUG, ERROR, INFO from log import LoggyLogglyMcface from security import * from cc_interface import PortugueseCitizenCard HOST = "127.0.0.1" PORT_MAN = 8080 PORT_REPO = 8081 MAX_BUFFER_SIZE = 10000 class Repository(): def __init__(self, host, port): LOG = "./log.txt" for filename in listdir("./"): if filename == "log.txt": os.remove(LOG) self.mylogger = LoggyLogglyMcface(name=Repository.__name__) self.mylogger.log(INFO, "Entering Repository interface") # repository information self.name = Repository.__name__ self.privKname = "privK" + self.name self.password = "<PASSWORD>" self.repo_pubkey = None self.man_pubkey = None self.host = host self.port = port self.loggedInClient = 0 # client public keys self.clients_pubkey = set() # Addresses of clients and manager self.address_client = [] self.manager_address = None # list of active and closed auctions self.active_auctions = [] self.closed_auctions = [] self.all_auctions = [] self.sock = socket(AF_INET, SOCK_DGRAM) self.sock.bind((self.host, self.port)) # incremental serial number of the auctions self.serial = 0 # hash of the previous block (auction serial, previous hash) self.hash_prev = {} # generate public and private key self.certgen = GenerateCertificates() self.certops = CertificateOperations() self.crypto = CryptoUtils() # dictionary of id of the client and public key self.pubkey_dict = {} # client is waiting for message (after sending proof-of-work result) self.current_client = None self.client_waiting = False def start(self): """ Servers and Client exchange public keys """ try: # verify if repository private key already exists. load if true if self.certgen.checkExistence(self.name): self.certgen.loadPrivateKeyFromFile(self.privKname, password=self.password) else: self.certgen.writePrivateKeyToFile(self.privKname, password=self.password) self.repo_pubkey = self.certgen.publicKeyToBytes() print("Listening...") self.mylogger.log(INFO, "Exchanging public key with the manager") data1, self.manager_address = self.sock.recvfrom(MAX_BUFFER_SIZE) print("> manager pubkey received") msg = json.dumps({'repo_pubk': self.repo_pubkey.decode()}) bytes = self.sock.sendto(msg.encode(), self.manager_address) self.mylogger.log(INFO, "Manager public key received") data1 = json.loads(data1) if 'man_pubk' in data1: self.man_pubkey = data1['man_pubk'] self.mylogger.log(INFO, "Man Pubkey : \n{}".format(self.man_pubkey)) self.mylogger.log(INFO, "Exchanging public key with the client") data2, client_addr = self.sock.recvfrom(MAX_BUFFER_SIZE) print("> client pubkey received") bytes = self.sock.sendto(msg.encode(), client_addr) self.mylogger.log(INFO, "Client public key received") data2 = json.loads(data2) self.client_login(data2, client_addr) self.loop() except: self.mylogger.log(INFO, "Cannot start repository") raise def loop(self): """ The main loop of the repository. It waits for messages of clients (both system clients or servers) and calls functions according to the received messages """ try: while (True): date_time = datetime.datetime.now() for auction in self.active_auctions: timestamp_auction = datetime.datetime.strptime(auction.timestamp, '%m/%d/%Y, %H:%M:%S') delta = date_time - timestamp_auction seconds = delta.days * 24 * 3600 + delta.seconds time_limit = re.findall('\d+', auction.time_limit) time_limit = (int(time_limit[0]) * 3600) + (int(time_limit[1]) * 60) + int(time_limit[2]) print("info: {} seconds have passed on auction {}".format(seconds, auction.serial)) if seconds > time_limit: print("> auction {} has ended".format(auction.serial)) self.closed_auctions.append(auction) self.active_auctions.remove(auction) file = "auction{}.txt".format(auction.serial) current_path = os.getcwd() path = "{}/auctions/{}".format(current_path, file) msg = {'payload': {'end': path}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), self.manager_address) data, addr = self.sock.recvfrom(MAX_BUFFER_SIZE) data = json.loads(data) signature = base64.b64decode(data['signature']) if self.valid_signature(self.man_pubkey, json.dumps(data['payload']), signature): if data['payload']['ack'] == 'ok': with open(path) as f: lines = f.readlines() lines = [x.strip("\n") for x in lines] blockchain = None for i in range(len(lines)): lines_dict = literal_eval(lines[i]) if i == 0: current_serial = lines_dict['serial'] blockchain = Blockchain(lines_dict['key'], lines_dict['cert'], lines_dict['serial'], lines_dict['id'], lines_dict['timestamp'], lines_dict['name'], lines_dict['time-limit'], lines_dict['description'], lines_dict['type'], lines_dict['state'], lines_dict['winner'], lines_dict['winner_amount']) else: block = Block(lines_dict['key'], lines_dict['cert'], lines_dict['serial'], lines_dict['hash'], lines_dict['hash_prev'], lines_dict['amount'], lines_dict['name'], lines_dict['id'], lines_dict['timestamp']) blockchain.add_block(block) for a in range(len(self.closed_auctions)): if auction.serial == self.closed_auctions[a].serial: self.closed_auctions[a] = blockchain for a in range(len(self.all_auctions)): if auction.serial == self.all_auctions[a].serial: self.all_auctions[a] = blockchain if self.client_waiting: msg = {'payload': {'ack': 'nok', 'info': 'busy: bid no created'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), self.current_client) else: print("> no bids on ended auction {} -> no possible winner".format(auction.serial)) else: print("> couldn't find the winner") data, addr = self.sock.recvfrom(MAX_BUFFER_SIZE) data = json.loads(data) if (addr not in self.address_client) and (addr != self.manager_address): print("> client pubkey received") msg = json.dumps({'repo_pubk': self.repo_pubkey.decode()}) bytes = self.sock.sendto(msg.encode(), addr) self.client_login(data, addr) else: self.client_waiting = False if 'auction' in data['payload']: signature = base64.b64decode(data['signature']) if data['payload']['valid']: if self.valid_signature(self.man_pubkey, json.dumps(data['payload']), signature): data2 = data['payload'] self.create_auction(addr, data2['auction']['key'], data2['auction']['cert'], self.serial + 1, data2['auction']['id'], data2['auction']['timestamp'], data2['auction']['name'], data2['auction']['time-limit'], data2['auction']['description'], data2['auction']['type']) elif 'bid' in data['payload']: data2 = copy.deepcopy(data) signature = base64.b64decode(data2['payload'].pop('sig_c')) if self.crypto.verifySignatureCC(self.pubkey_dict[data['payload']['bid']['id']], json.dumps(data2['payload']), signature): self.place_bid(addr, data['payload']) elif 'command' in data['payload']: signature = base64.b64decode(data['signature']) data2 = data['payload'] payload = json.dumps(data2) if 'bid_request' in data2['command']: if self.crypto.verifySignatureCC(self.pubkey_dict[data2['id']], payload, signature): self.send_pow(addr, data2) elif 'list_open' in data2['command']: if self.crypto.verifySignatureCC(self.pubkey_dict[data2['id']], payload, signature): self.list_open(addr) elif 'list_closed' in data2['command']: if self.crypto.verifySignatureCC(self.pubkey_dict[data2['id']], payload, signature): self.list_closed(addr) elif 'bid_auction' in data2['command']: if self.crypto.verifySignatureCC(self.pubkey_dict[data2['id']], payload, signature): self.bids_auction(addr, data2['serial']) elif 'bid_client' in data2['command']: if self.crypto.verifySignatureCC(self.pubkey_dict[data2['id']], payload, signature): self.bids_client(addr, data2['c_id']) elif 'check_receipt' in data2['command']: if self.crypto.verifySignatureCC(self.pubkey_dict[data2['id']], payload, signature): self.check_receipt(addr, data2['serial'], data2['hash']) elif 'list_ids' in data2['command']: if self.crypto.verifySignatureCC(self.pubkey_dict[data2['id']], payload, signature): self.list_ids(addr) if 'exit' in data['payload']: msg = json.dumps({'payload': {'exit': 'client exit'}}) signature = base64.b64decode(data['signature']) if self.crypto.verifySignatureCC(self.pubkey_dict[data['payload']['id']], json.dumps(data['payload']), signature): self.loggedInClient -= 1 if self.loggedInClient <= 0: self.mylogger.log(INFO, "Exiting Repository") self.exit(0) for auction in self.active_auctions: file = "auction{}.txt".format(auction.serial) auction.save_to_file(file) except: self.mylogger.log(INFO, "Exception on repository server's loop ") raise def create_auction(self, addr, key, cert, serial, id, timestamp, name, timelimit, description, type): """ Create an auction (new blockchain) and store it in a file after receiving its parameters from the manager server """ try: self.mylogger.log(INFO, "Create auction ") blockchain = Blockchain(key, cert, serial, id, timestamp, name, timelimit, description, type, state='active') self.serial = self.serial + 1 print("> auction creation: OK") self.active_auctions.append(blockchain) self.all_auctions.append(blockchain) self.hash_prev[str(serial)] = '0' msg = {'payload': {'ack': 'ok', 'info': 'auction', 'id': id, 'serial': str(serial)}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), addr) except: self.mylogger.log(INFO, "Auction cannot be created ") print("> auction creation: NOT OK\n") msg = {'payload': {'ack': 'nok', 'info': 'auction', 'id': id}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), addr) # send the proof-of-work to client. The cryptopuzzle is a hash-cash def send_pow(self, address_client, data): """ Send proof-of-work to the client (random string and number of zeros required). A response with a string and a digest is received and the function calculates the SHA256 digest of the string and compares it with the digest, also sent by the client. If equal, the client may send the bid parameters. """ try: self.mylogger.log(INFO, "Sending proof-of-work to client ") type = "" auction_exists = False for auction in self.active_auctions: if str(auction.serial) == data['serial']: type = auction.type auction_exists = True if auction_exists is False: msg = {'payload': {'ack': 'nok', 'info': 'auction does not exist'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) else: r_string = ''.join( random.choice(string.digits + string.ascii_lowercase + string.ascii_uppercase) for c in range(6)) msg = {'payload': {'ack': 'ok', 'r_string': r_string, 'numZeros': '5', 'type': type, 'hash_prev': self.hash_prev[data['serial']]}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) data2, addr = self.sock.recvfrom(MAX_BUFFER_SIZE) data2 = json.loads(data2) signature = base64.b64decode(data2['signature']) if self.crypto.verifySignatureCC(self.pubkey_dict[data2['payload']['id']], json.dumps(data2['payload']), signature): if 'digest' in data2['payload']: print("> proof-of-work result of client: " + json.dumps(data2['payload']['digest'])) hash_object = hashlib.sha256(data2['payload']['string'].encode('utf-8')) digest = hash_object.hexdigest() if data2['payload']['digest'] == digest: msg2 = {'payload': {'ack': 'ok', 'type': type, 'hash_prev': self.hash_prev[data['serial']]}} self.current_client = addr self.client_waiting = True else: msg2 = {'payload': {'ack': 'nok'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg2['payload']))).decode() msg2['signature'] = signature bytes = self.sock.sendto(json.dumps(msg2).encode(), address_client) else: msg2 = {'payload': {'ack': 'nok', 'info': 'busy: could not send proof-of-work'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg2['payload']))).decode() msg2['signature'] = signature bytes = self.sock.sendto(json.dumps(msg2).encode(), address_client) except: print("Cannot send proof-of-work to client") self.mylogger.log(INFO, "Cannot send proof-of-work to client ") raise def place_bid(self, addr, data): """ Receives the new bid parameters, creates a new block and inserts it in the blockchain of the respective auction """ try: self.mylogger.log(INFO, "Place a bid ") client_address = addr for auction in self.active_auctions: if data['bid']['serial'] == str(auction.serial): block = Block(data['bid']['key'], data['bid']['cert'], data['bid']['serial'], data['bid']['hash'], data['bid']['hash_prev'], data['bid']['amount'], data['bid']['name'], data['bid']['id'], data['bid']['timestamp']) self.hash_prev[data['bid']['serial']] = data['bid']['hash'] msg = {'payload': {'bid_valid': data}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), self.manager_address) data2, addr = self.sock.recvfrom(MAX_BUFFER_SIZE) data2 = json.loads(data2) signature = base64.b64decode(data2['signature']) payload = json.dumps(data2['payload']) if self.valid_signature(self.man_pubkey, payload, signature): if data2['payload']['valid'] is True: auction.add_block(block) print("> bid creation in auction {}: OK".format(auction.serial)) signature = base64.b64encode(self.certgen.signData(json.dumps(data2['payload']['receipt']))).decode() data2['payload']['receipt']['sig_r'] = signature msg = {'payload': {'ack': 'ok', 'receipt': data2['payload']['receipt']}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), client_address) break else: print("> bid creation in auction {}: NOK".format(auction.serial)) if 'info' in data2['payload']: msg = {'payload': {'ack': 'nok', 'info': data2['payload']['info']}} else: msg = {'payload': {'ack': 'nok', 'valid': data2['payload']['valid']}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), client_address) break else: print("> bid creation in auction {}: NOK".format(auction.serial)) msg = {'payload': {'ack': 'nok', 'info': 'non active'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), client_address) except: print("Cannot create bid") self.mylogger.log(INFO, "Cannot create bid ") raise def list_ids(self, address_client): """ Send list of the IDs of the clients of the system """ try: self.mylogger.log(INFO, "Listing active auctions") if self.pubkey_dict: msg = {'payload': {'ack': 'ok', 'ids': list(self.pubkey_dict.keys())}} else: msg = msg = {'payload': {'ack': 'nok'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) except: self.mylogger.log(INFO, "Cannot list ids of clients") raise def list_open(self, address_client): """ Send list of the currently active auctions """ try: self.mylogger.log(INFO, "Listing active auctions") auctions = "" for auction in self.active_auctions: auctions = auctions + str(auction.info_user()) + "\n" if auctions != "": msg = {'payload': auctions} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) print("> sending list of active auctions") else: msg = {'payload': {'ack': 'nok'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) except: print("Cannot send active auctions") self.mylogger.log(INFO, "Cannot send active auctions ") raise def list_closed(self, address_client): """ Send list of the closed auctions """ try: self.mylogger.log(INFO, "Listing closed auctions ") auctions = "" for auction in self.closed_auctions: auctions = auctions + str(auction.info_user()) + "\n" if auctions != "": msg = {'payload': auctions} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) print("> sending list of closed auctions") else: msg = {'payload': {'ack': 'nok'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) except: print("Can't send active auctions") self.mylogger.log(INFO, "Cannot send active auctions ") raise def bids_auction(self, address_client, serial): """ Send list of all the bids of an auction """ try: self.mylogger.log(INFO, "Listing bids of auction {} ".format(serial)) msg = {} i = 0 result = None auctions_exists = False for auction in self.all_auctions: if auction.serial == int(serial): auctions_exists = True result = auction.bids_auction(serial) if auctions_exists: for bid in result: bid_number = "bid_{}".format(i) msg[bid_number] = bid i = i + 1 msg = {'payload': msg} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) print("\n> sent list of bids of auction {}".format(serial)) else: msg = {'payload': {'ack': 'nok'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) except: print("> cannot send list of bids of auction {}".format(serial)) self.mylogger.log(INFO, "Cannot list bids of auction {}".format(serial)) raise def bids_client(self, address_client, id): """ Send list of all the bids of a client """ try: self.mylogger.log(INFO, "Listing bids of client {} ".format(id)) msg = {} i = 0 result = None client_exists = False for auction in self.all_auctions: if str(auction.id) == id: client_exists = True result = auction.bids_client(id) if client_exists: for bid in result: bid_number = "bid_{}".format(i) msg[bid_number] = bid i = i + 1 msg = {'payload': msg} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) print("\n> sent list of bids of client {}".format(id)) else: msg = {'payload': {'ack': 'nok'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) except: print("> can't send list of bids of client {}".format(id)) self.mylogger.log(INFO, "Listing bids of client {} ".format(id)) raise def check_receipt(self, address_client, serial, hash): """ Send bid information to a client requesting it, for validation against a receipt. """ try: self.mylogger.log(INFO, "Sending bid information for receipt validation ") print("> sending bid information for receipt validation") closed_auctions = False for auction in self.closed_auctions: if str(auction.serial) == serial: closed_auctions = True info = auction.bid_info(hash) if info != "": msg = {'payload': {'bid': info}} else: msg = {'payload': {'ack': 'nok', 'info': 'no info about bid'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) else: msg = {'payload': {'ack': 'nok', 'info': 'the auction is not closed'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) if not closed_auctions: msg = {'payload': {'ack': 'nok', 'info': 'no closed auctions'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) except: print("> cannot send bid information for receipt validation") self.mylogger.log(INFO, "Cannot send bid information for receipt validation ") def client_login(self, message, client_addr): """ Storing information on a new client of the system """ try: self.mylogger.log(INFO, "Adding new client ") cert = None if 'c_pubk' in message: self.mylogger.log(INFO, "Client Pubkey : \n{}".format(message['c_pubk'])) self.loggedInClient += 1 self.pubkey_dict[message['id']] = message['c_pubk'] self.address_client.append(client_addr) except: print("Cannot sign up new client") self.mylogger.log(INFO, "Cannot signup new client ") raise def valid_signature(self, pubk, message, signature): """ Validate an entity's signature on a message """ try: pubk = self.crypto.loadPubk(pubk) if not self.crypto.verifySignatureServers(pubk, message, signature): return False return True except: print("Cannot validate signature") self.mylogger.log(INFO, "Cannot validate signature ") raise def exit(self, type): """ Shutdown the repository """ try: self.mylogger.log(INFO, "Exiting repository ") print("Exiting...") self.sock.close() sys.exit(type) except: self.mylogger.log(INFO, "Cannot exit repository ") raise if __name__ == "__main__": r = Repository(HOST, PORT_REPO) try: r.start() except KeyboardInterrupt: print("Exiting...")
import hashlib import os, datetime, sys, json, base64, re, copy import random import string from os import listdir from ast import literal_eval from socket import * from blockchain import * from logging import DEBUG, ERROR, INFO from log import LoggyLogglyMcface from security import * from cc_interface import PortugueseCitizenCard HOST = "127.0.0.1" PORT_MAN = 8080 PORT_REPO = 8081 MAX_BUFFER_SIZE = 10000 class Repository(): def __init__(self, host, port): LOG = "./log.txt" for filename in listdir("./"): if filename == "log.txt": os.remove(LOG) self.mylogger = LoggyLogglyMcface(name=Repository.__name__) self.mylogger.log(INFO, "Entering Repository interface") # repository information self.name = Repository.__name__ self.privKname = "privK" + self.name self.password = "<PASSWORD>" self.repo_pubkey = None self.man_pubkey = None self.host = host self.port = port self.loggedInClient = 0 # client public keys self.clients_pubkey = set() # Addresses of clients and manager self.address_client = [] self.manager_address = None # list of active and closed auctions self.active_auctions = [] self.closed_auctions = [] self.all_auctions = [] self.sock = socket(AF_INET, SOCK_DGRAM) self.sock.bind((self.host, self.port)) # incremental serial number of the auctions self.serial = 0 # hash of the previous block (auction serial, previous hash) self.hash_prev = {} # generate public and private key self.certgen = GenerateCertificates() self.certops = CertificateOperations() self.crypto = CryptoUtils() # dictionary of id of the client and public key self.pubkey_dict = {} # client is waiting for message (after sending proof-of-work result) self.current_client = None self.client_waiting = False def start(self): """ Servers and Client exchange public keys """ try: # verify if repository private key already exists. load if true if self.certgen.checkExistence(self.name): self.certgen.loadPrivateKeyFromFile(self.privKname, password=self.password) else: self.certgen.writePrivateKeyToFile(self.privKname, password=self.password) self.repo_pubkey = self.certgen.publicKeyToBytes() print("Listening...") self.mylogger.log(INFO, "Exchanging public key with the manager") data1, self.manager_address = self.sock.recvfrom(MAX_BUFFER_SIZE) print("> manager pubkey received") msg = json.dumps({'repo_pubk': self.repo_pubkey.decode()}) bytes = self.sock.sendto(msg.encode(), self.manager_address) self.mylogger.log(INFO, "Manager public key received") data1 = json.loads(data1) if 'man_pubk' in data1: self.man_pubkey = data1['man_pubk'] self.mylogger.log(INFO, "Man Pubkey : \n{}".format(self.man_pubkey)) self.mylogger.log(INFO, "Exchanging public key with the client") data2, client_addr = self.sock.recvfrom(MAX_BUFFER_SIZE) print("> client pubkey received") bytes = self.sock.sendto(msg.encode(), client_addr) self.mylogger.log(INFO, "Client public key received") data2 = json.loads(data2) self.client_login(data2, client_addr) self.loop() except: self.mylogger.log(INFO, "Cannot start repository") raise def loop(self): """ The main loop of the repository. It waits for messages of clients (both system clients or servers) and calls functions according to the received messages """ try: while (True): date_time = datetime.datetime.now() for auction in self.active_auctions: timestamp_auction = datetime.datetime.strptime(auction.timestamp, '%m/%d/%Y, %H:%M:%S') delta = date_time - timestamp_auction seconds = delta.days * 24 * 3600 + delta.seconds time_limit = re.findall('\d+', auction.time_limit) time_limit = (int(time_limit[0]) * 3600) + (int(time_limit[1]) * 60) + int(time_limit[2]) print("info: {} seconds have passed on auction {}".format(seconds, auction.serial)) if seconds > time_limit: print("> auction {} has ended".format(auction.serial)) self.closed_auctions.append(auction) self.active_auctions.remove(auction) file = "auction{}.txt".format(auction.serial) current_path = os.getcwd() path = "{}/auctions/{}".format(current_path, file) msg = {'payload': {'end': path}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), self.manager_address) data, addr = self.sock.recvfrom(MAX_BUFFER_SIZE) data = json.loads(data) signature = base64.b64decode(data['signature']) if self.valid_signature(self.man_pubkey, json.dumps(data['payload']), signature): if data['payload']['ack'] == 'ok': with open(path) as f: lines = f.readlines() lines = [x.strip("\n") for x in lines] blockchain = None for i in range(len(lines)): lines_dict = literal_eval(lines[i]) if i == 0: current_serial = lines_dict['serial'] blockchain = Blockchain(lines_dict['key'], lines_dict['cert'], lines_dict['serial'], lines_dict['id'], lines_dict['timestamp'], lines_dict['name'], lines_dict['time-limit'], lines_dict['description'], lines_dict['type'], lines_dict['state'], lines_dict['winner'], lines_dict['winner_amount']) else: block = Block(lines_dict['key'], lines_dict['cert'], lines_dict['serial'], lines_dict['hash'], lines_dict['hash_prev'], lines_dict['amount'], lines_dict['name'], lines_dict['id'], lines_dict['timestamp']) blockchain.add_block(block) for a in range(len(self.closed_auctions)): if auction.serial == self.closed_auctions[a].serial: self.closed_auctions[a] = blockchain for a in range(len(self.all_auctions)): if auction.serial == self.all_auctions[a].serial: self.all_auctions[a] = blockchain if self.client_waiting: msg = {'payload': {'ack': 'nok', 'info': 'busy: bid no created'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), self.current_client) else: print("> no bids on ended auction {} -> no possible winner".format(auction.serial)) else: print("> couldn't find the winner") data, addr = self.sock.recvfrom(MAX_BUFFER_SIZE) data = json.loads(data) if (addr not in self.address_client) and (addr != self.manager_address): print("> client pubkey received") msg = json.dumps({'repo_pubk': self.repo_pubkey.decode()}) bytes = self.sock.sendto(msg.encode(), addr) self.client_login(data, addr) else: self.client_waiting = False if 'auction' in data['payload']: signature = base64.b64decode(data['signature']) if data['payload']['valid']: if self.valid_signature(self.man_pubkey, json.dumps(data['payload']), signature): data2 = data['payload'] self.create_auction(addr, data2['auction']['key'], data2['auction']['cert'], self.serial + 1, data2['auction']['id'], data2['auction']['timestamp'], data2['auction']['name'], data2['auction']['time-limit'], data2['auction']['description'], data2['auction']['type']) elif 'bid' in data['payload']: data2 = copy.deepcopy(data) signature = base64.b64decode(data2['payload'].pop('sig_c')) if self.crypto.verifySignatureCC(self.pubkey_dict[data['payload']['bid']['id']], json.dumps(data2['payload']), signature): self.place_bid(addr, data['payload']) elif 'command' in data['payload']: signature = base64.b64decode(data['signature']) data2 = data['payload'] payload = json.dumps(data2) if 'bid_request' in data2['command']: if self.crypto.verifySignatureCC(self.pubkey_dict[data2['id']], payload, signature): self.send_pow(addr, data2) elif 'list_open' in data2['command']: if self.crypto.verifySignatureCC(self.pubkey_dict[data2['id']], payload, signature): self.list_open(addr) elif 'list_closed' in data2['command']: if self.crypto.verifySignatureCC(self.pubkey_dict[data2['id']], payload, signature): self.list_closed(addr) elif 'bid_auction' in data2['command']: if self.crypto.verifySignatureCC(self.pubkey_dict[data2['id']], payload, signature): self.bids_auction(addr, data2['serial']) elif 'bid_client' in data2['command']: if self.crypto.verifySignatureCC(self.pubkey_dict[data2['id']], payload, signature): self.bids_client(addr, data2['c_id']) elif 'check_receipt' in data2['command']: if self.crypto.verifySignatureCC(self.pubkey_dict[data2['id']], payload, signature): self.check_receipt(addr, data2['serial'], data2['hash']) elif 'list_ids' in data2['command']: if self.crypto.verifySignatureCC(self.pubkey_dict[data2['id']], payload, signature): self.list_ids(addr) if 'exit' in data['payload']: msg = json.dumps({'payload': {'exit': 'client exit'}}) signature = base64.b64decode(data['signature']) if self.crypto.verifySignatureCC(self.pubkey_dict[data['payload']['id']], json.dumps(data['payload']), signature): self.loggedInClient -= 1 if self.loggedInClient <= 0: self.mylogger.log(INFO, "Exiting Repository") self.exit(0) for auction in self.active_auctions: file = "auction{}.txt".format(auction.serial) auction.save_to_file(file) except: self.mylogger.log(INFO, "Exception on repository server's loop ") raise def create_auction(self, addr, key, cert, serial, id, timestamp, name, timelimit, description, type): """ Create an auction (new blockchain) and store it in a file after receiving its parameters from the manager server """ try: self.mylogger.log(INFO, "Create auction ") blockchain = Blockchain(key, cert, serial, id, timestamp, name, timelimit, description, type, state='active') self.serial = self.serial + 1 print("> auction creation: OK") self.active_auctions.append(blockchain) self.all_auctions.append(blockchain) self.hash_prev[str(serial)] = '0' msg = {'payload': {'ack': 'ok', 'info': 'auction', 'id': id, 'serial': str(serial)}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), addr) except: self.mylogger.log(INFO, "Auction cannot be created ") print("> auction creation: NOT OK\n") msg = {'payload': {'ack': 'nok', 'info': 'auction', 'id': id}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), addr) # send the proof-of-work to client. The cryptopuzzle is a hash-cash def send_pow(self, address_client, data): """ Send proof-of-work to the client (random string and number of zeros required). A response with a string and a digest is received and the function calculates the SHA256 digest of the string and compares it with the digest, also sent by the client. If equal, the client may send the bid parameters. """ try: self.mylogger.log(INFO, "Sending proof-of-work to client ") type = "" auction_exists = False for auction in self.active_auctions: if str(auction.serial) == data['serial']: type = auction.type auction_exists = True if auction_exists is False: msg = {'payload': {'ack': 'nok', 'info': 'auction does not exist'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) else: r_string = ''.join( random.choice(string.digits + string.ascii_lowercase + string.ascii_uppercase) for c in range(6)) msg = {'payload': {'ack': 'ok', 'r_string': r_string, 'numZeros': '5', 'type': type, 'hash_prev': self.hash_prev[data['serial']]}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) data2, addr = self.sock.recvfrom(MAX_BUFFER_SIZE) data2 = json.loads(data2) signature = base64.b64decode(data2['signature']) if self.crypto.verifySignatureCC(self.pubkey_dict[data2['payload']['id']], json.dumps(data2['payload']), signature): if 'digest' in data2['payload']: print("> proof-of-work result of client: " + json.dumps(data2['payload']['digest'])) hash_object = hashlib.sha256(data2['payload']['string'].encode('utf-8')) digest = hash_object.hexdigest() if data2['payload']['digest'] == digest: msg2 = {'payload': {'ack': 'ok', 'type': type, 'hash_prev': self.hash_prev[data['serial']]}} self.current_client = addr self.client_waiting = True else: msg2 = {'payload': {'ack': 'nok'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg2['payload']))).decode() msg2['signature'] = signature bytes = self.sock.sendto(json.dumps(msg2).encode(), address_client) else: msg2 = {'payload': {'ack': 'nok', 'info': 'busy: could not send proof-of-work'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg2['payload']))).decode() msg2['signature'] = signature bytes = self.sock.sendto(json.dumps(msg2).encode(), address_client) except: print("Cannot send proof-of-work to client") self.mylogger.log(INFO, "Cannot send proof-of-work to client ") raise def place_bid(self, addr, data): """ Receives the new bid parameters, creates a new block and inserts it in the blockchain of the respective auction """ try: self.mylogger.log(INFO, "Place a bid ") client_address = addr for auction in self.active_auctions: if data['bid']['serial'] == str(auction.serial): block = Block(data['bid']['key'], data['bid']['cert'], data['bid']['serial'], data['bid']['hash'], data['bid']['hash_prev'], data['bid']['amount'], data['bid']['name'], data['bid']['id'], data['bid']['timestamp']) self.hash_prev[data['bid']['serial']] = data['bid']['hash'] msg = {'payload': {'bid_valid': data}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), self.manager_address) data2, addr = self.sock.recvfrom(MAX_BUFFER_SIZE) data2 = json.loads(data2) signature = base64.b64decode(data2['signature']) payload = json.dumps(data2['payload']) if self.valid_signature(self.man_pubkey, payload, signature): if data2['payload']['valid'] is True: auction.add_block(block) print("> bid creation in auction {}: OK".format(auction.serial)) signature = base64.b64encode(self.certgen.signData(json.dumps(data2['payload']['receipt']))).decode() data2['payload']['receipt']['sig_r'] = signature msg = {'payload': {'ack': 'ok', 'receipt': data2['payload']['receipt']}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), client_address) break else: print("> bid creation in auction {}: NOK".format(auction.serial)) if 'info' in data2['payload']: msg = {'payload': {'ack': 'nok', 'info': data2['payload']['info']}} else: msg = {'payload': {'ack': 'nok', 'valid': data2['payload']['valid']}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), client_address) break else: print("> bid creation in auction {}: NOK".format(auction.serial)) msg = {'payload': {'ack': 'nok', 'info': 'non active'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), client_address) except: print("Cannot create bid") self.mylogger.log(INFO, "Cannot create bid ") raise def list_ids(self, address_client): """ Send list of the IDs of the clients of the system """ try: self.mylogger.log(INFO, "Listing active auctions") if self.pubkey_dict: msg = {'payload': {'ack': 'ok', 'ids': list(self.pubkey_dict.keys())}} else: msg = msg = {'payload': {'ack': 'nok'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) except: self.mylogger.log(INFO, "Cannot list ids of clients") raise def list_open(self, address_client): """ Send list of the currently active auctions """ try: self.mylogger.log(INFO, "Listing active auctions") auctions = "" for auction in self.active_auctions: auctions = auctions + str(auction.info_user()) + "\n" if auctions != "": msg = {'payload': auctions} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) print("> sending list of active auctions") else: msg = {'payload': {'ack': 'nok'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) except: print("Cannot send active auctions") self.mylogger.log(INFO, "Cannot send active auctions ") raise def list_closed(self, address_client): """ Send list of the closed auctions """ try: self.mylogger.log(INFO, "Listing closed auctions ") auctions = "" for auction in self.closed_auctions: auctions = auctions + str(auction.info_user()) + "\n" if auctions != "": msg = {'payload': auctions} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) print("> sending list of closed auctions") else: msg = {'payload': {'ack': 'nok'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) except: print("Can't send active auctions") self.mylogger.log(INFO, "Cannot send active auctions ") raise def bids_auction(self, address_client, serial): """ Send list of all the bids of an auction """ try: self.mylogger.log(INFO, "Listing bids of auction {} ".format(serial)) msg = {} i = 0 result = None auctions_exists = False for auction in self.all_auctions: if auction.serial == int(serial): auctions_exists = True result = auction.bids_auction(serial) if auctions_exists: for bid in result: bid_number = "bid_{}".format(i) msg[bid_number] = bid i = i + 1 msg = {'payload': msg} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) print("\n> sent list of bids of auction {}".format(serial)) else: msg = {'payload': {'ack': 'nok'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) except: print("> cannot send list of bids of auction {}".format(serial)) self.mylogger.log(INFO, "Cannot list bids of auction {}".format(serial)) raise def bids_client(self, address_client, id): """ Send list of all the bids of a client """ try: self.mylogger.log(INFO, "Listing bids of client {} ".format(id)) msg = {} i = 0 result = None client_exists = False for auction in self.all_auctions: if str(auction.id) == id: client_exists = True result = auction.bids_client(id) if client_exists: for bid in result: bid_number = "bid_{}".format(i) msg[bid_number] = bid i = i + 1 msg = {'payload': msg} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) print("\n> sent list of bids of client {}".format(id)) else: msg = {'payload': {'ack': 'nok'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) except: print("> can't send list of bids of client {}".format(id)) self.mylogger.log(INFO, "Listing bids of client {} ".format(id)) raise def check_receipt(self, address_client, serial, hash): """ Send bid information to a client requesting it, for validation against a receipt. """ try: self.mylogger.log(INFO, "Sending bid information for receipt validation ") print("> sending bid information for receipt validation") closed_auctions = False for auction in self.closed_auctions: if str(auction.serial) == serial: closed_auctions = True info = auction.bid_info(hash) if info != "": msg = {'payload': {'bid': info}} else: msg = {'payload': {'ack': 'nok', 'info': 'no info about bid'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) else: msg = {'payload': {'ack': 'nok', 'info': 'the auction is not closed'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) if not closed_auctions: msg = {'payload': {'ack': 'nok', 'info': 'no closed auctions'}} signature = base64.b64encode(self.certgen.signData(json.dumps(msg['payload']))).decode() msg['signature'] = signature bytes = self.sock.sendto(json.dumps(msg).encode(), address_client) except: print("> cannot send bid information for receipt validation") self.mylogger.log(INFO, "Cannot send bid information for receipt validation ") def client_login(self, message, client_addr): """ Storing information on a new client of the system """ try: self.mylogger.log(INFO, "Adding new client ") cert = None if 'c_pubk' in message: self.mylogger.log(INFO, "Client Pubkey : \n{}".format(message['c_pubk'])) self.loggedInClient += 1 self.pubkey_dict[message['id']] = message['c_pubk'] self.address_client.append(client_addr) except: print("Cannot sign up new client") self.mylogger.log(INFO, "Cannot signup new client ") raise def valid_signature(self, pubk, message, signature): """ Validate an entity's signature on a message """ try: pubk = self.crypto.loadPubk(pubk) if not self.crypto.verifySignatureServers(pubk, message, signature): return False return True except: print("Cannot validate signature") self.mylogger.log(INFO, "Cannot validate signature ") raise def exit(self, type): """ Shutdown the repository """ try: self.mylogger.log(INFO, "Exiting repository ") print("Exiting...") self.sock.close() sys.exit(type) except: self.mylogger.log(INFO, "Cannot exit repository ") raise if __name__ == "__main__": r = Repository(HOST, PORT_REPO) try: r.start() except KeyboardInterrupt: print("Exiting...")
en
0.883986
# repository information # client public keys # Addresses of clients and manager # list of active and closed auctions # incremental serial number of the auctions # hash of the previous block (auction serial, previous hash) # generate public and private key # dictionary of id of the client and public key # client is waiting for message (after sending proof-of-work result) Servers and Client exchange public keys # verify if repository private key already exists. load if true The main loop of the repository. It waits for messages of clients (both system clients or servers) and calls functions according to the received messages Create an auction (new blockchain) and store it in a file after receiving its parameters from the manager server # send the proof-of-work to client. The cryptopuzzle is a hash-cash Send proof-of-work to the client (random string and number of zeros required). A response with a string and a digest is received and the function calculates the SHA256 digest of the string and compares it with the digest, also sent by the client. If equal, the client may send the bid parameters. Receives the new bid parameters, creates a new block and inserts it in the blockchain of the respective auction Send list of the IDs of the clients of the system Send list of the currently active auctions Send list of the closed auctions Send list of all the bids of an auction Send list of all the bids of a client Send bid information to a client requesting it, for validation against a receipt. Storing information on a new client of the system Validate an entity's signature on a message Shutdown the repository
2.364812
2
python/packages/nisar/workflows/split_spectrum.py
isce3-testing/isce3-circleci-poc
0
6620597
#!/usr/bin/env python3 import os import pathlib import time import h5py import isce3 import journal import numpy as np from isce3.splitspectrum import splitspectrum from nisar.h5 import cp_h5_meta_data from nisar.products.readers import SLC from nisar.workflows.split_spectrum_runconfig import SplitSpectrumRunConfig from nisar.workflows.yaml_argparse import YamlArgparse def prep_subband_h5(full_hdf5: str, sub_band_hdf5: str, freq_pols): common_parent_path = 'science/LSAR' swath_path = f'{common_parent_path}/SLC/swaths/' freq_a_path = f'{swath_path}/frequencyA/' freq_b_path = f'{swath_path}/frequencyB/' metadata_path = f'{common_parent_path}/SLC/metadata/' ident_path = f'{common_parent_path}/identification/' pol_a_path = f'{freq_a_path}/listOfPolarizations' pol_b_path = f'{freq_b_path}/listOfPolarizations' with h5py.File(full_hdf5, 'r', libver='latest', swmr=True) as src_h5, \ h5py.File(sub_band_hdf5, 'w') as dst_h5: pols_freqA = list( np.array(src_h5[pol_a_path][()], dtype=str)) pols_freqB = list( np.array(src_h5[pol_b_path][()], dtype=str)) if freq_pols['A']: pols_a_excludes = [pol for pol in pols_freqA if pol not in freq_pols['A']] else: pols_a_excludes = pols_freqA if freq_pols['B']: pols_b_excludes = [pol for pol in pols_freqB if pol not in freq_pols['B']] else: pols_b_excludes = pols_freqB if pols_a_excludes: cp_h5_meta_data(src_h5, dst_h5, freq_a_path, excludes=pols_a_excludes) else: cp_h5_meta_data(src_h5, dst_h5, freq_a_path, excludes=['']) if pols_b_excludes: cp_h5_meta_data(src_h5, dst_h5, freq_b_path, excludes=pols_b_excludes) else: cp_h5_meta_data(src_h5, dst_h5, freq_b_path, excludes=['']) cp_h5_meta_data(src_h5, dst_h5, metadata_path, excludes=['']) cp_h5_meta_data(src_h5, dst_h5, ident_path, excludes=['']) cp_h5_meta_data(src_h5, dst_h5, swath_path, excludes=['frequencyA', 'frequencyB']) def run(cfg: dict): ''' run bandpass ''' # pull parameters from cfg ref_hdf5 = cfg['input_file_group']['reference_rslc_file_path'] sec_hdf5 = cfg['input_file_group']['secondary_rslc_file_path'] # Extract range split spectrum dictionary and corresponding parameters ionosphere_option = cfg['processing']['ionosphere_phase_correction'] method = ionosphere_option['spectral_diversity'] split_cfg = ionosphere_option['split_range_spectrum'] iono_freq_pol = ionosphere_option['list_of_frequencies'] blocksize = split_cfg['lines_per_block'] window_function = split_cfg['window_function'] window_shape = split_cfg['window_shape'] low_band_bandwidth = split_cfg['low_band_bandwidth'] high_band_bandwidth = split_cfg['high_band_bandwidth'] scratch_path = pathlib.Path(cfg['product_path_group']['scratch_path']) info_channel = journal.info("split_spectrum.run") info_channel.log("starting split_spectrum") t_all = time.time() # Check split spectrum method if method == 'split_main_band': split_band_path = pathlib.Path( f"{scratch_path}/ionosphere/split_spectrum/") split_band_path.mkdir(parents=True, exist_ok=True) common_parent_path = 'science/LSAR' freq = 'A' pol_list = iono_freq_pol[freq] info_channel.log(f'Split the main band {pol_list} of the signal') for hdf5_ind, hdf5_str in enumerate([ref_hdf5, sec_hdf5]): # reference SLC if hdf5_ind == 0: low_band_output = f"{split_band_path}/ref_low_band_slc.h5" high_band_output = f"{split_band_path}/ref_high_band_slc.h5" # secondary SLC else: low_band_output = f"{split_band_path}/sec_low_band_slc.h5" high_band_output = f"{split_band_path}/sec_high_band_slc.h5" # Open RSLC product slc_product = SLC(hdf5file=hdf5_str) # Extract metadata # meta data extraction meta_data = splitspectrum.bandpass_meta_data.load_from_slc( slc_product=slc_product, freq=freq) bandwidth_half = 0.5 * meta_data.rg_bandwidth low_frequency_slc = meta_data.center_freq - bandwidth_half high_frequency_slc = meta_data.center_freq + bandwidth_half # first and second elements are the frequency ranges for low and high sub-bands, respectively. low_subband_frequencies = np.array( [low_frequency_slc, low_frequency_slc + low_band_bandwidth]) high_subband_frequencies = np.array( [high_frequency_slc - high_band_bandwidth, high_frequency_slc]) low_band_center_freq = low_frequency_slc + low_band_bandwidth/2 high_band_center_freq = high_frequency_slc - high_band_bandwidth/2 # Specify split-spectrum parameters split_spectrum_parameters = splitspectrum.SplitSpectrum( rg_sample_freq=meta_data.rg_sample_freq, rg_bandwidth=meta_data.rg_bandwidth, center_frequency=meta_data.center_freq, slant_range=meta_data.slant_range, freq=freq) dest_freq_path = os.path.join(slc_product.SwathPath, f'frequency{freq}') # prepare HDF5 for subband SLC HDF5 prep_subband_h5(hdf5_str, low_band_output, iono_freq_pol) prep_subband_h5(hdf5_str, high_band_output, iono_freq_pol) with h5py.File(hdf5_str, 'r', libver='latest', swmr=True) as src_h5, \ h5py.File(low_band_output, 'r+') as dst_h5_low, \ h5py.File(high_band_output, 'r+') as dst_h5_high: # Copy HDF5 metadata for low high band # cp_h5_meta_data(src_h5, dst_h5_low, f'{common_parent_path}') # cp_h5_meta_data(src_h5, dst_h5_high, f'{common_parent_path}') for pol in pol_list: raster_str = f'HDF5:{hdf5_str}:/{slc_product.slcPath(freq, pol)}' slc_raster = isce3.io.Raster(raster_str) rows = slc_raster.length cols = slc_raster.width nblocks = int(np.ceil(rows / blocksize)) fft_size = cols for block in range(0, nblocks): info_channel.log(f" split_spectrum block: {block}") row_start = block * blocksize if ((row_start + blocksize) > rows): block_rows_data = rows - row_start else: block_rows_data = blocksize dest_pol_path = f"{dest_freq_path}/{pol}" target_slc_image = np.empty([block_rows_data, cols], dtype=complex) src_h5[dest_pol_path].read_direct( target_slc_image, np.s_[row_start: row_start + block_rows_data, :]) subband_slc_low, subband_meta_low = \ split_spectrum_parameters.bandpass_shift_spectrum( slc_raster=target_slc_image, low_frequency=low_subband_frequencies[0], high_frequency=low_subband_frequencies[1], new_center_frequency=low_band_center_freq, fft_size=fft_size, window_shape=window_shape, window_function=window_function, resampling=False ) subband_slc_high, subband_meta_high = \ split_spectrum_parameters.bandpass_shift_spectrum( slc_raster=target_slc_image, low_frequency=high_subband_frequencies[0], high_frequency=high_subband_frequencies[1], new_center_frequency=high_band_center_freq, fft_size=fft_size, window_shape=window_shape, window_function=window_function, resampling=False ) if block == 0: del dst_h5_low[dest_pol_path] del dst_h5_high[dest_pol_path] # Initialize the raster with updated shape in HDF5 dst_h5_low.create_dataset(dest_pol_path, [rows, cols], np.complex64, chunks=(128, 128)) dst_h5_high.create_dataset(dest_pol_path, [rows, cols], np.complex64, chunks=(128, 128)) # Write bandpassed SLC to HDF5 dst_h5_low[dest_pol_path].write_direct( subband_slc_low, dest_sel=np.s_[ row_start: row_start + block_rows_data, :]) dst_h5_high[dest_pol_path].write_direct( subband_slc_high, dest_sel=np.s_[ row_start: row_start + block_rows_data, :]) dst_h5_low[dest_pol_path].attrs[ 'description'] = f"Split-spectrum SLC image ({pol})" dst_h5_low[dest_pol_path].attrs['units'] = f"" dst_h5_high[dest_pol_path].attrs[ 'description'] = f"Split-spectrum SLC image ({pol})" dst_h5_high[dest_pol_path].attrs['units'] = f"" # update meta information for bandpass SLC data = dst_h5_low[f"{dest_freq_path}/processedCenterFrequency"] data[...] = subband_meta_low['center_frequency'] data = dst_h5_low[f"{dest_freq_path}/processedRangeBandwidth"] data[...] = subband_meta_low['rg_bandwidth'] data = dst_h5_high[f"{dest_freq_path}/processedCenterFrequency"] data[...] = subband_meta_high['center_frequency'] data = dst_h5_high[f"{dest_freq_path}/processedRangeBandwidth"] data[...] = subband_meta_high['rg_bandwidth'] else: info_channel.log('Split spectrum is not needed') t_all_elapsed = time.time() - t_all info_channel.log( f"successfully ran split_spectrum in {t_all_elapsed:.3f} seconds") if __name__ == "__main__": ''' Run split-spectrum from command line ''' # load command line args split_spectrum_parser = YamlArgparse() args = split_spectrum_parser.parse() # get a runconfig dict from command line args split_spectrum_runconfig = SplitSpectrumRunConfig(args) # run bandpass run(split_spectrum_runconfig.cfg)
#!/usr/bin/env python3 import os import pathlib import time import h5py import isce3 import journal import numpy as np from isce3.splitspectrum import splitspectrum from nisar.h5 import cp_h5_meta_data from nisar.products.readers import SLC from nisar.workflows.split_spectrum_runconfig import SplitSpectrumRunConfig from nisar.workflows.yaml_argparse import YamlArgparse def prep_subband_h5(full_hdf5: str, sub_band_hdf5: str, freq_pols): common_parent_path = 'science/LSAR' swath_path = f'{common_parent_path}/SLC/swaths/' freq_a_path = f'{swath_path}/frequencyA/' freq_b_path = f'{swath_path}/frequencyB/' metadata_path = f'{common_parent_path}/SLC/metadata/' ident_path = f'{common_parent_path}/identification/' pol_a_path = f'{freq_a_path}/listOfPolarizations' pol_b_path = f'{freq_b_path}/listOfPolarizations' with h5py.File(full_hdf5, 'r', libver='latest', swmr=True) as src_h5, \ h5py.File(sub_band_hdf5, 'w') as dst_h5: pols_freqA = list( np.array(src_h5[pol_a_path][()], dtype=str)) pols_freqB = list( np.array(src_h5[pol_b_path][()], dtype=str)) if freq_pols['A']: pols_a_excludes = [pol for pol in pols_freqA if pol not in freq_pols['A']] else: pols_a_excludes = pols_freqA if freq_pols['B']: pols_b_excludes = [pol for pol in pols_freqB if pol not in freq_pols['B']] else: pols_b_excludes = pols_freqB if pols_a_excludes: cp_h5_meta_data(src_h5, dst_h5, freq_a_path, excludes=pols_a_excludes) else: cp_h5_meta_data(src_h5, dst_h5, freq_a_path, excludes=['']) if pols_b_excludes: cp_h5_meta_data(src_h5, dst_h5, freq_b_path, excludes=pols_b_excludes) else: cp_h5_meta_data(src_h5, dst_h5, freq_b_path, excludes=['']) cp_h5_meta_data(src_h5, dst_h5, metadata_path, excludes=['']) cp_h5_meta_data(src_h5, dst_h5, ident_path, excludes=['']) cp_h5_meta_data(src_h5, dst_h5, swath_path, excludes=['frequencyA', 'frequencyB']) def run(cfg: dict): ''' run bandpass ''' # pull parameters from cfg ref_hdf5 = cfg['input_file_group']['reference_rslc_file_path'] sec_hdf5 = cfg['input_file_group']['secondary_rslc_file_path'] # Extract range split spectrum dictionary and corresponding parameters ionosphere_option = cfg['processing']['ionosphere_phase_correction'] method = ionosphere_option['spectral_diversity'] split_cfg = ionosphere_option['split_range_spectrum'] iono_freq_pol = ionosphere_option['list_of_frequencies'] blocksize = split_cfg['lines_per_block'] window_function = split_cfg['window_function'] window_shape = split_cfg['window_shape'] low_band_bandwidth = split_cfg['low_band_bandwidth'] high_band_bandwidth = split_cfg['high_band_bandwidth'] scratch_path = pathlib.Path(cfg['product_path_group']['scratch_path']) info_channel = journal.info("split_spectrum.run") info_channel.log("starting split_spectrum") t_all = time.time() # Check split spectrum method if method == 'split_main_band': split_band_path = pathlib.Path( f"{scratch_path}/ionosphere/split_spectrum/") split_band_path.mkdir(parents=True, exist_ok=True) common_parent_path = 'science/LSAR' freq = 'A' pol_list = iono_freq_pol[freq] info_channel.log(f'Split the main band {pol_list} of the signal') for hdf5_ind, hdf5_str in enumerate([ref_hdf5, sec_hdf5]): # reference SLC if hdf5_ind == 0: low_band_output = f"{split_band_path}/ref_low_band_slc.h5" high_band_output = f"{split_band_path}/ref_high_band_slc.h5" # secondary SLC else: low_band_output = f"{split_band_path}/sec_low_band_slc.h5" high_band_output = f"{split_band_path}/sec_high_band_slc.h5" # Open RSLC product slc_product = SLC(hdf5file=hdf5_str) # Extract metadata # meta data extraction meta_data = splitspectrum.bandpass_meta_data.load_from_slc( slc_product=slc_product, freq=freq) bandwidth_half = 0.5 * meta_data.rg_bandwidth low_frequency_slc = meta_data.center_freq - bandwidth_half high_frequency_slc = meta_data.center_freq + bandwidth_half # first and second elements are the frequency ranges for low and high sub-bands, respectively. low_subband_frequencies = np.array( [low_frequency_slc, low_frequency_slc + low_band_bandwidth]) high_subband_frequencies = np.array( [high_frequency_slc - high_band_bandwidth, high_frequency_slc]) low_band_center_freq = low_frequency_slc + low_band_bandwidth/2 high_band_center_freq = high_frequency_slc - high_band_bandwidth/2 # Specify split-spectrum parameters split_spectrum_parameters = splitspectrum.SplitSpectrum( rg_sample_freq=meta_data.rg_sample_freq, rg_bandwidth=meta_data.rg_bandwidth, center_frequency=meta_data.center_freq, slant_range=meta_data.slant_range, freq=freq) dest_freq_path = os.path.join(slc_product.SwathPath, f'frequency{freq}') # prepare HDF5 for subband SLC HDF5 prep_subband_h5(hdf5_str, low_band_output, iono_freq_pol) prep_subband_h5(hdf5_str, high_band_output, iono_freq_pol) with h5py.File(hdf5_str, 'r', libver='latest', swmr=True) as src_h5, \ h5py.File(low_band_output, 'r+') as dst_h5_low, \ h5py.File(high_band_output, 'r+') as dst_h5_high: # Copy HDF5 metadata for low high band # cp_h5_meta_data(src_h5, dst_h5_low, f'{common_parent_path}') # cp_h5_meta_data(src_h5, dst_h5_high, f'{common_parent_path}') for pol in pol_list: raster_str = f'HDF5:{hdf5_str}:/{slc_product.slcPath(freq, pol)}' slc_raster = isce3.io.Raster(raster_str) rows = slc_raster.length cols = slc_raster.width nblocks = int(np.ceil(rows / blocksize)) fft_size = cols for block in range(0, nblocks): info_channel.log(f" split_spectrum block: {block}") row_start = block * blocksize if ((row_start + blocksize) > rows): block_rows_data = rows - row_start else: block_rows_data = blocksize dest_pol_path = f"{dest_freq_path}/{pol}" target_slc_image = np.empty([block_rows_data, cols], dtype=complex) src_h5[dest_pol_path].read_direct( target_slc_image, np.s_[row_start: row_start + block_rows_data, :]) subband_slc_low, subband_meta_low = \ split_spectrum_parameters.bandpass_shift_spectrum( slc_raster=target_slc_image, low_frequency=low_subband_frequencies[0], high_frequency=low_subband_frequencies[1], new_center_frequency=low_band_center_freq, fft_size=fft_size, window_shape=window_shape, window_function=window_function, resampling=False ) subband_slc_high, subband_meta_high = \ split_spectrum_parameters.bandpass_shift_spectrum( slc_raster=target_slc_image, low_frequency=high_subband_frequencies[0], high_frequency=high_subband_frequencies[1], new_center_frequency=high_band_center_freq, fft_size=fft_size, window_shape=window_shape, window_function=window_function, resampling=False ) if block == 0: del dst_h5_low[dest_pol_path] del dst_h5_high[dest_pol_path] # Initialize the raster with updated shape in HDF5 dst_h5_low.create_dataset(dest_pol_path, [rows, cols], np.complex64, chunks=(128, 128)) dst_h5_high.create_dataset(dest_pol_path, [rows, cols], np.complex64, chunks=(128, 128)) # Write bandpassed SLC to HDF5 dst_h5_low[dest_pol_path].write_direct( subband_slc_low, dest_sel=np.s_[ row_start: row_start + block_rows_data, :]) dst_h5_high[dest_pol_path].write_direct( subband_slc_high, dest_sel=np.s_[ row_start: row_start + block_rows_data, :]) dst_h5_low[dest_pol_path].attrs[ 'description'] = f"Split-spectrum SLC image ({pol})" dst_h5_low[dest_pol_path].attrs['units'] = f"" dst_h5_high[dest_pol_path].attrs[ 'description'] = f"Split-spectrum SLC image ({pol})" dst_h5_high[dest_pol_path].attrs['units'] = f"" # update meta information for bandpass SLC data = dst_h5_low[f"{dest_freq_path}/processedCenterFrequency"] data[...] = subband_meta_low['center_frequency'] data = dst_h5_low[f"{dest_freq_path}/processedRangeBandwidth"] data[...] = subband_meta_low['rg_bandwidth'] data = dst_h5_high[f"{dest_freq_path}/processedCenterFrequency"] data[...] = subband_meta_high['center_frequency'] data = dst_h5_high[f"{dest_freq_path}/processedRangeBandwidth"] data[...] = subband_meta_high['rg_bandwidth'] else: info_channel.log('Split spectrum is not needed') t_all_elapsed = time.time() - t_all info_channel.log( f"successfully ran split_spectrum in {t_all_elapsed:.3f} seconds") if __name__ == "__main__": ''' Run split-spectrum from command line ''' # load command line args split_spectrum_parser = YamlArgparse() args = split_spectrum_parser.parse() # get a runconfig dict from command line args split_spectrum_runconfig = SplitSpectrumRunConfig(args) # run bandpass run(split_spectrum_runconfig.cfg)
en
0.560171
#!/usr/bin/env python3 run bandpass # pull parameters from cfg # Extract range split spectrum dictionary and corresponding parameters # Check split spectrum method # reference SLC # secondary SLC # Open RSLC product # Extract metadata # meta data extraction # first and second elements are the frequency ranges for low and high sub-bands, respectively. # Specify split-spectrum parameters # prepare HDF5 for subband SLC HDF5 # Copy HDF5 metadata for low high band # cp_h5_meta_data(src_h5, dst_h5_low, f'{common_parent_path}') # cp_h5_meta_data(src_h5, dst_h5_high, f'{common_parent_path}') # Initialize the raster with updated shape in HDF5 # Write bandpassed SLC to HDF5 # update meta information for bandpass SLC Run split-spectrum from command line # load command line args # get a runconfig dict from command line args # run bandpass
1.821961
2
demopytest/demopytest.py
SimJoonYeol/pytestdemo
0
6620598
# -*- coding: utf-8 -*- def demo_method(num): num += 1 return num def demo_raise(): import rospy class demo_class(object): def demo_plus_10(self, num): num += 10 return num def demo_minus_10(self, num): num -= 10 return num def get_collections(): from demopytest import demomock collections = demomock.get_mongodb() result = '' for collection in collections: result += collection return result
# -*- coding: utf-8 -*- def demo_method(num): num += 1 return num def demo_raise(): import rospy class demo_class(object): def demo_plus_10(self, num): num += 10 return num def demo_minus_10(self, num): num -= 10 return num def get_collections(): from demopytest import demomock collections = demomock.get_mongodb() result = '' for collection in collections: result += collection return result
en
0.769321
# -*- coding: utf-8 -*-
3.041318
3
poco/scripts/extract_unidentified_keywords.py
sunliwen/poco
0
6620599
<reponame>sunliwen/poco<gh_stars>0 import sys import os.path from apps.apis.search.keyword_list import keyword_list def run(site_id, path): print "Note: " print " 1. add '#' to a line to black list a keyword" print " 2. lines without '#' would be treated as white listed" print " 3. some lines are pre-marked as black listed. You may adjust this by removing the '#'" answer = raw_input("Do you really want to extract unidentified keyword file for site: %s to path: %s?(enter 'yes' to continue)" % (site_id, path)) if answer == "yes": f_add_to_whitelist = open(path, "w") for record in keyword_list.fetchSuggestKeywordList(site_id): keyword = record["keyword"].encode("utf8") #if record["type"] == keyword_list.WHITE_LIST: # f_white.write("%s\n" % keyword) #elif record["type"] == keyword_list.BLACK_LIST: # f_black.write("%s\n" % keyword) if record["type"] == keyword_list.UNIDENTIFIED_LIST: if len(record["keyword"]) < 2 or record["count"] < 3: f_add_to_whitelist.write("#%s\n" % keyword) else: f_add_to_whitelist.write("%s\n" % keyword) f_add_to_whitelist.close() print "Finished." else: print "Exit without action." sys.exit(0)
import sys import os.path from apps.apis.search.keyword_list import keyword_list def run(site_id, path): print "Note: " print " 1. add '#' to a line to black list a keyword" print " 2. lines without '#' would be treated as white listed" print " 3. some lines are pre-marked as black listed. You may adjust this by removing the '#'" answer = raw_input("Do you really want to extract unidentified keyword file for site: %s to path: %s?(enter 'yes' to continue)" % (site_id, path)) if answer == "yes": f_add_to_whitelist = open(path, "w") for record in keyword_list.fetchSuggestKeywordList(site_id): keyword = record["keyword"].encode("utf8") #if record["type"] == keyword_list.WHITE_LIST: # f_white.write("%s\n" % keyword) #elif record["type"] == keyword_list.BLACK_LIST: # f_black.write("%s\n" % keyword) if record["type"] == keyword_list.UNIDENTIFIED_LIST: if len(record["keyword"]) < 2 or record["count"] < 3: f_add_to_whitelist.write("#%s\n" % keyword) else: f_add_to_whitelist.write("%s\n" % keyword) f_add_to_whitelist.close() print "Finished." else: print "Exit without action." sys.exit(0)
en
0.172025
#if record["type"] == keyword_list.WHITE_LIST: # f_white.write("%s\n" % keyword) #elif record["type"] == keyword_list.BLACK_LIST: # f_black.write("%s\n" % keyword)
3.269286
3
python/spi/parser.py
montreal91/jolly-jay
0
6620600
<reponame>montreal91/jolly-jay from spi.errors import ParserError, ErrorCode from spi.token import TokenType from spi.ast import Assign from spi.ast import BinaryOperation from spi.ast import Block from spi.ast import Compound from spi.ast import NoOp from spi.ast import Number from spi.ast import Param from spi.ast import ProcedureCall from spi.ast import ProcedureDeclaration from spi.ast import Program from spi.ast import Var from spi.ast import VarDeclaration from spi.ast import Type from spi.ast import UnaryOperation class Parser: def __init__(self, lexer): self._lexer = lexer self._parse_tree = None # Set current token to the first token from the input self._current_token = self._lexer.get_next_token() def parse(self): if self._parse_tree is not None: return self._parse_tree self._parse_tree = self._program() if self._current_token.get_type() != TokenType.EOF: self._error( error_code=ErrorCode.UNEXPECTED_TOKEN, token=self._current_token ) return self._parse_tree def _program(self): """ program : PROGRAM variable SEMI block DOT """ self._eat(TokenType.PROGRAM) var_node = self._variable() prog_name = var_node.value self._eat(TokenType.SEMI) block_node = self._block() program_node = Program(name=prog_name, block=block_node) self._eat(TokenType.DOT) return program_node def _block(self): """ block : declarations compound_statement """ declaration_nodes = self._declarations() compound_statement_node = self._compound_statement() return Block( declarations=declaration_nodes, compound_statement=compound_statement_node ) def _declarations(self): """ declarations : (VAR (variable_declaration SEMI)+)? | procedure_declaration* | empty """ declarations = [] while self._current_token.get_type() == TokenType.VAR: self._eat(TokenType.VAR) while self._current_token.get_type() == TokenType.ID: var_decl = self._variable_declaration() declarations.extend(var_decl) self._eat(TokenType.SEMI) while self._current_token.get_type() == TokenType.PROCEDURE: declarations.append(self._procedure_declaration()) return declarations def _procedure_declaration(self): """ procedure_declaration : PROCEDURE ID (LPAR formal_parameter_list RPAR)? SEMI block SEMI """ self._eat(TokenType.PROCEDURE) proc_name = self._current_token.get_value() self._eat(TokenType.ID) params = [] if self._current_token.get_type() == TokenType.LPAR: self._eat(TokenType.LPAR) params = self._formal_parameter_list() self._eat(TokenType.RPAR) self._eat(TokenType.SEMI) block_node = self._block() proc_decl = ProcedureDeclaration(proc_name, params, block_node) self._eat(TokenType.SEMI) return proc_decl def _proccall_statement(self): """ proccall_statement: ID LPAR (expr (COMMA expr)*)? RPAR """ token = self._current_token proc_name = token.get_value() self._eat(TokenType.ID) self._eat(TokenType.LPAR) actual_params = [] if self._current_token.get_type() != TokenType.RPAR: node = self._expr() actual_params.append(node) while self._current_token.get_type() == TokenType.COMMA: self._eat(TokenType.COMMA) node = self._expr() actual_params.append(node) self._eat(TokenType.RPAR) return ProcedureCall( proc_name=proc_name, actual_params=actual_params, token=token ) def _formal_parameter_list(self): """ formal_parameter_list : formal_parameters | formal_parameters SEMI formal_parameter_list """ parameters = self._formal_parameters() if self._current_token.get_type() == TokenType.SEMI: self._eat(TokenType.SEMI) parameters.extend(self._formal_parameter_list()) return parameters def _formal_parameters(self): """ formal_parameters : ID (COMMA ID)* COLON type_spec """ param_nodes = [Var(self._current_token)] self._eat(TokenType.ID) while self._current_token.get_type() == TokenType.COMMA: self._eat(TokenType.COMMA) param_nodes.append(Var(self._current_token)) self._eat(TokenType.ID) self._eat(TokenType.COLON) type_node = self._type_spec() return [ Param(var_node, type_node) for var_node in param_nodes ] def _variable_declaration(self): """ variable_declaration : ID (COMMA ID)* COLON type_spec """ var_nodes = [Var(self._current_token)] # first ID self._eat(TokenType.ID) while self._current_token.get_type() == TokenType.COMMA: self._eat(TokenType.COMMA) var_nodes.append(Var(self._current_token)) self._eat(TokenType.ID) self._eat(TokenType.COLON) type_node = self._type_spec() return tuple( VarDeclaration(var_node, type_node) for var_node in var_nodes ) def _type_spec(self): """ type_spec : INTEGER | REAL """ token = self._current_token if self._current_token.get_type() == TokenType.INTEGER: self._eat(TokenType.INTEGER) elif self._current_token.get_type() == TokenType.REAL: self._eat(TokenType.REAL) else: self._error(error_code=ErrorCode.UNEXPECTED_TOKEN, token=token) return Type(token) def _compound_statement(self): """ compound_statement: BEGIN statement_list END """ self._eat(TokenType.BEGIN) nodes = self._statement_list() self._eat(TokenType.END) root = Compound() for node in nodes: root.children.append(node) return root def _statement_list(self): """ statement_list : statement | statement SEMI statement_list """ node = self._statement() results = [node] while self._current_token.get_type() == TokenType.SEMI: self._eat(TokenType.SEMI) results.append(self._statement()) if self._current_token.get_type() == TokenType.ID: self._error( error_code=ErrorCode.UNEXPECTED_TOKEN, token=self._current_token ) return results def _statement(self): """ statement : compound_statement | proccall_statement | assignment_statement | empty """ if self._current_token.get_type() == TokenType.BEGIN: node = self._compound_statement() elif self._current_token.get_type() == TokenType.ID: if self._lexer.get_current_char() == '(': node = self._proccall_statement() else: node = self._assignment_statement() else: node = self._empty() return node def _assignment_statement(self): """ assignment_statement : variable ASSIGN expr """ left = self._variable() token = self._current_token self._eat(TokenType.ASSIGN) right = self._expr() return Assign(left=left, op=token, right=right) def _variable(self): """ variable : ID """ node = Var(self._current_token) self._eat(TokenType.ID) return node @staticmethod def _empty(): """ An empty production. """ return NoOp() def _expr(self): """ Process expr production. expr : operand ((PLUS | MINUS) operand)* """ node = self._operand() while self._current_token.get_type() in (TokenType.PLUS, TokenType.MINUS): token = self._current_token if token.get_type() == TokenType.PLUS: self._eat(TokenType.PLUS) elif token.get_type() == TokenType.MINUS: self._eat(TokenType.MINUS) else: self._error(error_code=ErrorCode.UNEXPECTED_TOKEN, token=token) node = BinaryOperation(left=node, op=token, right=self._operand()) return node def _operand(self): """ Process operand production. operand : factor ((MULTIPLY | INTEGER_DIV | REAL_DIV) factor)* """ node = self._factor() types = (TokenType.MULTIPLY, TokenType.INTEGER_DIV, TokenType.REAL_DIV) while self._current_token.get_type() in types: token = self._current_token if token.get_type() == TokenType.MULTIPLY: self._eat(TokenType.MULTIPLY) elif token.get_type() == TokenType.INTEGER_DIV: self._eat(TokenType.INTEGER_DIV) elif token.get_type() == TokenType.REAL_DIV: self._eat(TokenType.REAL_DIV) else: self._error(error_code=ErrorCode.UNEXPECTED_TOKEN, token=token) node = BinaryOperation(left=node, op=token, right=self._factor()) return node def _factor(self): """ Process factor production. factor : PLUS factor | MINUS factor | INTEGER_LITERAL | REAL_LITERAL | LPAR expr RPAR | variable """ token = self._current_token if token.get_type() in (TokenType.PLUS, TokenType.MINUS): self._eat(token.get_type()) return UnaryOperation(op=token, right=self._factor()) elif token.get_type() == TokenType.INTEGER_LITERAL: self._eat(TokenType.INTEGER_LITERAL) return Number(token) elif token.get_type() == TokenType.REAL_LITERAL: self._eat(TokenType.REAL_LITERAL) return Number(token) elif token.get_type() == TokenType.LPAR: self._eat(TokenType.LPAR) node = self._expr() self._eat(TokenType.RPAR) return node elif token.get_type() == TokenType.ID: # ??? return self._variable() self._error(error_code=ErrorCode.UNEXPECTED_TOKEN, token=token) def _eat(self, token_type): """ 'Eats' current token if it is of expected type. Compare the current token type with the passed token type and if they match then "eat" the current token and assign the next token to the self._current_token, otherwise raise an exception. """ if self._current_token.get_type() == token_type: self._current_token = self._lexer.get_next_token() else: print( f"expected type was {token_type} " f"got {self._current_token.get_type()}" ) self._error( error_code=ErrorCode.UNEXPECTED_TOKEN, token=self._current_token ) def _error(self, error_code, token): raise ParserError( error_code=error_code, token=token, message=f"{error_code.value} -> {token}", )
from spi.errors import ParserError, ErrorCode from spi.token import TokenType from spi.ast import Assign from spi.ast import BinaryOperation from spi.ast import Block from spi.ast import Compound from spi.ast import NoOp from spi.ast import Number from spi.ast import Param from spi.ast import ProcedureCall from spi.ast import ProcedureDeclaration from spi.ast import Program from spi.ast import Var from spi.ast import VarDeclaration from spi.ast import Type from spi.ast import UnaryOperation class Parser: def __init__(self, lexer): self._lexer = lexer self._parse_tree = None # Set current token to the first token from the input self._current_token = self._lexer.get_next_token() def parse(self): if self._parse_tree is not None: return self._parse_tree self._parse_tree = self._program() if self._current_token.get_type() != TokenType.EOF: self._error( error_code=ErrorCode.UNEXPECTED_TOKEN, token=self._current_token ) return self._parse_tree def _program(self): """ program : PROGRAM variable SEMI block DOT """ self._eat(TokenType.PROGRAM) var_node = self._variable() prog_name = var_node.value self._eat(TokenType.SEMI) block_node = self._block() program_node = Program(name=prog_name, block=block_node) self._eat(TokenType.DOT) return program_node def _block(self): """ block : declarations compound_statement """ declaration_nodes = self._declarations() compound_statement_node = self._compound_statement() return Block( declarations=declaration_nodes, compound_statement=compound_statement_node ) def _declarations(self): """ declarations : (VAR (variable_declaration SEMI)+)? | procedure_declaration* | empty """ declarations = [] while self._current_token.get_type() == TokenType.VAR: self._eat(TokenType.VAR) while self._current_token.get_type() == TokenType.ID: var_decl = self._variable_declaration() declarations.extend(var_decl) self._eat(TokenType.SEMI) while self._current_token.get_type() == TokenType.PROCEDURE: declarations.append(self._procedure_declaration()) return declarations def _procedure_declaration(self): """ procedure_declaration : PROCEDURE ID (LPAR formal_parameter_list RPAR)? SEMI block SEMI """ self._eat(TokenType.PROCEDURE) proc_name = self._current_token.get_value() self._eat(TokenType.ID) params = [] if self._current_token.get_type() == TokenType.LPAR: self._eat(TokenType.LPAR) params = self._formal_parameter_list() self._eat(TokenType.RPAR) self._eat(TokenType.SEMI) block_node = self._block() proc_decl = ProcedureDeclaration(proc_name, params, block_node) self._eat(TokenType.SEMI) return proc_decl def _proccall_statement(self): """ proccall_statement: ID LPAR (expr (COMMA expr)*)? RPAR """ token = self._current_token proc_name = token.get_value() self._eat(TokenType.ID) self._eat(TokenType.LPAR) actual_params = [] if self._current_token.get_type() != TokenType.RPAR: node = self._expr() actual_params.append(node) while self._current_token.get_type() == TokenType.COMMA: self._eat(TokenType.COMMA) node = self._expr() actual_params.append(node) self._eat(TokenType.RPAR) return ProcedureCall( proc_name=proc_name, actual_params=actual_params, token=token ) def _formal_parameter_list(self): """ formal_parameter_list : formal_parameters | formal_parameters SEMI formal_parameter_list """ parameters = self._formal_parameters() if self._current_token.get_type() == TokenType.SEMI: self._eat(TokenType.SEMI) parameters.extend(self._formal_parameter_list()) return parameters def _formal_parameters(self): """ formal_parameters : ID (COMMA ID)* COLON type_spec """ param_nodes = [Var(self._current_token)] self._eat(TokenType.ID) while self._current_token.get_type() == TokenType.COMMA: self._eat(TokenType.COMMA) param_nodes.append(Var(self._current_token)) self._eat(TokenType.ID) self._eat(TokenType.COLON) type_node = self._type_spec() return [ Param(var_node, type_node) for var_node in param_nodes ] def _variable_declaration(self): """ variable_declaration : ID (COMMA ID)* COLON type_spec """ var_nodes = [Var(self._current_token)] # first ID self._eat(TokenType.ID) while self._current_token.get_type() == TokenType.COMMA: self._eat(TokenType.COMMA) var_nodes.append(Var(self._current_token)) self._eat(TokenType.ID) self._eat(TokenType.COLON) type_node = self._type_spec() return tuple( VarDeclaration(var_node, type_node) for var_node in var_nodes ) def _type_spec(self): """ type_spec : INTEGER | REAL """ token = self._current_token if self._current_token.get_type() == TokenType.INTEGER: self._eat(TokenType.INTEGER) elif self._current_token.get_type() == TokenType.REAL: self._eat(TokenType.REAL) else: self._error(error_code=ErrorCode.UNEXPECTED_TOKEN, token=token) return Type(token) def _compound_statement(self): """ compound_statement: BEGIN statement_list END """ self._eat(TokenType.BEGIN) nodes = self._statement_list() self._eat(TokenType.END) root = Compound() for node in nodes: root.children.append(node) return root def _statement_list(self): """ statement_list : statement | statement SEMI statement_list """ node = self._statement() results = [node] while self._current_token.get_type() == TokenType.SEMI: self._eat(TokenType.SEMI) results.append(self._statement()) if self._current_token.get_type() == TokenType.ID: self._error( error_code=ErrorCode.UNEXPECTED_TOKEN, token=self._current_token ) return results def _statement(self): """ statement : compound_statement | proccall_statement | assignment_statement | empty """ if self._current_token.get_type() == TokenType.BEGIN: node = self._compound_statement() elif self._current_token.get_type() == TokenType.ID: if self._lexer.get_current_char() == '(': node = self._proccall_statement() else: node = self._assignment_statement() else: node = self._empty() return node def _assignment_statement(self): """ assignment_statement : variable ASSIGN expr """ left = self._variable() token = self._current_token self._eat(TokenType.ASSIGN) right = self._expr() return Assign(left=left, op=token, right=right) def _variable(self): """ variable : ID """ node = Var(self._current_token) self._eat(TokenType.ID) return node @staticmethod def _empty(): """ An empty production. """ return NoOp() def _expr(self): """ Process expr production. expr : operand ((PLUS | MINUS) operand)* """ node = self._operand() while self._current_token.get_type() in (TokenType.PLUS, TokenType.MINUS): token = self._current_token if token.get_type() == TokenType.PLUS: self._eat(TokenType.PLUS) elif token.get_type() == TokenType.MINUS: self._eat(TokenType.MINUS) else: self._error(error_code=ErrorCode.UNEXPECTED_TOKEN, token=token) node = BinaryOperation(left=node, op=token, right=self._operand()) return node def _operand(self): """ Process operand production. operand : factor ((MULTIPLY | INTEGER_DIV | REAL_DIV) factor)* """ node = self._factor() types = (TokenType.MULTIPLY, TokenType.INTEGER_DIV, TokenType.REAL_DIV) while self._current_token.get_type() in types: token = self._current_token if token.get_type() == TokenType.MULTIPLY: self._eat(TokenType.MULTIPLY) elif token.get_type() == TokenType.INTEGER_DIV: self._eat(TokenType.INTEGER_DIV) elif token.get_type() == TokenType.REAL_DIV: self._eat(TokenType.REAL_DIV) else: self._error(error_code=ErrorCode.UNEXPECTED_TOKEN, token=token) node = BinaryOperation(left=node, op=token, right=self._factor()) return node def _factor(self): """ Process factor production. factor : PLUS factor | MINUS factor | INTEGER_LITERAL | REAL_LITERAL | LPAR expr RPAR | variable """ token = self._current_token if token.get_type() in (TokenType.PLUS, TokenType.MINUS): self._eat(token.get_type()) return UnaryOperation(op=token, right=self._factor()) elif token.get_type() == TokenType.INTEGER_LITERAL: self._eat(TokenType.INTEGER_LITERAL) return Number(token) elif token.get_type() == TokenType.REAL_LITERAL: self._eat(TokenType.REAL_LITERAL) return Number(token) elif token.get_type() == TokenType.LPAR: self._eat(TokenType.LPAR) node = self._expr() self._eat(TokenType.RPAR) return node elif token.get_type() == TokenType.ID: # ??? return self._variable() self._error(error_code=ErrorCode.UNEXPECTED_TOKEN, token=token) def _eat(self, token_type): """ 'Eats' current token if it is of expected type. Compare the current token type with the passed token type and if they match then "eat" the current token and assign the next token to the self._current_token, otherwise raise an exception. """ if self._current_token.get_type() == token_type: self._current_token = self._lexer.get_next_token() else: print( f"expected type was {token_type} " f"got {self._current_token.get_type()}" ) self._error( error_code=ErrorCode.UNEXPECTED_TOKEN, token=self._current_token ) def _error(self, error_code, token): raise ParserError( error_code=error_code, token=token, message=f"{error_code.value} -> {token}", )
en
0.536399
# Set current token to the first token from the input program : PROGRAM variable SEMI block DOT block : declarations compound_statement declarations : (VAR (variable_declaration SEMI)+)? | procedure_declaration* | empty procedure_declaration : PROCEDURE ID (LPAR formal_parameter_list RPAR)? SEMI block SEMI proccall_statement: ID LPAR (expr (COMMA expr)*)? RPAR formal_parameter_list : formal_parameters | formal_parameters SEMI formal_parameter_list formal_parameters : ID (COMMA ID)* COLON type_spec variable_declaration : ID (COMMA ID)* COLON type_spec # first ID type_spec : INTEGER | REAL compound_statement: BEGIN statement_list END statement_list : statement | statement SEMI statement_list statement : compound_statement | proccall_statement | assignment_statement | empty assignment_statement : variable ASSIGN expr variable : ID An empty production. Process expr production. expr : operand ((PLUS | MINUS) operand)* Process operand production. operand : factor ((MULTIPLY | INTEGER_DIV | REAL_DIV) factor)* Process factor production. factor : PLUS factor | MINUS factor | INTEGER_LITERAL | REAL_LITERAL | LPAR expr RPAR | variable # ??? 'Eats' current token if it is of expected type. Compare the current token type with the passed token type and if they match then "eat" the current token and assign the next token to the self._current_token, otherwise raise an exception.
2.586588
3
setup.py
7starsea/shark
0
6620601
from skbuild import setup from setuptools import find_packages # # python setup.py install --generator "Sublime Text 2 - Unix Makefiles" -- -- -j8 # # python setup.py install -- -- -j8 package_folder = 'shark' setup( name='shark', version='0.0.1', description='reinforcement learning project shark', author='<NAME>', author_email='<EMAIL>,<EMAIL>', license='MIT', python_requires='>=3.6', packages=find_packages(exclude=("test", "test.*", "docs", "docs.*")), # same as name cmake_source_dir="shark", classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', # Indicate who your project is intended for 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Software Development :: Libraries :: Python Modules', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], keywords='reinforcement learning project pytorch', # install_requires=[ # 'gym>=0.15.0', # 'tqdm', # 'numpy', # 'tensorboard', # 'torch>=1.2.0', # ], ) # print(find_packages())
from skbuild import setup from setuptools import find_packages # # python setup.py install --generator "Sublime Text 2 - Unix Makefiles" -- -- -j8 # # python setup.py install -- -- -j8 package_folder = 'shark' setup( name='shark', version='0.0.1', description='reinforcement learning project shark', author='<NAME>', author_email='<EMAIL>,<EMAIL>', license='MIT', python_requires='>=3.6', packages=find_packages(exclude=("test", "test.*", "docs", "docs.*")), # same as name cmake_source_dir="shark", classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', # Indicate who your project is intended for 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Software Development :: Libraries :: Python Modules', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], keywords='reinforcement learning project pytorch', # install_requires=[ # 'gym>=0.15.0', # 'tqdm', # 'numpy', # 'tensorboard', # 'torch>=1.2.0', # ], ) # print(find_packages())
en
0.627823
# # python setup.py install --generator "Sublime Text 2 - Unix Makefiles" -- -- -j8 # # python setup.py install -- -- -j8 # same as name # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable # Indicate who your project is intended for # Pick your license as you wish (should match "license" above) # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. # install_requires=[ # 'gym>=0.15.0', # 'tqdm', # 'numpy', # 'tensorboard', # 'torch>=1.2.0', # ], # print(find_packages())
1.687061
2
git/remote.py
swallat/GitPython
1
6620602
<reponame>swallat/GitPython # remote.py # Copyright (C) 2008, 2009 <NAME> (<EMAIL>) and contributors # # This module is part of GitPython and is released under # the BSD License: http://www.opensource.org/licenses/bsd-license.php # Module implementing a remote object allowing easy access to git remotes from exc import GitCommandError from ConfigParser import NoOptionError from config import SectionConstraint from git.util import ( LazyMixin, Iterable, IterableList ) from git.db.interface import TransportDB from refs import RemoteReference import os __all__ = ['Remote'] class PushInfo(object): """Wrapper for basic PushInfo to provide the previous interface which includes resolved objects instead of plain shas old_commit # object for the corresponding old_commit_sha""" class FetchInfo(object): """Wrapper to restore the previous interface, resolving objects and wrapping references""" class Remote(LazyMixin, Iterable): """Provides easy read and write access to a git remote. Everything not part of this interface is considered an option for the current remote, allowing constructs like remote.pushurl to query the pushurl. NOTE: When querying configuration, the configuration accessor will be cached to speed up subsequent accesses.""" __slots__ = ( "repo", "name", "_config_reader" ) _id_attribute_ = "name" def __init__(self, repo, name): """Initialize a remote instance :param repo: The repository we are a remote of :param name: the name of the remote, i.e. 'origin'""" if not hasattr(repo, 'git'): # note: at some point we could just create a git command instance ourselves # but lets just be lazy for now raise AssertionError("Require repository to provide a git command instance currently") #END assert git cmd if not isinstance(repo, TransportDB): raise AssertionError("Require TransportDB interface implementation") #END verify interface self.repo = repo self.name = name if os.name == 'nt': # some oddity: on windows, python 2.5, it for some reason does not realize # that it has the config_writer property, but instead calls __getattr__ # which will not yield the expected results. 'pinging' the members # with a dir call creates the config_writer property that we require # ... bugs like these make me wonder wheter python really wants to be used # for production. It doesn't happen on linux though. dir(self) # END windows special handling def __getattr__(self, attr): """Allows to call this instance like remote.special( *args, **kwargs) to call git-remote special self.name""" if attr == "_config_reader": return super(Remote, self).__getattr__(attr) # sometimes, probably due to a bug in python itself, we are being called # even though a slot of the same name exists try: return self._config_reader.get(attr) except NoOptionError: return super(Remote, self).__getattr__(attr) # END handle exception def _config_section_name(self): return 'remote "%s"' % self.name def _set_cache_(self, attr): if attr == "_config_reader": self._config_reader = SectionConstraint(self.repo.config_reader(), self._config_section_name()) else: super(Remote, self)._set_cache_(attr) def __str__(self): return self.name def __repr__(self): return '<git.%s "%s">' % (self.__class__.__name__, self.name) def __eq__(self, other): return self.name == other.name def __ne__(self, other): return not ( self == other ) def __hash__(self): return hash(self.name) @classmethod def iter_items(cls, repo): """:return: Iterator yielding Remote objects of the given repository""" for section in repo.config_reader("repository").sections(): if not section.startswith('remote'): continue lbound = section.find('"') rbound = section.rfind('"') if lbound == -1 or rbound == -1: raise ValueError("Remote-Section has invalid format: %r" % section) yield Remote(repo, section[lbound+1:rbound]) # END for each configuration section @property def refs(self): """ :return: IterableList of RemoteReference objects. It is prefixed, allowing you to omit the remote path portion, i.e.:: remote.refs.master # yields RemoteReference('/refs/remotes/origin/master')""" out_refs = IterableList(RemoteReference._id_attribute_, "%s/" % self.name) out_refs.extend(RemoteReference.list_items(self.repo, remote=self.name)) assert out_refs, "Remote %s did not have any references" % self.name return out_refs @property def stale_refs(self): """ :return: IterableList RemoteReference objects that do not have a corresponding head in the remote reference anymore as they have been deleted on the remote side, but are still available locally. The IterableList is prefixed, hence the 'origin' must be omitted. See 'refs' property for an example.""" out_refs = IterableList(RemoteReference._id_attribute_, "%s/" % self.name) for line in self.repo.git.remote("prune", "--dry-run", self).splitlines()[2:]: # expecting # * [would prune] origin/new_branch token = " * [would prune] " if not line.startswith(token): raise ValueError("Could not parse git-remote prune result: %r" % line) fqhn = "%s/%s" % (RemoteReference._common_path_default,line.replace(token, "")) out_refs.append(RemoteReference(self.repo, fqhn)) # END for each line return out_refs @classmethod def create(cls, repo, name, url, **kwargs): """Create a new remote to the given repository :param repo: Repository instance that is to receive the new remote :param name: Desired name of the remote :param url: URL which corresponds to the remote's name :param kwargs: Additional arguments to be passed to the git-remote add command :return: New Remote instance :raise GitCommandError: in case an origin with that name already exists""" repo.git.remote( "add", name, url, **kwargs ) return cls(repo, name) # add is an alias add = create @classmethod def remove(cls, repo, name ): """Remove the remote with the given name""" repo.git.remote("rm", name) # alias rm = remove def rename(self, new_name): """Rename self to the given new_name :return: self """ if self.name == new_name: return self self.repo.git.remote("rename", self.name, new_name) self.name = new_name try: del(self._config_reader) # it contains cached values, section names are different now except AttributeError: pass #END handle exception return self def update(self, **kwargs): """Fetch all changes for this remote, including new branches which will be forced in ( in case your local remote branch is not part the new remote branches ancestry anymore ). :param kwargs: Additional arguments passed to git-remote update :return: self """ self.repo.git.remote("update", self.name) return self def fetch(self, refspec=None, progress=None, **kwargs): """Fetch the latest changes for this remote :param refspec: A "refspec" is used by fetch and push to describe the mapping between remote ref and local ref. They are combined with a colon in the format <src>:<dst>, preceded by an optional plus sign, +. For example: git fetch $URL refs/heads/master:refs/heads/origin means "grab the master branch head from the $URL and store it as my origin branch head". And git push $URL refs/heads/master:refs/heads/to-upstream means "publish my master branch head as to-upstream branch at $URL". See also git-push(1). Taken from the git manual :param progress: See 'push' method :param kwargs: Additional arguments to be passed to git-fetch :return: IterableList(FetchInfo, ...) list of FetchInfo instances providing detailed information about the fetch results :note: As fetch does not provide progress information to non-ttys, we cannot make it available here unfortunately as in the 'push' method.""" return self.repo.fetch(self.name, refspec, progress, **kwargs) def pull(self, refspec=None, progress=None, **kwargs): """Pull changes from the given branch, being the same as a fetch followed by a merge of branch with your local branch. :param refspec: see 'fetch' method :param progress: see 'push' method :param kwargs: Additional arguments to be passed to git-pull :return: Please see 'fetch' method """ return self.repo.pull(self.name, refspec, progress, **kwargs) def push(self, refspec=None, progress=None, **kwargs): """Push changes from source branch in refspec to target branch in refspec. :param refspec: see 'fetch' method :param progress: Instance of type RemoteProgress allowing the caller to receive progress information until the method returns. If None, progress information will be discarded :param kwargs: Additional arguments to be passed to git-push :return: IterableList(PushInfo, ...) iterable list of PushInfo instances, each one informing about an individual head which had been updated on the remote side. If the push contains rejected heads, these will have the PushInfo.ERROR bit set in their flags. If the operation fails completely, the length of the returned IterableList will be null.""" return self.repo.push(self.name, refspec, progress, **kwargs) @property def config_reader(self): """ :return: GitConfigParser compatible object able to read options for only our remote. Hence you may simple type config.get("pushurl") to obtain the information""" return self._config_reader @property def config_writer(self): """ :return: GitConfigParser compatible object able to write options for this remote. :note: You can only own one writer at a time - delete it to release the configuration file and make it useable by others. To assure consistent results, you should only query options through the writer. Once you are done writing, you are free to use the config reader once again.""" writer = self.repo.config_writer() # clear our cache to assure we re-read the possibly changed configuration try: del(self._config_reader) except AttributeError: pass #END handle exception return SectionConstraint(writer, self._config_section_name())
# remote.py # Copyright (C) 2008, 2009 <NAME> (<EMAIL>) and contributors # # This module is part of GitPython and is released under # the BSD License: http://www.opensource.org/licenses/bsd-license.php # Module implementing a remote object allowing easy access to git remotes from exc import GitCommandError from ConfigParser import NoOptionError from config import SectionConstraint from git.util import ( LazyMixin, Iterable, IterableList ) from git.db.interface import TransportDB from refs import RemoteReference import os __all__ = ['Remote'] class PushInfo(object): """Wrapper for basic PushInfo to provide the previous interface which includes resolved objects instead of plain shas old_commit # object for the corresponding old_commit_sha""" class FetchInfo(object): """Wrapper to restore the previous interface, resolving objects and wrapping references""" class Remote(LazyMixin, Iterable): """Provides easy read and write access to a git remote. Everything not part of this interface is considered an option for the current remote, allowing constructs like remote.pushurl to query the pushurl. NOTE: When querying configuration, the configuration accessor will be cached to speed up subsequent accesses.""" __slots__ = ( "repo", "name", "_config_reader" ) _id_attribute_ = "name" def __init__(self, repo, name): """Initialize a remote instance :param repo: The repository we are a remote of :param name: the name of the remote, i.e. 'origin'""" if not hasattr(repo, 'git'): # note: at some point we could just create a git command instance ourselves # but lets just be lazy for now raise AssertionError("Require repository to provide a git command instance currently") #END assert git cmd if not isinstance(repo, TransportDB): raise AssertionError("Require TransportDB interface implementation") #END verify interface self.repo = repo self.name = name if os.name == 'nt': # some oddity: on windows, python 2.5, it for some reason does not realize # that it has the config_writer property, but instead calls __getattr__ # which will not yield the expected results. 'pinging' the members # with a dir call creates the config_writer property that we require # ... bugs like these make me wonder wheter python really wants to be used # for production. It doesn't happen on linux though. dir(self) # END windows special handling def __getattr__(self, attr): """Allows to call this instance like remote.special( *args, **kwargs) to call git-remote special self.name""" if attr == "_config_reader": return super(Remote, self).__getattr__(attr) # sometimes, probably due to a bug in python itself, we are being called # even though a slot of the same name exists try: return self._config_reader.get(attr) except NoOptionError: return super(Remote, self).__getattr__(attr) # END handle exception def _config_section_name(self): return 'remote "%s"' % self.name def _set_cache_(self, attr): if attr == "_config_reader": self._config_reader = SectionConstraint(self.repo.config_reader(), self._config_section_name()) else: super(Remote, self)._set_cache_(attr) def __str__(self): return self.name def __repr__(self): return '<git.%s "%s">' % (self.__class__.__name__, self.name) def __eq__(self, other): return self.name == other.name def __ne__(self, other): return not ( self == other ) def __hash__(self): return hash(self.name) @classmethod def iter_items(cls, repo): """:return: Iterator yielding Remote objects of the given repository""" for section in repo.config_reader("repository").sections(): if not section.startswith('remote'): continue lbound = section.find('"') rbound = section.rfind('"') if lbound == -1 or rbound == -1: raise ValueError("Remote-Section has invalid format: %r" % section) yield Remote(repo, section[lbound+1:rbound]) # END for each configuration section @property def refs(self): """ :return: IterableList of RemoteReference objects. It is prefixed, allowing you to omit the remote path portion, i.e.:: remote.refs.master # yields RemoteReference('/refs/remotes/origin/master')""" out_refs = IterableList(RemoteReference._id_attribute_, "%s/" % self.name) out_refs.extend(RemoteReference.list_items(self.repo, remote=self.name)) assert out_refs, "Remote %s did not have any references" % self.name return out_refs @property def stale_refs(self): """ :return: IterableList RemoteReference objects that do not have a corresponding head in the remote reference anymore as they have been deleted on the remote side, but are still available locally. The IterableList is prefixed, hence the 'origin' must be omitted. See 'refs' property for an example.""" out_refs = IterableList(RemoteReference._id_attribute_, "%s/" % self.name) for line in self.repo.git.remote("prune", "--dry-run", self).splitlines()[2:]: # expecting # * [would prune] origin/new_branch token = " * [would prune] " if not line.startswith(token): raise ValueError("Could not parse git-remote prune result: %r" % line) fqhn = "%s/%s" % (RemoteReference._common_path_default,line.replace(token, "")) out_refs.append(RemoteReference(self.repo, fqhn)) # END for each line return out_refs @classmethod def create(cls, repo, name, url, **kwargs): """Create a new remote to the given repository :param repo: Repository instance that is to receive the new remote :param name: Desired name of the remote :param url: URL which corresponds to the remote's name :param kwargs: Additional arguments to be passed to the git-remote add command :return: New Remote instance :raise GitCommandError: in case an origin with that name already exists""" repo.git.remote( "add", name, url, **kwargs ) return cls(repo, name) # add is an alias add = create @classmethod def remove(cls, repo, name ): """Remove the remote with the given name""" repo.git.remote("rm", name) # alias rm = remove def rename(self, new_name): """Rename self to the given new_name :return: self """ if self.name == new_name: return self self.repo.git.remote("rename", self.name, new_name) self.name = new_name try: del(self._config_reader) # it contains cached values, section names are different now except AttributeError: pass #END handle exception return self def update(self, **kwargs): """Fetch all changes for this remote, including new branches which will be forced in ( in case your local remote branch is not part the new remote branches ancestry anymore ). :param kwargs: Additional arguments passed to git-remote update :return: self """ self.repo.git.remote("update", self.name) return self def fetch(self, refspec=None, progress=None, **kwargs): """Fetch the latest changes for this remote :param refspec: A "refspec" is used by fetch and push to describe the mapping between remote ref and local ref. They are combined with a colon in the format <src>:<dst>, preceded by an optional plus sign, +. For example: git fetch $URL refs/heads/master:refs/heads/origin means "grab the master branch head from the $URL and store it as my origin branch head". And git push $URL refs/heads/master:refs/heads/to-upstream means "publish my master branch head as to-upstream branch at $URL". See also git-push(1). Taken from the git manual :param progress: See 'push' method :param kwargs: Additional arguments to be passed to git-fetch :return: IterableList(FetchInfo, ...) list of FetchInfo instances providing detailed information about the fetch results :note: As fetch does not provide progress information to non-ttys, we cannot make it available here unfortunately as in the 'push' method.""" return self.repo.fetch(self.name, refspec, progress, **kwargs) def pull(self, refspec=None, progress=None, **kwargs): """Pull changes from the given branch, being the same as a fetch followed by a merge of branch with your local branch. :param refspec: see 'fetch' method :param progress: see 'push' method :param kwargs: Additional arguments to be passed to git-pull :return: Please see 'fetch' method """ return self.repo.pull(self.name, refspec, progress, **kwargs) def push(self, refspec=None, progress=None, **kwargs): """Push changes from source branch in refspec to target branch in refspec. :param refspec: see 'fetch' method :param progress: Instance of type RemoteProgress allowing the caller to receive progress information until the method returns. If None, progress information will be discarded :param kwargs: Additional arguments to be passed to git-push :return: IterableList(PushInfo, ...) iterable list of PushInfo instances, each one informing about an individual head which had been updated on the remote side. If the push contains rejected heads, these will have the PushInfo.ERROR bit set in their flags. If the operation fails completely, the length of the returned IterableList will be null.""" return self.repo.push(self.name, refspec, progress, **kwargs) @property def config_reader(self): """ :return: GitConfigParser compatible object able to read options for only our remote. Hence you may simple type config.get("pushurl") to obtain the information""" return self._config_reader @property def config_writer(self): """ :return: GitConfigParser compatible object able to write options for this remote. :note: You can only own one writer at a time - delete it to release the configuration file and make it useable by others. To assure consistent results, you should only query options through the writer. Once you are done writing, you are free to use the config reader once again.""" writer = self.repo.config_writer() # clear our cache to assure we re-read the possibly changed configuration try: del(self._config_reader) except AttributeError: pass #END handle exception return SectionConstraint(writer, self._config_section_name())
en
0.834528
# remote.py # Copyright (C) 2008, 2009 <NAME> (<EMAIL>) and contributors # # This module is part of GitPython and is released under # the BSD License: http://www.opensource.org/licenses/bsd-license.php # Module implementing a remote object allowing easy access to git remotes Wrapper for basic PushInfo to provide the previous interface which includes resolved objects instead of plain shas old_commit # object for the corresponding old_commit_sha Wrapper to restore the previous interface, resolving objects and wrapping references Provides easy read and write access to a git remote. Everything not part of this interface is considered an option for the current remote, allowing constructs like remote.pushurl to query the pushurl. NOTE: When querying configuration, the configuration accessor will be cached to speed up subsequent accesses. Initialize a remote instance :param repo: The repository we are a remote of :param name: the name of the remote, i.e. 'origin' # note: at some point we could just create a git command instance ourselves # but lets just be lazy for now #END assert git cmd #END verify interface # some oddity: on windows, python 2.5, it for some reason does not realize # that it has the config_writer property, but instead calls __getattr__ # which will not yield the expected results. 'pinging' the members # with a dir call creates the config_writer property that we require # ... bugs like these make me wonder wheter python really wants to be used # for production. It doesn't happen on linux though. # END windows special handling Allows to call this instance like remote.special( *args, **kwargs) to call git-remote special self.name # sometimes, probably due to a bug in python itself, we are being called # even though a slot of the same name exists # END handle exception :return: Iterator yielding Remote objects of the given repository # END for each configuration section :return: IterableList of RemoteReference objects. It is prefixed, allowing you to omit the remote path portion, i.e.:: remote.refs.master # yields RemoteReference('/refs/remotes/origin/master') :return: IterableList RemoteReference objects that do not have a corresponding head in the remote reference anymore as they have been deleted on the remote side, but are still available locally. The IterableList is prefixed, hence the 'origin' must be omitted. See 'refs' property for an example. # expecting # * [would prune] origin/new_branch # END for each line Create a new remote to the given repository :param repo: Repository instance that is to receive the new remote :param name: Desired name of the remote :param url: URL which corresponds to the remote's name :param kwargs: Additional arguments to be passed to the git-remote add command :return: New Remote instance :raise GitCommandError: in case an origin with that name already exists # add is an alias Remove the remote with the given name # alias Rename self to the given new_name :return: self # it contains cached values, section names are different now #END handle exception Fetch all changes for this remote, including new branches which will be forced in ( in case your local remote branch is not part the new remote branches ancestry anymore ). :param kwargs: Additional arguments passed to git-remote update :return: self Fetch the latest changes for this remote :param refspec: A "refspec" is used by fetch and push to describe the mapping between remote ref and local ref. They are combined with a colon in the format <src>:<dst>, preceded by an optional plus sign, +. For example: git fetch $URL refs/heads/master:refs/heads/origin means "grab the master branch head from the $URL and store it as my origin branch head". And git push $URL refs/heads/master:refs/heads/to-upstream means "publish my master branch head as to-upstream branch at $URL". See also git-push(1). Taken from the git manual :param progress: See 'push' method :param kwargs: Additional arguments to be passed to git-fetch :return: IterableList(FetchInfo, ...) list of FetchInfo instances providing detailed information about the fetch results :note: As fetch does not provide progress information to non-ttys, we cannot make it available here unfortunately as in the 'push' method. Pull changes from the given branch, being the same as a fetch followed by a merge of branch with your local branch. :param refspec: see 'fetch' method :param progress: see 'push' method :param kwargs: Additional arguments to be passed to git-pull :return: Please see 'fetch' method Push changes from source branch in refspec to target branch in refspec. :param refspec: see 'fetch' method :param progress: Instance of type RemoteProgress allowing the caller to receive progress information until the method returns. If None, progress information will be discarded :param kwargs: Additional arguments to be passed to git-push :return: IterableList(PushInfo, ...) iterable list of PushInfo instances, each one informing about an individual head which had been updated on the remote side. If the push contains rejected heads, these will have the PushInfo.ERROR bit set in their flags. If the operation fails completely, the length of the returned IterableList will be null. :return: GitConfigParser compatible object able to read options for only our remote. Hence you may simple type config.get("pushurl") to obtain the information :return: GitConfigParser compatible object able to write options for this remote. :note: You can only own one writer at a time - delete it to release the configuration file and make it useable by others. To assure consistent results, you should only query options through the writer. Once you are done writing, you are free to use the config reader once again. # clear our cache to assure we re-read the possibly changed configuration #END handle exception
2.544036
3
score_map_method/activation_map.py
naver-ai/calm
77
6620603
""" CALM Copyright (c) 2021-present NAVER Corp. MIT license """ __all__ = ['activation_map'] def activation_map(model, images, targets, score_map_process, superclass=None, **kwargs): cams = model(images, targets, superclass, return_cam=score_map_process) return cams
""" CALM Copyright (c) 2021-present NAVER Corp. MIT license """ __all__ = ['activation_map'] def activation_map(model, images, targets, score_map_process, superclass=None, **kwargs): cams = model(images, targets, superclass, return_cam=score_map_process) return cams
en
0.621563
CALM Copyright (c) 2021-present NAVER Corp. MIT license
2.071302
2
cogs/restricted.py
TrendingTechnology/tessarect-bot
1
6620604
import discord from discord.ext import commands,tasks import random import requests import json import asyncio import itertools import io from contextlib import redirect_stdout mainaccid =900992402356043806 class Restricted(commands.Cog): def __init__(self,bot): self.bot=bot ##DANGEROUS-> "https://stackoverflow.com/questions/34385014/how-do-i-set-the-output-of-exec-to-variable-python" ##BUT RUNNING FROM SERVERS LIKE heroku TILL NOW HAVE NOT SHOWN ANY AFFECT ON THE CODING COMPUTER EVEN WITH OS MODULE CODES ##THE OUTPUT IS : "py" ##eval command->executes any python code and displays output(work in progress) @commands.is_owner() @commands.command(hidden=True) async def servers(self,ctx): activeservers = self.bot.guilds for guild in activeservers: name=str(guild.name) description=str(guild.description) owner=str(guild.owner) _id = str(guild.id) region=str(guild.region) memcount=str(guild.member_count) icon = str(guild.icon_url) ver = str(ctx.guild.verification_level) embed=discord.Embed( title=name +" Server Information", description=description, color=discord.Color.blue() ) embed.set_thumbnail(url=icon) embed.add_field(name="Owner",value=owner,inline=True) embed.add_field(name="Server Id",value=_id,inline=True) embed.add_field(name="Region",value=region,inline=True) embed.add_field(name="Member Count",value=memcount,inline=True) embed.add_field(name="Verification Level",value=ver,inline=True) await ctx.send(embed=embed) print(guild.name) @commands.is_owner() @commands.command(hidden=True) async def invservers(self,ctx): invites = [] for guild in self.bot.guilds: for c in guild.text_channels: if c.permissions_for(guild.me).create_instant_invite: # make sure the bot can actually create an invite invite = await c.create_invite() invites.append(invite) break print(invites) # stop iterating over guild.text_channels, since you only need one invite per guild @commands.is_owner() @commands.command(hidden=True) async def msgservers(self,ctx,*,text): activeservers = self.bot.guilds for guild in activeservers: allowed=[] for channel in guild.text_channels: if channel.permissions_for(guild.me).send_messages and channel.permissions_for(guild.me).embed_links: allowed.append(channel) if len(allowed) >= 1: to_post = allowed[0] for channel in allowed: if "general" in channel.name.lower(): to_post = channel break try: await to_post.send(text) await ctx.send("Sent message to Guild: "+guild.name+" Channel: "+to_post.name) except Exception as e: await ctx.send(e) @commands.is_owner() @commands.command(hidden=True) async def msgserver(self,ctx): def check(msg): return msg.author == ctx.author and str(ctx.author.id) == mainaccid and msg.channel == ctx.channel await ctx.send("Guild name:") try: guild = await self.bot.wait_for("message", check=check , timeout=60) except asyncio.TimeoutError: await ctx.send("Sorry you took too long to respond!(waited for 60sec)") return await ctx.send("Channel name:") try: channel = await self.bot.wait_for("message", check=check , timeout=60) except asyncio.TimeoutError: await ctx.send("Sorry you took too long to respond!(waited for 60sec)") return await ctx.send("Message:") try: msg = await self.bot.wait_for("message", check=check , timeout=60) except asyncio.TimeoutError: await ctx.send("Sorry you took too long to respond!(waited for 60sec)") return await ctx.send("Times:") try: times = await self.bot.wait_for("message", check=check , timeout=60) except asyncio.TimeoutError: await ctx.send("Sorry you took too long to respond!(waited for 60sec)") return activeservers = self.bot.guilds for g in activeservers: if g.name==guild.content: for ch in g.channels: if(ch.name == channel.content): for i in range(int(times.content)): try: await ch.send(msg.content) await ctx.send("Sent message") except Exception as e: await ctx.send(e) def setup(bot): bot.add_cog(Restricted(bot))
import discord from discord.ext import commands,tasks import random import requests import json import asyncio import itertools import io from contextlib import redirect_stdout mainaccid =900992402356043806 class Restricted(commands.Cog): def __init__(self,bot): self.bot=bot ##DANGEROUS-> "https://stackoverflow.com/questions/34385014/how-do-i-set-the-output-of-exec-to-variable-python" ##BUT RUNNING FROM SERVERS LIKE heroku TILL NOW HAVE NOT SHOWN ANY AFFECT ON THE CODING COMPUTER EVEN WITH OS MODULE CODES ##THE OUTPUT IS : "py" ##eval command->executes any python code and displays output(work in progress) @commands.is_owner() @commands.command(hidden=True) async def servers(self,ctx): activeservers = self.bot.guilds for guild in activeservers: name=str(guild.name) description=str(guild.description) owner=str(guild.owner) _id = str(guild.id) region=str(guild.region) memcount=str(guild.member_count) icon = str(guild.icon_url) ver = str(ctx.guild.verification_level) embed=discord.Embed( title=name +" Server Information", description=description, color=discord.Color.blue() ) embed.set_thumbnail(url=icon) embed.add_field(name="Owner",value=owner,inline=True) embed.add_field(name="Server Id",value=_id,inline=True) embed.add_field(name="Region",value=region,inline=True) embed.add_field(name="Member Count",value=memcount,inline=True) embed.add_field(name="Verification Level",value=ver,inline=True) await ctx.send(embed=embed) print(guild.name) @commands.is_owner() @commands.command(hidden=True) async def invservers(self,ctx): invites = [] for guild in self.bot.guilds: for c in guild.text_channels: if c.permissions_for(guild.me).create_instant_invite: # make sure the bot can actually create an invite invite = await c.create_invite() invites.append(invite) break print(invites) # stop iterating over guild.text_channels, since you only need one invite per guild @commands.is_owner() @commands.command(hidden=True) async def msgservers(self,ctx,*,text): activeservers = self.bot.guilds for guild in activeservers: allowed=[] for channel in guild.text_channels: if channel.permissions_for(guild.me).send_messages and channel.permissions_for(guild.me).embed_links: allowed.append(channel) if len(allowed) >= 1: to_post = allowed[0] for channel in allowed: if "general" in channel.name.lower(): to_post = channel break try: await to_post.send(text) await ctx.send("Sent message to Guild: "+guild.name+" Channel: "+to_post.name) except Exception as e: await ctx.send(e) @commands.is_owner() @commands.command(hidden=True) async def msgserver(self,ctx): def check(msg): return msg.author == ctx.author and str(ctx.author.id) == mainaccid and msg.channel == ctx.channel await ctx.send("Guild name:") try: guild = await self.bot.wait_for("message", check=check , timeout=60) except asyncio.TimeoutError: await ctx.send("Sorry you took too long to respond!(waited for 60sec)") return await ctx.send("Channel name:") try: channel = await self.bot.wait_for("message", check=check , timeout=60) except asyncio.TimeoutError: await ctx.send("Sorry you took too long to respond!(waited for 60sec)") return await ctx.send("Message:") try: msg = await self.bot.wait_for("message", check=check , timeout=60) except asyncio.TimeoutError: await ctx.send("Sorry you took too long to respond!(waited for 60sec)") return await ctx.send("Times:") try: times = await self.bot.wait_for("message", check=check , timeout=60) except asyncio.TimeoutError: await ctx.send("Sorry you took too long to respond!(waited for 60sec)") return activeservers = self.bot.guilds for g in activeservers: if g.name==guild.content: for ch in g.channels: if(ch.name == channel.content): for i in range(int(times.content)): try: await ch.send(msg.content) await ctx.send("Sent message") except Exception as e: await ctx.send(e) def setup(bot): bot.add_cog(Restricted(bot))
en
0.526278
##DANGEROUS-> "https://stackoverflow.com/questions/34385014/how-do-i-set-the-output-of-exec-to-variable-python" ##BUT RUNNING FROM SERVERS LIKE heroku TILL NOW HAVE NOT SHOWN ANY AFFECT ON THE CODING COMPUTER EVEN WITH OS MODULE CODES ##THE OUTPUT IS : "py" ##eval command->executes any python code and displays output(work in progress) # make sure the bot can actually create an invite # stop iterating over guild.text_channels, since you only need one invite per guild
2.552223
3
rio/blueprints/api_1.py
soasme/rio
0
6620605
<reponame>soasme/rio # -*- coding: utf-8 -*- """ rio.blueprints.api_1 ~~~~~~~~~~~~~~~~~~~~~ """ from flask import Blueprint bp = Blueprint('api_1', __name__)
# -*- coding: utf-8 -*- """ rio.blueprints.api_1 ~~~~~~~~~~~~~~~~~~~~~ """ from flask import Blueprint bp = Blueprint('api_1', __name__)
en
0.352277
# -*- coding: utf-8 -*- rio.blueprints.api_1 ~~~~~~~~~~~~~~~~~~~~~
1.378232
1
src/ds/doubly_linkedlist.py
snandasena/python-oop
0
6620606
class Node: def __init__(self, data, next=None, prev=None): self.data = data self.next = next self.prev = prev def __str__(self): return ('(' + str(self.data) + ')') class DoublyLinkedLint: def __init__(self, r=None): self.root = r self.last = r self.size = 0 def add(self, data): if self.size == 0: self.root = Node(data) self.last = self.root else: new_node = Node(data, self.root) self.root.prev = new_node self.root = new_node self.size += 1 def find(self, data): curr = self.root while curr is not None: if curr.data == data: return data elif curr.next == None: return False else: curr = curr.next def remove(self, data): curr = self.root while curr is not None: if curr.data == data: if curr.prev is not None: if curr.next is not None: curr.prev.next = curr.next curr.next.prev = curr.prev else: curr.next.prev = None self.last = curr.prev else: self.root = curr.next curr.next.prev = self.root self.size += 1 return True else: curr = curr.next return False def print_list(self): if self.root is None: return curr = self.root print(curr, end='->') while curr.next is not None: curr = curr.next print(curr, end='->') print() if __name__ == '__main__': dll = DoublyLinkedLint() for i in [5, 9, 3, 8, 9]: dll.add(i) print('size=', dll.size) dll.print_list() dll.remove(8) dll.print_list()
class Node: def __init__(self, data, next=None, prev=None): self.data = data self.next = next self.prev = prev def __str__(self): return ('(' + str(self.data) + ')') class DoublyLinkedLint: def __init__(self, r=None): self.root = r self.last = r self.size = 0 def add(self, data): if self.size == 0: self.root = Node(data) self.last = self.root else: new_node = Node(data, self.root) self.root.prev = new_node self.root = new_node self.size += 1 def find(self, data): curr = self.root while curr is not None: if curr.data == data: return data elif curr.next == None: return False else: curr = curr.next def remove(self, data): curr = self.root while curr is not None: if curr.data == data: if curr.prev is not None: if curr.next is not None: curr.prev.next = curr.next curr.next.prev = curr.prev else: curr.next.prev = None self.last = curr.prev else: self.root = curr.next curr.next.prev = self.root self.size += 1 return True else: curr = curr.next return False def print_list(self): if self.root is None: return curr = self.root print(curr, end='->') while curr.next is not None: curr = curr.next print(curr, end='->') print() if __name__ == '__main__': dll = DoublyLinkedLint() for i in [5, 9, 3, 8, 9]: dll.add(i) print('size=', dll.size) dll.print_list() dll.remove(8) dll.print_list()
none
1
3.5957
4
src/utils/camerastreamer/camerastreamer.py
KeithAzzopardi1998/BFMC_Startup
0
6620607
<filename>src/utils/camerastreamer/camerastreamer.py # Copyright (c) 2019, Bosch Engineering Center Cluj and BFMC organizers # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. 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. # 3. Neither the name of the copyright holder 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 HOLDER 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 import socket import struct import time import numpy as np from multiprocessing import Process from threading import Thread import cv2 import os from src.utils.templates.workerprocess import WorkerProcess class CameraStreamer(WorkerProcess): # ===================================== INIT ========================================= def __init__(self, inPs, outPs): """Process used for sending images over the network. UDP protocol is used. The image is compressed before it is send. Used for visualizing your raspicam from PC. Parameters ---------- inPs : list(Pipe) List of input pipes, only the first pipe is used to transfer the captured frames. outPs : list(Pipe) List of output pipes (not used at the moment) """ super(CameraStreamer,self).__init__( inPs, outPs) self.serverIp = os.environ['IP_PC'] # PC ip self.port = 2244 # com port # ===================================== RUN ========================================== def run(self): """Apply the initializing methods and start the threads. """ self._init_socket() super(CameraStreamer,self).run() # ===================================== INIT THREADS ================================= def _init_threads(self): """Initialize the sending thread. """ if self._blocker.is_set(): return streamTh = Thread(name='StreamSending',target = self._send_thread, args= (self.inPs[0], )) streamTh.daemon = True self.threads.append(streamTh) # ===================================== INIT SOCKET ================================== def _init_socket(self): """Initialize the socket. """ self.client_socket = socket.socket() self.connection = None # Trying repeatedly to connect the camera receiver. try: while self.connection is None and not self._blocker.is_set(): try: self.client_socket.connect((self.serverIp, self.port)) self.client_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) self.connection = self.client_socket.makefile('wb') except ConnectionRefusedError as error: time.sleep(0.5) pass except KeyboardInterrupt: self._blocker.set() pass # ===================================== SEND THREAD ================================== def _send_thread(self, inP): """Sending the frames received thought the input pipe to remote client by using a socket. Parameters ---------- inP : Pipe Input pipe to read the frames from other process. """ encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 70] print('Start streaming') while True: time.sleep(0.05) try: print("LOG: fetching image") stamps, image = inP.recv() print("LOG: image shape before processing",image.shape) image=process_image(image) print("LOG: image shape after processing",image.shape) result, image = cv2.imencode('.jpg', image, encode_param) data = image.tobytes() size = len(data) print("LOG: packaged image into packet of size %d ... going to transmit"%size) self.connection.write(struct.pack("<L",size)) self.connection.write(data) print("LOG: successfully transmitted frame") except Exception as e: print("CameraStreamer failed to stream images:",e,"\n") # Reinitialize the socket for reconnecting to client. self.connection = None self._init_socket() pass import matplotlib.image as mpimg import numpy as np import cv2 def grayscale(img): """ Applies the Grayscale transform This will return an image with only one color channel but NOTE: to see the returned image as grayscale (assuming your grayscaled image is called 'gray') you should call plt.imshow(gray, cmap='gray') If you read an image with cv2.imread() use BGR2GRAY return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) """ return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) def canny(img, low_threshold, high_threshold): """Applies the Canny transform""" return cv2.Canny(img, low_threshold, high_threshold) def gaussian_blur(img, kernel_size): """Applies a Gaussian Noise kernel""" return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0) def region_of_interest(img, vertices): """ Applies an image mask. Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. `vertices` should be a numpy array of integer points. """ # Defining a blank mask to start with mask = np.zeros_like(img) # Defining a 3 channel or 1 channel color to fill the mask with depending on the input image if len(img.shape) > 2: channel_count = img.shape[2] # i.e. 3 or 4 depending on your image ignore_mask_color = (255,) * channel_count else: ignore_mask_color = 255 # Filling pixels inside the polygon defined by "vertices" with the fill color cv2.fillPoly(mask, vertices, ignore_mask_color) # Returning the image only where mask pixels are nonzero masked_image = cv2.bitwise_and(img, mask) return masked_image def draw_lines(img, lines, color=[255, 0, 0], thickness=2): """ NOTE: this is the function you might want to use as a starting point once you want to average/extrapolate the line segments you detect to map out the full extent of the lane (going from the result shown in raw-lines-example.mp4 to that shown in P1_example.mp4). Think about things like separating line segments by their slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left line vs. the right line. Then, you can average the position of each of the lines and extrapolate to the top and bottom of the lane. This function draws `lines` with `color` and `thickness`. Lines are drawn on the image inplace (mutates the image). If you want to make the lines semi-transparent, think about combining this function with the weighted_img() function below """ for line in lines: for x1,y1,x2,y2 in line: cv2.line(img, (x1, y1), (x2, y2), color, thickness) def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap): """ `img` should be the output of a Canny transform. Returns an image with hough lines drawn. """ lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap) line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8) draw_lines(line_img, lines) return line_img # Python 3 has support for cool math symbols. def weighted_img(img, initial_img, α=0.8, β=1., γ=0.): """ `img` is the output of the hough_lines(), An image with lines drawn on it. Should be a blank image (all black) with lines drawn on it. `initial_img` should be the image before any processing. The result image is computed as follows: initial_img * α + img * β + γ NOTE: initial_img and img must be the same shape! """ return cv2.addWeighted(initial_img, α, img, β, γ) def process_image(img): #read_image = mpimg.imread(img) image = np.copy(img) gray_image = grayscale(image) blur_gray = gaussian_blur(gray_image, kernel_size=5) edges = canny(blur_gray, low_threshold=90, high_threshold=180) imshape = image.shape vertices = np.array([[(0, imshape[0]), (480, 300), (480, 300), (imshape[1], imshape[0])]], dtype=np.int32) masked_edges = region_of_interest(edges, vertices) line_image = hough_lines(masked_edges, rho=1, theta=np.pi/180, threshold=50, min_line_len=25, max_line_gap=200) lines_edges = weighted_img(line_image, image, α=0.8, β=1., γ=0.) return lines_edges
<filename>src/utils/camerastreamer/camerastreamer.py # Copyright (c) 2019, Bosch Engineering Center Cluj and BFMC organizers # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. 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. # 3. Neither the name of the copyright holder 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 HOLDER 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 import socket import struct import time import numpy as np from multiprocessing import Process from threading import Thread import cv2 import os from src.utils.templates.workerprocess import WorkerProcess class CameraStreamer(WorkerProcess): # ===================================== INIT ========================================= def __init__(self, inPs, outPs): """Process used for sending images over the network. UDP protocol is used. The image is compressed before it is send. Used for visualizing your raspicam from PC. Parameters ---------- inPs : list(Pipe) List of input pipes, only the first pipe is used to transfer the captured frames. outPs : list(Pipe) List of output pipes (not used at the moment) """ super(CameraStreamer,self).__init__( inPs, outPs) self.serverIp = os.environ['IP_PC'] # PC ip self.port = 2244 # com port # ===================================== RUN ========================================== def run(self): """Apply the initializing methods and start the threads. """ self._init_socket() super(CameraStreamer,self).run() # ===================================== INIT THREADS ================================= def _init_threads(self): """Initialize the sending thread. """ if self._blocker.is_set(): return streamTh = Thread(name='StreamSending',target = self._send_thread, args= (self.inPs[0], )) streamTh.daemon = True self.threads.append(streamTh) # ===================================== INIT SOCKET ================================== def _init_socket(self): """Initialize the socket. """ self.client_socket = socket.socket() self.connection = None # Trying repeatedly to connect the camera receiver. try: while self.connection is None and not self._blocker.is_set(): try: self.client_socket.connect((self.serverIp, self.port)) self.client_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) self.connection = self.client_socket.makefile('wb') except ConnectionRefusedError as error: time.sleep(0.5) pass except KeyboardInterrupt: self._blocker.set() pass # ===================================== SEND THREAD ================================== def _send_thread(self, inP): """Sending the frames received thought the input pipe to remote client by using a socket. Parameters ---------- inP : Pipe Input pipe to read the frames from other process. """ encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 70] print('Start streaming') while True: time.sleep(0.05) try: print("LOG: fetching image") stamps, image = inP.recv() print("LOG: image shape before processing",image.shape) image=process_image(image) print("LOG: image shape after processing",image.shape) result, image = cv2.imencode('.jpg', image, encode_param) data = image.tobytes() size = len(data) print("LOG: packaged image into packet of size %d ... going to transmit"%size) self.connection.write(struct.pack("<L",size)) self.connection.write(data) print("LOG: successfully transmitted frame") except Exception as e: print("CameraStreamer failed to stream images:",e,"\n") # Reinitialize the socket for reconnecting to client. self.connection = None self._init_socket() pass import matplotlib.image as mpimg import numpy as np import cv2 def grayscale(img): """ Applies the Grayscale transform This will return an image with only one color channel but NOTE: to see the returned image as grayscale (assuming your grayscaled image is called 'gray') you should call plt.imshow(gray, cmap='gray') If you read an image with cv2.imread() use BGR2GRAY return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) """ return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) def canny(img, low_threshold, high_threshold): """Applies the Canny transform""" return cv2.Canny(img, low_threshold, high_threshold) def gaussian_blur(img, kernel_size): """Applies a Gaussian Noise kernel""" return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0) def region_of_interest(img, vertices): """ Applies an image mask. Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. `vertices` should be a numpy array of integer points. """ # Defining a blank mask to start with mask = np.zeros_like(img) # Defining a 3 channel or 1 channel color to fill the mask with depending on the input image if len(img.shape) > 2: channel_count = img.shape[2] # i.e. 3 or 4 depending on your image ignore_mask_color = (255,) * channel_count else: ignore_mask_color = 255 # Filling pixels inside the polygon defined by "vertices" with the fill color cv2.fillPoly(mask, vertices, ignore_mask_color) # Returning the image only where mask pixels are nonzero masked_image = cv2.bitwise_and(img, mask) return masked_image def draw_lines(img, lines, color=[255, 0, 0], thickness=2): """ NOTE: this is the function you might want to use as a starting point once you want to average/extrapolate the line segments you detect to map out the full extent of the lane (going from the result shown in raw-lines-example.mp4 to that shown in P1_example.mp4). Think about things like separating line segments by their slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left line vs. the right line. Then, you can average the position of each of the lines and extrapolate to the top and bottom of the lane. This function draws `lines` with `color` and `thickness`. Lines are drawn on the image inplace (mutates the image). If you want to make the lines semi-transparent, think about combining this function with the weighted_img() function below """ for line in lines: for x1,y1,x2,y2 in line: cv2.line(img, (x1, y1), (x2, y2), color, thickness) def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap): """ `img` should be the output of a Canny transform. Returns an image with hough lines drawn. """ lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap) line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8) draw_lines(line_img, lines) return line_img # Python 3 has support for cool math symbols. def weighted_img(img, initial_img, α=0.8, β=1., γ=0.): """ `img` is the output of the hough_lines(), An image with lines drawn on it. Should be a blank image (all black) with lines drawn on it. `initial_img` should be the image before any processing. The result image is computed as follows: initial_img * α + img * β + γ NOTE: initial_img and img must be the same shape! """ return cv2.addWeighted(initial_img, α, img, β, γ) def process_image(img): #read_image = mpimg.imread(img) image = np.copy(img) gray_image = grayscale(image) blur_gray = gaussian_blur(gray_image, kernel_size=5) edges = canny(blur_gray, low_threshold=90, high_threshold=180) imshape = image.shape vertices = np.array([[(0, imshape[0]), (480, 300), (480, 300), (imshape[1], imshape[0])]], dtype=np.int32) masked_edges = region_of_interest(edges, vertices) line_image = hough_lines(masked_edges, rho=1, theta=np.pi/180, threshold=50, min_line_len=25, max_line_gap=200) lines_edges = weighted_img(line_image, image, α=0.8, β=1., γ=0.) return lines_edges
en
0.802447
# Copyright (c) 2019, Bosch Engineering Center Cluj and BFMC organizers # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. 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. # 3. Neither the name of the copyright holder 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 HOLDER 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 # ===================================== INIT ========================================= Process used for sending images over the network. UDP protocol is used. The image is compressed before it is send. Used for visualizing your raspicam from PC. Parameters ---------- inPs : list(Pipe) List of input pipes, only the first pipe is used to transfer the captured frames. outPs : list(Pipe) List of output pipes (not used at the moment) # PC ip # com port # ===================================== RUN ========================================== Apply the initializing methods and start the threads. # ===================================== INIT THREADS ================================= Initialize the sending thread. # ===================================== INIT SOCKET ================================== Initialize the socket. # Trying repeatedly to connect the camera receiver. # ===================================== SEND THREAD ================================== Sending the frames received thought the input pipe to remote client by using a socket. Parameters ---------- inP : Pipe Input pipe to read the frames from other process. # Reinitialize the socket for reconnecting to client. Applies the Grayscale transform This will return an image with only one color channel but NOTE: to see the returned image as grayscale (assuming your grayscaled image is called 'gray') you should call plt.imshow(gray, cmap='gray') If you read an image with cv2.imread() use BGR2GRAY return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) Applies the Canny transform Applies a Gaussian Noise kernel Applies an image mask. Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. `vertices` should be a numpy array of integer points. # Defining a blank mask to start with # Defining a 3 channel or 1 channel color to fill the mask with depending on the input image # i.e. 3 or 4 depending on your image # Filling pixels inside the polygon defined by "vertices" with the fill color # Returning the image only where mask pixels are nonzero NOTE: this is the function you might want to use as a starting point once you want to average/extrapolate the line segments you detect to map out the full extent of the lane (going from the result shown in raw-lines-example.mp4 to that shown in P1_example.mp4). Think about things like separating line segments by their slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left line vs. the right line. Then, you can average the position of each of the lines and extrapolate to the top and bottom of the lane. This function draws `lines` with `color` and `thickness`. Lines are drawn on the image inplace (mutates the image). If you want to make the lines semi-transparent, think about combining this function with the weighted_img() function below `img` should be the output of a Canny transform. Returns an image with hough lines drawn. # Python 3 has support for cool math symbols. `img` is the output of the hough_lines(), An image with lines drawn on it. Should be a blank image (all black) with lines drawn on it. `initial_img` should be the image before any processing. The result image is computed as follows: initial_img * α + img * β + γ NOTE: initial_img and img must be the same shape! #read_image = mpimg.imread(img)
1.60349
2
development-resources/investigations/audio_format.py
CameronJRAllan/eTree-Browser
1
6620608
<filename>development-resources/investigations/audio_format.py import sys from SPARQLWrapper import SPARQLWrapper, JSON, POSTDIRECTLY import cache import statistics as s class AudioFormat(): def __init__(self): self.sparql = SPARQLWrapper("http://etree.linkedmusic.org/sparql") self.sparql.setReturnFormat(JSON) self.sparql.setMethod("POST") performances = cache.load('list_all_performances') # performances = self.get_all_performances() # cache.save(performances, 'list_all_performances') print('Got perm') self.examine_tracklists(performances) def examine_tracklists(self, performances): count = {'mp3': 0, 'flac24': 0, 'flac16': 0, 'mp3_vbr': 0, 'shn' : 0, 'ogg': 0, 'wav' : 0} numSingleFormat = 0 countUnique = {'mp3': 0, 'flac24': 0, 'flac16': 0, 'mp3_vbr': 0, 'shn' : 0, 'ogg': 0, 'wav' : 0} numFormatsFound = [] for single in performances['results']['bindings']: # [:40] tracklist = self.get_tracklist(single['label']['value']) print(single['label']['value']) formatsFound = [] for item in tracklist['results']['bindings']: extension = item['audio']['value'][item['audio']['value'].rfind('.') + 1:] if 'mp3' not in extension and 'flac' not in extension: formatsFound.append(extension) else: if 'mp3' in extension: formatsFound.append(self.subtype_mp3(item['audio']['value'])) if 'flac' in extension: formatsFound.append(self.subtype_flac(item['audio']['value'])) if len(list(set(formatsFound))) == 1: numSingleFormat += 1 countUnique[formatsFound[0]] += 1 numFormatsFound.append(len(list(set(formatsFound)))) for format in list(set(formatsFound)): count[format] += 1 for k in count.keys(): print(str(k) + ': ' + str(count[k])) print('\n\nUnique count: ' + str(numSingleFormat)) for k in countUnique.keys(): print(str(k) + ': ' + str(countUnique[k])) print(s.mean(numFormatsFound)) def subtype_mp3(self, url): final_7 = url[url.rfind('.') - 3:] if 'vbr' in final_7.lower(): return 'mp3_vbr' if '64kb' in final_7.lower(): return 'mp3_64kb' else: return 'mp3' def subtype_flac(self, url): filename = url[url.rfind('/') + 1:] if 'flac24' in url.lower(): return 'flac24' else: return 'flac16' def get_all_performances(self): self.sparql.setQuery(""" PREFIX etree:<http://etree.linkedmusic.org/vocab/> PREFIX mo:<http://purl.org/ontology/mo/> PREFIX event:<http://purl.org/NET/c4dm/event.owl#> PREFIX skos:<http://www.w3.org/2004/02/skos/core#> PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT DISTINCT ?performer ?name ?label ?place WHERE { ?art skos:prefLabel ?label. ?art event:place ?location. ?location etree:location ?place. ?performer foaf:name ?name. ?art mo:performer ?performer. } GROUP BY (?name) LIMIT 2 """) return self.sparql.query().convert() def get_tracklist(self, label): self.sparql.setQuery(""" PREFIX etree:<http://etree.linkedmusic.org/vocab/> PREFIX mo:<http://purl.org/ontology/mo/> PREFIX event:<http://purl.org/NET/c4dm/event.owl#> PREFIX skos:<http://www.w3.org/2004/02/skos/core#> PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT DISTINCT ?audio ?label ?num {{ ?perf event:hasSubEvent ?tracklist. ?tracklist skos:prefLabel ?label. ?tracklist etree:number ?num. ?tracklist etree:audio ?audio. ?perf rdf:type mo:Performance. ?perf skos:prefLabel "{0}". }} GROUP BY ?label ?audio ?num ORDER BY ?num """.format(label)) return self.sparql.query().convert() if __name__ == '__main__': instance = AudioFormat()
<filename>development-resources/investigations/audio_format.py import sys from SPARQLWrapper import SPARQLWrapper, JSON, POSTDIRECTLY import cache import statistics as s class AudioFormat(): def __init__(self): self.sparql = SPARQLWrapper("http://etree.linkedmusic.org/sparql") self.sparql.setReturnFormat(JSON) self.sparql.setMethod("POST") performances = cache.load('list_all_performances') # performances = self.get_all_performances() # cache.save(performances, 'list_all_performances') print('Got perm') self.examine_tracklists(performances) def examine_tracklists(self, performances): count = {'mp3': 0, 'flac24': 0, 'flac16': 0, 'mp3_vbr': 0, 'shn' : 0, 'ogg': 0, 'wav' : 0} numSingleFormat = 0 countUnique = {'mp3': 0, 'flac24': 0, 'flac16': 0, 'mp3_vbr': 0, 'shn' : 0, 'ogg': 0, 'wav' : 0} numFormatsFound = [] for single in performances['results']['bindings']: # [:40] tracklist = self.get_tracklist(single['label']['value']) print(single['label']['value']) formatsFound = [] for item in tracklist['results']['bindings']: extension = item['audio']['value'][item['audio']['value'].rfind('.') + 1:] if 'mp3' not in extension and 'flac' not in extension: formatsFound.append(extension) else: if 'mp3' in extension: formatsFound.append(self.subtype_mp3(item['audio']['value'])) if 'flac' in extension: formatsFound.append(self.subtype_flac(item['audio']['value'])) if len(list(set(formatsFound))) == 1: numSingleFormat += 1 countUnique[formatsFound[0]] += 1 numFormatsFound.append(len(list(set(formatsFound)))) for format in list(set(formatsFound)): count[format] += 1 for k in count.keys(): print(str(k) + ': ' + str(count[k])) print('\n\nUnique count: ' + str(numSingleFormat)) for k in countUnique.keys(): print(str(k) + ': ' + str(countUnique[k])) print(s.mean(numFormatsFound)) def subtype_mp3(self, url): final_7 = url[url.rfind('.') - 3:] if 'vbr' in final_7.lower(): return 'mp3_vbr' if '64kb' in final_7.lower(): return 'mp3_64kb' else: return 'mp3' def subtype_flac(self, url): filename = url[url.rfind('/') + 1:] if 'flac24' in url.lower(): return 'flac24' else: return 'flac16' def get_all_performances(self): self.sparql.setQuery(""" PREFIX etree:<http://etree.linkedmusic.org/vocab/> PREFIX mo:<http://purl.org/ontology/mo/> PREFIX event:<http://purl.org/NET/c4dm/event.owl#> PREFIX skos:<http://www.w3.org/2004/02/skos/core#> PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT DISTINCT ?performer ?name ?label ?place WHERE { ?art skos:prefLabel ?label. ?art event:place ?location. ?location etree:location ?place. ?performer foaf:name ?name. ?art mo:performer ?performer. } GROUP BY (?name) LIMIT 2 """) return self.sparql.query().convert() def get_tracklist(self, label): self.sparql.setQuery(""" PREFIX etree:<http://etree.linkedmusic.org/vocab/> PREFIX mo:<http://purl.org/ontology/mo/> PREFIX event:<http://purl.org/NET/c4dm/event.owl#> PREFIX skos:<http://www.w3.org/2004/02/skos/core#> PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT DISTINCT ?audio ?label ?num {{ ?perf event:hasSubEvent ?tracklist. ?tracklist skos:prefLabel ?label. ?tracklist etree:number ?num. ?tracklist etree:audio ?audio. ?perf rdf:type mo:Performance. ?perf skos:prefLabel "{0}". }} GROUP BY ?label ?audio ?num ORDER BY ?num """.format(label)) return self.sparql.query().convert() if __name__ == '__main__': instance = AudioFormat()
en
0.267127
# performances = self.get_all_performances() # cache.save(performances, 'list_all_performances') # [:40] PREFIX etree:<http://etree.linkedmusic.org/vocab/> PREFIX mo:<http://purl.org/ontology/mo/> PREFIX event:<http://purl.org/NET/c4dm/event.owl#> PREFIX skos:<http://www.w3.org/2004/02/skos/core#> PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT DISTINCT ?performer ?name ?label ?place WHERE { ?art skos:prefLabel ?label. ?art event:place ?location. ?location etree:location ?place. ?performer foaf:name ?name. ?art mo:performer ?performer. } GROUP BY (?name) LIMIT 2 PREFIX etree:<http://etree.linkedmusic.org/vocab/> PREFIX mo:<http://purl.org/ontology/mo/> PREFIX event:<http://purl.org/NET/c4dm/event.owl#> PREFIX skos:<http://www.w3.org/2004/02/skos/core#> PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT DISTINCT ?audio ?label ?num {{ ?perf event:hasSubEvent ?tracklist. ?tracklist skos:prefLabel ?label. ?tracklist etree:number ?num. ?tracklist etree:audio ?audio. ?perf rdf:type mo:Performance. ?perf skos:prefLabel "{0}". }} GROUP BY ?label ?audio ?num ORDER BY ?num
2.405538
2
fingo/scaling.py
aquatix/fingo
0
6620609
# encoding: utf-8 from __future__ import absolute_import import logging import os from PIL import Image as PILImage, ImageFile as PILImageFile, ExifTags from datetime import datetime import exifread import imagehash import json import pytz import requests try: DEBUG = settings.DEBUG except NameError: DEBUG = True #DEBUG = False logger = logging.getLogger('fingo') logger.setLevel(logging.DEBUG) lh = logging.StreamHandler() if DEBUG: lh.setLevel(logging.DEBUG) else: lh.setLevel(logging.ERROR) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') lh.setFormatter(formatter) logger.addHandler(lh) def scale_image(image_id, destination_dir, width, height, crop=False): """ Create scaled versions of the Image with image_id """ image = Image.objects.get(pk=image_id) if not image.image_hash: logger.info('No hash found for Image with pk %d', image.pk) return filename_base = os.path.join(destination_dir, image.image_hash[:2], image.image_hash) util.ensure_dir_exists(filename_base) variant = '_{}-{}.{}'.format(width, height, image.file_ext) if os.path.isfile(filename_base + variant): #logger.debug('Skipping resize for existing %s%s', filename_base, variant) return logger.info('resizing into %s', filename_base + variant) # TODO: be more clever with the config if width == 0: raise Exception('width can not be zero') if height == 0: raise Exception('height can not be zero') try: im = PILImage.open(image.get_filepath()) im.thumbnail((width, height)) if image.file_ext == 'jpg' or image.file_ext == 'jpeg': if width >= settings.EXIF_COPY_THRESHOLD or height >= settings.EXIF_COPY_THRESHOLD: # If variant is larger than the set threshold, copy EXIF tags # Smaller variants effectively get EXIF stripped so resulting files are smaller # (good for thumbnails) try: exif = im.info['exif'] im.save(filename_base + variant, 'JPEG', exif=exif) except KeyError: # No EXIF found, save normally im.save(filename_base + variant, 'JPEG') else: im.save(filename_base + variant, 'JPEG') elif image.file_ext == 'png': im.save(filename_base + variant, 'PNG') except IOError: logger.info('Cannot create %dx%d variant for %s', width, height, image) def update_scaled_images(collection): """ Iterate through the images in the Collection and generate resized versions of images that don't have those yet """ images = collection.images() variants = PhotoSize.objects.all() if len(variants) == 0: logger.info('No size variants defined, configure some PhotoSizes') return for image in images: for variant in variants: scale_image(image.pk, collection.archive_dir, variant.width, variant.height, variant.crop_to_fit)
# encoding: utf-8 from __future__ import absolute_import import logging import os from PIL import Image as PILImage, ImageFile as PILImageFile, ExifTags from datetime import datetime import exifread import imagehash import json import pytz import requests try: DEBUG = settings.DEBUG except NameError: DEBUG = True #DEBUG = False logger = logging.getLogger('fingo') logger.setLevel(logging.DEBUG) lh = logging.StreamHandler() if DEBUG: lh.setLevel(logging.DEBUG) else: lh.setLevel(logging.ERROR) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') lh.setFormatter(formatter) logger.addHandler(lh) def scale_image(image_id, destination_dir, width, height, crop=False): """ Create scaled versions of the Image with image_id """ image = Image.objects.get(pk=image_id) if not image.image_hash: logger.info('No hash found for Image with pk %d', image.pk) return filename_base = os.path.join(destination_dir, image.image_hash[:2], image.image_hash) util.ensure_dir_exists(filename_base) variant = '_{}-{}.{}'.format(width, height, image.file_ext) if os.path.isfile(filename_base + variant): #logger.debug('Skipping resize for existing %s%s', filename_base, variant) return logger.info('resizing into %s', filename_base + variant) # TODO: be more clever with the config if width == 0: raise Exception('width can not be zero') if height == 0: raise Exception('height can not be zero') try: im = PILImage.open(image.get_filepath()) im.thumbnail((width, height)) if image.file_ext == 'jpg' or image.file_ext == 'jpeg': if width >= settings.EXIF_COPY_THRESHOLD or height >= settings.EXIF_COPY_THRESHOLD: # If variant is larger than the set threshold, copy EXIF tags # Smaller variants effectively get EXIF stripped so resulting files are smaller # (good for thumbnails) try: exif = im.info['exif'] im.save(filename_base + variant, 'JPEG', exif=exif) except KeyError: # No EXIF found, save normally im.save(filename_base + variant, 'JPEG') else: im.save(filename_base + variant, 'JPEG') elif image.file_ext == 'png': im.save(filename_base + variant, 'PNG') except IOError: logger.info('Cannot create %dx%d variant for %s', width, height, image) def update_scaled_images(collection): """ Iterate through the images in the Collection and generate resized versions of images that don't have those yet """ images = collection.images() variants = PhotoSize.objects.all() if len(variants) == 0: logger.info('No size variants defined, configure some PhotoSizes') return for image in images: for variant in variants: scale_image(image.pk, collection.archive_dir, variant.width, variant.height, variant.crop_to_fit)
en
0.800171
# encoding: utf-8 #DEBUG = False Create scaled versions of the Image with image_id #logger.debug('Skipping resize for existing %s%s', filename_base, variant) # TODO: be more clever with the config # If variant is larger than the set threshold, copy EXIF tags # Smaller variants effectively get EXIF stripped so resulting files are smaller # (good for thumbnails) # No EXIF found, save normally Iterate through the images in the Collection and generate resized versions of images that don't have those yet
2.536353
3
python2.7/tests.py
PereBal/Komparator
0
6620610
<reponame>PereBal/Komparator<filename>python2.7/tests.py<gh_stars>0 # TODO # model: (int, 1) -> funciona com toca. Les tuples son especials x) # faltaria afegir un parseig del model import unittest from dictcompy import (DictComPy, Opt, Eq, Excl, In, Like, Date, Or_None, Or_Empty) MODELS = { 'int': [{'a': int}], 'float': [{'a': float}], 'complex': [{'a': complex}], 'bool': [{'a': bool}], 'str': [{'a': str}], 'list': [{'a': list}, {'a': []}, {'a': (list, [])}, {'a': [int]}, {'a': [int, str, bool]}], 'tuple': [{'a': tuple}, {'a': (tuple, (int,))}, {'a': (tuple, (int,str,bool))}], 'dict': [], } class TestDictComPy(unittest.TestCase): def test_plain_int(self): dcp = DictComPy(model=MODELS['int'][0]) self.assertFalse(dcp.match(expr={'b': 1})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertFalse(dcp.match(expr={'a': True})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 'as'})) self.assertTrue(dcp.match(expr={'a': 1})) self.assertTrue(dcp.match(expr={'a': 0})) def test_plain_float(self): dcp = DictComPy(model=MODELS['float'][0]) self.assertFalse(dcp.match(expr={'b': 1.0})) self.assertFalse(dcp.match(expr={'a': 0})) self.assertFalse(dcp.match(expr={'a': True})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 'as'})) self.assertTrue(dcp.match(expr={'a': 1.0})) def test_plain_complex(self): dcp = DictComPy(model=MODELS['complex'][0]) c = complex(1, 2) self.assertFalse(dcp.match(expr={'b': c})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertFalse(dcp.match(expr={'a': True})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 'as'})) self.assertTrue(dcp.match(expr={'a': c})) def test_plain_bool(self): dcp = DictComPy(model=MODELS['bool'][0]) self.assertFalse(dcp.match(expr={'b': True})) self.assertFalse(dcp.match(expr={'a': 0})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 'as'})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertTrue(dcp.match(expr={'a': True})) self.assertTrue(dcp.match(expr={'a': False})) def test_plain_string(self): dcp = DictComPy(model=MODELS['str'][0]) self.assertFalse(dcp.match(expr={'b': u'a'})) self.assertFalse(dcp.match(expr={'a': 23})) self.assertFalse(dcp.match(expr={'a': True})) self.assertTrue(dcp.match(expr={'a': 'a'})) self.assertTrue(dcp.match(expr={'a': u'a'})) self.assertTrue(dcp.match(expr={'a': u''})) self.assertTrue(dcp.match(expr={'a': ''})) def test_plain_list(self): dcp = DictComPy(model=MODELS['list'][0]) self.assertFalse(dcp.match(expr={'b': []})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertTrue(dcp.match(expr={'a': []})) self.assertTrue(dcp.match(expr={'a': [1]})) self.assertTrue(dcp.match(expr={'a': [1, '1021', True]})) dcp = DictComPy(model=MODELS['list'][1]) self.assertFalse(dcp.match(expr={'b': []})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertFalse(dcp.match(expr={'a': [1]})) self.assertFalse(dcp.match(expr={'a': [1, '1021', True]})) self.assertTrue(dcp.match(expr={'a': []})) dcp = DictComPy(model=MODELS['list'][2]) self.assertFalse(dcp.match(expr={'b': []})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertFalse(dcp.match(expr={'a': [1]})) self.assertFalse(dcp.match(expr={'a': [1, '1021', True]})) self.assertTrue(dcp.match(expr={'a': []})) dcp = DictComPy(model=MODELS['list'][3]) self.assertFalse(dcp.match(expr={'b': [1]})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertFalse(dcp.match(expr={'a': []})) self.assertFalse(dcp.match(expr={'a': [1, '1021', True]})) self.assertTrue(dcp.match(expr={'a': [1]})) self.assertTrue(dcp.match(expr={'a': [1, 2, 3]})) dcp = DictComPy(model=MODELS['list'][4]) self.assertFalse(dcp.match(expr={'b': []})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertFalse(dcp.match(expr={'a': []})) self.assertFalse(dcp.match(expr={'a': [1]})) self.assertFalse(dcp.match(expr={'a': [1, '1021', True, 1.0]})) self.assertTrue(dcp.match(expr={'a': [1, '1021', True]})) def test_plain_tuple(self): dcp = DictComPy(model=MODELS['tuple'][0]) self.assertFalse(dcp.match(expr={'b': ()})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertTrue(dcp.match(expr={'a': ()})) self.assertTrue(dcp.match(expr={'a': (1,)})) # 1, <-- common mistake self.assertTrue(dcp.match(expr={'a': (1, '1021', True)})) dcp = DictComPy(model=MODELS['tuple'][1]) # ',' <-- self.assertFalse(dcp.match(expr={'b': (1,)})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertFalse(dcp.match(expr={'a': ()})) self.assertFalse(dcp.match(expr={'a': (1, '1021', True)})) self.assertFalse(dcp.match(expr={'a': ('',)})) self.assertTrue(dcp.match(expr={'a': (1,)})) self.assertTrue(dcp.match(expr={'a': (1, 2, 3)})) dcp = DictComPy(model=MODELS['tuple'][2]) # ',' <-- self.assertFalse(dcp.match(expr={'b': (1,)})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertFalse(dcp.match(expr={'a': ()})) self.assertFalse(dcp.match(expr={'a': (1,)})) self.assertFalse(dcp.match(expr={'a': (1, 2, 3)})) self.assertFalse(dcp.match(expr={'a': (1, '1021', True, 1.0)})) self.assertTrue(dcp.match(expr={'a': (1, '1021', True)})) def test_nested_int(self): dcp = DictComPy({'a': {'b': int}}) self.assertFalse(dcp.match(expr={'b': {'b': 1}})) self.assertFalse(dcp.match(expr={'a': {'a': 1}})) self.assertFalse(dcp.match(expr={'a': {'b': ''}})) self.assertTrue(dcp.match(expr={'a': {'b': 1}})) def test_In(self): dcp = DictComPy({'a': (In, range(0,5,2))}) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 10})) self.assertTrue(dcp.match(expr={'a': 2})) def test_Like(self): dcp = DictComPy({'a': (Like, '\d,\w+')}) self.assertFalse(dcp.match(expr={'a': '1,'})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': '10'})) self.assertTrue(dcp.match(expr={'a': '1,0102dsada_dede'})) def test_Date(self): dcp = DictComPy({'a': (Date, '%Y-%d-%m')}) self.assertFalse(dcp.match(expr={'a': '2015-02-31'})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': '2015-32-01'})) self.assertTrue(dcp.match(expr={'a': '2015-30-01'})) def test_Excl(self): dcp = DictComPy({'a': (Excl, ('1', '2'), {'1': int, '2': str})}) self.assertFalse(dcp.match(expr={'a': {'1': 's'}})) self.assertFalse(dcp.match(expr={'a': {'2': 1}})) self.assertFalse(dcp.match(expr={'a': {'1': 1, '2': 's'}})) self.assertTrue(dcp.match(expr={'a': {'1': 1}})) self.assertTrue(dcp.match(expr={'a': {'2': 's'}})) def test_Opt(self): dcp = DictComPy({'a': (Opt, int)}) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 's'})) self.assertFalse(dcp.match(expr={'a': True})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertTrue(dcp.match(expr={'a': 1})) self.assertTrue(dcp.match(expr={'b': 1})) def test_Eq(self): dcp = DictComPy({'a': (Eq, 3)}) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': 4})) self.assertTrue(dcp.match(expr={'a': 3})) dcp = DictComPy({'a': (Eq, dict)}) self.assertFalse(dcp.match(expr={'a': {}})) self.assertFalse(dcp.match(expr={'a': list})) self.assertTrue(dcp.match(expr={'a': dict})) def test_Or_None(self): dcp = DictComPy({'a': (Or_None, int)}) self.assertFalse(dcp.match(expr={'b': 1})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': False})) self.assertTrue(dcp.match(expr={'a': None})) self.assertTrue(dcp.match(expr={'a': 1})) dcp = DictComPy({'a': (Or_None, (tuple, int))}) self.assertFalse(dcp.match(expr={'b': 1})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': False})) self.assertFalse(dcp.match(expr={'a': []})) self.assertFalse(dcp.match(expr={'a': None})) self.assertFalse(dcp.match(expr={'a': ('df',)})) self.assertTrue(dcp.match(expr={'a': ()})) self.assertTrue(dcp.match(expr={'a': (1,)})) def test_Or_Empty(self): dcp = DictComPy({'a': (Or_Empty, {'b': int})}) self.assertFalse(dcp.match(expr={'b': 1})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': False})) self.assertFalse(dcp.match(expr={'a': []})) self.assertFalse(dcp.match(expr={'a': None})) self.assertFalse(dcp.match(expr={'a': ('df',)})) self.assertTrue(dcp.match(expr={'a': {}})) self.assertTrue(dcp.match(expr={'a': {'b': 1}})) dcp = DictComPy({'a': (Or_Empty, [int])}) self.assertFalse(dcp.match(expr={'b': 1})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': False})) self.assertFalse(dcp.match(expr={'a': None})) self.assertFalse(dcp.match(expr={'a': ['df']})) self.assertTrue(dcp.match(expr={'a': []})) self.assertTrue(dcp.match(expr={'a': [1]})) """ Failing dcp = DictComPy({'a': (Or_Empty, (tuple, int))}) self.assertFalse(dcp.match(expr={'b': 1})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': False})) self.assertFalse(dcp.match(expr={'a': []})) self.assertFalse(dcp.match(expr={'a': None})) self.assertFalse(dcp.match(expr={'a': ('df',)})) self.assertTrue(dcp.match(expr={'a': ()})) self.assertTrue(dcp.match(expr={'a': (1,)})) """ if __name__ == '__main__': unittest.main()
# TODO # model: (int, 1) -> funciona com toca. Les tuples son especials x) # faltaria afegir un parseig del model import unittest from dictcompy import (DictComPy, Opt, Eq, Excl, In, Like, Date, Or_None, Or_Empty) MODELS = { 'int': [{'a': int}], 'float': [{'a': float}], 'complex': [{'a': complex}], 'bool': [{'a': bool}], 'str': [{'a': str}], 'list': [{'a': list}, {'a': []}, {'a': (list, [])}, {'a': [int]}, {'a': [int, str, bool]}], 'tuple': [{'a': tuple}, {'a': (tuple, (int,))}, {'a': (tuple, (int,str,bool))}], 'dict': [], } class TestDictComPy(unittest.TestCase): def test_plain_int(self): dcp = DictComPy(model=MODELS['int'][0]) self.assertFalse(dcp.match(expr={'b': 1})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertFalse(dcp.match(expr={'a': True})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 'as'})) self.assertTrue(dcp.match(expr={'a': 1})) self.assertTrue(dcp.match(expr={'a': 0})) def test_plain_float(self): dcp = DictComPy(model=MODELS['float'][0]) self.assertFalse(dcp.match(expr={'b': 1.0})) self.assertFalse(dcp.match(expr={'a': 0})) self.assertFalse(dcp.match(expr={'a': True})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 'as'})) self.assertTrue(dcp.match(expr={'a': 1.0})) def test_plain_complex(self): dcp = DictComPy(model=MODELS['complex'][0]) c = complex(1, 2) self.assertFalse(dcp.match(expr={'b': c})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertFalse(dcp.match(expr={'a': True})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 'as'})) self.assertTrue(dcp.match(expr={'a': c})) def test_plain_bool(self): dcp = DictComPy(model=MODELS['bool'][0]) self.assertFalse(dcp.match(expr={'b': True})) self.assertFalse(dcp.match(expr={'a': 0})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 'as'})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertTrue(dcp.match(expr={'a': True})) self.assertTrue(dcp.match(expr={'a': False})) def test_plain_string(self): dcp = DictComPy(model=MODELS['str'][0]) self.assertFalse(dcp.match(expr={'b': u'a'})) self.assertFalse(dcp.match(expr={'a': 23})) self.assertFalse(dcp.match(expr={'a': True})) self.assertTrue(dcp.match(expr={'a': 'a'})) self.assertTrue(dcp.match(expr={'a': u'a'})) self.assertTrue(dcp.match(expr={'a': u''})) self.assertTrue(dcp.match(expr={'a': ''})) def test_plain_list(self): dcp = DictComPy(model=MODELS['list'][0]) self.assertFalse(dcp.match(expr={'b': []})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertTrue(dcp.match(expr={'a': []})) self.assertTrue(dcp.match(expr={'a': [1]})) self.assertTrue(dcp.match(expr={'a': [1, '1021', True]})) dcp = DictComPy(model=MODELS['list'][1]) self.assertFalse(dcp.match(expr={'b': []})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertFalse(dcp.match(expr={'a': [1]})) self.assertFalse(dcp.match(expr={'a': [1, '1021', True]})) self.assertTrue(dcp.match(expr={'a': []})) dcp = DictComPy(model=MODELS['list'][2]) self.assertFalse(dcp.match(expr={'b': []})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertFalse(dcp.match(expr={'a': [1]})) self.assertFalse(dcp.match(expr={'a': [1, '1021', True]})) self.assertTrue(dcp.match(expr={'a': []})) dcp = DictComPy(model=MODELS['list'][3]) self.assertFalse(dcp.match(expr={'b': [1]})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertFalse(dcp.match(expr={'a': []})) self.assertFalse(dcp.match(expr={'a': [1, '1021', True]})) self.assertTrue(dcp.match(expr={'a': [1]})) self.assertTrue(dcp.match(expr={'a': [1, 2, 3]})) dcp = DictComPy(model=MODELS['list'][4]) self.assertFalse(dcp.match(expr={'b': []})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertFalse(dcp.match(expr={'a': []})) self.assertFalse(dcp.match(expr={'a': [1]})) self.assertFalse(dcp.match(expr={'a': [1, '1021', True, 1.0]})) self.assertTrue(dcp.match(expr={'a': [1, '1021', True]})) def test_plain_tuple(self): dcp = DictComPy(model=MODELS['tuple'][0]) self.assertFalse(dcp.match(expr={'b': ()})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertTrue(dcp.match(expr={'a': ()})) self.assertTrue(dcp.match(expr={'a': (1,)})) # 1, <-- common mistake self.assertTrue(dcp.match(expr={'a': (1, '1021', True)})) dcp = DictComPy(model=MODELS['tuple'][1]) # ',' <-- self.assertFalse(dcp.match(expr={'b': (1,)})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertFalse(dcp.match(expr={'a': ()})) self.assertFalse(dcp.match(expr={'a': (1, '1021', True)})) self.assertFalse(dcp.match(expr={'a': ('',)})) self.assertTrue(dcp.match(expr={'a': (1,)})) self.assertTrue(dcp.match(expr={'a': (1, 2, 3)})) dcp = DictComPy(model=MODELS['tuple'][2]) # ',' <-- self.assertFalse(dcp.match(expr={'b': (1,)})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': {}})) self.assertFalse(dcp.match(expr={'a': ()})) self.assertFalse(dcp.match(expr={'a': (1,)})) self.assertFalse(dcp.match(expr={'a': (1, 2, 3)})) self.assertFalse(dcp.match(expr={'a': (1, '1021', True, 1.0)})) self.assertTrue(dcp.match(expr={'a': (1, '1021', True)})) def test_nested_int(self): dcp = DictComPy({'a': {'b': int}}) self.assertFalse(dcp.match(expr={'b': {'b': 1}})) self.assertFalse(dcp.match(expr={'a': {'a': 1}})) self.assertFalse(dcp.match(expr={'a': {'b': ''}})) self.assertTrue(dcp.match(expr={'a': {'b': 1}})) def test_In(self): dcp = DictComPy({'a': (In, range(0,5,2))}) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 10})) self.assertTrue(dcp.match(expr={'a': 2})) def test_Like(self): dcp = DictComPy({'a': (Like, '\d,\w+')}) self.assertFalse(dcp.match(expr={'a': '1,'})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': '10'})) self.assertTrue(dcp.match(expr={'a': '1,0102dsada_dede'})) def test_Date(self): dcp = DictComPy({'a': (Date, '%Y-%d-%m')}) self.assertFalse(dcp.match(expr={'a': '2015-02-31'})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': '2015-32-01'})) self.assertTrue(dcp.match(expr={'a': '2015-30-01'})) def test_Excl(self): dcp = DictComPy({'a': (Excl, ('1', '2'), {'1': int, '2': str})}) self.assertFalse(dcp.match(expr={'a': {'1': 's'}})) self.assertFalse(dcp.match(expr={'a': {'2': 1}})) self.assertFalse(dcp.match(expr={'a': {'1': 1, '2': 's'}})) self.assertTrue(dcp.match(expr={'a': {'1': 1}})) self.assertTrue(dcp.match(expr={'a': {'2': 's'}})) def test_Opt(self): dcp = DictComPy({'a': (Opt, int)}) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': 's'})) self.assertFalse(dcp.match(expr={'a': True})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertTrue(dcp.match(expr={'a': 1})) self.assertTrue(dcp.match(expr={'b': 1})) def test_Eq(self): dcp = DictComPy({'a': (Eq, 3)}) self.assertFalse(dcp.match(expr={'a': 1})) self.assertFalse(dcp.match(expr={'a': 4})) self.assertTrue(dcp.match(expr={'a': 3})) dcp = DictComPy({'a': (Eq, dict)}) self.assertFalse(dcp.match(expr={'a': {}})) self.assertFalse(dcp.match(expr={'a': list})) self.assertTrue(dcp.match(expr={'a': dict})) def test_Or_None(self): dcp = DictComPy({'a': (Or_None, int)}) self.assertFalse(dcp.match(expr={'b': 1})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': False})) self.assertTrue(dcp.match(expr={'a': None})) self.assertTrue(dcp.match(expr={'a': 1})) dcp = DictComPy({'a': (Or_None, (tuple, int))}) self.assertFalse(dcp.match(expr={'b': 1})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': False})) self.assertFalse(dcp.match(expr={'a': []})) self.assertFalse(dcp.match(expr={'a': None})) self.assertFalse(dcp.match(expr={'a': ('df',)})) self.assertTrue(dcp.match(expr={'a': ()})) self.assertTrue(dcp.match(expr={'a': (1,)})) def test_Or_Empty(self): dcp = DictComPy({'a': (Or_Empty, {'b': int})}) self.assertFalse(dcp.match(expr={'b': 1})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': False})) self.assertFalse(dcp.match(expr={'a': []})) self.assertFalse(dcp.match(expr={'a': None})) self.assertFalse(dcp.match(expr={'a': ('df',)})) self.assertTrue(dcp.match(expr={'a': {}})) self.assertTrue(dcp.match(expr={'a': {'b': 1}})) dcp = DictComPy({'a': (Or_Empty, [int])}) self.assertFalse(dcp.match(expr={'b': 1})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': False})) self.assertFalse(dcp.match(expr={'a': None})) self.assertFalse(dcp.match(expr={'a': ['df']})) self.assertTrue(dcp.match(expr={'a': []})) self.assertTrue(dcp.match(expr={'a': [1]})) """ Failing dcp = DictComPy({'a': (Or_Empty, (tuple, int))}) self.assertFalse(dcp.match(expr={'b': 1})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': False})) self.assertFalse(dcp.match(expr={'a': []})) self.assertFalse(dcp.match(expr={'a': None})) self.assertFalse(dcp.match(expr={'a': ('df',)})) self.assertTrue(dcp.match(expr={'a': ()})) self.assertTrue(dcp.match(expr={'a': (1,)})) """ if __name__ == '__main__': unittest.main()
en
0.153813
# TODO # model: (int, 1) -> funciona com toca. Les tuples son especials x) # faltaria afegir un parseig del model # 1, <-- common mistake # ',' <-- # ',' <-- Failing dcp = DictComPy({'a': (Or_Empty, (tuple, int))}) self.assertFalse(dcp.match(expr={'b': 1})) self.assertFalse(dcp.match(expr={'a': 1.0})) self.assertFalse(dcp.match(expr={'a': ''})) self.assertFalse(dcp.match(expr={'a': False})) self.assertFalse(dcp.match(expr={'a': []})) self.assertFalse(dcp.match(expr={'a': None})) self.assertFalse(dcp.match(expr={'a': ('df',)})) self.assertTrue(dcp.match(expr={'a': ()})) self.assertTrue(dcp.match(expr={'a': (1,)}))
3.118237
3
Jupyter_Notebooks/Scripts/Correspondence_XML_parser.py
NEU-Libraries/dsg-mhs
0
6620611
<gh_stars>0 import re import pandas as pd import xml.etree.ElementTree as ET # Read in file and get root of XML tree. def get_root(xml_file): tree = ET.parse(xml_file) root = tree.getroot() return root # Get namespace of individual file from root element. def get_namespace(root): namespace = re.match(r"{(.*)}", str(root.tag)) ns = {"ns":namespace.group(1)} return ns def build_dataframe(list_of_files): dataframe = [] for file in list_of_files: try: root = get_root(file) ns = get_namespace(root) reFile = str(re.search(r'.*/(.*.xml)', str(file)).group(1)) # get filename without path date = root.find('.//ns:date/[@type="creation"]', ns).get('when') # get date. source = root.find('.//ns:bibl//ns:author', ns).text # get source/author & target/recipient target = root.find('.//ns:bibl//ns:recipient', ns).text # Loops # loop to get all references (persRef) references_l = [] for ref in root.findall('.//ns:persRef', ns): person = ref.get('ref') references_l.append(person) references = ','.join(references_l) # loop to get subjects. subject_l = [] for subject in root.findall('.//ns:subject', ns): subject_l.append(subject.text) subjects = ','.join(subject_l) # loop to get all text within <div type="docbody"> text_l = [] for txt in root.findall('.//ns:div[@type="docbody"]', ns): string = ''.join(ET.tostring(txt, encoding='unicode', method='text')) clean_string = re.sub(r'[\t\n\s]+', ' ', string) text_l.append(clean_string) content = ' '.join(text_l) row = {'file': reFile, 'date': date, 'source': source, 'target':target, 'subjects': subjects, 'references': references, 'text': content} dataframe.append(row) except: print (file, '\n') df = pd.DataFrame(dataframe) return (df)
import re import pandas as pd import xml.etree.ElementTree as ET # Read in file and get root of XML tree. def get_root(xml_file): tree = ET.parse(xml_file) root = tree.getroot() return root # Get namespace of individual file from root element. def get_namespace(root): namespace = re.match(r"{(.*)}", str(root.tag)) ns = {"ns":namespace.group(1)} return ns def build_dataframe(list_of_files): dataframe = [] for file in list_of_files: try: root = get_root(file) ns = get_namespace(root) reFile = str(re.search(r'.*/(.*.xml)', str(file)).group(1)) # get filename without path date = root.find('.//ns:date/[@type="creation"]', ns).get('when') # get date. source = root.find('.//ns:bibl//ns:author', ns).text # get source/author & target/recipient target = root.find('.//ns:bibl//ns:recipient', ns).text # Loops # loop to get all references (persRef) references_l = [] for ref in root.findall('.//ns:persRef', ns): person = ref.get('ref') references_l.append(person) references = ','.join(references_l) # loop to get subjects. subject_l = [] for subject in root.findall('.//ns:subject', ns): subject_l.append(subject.text) subjects = ','.join(subject_l) # loop to get all text within <div type="docbody"> text_l = [] for txt in root.findall('.//ns:div[@type="docbody"]', ns): string = ''.join(ET.tostring(txt, encoding='unicode', method='text')) clean_string = re.sub(r'[\t\n\s]+', ' ', string) text_l.append(clean_string) content = ' '.join(text_l) row = {'file': reFile, 'date': date, 'source': source, 'target':target, 'subjects': subjects, 'references': references, 'text': content} dataframe.append(row) except: print (file, '\n') df = pd.DataFrame(dataframe) return (df)
en
0.793708
# Read in file and get root of XML tree. # Get namespace of individual file from root element. # get filename without path # get date. # get source/author & target/recipient # Loops # loop to get all references (persRef) # loop to get subjects. # loop to get all text within <div type="docbody">
2.854278
3
c64/constants.py
thanasisk/binja-c64
0
6620612
<filename>c64/constants.py # coding=utf-8 """ Copyright (c) 2021 <NAME> 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. """ KERNAL = { 0xFF81: "SCINIT", 0xFF84: "IOINIT", #. Initialize CIA's, SID volume; setup memory configuration; set and start interrupt timer. 0xFF87: "RAMTAS", 0xFF8A: "RESTOR", 0xFF8D: "VECTOR", 0xFF90: "SETMSG", 0xFF93: "LSTNSA", 0xFF96: "TALKSA", 0xFF99: "MEMBOT", 0xFF9C: "MEMTOP", 0xFF9F: "SCNKEY", 0xFFA2: "SETTMO", 0xFFA5: "IECIN", 0xFFA8: "IECOUT", 0xFFAB: "UNTALK", 0xFFAE: "UNLSTN", 0xFFB1: "LISTEN", 0xFFB4: "TALK", 0xFFB7: "READST", 0xFFBA: "SETLFS", 0xFFBD: "SETNAM", 0xFFC0: "OPEN", 0xFFC3: "CLOSE", 0xFFC6: "CHKIN", 0xFFC9: "CHKOUT", 0xFFCC: "CLRCHN", 0xFFCF: "CHRIN", 0xFFD2: "CHROUT", 0xFFD5: "LOAD", 0xFFD8: "SAVE", 0xFFDB: "SETTIM", 0xFFDE: "RDTIM", 0xFFE1: "STOP", 0xFFE4: "GETIN", 0xFFE7: "CLALL", 0xFFEA: "UDTIM", 0xFFED: "SCREEN", 0xFFF0: "PLOT", 0xFFF3: "IOBASE" }
<filename>c64/constants.py # coding=utf-8 """ Copyright (c) 2021 <NAME> 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. """ KERNAL = { 0xFF81: "SCINIT", 0xFF84: "IOINIT", #. Initialize CIA's, SID volume; setup memory configuration; set and start interrupt timer. 0xFF87: "RAMTAS", 0xFF8A: "RESTOR", 0xFF8D: "VECTOR", 0xFF90: "SETMSG", 0xFF93: "LSTNSA", 0xFF96: "TALKSA", 0xFF99: "MEMBOT", 0xFF9C: "MEMTOP", 0xFF9F: "SCNKEY", 0xFFA2: "SETTMO", 0xFFA5: "IECIN", 0xFFA8: "IECOUT", 0xFFAB: "UNTALK", 0xFFAE: "UNLSTN", 0xFFB1: "LISTEN", 0xFFB4: "TALK", 0xFFB7: "READST", 0xFFBA: "SETLFS", 0xFFBD: "SETNAM", 0xFFC0: "OPEN", 0xFFC3: "CLOSE", 0xFFC6: "CHKIN", 0xFFC9: "CHKOUT", 0xFFCC: "CLRCHN", 0xFFCF: "CHRIN", 0xFFD2: "CHROUT", 0xFFD5: "LOAD", 0xFFD8: "SAVE", 0xFFDB: "SETTIM", 0xFFDE: "RDTIM", 0xFFE1: "STOP", 0xFFE4: "GETIN", 0xFFE7: "CLALL", 0xFFEA: "UDTIM", 0xFFED: "SCREEN", 0xFFF0: "PLOT", 0xFFF3: "IOBASE" }
en
0.760916
# coding=utf-8 Copyright (c) 2021 <NAME> 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. #. Initialize CIA's, SID volume; setup memory configuration; set and start interrupt timer.
1.600085
2
coursera/semana7/exerc_02.py
pedrobenevides2/Ciencia-de-Dados
0
6620613
<reponame>pedrobenevides2/Ciencia-de-Dados<gh_stars>0 x =int(input('digite a largura: ')) y= int(input('digite a altura: ')) x1=x y1=y while y>=1: while x>0: if x==1: print("#",end="") elif x==x1: print("#", end='') elif y==1: print("#", end='') elif y==y1: print("#", end='') else: print(" ",end='') x=x-1 print() y=y-1 x=x1
x =int(input('digite a largura: ')) y= int(input('digite a altura: ')) x1=x y1=y while y>=1: while x>0: if x==1: print("#",end="") elif x==x1: print("#", end='') elif y==1: print("#", end='') elif y==y1: print("#", end='') else: print(" ",end='') x=x-1 print() y=y-1 x=x1
none
1
4.003368
4
.makeversion.py
mangal-wg/pymangal
3
6620614
<reponame>mangal-wg/pymangal import pymangal import os with open('.version', 'w') as f: f.write(pymangal.__version__) f.write("\n") with open('.tag', 'r') as f: t = f.readline().rstrip() if not t == pymangal.__version__ : os.system("git tag {0}".format(pymangal.__version__))
import pymangal import os with open('.version', 'w') as f: f.write(pymangal.__version__) f.write("\n") with open('.tag', 'r') as f: t = f.readline().rstrip() if not t == pymangal.__version__ : os.system("git tag {0}".format(pymangal.__version__))
none
1
2.363528
2
3Deep_Q_Network/agent.py
Mirocle007/Reinforcement_Learning
1
6620615
<filename>3Deep_Q_Network/agent.py """ Agent for the reinforcement learning, which learn from the environment and choose action. """ import numpy as np import tensorflow as tf def network(name, state, n_action, target_Q=None): """A simple 2 layer neural network """ n_state = state.shape[1].value with tf.variable_scope(name): # c_names(collections_names) are the collections to store variables c_names, n_l1, w_initializer, b_initializer = ( ["{}_params".format(name), tf.GraphKeys.GLOBAL_VARIABLES], 10, tf.random_normal_initializer(0., 0.3), tf.constant_initializer(0.1) # config of layers ) # first layer.collections is used later when assign to target net with tf.variable_scope("l1"): w1 = tf.get_variable("w1", [n_state, n_l1], initializer=w_initializer, collections=c_names) b1 = tf.get_variable("b1", [1, n_l1], initializer=b_initializer, collections=c_names) l1 = tf.nn.relu(tf.matmul(state, w1) + b1) # second layer. collections is used later when assign to target net with tf.variable_scope("l2"): w2 = tf.get_variable("w2", [n_l1, n_action], initializer=w_initializer, collections=c_names) b2 = tf.get_variable("b2", [1, n_action], initializer=b_initializer, collections=c_names) predict_Q = tf.matmul(l1, w2) + b2 if target_Q is not None: with tf.variable_scope("loss"): loss = tf.losses.mean_squared_error(target_Q, predict_Q) return predict_Q, loss else: return predict_Q class Agent(object): def __init__(self, opt): self.n_state = opt.n_state self.n_action = len(opt.action_space) self.actions = list(range(self.n_action)) self.gamma = opt.gamma self.lr = opt.learning_rate self.batch_size = opt.batch_size self.epsilon = opt.epsilon self.loss_history = [] self.memory_size = opt.memory_size self.memory = np.zeros((self.memory_size, 2 * self.n_state + 2)) self.replace_target_iter = opt.replace_target_iter self.learn_step_counter = 0 self._build_network() tnet_params = tf.get_collection("target_net_params") pnet_params = tf.get_collection("predict_net_params") self.replace_target_op = [tf.assign(t, p) for t, p in zip(tnet_params, pnet_params)] self.sess = tf.Session() self.sess.run(tf.global_variables_initializer()) self.saver = tf.train.Saver() if opt.output_graph: # $ tensorboard --logdir=logs tf.summary.FileWriter("logs/", self.sess.graph) def _build_network(self): self.target_Q = tf.placeholder(tf.float32, shape=(None,self.n_action)) self.state = tf.placeholder(tf.float32, shape=(None, self.n_state)) self.predict_Q, self.loss = network("predict_net", self.state, self.n_action, target_Q=self.target_Q) with tf.variable_scope("train"): self._train_op = tf.train.RMSPropOptimizer(self.lr).minimize(self.loss) self.next_state = tf.placeholder(tf.float32, [None, self.n_state], name="next_state") self.next_Q = network("target_net", self.next_state, self.n_action) def choose_action(self, state): if np.random.randn() < self.epsilon: state = state[np.newaxis, :] actions = self.sess.run( self.predict_Q, feed_dict={self.state: state} ) action = np.argmax(actions) else: action = np.random.choice(self.actions) action = int(action) return action def store(self, state, action, reward, next_action): if not hasattr(self, "memory_counter"): self.memory_counter = 0 observation = np.hstack((state, action, reward, next_action)) index = self.memory_counter % self.memory_size self.memory[index, :] = observation self.memory_counter += 1 def learn(self): # check to replace target net parameters if self.learn_step_counter % self.replace_target_iter == 0: self.sess.run(self.replace_target_op) if self.learn_step_counter % self.replace_target_iter * 100 == 0: self.save() if self.memory_counter > self.memory_size: sample_index = np.random.choice(self.memory_size, self.batch_size) else: sample_index = np.random.choice(self.memory_counter, self.batch_size) batch_memory = self.memory[sample_index, :] next_Q, predict_Q = self.sess.run( [self.next_Q, self.predict_Q], feed_dict={ self.next_state: batch_memory[:, -self.n_state: ], self.state: batch_memory[:, :self.n_state] } ) target_Q = predict_Q.copy() batch_index = np.arange(self.batch_size) action_index = batch_memory[:, self.n_state].astype(int) reward = batch_memory[:, self.n_state + 1] target_Q[batch_index, action_index] = reward + self.gamma * np.max(next_Q, 1) # train network _, loss = self.sess.run( [self._train_op, self.loss], feed_dict={ self.state: batch_memory[:, :self.n_state], self.target_Q: target_Q } ) self.loss_history.append(loss) self.learn_step_counter += 1 def plot_cost(self): import matplotlib.pyplot as plt plt.plot(np.arange(len(self.loss_history)), self.loss_history) plt.ylabel("loss") plt.xlabel('training steps') plt.show() def save(self): model_name = "./models/model_{}iter.ckpt".format(self.learn_step_counter) save_path = self.saver.save(self.sess, model_name) print("Model saved in path: {}".format(save_path)) def closs_session(self): self.sess.close()
<filename>3Deep_Q_Network/agent.py """ Agent for the reinforcement learning, which learn from the environment and choose action. """ import numpy as np import tensorflow as tf def network(name, state, n_action, target_Q=None): """A simple 2 layer neural network """ n_state = state.shape[1].value with tf.variable_scope(name): # c_names(collections_names) are the collections to store variables c_names, n_l1, w_initializer, b_initializer = ( ["{}_params".format(name), tf.GraphKeys.GLOBAL_VARIABLES], 10, tf.random_normal_initializer(0., 0.3), tf.constant_initializer(0.1) # config of layers ) # first layer.collections is used later when assign to target net with tf.variable_scope("l1"): w1 = tf.get_variable("w1", [n_state, n_l1], initializer=w_initializer, collections=c_names) b1 = tf.get_variable("b1", [1, n_l1], initializer=b_initializer, collections=c_names) l1 = tf.nn.relu(tf.matmul(state, w1) + b1) # second layer. collections is used later when assign to target net with tf.variable_scope("l2"): w2 = tf.get_variable("w2", [n_l1, n_action], initializer=w_initializer, collections=c_names) b2 = tf.get_variable("b2", [1, n_action], initializer=b_initializer, collections=c_names) predict_Q = tf.matmul(l1, w2) + b2 if target_Q is not None: with tf.variable_scope("loss"): loss = tf.losses.mean_squared_error(target_Q, predict_Q) return predict_Q, loss else: return predict_Q class Agent(object): def __init__(self, opt): self.n_state = opt.n_state self.n_action = len(opt.action_space) self.actions = list(range(self.n_action)) self.gamma = opt.gamma self.lr = opt.learning_rate self.batch_size = opt.batch_size self.epsilon = opt.epsilon self.loss_history = [] self.memory_size = opt.memory_size self.memory = np.zeros((self.memory_size, 2 * self.n_state + 2)) self.replace_target_iter = opt.replace_target_iter self.learn_step_counter = 0 self._build_network() tnet_params = tf.get_collection("target_net_params") pnet_params = tf.get_collection("predict_net_params") self.replace_target_op = [tf.assign(t, p) for t, p in zip(tnet_params, pnet_params)] self.sess = tf.Session() self.sess.run(tf.global_variables_initializer()) self.saver = tf.train.Saver() if opt.output_graph: # $ tensorboard --logdir=logs tf.summary.FileWriter("logs/", self.sess.graph) def _build_network(self): self.target_Q = tf.placeholder(tf.float32, shape=(None,self.n_action)) self.state = tf.placeholder(tf.float32, shape=(None, self.n_state)) self.predict_Q, self.loss = network("predict_net", self.state, self.n_action, target_Q=self.target_Q) with tf.variable_scope("train"): self._train_op = tf.train.RMSPropOptimizer(self.lr).minimize(self.loss) self.next_state = tf.placeholder(tf.float32, [None, self.n_state], name="next_state") self.next_Q = network("target_net", self.next_state, self.n_action) def choose_action(self, state): if np.random.randn() < self.epsilon: state = state[np.newaxis, :] actions = self.sess.run( self.predict_Q, feed_dict={self.state: state} ) action = np.argmax(actions) else: action = np.random.choice(self.actions) action = int(action) return action def store(self, state, action, reward, next_action): if not hasattr(self, "memory_counter"): self.memory_counter = 0 observation = np.hstack((state, action, reward, next_action)) index = self.memory_counter % self.memory_size self.memory[index, :] = observation self.memory_counter += 1 def learn(self): # check to replace target net parameters if self.learn_step_counter % self.replace_target_iter == 0: self.sess.run(self.replace_target_op) if self.learn_step_counter % self.replace_target_iter * 100 == 0: self.save() if self.memory_counter > self.memory_size: sample_index = np.random.choice(self.memory_size, self.batch_size) else: sample_index = np.random.choice(self.memory_counter, self.batch_size) batch_memory = self.memory[sample_index, :] next_Q, predict_Q = self.sess.run( [self.next_Q, self.predict_Q], feed_dict={ self.next_state: batch_memory[:, -self.n_state: ], self.state: batch_memory[:, :self.n_state] } ) target_Q = predict_Q.copy() batch_index = np.arange(self.batch_size) action_index = batch_memory[:, self.n_state].astype(int) reward = batch_memory[:, self.n_state + 1] target_Q[batch_index, action_index] = reward + self.gamma * np.max(next_Q, 1) # train network _, loss = self.sess.run( [self._train_op, self.loss], feed_dict={ self.state: batch_memory[:, :self.n_state], self.target_Q: target_Q } ) self.loss_history.append(loss) self.learn_step_counter += 1 def plot_cost(self): import matplotlib.pyplot as plt plt.plot(np.arange(len(self.loss_history)), self.loss_history) plt.ylabel("loss") plt.xlabel('training steps') plt.show() def save(self): model_name = "./models/model_{}iter.ckpt".format(self.learn_step_counter) save_path = self.saver.save(self.sess, model_name) print("Model saved in path: {}".format(save_path)) def closs_session(self): self.sess.close()
en
0.791454
Agent for the reinforcement learning, which learn from the environment and choose action. A simple 2 layer neural network # c_names(collections_names) are the collections to store variables # config of layers # first layer.collections is used later when assign to target net # second layer. collections is used later when assign to target net # $ tensorboard --logdir=logs # check to replace target net parameters # train network
3.321245
3
online_pharmacy/online_pharmacy/urls.py
geekyJock8/online_pharmacy
5
6620616
from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^',include('Register_and_login.urls')), url(r'^homepage/',include('MainPage.urls')), url(r'^username/cart/',include('cart.urls')), url(r'^username/',include('customer.urls')), url(r'^pharmacy_name/',include('pharmacy.urls')), url(r'^pharmacy_name/inventory',include('inventory.urls')), url(r'^search/all_search=pcm',include('items.urls')), url(r'^', include('order.urls')), url(r'^admin/', admin.site.urls) ]
from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^',include('Register_and_login.urls')), url(r'^homepage/',include('MainPage.urls')), url(r'^username/cart/',include('cart.urls')), url(r'^username/',include('customer.urls')), url(r'^pharmacy_name/',include('pharmacy.urls')), url(r'^pharmacy_name/inventory',include('inventory.urls')), url(r'^search/all_search=pcm',include('items.urls')), url(r'^', include('order.urls')), url(r'^admin/', admin.site.urls) ]
none
1
1.753483
2
TestBot/test_cogs/poketcgFunctions/database.py
austinmh12/DiscordBots
0
6620617
from .. import sql, log def initialise_db(): sql('poketcg', '''create table players ( discord_id integer ,cash integer ,daily_reset integer ,packs text ,packs_opened integer ,packs_bought integer ,total_cash integer ,total_cards integer ,cards_sold integer )''' ) sql('poketcg', '''create table packs ( discord_id integer ,set_id text ,amount integer )''' ) sql('poketcg', '''create table cards ( discord_id integer ,card_id text ,amount integer )''' ) sql('poketcg', '''create table version ( version text )''' ) sql('poketcg', 'insert into version values (?)', ('1.0.0',)) def get_version(): df = sql('poketcg', 'select * from version') if df.empty: return '' return df.to_dict('records')[0]['version'] def update_version(version): sql('poketcg', 'delete from version') sql('poketcg', 'insert into version values (?)', (version,)) def migrate_db(version): current = get_version() log.debug(current) log.debug(version) if version <= current: return log.debug('Migrating database') migration_versions = [k for k in migration_steps if k > current] migration_versions.sort() for migration_version in migration_versions: for step in migration_steps[migration_version]: sql('poketcg', step) update_version(version) migration_steps = { '1.1.0': [ "alter table players add column collections text default '{}'", "alter table players add column collections_bought integer default 0", "alter table players add column trainers text default '{}'", "alter table players add column trainers_bought integer default 0", "alter table players add column boosters text default '{}'", "alter table players add column boosters_bought integer default 0" ], '1.2.0': [ "alter table players add column daily_packs integer default 50", "alter table players add column quiz_questions integer default 5", "alter table players add column current_multiplier integer default 1", "alter table players add column quiz_correct integer default 0" ], '1.2.2': [ """create table tmp_player ( discord_id integer ,cash integer ,daily_reset integer ,packs text ,packs_opened integer ,packs_bought integer ,total_cash integer ,total_cards integer ,cards_sold integer ,daily_packs integer ,quiz_questions integer ,current_multiplier integer ,quiz_correct integer ) """, """insert into tmp_player select discord_id ,cash ,daily_reset ,packs ,packs_opened ,packs_bought ,total_cash ,total_cards ,cards_sold ,daily_packs ,quiz_questions ,current_multiplier ,quiz_correct from players """, 'drop table players', """create table players ( discord_id integer ,cash integer ,daily_reset integer ,packs text ,packs_opened integer ,packs_bought integer ,total_cash integer ,total_cards integer ,cards_sold integer ,daily_packs integer ,quiz_questions integer ,current_multiplier integer ,quiz_correct integer ) """, 'insert into players select * from tmp_player', 'drop table tmp_player' ], '1.2.3': [ 'alter table players add column quiz_reset integer default 1629401801.1' ], '1.3.0': [ "alter table players add column savelist text default '[]'" ], '1.4.0': [ "alter table players add column permanent_mult integer default 0" ] }
from .. import sql, log def initialise_db(): sql('poketcg', '''create table players ( discord_id integer ,cash integer ,daily_reset integer ,packs text ,packs_opened integer ,packs_bought integer ,total_cash integer ,total_cards integer ,cards_sold integer )''' ) sql('poketcg', '''create table packs ( discord_id integer ,set_id text ,amount integer )''' ) sql('poketcg', '''create table cards ( discord_id integer ,card_id text ,amount integer )''' ) sql('poketcg', '''create table version ( version text )''' ) sql('poketcg', 'insert into version values (?)', ('1.0.0',)) def get_version(): df = sql('poketcg', 'select * from version') if df.empty: return '' return df.to_dict('records')[0]['version'] def update_version(version): sql('poketcg', 'delete from version') sql('poketcg', 'insert into version values (?)', (version,)) def migrate_db(version): current = get_version() log.debug(current) log.debug(version) if version <= current: return log.debug('Migrating database') migration_versions = [k for k in migration_steps if k > current] migration_versions.sort() for migration_version in migration_versions: for step in migration_steps[migration_version]: sql('poketcg', step) update_version(version) migration_steps = { '1.1.0': [ "alter table players add column collections text default '{}'", "alter table players add column collections_bought integer default 0", "alter table players add column trainers text default '{}'", "alter table players add column trainers_bought integer default 0", "alter table players add column boosters text default '{}'", "alter table players add column boosters_bought integer default 0" ], '1.2.0': [ "alter table players add column daily_packs integer default 50", "alter table players add column quiz_questions integer default 5", "alter table players add column current_multiplier integer default 1", "alter table players add column quiz_correct integer default 0" ], '1.2.2': [ """create table tmp_player ( discord_id integer ,cash integer ,daily_reset integer ,packs text ,packs_opened integer ,packs_bought integer ,total_cash integer ,total_cards integer ,cards_sold integer ,daily_packs integer ,quiz_questions integer ,current_multiplier integer ,quiz_correct integer ) """, """insert into tmp_player select discord_id ,cash ,daily_reset ,packs ,packs_opened ,packs_bought ,total_cash ,total_cards ,cards_sold ,daily_packs ,quiz_questions ,current_multiplier ,quiz_correct from players """, 'drop table players', """create table players ( discord_id integer ,cash integer ,daily_reset integer ,packs text ,packs_opened integer ,packs_bought integer ,total_cash integer ,total_cards integer ,cards_sold integer ,daily_packs integer ,quiz_questions integer ,current_multiplier integer ,quiz_correct integer ) """, 'insert into players select * from tmp_player', 'drop table tmp_player' ], '1.2.3': [ 'alter table players add column quiz_reset integer default 1629401801.1' ], '1.3.0': [ "alter table players add column savelist text default '[]'" ], '1.4.0': [ "alter table players add column permanent_mult integer default 0" ] }
en
0.433302
create table players ( discord_id integer ,cash integer ,daily_reset integer ,packs text ,packs_opened integer ,packs_bought integer ,total_cash integer ,total_cards integer ,cards_sold integer ) create table packs ( discord_id integer ,set_id text ,amount integer ) create table cards ( discord_id integer ,card_id text ,amount integer ) create table version ( version text ) create table tmp_player ( discord_id integer ,cash integer ,daily_reset integer ,packs text ,packs_opened integer ,packs_bought integer ,total_cash integer ,total_cards integer ,cards_sold integer ,daily_packs integer ,quiz_questions integer ,current_multiplier integer ,quiz_correct integer ) insert into tmp_player select discord_id ,cash ,daily_reset ,packs ,packs_opened ,packs_bought ,total_cash ,total_cards ,cards_sold ,daily_packs ,quiz_questions ,current_multiplier ,quiz_correct from players create table players ( discord_id integer ,cash integer ,daily_reset integer ,packs text ,packs_opened integer ,packs_bought integer ,total_cash integer ,total_cards integer ,cards_sold integer ,daily_packs integer ,quiz_questions integer ,current_multiplier integer ,quiz_correct integer )
2.619636
3
rconweb/api/urls.py
ProfessorZ/hll_rcon_tool
0
6620618
<filename>rconweb/api/urls.py from django.urls import path from . import views from . import auth urlpatterns = [ path(name, func, name='name') for name, func in views.commands ] + [ path('login', auth.do_login), path('logout', auth.do_logout), path('is_logged_in', auth.is_logged_in), path('get_online_mods', auth.get_online_mods), path('get_ingame_mods', auth.get_ingame_mods) ]
<filename>rconweb/api/urls.py from django.urls import path from . import views from . import auth urlpatterns = [ path(name, func, name='name') for name, func in views.commands ] + [ path('login', auth.do_login), path('logout', auth.do_logout), path('is_logged_in', auth.is_logged_in), path('get_online_mods', auth.get_online_mods), path('get_ingame_mods', auth.get_ingame_mods) ]
none
1
2.077484
2
src/solana/_layouts/stake_instructions.py
yankev/solana-py
0
6620619
from enum import IntEnum from construct import Switch # type: ignore from construct import Int32ul, Int64ul, Int64sl, Pass # type: ignore from construct import Struct as cStruct from .shared import PUBLIC_KEY_LAYOUT class StakeInstructionType(IntEnum): """Instruction types for staking program.""" INITIALIZE_STAKE_ACCOUNT = 0 DELEGATE_STAKE = 2 WITHDRAW_STAKE = 4 DEACTIVATE = 5 _AUTHORIZED_LAYOUT = cStruct( "staker" / PUBLIC_KEY_LAYOUT, "withdrawer" / PUBLIC_KEY_LAYOUT, ) _LOCKUP_LAYOUT = cStruct( "unix_timestamp" / Int64sl, "epoch" / Int64ul, "custodian" / PUBLIC_KEY_LAYOUT, ) _INITIALIZE_STAKE_ACCOUNT_LAYOUT = cStruct( "authorized" / _AUTHORIZED_LAYOUT, "lockup" / _LOCKUP_LAYOUT, ) _WITHDRAW_STAKE_ACCOUNT_LAYOUT = cStruct( "lamports" / Int64ul, ) STAKE_INSTRUCTIONS_LAYOUT = cStruct( "instruction_type" / Int32ul, "args" / Switch( lambda this: this.instruction_type, { StakeInstructionType.INITIALIZE_STAKE_ACCOUNT: _INITIALIZE_STAKE_ACCOUNT_LAYOUT, StakeInstructionType.DELEGATE_STAKE: Pass, StakeInstructionType.DEACTIVATE: Pass, StakeInstructionType.WITHDRAW_STAKE: _WITHDRAW_STAKE_ACCOUNT_LAYOUT, }, ), )
from enum import IntEnum from construct import Switch # type: ignore from construct import Int32ul, Int64ul, Int64sl, Pass # type: ignore from construct import Struct as cStruct from .shared import PUBLIC_KEY_LAYOUT class StakeInstructionType(IntEnum): """Instruction types for staking program.""" INITIALIZE_STAKE_ACCOUNT = 0 DELEGATE_STAKE = 2 WITHDRAW_STAKE = 4 DEACTIVATE = 5 _AUTHORIZED_LAYOUT = cStruct( "staker" / PUBLIC_KEY_LAYOUT, "withdrawer" / PUBLIC_KEY_LAYOUT, ) _LOCKUP_LAYOUT = cStruct( "unix_timestamp" / Int64sl, "epoch" / Int64ul, "custodian" / PUBLIC_KEY_LAYOUT, ) _INITIALIZE_STAKE_ACCOUNT_LAYOUT = cStruct( "authorized" / _AUTHORIZED_LAYOUT, "lockup" / _LOCKUP_LAYOUT, ) _WITHDRAW_STAKE_ACCOUNT_LAYOUT = cStruct( "lamports" / Int64ul, ) STAKE_INSTRUCTIONS_LAYOUT = cStruct( "instruction_type" / Int32ul, "args" / Switch( lambda this: this.instruction_type, { StakeInstructionType.INITIALIZE_STAKE_ACCOUNT: _INITIALIZE_STAKE_ACCOUNT_LAYOUT, StakeInstructionType.DELEGATE_STAKE: Pass, StakeInstructionType.DEACTIVATE: Pass, StakeInstructionType.WITHDRAW_STAKE: _WITHDRAW_STAKE_ACCOUNT_LAYOUT, }, ), )
en
0.589977
# type: ignore # type: ignore Instruction types for staking program.
2.17897
2
alembic/versions/47124d1df386_remove_password.py
morelab/labmanager
2
6620620
<reponame>morelab/labmanager """Remove password Revision ID: <PASSWORD> Revises: <KEY> Create Date: 2016-11-03 17:12:14.046930 """ # revision identifiers, used by Alembic. revision = '4<PASSWORD>' down_revision = '1545f<PASSWORD>1cd' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql def upgrade(): ### commands auto generated by Alembic - please adjust! ### try: op.drop_column('siway_user', u'password') except: pass ### end Alembic commands ### pass def downgrade(): ### commands auto generated by Alembic - please adjust! ### try: op.add_column('siway_user', sa.Column(u'password', mysql.VARCHAR(length=255), nullable=False)) except: pass ### end Alembic commands ###
"""Remove password Revision ID: <PASSWORD> Revises: <KEY> Create Date: 2016-11-03 17:12:14.046930 """ # revision identifiers, used by Alembic. revision = '4<PASSWORD>' down_revision = '1545f<PASSWORD>1cd' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql def upgrade(): ### commands auto generated by Alembic - please adjust! ### try: op.drop_column('siway_user', u'password') except: pass ### end Alembic commands ### pass def downgrade(): ### commands auto generated by Alembic - please adjust! ### try: op.add_column('siway_user', sa.Column(u'password', mysql.VARCHAR(length=255), nullable=False)) except: pass ### end Alembic commands ###
en
0.525419
Remove password Revision ID: <PASSWORD> Revises: <KEY> Create Date: 2016-11-03 17:12:14.046930 # revision identifiers, used by Alembic. ### commands auto generated by Alembic - please adjust! ### ### end Alembic commands ### ### commands auto generated by Alembic - please adjust! ### ### end Alembic commands ###
1.256903
1
eveil/map.py
pjfichet/eveil
0
6620621
<filename>eveil/map.py # Copyright (C) 2018 <NAME> # <pierrejean dot fichet at posteo dot net> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # This submodule implements a directed graph. # The path algorithm comes from: https://www.python.org/doc/essays/graphs/ # Some other ideas come from: # https://triangleinequality.wordpress.com/2013/08/21/graphs-as-objects-in-python/ from .template import Template from .item import Container from .message import pose, expose_format, info from datetime import datetime, timedelta class Map(): """The Map class implements a graph: rooms are nodes, and links are edges. Rooms and links instances should be created from a Map object, using the new_room and new_link methods.""" def __init__(self, game): self.game = game self.rooms = [] self.links = [] self.linklists = [] def new_room(self, region, uid): room = Room(self.game, region, uid) self.rooms.append(room) return room def new_link(self, source, target): # First, our link is a simple list link = [source, target] if link in self.linklists: self.game.log("There is yet a link from room {} to room {}." .format(source.shortdesc, target.shortdesc) ) return self.linklists.append(link) # Now, we create a true Link instance link = Link(source, target) self.links.append(link) source.add_link(link) return link def path(self, source, target, path=[]): """ Returns the shortest path from source to target. Comes from: https://www.python.org/doc/essays/graphs/ """ path = path + [source] if source == target: return path if source not in self.rooms: return None shortest = None for room in source.get_targets(): if room not in path: newpath = self.path(room, target, path) if newpath: if not shortest or len(newpath) < len(shortest): shortest = newpath return shortest class Link(): """ An unidirectional link between two rooms.""" def __init__(self, source, target): self.rooms = [source, target] self.source = source self.target = target # pose_leave and pose_enter define the characters' # automated poses when they leave a room and # enter another. # self.pose_move = None # self.pose_leave = None # self.pose_enter = None self.door = None def move(self, character): self.leave(character) character.queue.add(self.enter, character) def leave(self, character): pose(character, "/Il se dirige vers {}." .format(self.target.shortdesc)) def enter(self, character): pose(character, "/Il quitte les environs en rejoignant {}." .format(self.target.shortdesc)) self.source.del_character(character) self.target.send_longdesc(character) self.target.add_character(character) character.set_room(self.target) pose(character, "/Il arrive par ici depuis {}." .format(self.source.shortdesc)) class Door(): """A door.""" def __init__(self): self.is_opened = True self.can_close = False self.is_closed = False self.can_lock = False self.is_locked = False self.key = None class Room(): NEVER = datetime(2000, 1, 1) RPDELTA = timedelta(minutes=15) def __init__(self, game, region, uid): self.game = game self.region = region self.uid = region + '_' + uid if self.game.db.has('room', self.uid): self.data = self.game.db.get('room', self.uid) self.container = Container(self.game, self.data['container']) else: self.data = { 'container': self.game.db.uid() } self.container = Container(self.game, self.data['container']) self.container.set_volume(10000) self.game.db.put('room', self.uid, self.data) self.shortdesc = None self.longdesc = None self.links = [] self.sources = [] self.targets = [] self.characters = [] self.next_rp = Room.NEVER def short(self, text): """Sets the short description (title).""" self.shortdesc = text def long(self, text, dictionary={}): """Sets the long description.""" self.longdesc = Template( "<h3>{{room.shortdesc}}</h3>" + text #+ "<p>{{list_char}}</p>", + "<p>{{list_item}}</p><p>{{list_char}}</p>", dictionary) def add_link(self, link): if self in link.rooms and link not in self.links: self.links.append(link) if link.source == self: self.targets.append(link) else: self.sources.append(link) def get_sources(self): """ Return the list of rooms from which one can come here.""" return [link.source for link in self.links] def get_targets(self): """ Return the list of rooms one can go from here.""" return [link.target for link in self.targets] def get_target_link(self, target): """ Return the link leading to the target room.""" for link in self.targets: if link.target == target: return link def get_source_link(self, source): """ Return the link by which one can come from source room.""" for link in self.sources: if link.source == source: return link def add_character(self, character): """ add a character to the room.""" self.characters.append(character) # Give a chance to players to have RP, even if they're not # exposing yet. if len(self.characters) > 1: self.next_rp = datetime.now() + Room.RPDELTA def del_character(self, character): """Removes a character form the rom.""" self.characters.remove(character) if len(self.characters) < 2: # A character alone is not having RP. self.next_rp = Room.NEVER def send_longdesc(self, character): """ Send the long description to a character.""" list_char = ", ".join( [expose_format(char, character, char.data['pose']) for char in self.characters]) if list_char: list_char += "." list_item = "" if self.container.items: list_item = ", ".join([item.data['roomdesc'] for item in self.container.items]) list_item = list_item.capitalize() + "." character.player.client.send(self.longdesc.render({ "character": character, "room": self, "list_char": list_char, "list_item": list_item, })) def move(self, character, word): """ Move a character to an adjacent room. """ for link in self.targets: if word in link.target.shortdesc: link.move(character) return info(character.player, "Aller où?") def rp(self): """ Update the RP status of the room.""" if len(self.characters) > 1: self.next_rp = datetime.now() + Room.RPDELTA def has_rp(self, now): """ Check if the room is RP active.""" # self.del_character() takes care a lonely character # won't have RP. return bool(self.next_rp >= now)
<filename>eveil/map.py # Copyright (C) 2018 <NAME> # <pierrejean dot fichet at posteo dot net> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # This submodule implements a directed graph. # The path algorithm comes from: https://www.python.org/doc/essays/graphs/ # Some other ideas come from: # https://triangleinequality.wordpress.com/2013/08/21/graphs-as-objects-in-python/ from .template import Template from .item import Container from .message import pose, expose_format, info from datetime import datetime, timedelta class Map(): """The Map class implements a graph: rooms are nodes, and links are edges. Rooms and links instances should be created from a Map object, using the new_room and new_link methods.""" def __init__(self, game): self.game = game self.rooms = [] self.links = [] self.linklists = [] def new_room(self, region, uid): room = Room(self.game, region, uid) self.rooms.append(room) return room def new_link(self, source, target): # First, our link is a simple list link = [source, target] if link in self.linklists: self.game.log("There is yet a link from room {} to room {}." .format(source.shortdesc, target.shortdesc) ) return self.linklists.append(link) # Now, we create a true Link instance link = Link(source, target) self.links.append(link) source.add_link(link) return link def path(self, source, target, path=[]): """ Returns the shortest path from source to target. Comes from: https://www.python.org/doc/essays/graphs/ """ path = path + [source] if source == target: return path if source not in self.rooms: return None shortest = None for room in source.get_targets(): if room not in path: newpath = self.path(room, target, path) if newpath: if not shortest or len(newpath) < len(shortest): shortest = newpath return shortest class Link(): """ An unidirectional link between two rooms.""" def __init__(self, source, target): self.rooms = [source, target] self.source = source self.target = target # pose_leave and pose_enter define the characters' # automated poses when they leave a room and # enter another. # self.pose_move = None # self.pose_leave = None # self.pose_enter = None self.door = None def move(self, character): self.leave(character) character.queue.add(self.enter, character) def leave(self, character): pose(character, "/Il se dirige vers {}." .format(self.target.shortdesc)) def enter(self, character): pose(character, "/Il quitte les environs en rejoignant {}." .format(self.target.shortdesc)) self.source.del_character(character) self.target.send_longdesc(character) self.target.add_character(character) character.set_room(self.target) pose(character, "/Il arrive par ici depuis {}." .format(self.source.shortdesc)) class Door(): """A door.""" def __init__(self): self.is_opened = True self.can_close = False self.is_closed = False self.can_lock = False self.is_locked = False self.key = None class Room(): NEVER = datetime(2000, 1, 1) RPDELTA = timedelta(minutes=15) def __init__(self, game, region, uid): self.game = game self.region = region self.uid = region + '_' + uid if self.game.db.has('room', self.uid): self.data = self.game.db.get('room', self.uid) self.container = Container(self.game, self.data['container']) else: self.data = { 'container': self.game.db.uid() } self.container = Container(self.game, self.data['container']) self.container.set_volume(10000) self.game.db.put('room', self.uid, self.data) self.shortdesc = None self.longdesc = None self.links = [] self.sources = [] self.targets = [] self.characters = [] self.next_rp = Room.NEVER def short(self, text): """Sets the short description (title).""" self.shortdesc = text def long(self, text, dictionary={}): """Sets the long description.""" self.longdesc = Template( "<h3>{{room.shortdesc}}</h3>" + text #+ "<p>{{list_char}}</p>", + "<p>{{list_item}}</p><p>{{list_char}}</p>", dictionary) def add_link(self, link): if self in link.rooms and link not in self.links: self.links.append(link) if link.source == self: self.targets.append(link) else: self.sources.append(link) def get_sources(self): """ Return the list of rooms from which one can come here.""" return [link.source for link in self.links] def get_targets(self): """ Return the list of rooms one can go from here.""" return [link.target for link in self.targets] def get_target_link(self, target): """ Return the link leading to the target room.""" for link in self.targets: if link.target == target: return link def get_source_link(self, source): """ Return the link by which one can come from source room.""" for link in self.sources: if link.source == source: return link def add_character(self, character): """ add a character to the room.""" self.characters.append(character) # Give a chance to players to have RP, even if they're not # exposing yet. if len(self.characters) > 1: self.next_rp = datetime.now() + Room.RPDELTA def del_character(self, character): """Removes a character form the rom.""" self.characters.remove(character) if len(self.characters) < 2: # A character alone is not having RP. self.next_rp = Room.NEVER def send_longdesc(self, character): """ Send the long description to a character.""" list_char = ", ".join( [expose_format(char, character, char.data['pose']) for char in self.characters]) if list_char: list_char += "." list_item = "" if self.container.items: list_item = ", ".join([item.data['roomdesc'] for item in self.container.items]) list_item = list_item.capitalize() + "." character.player.client.send(self.longdesc.render({ "character": character, "room": self, "list_char": list_char, "list_item": list_item, })) def move(self, character, word): """ Move a character to an adjacent room. """ for link in self.targets: if word in link.target.shortdesc: link.move(character) return info(character.player, "Aller où?") def rp(self): """ Update the RP status of the room.""" if len(self.characters) > 1: self.next_rp = datetime.now() + Room.RPDELTA def has_rp(self, now): """ Check if the room is RP active.""" # self.del_character() takes care a lonely character # won't have RP. return bool(self.next_rp >= now)
en
0.849813
# Copyright (C) 2018 <NAME> # <pierrejean dot fichet at posteo dot net> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # This submodule implements a directed graph. # The path algorithm comes from: https://www.python.org/doc/essays/graphs/ # Some other ideas come from: # https://triangleinequality.wordpress.com/2013/08/21/graphs-as-objects-in-python/ The Map class implements a graph: rooms are nodes, and links are edges. Rooms and links instances should be created from a Map object, using the new_room and new_link methods. # First, our link is a simple list # Now, we create a true Link instance Returns the shortest path from source to target. Comes from: https://www.python.org/doc/essays/graphs/ An unidirectional link between two rooms. # pose_leave and pose_enter define the characters' # automated poses when they leave a room and # enter another. # self.pose_move = None # self.pose_leave = None # self.pose_enter = None A door. Sets the short description (title). Sets the long description. #+ "<p>{{list_char}}</p>", Return the list of rooms from which one can come here. Return the list of rooms one can go from here. Return the link leading to the target room. Return the link by which one can come from source room. add a character to the room. # Give a chance to players to have RP, even if they're not # exposing yet. Removes a character form the rom. # A character alone is not having RP. Send the long description to a character. Move a character to an adjacent room. Update the RP status of the room. Check if the room is RP active. # self.del_character() takes care a lonely character # won't have RP.
2.49074
2
pimpd/fonts.py
eprst/pimpd
1
6620622
<reponame>eprst/pimpd<gh_stars>1-10 from PIL import ImageFont import os.path if os.path.exists('Arial.ttf'): DEFAULT_FONT = 'Arial.ttf' else: DEFAULT_FONT = 'DejaVuSans.ttf' DEFAULT_FONT_12 = ImageFont.truetype(DEFAULT_FONT, 12) DEFAULT_FONT_14 = ImageFont.truetype(DEFAULT_FONT, 14) #DEFAULT_FONT = 'NotoSans-Regular.ttf' #DEFAULT_FONT_12 = ImageFont.truetype(DEFAULT_FONT, 11) #DEFAULT_FONT_14 = ImageFont.truetype(DEFAULT_FONT, 13)
from PIL import ImageFont import os.path if os.path.exists('Arial.ttf'): DEFAULT_FONT = 'Arial.ttf' else: DEFAULT_FONT = 'DejaVuSans.ttf' DEFAULT_FONT_12 = ImageFont.truetype(DEFAULT_FONT, 12) DEFAULT_FONT_14 = ImageFont.truetype(DEFAULT_FONT, 14) #DEFAULT_FONT = 'NotoSans-Regular.ttf' #DEFAULT_FONT_12 = ImageFont.truetype(DEFAULT_FONT, 11) #DEFAULT_FONT_14 = ImageFont.truetype(DEFAULT_FONT, 13)
en
0.502798
#DEFAULT_FONT = 'NotoSans-Regular.ttf' #DEFAULT_FONT_12 = ImageFont.truetype(DEFAULT_FONT, 11) #DEFAULT_FONT_14 = ImageFont.truetype(DEFAULT_FONT, 13)
2.548538
3
api/picklists/helpers.py
django-doctor/lite-api
3
6620623
from api.core.exceptions import NotFoundError from api.picklists.models import PicklistItem def get_picklist_item(pk): try: return PicklistItem.objects.get(pk=pk) except PicklistItem.DoesNotExist: raise NotFoundError({"picklist_item": "Picklist item not found - " + str(pk)})
from api.core.exceptions import NotFoundError from api.picklists.models import PicklistItem def get_picklist_item(pk): try: return PicklistItem.objects.get(pk=pk) except PicklistItem.DoesNotExist: raise NotFoundError({"picklist_item": "Picklist item not found - " + str(pk)})
none
1
2.599634
3
mapps/migrations/0001_initial.py
fossabot/mendelmd
33
6620624
# Generated by Django 2.1.4 on 2018-12-27 08:50 from django.conf import settings import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='App', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('status', models.CharField(max_length=255)), ('category', models.CharField(max_length=255)), ('source', models.CharField(blank=True, max_length=600, null=True)), ('repository', models.CharField(blank=True, max_length=600, null=True)), ('install', models.CharField(blank=True, max_length=600, null=True)), ('main', models.CharField(blank=True, max_length=600, null=True)), ('type', models.CharField(max_length=255)), ('config', django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True)), ('user', models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
# Generated by Django 2.1.4 on 2018-12-27 08:50 from django.conf import settings import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='App', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('status', models.CharField(max_length=255)), ('category', models.CharField(max_length=255)), ('source', models.CharField(blank=True, max_length=600, null=True)), ('repository', models.CharField(blank=True, max_length=600, null=True)), ('install', models.CharField(blank=True, max_length=600, null=True)), ('main', models.CharField(blank=True, max_length=600, null=True)), ('type', models.CharField(max_length=255)), ('config', django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True)), ('user', models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
en
0.726127
# Generated by Django 2.1.4 on 2018-12-27 08:50
1.821649
2
op_robot_tests/tests_files/brokers/openprocurement_client_helper.py
dobruy2517/robot_tests_kap
0
6620625
<filename>op_robot_tests/tests_files/brokers/openprocurement_client_helper.py from openprocurement_client.client import Client from openprocurement_client.utils import get_tender_id_by_uaid def prepare_api_wrapper(key, host_url, api_version): return Client(key, host_url, api_version)
<filename>op_robot_tests/tests_files/brokers/openprocurement_client_helper.py from openprocurement_client.client import Client from openprocurement_client.utils import get_tender_id_by_uaid def prepare_api_wrapper(key, host_url, api_version): return Client(key, host_url, api_version)
none
1
1.827399
2
Source/FaceRecognition/Agents/FakeDetectionAgent.py
robertkarol/ReDe-Multiagent-Face-Recognition-System
0
6620626
from Agents.SystemAgent import SystemAgent from Domain.Connection import Connection from Domain.RecognitionRequest import RecognitionRequest from Domain.RecognitionResponse import RecognitionResponse from Utils.DatasetHelpers import DatasetHelpers from concurrent.futures.thread import ThreadPoolExecutor from spade.behaviour import PeriodicBehaviour, CyclicBehaviour import asyncio import codecs import io import random class FakeDetectionAgent(SystemAgent): class FakeDetectionBehavior(PeriodicBehaviour): def __init__(self, outer_ref, period): super().__init__(period=period) self.__outer_ref: FakeDetectionAgent = outer_ref try: self.__face_images = DatasetHelpers.load_images(self.__outer_ref.data_directory) except FileNotFoundError as error: self.__outer_ref.log(f"Error loading files: {error}", "critical") self.__outer_ref.stop() async def on_start(self): self.__outer_ref.log(f"{self.__outer_ref.jid} starting fake detection. . .", "info") async def run(self): self.__outer_ref.log(f"{self.__outer_ref.jid} sending face image. . .", "info") image = self.__get_random_face_image() request = RecognitionRequest(str(self.__outer_ref.jid), self.__outer_ref.agent_location, self.__image_to_base64(image), self.__outer_ref.generate_outcome, base64encoded=True) data = str.encode(RecognitionRequest.serialize(request)) try: await self.__outer_ref._connection.write_data(data) except ConnectionError as error: self.__outer_ref.log(f"Error writing to connection: {error}", "critical") self.kill() self.__outer_ref.stop() self.__outer_ref.log(f"{self.__outer_ref.jid} done sending face image . . .", "info") async def on_end(self): self.__outer_ref.log(f"{self.__outer_ref.jid} ending fake detection. . .", "info") def __image_to_base64(self, image): byte = io.BytesIO() image.save(byte, 'JPEG') return codecs.encode(byte.getvalue(), 'base64').decode() def __get_random_face_image(self): return random.choice(self.__face_images) class ResponseReceiverBehavior(CyclicBehaviour): def __init__(self, outer_ref): super().__init__() self.__outer_ref: FakeDetectionAgent = outer_ref async def on_start(self): self.__outer_ref.log(f"{self.__outer_ref.jid} starting responses receiver. . .", "info") async def run(self): self.__outer_ref.log(f"{self.__outer_ref.jid} waiting for response. . .", "info") try: data = await self.__outer_ref._connection.read_data() if not data: self.kill() self.__outer_ref.log(f"{self.__outer_ref.jid} received: " f"{RecognitionResponse.deserialize(data)!r}", "info") except ConnectionError as error: self.__outer_ref.log(f"Error reading from connection: {error}", "critical") self.kill() self.__outer_ref.stop() self.__outer_ref.log(f"{self.__outer_ref.jid} done processing response . . .", "info") async def on_end(self): self.__outer_ref.log(f"{self.__outer_ref.jid} ending responses receiver. . .", "info") def __init__(self, jid: str, password: str, agent_location: str, data_directory: str, executor: ThreadPoolExecutor, recognition_system_ip: str, recognition_system_port: int, detection_interval: int = 1, generate_outcome: bool = False, message_checking_interval: int = 5, verify_security: bool = False): super().__init__(jid, password, executor, verify_security, message_checking_interval) self.__agent_location = agent_location self.__data_directory = data_directory self.__recognition_system_ip = recognition_system_ip self.__recognition_system_port = recognition_system_port self.__detection_interval = detection_interval self.__generate_outcome = generate_outcome self._connection: Connection @property def agent_location(self): return self.__agent_location @property def data_directory(self): return self.__data_directory @property def detection_interval(self): return self.__detection_interval @property def generate_outcome(self): return self.__generate_outcome @property def recognition_system_ip(self): return self.__recognition_system_ip @property def recognition_system_port(self): return self.__recognition_system_port async def setup(self): await super().setup() reader_stream, writer_stream = \ await asyncio.open_connection(self.__recognition_system_ip, self.__recognition_system_port) self._connection = Connection(str(self.jid), reader_stream, writer_stream) detection_behavior = self.FakeDetectionBehavior(self, self.detection_interval) receiver_behavior = self.ResponseReceiverBehavior(self) self.add_behaviour(detection_behavior) self.add_behaviour(receiver_behavior) def stop(self): self._connection.close() return super().stop()
from Agents.SystemAgent import SystemAgent from Domain.Connection import Connection from Domain.RecognitionRequest import RecognitionRequest from Domain.RecognitionResponse import RecognitionResponse from Utils.DatasetHelpers import DatasetHelpers from concurrent.futures.thread import ThreadPoolExecutor from spade.behaviour import PeriodicBehaviour, CyclicBehaviour import asyncio import codecs import io import random class FakeDetectionAgent(SystemAgent): class FakeDetectionBehavior(PeriodicBehaviour): def __init__(self, outer_ref, period): super().__init__(period=period) self.__outer_ref: FakeDetectionAgent = outer_ref try: self.__face_images = DatasetHelpers.load_images(self.__outer_ref.data_directory) except FileNotFoundError as error: self.__outer_ref.log(f"Error loading files: {error}", "critical") self.__outer_ref.stop() async def on_start(self): self.__outer_ref.log(f"{self.__outer_ref.jid} starting fake detection. . .", "info") async def run(self): self.__outer_ref.log(f"{self.__outer_ref.jid} sending face image. . .", "info") image = self.__get_random_face_image() request = RecognitionRequest(str(self.__outer_ref.jid), self.__outer_ref.agent_location, self.__image_to_base64(image), self.__outer_ref.generate_outcome, base64encoded=True) data = str.encode(RecognitionRequest.serialize(request)) try: await self.__outer_ref._connection.write_data(data) except ConnectionError as error: self.__outer_ref.log(f"Error writing to connection: {error}", "critical") self.kill() self.__outer_ref.stop() self.__outer_ref.log(f"{self.__outer_ref.jid} done sending face image . . .", "info") async def on_end(self): self.__outer_ref.log(f"{self.__outer_ref.jid} ending fake detection. . .", "info") def __image_to_base64(self, image): byte = io.BytesIO() image.save(byte, 'JPEG') return codecs.encode(byte.getvalue(), 'base64').decode() def __get_random_face_image(self): return random.choice(self.__face_images) class ResponseReceiverBehavior(CyclicBehaviour): def __init__(self, outer_ref): super().__init__() self.__outer_ref: FakeDetectionAgent = outer_ref async def on_start(self): self.__outer_ref.log(f"{self.__outer_ref.jid} starting responses receiver. . .", "info") async def run(self): self.__outer_ref.log(f"{self.__outer_ref.jid} waiting for response. . .", "info") try: data = await self.__outer_ref._connection.read_data() if not data: self.kill() self.__outer_ref.log(f"{self.__outer_ref.jid} received: " f"{RecognitionResponse.deserialize(data)!r}", "info") except ConnectionError as error: self.__outer_ref.log(f"Error reading from connection: {error}", "critical") self.kill() self.__outer_ref.stop() self.__outer_ref.log(f"{self.__outer_ref.jid} done processing response . . .", "info") async def on_end(self): self.__outer_ref.log(f"{self.__outer_ref.jid} ending responses receiver. . .", "info") def __init__(self, jid: str, password: str, agent_location: str, data_directory: str, executor: ThreadPoolExecutor, recognition_system_ip: str, recognition_system_port: int, detection_interval: int = 1, generate_outcome: bool = False, message_checking_interval: int = 5, verify_security: bool = False): super().__init__(jid, password, executor, verify_security, message_checking_interval) self.__agent_location = agent_location self.__data_directory = data_directory self.__recognition_system_ip = recognition_system_ip self.__recognition_system_port = recognition_system_port self.__detection_interval = detection_interval self.__generate_outcome = generate_outcome self._connection: Connection @property def agent_location(self): return self.__agent_location @property def data_directory(self): return self.__data_directory @property def detection_interval(self): return self.__detection_interval @property def generate_outcome(self): return self.__generate_outcome @property def recognition_system_ip(self): return self.__recognition_system_ip @property def recognition_system_port(self): return self.__recognition_system_port async def setup(self): await super().setup() reader_stream, writer_stream = \ await asyncio.open_connection(self.__recognition_system_ip, self.__recognition_system_port) self._connection = Connection(str(self.jid), reader_stream, writer_stream) detection_behavior = self.FakeDetectionBehavior(self, self.detection_interval) receiver_behavior = self.ResponseReceiverBehavior(self) self.add_behaviour(detection_behavior) self.add_behaviour(receiver_behavior) def stop(self): self._connection.close() return super().stop()
none
1
2.337339
2
Day-1/code.py
vaithak/Advent-of-Code-2021
0
6620627
<filename>Day-1/code.py def F(win_size): prev_arr = [] prev_sum = 0 win_start_idx = 0 # essentially prev_arr is a circular window. increased_cnt = 0 with open('input.txt') as f: for x in f: x = int(x) if len(prev_arr) == win_size: diff_sum = (x - prev_arr[win_start_idx]) increased_cnt += diff_sum > 0 prev_sum += diff_sum prev_arr[win_start_idx] = x win_start_idx = (win_start_idx + 1)%win_size else: prev_arr.append(x) prev_sum += x print("\tlast number: ", x) print("\tcount : ", increased_cnt) print("Part 1:") F(1) print("Part 2:") F(3)
<filename>Day-1/code.py def F(win_size): prev_arr = [] prev_sum = 0 win_start_idx = 0 # essentially prev_arr is a circular window. increased_cnt = 0 with open('input.txt') as f: for x in f: x = int(x) if len(prev_arr) == win_size: diff_sum = (x - prev_arr[win_start_idx]) increased_cnt += diff_sum > 0 prev_sum += diff_sum prev_arr[win_start_idx] = x win_start_idx = (win_start_idx + 1)%win_size else: prev_arr.append(x) prev_sum += x print("\tlast number: ", x) print("\tcount : ", increased_cnt) print("Part 1:") F(1) print("Part 2:") F(3)
en
0.950773
# essentially prev_arr is a circular window.
3.398809
3
Joe #2 Monte-Carlo Control in Easy21/easy21.py
analog-rl/Easy21
6
6620628
from enum import Enum import copy import random random.seed(1) class State: def __init__(self, dealer_card, player_card, is_terminal=False): """ :type self.is_terminal: bool :type self.dealer: int :type self.player: int """ self.dealer = dealer_card.value self.player = player_card.value self.term = is_terminal self.r = 0 class Card: def __init__(self, force_black=False): """ :type self.value: int """ self.value = random.randint(1,10) self.absolute_value = self.value if force_black or random.randint(1,3) != 1: self.is_black = True else: self.is_black = False self.value = 0 - self.value self.is_red = not self.is_black class Actions(Enum): # Possible actions hit = 0 stick = 1 @staticmethod def to_action(n): return Actions.hit if n==0 else Actions.stick @staticmethod def as_int(a): return 0 if a == Actions.hit else 1 class Environment: def __init__(self): self.player_values_count = 21 self.dealer_values_count = 10 self.actions_count = 2 # number of possible actions def get_start_state(self): s = State(Card(True), Card(True)) return s def step(self, s, a): # type: (object, object) -> object """ :type s: State """ next_s = copy.copy(s) r = 0 if a == Actions.stick: while not next_s.term: next_s.dealer += Card().value if next_s.dealer < 1 or next_s.dealer > 21: next_s.term = True r = 1 elif next_s.dealer >= 17: next_s.term = True if next_s.dealer > next_s.player: r = -1 elif next_s.dealer < next_s.player: r = 1 else: next_s.player += Card().value if next_s.player < 1 or next_s.player > 21: next_s.term = True r = -1 next_s.r = r return next_s, r
from enum import Enum import copy import random random.seed(1) class State: def __init__(self, dealer_card, player_card, is_terminal=False): """ :type self.is_terminal: bool :type self.dealer: int :type self.player: int """ self.dealer = dealer_card.value self.player = player_card.value self.term = is_terminal self.r = 0 class Card: def __init__(self, force_black=False): """ :type self.value: int """ self.value = random.randint(1,10) self.absolute_value = self.value if force_black or random.randint(1,3) != 1: self.is_black = True else: self.is_black = False self.value = 0 - self.value self.is_red = not self.is_black class Actions(Enum): # Possible actions hit = 0 stick = 1 @staticmethod def to_action(n): return Actions.hit if n==0 else Actions.stick @staticmethod def as_int(a): return 0 if a == Actions.hit else 1 class Environment: def __init__(self): self.player_values_count = 21 self.dealer_values_count = 10 self.actions_count = 2 # number of possible actions def get_start_state(self): s = State(Card(True), Card(True)) return s def step(self, s, a): # type: (object, object) -> object """ :type s: State """ next_s = copy.copy(s) r = 0 if a == Actions.stick: while not next_s.term: next_s.dealer += Card().value if next_s.dealer < 1 or next_s.dealer > 21: next_s.term = True r = 1 elif next_s.dealer >= 17: next_s.term = True if next_s.dealer > next_s.player: r = -1 elif next_s.dealer < next_s.player: r = 1 else: next_s.player += Card().value if next_s.player < 1 or next_s.player > 21: next_s.term = True r = -1 next_s.r = r return next_s, r
en
0.47446
:type self.is_terminal: bool :type self.dealer: int :type self.player: int :type self.value: int # Possible actions # number of possible actions # type: (object, object) -> object :type s: State
3.447471
3
tasks/cv-fast-autocv/finetuning.py
vitoryeso/tasks
2
6620629
<filename>tasks/cv-fast-autocv/finetuning.py from checkpoint import TrainedModels from networks import CustomModule class FineTuning(): def __init__(self, model_archs, num_classes): self.model_archs = model_archs self.num_classes = num_classes self.trained_models = TrainedModels() def fine_tuning(self, model_arch): if model_arch in ['resnet18', 'resnet50']: model_conv = self.trained_models.get_model(model_arch) for param in model_conv.parameters(): param.requires_grad = False num_ftrs = model_conv.fc.in_features net_out = CustomModule(num_ftrs, self.num_classes) model_conv.fc = net_out if model_arch in ['vgg16']: model_conv = self.trained_models.get_model(model_arch) for param in model_conv.parameters(): param.requires_grad = False num_ftrs = model_conv.classifier[0].in_features net_out = CustomModule(num_ftrs, self.num_classes) model_conv.classifier = net_out return model_conv
<filename>tasks/cv-fast-autocv/finetuning.py from checkpoint import TrainedModels from networks import CustomModule class FineTuning(): def __init__(self, model_archs, num_classes): self.model_archs = model_archs self.num_classes = num_classes self.trained_models = TrainedModels() def fine_tuning(self, model_arch): if model_arch in ['resnet18', 'resnet50']: model_conv = self.trained_models.get_model(model_arch) for param in model_conv.parameters(): param.requires_grad = False num_ftrs = model_conv.fc.in_features net_out = CustomModule(num_ftrs, self.num_classes) model_conv.fc = net_out if model_arch in ['vgg16']: model_conv = self.trained_models.get_model(model_arch) for param in model_conv.parameters(): param.requires_grad = False num_ftrs = model_conv.classifier[0].in_features net_out = CustomModule(num_ftrs, self.num_classes) model_conv.classifier = net_out return model_conv
none
1
2.418703
2
tests/functional/test_validate.py
KOSASIH/submanager
2
6620630
<reponame>KOSASIH/submanager """Test that the validate-config command validates the configuration.""" # Future imports from __future__ import ( annotations, ) # Standard library imports from typing import ( Dict, Optional, Tuple, Type, Union, ) # Third party imports import pytest from typing_extensions import ( Final, ) # Local imports import submanager.enums import submanager.exceptions import submanager.models.config from submanager.types import ( ConfigDict, ) from tests.functional.conftest import ( CONFIG_EXTENSIONS_BAD, CONFIG_EXTENSIONS_GOOD, CONFIG_PATHS_OFFLINE, CONFIG_PATHS_ONLINE, RunAndCheckCLICallable, RunAndCheckDebugCallable, ) # ---- Types ---- RequestValues = Union[str, bool, None] RequestTuple = Union[Tuple[ConfigDict, RequestValues], ConfigDict] ExpectedTuple = Tuple[ str, Optional[Type[submanager.exceptions.SubManagerUserError]], ] ParamConfigs = Dict[str, Tuple[RequestTuple, ExpectedTuple]] # ---- Constants ---- # pylint: disable = consider-using-namedtuple-or-dataclass PSEUDORANDOM_STRING: Final[str] = "izouashbutyzyep" INT_VALUE: Final[int] = 42 # CLI constants VALIDATE_COMMAND: Final[str] = "validate-config" MINIMAL_ARGS: Final[list[str]] = ["", "--minimal"] INCLUDE_DISABLED_ARGS: Final[list[str]] = ["", "--include-disabled"] OFFLINE_ONLY_ARG: Final[str] = "--offline-only" OFFLINE_ONLY_ARGS: Final = [ OFFLINE_ONLY_ARG, pytest.param("", marks=[pytest.mark.online]), ] OFFLINE_ONLY_ARGS_SLOW: Final = [ OFFLINE_ONLY_ARG, pytest.param("", marks=[pytest.mark.slow, pytest.mark.online]), ] # Offline validation param configs VALIDATION_EXPECTED: Final[ExpectedTuple] = ( "validat", submanager.exceptions.ConfigValidationError, ) ACCOUNT_EXPECTED: Final[ExpectedTuple] = ( "account", submanager.exceptions.AccountConfigError, ) READONLY_EXPECTED: Final[ExpectedTuple] = ( "read", submanager.exceptions.RedditReadOnlyError, ) BAD_VALIDATE_OFFLINE_PARAMS: Final[ParamConfigs] = { "non_existent_key": ( {PSEUDORANDOM_STRING: PSEUDORANDOM_STRING}, VALIDATION_EXPECTED, ), "account_int": ( {"context_default": {"account": INT_VALUE}}, VALIDATION_EXPECTED, ), "account_nomatch": ( {"context_default": {"account": PSEUDORANDOM_STRING}}, VALIDATION_EXPECTED, ), "subreddit_int": ( {"context_default": {"subreddit": INT_VALUE}}, VALIDATION_EXPECTED, ), "subreddit_missing": ( {"context_default": {"subreddit": None}}, VALIDATION_EXPECTED, ), "clientid_missing": ( {"accounts": {"muskbot": {"config": {"client_id": None}}}}, ACCOUNT_EXPECTED, ), "sitename_nomatch": ( { "accounts": { "muskrat": {"config": {"site_name": PSEUDORANDOM_STRING}}, }, }, ACCOUNT_EXPECTED, ), "token_missing": ( {"accounts": {"muskbot": {"config": {"refresh_token": None}}}}, READONLY_EXPECTED, ), "pw_missing": ( {"accounts": {"muskrat": {"config": {"password": None}}}}, READONLY_EXPECTED, ), } # Onlne validation param configs NON_ACCESSIBLE_PAGE: Final[str] = "non_accessible_page" NON_MOD_SUBREDDIT: Final[str] = "SubManagerTesting2" NON_SUPPORTED_WIDGET: Final[str] = "Bad Type Widget" NON_WRITEABLE_PAGE: Final[str] = "non_writable_page" NON_WRITEABLE_WIDGET: Final[str] = "Test Widget" THREAD_ID_LINK: Final[str] = "oy6ju3" THREAD_ID_NOT_OP: Final[str] = "owu3jn" BAD_VALIDATE_ONLINE_PARAMS: Final[ParamConfigs] = { "placebo": ( ({}, True), ("succe", None), ), "client_id_bad": ( ( { "accounts": { "testbot": {"config": {"client_id": PSEUDORANDOM_STRING}}, }, }, True, ), ("scope", submanager.exceptions.ScopeCheckError), ), "subreddit_notfound": ( ( {"context_default": {"subreddit": PSEUDORANDOM_STRING}}, "sync_manager.items.menus.targets.old_reddit_menu", ), ("subreddit", submanager.exceptions.SubredditNotFoundError), ), "thread_source_notfound": ( ( { "thread_manager": { "items": { "cycle_thread": { "source": {"endpoint_name": PSEUDORANDOM_STRING}, }, }, }, }, "thread_manager.items.cycle_thread", ), ("found", submanager.exceptions.RedditObjectNotFoundError), ), "menu_notfound": ( ( { "sync_manager": { "items": { "menus": { "targets": { "new_reddit_menu": { "context": { "subreddit": NON_MOD_SUBREDDIT, }, }, }, }, }, }, }, "sync_manager.items.menus.targets.new_reddit_menu", ), ("create", submanager.exceptions.RedditObjectNotFoundError), ), "thread_notfound": ( ( { "sync_manager": { "items": { "sidebar_thread": { "targets": { "thread_target": { "endpoint_name": PSEUDORANDOM_STRING, }, }, }, }, }, }, "sync_manager.items.sidebar_thread.targets.thread_target", ), ("found", submanager.exceptions.RedditObjectNotFoundError), ), "thread_notop": ( ( { "sync_manager": { "items": { "sidebar_thread": { "targets": { "thread_target": { "endpoint_name": THREAD_ID_NOT_OP, }, }, }, }, }, }, "sync_manager.items.sidebar_thread.targets.thread_target", ), ("account", submanager.exceptions.NotOPError), ), "thread_wrong_type": ( ( { "sync_manager": { "items": { "sidebar_thread": { "targets": { "thread_target": { "endpoint_name": THREAD_ID_LINK, }, }, }, }, }, }, "sync_manager.items.sidebar_thread.targets.thread_target", ), ("link", submanager.exceptions.PostTypeError), ), "widget_notfound": ( ( { "sync_manager": { "items": { "sidebar_thread": { "targets": { "new_reddit_widget": { "endpoint_name": PSEUDORANDOM_STRING, }, }, }, }, }, }, "sync_manager.items.sidebar_thread.targets.new_reddit_widget", ), ("found", submanager.exceptions.RedditObjectNotFoundError), ), "widget_wrong_type": ( ( { "sync_manager": { "items": { "sidebar_thread": { "targets": { "new_reddit_widget": { "endpoint_name": NON_SUPPORTED_WIDGET, }, }, }, }, }, }, "sync_manager.items.sidebar_thread.targets.new_reddit_widget", ), ("type", submanager.exceptions.WidgetTypeError), ), "widget_notwriteable": ( ( { "sync_manager": { "items": { "sidebar_thread": { "targets": { "new_reddit_widget": { "endpoint_name": NON_WRITEABLE_WIDGET, "context": { "subreddit": NON_MOD_SUBREDDIT, }, }, }, }, }, }, }, "sync_manager.items.sidebar_thread.targets.new_reddit_widget", ), ("mod", submanager.exceptions.NotAModError), ), "wiki_notfound_source": ( ( { "sync_manager": { "items": { "cross_sub_sync": { "source": {"endpoint_name": PSEUDORANDOM_STRING}, }, }, }, }, "sync_manager.items.cross_sub_sync.targets.index_clone", ), ("found", submanager.exceptions.RedditObjectNotFoundError), ), "wiki_notaccessible_source": ( ( { "sync_manager": { "items": { "cross_sub_sync": { "source": {"endpoint_name": NON_ACCESSIBLE_PAGE}, }, }, }, }, "sync_manager.items.cross_sub_sync.targets.index_clone", ), ("access", submanager.exceptions.RedditObjectNotAccessibleError), ), "wiki_notfound_target": ( ( { "sync_manager": { "items": { "disabled_sync_item": { "targets": { "non_existent": { "endpoint_name": PSEUDORANDOM_STRING, }, }, }, }, }, }, "sync_manager.items.disabled_sync_item.targets.non_existent", ), ("found", submanager.exceptions.RedditObjectNotFoundError), ), "wiki_notaccessible_target": ( ( {}, "sync_manager.items.disabled_sync_item.targets.non_existent", ), ("access", submanager.exceptions.RedditObjectNotAccessibleError), ), "wiki_notwriteable_target": ( ( { "sync_manager": { "items": { "disabled_sync_item": { "targets": { "non_existent": { "endpoint_name": NON_WRITEABLE_PAGE, "context": { "subreddit": NON_MOD_SUBREDDIT, }, }, }, }, }, }, }, "sync_manager.items.disabled_sync_item.targets.non_existent", ), ("edit", submanager.exceptions.WikiPagePermissionError), ), } # ---- Tests ---- @pytest.mark.parametrize("include_disabled", INCLUDE_DISABLED_ARGS) @pytest.mark.parametrize("minimal", MINIMAL_ARGS) def test_generated_error( run_and_check_cli: RunAndCheckCLICallable, example_config: submanager.models.config.ConfigPaths, minimal: str, include_disabled: str, ) -> None: """Test that the generated config validates false.""" error_type: type[submanager.exceptions.SubManagerUserError] if minimal: error_type = submanager.exceptions.AccountConfigError else: error_type = submanager.exceptions.ConfigDefaultError run_and_check_cli( cli_args=[ VALIDATE_COMMAND, OFFLINE_ONLY_ARG, minimal, include_disabled, ], config_paths=example_config, check_text="account" if minimal else "default", check_code=submanager.enums.ExitCode.ERROR_USER, check_error=error_type, ) @pytest.mark.parametrize("temp_config_dir", ["", "missing_dir"], indirect=True) @pytest.mark.parametrize("minimal", MINIMAL_ARGS) def test_config_not_found( run_and_check_cli: RunAndCheckCLICallable, temp_config_paths: submanager.models.config.ConfigPaths, minimal: str, ) -> None: """Test that the config not being found validates false.""" run_and_check_cli( cli_args=[VALIDATE_COMMAND, OFFLINE_ONLY_ARG, minimal], config_paths=temp_config_paths, check_text="not found", check_code=submanager.enums.ExitCode.ERROR_USER, check_error=submanager.exceptions.ConfigNotFoundError, ) @pytest.mark.parametrize("minimal", MINIMAL_ARGS) @pytest.mark.parametrize( "temp_config_paths", CONFIG_EXTENSIONS_GOOD + CONFIG_EXTENSIONS_BAD, indirect=True, ) def test_config_empty_error( run_and_check_cli: RunAndCheckCLICallable, empty_config: submanager.models.config.ConfigPaths, minimal: str, ) -> None: """Test that validating a config file with an unknown extension errors.""" extension = empty_config.static.suffix.lstrip(".") check_error: type[submanager.exceptions.SubManagerUserError] if extension == "json": check_text = "pars" check_error = submanager.exceptions.ConfigParsingError elif extension in CONFIG_EXTENSIONS_GOOD: check_text = "empty" check_error = submanager.exceptions.ConfigEmptyError else: check_text = "extension" check_error = submanager.exceptions.ConfigExtensionError run_and_check_cli( cli_args=[VALIDATE_COMMAND, OFFLINE_ONLY_ARG, minimal], config_paths=empty_config, check_text=check_text, check_code=submanager.enums.ExitCode.ERROR_USER, check_error=check_error, ) @pytest.mark.parametrize("minimal", MINIMAL_ARGS) @pytest.mark.parametrize("temp_config_paths", ["json"], indirect=True) def test_config_list_error( run_and_check_cli: RunAndCheckCLICallable, list_config: submanager.models.config.ConfigPaths, minimal: str, ) -> None: """Test that a config file with the wrong data structure fails validate.""" run_and_check_cli( cli_args=[VALIDATE_COMMAND, OFFLINE_ONLY_ARG, minimal], config_paths=list_config, check_text="structure", check_code=submanager.enums.ExitCode.ERROR_USER, check_error=submanager.exceptions.ConfigDataTypeError, ) @pytest.mark.parametrize("include_disabled", INCLUDE_DISABLED_ARGS) @pytest.mark.parametrize("minimal", MINIMAL_ARGS) @pytest.mark.parametrize("file_config", CONFIG_PATHS_OFFLINE, indirect=True) def test_valid_offline( run_and_check_cli: RunAndCheckCLICallable, file_config: submanager.models.config.ConfigPaths, minimal: str, include_disabled: str, ) -> None: """Test that the test configs validate true in offline mode.""" run_and_check_cli( cli_args=[ VALIDATE_COMMAND, OFFLINE_ONLY_ARG, minimal, include_disabled, ], config_paths=file_config, check_text="succe", ) @pytest.mark.parametrize("minimal", MINIMAL_ARGS) @pytest.mark.parametrize("file_config", CONFIG_PATHS_OFFLINE, indirect=True) def test_parsing_error( run_and_check_cli: RunAndCheckCLICallable, file_config: submanager.models.config.ConfigPaths, minimal: str, ) -> None: """Test that config files with an invalid file format validate false.""" with open(file_config.static, encoding="utf-8") as config_file_read: config_file_text = config_file_read.read() config_file_text = config_file_text.replace('"', "", 1) with open( file_config.static, mode="w", encoding="utf-8", newline="\n", ) as config_file_write: config_file_write.write(config_file_text) run_and_check_cli( cli_args=[VALIDATE_COMMAND, OFFLINE_ONLY_ARG, minimal], config_paths=file_config, check_text="pars", check_code=submanager.enums.ExitCode.ERROR_USER, check_error=submanager.exceptions.ConfigParsingError, ) @pytest.mark.parametrize("minimal", MINIMAL_ARGS) @pytest.mark.parametrize( ("modified_config", "check_vars"), list(BAD_VALIDATE_OFFLINE_PARAMS.values()), ids=list(BAD_VALIDATE_OFFLINE_PARAMS.keys()), indirect=["modified_config"], ) @pytest.mark.parametrize("file_config", CONFIG_PATHS_OFFLINE, indirect=True) def test_value_error( run_and_check_cli: RunAndCheckCLICallable, modified_config: submanager.models.config.ConfigPaths, check_vars: ExpectedTuple, minimal: str, ) -> None: """Test that config files with a bad value validate false.""" check_text, check_error = check_vars cli_args = [VALIDATE_COMMAND, OFFLINE_ONLY_ARG, minimal] if minimal and ( check_error is None or (check_error == submanager.exceptions.RedditReadOnlyError) ): run_and_check_cli( cli_args=cli_args, config_paths=modified_config, check_text="succe", ) else: run_and_check_cli( cli_args=cli_args, config_paths=modified_config, check_text=check_text, check_code=submanager.enums.ExitCode.ERROR_USER, check_error=check_error, ) def test_debug_error( run_and_check_debug: RunAndCheckDebugCallable, ) -> None: """Test that --debug allows the error to bubble up and dump traceback.""" run_and_check_debug([VALIDATE_COMMAND, OFFLINE_ONLY_ARG]) @pytest.mark.parametrize("include_disabled", INCLUDE_DISABLED_ARGS) @pytest.mark.parametrize("offline_only", OFFLINE_ONLY_ARGS_SLOW) @pytest.mark.parametrize("file_config", CONFIG_PATHS_ONLINE, indirect=True) def test_valid_online( run_and_check_cli: RunAndCheckCLICallable, file_config: submanager.models.config.ConfigPaths, offline_only: str, include_disabled: str, ) -> None: """Test that the test configs validate true in offline mode.""" should_fail = bool(include_disabled and not offline_only) run_and_check_cli( cli_args=[VALIDATE_COMMAND, offline_only, include_disabled], config_paths=file_config, check_text="access" if should_fail else "succe", check_exits=should_fail, check_code=submanager.enums.ExitCode.ERROR_USER, check_error=submanager.exceptions.RedditObjectNotAccessibleError, ) @pytest.mark.parametrize("offline_only", OFFLINE_ONLY_ARGS) @pytest.mark.parametrize( ("modified_config", "check_vars"), list(BAD_VALIDATE_ONLINE_PARAMS.values()), ids=list(BAD_VALIDATE_ONLINE_PARAMS.keys()), indirect=["modified_config"], ) @pytest.mark.parametrize("file_config", CONFIG_PATHS_ONLINE, indirect=True) def test_online_error( run_and_check_cli: RunAndCheckCLICallable, modified_config: submanager.models.config.ConfigPaths, check_vars: ExpectedTuple, offline_only: str, ) -> None: """Test that config files that produce Reddit errors validate false.""" check_text, check_error = check_vars cli_args = [VALIDATE_COMMAND, offline_only] if offline_only or check_error is None: run_and_check_cli( cli_args=cli_args, config_paths=modified_config, check_text="succe", ) else: run_and_check_cli( cli_args=cli_args, config_paths=modified_config, check_text=check_text, check_code=submanager.enums.ExitCode.ERROR_USER, check_error=check_error, )
"""Test that the validate-config command validates the configuration.""" # Future imports from __future__ import ( annotations, ) # Standard library imports from typing import ( Dict, Optional, Tuple, Type, Union, ) # Third party imports import pytest from typing_extensions import ( Final, ) # Local imports import submanager.enums import submanager.exceptions import submanager.models.config from submanager.types import ( ConfigDict, ) from tests.functional.conftest import ( CONFIG_EXTENSIONS_BAD, CONFIG_EXTENSIONS_GOOD, CONFIG_PATHS_OFFLINE, CONFIG_PATHS_ONLINE, RunAndCheckCLICallable, RunAndCheckDebugCallable, ) # ---- Types ---- RequestValues = Union[str, bool, None] RequestTuple = Union[Tuple[ConfigDict, RequestValues], ConfigDict] ExpectedTuple = Tuple[ str, Optional[Type[submanager.exceptions.SubManagerUserError]], ] ParamConfigs = Dict[str, Tuple[RequestTuple, ExpectedTuple]] # ---- Constants ---- # pylint: disable = consider-using-namedtuple-or-dataclass PSEUDORANDOM_STRING: Final[str] = "izouashbutyzyep" INT_VALUE: Final[int] = 42 # CLI constants VALIDATE_COMMAND: Final[str] = "validate-config" MINIMAL_ARGS: Final[list[str]] = ["", "--minimal"] INCLUDE_DISABLED_ARGS: Final[list[str]] = ["", "--include-disabled"] OFFLINE_ONLY_ARG: Final[str] = "--offline-only" OFFLINE_ONLY_ARGS: Final = [ OFFLINE_ONLY_ARG, pytest.param("", marks=[pytest.mark.online]), ] OFFLINE_ONLY_ARGS_SLOW: Final = [ OFFLINE_ONLY_ARG, pytest.param("", marks=[pytest.mark.slow, pytest.mark.online]), ] # Offline validation param configs VALIDATION_EXPECTED: Final[ExpectedTuple] = ( "validat", submanager.exceptions.ConfigValidationError, ) ACCOUNT_EXPECTED: Final[ExpectedTuple] = ( "account", submanager.exceptions.AccountConfigError, ) READONLY_EXPECTED: Final[ExpectedTuple] = ( "read", submanager.exceptions.RedditReadOnlyError, ) BAD_VALIDATE_OFFLINE_PARAMS: Final[ParamConfigs] = { "non_existent_key": ( {PSEUDORANDOM_STRING: PSEUDORANDOM_STRING}, VALIDATION_EXPECTED, ), "account_int": ( {"context_default": {"account": INT_VALUE}}, VALIDATION_EXPECTED, ), "account_nomatch": ( {"context_default": {"account": PSEUDORANDOM_STRING}}, VALIDATION_EXPECTED, ), "subreddit_int": ( {"context_default": {"subreddit": INT_VALUE}}, VALIDATION_EXPECTED, ), "subreddit_missing": ( {"context_default": {"subreddit": None}}, VALIDATION_EXPECTED, ), "clientid_missing": ( {"accounts": {"muskbot": {"config": {"client_id": None}}}}, ACCOUNT_EXPECTED, ), "sitename_nomatch": ( { "accounts": { "muskrat": {"config": {"site_name": PSEUDORANDOM_STRING}}, }, }, ACCOUNT_EXPECTED, ), "token_missing": ( {"accounts": {"muskbot": {"config": {"refresh_token": None}}}}, READONLY_EXPECTED, ), "pw_missing": ( {"accounts": {"muskrat": {"config": {"password": None}}}}, READONLY_EXPECTED, ), } # Onlne validation param configs NON_ACCESSIBLE_PAGE: Final[str] = "non_accessible_page" NON_MOD_SUBREDDIT: Final[str] = "SubManagerTesting2" NON_SUPPORTED_WIDGET: Final[str] = "Bad Type Widget" NON_WRITEABLE_PAGE: Final[str] = "non_writable_page" NON_WRITEABLE_WIDGET: Final[str] = "Test Widget" THREAD_ID_LINK: Final[str] = "oy6ju3" THREAD_ID_NOT_OP: Final[str] = "owu3jn" BAD_VALIDATE_ONLINE_PARAMS: Final[ParamConfigs] = { "placebo": ( ({}, True), ("succe", None), ), "client_id_bad": ( ( { "accounts": { "testbot": {"config": {"client_id": PSEUDORANDOM_STRING}}, }, }, True, ), ("scope", submanager.exceptions.ScopeCheckError), ), "subreddit_notfound": ( ( {"context_default": {"subreddit": PSEUDORANDOM_STRING}}, "sync_manager.items.menus.targets.old_reddit_menu", ), ("subreddit", submanager.exceptions.SubredditNotFoundError), ), "thread_source_notfound": ( ( { "thread_manager": { "items": { "cycle_thread": { "source": {"endpoint_name": PSEUDORANDOM_STRING}, }, }, }, }, "thread_manager.items.cycle_thread", ), ("found", submanager.exceptions.RedditObjectNotFoundError), ), "menu_notfound": ( ( { "sync_manager": { "items": { "menus": { "targets": { "new_reddit_menu": { "context": { "subreddit": NON_MOD_SUBREDDIT, }, }, }, }, }, }, }, "sync_manager.items.menus.targets.new_reddit_menu", ), ("create", submanager.exceptions.RedditObjectNotFoundError), ), "thread_notfound": ( ( { "sync_manager": { "items": { "sidebar_thread": { "targets": { "thread_target": { "endpoint_name": PSEUDORANDOM_STRING, }, }, }, }, }, }, "sync_manager.items.sidebar_thread.targets.thread_target", ), ("found", submanager.exceptions.RedditObjectNotFoundError), ), "thread_notop": ( ( { "sync_manager": { "items": { "sidebar_thread": { "targets": { "thread_target": { "endpoint_name": THREAD_ID_NOT_OP, }, }, }, }, }, }, "sync_manager.items.sidebar_thread.targets.thread_target", ), ("account", submanager.exceptions.NotOPError), ), "thread_wrong_type": ( ( { "sync_manager": { "items": { "sidebar_thread": { "targets": { "thread_target": { "endpoint_name": THREAD_ID_LINK, }, }, }, }, }, }, "sync_manager.items.sidebar_thread.targets.thread_target", ), ("link", submanager.exceptions.PostTypeError), ), "widget_notfound": ( ( { "sync_manager": { "items": { "sidebar_thread": { "targets": { "new_reddit_widget": { "endpoint_name": PSEUDORANDOM_STRING, }, }, }, }, }, }, "sync_manager.items.sidebar_thread.targets.new_reddit_widget", ), ("found", submanager.exceptions.RedditObjectNotFoundError), ), "widget_wrong_type": ( ( { "sync_manager": { "items": { "sidebar_thread": { "targets": { "new_reddit_widget": { "endpoint_name": NON_SUPPORTED_WIDGET, }, }, }, }, }, }, "sync_manager.items.sidebar_thread.targets.new_reddit_widget", ), ("type", submanager.exceptions.WidgetTypeError), ), "widget_notwriteable": ( ( { "sync_manager": { "items": { "sidebar_thread": { "targets": { "new_reddit_widget": { "endpoint_name": NON_WRITEABLE_WIDGET, "context": { "subreddit": NON_MOD_SUBREDDIT, }, }, }, }, }, }, }, "sync_manager.items.sidebar_thread.targets.new_reddit_widget", ), ("mod", submanager.exceptions.NotAModError), ), "wiki_notfound_source": ( ( { "sync_manager": { "items": { "cross_sub_sync": { "source": {"endpoint_name": PSEUDORANDOM_STRING}, }, }, }, }, "sync_manager.items.cross_sub_sync.targets.index_clone", ), ("found", submanager.exceptions.RedditObjectNotFoundError), ), "wiki_notaccessible_source": ( ( { "sync_manager": { "items": { "cross_sub_sync": { "source": {"endpoint_name": NON_ACCESSIBLE_PAGE}, }, }, }, }, "sync_manager.items.cross_sub_sync.targets.index_clone", ), ("access", submanager.exceptions.RedditObjectNotAccessibleError), ), "wiki_notfound_target": ( ( { "sync_manager": { "items": { "disabled_sync_item": { "targets": { "non_existent": { "endpoint_name": PSEUDORANDOM_STRING, }, }, }, }, }, }, "sync_manager.items.disabled_sync_item.targets.non_existent", ), ("found", submanager.exceptions.RedditObjectNotFoundError), ), "wiki_notaccessible_target": ( ( {}, "sync_manager.items.disabled_sync_item.targets.non_existent", ), ("access", submanager.exceptions.RedditObjectNotAccessibleError), ), "wiki_notwriteable_target": ( ( { "sync_manager": { "items": { "disabled_sync_item": { "targets": { "non_existent": { "endpoint_name": NON_WRITEABLE_PAGE, "context": { "subreddit": NON_MOD_SUBREDDIT, }, }, }, }, }, }, }, "sync_manager.items.disabled_sync_item.targets.non_existent", ), ("edit", submanager.exceptions.WikiPagePermissionError), ), } # ---- Tests ---- @pytest.mark.parametrize("include_disabled", INCLUDE_DISABLED_ARGS) @pytest.mark.parametrize("minimal", MINIMAL_ARGS) def test_generated_error( run_and_check_cli: RunAndCheckCLICallable, example_config: submanager.models.config.ConfigPaths, minimal: str, include_disabled: str, ) -> None: """Test that the generated config validates false.""" error_type: type[submanager.exceptions.SubManagerUserError] if minimal: error_type = submanager.exceptions.AccountConfigError else: error_type = submanager.exceptions.ConfigDefaultError run_and_check_cli( cli_args=[ VALIDATE_COMMAND, OFFLINE_ONLY_ARG, minimal, include_disabled, ], config_paths=example_config, check_text="account" if minimal else "default", check_code=submanager.enums.ExitCode.ERROR_USER, check_error=error_type, ) @pytest.mark.parametrize("temp_config_dir", ["", "missing_dir"], indirect=True) @pytest.mark.parametrize("minimal", MINIMAL_ARGS) def test_config_not_found( run_and_check_cli: RunAndCheckCLICallable, temp_config_paths: submanager.models.config.ConfigPaths, minimal: str, ) -> None: """Test that the config not being found validates false.""" run_and_check_cli( cli_args=[VALIDATE_COMMAND, OFFLINE_ONLY_ARG, minimal], config_paths=temp_config_paths, check_text="not found", check_code=submanager.enums.ExitCode.ERROR_USER, check_error=submanager.exceptions.ConfigNotFoundError, ) @pytest.mark.parametrize("minimal", MINIMAL_ARGS) @pytest.mark.parametrize( "temp_config_paths", CONFIG_EXTENSIONS_GOOD + CONFIG_EXTENSIONS_BAD, indirect=True, ) def test_config_empty_error( run_and_check_cli: RunAndCheckCLICallable, empty_config: submanager.models.config.ConfigPaths, minimal: str, ) -> None: """Test that validating a config file with an unknown extension errors.""" extension = empty_config.static.suffix.lstrip(".") check_error: type[submanager.exceptions.SubManagerUserError] if extension == "json": check_text = "pars" check_error = submanager.exceptions.ConfigParsingError elif extension in CONFIG_EXTENSIONS_GOOD: check_text = "empty" check_error = submanager.exceptions.ConfigEmptyError else: check_text = "extension" check_error = submanager.exceptions.ConfigExtensionError run_and_check_cli( cli_args=[VALIDATE_COMMAND, OFFLINE_ONLY_ARG, minimal], config_paths=empty_config, check_text=check_text, check_code=submanager.enums.ExitCode.ERROR_USER, check_error=check_error, ) @pytest.mark.parametrize("minimal", MINIMAL_ARGS) @pytest.mark.parametrize("temp_config_paths", ["json"], indirect=True) def test_config_list_error( run_and_check_cli: RunAndCheckCLICallable, list_config: submanager.models.config.ConfigPaths, minimal: str, ) -> None: """Test that a config file with the wrong data structure fails validate.""" run_and_check_cli( cli_args=[VALIDATE_COMMAND, OFFLINE_ONLY_ARG, minimal], config_paths=list_config, check_text="structure", check_code=submanager.enums.ExitCode.ERROR_USER, check_error=submanager.exceptions.ConfigDataTypeError, ) @pytest.mark.parametrize("include_disabled", INCLUDE_DISABLED_ARGS) @pytest.mark.parametrize("minimal", MINIMAL_ARGS) @pytest.mark.parametrize("file_config", CONFIG_PATHS_OFFLINE, indirect=True) def test_valid_offline( run_and_check_cli: RunAndCheckCLICallable, file_config: submanager.models.config.ConfigPaths, minimal: str, include_disabled: str, ) -> None: """Test that the test configs validate true in offline mode.""" run_and_check_cli( cli_args=[ VALIDATE_COMMAND, OFFLINE_ONLY_ARG, minimal, include_disabled, ], config_paths=file_config, check_text="succe", ) @pytest.mark.parametrize("minimal", MINIMAL_ARGS) @pytest.mark.parametrize("file_config", CONFIG_PATHS_OFFLINE, indirect=True) def test_parsing_error( run_and_check_cli: RunAndCheckCLICallable, file_config: submanager.models.config.ConfigPaths, minimal: str, ) -> None: """Test that config files with an invalid file format validate false.""" with open(file_config.static, encoding="utf-8") as config_file_read: config_file_text = config_file_read.read() config_file_text = config_file_text.replace('"', "", 1) with open( file_config.static, mode="w", encoding="utf-8", newline="\n", ) as config_file_write: config_file_write.write(config_file_text) run_and_check_cli( cli_args=[VALIDATE_COMMAND, OFFLINE_ONLY_ARG, minimal], config_paths=file_config, check_text="pars", check_code=submanager.enums.ExitCode.ERROR_USER, check_error=submanager.exceptions.ConfigParsingError, ) @pytest.mark.parametrize("minimal", MINIMAL_ARGS) @pytest.mark.parametrize( ("modified_config", "check_vars"), list(BAD_VALIDATE_OFFLINE_PARAMS.values()), ids=list(BAD_VALIDATE_OFFLINE_PARAMS.keys()), indirect=["modified_config"], ) @pytest.mark.parametrize("file_config", CONFIG_PATHS_OFFLINE, indirect=True) def test_value_error( run_and_check_cli: RunAndCheckCLICallable, modified_config: submanager.models.config.ConfigPaths, check_vars: ExpectedTuple, minimal: str, ) -> None: """Test that config files with a bad value validate false.""" check_text, check_error = check_vars cli_args = [VALIDATE_COMMAND, OFFLINE_ONLY_ARG, minimal] if minimal and ( check_error is None or (check_error == submanager.exceptions.RedditReadOnlyError) ): run_and_check_cli( cli_args=cli_args, config_paths=modified_config, check_text="succe", ) else: run_and_check_cli( cli_args=cli_args, config_paths=modified_config, check_text=check_text, check_code=submanager.enums.ExitCode.ERROR_USER, check_error=check_error, ) def test_debug_error( run_and_check_debug: RunAndCheckDebugCallable, ) -> None: """Test that --debug allows the error to bubble up and dump traceback.""" run_and_check_debug([VALIDATE_COMMAND, OFFLINE_ONLY_ARG]) @pytest.mark.parametrize("include_disabled", INCLUDE_DISABLED_ARGS) @pytest.mark.parametrize("offline_only", OFFLINE_ONLY_ARGS_SLOW) @pytest.mark.parametrize("file_config", CONFIG_PATHS_ONLINE, indirect=True) def test_valid_online( run_and_check_cli: RunAndCheckCLICallable, file_config: submanager.models.config.ConfigPaths, offline_only: str, include_disabled: str, ) -> None: """Test that the test configs validate true in offline mode.""" should_fail = bool(include_disabled and not offline_only) run_and_check_cli( cli_args=[VALIDATE_COMMAND, offline_only, include_disabled], config_paths=file_config, check_text="access" if should_fail else "succe", check_exits=should_fail, check_code=submanager.enums.ExitCode.ERROR_USER, check_error=submanager.exceptions.RedditObjectNotAccessibleError, ) @pytest.mark.parametrize("offline_only", OFFLINE_ONLY_ARGS) @pytest.mark.parametrize( ("modified_config", "check_vars"), list(BAD_VALIDATE_ONLINE_PARAMS.values()), ids=list(BAD_VALIDATE_ONLINE_PARAMS.keys()), indirect=["modified_config"], ) @pytest.mark.parametrize("file_config", CONFIG_PATHS_ONLINE, indirect=True) def test_online_error( run_and_check_cli: RunAndCheckCLICallable, modified_config: submanager.models.config.ConfigPaths, check_vars: ExpectedTuple, offline_only: str, ) -> None: """Test that config files that produce Reddit errors validate false.""" check_text, check_error = check_vars cli_args = [VALIDATE_COMMAND, offline_only] if offline_only or check_error is None: run_and_check_cli( cli_args=cli_args, config_paths=modified_config, check_text="succe", ) else: run_and_check_cli( cli_args=cli_args, config_paths=modified_config, check_text=check_text, check_code=submanager.enums.ExitCode.ERROR_USER, check_error=check_error, )
en
0.647872
Test that the validate-config command validates the configuration. # Future imports # Standard library imports # Third party imports # Local imports # ---- Types ---- # ---- Constants ---- # pylint: disable = consider-using-namedtuple-or-dataclass # CLI constants # Offline validation param configs # Onlne validation param configs # ---- Tests ---- Test that the generated config validates false. Test that the config not being found validates false. Test that validating a config file with an unknown extension errors. Test that a config file with the wrong data structure fails validate. Test that the test configs validate true in offline mode. Test that config files with an invalid file format validate false. Test that config files with a bad value validate false. Test that --debug allows the error to bubble up and dump traceback. Test that the test configs validate true in offline mode. Test that config files that produce Reddit errors validate false.
2.058074
2
demos/prey-predator/run.py
calvbore/demos
1
6620631
<filename>demos/prey-predator/run.py # The following imports NEED to be in the exact order from cadCAD.engine import ExecutionMode, ExecutionContext, Executor # Simulation configs, input any new simulations here from prey_predator_sd import config from prey_predator_abm import config #from {new_simulation} import config from cadCAD import configs import pandas as pd def run(drop_midsteps: bool=True) -> pd.DataFrame: """ Run all experiments and return their output on the dataset column. Each line represents an iteration of the parameter-sweep combinations. """ exec_mode = ExecutionMode() exec_context = ExecutionContext(exec_mode.local_mode) run = Executor(exec_context=exec_context, configs=configs) results = pd.DataFrame() (system_events, tensor_field, sessions) = run.execute() df = pd.DataFrame(system_events) results = [] for i, (_, subset_df) in enumerate(df.groupby(["simulation", "subset"])): params = configs[i].sim_config['M'] result_record = pd.DataFrame.from_records([tuple([i for i in params.values()])], columns=list(params.keys())) # keep only last substep of each timestep if drop_midsteps: max_substep = max(subset_df.substep) is_droppable = (subset_df.substep != max_substep) is_droppable &= (subset_df.substep != 0) subset_df = subset_df.loc[~is_droppable] result_record['dataset'] = [subset_df] results.append(result_record) return pd.concat(results).reset_index()
<filename>demos/prey-predator/run.py # The following imports NEED to be in the exact order from cadCAD.engine import ExecutionMode, ExecutionContext, Executor # Simulation configs, input any new simulations here from prey_predator_sd import config from prey_predator_abm import config #from {new_simulation} import config from cadCAD import configs import pandas as pd def run(drop_midsteps: bool=True) -> pd.DataFrame: """ Run all experiments and return their output on the dataset column. Each line represents an iteration of the parameter-sweep combinations. """ exec_mode = ExecutionMode() exec_context = ExecutionContext(exec_mode.local_mode) run = Executor(exec_context=exec_context, configs=configs) results = pd.DataFrame() (system_events, tensor_field, sessions) = run.execute() df = pd.DataFrame(system_events) results = [] for i, (_, subset_df) in enumerate(df.groupby(["simulation", "subset"])): params = configs[i].sim_config['M'] result_record = pd.DataFrame.from_records([tuple([i for i in params.values()])], columns=list(params.keys())) # keep only last substep of each timestep if drop_midsteps: max_substep = max(subset_df.substep) is_droppable = (subset_df.substep != max_substep) is_droppable &= (subset_df.substep != 0) subset_df = subset_df.loc[~is_droppable] result_record['dataset'] = [subset_df] results.append(result_record) return pd.concat(results).reset_index()
en
0.727511
# The following imports NEED to be in the exact order # Simulation configs, input any new simulations here #from {new_simulation} import config Run all experiments and return their output on the dataset column. Each line represents an iteration of the parameter-sweep combinations. # keep only last substep of each timestep
2.316818
2
sequentialSearch.py
adenosinew/algorithms
0
6620632
<reponame>adenosinew/algorithms<filename>sequentialSearch.py def sequentialSearch(alist, item): pos = 0 found = False while pos < len(alist) and not found: if alist[pos] == item: found = True else: pos = pos + 1 return found testlist = [1,2,3,4,8,32,35,14,6,0] print(sequentialSearch(testlist, 3))
def sequentialSearch(alist, item): pos = 0 found = False while pos < len(alist) and not found: if alist[pos] == item: found = True else: pos = pos + 1 return found testlist = [1,2,3,4,8,32,35,14,6,0] print(sequentialSearch(testlist, 3))
none
1
3.922633
4
utils/json_aggregator.py
eolecvk/intro_spark_twitter
1
6620633
<reponame>eolecvk/intro_spark_twitter def jsonfiles_to_json(indir_path, outfile_path): """ Group a collection of json objects in individividual files into a single json file, one line per json object cf https://docs.databricks.com/spark/latest/data-sources/read-json.html """ import os import simplejson as json # Generate list of tweet file full paths fpaths = [os.path.join(indir_path, fname) for fname in os.listdir(indir_path)] # Define list of tweets to write in output file result = [] # Open each tweet file and get relevant fields for fpath in fpaths: try: with open(fpath, 'r') as fp: tweet = json.load(fp) tweet_id = tweet['id'] user_id = tweet['user']['id'] text = (tweet['text'] .replace('\n',' ') .replace('\t',' ') .replace('\r',' ') .replace('"',' ')) new_record = { "tweet_id" : tweet_id, "user_id" : user_id, "text" : text } new_record_str = json.dumps(new_record, separators=(',', ':')) result.append(new_record_str) except Exception as e: print(e) continue # Write list of json objects to file (one obj per line) with open(outfile_path, 'w') as fp: for line in result: fp.write(line + '\n') def jsonfiles_to_csv(dirpath, tsvpath): """ inputs: + dirpath : full path of dir that contains the tweets .json file + csvpath : full path of output tsv file Compiles a collection of tweets as a tsv file. The tweet fields that are kept include: `user_id`, `tweet_id`, and `tweet_text` """ import os import csv # Generate list of tweet file full paths fpaths = [os.path.join(dirpath, fname) for fname in os.listdir(dirpath)] # Define result list (to be written to output file) result = [] # Open each tweet file and get relevant fields for fpath in fpaths: try: with open(fpath, 'r') as fp: tweet = json.load(fp) tweet_id = tweet['id'] user_id = tweet['user']['id'] text = (tweet['text'] .replace('\n',' ') .replace('\t',' ') .replace('\r',' ') .replace('"',' ')) new_record = (tweet_id, user_id, text) result.append(new_record) except Exception as e: print(e) print("Issue with file: [{}]".format(fpath)) # Save output to .tsv file with open(tsvpath, 'w') as fp: wr = csv.writer(fp, delimiter='\t') wr.writerows(result) # ----------------------------------------------------------------------- if __name__ == "__main__": dirpath = "FULL/PATH/TO/INPUT/TWEET/DIR" outpath = "FULL/PATH/TO/OUTPUT/JSON/FILE" jsonfiles_to_json(dirpath, outpath)
def jsonfiles_to_json(indir_path, outfile_path): """ Group a collection of json objects in individividual files into a single json file, one line per json object cf https://docs.databricks.com/spark/latest/data-sources/read-json.html """ import os import simplejson as json # Generate list of tweet file full paths fpaths = [os.path.join(indir_path, fname) for fname in os.listdir(indir_path)] # Define list of tweets to write in output file result = [] # Open each tweet file and get relevant fields for fpath in fpaths: try: with open(fpath, 'r') as fp: tweet = json.load(fp) tweet_id = tweet['id'] user_id = tweet['user']['id'] text = (tweet['text'] .replace('\n',' ') .replace('\t',' ') .replace('\r',' ') .replace('"',' ')) new_record = { "tweet_id" : tweet_id, "user_id" : user_id, "text" : text } new_record_str = json.dumps(new_record, separators=(',', ':')) result.append(new_record_str) except Exception as e: print(e) continue # Write list of json objects to file (one obj per line) with open(outfile_path, 'w') as fp: for line in result: fp.write(line + '\n') def jsonfiles_to_csv(dirpath, tsvpath): """ inputs: + dirpath : full path of dir that contains the tweets .json file + csvpath : full path of output tsv file Compiles a collection of tweets as a tsv file. The tweet fields that are kept include: `user_id`, `tweet_id`, and `tweet_text` """ import os import csv # Generate list of tweet file full paths fpaths = [os.path.join(dirpath, fname) for fname in os.listdir(dirpath)] # Define result list (to be written to output file) result = [] # Open each tweet file and get relevant fields for fpath in fpaths: try: with open(fpath, 'r') as fp: tweet = json.load(fp) tweet_id = tweet['id'] user_id = tweet['user']['id'] text = (tweet['text'] .replace('\n',' ') .replace('\t',' ') .replace('\r',' ') .replace('"',' ')) new_record = (tweet_id, user_id, text) result.append(new_record) except Exception as e: print(e) print("Issue with file: [{}]".format(fpath)) # Save output to .tsv file with open(tsvpath, 'w') as fp: wr = csv.writer(fp, delimiter='\t') wr.writerows(result) # ----------------------------------------------------------------------- if __name__ == "__main__": dirpath = "FULL/PATH/TO/INPUT/TWEET/DIR" outpath = "FULL/PATH/TO/OUTPUT/JSON/FILE" jsonfiles_to_json(dirpath, outpath)
en
0.708111
Group a collection of json objects in individividual files into a single json file, one line per json object cf https://docs.databricks.com/spark/latest/data-sources/read-json.html # Generate list of tweet file full paths # Define list of tweets to write in output file # Open each tweet file and get relevant fields # Write list of json objects to file (one obj per line) inputs: + dirpath : full path of dir that contains the tweets .json file + csvpath : full path of output tsv file Compiles a collection of tweets as a tsv file. The tweet fields that are kept include: `user_id`, `tweet_id`, and `tweet_text` # Generate list of tweet file full paths # Define result list (to be written to output file) # Open each tweet file and get relevant fields # Save output to .tsv file # -----------------------------------------------------------------------
3.453315
3
src/genie/libs/parser/iosxr/show_media.py
deepB123/genieparser
0
6620634
<filename>src/genie/libs/parser/iosxr/show_media.py ''' show_media.py IOSXR parsers for the following show commands: * 'show media' * 'show filesystem' * 'show controllers fabric plane all' ''' from genie.metaparser import MetaParser from genie.metaparser.util.schemaengine import Any, Or, Optional import re # ======================================================= # Schema for `show media` # ======================================================== class ShowMediaSchema(MetaParser): schema = { 'partition': { Any(): { 'size': str, 'used': str, 'percent': str, 'avail': str, } } } class ShowMedia(ShowMediaSchema): """Parser for show media interface on iosxr routers parser class - implements detail parsing mechanisms for cli output. """ cli_command = 'show media' """ Tue Apr 13 18:43:17.452 UTC Media info for node0_RP0_CPU0 ------------------------------------------------------------ Partition Size Used Percent Avail disk2: 3.8G 945M 25% 2.9G disk0: 3.4G 9.6M 1% 3.2G /var/lib/docker 5.6G 12M 1% 5.3G harddisk: 51G 1016M 3% 48G log: 4.5G 253M 6% 4.0G ------------------------------------------------------------ log: = system log files (read-only) """ def cli(self, output=None): if output is None: out = self.device.execute(self.cli_command) else: out = output media_dict = {} result_dict = {} """ Variables Parsed: partition = Partition size = Size used = Used percent = Percent avail = Avail """ p0 = re.compile(r'^(?P<partition>(\w+:|\/\S+))\s+(?P<size>\S+)\s+(?P<used>\S+)\s+(?P<percent>\d+%)\s+(?P<avail>\S+)$') for line in out.splitlines(): line = line.strip() m = p0.match(line) if m: if 'partition' not in media_dict: result_dict = media_dict.setdefault('partition',{}) size = m.groupdict()['size'] used = m.groupdict()['used'] percent = m.groupdict()['percent'] avail = m.groupdict()['avail'] partition = m.groupdict()['partition'] result_dict[partition] = {} result_dict[partition]['size'] = size result_dict[partition]['used'] = used result_dict[partition]['percent'] = percent result_dict[partition]['avail'] = avail continue return media_dict # ========================== # Parser for 'show filesystem' # ========================== # ======================================================= # Schema for `show filesystem` # ======================================================== class FileSystemSchema(MetaParser): schema = { 'prefixes': { Any(): { 'size': str, 'free': str, 'type': str, 'flags': str, } } } class ShowFileSystem(FileSystemSchema): """Parser for show filesystem interface on iosxr routers parser class - implements detail parsing mechanisms for cli output. """ cli_command = 'show filesystem' """ Fri Apr 16 21:22:35.610 UTC File Systems: Size(b) Free(b) Type Flags Prefixes 48648003584 42960728064 flash rw /misc/config 0 0 network rw tftp: 4008443904 3018457088 flash-disk rw disk2: 0 0 network rw ftp: 54744576000 53680197632 harddisk rw harddisk: 3590602752 3580395520 flash-disk rw disk0: """ def cli(self, output=None): if output is None: out = self.device.execute(self.cli_command) else: out = output filesystem_dict = {} result_dict = {} """ Variables Parsed: size = Size free = Free type = Type flags = Flags prefixes = Prefixes """ p0 = re.compile(r'^(?P<size>\s*\d+)\s+(?P<free>\d+)\s+(?P<type>(\w+|\w+-\w+))\s+(?P<flags>\w+)\s+(?P<prefixes>(\w+:|.?\w+)*)') for line in out.splitlines(): line = line.strip() m = p0.match(line) if m: if 'prefixes' not in filesystem_dict: result_dict = filesystem_dict.setdefault('prefixes',{}) size = m.groupdict()['size'] free = m.groupdict()['free'] type_ = m.groupdict()['type'] flags = m.groupdict()['flags'] prefixes = m.groupdict()['prefixes'] result_dict[prefixes] = {} result_dict[prefixes]['size'] = size result_dict[prefixes]['free'] = free result_dict[prefixes]['type'] = type_ result_dict[prefixes]['flags'] = flags continue return filesystem_dict # ========================== # Parser for 'show controllers fabric plane all' # ========================== # ======================================================= # Schema for `show controllers fabric plane all` # ======================================================== class ControllersFabricPlaneAllSchema(MetaParser): schema = { 'plane_id': { Any(): { 'admin_state': str, 'plane_state': str, 'ud_counter': str, 'mcast_counter': str, } } } class ShowControllersFabricPlaneAll(ControllersFabricPlaneAllSchema): """Parser for show controller fabric plane all interface on iosxr routers parser class - implements detail parsing mechanisms for cli output. """ cli_command = 'show controllers fabric plane all' """ Thu Jul 30 13:16:17.593 UTC Plane Admin Plane up->dn up->mcast Id State State counter counter -------------------------------------- 0 UP UP 0 0 1 UP UP 0 0 2 UP DN 0 0 3 UP DN 0 0 4 UP DN 0 0 5 UP DN 0 0 6 UP DN 0 0 7 UP DN 0 0 """ def cli(self, output=None): if output is None: out = self.device.execute(self.cli_command) else: out = output cfabric_dict = {} result_dict = {} """ Variables Parsed: plane_id = Plane ID admin_state = Admin State plane_state = Plane State ud_counter = up->down counter mcast_counter = mcast counter """ p0 = re.compile(r'^(?P<plane_id>\d+)\s+(?P<admin_state>\w+)\s+(?P<plane_state>\w+)\s+(?P<ud_counter>\d+)\s+(?P<mcast_counter>\d+)') for line in out.splitlines(): line = line.strip() m = p0.match(line) if m: if 'plane_id' not in cfabric_dict: result_dict = cfabric_dict.setdefault('plane_id',{}) plane_id = m.groupdict()['plane_id'] admin_state = m.groupdict()['admin_state'] plane_state = m.groupdict()['plane_state'] ud_counter = m.groupdict()['ud_counter'] mcast_counter = m.groupdict()['mcast_counter'] result_dict[plane_id] = {} result_dict[plane_id]['admin_state'] = admin_state result_dict[plane_id]['plane_state'] = plane_state result_dict[plane_id]['ud_counter'] = ud_counter result_dict[plane_id]['mcast_counter'] = mcast_counter continue return cfabric_dict
<filename>src/genie/libs/parser/iosxr/show_media.py ''' show_media.py IOSXR parsers for the following show commands: * 'show media' * 'show filesystem' * 'show controllers fabric plane all' ''' from genie.metaparser import MetaParser from genie.metaparser.util.schemaengine import Any, Or, Optional import re # ======================================================= # Schema for `show media` # ======================================================== class ShowMediaSchema(MetaParser): schema = { 'partition': { Any(): { 'size': str, 'used': str, 'percent': str, 'avail': str, } } } class ShowMedia(ShowMediaSchema): """Parser for show media interface on iosxr routers parser class - implements detail parsing mechanisms for cli output. """ cli_command = 'show media' """ Tue Apr 13 18:43:17.452 UTC Media info for node0_RP0_CPU0 ------------------------------------------------------------ Partition Size Used Percent Avail disk2: 3.8G 945M 25% 2.9G disk0: 3.4G 9.6M 1% 3.2G /var/lib/docker 5.6G 12M 1% 5.3G harddisk: 51G 1016M 3% 48G log: 4.5G 253M 6% 4.0G ------------------------------------------------------------ log: = system log files (read-only) """ def cli(self, output=None): if output is None: out = self.device.execute(self.cli_command) else: out = output media_dict = {} result_dict = {} """ Variables Parsed: partition = Partition size = Size used = Used percent = Percent avail = Avail """ p0 = re.compile(r'^(?P<partition>(\w+:|\/\S+))\s+(?P<size>\S+)\s+(?P<used>\S+)\s+(?P<percent>\d+%)\s+(?P<avail>\S+)$') for line in out.splitlines(): line = line.strip() m = p0.match(line) if m: if 'partition' not in media_dict: result_dict = media_dict.setdefault('partition',{}) size = m.groupdict()['size'] used = m.groupdict()['used'] percent = m.groupdict()['percent'] avail = m.groupdict()['avail'] partition = m.groupdict()['partition'] result_dict[partition] = {} result_dict[partition]['size'] = size result_dict[partition]['used'] = used result_dict[partition]['percent'] = percent result_dict[partition]['avail'] = avail continue return media_dict # ========================== # Parser for 'show filesystem' # ========================== # ======================================================= # Schema for `show filesystem` # ======================================================== class FileSystemSchema(MetaParser): schema = { 'prefixes': { Any(): { 'size': str, 'free': str, 'type': str, 'flags': str, } } } class ShowFileSystem(FileSystemSchema): """Parser for show filesystem interface on iosxr routers parser class - implements detail parsing mechanisms for cli output. """ cli_command = 'show filesystem' """ Fri Apr 16 21:22:35.610 UTC File Systems: Size(b) Free(b) Type Flags Prefixes 48648003584 42960728064 flash rw /misc/config 0 0 network rw tftp: 4008443904 3018457088 flash-disk rw disk2: 0 0 network rw ftp: 54744576000 53680197632 harddisk rw harddisk: 3590602752 3580395520 flash-disk rw disk0: """ def cli(self, output=None): if output is None: out = self.device.execute(self.cli_command) else: out = output filesystem_dict = {} result_dict = {} """ Variables Parsed: size = Size free = Free type = Type flags = Flags prefixes = Prefixes """ p0 = re.compile(r'^(?P<size>\s*\d+)\s+(?P<free>\d+)\s+(?P<type>(\w+|\w+-\w+))\s+(?P<flags>\w+)\s+(?P<prefixes>(\w+:|.?\w+)*)') for line in out.splitlines(): line = line.strip() m = p0.match(line) if m: if 'prefixes' not in filesystem_dict: result_dict = filesystem_dict.setdefault('prefixes',{}) size = m.groupdict()['size'] free = m.groupdict()['free'] type_ = m.groupdict()['type'] flags = m.groupdict()['flags'] prefixes = m.groupdict()['prefixes'] result_dict[prefixes] = {} result_dict[prefixes]['size'] = size result_dict[prefixes]['free'] = free result_dict[prefixes]['type'] = type_ result_dict[prefixes]['flags'] = flags continue return filesystem_dict # ========================== # Parser for 'show controllers fabric plane all' # ========================== # ======================================================= # Schema for `show controllers fabric plane all` # ======================================================== class ControllersFabricPlaneAllSchema(MetaParser): schema = { 'plane_id': { Any(): { 'admin_state': str, 'plane_state': str, 'ud_counter': str, 'mcast_counter': str, } } } class ShowControllersFabricPlaneAll(ControllersFabricPlaneAllSchema): """Parser for show controller fabric plane all interface on iosxr routers parser class - implements detail parsing mechanisms for cli output. """ cli_command = 'show controllers fabric plane all' """ Thu Jul 30 13:16:17.593 UTC Plane Admin Plane up->dn up->mcast Id State State counter counter -------------------------------------- 0 UP UP 0 0 1 UP UP 0 0 2 UP DN 0 0 3 UP DN 0 0 4 UP DN 0 0 5 UP DN 0 0 6 UP DN 0 0 7 UP DN 0 0 """ def cli(self, output=None): if output is None: out = self.device.execute(self.cli_command) else: out = output cfabric_dict = {} result_dict = {} """ Variables Parsed: plane_id = Plane ID admin_state = Admin State plane_state = Plane State ud_counter = up->down counter mcast_counter = mcast counter """ p0 = re.compile(r'^(?P<plane_id>\d+)\s+(?P<admin_state>\w+)\s+(?P<plane_state>\w+)\s+(?P<ud_counter>\d+)\s+(?P<mcast_counter>\d+)') for line in out.splitlines(): line = line.strip() m = p0.match(line) if m: if 'plane_id' not in cfabric_dict: result_dict = cfabric_dict.setdefault('plane_id',{}) plane_id = m.groupdict()['plane_id'] admin_state = m.groupdict()['admin_state'] plane_state = m.groupdict()['plane_state'] ud_counter = m.groupdict()['ud_counter'] mcast_counter = m.groupdict()['mcast_counter'] result_dict[plane_id] = {} result_dict[plane_id]['admin_state'] = admin_state result_dict[plane_id]['plane_state'] = plane_state result_dict[plane_id]['ud_counter'] = ud_counter result_dict[plane_id]['mcast_counter'] = mcast_counter continue return cfabric_dict
en
0.445974
show_media.py IOSXR parsers for the following show commands: * 'show media' * 'show filesystem' * 'show controllers fabric plane all' # ======================================================= # Schema for `show media` # ======================================================== Parser for show media interface on iosxr routers parser class - implements detail parsing mechanisms for cli output. Tue Apr 13 18:43:17.452 UTC Media info for node0_RP0_CPU0 ------------------------------------------------------------ Partition Size Used Percent Avail disk2: 3.8G 945M 25% 2.9G disk0: 3.4G 9.6M 1% 3.2G /var/lib/docker 5.6G 12M 1% 5.3G harddisk: 51G 1016M 3% 48G log: 4.5G 253M 6% 4.0G ------------------------------------------------------------ log: = system log files (read-only) Variables Parsed: partition = Partition size = Size used = Used percent = Percent avail = Avail # ========================== # Parser for 'show filesystem' # ========================== # ======================================================= # Schema for `show filesystem` # ======================================================== Parser for show filesystem interface on iosxr routers parser class - implements detail parsing mechanisms for cli output. Fri Apr 16 21:22:35.610 UTC File Systems: Size(b) Free(b) Type Flags Prefixes 48648003584 42960728064 flash rw /misc/config 0 0 network rw tftp: 4008443904 3018457088 flash-disk rw disk2: 0 0 network rw ftp: 54744576000 53680197632 harddisk rw harddisk: 3590602752 3580395520 flash-disk rw disk0: Variables Parsed: size = Size free = Free type = Type flags = Flags prefixes = Prefixes # ========================== # Parser for 'show controllers fabric plane all' # ========================== # ======================================================= # Schema for `show controllers fabric plane all` # ======================================================== Parser for show controller fabric plane all interface on iosxr routers parser class - implements detail parsing mechanisms for cli output. Thu Jul 30 13:16:17.593 UTC Plane Admin Plane up->dn up->mcast Id State State counter counter -------------------------------------- 0 UP UP 0 0 1 UP UP 0 0 2 UP DN 0 0 3 UP DN 0 0 4 UP DN 0 0 5 UP DN 0 0 6 UP DN 0 0 7 UP DN 0 0 Variables Parsed: plane_id = Plane ID admin_state = Admin State plane_state = Plane State ud_counter = up->down counter mcast_counter = mcast counter
2.351006
2
random_or_override.py
wert23239/AzulRL
1
6620635
import random from numpy.random import choice """ Returns either a random int, or an overriden value (for testing). When overriding, pass in a sequence of ints for this function to return. """ class RandomOrOverride: def __init__(self, override=[], seed=None): self.override = override self.override_index = 0 random.seed(seed) def random_range(self, min, max): if self.override_index >= len(self.override): return random.randint(min, max) else: res = self.override[self.override_index] self.override_index += 1 return res def random_range_cont(self): if self.override_index >= len(self.override): return random.random() else: res = self.override[self.override_index] self.override_index += 1 return res def random_sample(self, population, k): if self.override_index + k > len(self.override): return random.sample(population, k) else: res = self.override[self.override_index:self.override_index + k] self.override_index += k return res def weighted_random_choice(self, population_size, probability_distribution): if self.override_index >= len(self.override): return choice(population_size, p=probability_distribution) else: res = self.override[self.override_index] self.override_index += 1 return res
import random from numpy.random import choice """ Returns either a random int, or an overriden value (for testing). When overriding, pass in a sequence of ints for this function to return. """ class RandomOrOverride: def __init__(self, override=[], seed=None): self.override = override self.override_index = 0 random.seed(seed) def random_range(self, min, max): if self.override_index >= len(self.override): return random.randint(min, max) else: res = self.override[self.override_index] self.override_index += 1 return res def random_range_cont(self): if self.override_index >= len(self.override): return random.random() else: res = self.override[self.override_index] self.override_index += 1 return res def random_sample(self, population, k): if self.override_index + k > len(self.override): return random.sample(population, k) else: res = self.override[self.override_index:self.override_index + k] self.override_index += k return res def weighted_random_choice(self, population_size, probability_distribution): if self.override_index >= len(self.override): return choice(population_size, p=probability_distribution) else: res = self.override[self.override_index] self.override_index += 1 return res
en
0.786388
Returns either a random int, or an overriden value (for testing). When overriding, pass in a sequence of ints for this function to return.
3.829636
4
carrier/regression/mercedes-benz-greener-manufacturing/src/eda/eda.py
talk2sunil83/UpgradLearning
0
6620636
<reponame>talk2sunil83/UpgradLearning # %% [markdown] ''' # [Mercedes-Benz Greener Manufacturing](https://www.kaggle.com/c/mercedes-benz-greener-manufacturing) from [Kaggle](https://www.kaggle.com/) ''' # %% [markdown] ''' # Problem statement Since the first automobile, the Benz Patent Motor Car in 1886, Mercedes-Benz has stood for important automotive innovations. These include, for example, the passenger safety cell with crumple zone, the airbag and intelligent assistance systems. Mercedes-Benz applies for nearly 2000 patents per year, making the brand the European leader among premium car makers. Daimler’s Mercedes-Benz cars are leaders in the premium car industry. With a huge selection of features and options, customers can choose the customized Mercedes-Benz of their dreams. . To ensure the safety and reliability of each and every unique car configuration before they hit the road, Daimler’s engineers have developed a robust testing system. But, optimizing the speed of their testing system for so many possible feature combinations is complex and time-consuming without a powerful algorithmic approach. As one of the world’s biggest manufacturers of premium cars, safety and efficiency are paramount on Daimler’s production lines. ![](https://storage.googleapis.com/kaggle-competitions/kaggle/6565/media/daimler-mercedes%20V02.jpg) In this competition, **Daimler is challenging Kagglers to tackle the curse of dimensionality and reduce the time that cars spend on the test bench. Competitors will work with a dataset representing different permutations of Mercedes-Benz car features to predict the time it takes to pass testing. Winning algorithms will contribute to speedier testing, resulting in lower carbon dioxide emissions without reducing Daimler’s standards.** ''' # %% [markdown] ''' # Solution Approach - Step1 - Step2 ''' # %% [markdown] ''' **Author** : <NAME> || <EMAIL> || +91 96206 38383 || ''' # %% [markdown] ''' # Solution ''' # %% [markdown] ''' # Lib Imports ''' # %% import pickle from sklearn.decomposition import PCA from sklearn.preprocessing import OneHotEncoder from typing import Dict, List, Sequence, Tuple import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import plotly.figure_factory as ff import plotly.graph_objects as go import plotly.express as px from IPython.display import display from enum import Enum, auto %matplotlib inline # %% [markdown] ''' # Data load ''' # %% base_path = '../../data/' train = pd.read_csv(f"{base_path}train.csv.zip", compression='zip') test = pd.read_csv(f"{base_path}test.csv.zip", compression='zip') # %% print(train.shape, test.shape) # %% [markdown] ''' # Pandas settings ''' # %% pd.options.display.max_columns = None pd.options.display.max_rows = 500 pd.options.display.width = None pd.options.display.max_colwidth = 100 pd.options.display.precision = 3 # %% [markdown] ''' # Data Overview ''' # %% print(train.shape, test.shape) # %% train.info(verbose=1) # %% train.sample(10) # %% (train.isnull().sum()/train.shape[0])*100 # %% train.isnull().mean()*100 # %% # Count of data types train.dtypes.value_counts() # %% [markdown] ''' # EDA ''' # %% [markdown] ''' # EDA Utility Functions ''' # %% def print_null_percents(frame: pd.DataFrame, full: bool = False, display_cols=True): """Prints null columns perdent and count Args: frame (pd.DataFrame):Dataframe where null needs to be counted full (bool, optional): show all columns. Defaults to False. display_cols (bool, optional): show columns or not. Defaults to True. """ null_counts = frame.isna().sum() if not full: null_counts = null_counts[null_counts > 0] if display_cols: display(round((null_counts/frame.shape[0])*100, 2).sort_values(ascending=False)) print(f"Columns count with null: {len(null_counts[null_counts > 0])}") class GraphType(Enum): """Graph Type Enum Args: Enum ([type]): Built-in Enum Class """ BAR = auto() LINE = auto() DIST = auto() def plot_univariate_series( series: pd.Series, title: str, xlabel: str, ylabel: str, graph_type: GraphType = None, showlegend: bool = False, log_x=False, log_y=False, * args, **kwargs) -> None: """Bar plots a interger series Args: series (pd.Series): series to be plotted title (str): graph title xlabel (str): x-axis label ylabel (str): y-axis label graph_type (GraphType, optional): graph type showlegend (bool, optional): default False log_x (bool, optional): default False log_y (bool, optional): default False """ labels = {"x": xlabel, "y": ylabel} fig = None if graph_type is None or graph_type == GraphType.BAR: fig = px.bar(x=series.index, y=series, color=series.index, title=title, labels=labels, log_x=log_x, log_y=log_y, *args, **kwargs) if graph_type == GraphType.LINE: px.scatter(x=series.index, y=series, title=title, labels=labels, color=series.index, *args, **kwargs) fig.update_layout(showlegend=showlegend) fig.show() def get_univariate_cat_plot_strs(value: str, **kwargs) -> Tuple[str, str, str]: """Creates graph title, x-axis text and y-axis text for given value Args: value (str): column name Returns: Tuple[str, str, str]: title, x-axis text and y-axis text """ full_name = value # TODO: write logic to make name if len(full_name) > 30: full_name = value count_str = full_name + ' Count' + " - Log Scale" if kwargs.get("log_y") else "" return count_str + ' Plot', full_name, count_str def plot_cat_data(c: str, value_counts_ser: pd.Series, *args, **kwargs): """Plots the value count series Args: c ([str]): column name value_counts_ser ([pd.Series]): value counts series """ t, xl, yl = get_univariate_cat_plot_strs(c, **kwargs) plot_univariate_series(value_counts_ser, t, xl, yl, *args, **kwargs) def plot_univariate_categorical_columns(categorical_cols: Sequence[str], dataframe: pd.DataFrame, plot_limit: int = 30, print_value_counts=False, *args, **kwargs) -> None: """plots categorical variable bars Args: categorical_cols (Sequence[str]): categorical columns dataframe (pd.DataFrame): DataFrame """ for c in categorical_cols: value_counts_ser = dataframe[c].value_counts() if print_value_counts: print(value_counts_ser) cnt_len = len(value_counts_ser) if cnt_len > 1 and cnt_len < plot_limit: plot_cat_data(c, value_counts_ser, *args, **kwargs) def plot_dist(data_frame: pd.DataFrame, cols_to_plot: List[str], merge_all: bool = False, width=800, *args, **kwargs) -> None: if merge_all: fig = ff.create_distplot(hist_data=data_frame, group_labels=cols_to_plot, *args, **kwargs) fig.update_layout(title_text=f"Dist plot for Numeric Columns", width=width) fig.show() else: for _, c in enumerate(cols_to_plot): fig = ff.create_distplot(hist_data=[data_frame[c].values], group_labels=[c], *args, **kwargs) fig.update_layout(title_text=f"Distribution plot for {c}", width=width) fig.show() def plot_box(df: pd.DataFrame, x: str, y: str) -> None: fig = px.box(df, x=x, y=y, color=x) fig.show() def getdtype(col_data: pd.Series): if col_data.dtype == np.int64 or col_data.dtype == np.float64: return 'num' elif col_data.dtype == 'category': return 'cat' def plot_two_variables(df, x, y): if getdtype(df[x]) == 'num' and getdtype(df[y]) == 'num': fig = px.scatter(df, x=x, y=y, trendline="ols") fig.show() elif (getdtype(df[x]) == 'cat' and getdtype(df[y]) == 'num'): plot_box(df, x, y) elif (getdtype(df[x]) == 'num' and getdtype(df[y]) == 'cat'): plot_box(df, y, x) def set_value_count_color(value): return "background-color: rgba(221, 207, 155, 0.1)" if value <= 5. else '' def print_value_count_percents(categorical_cols: Sequence[str], dataframe: pd.DataFrame) -> None: total_recs = dataframe.shape[0] # ret_values = {} for c in categorical_cols: value_counts_ser = dataframe[c].value_counts() value_counts_per = round(dataframe[c].value_counts()*100/total_recs, 2) df = pd.DataFrame({"Value": value_counts_ser.index, "Value Counts": value_counts_ser.values, "Percent": value_counts_per.values}) df.sort_values(by="Percent", ascending=False) # ret_values[c] = df print(f"\nValue Counts for {c}") # styled_df = df.style.apply(lambda row: highlight_other_group(row, col_count, 5), axis=1) styled_df = df.style.format({ "Percent": "{:.2f}%" }). \ applymap(set_value_count_color, subset=["Percent"]). \ hide_index() display(styled_df) # return ret_values def print_count_of_uniques(dataframe: pd.DataFrame, display_res=False) -> pd.DataFrame: cols = dataframe.columns unique_values = [] unique_len = [] for c in cols: uniques = dataframe[c].unique() unique_values.append(sorted(uniques)) unique_len.append(len(uniques)) frame = pd.DataFrame({ "Column": cols, "Unique Values": unique_values, "Column Unique Count": unique_len}) frame.sort_values(by=["Column Unique Count", "Column"], ascending=[False, True], inplace=True) if display_res: display(frame.style.hide_index()) return frame # %% id_cols = ["ID"] target_col = 'y' # %% [markdown] ''' # Univariate ''' # %% [markdown] ''' # value counts ''' # %% unique_val_frame = print_count_of_uniques(train) single_valued_cols = sorted(list(unique_val_frame[unique_val_frame["Column Unique Count"] == 1]["Column"])) display(unique_val_frame.style.hide_index(), single_valued_cols) # %% str_cols = list(train.select_dtypes('object').columns) binary_cols = [c for c in train.columns if ((c not in single_valued_cols) and (c not in id_cols) and (c not in str_cols) and c != target_col)] # %% print_value_count_percents(list(str_cols), train) # %% print_count_of_uniques(train[binary_cols]) # %% [markdown] ''' ## Drop unwanted columns ''' # %% # Drop unwanted columns cols_to_drop = id_cols + single_valued_cols train.drop(cols_to_drop, axis=1, inplace=True) test.drop(cols_to_drop, axis=1, inplace=True) # %% print(train.shape, test.shape) # %% [markdown] ''' # distributions ''' # %% [markdown] ''' # Plotting numeric and categorical ''' # %% [markdown] ''' ## Numerics ''' # %% # plot target plot_dist(train, [target_col], show_rug=False) # %% [markdown] ''' ## categorical ''' # %% # Plot string valued columns frequency plot_univariate_categorical_columns(list(str_cols), train, log_y=True, plot_limit=50) # %% for col in str_cols: plot_box(train, col, 'y') # %% # Some binary columns plot_univariate_categorical_columns(['X350', 'X351', 'X352', 'X353', 'X354', 'X355', 'X356', 'X357'], train, log_y=True) # %% [markdown] ''' # Bi-variate ''' # %% [markdown] ''' # Correlation ''' # %% train_corr = train.corr() # %% fig = px.imshow(train_corr) fig.update_layout(width=1000, height=1000) fig.show() # %% [markdown] ''' # Numeric-Numeric (Scatter plot) ''' # %% # pair plot fig = px.scatter_matrix(train[train_corr[target_col].abs().nlargest(16).index], width=1000, height=1000) fig.show() # %% [markdown] ''' # Numeric-Categorical (Box and violin) ''' # %% # get top 15 cols correlated with target column top_15_cols = train_corr[target_col].abs().nlargest(16)[1:].index for c in top_15_cols: plot_box(train, c, 'y') # %% [markdown] ''' # Categorical-Categorical (Cross Table) - How to do it? ''' # %% # TODO: Zero-One count compare plot # %% [markdown] ''' # Pre processing ''' # %% [markdown] ''' ## Pre processing Utils ''' # %% # def replace_values_having_less_count(dataframe: pd.DataFrame, target_cols: Sequence[str], threshold: Union[int, Sequence[int]] = 100, replace_with: Union[int, float, str, Sequence[int], Sequence[float], Sequence[str]] = "OT") -> DataFrame: # pass def replace_values_having_less_count(dataframe: pd.DataFrame, target_cols: Sequence[str], threshold: int = 100, replace_with="OT") -> pd.DataFrame: for c in target_cols: vc = dataframe[c].value_counts() replace_dict = {v: replace_with for v in list(vc[vc <= threshold].index)} dataframe[c] = dataframe[c].replace(replace_dict) return dataframe # %% train = replace_values_having_less_count(train, train.select_dtypes('object').columns) # %% print_value_count_percents(list(str_cols), train) # %% for col in str_cols: plot_box(train, col, 'y') # %% [markdown] ''' ## Fix column dtypes - NA ''' # %% display(train.dtypes, test.dtypes) # %% [markdown] ''' # Null Handling - NA ''' # %% print(train.isna().sum().sum(), test.isna().sum().sum()) # %% [markdown] ''' # Scaling - NA ''' # %% [markdown] ''' # Conversion of categorical (OHE or mean) ''' # %% encoded_train = train.copy() encoded_test = test.copy() # Could do get_dummies but test is separate sow we need to preserver encoders col_encoder = {} for col in str_cols: current_col_data = train[[col]] ohe = OneHotEncoder(handle_unknown='ignore').fit(current_col_data) transformed_train = ohe.transform(current_col_data).toarray() transformed_test = ohe.transform(test[[col]]).toarray() cols = [f"{col}_{c}" for c in ohe.categories_[0]] encoded_train = pd.concat([encoded_train, pd.DataFrame(np.array(transformed_train), columns=cols)], axis=1) encoded_test = pd.concat([encoded_test, pd.DataFrame(np.array(transformed_test), columns=cols)], axis=1) encoded_train.drop(col, axis=1, inplace=True) encoded_test.drop(col, axis=1, inplace=True) # %% print(train.shape, encoded_train.shape, test.shape, encoded_test.shape) # %% [markdown] ''' # Outlier Treatment - NA ''' # %% [markdown] ''' # Single valued removal - Done ''' # %% [markdown] ''' # ID Removal - Done ''' # %% [markdown] ''' # Non important column removal - NA ''' # %% [markdown] ''' # Feature creation - NA ''' # %% [markdown] ''' # Dimensionality Reduction ''' # %% # lets PCA with 90% information preservation pca = PCA(0.9) X = encoded_train.drop(target_col, axis=1) y = encoded_train[target_col] pca.fit(X) encoded_train_dim_red = pca.transform(X) encoded_test_dim_red = pca.transform(encoded_test) # %% def save_file(base_path, object, filename) -> None: with open(f"{base_path}{filename}.pkl", 'wb') as f: f.write(pickle.dumps(object)) save_file(base_path, encoded_train, 'encoded_train') save_file(base_path, encoded_test, 'encoded_test') save_file(base_path, encoded_train_dim_red, 'encoded_train_dim_red') save_file(base_path, encoded_test_dim_red, 'encoded_test_dim_red') # encoded_train.to_pickle(f"{base_path}encoded_train.pkl") # encoded_test.to_pickle(f"{base_path}encoded_test.pkl") # encoded_train_dim_red.to_pickle(f"{base_path}encoded_train_dim_red.pkl") # encoded_test_dim_red.to_pickle(f"{base_path}encoded_test_dim_red.pkl") # %% # %% # %% # %%
# %% [markdown] ''' # [Mercedes-Benz Greener Manufacturing](https://www.kaggle.com/c/mercedes-benz-greener-manufacturing) from [Kaggle](https://www.kaggle.com/) ''' # %% [markdown] ''' # Problem statement Since the first automobile, the Benz Patent Motor Car in 1886, Mercedes-Benz has stood for important automotive innovations. These include, for example, the passenger safety cell with crumple zone, the airbag and intelligent assistance systems. Mercedes-Benz applies for nearly 2000 patents per year, making the brand the European leader among premium car makers. Daimler’s Mercedes-Benz cars are leaders in the premium car industry. With a huge selection of features and options, customers can choose the customized Mercedes-Benz of their dreams. . To ensure the safety and reliability of each and every unique car configuration before they hit the road, Daimler’s engineers have developed a robust testing system. But, optimizing the speed of their testing system for so many possible feature combinations is complex and time-consuming without a powerful algorithmic approach. As one of the world’s biggest manufacturers of premium cars, safety and efficiency are paramount on Daimler’s production lines. ![](https://storage.googleapis.com/kaggle-competitions/kaggle/6565/media/daimler-mercedes%20V02.jpg) In this competition, **Daimler is challenging Kagglers to tackle the curse of dimensionality and reduce the time that cars spend on the test bench. Competitors will work with a dataset representing different permutations of Mercedes-Benz car features to predict the time it takes to pass testing. Winning algorithms will contribute to speedier testing, resulting in lower carbon dioxide emissions without reducing Daimler’s standards.** ''' # %% [markdown] ''' # Solution Approach - Step1 - Step2 ''' # %% [markdown] ''' **Author** : <NAME> || <EMAIL> || +91 96206 38383 || ''' # %% [markdown] ''' # Solution ''' # %% [markdown] ''' # Lib Imports ''' # %% import pickle from sklearn.decomposition import PCA from sklearn.preprocessing import OneHotEncoder from typing import Dict, List, Sequence, Tuple import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import plotly.figure_factory as ff import plotly.graph_objects as go import plotly.express as px from IPython.display import display from enum import Enum, auto %matplotlib inline # %% [markdown] ''' # Data load ''' # %% base_path = '../../data/' train = pd.read_csv(f"{base_path}train.csv.zip", compression='zip') test = pd.read_csv(f"{base_path}test.csv.zip", compression='zip') # %% print(train.shape, test.shape) # %% [markdown] ''' # Pandas settings ''' # %% pd.options.display.max_columns = None pd.options.display.max_rows = 500 pd.options.display.width = None pd.options.display.max_colwidth = 100 pd.options.display.precision = 3 # %% [markdown] ''' # Data Overview ''' # %% print(train.shape, test.shape) # %% train.info(verbose=1) # %% train.sample(10) # %% (train.isnull().sum()/train.shape[0])*100 # %% train.isnull().mean()*100 # %% # Count of data types train.dtypes.value_counts() # %% [markdown] ''' # EDA ''' # %% [markdown] ''' # EDA Utility Functions ''' # %% def print_null_percents(frame: pd.DataFrame, full: bool = False, display_cols=True): """Prints null columns perdent and count Args: frame (pd.DataFrame):Dataframe where null needs to be counted full (bool, optional): show all columns. Defaults to False. display_cols (bool, optional): show columns or not. Defaults to True. """ null_counts = frame.isna().sum() if not full: null_counts = null_counts[null_counts > 0] if display_cols: display(round((null_counts/frame.shape[0])*100, 2).sort_values(ascending=False)) print(f"Columns count with null: {len(null_counts[null_counts > 0])}") class GraphType(Enum): """Graph Type Enum Args: Enum ([type]): Built-in Enum Class """ BAR = auto() LINE = auto() DIST = auto() def plot_univariate_series( series: pd.Series, title: str, xlabel: str, ylabel: str, graph_type: GraphType = None, showlegend: bool = False, log_x=False, log_y=False, * args, **kwargs) -> None: """Bar plots a interger series Args: series (pd.Series): series to be plotted title (str): graph title xlabel (str): x-axis label ylabel (str): y-axis label graph_type (GraphType, optional): graph type showlegend (bool, optional): default False log_x (bool, optional): default False log_y (bool, optional): default False """ labels = {"x": xlabel, "y": ylabel} fig = None if graph_type is None or graph_type == GraphType.BAR: fig = px.bar(x=series.index, y=series, color=series.index, title=title, labels=labels, log_x=log_x, log_y=log_y, *args, **kwargs) if graph_type == GraphType.LINE: px.scatter(x=series.index, y=series, title=title, labels=labels, color=series.index, *args, **kwargs) fig.update_layout(showlegend=showlegend) fig.show() def get_univariate_cat_plot_strs(value: str, **kwargs) -> Tuple[str, str, str]: """Creates graph title, x-axis text and y-axis text for given value Args: value (str): column name Returns: Tuple[str, str, str]: title, x-axis text and y-axis text """ full_name = value # TODO: write logic to make name if len(full_name) > 30: full_name = value count_str = full_name + ' Count' + " - Log Scale" if kwargs.get("log_y") else "" return count_str + ' Plot', full_name, count_str def plot_cat_data(c: str, value_counts_ser: pd.Series, *args, **kwargs): """Plots the value count series Args: c ([str]): column name value_counts_ser ([pd.Series]): value counts series """ t, xl, yl = get_univariate_cat_plot_strs(c, **kwargs) plot_univariate_series(value_counts_ser, t, xl, yl, *args, **kwargs) def plot_univariate_categorical_columns(categorical_cols: Sequence[str], dataframe: pd.DataFrame, plot_limit: int = 30, print_value_counts=False, *args, **kwargs) -> None: """plots categorical variable bars Args: categorical_cols (Sequence[str]): categorical columns dataframe (pd.DataFrame): DataFrame """ for c in categorical_cols: value_counts_ser = dataframe[c].value_counts() if print_value_counts: print(value_counts_ser) cnt_len = len(value_counts_ser) if cnt_len > 1 and cnt_len < plot_limit: plot_cat_data(c, value_counts_ser, *args, **kwargs) def plot_dist(data_frame: pd.DataFrame, cols_to_plot: List[str], merge_all: bool = False, width=800, *args, **kwargs) -> None: if merge_all: fig = ff.create_distplot(hist_data=data_frame, group_labels=cols_to_plot, *args, **kwargs) fig.update_layout(title_text=f"Dist plot for Numeric Columns", width=width) fig.show() else: for _, c in enumerate(cols_to_plot): fig = ff.create_distplot(hist_data=[data_frame[c].values], group_labels=[c], *args, **kwargs) fig.update_layout(title_text=f"Distribution plot for {c}", width=width) fig.show() def plot_box(df: pd.DataFrame, x: str, y: str) -> None: fig = px.box(df, x=x, y=y, color=x) fig.show() def getdtype(col_data: pd.Series): if col_data.dtype == np.int64 or col_data.dtype == np.float64: return 'num' elif col_data.dtype == 'category': return 'cat' def plot_two_variables(df, x, y): if getdtype(df[x]) == 'num' and getdtype(df[y]) == 'num': fig = px.scatter(df, x=x, y=y, trendline="ols") fig.show() elif (getdtype(df[x]) == 'cat' and getdtype(df[y]) == 'num'): plot_box(df, x, y) elif (getdtype(df[x]) == 'num' and getdtype(df[y]) == 'cat'): plot_box(df, y, x) def set_value_count_color(value): return "background-color: rgba(221, 207, 155, 0.1)" if value <= 5. else '' def print_value_count_percents(categorical_cols: Sequence[str], dataframe: pd.DataFrame) -> None: total_recs = dataframe.shape[0] # ret_values = {} for c in categorical_cols: value_counts_ser = dataframe[c].value_counts() value_counts_per = round(dataframe[c].value_counts()*100/total_recs, 2) df = pd.DataFrame({"Value": value_counts_ser.index, "Value Counts": value_counts_ser.values, "Percent": value_counts_per.values}) df.sort_values(by="Percent", ascending=False) # ret_values[c] = df print(f"\nValue Counts for {c}") # styled_df = df.style.apply(lambda row: highlight_other_group(row, col_count, 5), axis=1) styled_df = df.style.format({ "Percent": "{:.2f}%" }). \ applymap(set_value_count_color, subset=["Percent"]). \ hide_index() display(styled_df) # return ret_values def print_count_of_uniques(dataframe: pd.DataFrame, display_res=False) -> pd.DataFrame: cols = dataframe.columns unique_values = [] unique_len = [] for c in cols: uniques = dataframe[c].unique() unique_values.append(sorted(uniques)) unique_len.append(len(uniques)) frame = pd.DataFrame({ "Column": cols, "Unique Values": unique_values, "Column Unique Count": unique_len}) frame.sort_values(by=["Column Unique Count", "Column"], ascending=[False, True], inplace=True) if display_res: display(frame.style.hide_index()) return frame # %% id_cols = ["ID"] target_col = 'y' # %% [markdown] ''' # Univariate ''' # %% [markdown] ''' # value counts ''' # %% unique_val_frame = print_count_of_uniques(train) single_valued_cols = sorted(list(unique_val_frame[unique_val_frame["Column Unique Count"] == 1]["Column"])) display(unique_val_frame.style.hide_index(), single_valued_cols) # %% str_cols = list(train.select_dtypes('object').columns) binary_cols = [c for c in train.columns if ((c not in single_valued_cols) and (c not in id_cols) and (c not in str_cols) and c != target_col)] # %% print_value_count_percents(list(str_cols), train) # %% print_count_of_uniques(train[binary_cols]) # %% [markdown] ''' ## Drop unwanted columns ''' # %% # Drop unwanted columns cols_to_drop = id_cols + single_valued_cols train.drop(cols_to_drop, axis=1, inplace=True) test.drop(cols_to_drop, axis=1, inplace=True) # %% print(train.shape, test.shape) # %% [markdown] ''' # distributions ''' # %% [markdown] ''' # Plotting numeric and categorical ''' # %% [markdown] ''' ## Numerics ''' # %% # plot target plot_dist(train, [target_col], show_rug=False) # %% [markdown] ''' ## categorical ''' # %% # Plot string valued columns frequency plot_univariate_categorical_columns(list(str_cols), train, log_y=True, plot_limit=50) # %% for col in str_cols: plot_box(train, col, 'y') # %% # Some binary columns plot_univariate_categorical_columns(['X350', 'X351', 'X352', 'X353', 'X354', 'X355', 'X356', 'X357'], train, log_y=True) # %% [markdown] ''' # Bi-variate ''' # %% [markdown] ''' # Correlation ''' # %% train_corr = train.corr() # %% fig = px.imshow(train_corr) fig.update_layout(width=1000, height=1000) fig.show() # %% [markdown] ''' # Numeric-Numeric (Scatter plot) ''' # %% # pair plot fig = px.scatter_matrix(train[train_corr[target_col].abs().nlargest(16).index], width=1000, height=1000) fig.show() # %% [markdown] ''' # Numeric-Categorical (Box and violin) ''' # %% # get top 15 cols correlated with target column top_15_cols = train_corr[target_col].abs().nlargest(16)[1:].index for c in top_15_cols: plot_box(train, c, 'y') # %% [markdown] ''' # Categorical-Categorical (Cross Table) - How to do it? ''' # %% # TODO: Zero-One count compare plot # %% [markdown] ''' # Pre processing ''' # %% [markdown] ''' ## Pre processing Utils ''' # %% # def replace_values_having_less_count(dataframe: pd.DataFrame, target_cols: Sequence[str], threshold: Union[int, Sequence[int]] = 100, replace_with: Union[int, float, str, Sequence[int], Sequence[float], Sequence[str]] = "OT") -> DataFrame: # pass def replace_values_having_less_count(dataframe: pd.DataFrame, target_cols: Sequence[str], threshold: int = 100, replace_with="OT") -> pd.DataFrame: for c in target_cols: vc = dataframe[c].value_counts() replace_dict = {v: replace_with for v in list(vc[vc <= threshold].index)} dataframe[c] = dataframe[c].replace(replace_dict) return dataframe # %% train = replace_values_having_less_count(train, train.select_dtypes('object').columns) # %% print_value_count_percents(list(str_cols), train) # %% for col in str_cols: plot_box(train, col, 'y') # %% [markdown] ''' ## Fix column dtypes - NA ''' # %% display(train.dtypes, test.dtypes) # %% [markdown] ''' # Null Handling - NA ''' # %% print(train.isna().sum().sum(), test.isna().sum().sum()) # %% [markdown] ''' # Scaling - NA ''' # %% [markdown] ''' # Conversion of categorical (OHE or mean) ''' # %% encoded_train = train.copy() encoded_test = test.copy() # Could do get_dummies but test is separate sow we need to preserver encoders col_encoder = {} for col in str_cols: current_col_data = train[[col]] ohe = OneHotEncoder(handle_unknown='ignore').fit(current_col_data) transformed_train = ohe.transform(current_col_data).toarray() transformed_test = ohe.transform(test[[col]]).toarray() cols = [f"{col}_{c}" for c in ohe.categories_[0]] encoded_train = pd.concat([encoded_train, pd.DataFrame(np.array(transformed_train), columns=cols)], axis=1) encoded_test = pd.concat([encoded_test, pd.DataFrame(np.array(transformed_test), columns=cols)], axis=1) encoded_train.drop(col, axis=1, inplace=True) encoded_test.drop(col, axis=1, inplace=True) # %% print(train.shape, encoded_train.shape, test.shape, encoded_test.shape) # %% [markdown] ''' # Outlier Treatment - NA ''' # %% [markdown] ''' # Single valued removal - Done ''' # %% [markdown] ''' # ID Removal - Done ''' # %% [markdown] ''' # Non important column removal - NA ''' # %% [markdown] ''' # Feature creation - NA ''' # %% [markdown] ''' # Dimensionality Reduction ''' # %% # lets PCA with 90% information preservation pca = PCA(0.9) X = encoded_train.drop(target_col, axis=1) y = encoded_train[target_col] pca.fit(X) encoded_train_dim_red = pca.transform(X) encoded_test_dim_red = pca.transform(encoded_test) # %% def save_file(base_path, object, filename) -> None: with open(f"{base_path}{filename}.pkl", 'wb') as f: f.write(pickle.dumps(object)) save_file(base_path, encoded_train, 'encoded_train') save_file(base_path, encoded_test, 'encoded_test') save_file(base_path, encoded_train_dim_red, 'encoded_train_dim_red') save_file(base_path, encoded_test_dim_red, 'encoded_test_dim_red') # encoded_train.to_pickle(f"{base_path}encoded_train.pkl") # encoded_test.to_pickle(f"{base_path}encoded_test.pkl") # encoded_train_dim_red.to_pickle(f"{base_path}encoded_train_dim_red.pkl") # encoded_test_dim_red.to_pickle(f"{base_path}encoded_test_dim_red.pkl") # %% # %% # %% # %%
en
0.627694
# %% [markdown] # [Mercedes-Benz Greener Manufacturing](https://www.kaggle.com/c/mercedes-benz-greener-manufacturing) from [Kaggle](https://www.kaggle.com/) # %% [markdown] # Problem statement Since the first automobile, the Benz Patent Motor Car in 1886, Mercedes-Benz has stood for important automotive innovations. These include, for example, the passenger safety cell with crumple zone, the airbag and intelligent assistance systems. Mercedes-Benz applies for nearly 2000 patents per year, making the brand the European leader among premium car makers. Daimler’s Mercedes-Benz cars are leaders in the premium car industry. With a huge selection of features and options, customers can choose the customized Mercedes-Benz of their dreams. . To ensure the safety and reliability of each and every unique car configuration before they hit the road, Daimler’s engineers have developed a robust testing system. But, optimizing the speed of their testing system for so many possible feature combinations is complex and time-consuming without a powerful algorithmic approach. As one of the world’s biggest manufacturers of premium cars, safety and efficiency are paramount on Daimler’s production lines. ![](https://storage.googleapis.com/kaggle-competitions/kaggle/6565/media/daimler-mercedes%20V02.jpg) In this competition, **Daimler is challenging Kagglers to tackle the curse of dimensionality and reduce the time that cars spend on the test bench. Competitors will work with a dataset representing different permutations of Mercedes-Benz car features to predict the time it takes to pass testing. Winning algorithms will contribute to speedier testing, resulting in lower carbon dioxide emissions without reducing Daimler’s standards.** # %% [markdown] # Solution Approach - Step1 - Step2 # %% [markdown] **Author** : <NAME> || <EMAIL> || +91 96206 38383 || # %% [markdown] # Solution # %% [markdown] # Lib Imports # %% # %% [markdown] # Data load # %% # %% # %% [markdown] # Pandas settings # %% # %% [markdown] # Data Overview # %% # %% # %% # %% # %% # %% # Count of data types # %% [markdown] # EDA # %% [markdown] # EDA Utility Functions # %% Prints null columns perdent and count Args: frame (pd.DataFrame):Dataframe where null needs to be counted full (bool, optional): show all columns. Defaults to False. display_cols (bool, optional): show columns or not. Defaults to True. Graph Type Enum Args: Enum ([type]): Built-in Enum Class Bar plots a interger series Args: series (pd.Series): series to be plotted title (str): graph title xlabel (str): x-axis label ylabel (str): y-axis label graph_type (GraphType, optional): graph type showlegend (bool, optional): default False log_x (bool, optional): default False log_y (bool, optional): default False Creates graph title, x-axis text and y-axis text for given value Args: value (str): column name Returns: Tuple[str, str, str]: title, x-axis text and y-axis text # TODO: write logic to make name Plots the value count series Args: c ([str]): column name value_counts_ser ([pd.Series]): value counts series plots categorical variable bars Args: categorical_cols (Sequence[str]): categorical columns dataframe (pd.DataFrame): DataFrame # ret_values = {} # ret_values[c] = df # styled_df = df.style.apply(lambda row: highlight_other_group(row, col_count, 5), axis=1) # return ret_values # %% # %% [markdown] # Univariate # %% [markdown] # value counts # %% # %% # %% # %% # %% [markdown] ## Drop unwanted columns # %% # Drop unwanted columns # %% # %% [markdown] # distributions # %% [markdown] # Plotting numeric and categorical # %% [markdown] ## Numerics # %% # plot target # %% [markdown] ## categorical # %% # Plot string valued columns frequency # %% # %% # Some binary columns # %% [markdown] # Bi-variate # %% [markdown] # Correlation # %% # %% # %% [markdown] # Numeric-Numeric (Scatter plot) # %% # pair plot # %% [markdown] # Numeric-Categorical (Box and violin) # %% # get top 15 cols correlated with target column # %% [markdown] # Categorical-Categorical (Cross Table) - How to do it? # %% # TODO: Zero-One count compare plot # %% [markdown] # Pre processing # %% [markdown] ## Pre processing Utils # %% # def replace_values_having_less_count(dataframe: pd.DataFrame, target_cols: Sequence[str], threshold: Union[int, Sequence[int]] = 100, replace_with: Union[int, float, str, Sequence[int], Sequence[float], Sequence[str]] = "OT") -> DataFrame: # pass # %% # %% # %% # %% [markdown] ## Fix column dtypes - NA # %% # %% [markdown] # Null Handling - NA # %% # %% [markdown] # Scaling - NA # %% [markdown] # Conversion of categorical (OHE or mean) # %% # Could do get_dummies but test is separate sow we need to preserver encoders # %% # %% [markdown] # Outlier Treatment - NA # %% [markdown] # Single valued removal - Done # %% [markdown] # ID Removal - Done # %% [markdown] # Non important column removal - NA # %% [markdown] # Feature creation - NA # %% [markdown] # Dimensionality Reduction # %% # lets PCA with 90% information preservation # %% # encoded_train.to_pickle(f"{base_path}encoded_train.pkl") # encoded_test.to_pickle(f"{base_path}encoded_test.pkl") # encoded_train_dim_red.to_pickle(f"{base_path}encoded_train_dim_red.pkl") # encoded_test_dim_red.to_pickle(f"{base_path}encoded_test_dim_red.pkl") # %% # %% # %% # %%
2.69909
3
test/common.py
xharaken/john-law-coin
75
6620637
#!/usr/bin/env python3 # # Copyright (c) 2021 <NAME> # # This software is released under the MIT License. # http://opensource.org/licenses/mit-license.php import glob, os, subprocess, sys, time def kill_ganache(): kill_command = [ "ps axf | grep ganache | grep -v grep |" + "awk '{ print $1 }' | xargs kill -9"] kill_proc = subprocess.Popen( kill_command, shell=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) kill_proc.communicate() # Remove tmp files generated by Truffle. command = "rm -rf /tmp/tmp-*/* 2> /dev/null" subprocess.run(command, shell=True) command = "rm -rf /tmp/tmp-* 2> /dev/null" subprocess.run(command, shell=True) for file in glob.glob("/tmp/tmp-*/*"): command = "rm -rf " + file + " 2> /dev/null" subprocess.run(command, shell=True) for file in glob.glob("/tmp/tmp-*"): command = "rm -rf " + file + " 2> /dev/null" subprocess.run(command, shell=True) def reset_network(voters): # os.chdir(os.path.dirname(os.path.abspath(__file__))) kill_ganache() time.sleep(6) network = subprocess.Popen( "ganache-cli --port 8546 -l 1200000000 -a" + str(voters), shell=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) time.sleep(6) def run_test(command): print(command, file=sys.stderr) subprocess.run(command, shell=True) sys.stdout.flush() kill_ganache()
#!/usr/bin/env python3 # # Copyright (c) 2021 <NAME> # # This software is released under the MIT License. # http://opensource.org/licenses/mit-license.php import glob, os, subprocess, sys, time def kill_ganache(): kill_command = [ "ps axf | grep ganache | grep -v grep |" + "awk '{ print $1 }' | xargs kill -9"] kill_proc = subprocess.Popen( kill_command, shell=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) kill_proc.communicate() # Remove tmp files generated by Truffle. command = "rm -rf /tmp/tmp-*/* 2> /dev/null" subprocess.run(command, shell=True) command = "rm -rf /tmp/tmp-* 2> /dev/null" subprocess.run(command, shell=True) for file in glob.glob("/tmp/tmp-*/*"): command = "rm -rf " + file + " 2> /dev/null" subprocess.run(command, shell=True) for file in glob.glob("/tmp/tmp-*"): command = "rm -rf " + file + " 2> /dev/null" subprocess.run(command, shell=True) def reset_network(voters): # os.chdir(os.path.dirname(os.path.abspath(__file__))) kill_ganache() time.sleep(6) network = subprocess.Popen( "ganache-cli --port 8546 -l 1200000000 -a" + str(voters), shell=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) time.sleep(6) def run_test(command): print(command, file=sys.stderr) subprocess.run(command, shell=True) sys.stdout.flush() kill_ganache()
en
0.536406
#!/usr/bin/env python3 # # Copyright (c) 2021 <NAME> # # This software is released under the MIT License. # http://opensource.org/licenses/mit-license.php # Remove tmp files generated by Truffle. # os.chdir(os.path.dirname(os.path.abspath(__file__)))
2.073221
2
python/spacy_lemmatizer/lemmatizer_app.py
bakdata/common-kafka-streams-demo
4
6620638
from typing import Dict, Union, List from faust import TopicT from faust.serializers.codecs import codecs from faust_bootstrap.core.app import FaustApplication from faust_bootstrap.core.streams.models import DeadLetter from faust_s3_backed_serializer import S3BackedSerializer from spacy_lemmatizer.lemmatizer.agent import create_spacy_agent from spacy_lemmatizer.models import Text, LemmaText class LemmatizerApp(FaustApplication): s3_serde: bool input_topics: TopicT output_topic: TopicT error_topic: TopicT def __init__(self): super(LemmatizerApp, self).__init__() def _register_parameters(self): self.register_parameter("--s3-serde", False, "Activate s3-backed SerDe as serializer", bool, default=False) def get_unique_app_id(self): return f'spacy-lemmatizer-{self.output_topic_name}' def get_serde_avro_from_topic(self, topic: Union[str, List[str]]): value = self.create_avro_serde(topic, False) return value def create_s3_serde(self, topic: Union[str, List[str]]): value_s3_serializer = self.create_s3_backed_serde(topic, self._generate_streams_config()) value_avro = self.get_serde_avro_from_topic(topic) return value_avro | value_s3_serializer def create_serde(self, topic: Union[str, List[str]]): if self.s3_serde: return self.create_s3_serde(topic) else: return self.get_serde_avro_from_topic(topic) def setup_topics(self): value_serializer_input = self.create_serde(self.input_topic_names[0]) value_serializer_output = self.create_serde(self.output_topic_name) schema_input = self.create_schema_from(codecs["raw"], value_serializer_input, bytes, Text) schema_output = self.create_schema_from(codecs["raw"], value_serializer_output, bytes, LemmaText) value_serializer_error = self.create_avro_serde(self.error_topic_name, False) schema_error = self.create_schema_from(codecs["raw"], value_serializer_error, bytes, DeadLetter) self.input_topics = self.get_topic_from_schema(self.input_topic_names, schema_input) self.output_topic = self.get_topic_from_schema(self.output_topic_name, schema_output) if self.error_topic_name: self.error_topic = self.get_topic_from_schema(self.error_topic_name, schema_error) def build_topology(self): agent = create_spacy_agent(self.output_topic, self.error_topic) self.create_agent(agent, self.input_topics) @staticmethod def create_s3_backed_serde(topic: str, s3_config: Dict[str, str], is_key: bool = False): base_path = s3_config.get("s3backed.base.path") max_size = int(s3_config.get("s3backed.max.byte.size")) region_name = s3_config.get("s3backed.region") faust_s3_serializer = S3BackedSerializer(topic, base_path, region_name, None, max_size, is_key) return faust_s3_serializer
from typing import Dict, Union, List from faust import TopicT from faust.serializers.codecs import codecs from faust_bootstrap.core.app import FaustApplication from faust_bootstrap.core.streams.models import DeadLetter from faust_s3_backed_serializer import S3BackedSerializer from spacy_lemmatizer.lemmatizer.agent import create_spacy_agent from spacy_lemmatizer.models import Text, LemmaText class LemmatizerApp(FaustApplication): s3_serde: bool input_topics: TopicT output_topic: TopicT error_topic: TopicT def __init__(self): super(LemmatizerApp, self).__init__() def _register_parameters(self): self.register_parameter("--s3-serde", False, "Activate s3-backed SerDe as serializer", bool, default=False) def get_unique_app_id(self): return f'spacy-lemmatizer-{self.output_topic_name}' def get_serde_avro_from_topic(self, topic: Union[str, List[str]]): value = self.create_avro_serde(topic, False) return value def create_s3_serde(self, topic: Union[str, List[str]]): value_s3_serializer = self.create_s3_backed_serde(topic, self._generate_streams_config()) value_avro = self.get_serde_avro_from_topic(topic) return value_avro | value_s3_serializer def create_serde(self, topic: Union[str, List[str]]): if self.s3_serde: return self.create_s3_serde(topic) else: return self.get_serde_avro_from_topic(topic) def setup_topics(self): value_serializer_input = self.create_serde(self.input_topic_names[0]) value_serializer_output = self.create_serde(self.output_topic_name) schema_input = self.create_schema_from(codecs["raw"], value_serializer_input, bytes, Text) schema_output = self.create_schema_from(codecs["raw"], value_serializer_output, bytes, LemmaText) value_serializer_error = self.create_avro_serde(self.error_topic_name, False) schema_error = self.create_schema_from(codecs["raw"], value_serializer_error, bytes, DeadLetter) self.input_topics = self.get_topic_from_schema(self.input_topic_names, schema_input) self.output_topic = self.get_topic_from_schema(self.output_topic_name, schema_output) if self.error_topic_name: self.error_topic = self.get_topic_from_schema(self.error_topic_name, schema_error) def build_topology(self): agent = create_spacy_agent(self.output_topic, self.error_topic) self.create_agent(agent, self.input_topics) @staticmethod def create_s3_backed_serde(topic: str, s3_config: Dict[str, str], is_key: bool = False): base_path = s3_config.get("s3backed.base.path") max_size = int(s3_config.get("s3backed.max.byte.size")) region_name = s3_config.get("s3backed.region") faust_s3_serializer = S3BackedSerializer(topic, base_path, region_name, None, max_size, is_key) return faust_s3_serializer
none
1
2.036945
2
2-control-flow/sals-shipping/shipping.py
Dianicata/learn-python
0
6620639
<gh_stars>0 # Sal's Shipping # Dianicata currency ="$" import random weight = random.randint(1, 150) print("current random weight: " + str(weight)) # weight = 1.5 #Ground shipping ground_shipping_flat_charge = 20 if weight <= 2 and weight >= 0: ground_shipment_cost = round(weight * 1.50 + ground_shipping_flat_charge, 2) elif weight >= 2 and weight <= 6: ground_shipment_cost = round(weight * 3 + ground_shipping_flat_charge, 2) elif weight >= 6 and weight <=10: ground_shipment_cost = round(weight * 4 + ground_shipping_flat_charge, 2) elif weight > 10: ground_shipment_cost = round(weight * 4.75 + ground_shipping_flat_charge, 2) else: ground_shipment_cost = "Error: Please tell me the right weight of your package" print(f"Ground shipping option: {ground_shipment_cost}" + currency) # Ground_shipping_premium premium_flat_charge = 125 print(f"Premium flat charge: {premium_flat_charge}" + currency) # drone shipping if weight <= 2 and weight >= 0: drone_shipment_cost = round(weight * 4.50, 2) elif weight >= 2 and weight <= 6: drone_shipment_cost = round(weight * 9, 2) elif weight >= 6 and weight <= 10: drone_shipment_cost = round(weight * 12, 2) elif weight > 10: drone_shipment_cost = round(weight * 14.25, 2) else: drone_shipment_cost = "Error: Please tell me the right weight of your package" print(f"Drone shipping option: {drone_shipment_cost}" + currency) # Cheapest option shipping_option = "" shipping_cost = 0 if ground_shipment_cost < premium_flat_charge and ground_shipment_cost < drone_shipment_cost: shipping_option = "ground shipping" shipping_cost = ground_shipment_cost elif premium_flat_charge < ground_shipment_cost and premium_flat_charge < drone_shipment_cost: shipping_option = "premium flat charge" shipping_cost = premium_flat_charge elif drone_shipment_cost < premium_flat_charge and drone_shipment_cost < ground_shipment_cost: shipping_option = "drone shipping" shipping_cost = drone_shipment_cost print(f"Cheapest shipment option is with {shipping_option}: {shipping_cost}" + currency)
# Sal's Shipping # Dianicata currency ="$" import random weight = random.randint(1, 150) print("current random weight: " + str(weight)) # weight = 1.5 #Ground shipping ground_shipping_flat_charge = 20 if weight <= 2 and weight >= 0: ground_shipment_cost = round(weight * 1.50 + ground_shipping_flat_charge, 2) elif weight >= 2 and weight <= 6: ground_shipment_cost = round(weight * 3 + ground_shipping_flat_charge, 2) elif weight >= 6 and weight <=10: ground_shipment_cost = round(weight * 4 + ground_shipping_flat_charge, 2) elif weight > 10: ground_shipment_cost = round(weight * 4.75 + ground_shipping_flat_charge, 2) else: ground_shipment_cost = "Error: Please tell me the right weight of your package" print(f"Ground shipping option: {ground_shipment_cost}" + currency) # Ground_shipping_premium premium_flat_charge = 125 print(f"Premium flat charge: {premium_flat_charge}" + currency) # drone shipping if weight <= 2 and weight >= 0: drone_shipment_cost = round(weight * 4.50, 2) elif weight >= 2 and weight <= 6: drone_shipment_cost = round(weight * 9, 2) elif weight >= 6 and weight <= 10: drone_shipment_cost = round(weight * 12, 2) elif weight > 10: drone_shipment_cost = round(weight * 14.25, 2) else: drone_shipment_cost = "Error: Please tell me the right weight of your package" print(f"Drone shipping option: {drone_shipment_cost}" + currency) # Cheapest option shipping_option = "" shipping_cost = 0 if ground_shipment_cost < premium_flat_charge and ground_shipment_cost < drone_shipment_cost: shipping_option = "ground shipping" shipping_cost = ground_shipment_cost elif premium_flat_charge < ground_shipment_cost and premium_flat_charge < drone_shipment_cost: shipping_option = "premium flat charge" shipping_cost = premium_flat_charge elif drone_shipment_cost < premium_flat_charge and drone_shipment_cost < ground_shipment_cost: shipping_option = "drone shipping" shipping_cost = drone_shipment_cost print(f"Cheapest shipment option is with {shipping_option}: {shipping_cost}" + currency)
en
0.831579
# Sal's Shipping # Dianicata # weight = 1.5 #Ground shipping # Ground_shipping_premium # drone shipping # Cheapest option
3.65684
4
dev/Gems/CloudGemMetric/v1/AWS/common-code/MemoryUtils/mem_util.py
BadDevCode/lumberyard
1,738
6620640
<gh_stars>1000+ # # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. # # For complete copyright and license terms please see the LICENSE at the root of this # distribution (the "License"). All use of this software is governed by the License, # or, if provided, by the license below or the license accompanying this file. Do not # remove or modify any license notices. This file is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # import time import metric_constant as c import os import psutil def get_memory_usage(): memory = psutil.virtual_memory() return memory.percent def get_process_memory_usage_bytes(): pid = os.getpid() py = psutil.Process(pid) memoryUseBytes = py.memory_info()[0]/2 return memoryUseBytes def get_process_memory_usage_kilobytes(): return get_process_memory_usage_bytes()/1024 def get_process_memory_usage_megabytes(): return get_process_memory_usage_kilobytes()/1024 def get_memory_object(): return psutil.virtual_memory()
# # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. # # For complete copyright and license terms please see the LICENSE at the root of this # distribution (the "License"). All use of this software is governed by the License, # or, if provided, by the license below or the license accompanying this file. Do not # remove or modify any license notices. This file is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # import time import metric_constant as c import os import psutil def get_memory_usage(): memory = psutil.virtual_memory() return memory.percent def get_process_memory_usage_bytes(): pid = os.getpid() py = psutil.Process(pid) memoryUseBytes = py.memory_info()[0]/2 return memoryUseBytes def get_process_memory_usage_kilobytes(): return get_process_memory_usage_bytes()/1024 def get_process_memory_usage_megabytes(): return get_process_memory_usage_kilobytes()/1024 def get_memory_object(): return psutil.virtual_memory()
en
0.878427
# # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. # # For complete copyright and license terms please see the LICENSE at the root of this # distribution (the "License"). All use of this software is governed by the License, # or, if provided, by the license below or the license accompanying this file. Do not # remove or modify any license notices. This file is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
2.367469
2
ippa/proc/__init__.py
PatientPathwayAnalysis/IPPA-py
1
6620641
<reponame>PatientPathwayAnalysis/IPPA-py from .relatedillness import RelatedIllness
from .relatedillness import RelatedIllness
none
1
1.088694
1
hTools2.roboFontExt/lib/Scripts/current glyph/make points smooth.py
frankrolf/hTools2_extension
2
6620642
# [h] convert selected points to `smooth` g = CurrentGlyph() g.prepareUndo('convert to smooth') for c in g: for s in c: for p in s.points: if p not in s.offCurve and p.selected: s.smooth = True g.performUndo()
# [h] convert selected points to `smooth` g = CurrentGlyph() g.prepareUndo('convert to smooth') for c in g: for s in c: for p in s.points: if p not in s.offCurve and p.selected: s.smooth = True g.performUndo()
en
0.592435
# [h] convert selected points to `smooth`
2.696688
3
app/api/routers/users.py
ari-hacks/infra-pipeline
0
6620643
from fastapi import APIRouter, Request, Response, Body, HTTPException,Header from fastapi.responses import PlainTextResponse router = APIRouter() @router.get("/", status_code=200) async def health(): return {"Message":'user endpoint'} @router.get("/health-check", status_code=200) async def health(): return {"Message":'healthy user endpoint'}
from fastapi import APIRouter, Request, Response, Body, HTTPException,Header from fastapi.responses import PlainTextResponse router = APIRouter() @router.get("/", status_code=200) async def health(): return {"Message":'user endpoint'} @router.get("/health-check", status_code=200) async def health(): return {"Message":'healthy user endpoint'}
none
1
2.661938
3
Achilles/label/urls.py
parshwa1999/Map-Segmentation
5
6620644
from django.urls import path from label import views #from label import processing import os urlpatterns = [ path('', views.index, name='index'), path('home/', views.homepage, name='homepage'), path('user_login/', views.user_login, name='user_login'), path('development_tracker/', views.development_tracker, name='developmentTracker'), path('qgis_support/', views.qgis_support, name='qgisSupport'), path('labelme_support/', views.labelme_support, name='labelmeSupport'), path('qgis_support_response/', views.qgis_response, name='qgisResponse'), path('get_csv/', views.get_csv, name='getCsv'), path('get_mask/', views.get_mask, name='getPng'), path('get_json/', views.get_json, name='getJson'), path('labelme_support_response/', views.labelme_response, name='labelmeResponse'), path('development_tracker_response/', views.development_tracker_response, name='developmentTrackerResponse'), ]
from django.urls import path from label import views #from label import processing import os urlpatterns = [ path('', views.index, name='index'), path('home/', views.homepage, name='homepage'), path('user_login/', views.user_login, name='user_login'), path('development_tracker/', views.development_tracker, name='developmentTracker'), path('qgis_support/', views.qgis_support, name='qgisSupport'), path('labelme_support/', views.labelme_support, name='labelmeSupport'), path('qgis_support_response/', views.qgis_response, name='qgisResponse'), path('get_csv/', views.get_csv, name='getCsv'), path('get_mask/', views.get_mask, name='getPng'), path('get_json/', views.get_json, name='getJson'), path('labelme_support_response/', views.labelme_response, name='labelmeResponse'), path('development_tracker_response/', views.development_tracker_response, name='developmentTrackerResponse'), ]
en
0.253504
#from label import processing
1.814504
2
build/tests/test_code_generation.py
ExternalRepositories/ApprovalTests.cpp
259
6620645
<gh_stars>100-1000 import unittest import pyperclip from approvaltests.approvals import verify, verify_all from scripts.code_generation import CppGeneration from scripts.multiline_string_utilities import remove_indentation from tests.helpers import diff_merge_reporter # Convenience variable, so we can paste in code and run test_demo_convert_to_concatenation. # This is at global scope to prevent PyCharm reformatting the indentation when we # paste code in. to_concatenated_string = 'your string here' to_multiline_string = ('your string here') class CodeGeneration: @staticmethod def convert_concatenation_to_multiline(content: str) -> str: lines = content.splitlines() code = "remove_indentation << f'''\n" for line in lines: code += line + '\n' code += "'''" return code @staticmethod def convert_string_to_concatenation(content: str) -> str: lines = content.splitlines() code = '(' for line in lines: if '{' in line: code += 'f' code += f"'{line}\\n'\n" code += ')' return code @staticmethod def convert_string_to_joined_list(content: str) -> str: lines = content.splitlines() code = "'\\n'.join([\n" for line in lines: if '{' in line: code += 'f' code += f"'{line}',\n" code += '])' return code class TestCodeGeneration(unittest.TestCase): def test_convert_string_to_concatentation(self) -> None: content = remove_indentation << ''' toc ## v.x.y.z {self.old_feature_text()} ''' result = CodeGeneration.convert_string_to_concatenation(content) expected = remove_indentation << r""" ('\n' 'toc\n' '\n' '## v.x.y.z\n' '\n' f'{self.old_feature_text()}\n' '\n' )""" self.assertEqual(expected, result) def test_convert_string_to_joined_list(self) -> None: content = remove_indentation << ''' toc ## v.x.y.z {self.old_feature_text()} ''' result = CodeGeneration.convert_string_to_joined_list(content) expected = remove_indentation << r""" '\n'.join([ '', 'toc', '', '## v.x.y.z', '', f'{self.old_feature_text()}', '', ])""" self.assertEqual(expected, result) def test_concatentation_to_multiline(self) -> None: input = ('\n' 'toc\n' '\n' '## v.x.y.z\n' '\n' '{self.old_feature_text()}\n' '\n' ) output = CodeGeneration.convert_concatenation_to_multiline(input) verify(output, diff_merge_reporter) def test_entry_point_for_convert_to_concatenation(self) -> None: if to_concatenated_string != 'your string here': pyperclip.copy(CodeGeneration.convert_string_to_concatenation(to_concatenated_string)) print("converted concatened text copied to clipboard") def test_entry_point_for_convert_to_multiline(self) -> None: if to_multiline_string != 'your string here': code = CodeGeneration.convert_concatenation_to_multiline(to_multiline_string) print(code) pyperclip.copy(code) print("converted multiline text copied to clipboard") def test_validate_single_header_file_content(self) -> None: hs = ["A.h", "B.h"] hpps = ["C.hpp"] source_code_snippets = [ remove_indentation << ''' # Source code is fine: there should be no error message #include <iostream> #include "A.h" #include "B.h" ''', remove_indentation << ''' # A.h is incorrectly included #include <A.h> #include "B.h" ''', remove_indentation << ''' # B.h and C.hpp are incorrectly included: there should ve error messages for both #include <B.h> #include <C.hpp> ''', ] header = f"Testing validation of #include lines, with these header files: {str(hs)} and {str(hpps)}" def validate_includes(source: str) -> str: return f"""===============================\nSource snippet:\n{source}\n=>\nError message (if any):\n{CppGeneration.validate_single_header_file_content(hs, hpps, source)}""" verify_all( header, source_code_snippets, lambda source: validate_includes(source)) if __name__ == '__main__': unittest.main()
import unittest import pyperclip from approvaltests.approvals import verify, verify_all from scripts.code_generation import CppGeneration from scripts.multiline_string_utilities import remove_indentation from tests.helpers import diff_merge_reporter # Convenience variable, so we can paste in code and run test_demo_convert_to_concatenation. # This is at global scope to prevent PyCharm reformatting the indentation when we # paste code in. to_concatenated_string = 'your string here' to_multiline_string = ('your string here') class CodeGeneration: @staticmethod def convert_concatenation_to_multiline(content: str) -> str: lines = content.splitlines() code = "remove_indentation << f'''\n" for line in lines: code += line + '\n' code += "'''" return code @staticmethod def convert_string_to_concatenation(content: str) -> str: lines = content.splitlines() code = '(' for line in lines: if '{' in line: code += 'f' code += f"'{line}\\n'\n" code += ')' return code @staticmethod def convert_string_to_joined_list(content: str) -> str: lines = content.splitlines() code = "'\\n'.join([\n" for line in lines: if '{' in line: code += 'f' code += f"'{line}',\n" code += '])' return code class TestCodeGeneration(unittest.TestCase): def test_convert_string_to_concatentation(self) -> None: content = remove_indentation << ''' toc ## v.x.y.z {self.old_feature_text()} ''' result = CodeGeneration.convert_string_to_concatenation(content) expected = remove_indentation << r""" ('\n' 'toc\n' '\n' '## v.x.y.z\n' '\n' f'{self.old_feature_text()}\n' '\n' )""" self.assertEqual(expected, result) def test_convert_string_to_joined_list(self) -> None: content = remove_indentation << ''' toc ## v.x.y.z {self.old_feature_text()} ''' result = CodeGeneration.convert_string_to_joined_list(content) expected = remove_indentation << r""" '\n'.join([ '', 'toc', '', '## v.x.y.z', '', f'{self.old_feature_text()}', '', ])""" self.assertEqual(expected, result) def test_concatentation_to_multiline(self) -> None: input = ('\n' 'toc\n' '\n' '## v.x.y.z\n' '\n' '{self.old_feature_text()}\n' '\n' ) output = CodeGeneration.convert_concatenation_to_multiline(input) verify(output, diff_merge_reporter) def test_entry_point_for_convert_to_concatenation(self) -> None: if to_concatenated_string != 'your string here': pyperclip.copy(CodeGeneration.convert_string_to_concatenation(to_concatenated_string)) print("converted concatened text copied to clipboard") def test_entry_point_for_convert_to_multiline(self) -> None: if to_multiline_string != 'your string here': code = CodeGeneration.convert_concatenation_to_multiline(to_multiline_string) print(code) pyperclip.copy(code) print("converted multiline text copied to clipboard") def test_validate_single_header_file_content(self) -> None: hs = ["A.h", "B.h"] hpps = ["C.hpp"] source_code_snippets = [ remove_indentation << ''' # Source code is fine: there should be no error message #include <iostream> #include "A.h" #include "B.h" ''', remove_indentation << ''' # A.h is incorrectly included #include <A.h> #include "B.h" ''', remove_indentation << ''' # B.h and C.hpp are incorrectly included: there should ve error messages for both #include <B.h> #include <C.hpp> ''', ] header = f"Testing validation of #include lines, with these header files: {str(hs)} and {str(hpps)}" def validate_includes(source: str) -> str: return f"""===============================\nSource snippet:\n{source}\n=>\nError message (if any):\n{CppGeneration.validate_single_header_file_content(hs, hpps, source)}""" verify_all( header, source_code_snippets, lambda source: validate_includes(source)) if __name__ == '__main__': unittest.main()
en
0.530381
# Convenience variable, so we can paste in code and run test_demo_convert_to_concatenation. # This is at global scope to prevent PyCharm reformatting the indentation when we # paste code in. \n" for line in lines: code += line + '\n' code += " toc ## v.x.y.z {self.old_feature_text()} ('\n' 'toc\n' '\n' '## v.x.y.z\n' '\n' f'{self.old_feature_text()}\n' '\n' ) toc ## v.x.y.z {self.old_feature_text()} '\n'.join([ '', 'toc', '', '## v.x.y.z', '', f'{self.old_feature_text()}', '', ]) # v.x.y.z\n' # Source code is fine: there should be no error message #include <iostream> #include "A.h" #include "B.h" # A.h is incorrectly included #include <A.h> #include "B.h" # B.h and C.hpp are incorrectly included: there should ve error messages for both #include <B.h> #include <C.hpp> #include lines, with these header files: {str(hs)} and {str(hpps)}" ===============================\nSource snippet:\n{source}\n=>\nError message (if any):\n{CppGeneration.validate_single_header_file_content(hs, hpps, source)}
2.847451
3
hogwarts/data/readers/ceph_reader.py
PingchuanMa/hogwarts
4
6620646
<reponame>PingchuanMa/hogwarts<filename>hogwarts/data/readers/ceph_reader.py __all__ = ['CephReader'] import ceph import glog glog.setLevel(glog.logging.ERROR) class CephReader: def __call__(self, path): s3client = ceph.S3Client() content = s3client.Get(path) return content
__all__ = ['CephReader'] import ceph import glog glog.setLevel(glog.logging.ERROR) class CephReader: def __call__(self, path): s3client = ceph.S3Client() content = s3client.Get(path) return content
none
1
2.053192
2
backend/webapp/models.py
MehdiNV/hackzurich19-suisse-cheese
0
6620647
from django.db import models # Create your models here. class Articles(models.Model): title = models.CharField(max_length=200, default=None) timestamp = models.DateTimeField(default=None) body = models.CharField(max_length=1000, default=None) journal = models.CharField(max_length=200, default=None) def __str__(self): return self.title
from django.db import models # Create your models here. class Articles(models.Model): title = models.CharField(max_length=200, default=None) timestamp = models.DateTimeField(default=None) body = models.CharField(max_length=1000, default=None) journal = models.CharField(max_length=200, default=None) def __str__(self): return self.title
en
0.963489
# Create your models here.
2.534593
3
util_kerasmodel_to_tensorflow-pb.py
galsh17/cartwheel_train
32
6620648
#-------------------------------------------------------------------------------# # Utility to convert Keras model to Tensorflow's .PB (proto-binary) and then to # Nvidia libnvinfer's uff format. With UFF one can execute models on # TensorRT compatible devices like TX2. # # Author : <NAME> <<EMAIL>> # Created: 29th May, 2019 # Site : https://kusemanohar.wordpress.com/2019/05/25/hands-on-tensorrt-on-nvidiatx2/ #-------------------------------------------------------------------------------# import keras import numpy as np import os import tensorflow as tf from CustomNets import NetVLADLayer, GhostVLADLayer from predict_utils import change_model_inputshape from keras import backend as K import TerminalColors tcol = TerminalColors.bcolors() import argparse def load_keras_hdf5_model( kerasmodel_h5file, verbose=True ): """ Loads keras model from a HDF5 file """ assert os.path.isfile( kerasmodel_h5file ), 'The model weights file doesnot exists or there is a permission issue.'+"kerasmodel_file="+kerasmodel_h5file K.set_learning_phase(0) model = keras.models.load_model(kerasmodel_h5file, custom_objects={'NetVLADLayer': NetVLADLayer, 'GhostVLADLayer': GhostVLADLayer} ) if verbose: model.summary(); print tcol.OKGREEN, 'Successfully Loaded kerasmodel_h5file: ', tcol.ENDC, kerasmodel_h5file return model def load_basic_model( ): K.set_learning_phase(0) from CustomNets import make_from_mobilenet, make_from_vgg16 from CustomNets import NetVLADLayer, GhostVLADLayer # Please choose only one of these. if False: # VGG input_img = keras.layers.Input( shape=(240, 320, 3 ) ) cnn = make_from_vgg16( input_img, weights=None, layer_name='block5_pool', kernel_regularizer=keras.regularizers.l2(0.01) ) model = keras.models.Model( inputs=input_img, outputs=cnn ) if True: #mobilenet input_img = keras.layers.Input( shape=(240, 320, 3 ) ) cnn = make_from_mobilenet( input_img, layer_name='conv_pw_5_relu', weights=None, kernel_regularizer=keras.regularizers.l2(0.01) ) model = keras.models.Model( inputs=input_img, outputs=cnn ) if False: #mobilenet+netvlad input_img = keras.layers.Input( shape=(240, 320, 3 ) ) cnn = make_from_mobilenet( input_img, layer_name='conv_pw_5_relu', weights=None, kernel_regularizer=keras.regularizers.l2(0.01) ) # cnn = make_from_vgg16( input_img, weights=None, layer_name='block5_pool', kernel_regularizer=keras.regularizers.l2(0.01) ) out = NetVLADLayer(num_clusters = 16)( cnn ) model = keras.models.Model( inputs=input_img, outputs=out ) if False: #netvlad only input_img = keras.layers.Input( shape=(60, 80, 256 ) ) out = NetVLADLayer(num_clusters = 16)( input_img ) model = keras.models.Model( inputs=input_img, outputs=out ) model.summary() return model def write_kerasmodel_as_tensorflow_pb( model, LOG_DIR, output_model_name='output_model.pb' ): """ Takes as input a keras.models.Model() and writes out Tensorflow proto-binary. """ print tcol.HEADER,'[write_kerasmodel_as_tensorflow_pb] Start', tcol.ENDC import tensorflow as tf from tensorflow.python.framework import graph_util from tensorflow.python.framework import graph_io K.set_learning_phase(0) sess = K.get_session() # Make const print 'Make Computation Graph as Constant and Prune unnecessary stuff from it' constant_graph = graph_util.convert_variables_to_constants( sess, sess.graph.as_graph_def(), [node.op.name for node in model.outputs]) constant_graph = tf.graph_util.remove_training_nodes(constant_graph) #--- convert Switch --> Identity # I am doing this because TensorRT cannot process Switch operations. # # https://github.com/tensorflow/tensorflow/issues/8404#issuecomment-297469468 # for node in constant_graph.node: # if node.op == "Switch": # node.op = "Identity" # del node.input[1] # # END # Write .pb # output_model_name = 'output_model.pb' print tcol.OKGREEN, 'Write ', output_model_name, tcol.ENDC print 'model.outputs=', [node.op.name for node in model.outputs] graph_io.write_graph(constant_graph, LOG_DIR, output_model_name, as_text=False) print tcol.HEADER, '[write_kerasmodel_as_tensorflow_pb] Done', tcol.ENDC # Write .pbtxt (for viz only) output_model_pbtxt_name = output_model_name+'.pbtxt' #'output_model.pbtxt' print tcol.OKGREEN, 'Write ', output_model_pbtxt_name, tcol.ENDC tf.train.write_graph(constant_graph, LOG_DIR, output_model_pbtxt_name, as_text=True) # Write model.summary to file (to get info on input and output shapes) output_modelsummary_fname = LOG_DIR+'/'+output_model_name + '.modelsummary.log' print tcol.OKGREEN, 'Write ', output_modelsummary_fname, tcol.ENDC with open(output_modelsummary_fname,'w') as fh: # Pass the file handle in as a lambda function to make it callable model.summary(print_fn=lambda x: fh.write(x + '\n')) if __name__ == '__main__': #--- # Parse Command line parser = argparse.ArgumentParser(description='Convert Keras hdf5 models to .uff models for TensorRT.') parser.add_argument('--kerasmodel_h5file', '-h5', required=True, type=str, help='The input keras modelarch_and_weights full filename') args = parser.parse_args() #--- # Paths, File Init and other initialize # kerasmodel_h5file = 'models.keras/June2019/centeredinput-m1to1-240x320x3__mobilenet-conv_pw_6_relu__K16__allpairloss/modelarch_and_weights.700.h5' kerasmodel_h5file = args.kerasmodel_h5file LOG_DIR = '/'.join( kerasmodel_h5file.split('/')[0:-1] ) print tcol.HEADER print '##------------------------------------------------------------##' print '## kerasmodel_h5file = ', kerasmodel_h5file print '## LOG_DIR = ', LOG_DIR print '##------------------------------------------------------------##' print tcol.ENDC #--- # Load HDF5 Keras model model = load_keras_hdf5_model( kerasmodel_h5file, verbose=True ) #this # model = load_basic_model() # quit() #----- # Replace Input Layer's Dimensions im_rows = None#480 im_cols = 752 im_chnls = 3 if im_rows == None or im_cols == None or im_chnls == None: print tcol.WARNING, 'NOT doing `change_model_inputshape`', tcol.ENDC new_model = model else: # change_model_inputshape uses model_from_json internally, I feel a bit uncomfortable about this. new_model = change_model_inputshape( model, new_input_shape=(1,im_rows,im_cols,im_chnls), verbose=True ) print 'OLD MODEL: ', 'input_shape=', str(model.inputs) print 'NEW MODEL: input_shape=', str(new_model.inputs) #----- # Write Tensorflow (atleast 1.12) proto-binary (.pb) # write_kerasmodel_as_tensorflow_pb( new_model, LOG_DIR=LOG_DIR, output_model_name='output_model.pb' ) out_pb_fname = '.'.join( (kerasmodel_h5file.split('/')[-1]).split('.')[:-1] )+'.pb' write_kerasmodel_as_tensorflow_pb( new_model, LOG_DIR=LOG_DIR, output_model_name=out_pb_fname )
#-------------------------------------------------------------------------------# # Utility to convert Keras model to Tensorflow's .PB (proto-binary) and then to # Nvidia libnvinfer's uff format. With UFF one can execute models on # TensorRT compatible devices like TX2. # # Author : <NAME> <<EMAIL>> # Created: 29th May, 2019 # Site : https://kusemanohar.wordpress.com/2019/05/25/hands-on-tensorrt-on-nvidiatx2/ #-------------------------------------------------------------------------------# import keras import numpy as np import os import tensorflow as tf from CustomNets import NetVLADLayer, GhostVLADLayer from predict_utils import change_model_inputshape from keras import backend as K import TerminalColors tcol = TerminalColors.bcolors() import argparse def load_keras_hdf5_model( kerasmodel_h5file, verbose=True ): """ Loads keras model from a HDF5 file """ assert os.path.isfile( kerasmodel_h5file ), 'The model weights file doesnot exists or there is a permission issue.'+"kerasmodel_file="+kerasmodel_h5file K.set_learning_phase(0) model = keras.models.load_model(kerasmodel_h5file, custom_objects={'NetVLADLayer': NetVLADLayer, 'GhostVLADLayer': GhostVLADLayer} ) if verbose: model.summary(); print tcol.OKGREEN, 'Successfully Loaded kerasmodel_h5file: ', tcol.ENDC, kerasmodel_h5file return model def load_basic_model( ): K.set_learning_phase(0) from CustomNets import make_from_mobilenet, make_from_vgg16 from CustomNets import NetVLADLayer, GhostVLADLayer # Please choose only one of these. if False: # VGG input_img = keras.layers.Input( shape=(240, 320, 3 ) ) cnn = make_from_vgg16( input_img, weights=None, layer_name='block5_pool', kernel_regularizer=keras.regularizers.l2(0.01) ) model = keras.models.Model( inputs=input_img, outputs=cnn ) if True: #mobilenet input_img = keras.layers.Input( shape=(240, 320, 3 ) ) cnn = make_from_mobilenet( input_img, layer_name='conv_pw_5_relu', weights=None, kernel_regularizer=keras.regularizers.l2(0.01) ) model = keras.models.Model( inputs=input_img, outputs=cnn ) if False: #mobilenet+netvlad input_img = keras.layers.Input( shape=(240, 320, 3 ) ) cnn = make_from_mobilenet( input_img, layer_name='conv_pw_5_relu', weights=None, kernel_regularizer=keras.regularizers.l2(0.01) ) # cnn = make_from_vgg16( input_img, weights=None, layer_name='block5_pool', kernel_regularizer=keras.regularizers.l2(0.01) ) out = NetVLADLayer(num_clusters = 16)( cnn ) model = keras.models.Model( inputs=input_img, outputs=out ) if False: #netvlad only input_img = keras.layers.Input( shape=(60, 80, 256 ) ) out = NetVLADLayer(num_clusters = 16)( input_img ) model = keras.models.Model( inputs=input_img, outputs=out ) model.summary() return model def write_kerasmodel_as_tensorflow_pb( model, LOG_DIR, output_model_name='output_model.pb' ): """ Takes as input a keras.models.Model() and writes out Tensorflow proto-binary. """ print tcol.HEADER,'[write_kerasmodel_as_tensorflow_pb] Start', tcol.ENDC import tensorflow as tf from tensorflow.python.framework import graph_util from tensorflow.python.framework import graph_io K.set_learning_phase(0) sess = K.get_session() # Make const print 'Make Computation Graph as Constant and Prune unnecessary stuff from it' constant_graph = graph_util.convert_variables_to_constants( sess, sess.graph.as_graph_def(), [node.op.name for node in model.outputs]) constant_graph = tf.graph_util.remove_training_nodes(constant_graph) #--- convert Switch --> Identity # I am doing this because TensorRT cannot process Switch operations. # # https://github.com/tensorflow/tensorflow/issues/8404#issuecomment-297469468 # for node in constant_graph.node: # if node.op == "Switch": # node.op = "Identity" # del node.input[1] # # END # Write .pb # output_model_name = 'output_model.pb' print tcol.OKGREEN, 'Write ', output_model_name, tcol.ENDC print 'model.outputs=', [node.op.name for node in model.outputs] graph_io.write_graph(constant_graph, LOG_DIR, output_model_name, as_text=False) print tcol.HEADER, '[write_kerasmodel_as_tensorflow_pb] Done', tcol.ENDC # Write .pbtxt (for viz only) output_model_pbtxt_name = output_model_name+'.pbtxt' #'output_model.pbtxt' print tcol.OKGREEN, 'Write ', output_model_pbtxt_name, tcol.ENDC tf.train.write_graph(constant_graph, LOG_DIR, output_model_pbtxt_name, as_text=True) # Write model.summary to file (to get info on input and output shapes) output_modelsummary_fname = LOG_DIR+'/'+output_model_name + '.modelsummary.log' print tcol.OKGREEN, 'Write ', output_modelsummary_fname, tcol.ENDC with open(output_modelsummary_fname,'w') as fh: # Pass the file handle in as a lambda function to make it callable model.summary(print_fn=lambda x: fh.write(x + '\n')) if __name__ == '__main__': #--- # Parse Command line parser = argparse.ArgumentParser(description='Convert Keras hdf5 models to .uff models for TensorRT.') parser.add_argument('--kerasmodel_h5file', '-h5', required=True, type=str, help='The input keras modelarch_and_weights full filename') args = parser.parse_args() #--- # Paths, File Init and other initialize # kerasmodel_h5file = 'models.keras/June2019/centeredinput-m1to1-240x320x3__mobilenet-conv_pw_6_relu__K16__allpairloss/modelarch_and_weights.700.h5' kerasmodel_h5file = args.kerasmodel_h5file LOG_DIR = '/'.join( kerasmodel_h5file.split('/')[0:-1] ) print tcol.HEADER print '##------------------------------------------------------------##' print '## kerasmodel_h5file = ', kerasmodel_h5file print '## LOG_DIR = ', LOG_DIR print '##------------------------------------------------------------##' print tcol.ENDC #--- # Load HDF5 Keras model model = load_keras_hdf5_model( kerasmodel_h5file, verbose=True ) #this # model = load_basic_model() # quit() #----- # Replace Input Layer's Dimensions im_rows = None#480 im_cols = 752 im_chnls = 3 if im_rows == None or im_cols == None or im_chnls == None: print tcol.WARNING, 'NOT doing `change_model_inputshape`', tcol.ENDC new_model = model else: # change_model_inputshape uses model_from_json internally, I feel a bit uncomfortable about this. new_model = change_model_inputshape( model, new_input_shape=(1,im_rows,im_cols,im_chnls), verbose=True ) print 'OLD MODEL: ', 'input_shape=', str(model.inputs) print 'NEW MODEL: input_shape=', str(new_model.inputs) #----- # Write Tensorflow (atleast 1.12) proto-binary (.pb) # write_kerasmodel_as_tensorflow_pb( new_model, LOG_DIR=LOG_DIR, output_model_name='output_model.pb' ) out_pb_fname = '.'.join( (kerasmodel_h5file.split('/')[-1]).split('.')[:-1] )+'.pb' write_kerasmodel_as_tensorflow_pb( new_model, LOG_DIR=LOG_DIR, output_model_name=out_pb_fname )
en
0.472929
#-------------------------------------------------------------------------------# # Utility to convert Keras model to Tensorflow's .PB (proto-binary) and then to # Nvidia libnvinfer's uff format. With UFF one can execute models on # TensorRT compatible devices like TX2. # # Author : <NAME> <<EMAIL>> # Created: 29th May, 2019 # Site : https://kusemanohar.wordpress.com/2019/05/25/hands-on-tensorrt-on-nvidiatx2/ #-------------------------------------------------------------------------------# Loads keras model from a HDF5 file # Please choose only one of these. # VGG #mobilenet #mobilenet+netvlad # cnn = make_from_vgg16( input_img, weights=None, layer_name='block5_pool', kernel_regularizer=keras.regularizers.l2(0.01) ) #netvlad only Takes as input a keras.models.Model() and writes out Tensorflow proto-binary. # Make const #--- convert Switch --> Identity # I am doing this because TensorRT cannot process Switch operations. # # https://github.com/tensorflow/tensorflow/issues/8404#issuecomment-297469468 # for node in constant_graph.node: # if node.op == "Switch": # node.op = "Identity" # del node.input[1] # # END # Write .pb # output_model_name = 'output_model.pb' # Write .pbtxt (for viz only) #'output_model.pbtxt' # Write model.summary to file (to get info on input and output shapes) # Pass the file handle in as a lambda function to make it callable #--- # Parse Command line #--- # Paths, File Init and other initialize # kerasmodel_h5file = 'models.keras/June2019/centeredinput-m1to1-240x320x3__mobilenet-conv_pw_6_relu__K16__allpairloss/modelarch_and_weights.700.h5' #------------------------------------------------------------##' # kerasmodel_h5file = ', kerasmodel_h5file # LOG_DIR = ', LOG_DIR #------------------------------------------------------------##' #--- # Load HDF5 Keras model #this # model = load_basic_model() # quit() #----- # Replace Input Layer's Dimensions #480 # change_model_inputshape uses model_from_json internally, I feel a bit uncomfortable about this. #----- # Write Tensorflow (atleast 1.12) proto-binary (.pb) # write_kerasmodel_as_tensorflow_pb( new_model, LOG_DIR=LOG_DIR, output_model_name='output_model.pb' )
2.554977
3
Homework2/scripts/cone_maker.py
Doruk-Coskun/ceng477-rasterization
0
6620649
<reponame>Doruk-Coskun/ceng477-rasterization # author: <NAME> # more info: https://github.com/arifgorkemozer/3dgeometricshapes/ import math import sys if len(sys.argv) < 8: print "Usage: python cone_maker.py <cone_bottom_center_x>\n\t\t\t<cone_bottom_center_y>\n\t\t\t<cone_bottom_z_coord>\n\t\t\t<cone_top_distance>\n\t\t\t<cone_bottom_radius>\n\t\t\t<step_threshold>\n\t\t\t<last_vertex_id_in_3d_space>\n\t\t\t<color_primary: \"R|G|B\">\n\t\t\t<color_secondary: \"R|G|B\">\n\t\t\t<color_bottom_center: \"R|G|B\">\n\t\t\t<color_top: \"R|G|B\">" else: center_x = (float)(sys.argv[1]) center_y = (float)(sys.argv[2]) cone_bottom_z_coord = (float)(sys.argv[3]) cone_top_distance = (float)(sys.argv[4]) radius = (float)(sys.argv[5]) step_threshold = (float)(sys.argv[6]) last_vertex_id = (int)(sys.argv[7]) color_primary = None color_secondary = None color_cone_bottom_center = None color_cone_top = None if len(sys.argv) == 12: color_primary_values = sys.argv[8].split("|") color_secondary_values = sys.argv[9].split("|") color_bottom_values = sys.argv[10].split("|") color_top_values = sys.argv[11].split("|") cpv = [int(n) for n in color_primary_values] csv = [int(n) for n in color_secondary_values] cbv = [int(n) for n in color_bottom_values] ctv = [int(n) for n in color_top_values] color_primary = tuple(cpv) color_secondary = tuple(csv) color_cone_bottom_center = tuple(cbv) color_cone_top = tuple(ctv) else: color_primary = (255, 0, 0) color_secondary = (0, 0, 255) color_cone_bottom_center = (0, 255, 0) color_cone_top = (0, 255, 255) x = -radius points = [] while x <= radius: points.append( (x, math.sqrt(radius**2 - x**2), cone_bottom_z_coord) ) x += step_threshold points_inv = points[::-1] for elem in points_inv[1:]: points.append( (elem[0], -elem[1], elem[2]) ) # add bottom center points.append( (center_x, center_y, cone_bottom_z_coord) ) # add cone top points.append( (center_x, center_y, cone_bottom_z_coord - cone_top_distance) ) triangles = [] front_last_vertex_id = len(points)-2 front_center_id = len(points)-1 back_center_id = len(points) # cone bottom triangles (to cone bottom center) for i in range(1, front_last_vertex_id): triangles.append( (front_center_id +last_vertex_id, i+1 +last_vertex_id, i +last_vertex_id) ) # cone side triangles (to cone top) for i in range(1, front_last_vertex_id): triangles.append( (back_center_id +last_vertex_id, i +last_vertex_id, i+1 +last_vertex_id ) ) colors = [] for i in range(1, front_last_vertex_id+1): if i % 2 == 1: colors.append( color_primary ) else: colors.append( color_secondary ) colors.append(color_cone_bottom_center) colors.append(color_cone_top) print "Colors:" for c in colors: print c[0], c[1], c[2] print "Positions:", len(points) for elem in points: print elem[0], elem[1], elem[2] print "Triangles:", len(triangles) for tri in triangles: print tri[0], tri[1], tri[2] print len(points), "points created" print len(triangles), "triangles created" # write to a 3d scene file with open("cone_scene.txt", 'w') as f: f.write("100 100 100") f.write("\n") f.write("1") f.write("\n") f.write("#Vertices") f.write("\n") f.write(str(len(points))) f.write("\n") f.write("#Colors") f.write("\n") for c in colors: f.write( str(c[0]) + " " + str(c[1]) + " " + str(c[2])) f.write("\n") f.write("#Positions") f.write("\n") for elem in points: f.write( str(elem[0]) + " " + str(elem[1]) + " " + str(elem[2])) f.write("\n") f.write("#Translations") f.write("\n") f.write("0") f.write("\n") f.write("#Scalings") f.write("\n") f.write("0") f.write("\n") f.write("#Rotations") f.write("\n") f.write("0") f.write("\n") f.write("#Models") f.write("\n") f.write("1") f.write("\n") f.write("1") f.write("\n") f.write("1") f.write("\n") f.write("0") f.write("\n") f.write(str(len(triangles))) f.write("\n") for tri in triangles: f.write( str(tri[0]) + " " + str(tri[1]) + " " + str(tri[2])) f.write("\n")
# author: <NAME> # more info: https://github.com/arifgorkemozer/3dgeometricshapes/ import math import sys if len(sys.argv) < 8: print "Usage: python cone_maker.py <cone_bottom_center_x>\n\t\t\t<cone_bottom_center_y>\n\t\t\t<cone_bottom_z_coord>\n\t\t\t<cone_top_distance>\n\t\t\t<cone_bottom_radius>\n\t\t\t<step_threshold>\n\t\t\t<last_vertex_id_in_3d_space>\n\t\t\t<color_primary: \"R|G|B\">\n\t\t\t<color_secondary: \"R|G|B\">\n\t\t\t<color_bottom_center: \"R|G|B\">\n\t\t\t<color_top: \"R|G|B\">" else: center_x = (float)(sys.argv[1]) center_y = (float)(sys.argv[2]) cone_bottom_z_coord = (float)(sys.argv[3]) cone_top_distance = (float)(sys.argv[4]) radius = (float)(sys.argv[5]) step_threshold = (float)(sys.argv[6]) last_vertex_id = (int)(sys.argv[7]) color_primary = None color_secondary = None color_cone_bottom_center = None color_cone_top = None if len(sys.argv) == 12: color_primary_values = sys.argv[8].split("|") color_secondary_values = sys.argv[9].split("|") color_bottom_values = sys.argv[10].split("|") color_top_values = sys.argv[11].split("|") cpv = [int(n) for n in color_primary_values] csv = [int(n) for n in color_secondary_values] cbv = [int(n) for n in color_bottom_values] ctv = [int(n) for n in color_top_values] color_primary = tuple(cpv) color_secondary = tuple(csv) color_cone_bottom_center = tuple(cbv) color_cone_top = tuple(ctv) else: color_primary = (255, 0, 0) color_secondary = (0, 0, 255) color_cone_bottom_center = (0, 255, 0) color_cone_top = (0, 255, 255) x = -radius points = [] while x <= radius: points.append( (x, math.sqrt(radius**2 - x**2), cone_bottom_z_coord) ) x += step_threshold points_inv = points[::-1] for elem in points_inv[1:]: points.append( (elem[0], -elem[1], elem[2]) ) # add bottom center points.append( (center_x, center_y, cone_bottom_z_coord) ) # add cone top points.append( (center_x, center_y, cone_bottom_z_coord - cone_top_distance) ) triangles = [] front_last_vertex_id = len(points)-2 front_center_id = len(points)-1 back_center_id = len(points) # cone bottom triangles (to cone bottom center) for i in range(1, front_last_vertex_id): triangles.append( (front_center_id +last_vertex_id, i+1 +last_vertex_id, i +last_vertex_id) ) # cone side triangles (to cone top) for i in range(1, front_last_vertex_id): triangles.append( (back_center_id +last_vertex_id, i +last_vertex_id, i+1 +last_vertex_id ) ) colors = [] for i in range(1, front_last_vertex_id+1): if i % 2 == 1: colors.append( color_primary ) else: colors.append( color_secondary ) colors.append(color_cone_bottom_center) colors.append(color_cone_top) print "Colors:" for c in colors: print c[0], c[1], c[2] print "Positions:", len(points) for elem in points: print elem[0], elem[1], elem[2] print "Triangles:", len(triangles) for tri in triangles: print tri[0], tri[1], tri[2] print len(points), "points created" print len(triangles), "triangles created" # write to a 3d scene file with open("cone_scene.txt", 'w') as f: f.write("100 100 100") f.write("\n") f.write("1") f.write("\n") f.write("#Vertices") f.write("\n") f.write(str(len(points))) f.write("\n") f.write("#Colors") f.write("\n") for c in colors: f.write( str(c[0]) + " " + str(c[1]) + " " + str(c[2])) f.write("\n") f.write("#Positions") f.write("\n") for elem in points: f.write( str(elem[0]) + " " + str(elem[1]) + " " + str(elem[2])) f.write("\n") f.write("#Translations") f.write("\n") f.write("0") f.write("\n") f.write("#Scalings") f.write("\n") f.write("0") f.write("\n") f.write("#Rotations") f.write("\n") f.write("0") f.write("\n") f.write("#Models") f.write("\n") f.write("1") f.write("\n") f.write("1") f.write("\n") f.write("1") f.write("\n") f.write("0") f.write("\n") f.write(str(len(triangles))) f.write("\n") for tri in triangles: f.write( str(tri[0]) + " " + str(tri[1]) + " " + str(tri[2])) f.write("\n")
en
0.682237
# author: <NAME> # more info: https://github.com/arifgorkemozer/3dgeometricshapes/ # add bottom center # add cone top # cone bottom triangles (to cone bottom center) # cone side triangles (to cone top) # write to a 3d scene file
2.561173
3
tests/unit/utils/test_file_hash.py
blade2005/runway
134
6620650
<reponame>blade2005/runway<gh_stars>100-1000 """Test runway.utils._file_hash.""" # pylint: disable=no-self-use # pyright: basic from __future__ import annotations import hashlib from typing import TYPE_CHECKING import pytest from runway.utils._file_hash import FileHash if TYPE_CHECKING: from pathlib import Path MODULE = "runway.utils._file_hash" ALGS_TO_TEST = ["md5", "sha256"] class TestFileHash: """Test FileHash.""" @pytest.mark.parametrize("alg", ALGS_TO_TEST) def test_add_file(self, alg: str, tmp_path: Path) -> None: """Test add_file.""" content = "hello world!" expected = hashlib.new(alg) expected.update(content.encode()) test_file = tmp_path / "test.txt" test_file.write_text(content) result = FileHash(hashlib.new(alg)) result.add_file(test_file) assert result.digest_size == expected.digest_size assert result.digest == expected.digest() assert result.hexdigest == expected.hexdigest() @pytest.mark.parametrize("alg", ALGS_TO_TEST) def test_add_file_name(self, alg: str, tmp_path: Path) -> None: """Test add_file_name.""" test_file = tmp_path / "test.txt" test_file.resolve() expected = hashlib.new(alg) expected.update((str(test_file) + "\0").encode()) result_path = FileHash(hashlib.new(alg)) result_path.add_file_name(test_file) assert result_path.digest_size == expected.digest_size assert result_path.digest == expected.digest() assert result_path.hexdigest == expected.hexdigest() result_str = FileHash(hashlib.new(alg)) result_str.add_file_name(str(test_file)) assert result_str.digest_size == expected.digest_size assert result_str.digest == expected.digest() assert result_str.hexdigest == expected.hexdigest() @pytest.mark.parametrize("alg", ALGS_TO_TEST) def test_add_file_name_relative(self, alg: str, tmp_path: Path) -> None: """Test add_file_name.""" tld = tmp_path.parents[0] test_file = tmp_path / "test.txt" test_file.resolve() expected = hashlib.new(alg) expected.update((str(test_file.relative_to(tld)) + "\0").encode()) result_path = FileHash(hashlib.new(alg)) result_path.add_file_name(test_file, relative_to=tld) assert result_path.digest_size == expected.digest_size assert result_path.digest == expected.digest() assert result_path.hexdigest == expected.hexdigest() result_str = FileHash(hashlib.new(alg)) result_str.add_file_name(str(test_file), relative_to=tld) assert result_str.digest_size == expected.digest_size assert result_str.digest == expected.digest() assert result_str.hexdigest == expected.hexdigest() @pytest.mark.parametrize("alg", ALGS_TO_TEST) def test_add_files(self, alg: str, tmp_path: Path) -> None: """Test add_file.""" content = "hello world!" test_file0 = tmp_path / "test0.txt" test_file0.write_text(content) test_file1 = tmp_path / "test1.txt" test_file1.write_text(content) expected = hashlib.new(alg) for test_file in [test_file0, test_file1]: expected.update((str(test_file) + "\0").encode()) expected.update((content + "\0").encode()) result = FileHash(hashlib.new(alg)) result.add_files([test_file0, test_file1]) assert result.digest_size == expected.digest_size assert result.digest == expected.digest() assert result.hexdigest == expected.hexdigest() @pytest.mark.parametrize("alg", ALGS_TO_TEST) def test_add_files_relative(self, alg: str, tmp_path: Path) -> None: """Test add_file.""" tld = tmp_path.parents[0] content = "hello world!" test_file0 = tmp_path / "test0.txt" test_file0.write_text(content) test_file1 = tmp_path / "test1.txt" test_file1.write_text(content) expected = hashlib.new(alg) for test_file in [test_file0, test_file1]: expected.update((str(test_file.relative_to(tld)) + "\0").encode()) expected.update((content + "\0").encode()) result = FileHash(hashlib.new(alg)) result.add_files([test_file0, test_file1], relative_to=tld) assert result.digest_size == expected.digest_size assert result.digest == expected.digest() assert result.hexdigest == expected.hexdigest()
"""Test runway.utils._file_hash.""" # pylint: disable=no-self-use # pyright: basic from __future__ import annotations import hashlib from typing import TYPE_CHECKING import pytest from runway.utils._file_hash import FileHash if TYPE_CHECKING: from pathlib import Path MODULE = "runway.utils._file_hash" ALGS_TO_TEST = ["md5", "sha256"] class TestFileHash: """Test FileHash.""" @pytest.mark.parametrize("alg", ALGS_TO_TEST) def test_add_file(self, alg: str, tmp_path: Path) -> None: """Test add_file.""" content = "hello world!" expected = hashlib.new(alg) expected.update(content.encode()) test_file = tmp_path / "test.txt" test_file.write_text(content) result = FileHash(hashlib.new(alg)) result.add_file(test_file) assert result.digest_size == expected.digest_size assert result.digest == expected.digest() assert result.hexdigest == expected.hexdigest() @pytest.mark.parametrize("alg", ALGS_TO_TEST) def test_add_file_name(self, alg: str, tmp_path: Path) -> None: """Test add_file_name.""" test_file = tmp_path / "test.txt" test_file.resolve() expected = hashlib.new(alg) expected.update((str(test_file) + "\0").encode()) result_path = FileHash(hashlib.new(alg)) result_path.add_file_name(test_file) assert result_path.digest_size == expected.digest_size assert result_path.digest == expected.digest() assert result_path.hexdigest == expected.hexdigest() result_str = FileHash(hashlib.new(alg)) result_str.add_file_name(str(test_file)) assert result_str.digest_size == expected.digest_size assert result_str.digest == expected.digest() assert result_str.hexdigest == expected.hexdigest() @pytest.mark.parametrize("alg", ALGS_TO_TEST) def test_add_file_name_relative(self, alg: str, tmp_path: Path) -> None: """Test add_file_name.""" tld = tmp_path.parents[0] test_file = tmp_path / "test.txt" test_file.resolve() expected = hashlib.new(alg) expected.update((str(test_file.relative_to(tld)) + "\0").encode()) result_path = FileHash(hashlib.new(alg)) result_path.add_file_name(test_file, relative_to=tld) assert result_path.digest_size == expected.digest_size assert result_path.digest == expected.digest() assert result_path.hexdigest == expected.hexdigest() result_str = FileHash(hashlib.new(alg)) result_str.add_file_name(str(test_file), relative_to=tld) assert result_str.digest_size == expected.digest_size assert result_str.digest == expected.digest() assert result_str.hexdigest == expected.hexdigest() @pytest.mark.parametrize("alg", ALGS_TO_TEST) def test_add_files(self, alg: str, tmp_path: Path) -> None: """Test add_file.""" content = "hello world!" test_file0 = tmp_path / "test0.txt" test_file0.write_text(content) test_file1 = tmp_path / "test1.txt" test_file1.write_text(content) expected = hashlib.new(alg) for test_file in [test_file0, test_file1]: expected.update((str(test_file) + "\0").encode()) expected.update((content + "\0").encode()) result = FileHash(hashlib.new(alg)) result.add_files([test_file0, test_file1]) assert result.digest_size == expected.digest_size assert result.digest == expected.digest() assert result.hexdigest == expected.hexdigest() @pytest.mark.parametrize("alg", ALGS_TO_TEST) def test_add_files_relative(self, alg: str, tmp_path: Path) -> None: """Test add_file.""" tld = tmp_path.parents[0] content = "hello world!" test_file0 = tmp_path / "test0.txt" test_file0.write_text(content) test_file1 = tmp_path / "test1.txt" test_file1.write_text(content) expected = hashlib.new(alg) for test_file in [test_file0, test_file1]: expected.update((str(test_file.relative_to(tld)) + "\0").encode()) expected.update((content + "\0").encode()) result = FileHash(hashlib.new(alg)) result.add_files([test_file0, test_file1], relative_to=tld) assert result.digest_size == expected.digest_size assert result.digest == expected.digest() assert result.hexdigest == expected.hexdigest()
en
0.581632
Test runway.utils._file_hash. # pylint: disable=no-self-use # pyright: basic Test FileHash. Test add_file. Test add_file_name. Test add_file_name. Test add_file. Test add_file.
2.429001
2