content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import pandas as pd from sklearn.model_selection import GridSearchCV, train_test_split, cross_val_score from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score, classification_report import matplotlib.pyplot as plt import numpy as np import category_encoders as ce from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder, OrdinalEncoder def load_tit(path): """ downloads data from kaggle stored at path = "../Data/" returns a tuple of our titanic datasets- (train,test) """ train = pd.read_csv(path + 'tit_train.csv') test = pd.read_csv(path + "tit_test.csv") return (train, test) def gscv_results_terse(model, params, X_train, y_train, X_test, y_test): ''' clf = a classifier, params = a dict to feed to gridsearch_cv, score_list = list of evaluation metrics nuff said ''' scores = ["accuracy"] for score in scores: print("# Tuning hyper-parameters for %s" % score) clf = GridSearchCV(model, params, cv=10, scoring=score) clf.fit(X_train, y_train) print("Best parameters set found on development set: \n{}".format(clf.best_params_)) print('___________________________________') print('cv scores on the best estimator') scores = cross_val_score(clf.best_estimator_, X_train, y_train, scoring="accuracy", cv=10) print(scores) print('the average cv score is {:.3} with a std of {:.3}'.format(np.mean(scores), np.std(scores))) return clf def print_gscv_results(model, params, X_train, y_train, X_test, y_test): ''' clf = a classifier, params = a dict to feed to gridsearch_cv, score_list = list of evaluation metrics ''' scores = ["accuracy"] for score in scores: print("# Tuning hyper-parameters for %s" % score) print() clf = GridSearchCV(model, params, cv=5, scoring=score) clf.fit(X_train, y_train) print("Best parameters set found on development set:") print() print(clf.best_params_) print() print("Grid scores on development set:") print() means = clf.cv_results_['mean_test_score'] stds = clf.cv_results_['std_test_score'] for mean, std, params in zip(means, stds, clf.cv_results_['params']): print("%0.3f (+/-%0.03f) for %r" % (mean, std * 2, params)) print() print("Detailed classification report:") print() print("The model is trained on the full development set.") print("The scores are computed on the full evaluation set.") print() y_true, y_pred = y_test, clf.predict(X_test) print(classification_report(y_true, y_pred)) print('________________________________________________') print('best params for model are {}'.format(clf.best_params_)) print('\n___________________________________\n') print('cv scores on the best estimator') scores = cross_val_score(clf.best_estimator_, X_train, y_train, scoring="accuracy", cv=10) print(scores) print('the average cv score is {:.2}\n\n'.format(np.mean(scores))) return clf def visualize_classifier(model, X, y, ax=None, cmap='rainbow'): """ X is a 2D dataset nuf said """ ax = ax or plt.gca() # Plot the training points ax.scatter(X.iloc[:, 0], X.iloc[:, 1], c=y, s=30, cmap=cmap, clim=(y.min(), y.max()), zorder=3) ax.axis('tight') ax.axis('off') xlim = ax.get_xlim() ylim = ax.get_ylim() # fit the estimator model.fit(X, y) xx, yy = np.meshgrid(np.linspace(*xlim, num=200), np.linspace(*ylim, num=200)) Z = model.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) # Create a color plot with the results n_classes = len(np.unique(y)) contours = ax.contourf(xx, yy, Z, alpha=0.3, levels=np.arange(n_classes + 1) - 0.5, cmap=cmap, clim=(y.min(), y.max()), zorder=1) ax.set(xlim=xlim, ylim=ylim) # this dataset has unique cols so we will go through one by one def pp_Embarked(df): """ simply adds 'C' where missing values are present inplace imputation return df """ df.Embarked.fillna("C", inplace=True) return df def pp_Name(df): """ extracts the title from the Name column returns- df with a new column named Title appended to original df """ temp = df.Name.apply(lambda x: x.split(',')[1].split(".")[0].strip()) df['Title'] = temp return df def pp_Age(df): """ imputes missing values of age through a groupby([Pclass,Title,isFemale]) returns df with new column named Age_nonull appended to it """ transformed_Age = df.groupby(["Title", 'Pclass', "Sex"])['Age'].transform(lambda x: x.fillna(x.median())) df['Age_nonull'] = transformed_Age return df def pp_Fare(df): ''' This will clip outliers to the middle 98% of the range ''' temp = df['Fare'].copy() limits = np.percentile(temp, [1, 99]) df.Fare = np.clip(temp, limits[0], limits[1]) return df def pp_AgeBin(df): """ takes Age_nonull and puts in bins returns df with new column- AgeBin """ z = df.Age_nonull.round() # some values went to 0 so clip to 1 binborders = np.linspace(0, 80, 17) z = z.clip(1, None) z = z.astype("int32") df['AgeBin'] = pd.cut(z, bins=binborders, labels=False) return df def pp_Sex(df): """ maps male and female to 0 and 1 returns the df with is_Female added """ df['is_Female'] = df.Sex.apply(lambda row: 0 if row == "male" else 1) # one way return df def pp_Cabin(df): """ extracts the deck from the cabin. Mostly 1st class has cabin assignments. Replace nan with "unk". Leaves as an ordinal categorical. can be onehoted later. returns the df with Deck added as a column """ df["Deck"] = "UNK" temp = df.loc[df.Cabin.notnull(), :].copy() temp['D'] = temp.Cabin.apply(lambda z: z[0]) df.iloc[temp.index, -1] = temp["D"] # df.where(df.Deck != "0", "UNK") return df def scaleNumeric(df, cols): """ Standardize features by removing the mean and scaling to unit variance """ ss = StandardScaler() scaled_features = ss.fit_transform(df[cols].values) for i, col in enumerate(cols): df[col + "_scaled"] = scaled_features[:, i] return df def chooseFeatures(df, alist): """ df is our dataframe with all new features added alist is a list of cols to select for a new dataframe returns df[alist] """ return df[alist] def test_dtc(alist, df, labels): """ tests a decision tree model for classification prints out way to much stuff returns a GridSearchCV classifier """ a = df[alist] # select columns X_train, X_test, y_train, y_test = train_test_split(a, labels, test_size=0.2, random_state=42) dtc = DecisionTreeClassifier() dtc_dict = dt_dict = [{"max_depth": [2, 5, 8, 12, 15], "min_samples_leaf": [1, 2, 3], "max_features": [None, 1.0, 2, 'sqrt', X_train.shape[1]]}] clf = gscv_results_terse(dtc, dtc_dict, X_train, y_train, X_test, y_test) return clf ######################################################### # some utilities functions to aid in ml in general def lin_to_log_even(min_num, max_num, num_pts=10): """ This really only needed in min_num << 1 and min_max >> 1 creates an evenly spaced log space from min_num to max_num """ lmin = np.log10(min_num) lmax = np.log10(max_num) ls = np.linspace(lmin, lmax, num_pts) log_spaces = np.power(10, ls) # print(["{:05f}".format(each) for each in log_spaces]) return log_spaces def lin_to_log_random(num1, num2, num_pts=10): """ This really only needed in min_num << 1 and min_max >> 1 creates an array of random selected pts of len num_pts each point is in the log space from min_num to max_num """ ln1 = np.log10(num1) ln2 = np.log10(num2) range_bn = np.abs(ln2 - ln1) z = ln2 + np.random.rand(num_pts) * -range_bn zz = np.power(10, z) print(["{:05f}".format(each) for each in zz]) return zz
[ 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 24846, 18243, 33538, 11, 4512, 62, 9288, 62, 35312, 11, 3272, 62, 2100, 62, 26675, 198, 6738, 1341, 35720, 13, 21048, 1330, 26423, 27660, 9487, 7483, ...
2.381958
3,503
name = "magic_markdown" from magic_markdown.MagicMarkdown import MagicMarkdown
[ 3672, 796, 366, 32707, 62, 4102, 2902, 1, 198, 198, 6738, 5536, 62, 4102, 2902, 13, 22975, 9704, 2902, 1330, 6139, 9704, 2902, 198 ]
3.333333
24
import matplotlib.pyplot as plt import pandas as pd from house.production.solar_panel import SolarPanel from house import House from math import pi from time import time start_time = time() solar_panel_east = SolarPanel(285.0, 10*pi/180, -pi/2, 0.87, 1.540539, 10) solar_panel_west = SolarPanel(285.0, 10*pi/180, pi/2, 0.87, 1.540539, 10) house = House([], solar_panel_tp=(solar_panel_east, solar_panel_west)) irradiance_df = pd.read_csv(filepath_or_buffer="C:\\Users\\Lander\\Documents\\KULeuven\\2e bachelor\\semester 1\\P&O 3\\P-O-3-Smart-Energy-Home\\data\\Irradiance.csv", header=0, index_col="Date/Time", dtype={"watts-per-meter-sq": float}, parse_dates=["Date/Time"] ) start = pd.Timestamp("2016-06-17 00:00:00") # end = pd.Timestamp("2017-04-21 23:55:00") end = pd.Timestamp("2016-06-17 23:55:00") times = pd.date_range(start, end, freq="300S") data = [house.power_production(t, irradiance_df) for t in pd.date_range(start, end, freq="300S")] # print(data) plt.plot(data) print(time() - start_time) plt.show()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, 2156, 13, 25493, 13, 82, 6192, 62, 35330, 1330, 12347, 26639, 198, 6738, 2156, 1330, 2097, 198, 6738, 10688, 1330, 31028, 1...
2.091398
558
from tensorflow.keras.layers import Layer, Conv1D, Input, Dropout, MaxPool1D, Masking import tensorflow.keras.backend as K from tensorflow.keras import Model import tensorflow as tf if __name__ == '__main__': input_shape = (16, 5 * 256) filters = [32, 64, 128, 256] pooling_sizes = [2, 2, 2, 2] inputs = Input(shape=input_shape) x = CNN1D(filters=filters, pooling_sizes=pooling_sizes)(inputs) model = Model(inputs=inputs, outputs=x) model.summary()
[ 6738, 11192, 273, 11125, 13, 6122, 292, 13, 75, 6962, 1330, 34398, 11, 34872, 16, 35, 11, 23412, 11, 14258, 448, 11, 5436, 27201, 16, 35, 11, 18007, 278, 198, 11748, 11192, 273, 11125, 13, 6122, 292, 13, 1891, 437, 355, 509, 198, ...
2.487047
193
""" Play with autoformatting on save Ensure to pip install black within your environment """ # test linting with an unnecessary import # it should complain and suggest a solution import sys thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964, "okay": "This is getting way too long", }
[ 37811, 198, 11002, 351, 8295, 18982, 889, 319, 3613, 198, 4834, 19532, 284, 7347, 2721, 2042, 1626, 534, 2858, 198, 37811, 198, 198, 2, 1332, 300, 600, 278, 351, 281, 13114, 1330, 198, 2, 340, 815, 13121, 290, 1950, 257, 4610, 198, ...
3.191919
99
import json import os import mock def get_data_filepath(filename): """Construct filepath for a file in the test/data directory Args: filename: name of file Returns: full path to file """ return os.path.join(os.path.dirname(__file__), 'data', filename) def load_from_file(filename): """Load the contents of a file in the data directory. Args: filename: name of file to load Returns: contents of file as a string """ filepath = get_data_filepath(filename) with open(filepath) as f: return f.read()
[ 11748, 33918, 198, 11748, 28686, 198, 198, 11748, 15290, 628, 198, 198, 4299, 651, 62, 7890, 62, 7753, 6978, 7, 34345, 2599, 198, 220, 220, 220, 37227, 42316, 2393, 6978, 329, 257, 2393, 287, 262, 1332, 14, 7890, 8619, 198, 220, 220, ...
2.60793
227
import sys peak=[] with open(sys.argv[1],'r') as f: for line in f: line=line.strip('\n').split('\t') peak.append(int(line[3])) f.close() num=int(len(peak)/100.0) bin=[] for i in range(99): bin.append(str(i+1)+'\t'+str(sum(peak[num*i:num*(i+1)])/(num*1.0))+'\n') bin.append('100'+'\t'+str(sum(peak[num*99:])/(num*1.0))+'\n') with open('bin.txt','w') as f: f.writelines(bin) f.close
[ 11748, 25064, 198, 198, 36729, 28, 21737, 198, 4480, 1280, 7, 17597, 13, 853, 85, 58, 16, 60, 4032, 81, 11537, 355, 277, 25, 198, 197, 1640, 1627, 287, 277, 25, 198, 197, 197, 1370, 28, 1370, 13, 36311, 10786, 59, 77, 27691, 35312...
1.916667
204
import csv from faker import Faker fake = Faker() for x in range(0, 10): placa = fake.pystr(min_chars=3, max_chars=3).upper() + str(fake.pydecimal(left_digits=1, right_digits=1, positive=True)) + str(fake.pydecimal(left_digits=1, right_digits=1, positive=True)) placa = placa.replace(".","") atualLat = str(fake.geo_coordinate(center=-8.059845, radius=0.001)) atualLon = str(fake.geo_coordinate(center=-34.905552, radius=0.001)) geo0Lat = str(fake.geo_coordinate(center=-8.021154, radius=0.001)) geo0Lon = str(fake.geo_coordinate(center=-34.933909, radius=0.001)) geo1Lat = str(fake.geo_coordinate(center=-8.027868, radius=0.001)) geo1Lon = str(fake.geo_coordinate(center=-34.852109, radius=0.001)) geo2Lat = str(fake.geo_coordinate(center=-8.122738, radius=0.001)) geo2Lon = str(fake.geo_coordinate(center=-34.874526, radius=0.001)) geo3Lat = str(fake.geo_coordinate(center=-8.052431, radius=0.001)) geo3Lon = str(fake.geo_coordinate(center=-34.959744, radius=0.001)) csvRow = [placa,atualLat,atualLon,geo0Lat,geo0Lon,geo1Lat,geo1Lon,geo2Lat,geo2Lon,geo3Lat,geo3Lon,"0","0"] with open('cars.csv', 'a', newline='\n') as csvfile: spamwriter = csv.writer(csvfile, delimiter=',',quotechar='|',quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(csvRow)
[ 11748, 269, 21370, 201, 198, 6738, 277, 3110, 1330, 376, 3110, 201, 198, 201, 198, 30706, 796, 376, 3110, 3419, 201, 198, 201, 198, 201, 198, 1640, 2124, 287, 2837, 7, 15, 11, 838, 2599, 201, 198, 220, 220, 220, 21957, 64, 796, 83...
2.134707
631
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QLabel, QLineEdit, QVBoxLayout, QMessageBox, QCheckBox,\ QSpinBox, QComboBox, QListWidget, QDialog, QFileDialog, QProgressBar, QTableWidget, QTableWidgetItem,\ QAbstractItemView, QSpinBox, QSplitter, QSizePolicy, QAbstractScrollArea, QHBoxLayout, QTextEdit, QShortcut,\ QProgressDialog from PyQt5.QtGui import QPalette, QKeySequence, QDoubleValidator, QIntValidator from PyQt5.QtCore import Qt, QThread, QSignalMapper import sys import pyqtgraph as pg if __name__=='__main__': app = QApplication(sys.argv) dlg = MultiInputDialog(inputs={'value':100,'value2':10.0,'fit':True,'func':['Lor','Gau']}) dlg.show() sys.exit(app.exec_())
[ 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 1195, 38300, 11, 1195, 23416, 11, 1195, 49222, 21864, 11, 1195, 33986, 11, 1195, 13949, 18378, 11, 1195, 53, 14253, 32517, 11, 1195, 12837, 14253, 11, 1195, 9787, 14253, 11, ...
2.560284
282
import os import psutil import json import sqlite3 import threading from datetime import datetime, timezone from websocket import create_connection
[ 11748, 28686, 198, 11748, 26692, 22602, 198, 11748, 33918, 198, 11748, 44161, 578, 18, 198, 11748, 4704, 278, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 640, 11340, 198, 6738, 2639, 5459, 1330, 2251, 62, 38659, 198, 220, 220, 220, 220...
3.413043
46
from __future__ import print_function from simtk.openmm import app import simtk.openmm as mm from simtk import unit from sys import stdout import os import time import numpy as np import argparse from equil import setup_sim, dynamix parser = argparse.ArgumentParser(description='equilibrate structures') parser.add_argument('--sys', type=str, help='system pdb preface') parser.add_argument('--pdb', type=str, help='IC pdb') parser.add_argument('--nmin', type=int, help='number of minimization steps', default=50) parser.add_argument('--nstep', type=int, help='number of steps') args = parser.parse_args() systm = args.sys ns = args.nstep # load initial parameters and geometry prmtop = app.AmberPrmtopFile(systm + '.prmtop') pdb = app.PDBFile(args.pdb) # eq temp temp = 300.0 # timestep ts = 2.0 qs = pdb.positions top = pdb.topology unit_cell = top.getUnitCellDimensions() box = unit_cell*np.eye(3) # run it! sim = setup_sim(prmtop, temp, ts, qs, 'gpu', top, box) dynamix(systm, sim, ns, prmtop, temp, ts, 'gpu', min=args.nmin)
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 985, 30488, 13, 9654, 3020, 1330, 598, 198, 11748, 985, 30488, 13, 9654, 3020, 355, 8085, 198, 6738, 985, 30488, 1330, 4326, 198, 6738, 25064, 1330, 14367, 448, 198, 11748, 28686...
2.76738
374
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Tests for observations_transforms.""" import copy from typing import Mapping, Optional, Type from absl.testing import absltest from absl.testing import parameterized import cv2 import dm_env from dm_env import specs from dm_robotics.agentflow import spec_utils from dm_robotics.agentflow import testing_functions from dm_robotics.agentflow.preprocessors import observation_transforms from dm_robotics.agentflow.preprocessors import timestep_preprocessor from dm_robotics.transformations import transformations as tr import numpy as np _DEFAULT_TYPE = np.float64 def _build_unit_timestep_spec( observation_spec: Optional[Mapping[str, specs.Array]] = None, reward_spec: Optional[specs.Array] = None, discount_spec: Optional[specs.BoundedArray] = None): if observation_spec is None: name = 'foo' observation_spec = { name: specs.Array(shape=(2,), dtype=_DEFAULT_TYPE, name=name), } if reward_spec is None: reward_spec = scalar_array_spec(name='reward') if discount_spec is None: discount_spec = scalar_array_spec(name='discount') return spec_utils.TimeStepSpec( observation_spec=observation_spec, reward_spec=reward_spec, discount_spec=discount_spec) if __name__ == '__main__': absltest.main()
[ 2, 15069, 12131, 10766, 28478, 21852, 15302, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198,...
3.119008
605
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 23b.py ~~~~~~ Advent of Code 2017 - Day 23: Coprocessor Conflagration Part Two Now, it's time to fix the problem. The debug mode switch is wired directly to register a. You flip the switch, which makes register a now start at 1 when the program is executed. Immediately, the coprocessor begins to overheat. Whoever wrote this program obviously didn't choose a very efficient implementation. You'll need to optimize the program if it has any hope of completing before Santa needs that printer working. The coprocessor's ultimate goal is to determine the final value left in register h once the program completes. Technically, if it had that... it wouldn't even need to run the program. After setting register a to 1, if the program were to run to completion, what value would be left in register h? :copyright: (c) 2017 by Martin Bor. :license: MIT, see LICENSE for more details. """ import sys import math def solve(instructions): """Return value of h. Hand optimized. """ instr, reg, val = instructions.split('\n')[0].split() assert instr == 'set' assert reg == 'b' b = int(val) * 100 + 100000 start = b - 17000 end = b + 1 return sum(not is_prime(x) for x in range(start, end, 17)) if __name__ == "__main__": sys.exit(main(sys.argv))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 220, 220, 220, 2242, 65, 13, 9078, 198, 220, 220, 220, 220, 8728, 4907, 198, 220, 220, 220, 33732, ...
3.032051
468
# -*- coding: utf-8 -*- """ Created on Thu Sep 20 11:59:50 2018 @author: klaus """ import numpy as np import matplotlib.pyplot as plt import time import random from argparse import ArgumentParser, RawTextHelpFormatter if __name__ == "__main__": argument_parser = ArgumentParser(description=""" Game of Life: - Little python implementation of Conway's game of life. - The game board will be visualized with matplotlib. - See readme.md for more informations.""", epilog="https://github.com/WinterWonderland/Game_of_Life", formatter_class=RawTextHelpFormatter) argument_parser.add_argument("--width", metavar="", type=int, default=100, help="The width of the game board (default=100)") argument_parser.add_argument("--height", metavar="", type=int, default=100, help="The width of the game board (default=100)") argument_parser.add_argument("--interval", metavar="", type=float, default=0.3, help="Interval time between each step (default=0.3)") argument_parser.add_argument("--seed", metavar="", type=int, default=None, help="A seed for the random number generator to get identical play boards") args = argument_parser.parse_args() GameOfLife(width=args.width, height=args.height, interval=args.interval, seed=args.seed).run() input("press enter to quit")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 41972, 319, 26223, 8621, 1160, 1367, 25, 3270, 25, 1120, 2864, 201, 198, 201, 198, 31, 9800, 25, 479, 38024, 201, 198, 37811, 201, 198, 11748, 29...
1.786287
1,123
from ebird.api.constants import DEFAULT_BACK from tests.mixins.base import BaseMixin
[ 6738, 304, 16944, 13, 15042, 13, 9979, 1187, 1330, 5550, 38865, 62, 31098, 198, 6738, 5254, 13, 19816, 1040, 13, 8692, 1330, 7308, 35608, 259, 628 ]
3.307692
26
""" Export data from Tamr using df-connect. An example where everything is default in config file, which implies exported data is written back to same database as ingested from. """ import tamr_toolbox as tbox my_config = tbox.utils.config.from_yaml("examples/resources/conf/connect.config.yaml") my_connect = tbox.data_io.df_connect.client.from_config(my_config) tbox.data_io.df_connect.client.export_dataset( my_connect, dataset_name="example_dataset", target_table_name="example_target_table", )
[ 37811, 198, 43834, 1366, 422, 11552, 81, 1262, 47764, 12, 8443, 13, 1052, 1672, 810, 2279, 318, 4277, 287, 4566, 2393, 11, 198, 4758, 15565, 29050, 1366, 318, 3194, 736, 284, 976, 6831, 355, 44694, 422, 13, 198, 37811, 198, 11748, 218...
3.142857
161
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField from wtforms.validators import DataRequired, Length, EqualTo, URL from project.auth.models import User
[ 6738, 42903, 62, 86, 27110, 1330, 46947, 8479, 198, 6738, 266, 83, 23914, 1330, 10903, 15878, 11, 30275, 15878, 11, 41146, 15878, 198, 6738, 266, 83, 23914, 13, 12102, 2024, 1330, 6060, 37374, 11, 22313, 11, 28701, 2514, 11, 10289, 198,...
3.882353
51
from flask import Flask, render_template, request, jsonify import sqlite3 import json import re import logging from applicationInfo import ApplicationInfo logging.basicConfig(filename='/var/www/SoftDev2/projectGo.log', level=logging.DEBUG) app = Flask(__name__) applicationInfo = ApplicationInfo() row_pos_obligationid = 0 row_pos_userid = 1 row_pos_name = 2 row_pos_description = 3 row_pos_starttime = 4 row_pos_endtime = 5 row_pos_priority = 6 row_pos_status = 7 row_pos_category = 8 if __name__ == "__main__": app.run(debug=True, host='0.0.0.0', port=int('5000'))
[ 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 11, 2581, 11, 33918, 1958, 198, 11748, 44161, 578, 18, 198, 11748, 33918, 198, 11748, 302, 198, 11748, 18931, 198, 198, 6738, 3586, 12360, 1330, 15678, 12360, 198, 198, 6404, 2667, 13, 3548...
2.828431
204
# Copyright (c) 2018, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest from cuml import DBSCAN as cuDBSCAN from sklearn.cluster import DBSCAN as skDBSCAN from test_utils import array_equal import cudf import numpy as np
[ 2, 15069, 357, 66, 8, 2864, 11, 15127, 23929, 44680, 6234, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262,...
3.570755
212
N = int(input()) ans = 0 for _ in range(N): p, q = map(int, input().split()) ans += (1 / p) * q print(ans)
[ 45, 796, 493, 7, 15414, 28955, 198, 504, 796, 657, 198, 1640, 4808, 287, 2837, 7, 45, 2599, 198, 220, 220, 220, 279, 11, 10662, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 28955, 198, 220, 220, 220, 9093, 15853, 357, 16, 1220, 279,...
2.192308
52
from heapq import heappush, heappop l1 = ListNode(1) l1.next = ListNode(4) l1.next.next = ListNode(5) l2 = ListNode(1) l2.next = ListNode(3) l2.next.next = ListNode(4) l3 = ListNode(2) l3.next = ListNode(6) l3 = mergeKLists([l1, l2, l3]) p = l3 while p: print(p.val, end=" ") # 1 1 2 3 4 4 5 6 p = p.next print()
[ 6738, 24575, 80, 1330, 339, 1324, 1530, 11, 339, 1324, 404, 198, 198, 75, 16, 796, 7343, 19667, 7, 16, 8, 198, 75, 16, 13, 19545, 796, 7343, 19667, 7, 19, 8, 198, 75, 16, 13, 19545, 13, 19545, 796, 7343, 19667, 7, 20, 8, 198, ...
1.981707
164
import argparse import glob import numpy as np import os import skimage.io import torch import tifffile from cellpose import models def _parse_args(): """Parse command-line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( "-i", "--input", type=str, default=None, required=True, help="Input image or folder with images to mask.", ) parser.add_argument( "-o", "--output", type=str, default=None, required=False, help="Output folder, default mask within input folder", ) parser.add_argument( "-t", "--target", type=str, default=None, required=False, help="Target channel tag, if provided, it will look for files with the tag.", ) args = parser.parse_args() return args def main(): """Create cell masks and save them into mask folder within input folder.""" args = _parse_args() if os.path.isdir(args.input): inputs = glob.glob(f"{args.input}/*tif") elif os.path.isfile(args.input): inputs = [args.input] else: raise ValueError(f"Expected input folder or file. Provided {args.input}.") if args.target is not None: inputs = [x for x in inputs if args.target in x] output = args.output if output is None: output = f"{os.path.abspath(args.input)}/mask" if not os.path.exists(output): os.mkdir(output) cellpose_model = models.Cellpose(model_type="cyto", gpu=False) for input_file in inputs: img = skimage.io.imread(input_file) middle_slice = len(img) // 2 if len(img.shape) == 4: mask_nucl, *_ = cellpose_model.eval( [np.max(img, axis=1)[middle_slice]], diameter=150, channels=[0, 0], min_size=15, ) if len(img.shape) == 3: mask_nucl, *_ = cellpose_model.eval( [img[middle_slice]], diameter=150, channels=[0, 0], min_size=15, ) name = os.path.basename(input_file) out = f"{output}/{name}" tifffile.imsave(out, mask_nucl[0]) if __name__ == "__main__": main()
[ 11748, 1822, 29572, 198, 11748, 15095, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 1341, 9060, 13, 952, 198, 11748, 28034, 198, 11748, 256, 361, 487, 576, 198, 198, 6738, 2685, 3455, 1330, 4981, 628, 198, 4299, 48...
2.109275
1,089
# # Customer cliff dive data challenge # 2020-02-17 # Leslie Emery # ## Summary # ### The problem # The head of the Yammer product team has noticed a precipitous drop in weekly active users, which is one of the main KPIs for customer engagement. What has caused this drop? # ### My approach and results # I began by coming up with several questions to investigate: # - Was there any change in the way that weekly active users is calculated? # - This does not appear to be the case. To investigate this, I began by replicating the figure from the dashboard. I calculated a rolling 7-day count of engaged users, making sure to use the same method across the entire time frame covered by the dataset, and it still showed the same drop in engagement. # - Was there a change in any one particular type of "engagement"? # - I looked at a rolling 7-day count of each individual type of engagement action. From plotting all of these subplots, it looks to me like home_page, like_message, login, send_message, and view_inbox are all exhibiting a similar drop around the same time, so it's these underlying events that are driving the drop. # - Could a change in the user interface be making it more difficult or less pleasant for users? # - I couldn't find information in the available datasets to address this question. The `yammer_experiments` data set has information about experiments going on, presumably in the user interface. All of the listed experiments happened in June of 2014, though, which I think is too early to have caused the August drop in engagement. # - Is this drop a seasonal change that happens around this time every year? # - Because the data is only available for the period of time shown in the original dashboard, I can't investigate this question. I'd be very interested to see if there is a pattern of reduced engagement at the end of the summer, perhaps related to vacation or school schedules. # - Are users visiting the site less because they're getting more content via email? # - I calculated 7-day rolling counts of each type of email event, and all email events together. Email events overall went up during the time period immediately before the drop in user engagement. All four types of email events increased during the same period, indicating higher clickthroughs on emails, higher numbers of email open events, and more reengagement and weekly digest emails sent. It could be that the higher number of weekly digests sent out mean that users don't have to visit the site directly as much. # - Are users disengaging from the site due to too many emails/notifications? # - I calculated a rolling 7-day count of emails sent to each user and found that the number of emails sent to each user per 7-day period has increased from 5.4 emails (July 20) to 7.75 emails (August 11). This suggests that an increasing volume of emails sent to individual users could have driven them away from using the site. To investigate this further I would want to look into email unsubscribe rates. If unsubscribe rates have also gone up, then it seems that Yammer is sending too many emails to its users. # - To investigate whether the number of emails sent per user is correlated with the number of engaged users, I used a Granger causality test to see if "emails sent per user" could be used to predict "number of engaged users". With a high enough lag, the test statistics might be starting to become significant, but I would want to investigate these test results further before making any recommendations based on them. # - Is the drop in engagement due to a decrease in new activated users? e.g. they are reaching the end of potential customer base? # - I calculated the cumulative number of newly activated users over time, using the activation time for each user in the users table. I wanted to see if customer growth had leveled off. However, I saw that customer growth was still increasing in the same pattern. This was true when using creating date rather than activation date as well. # What is my recommendation to Yammer? # I have a few recommendations to Yammer: # - Try decreasing the number of emails sent to each individual user to see if this increases engagement. They could try this for a subset of users first. # - Investigate email unsubscribe rates to see if they are going up. This would indicate that increased email volume might be making users unhappy. # - Compare this data to a wider time range to see if the drop shown here is seasonal. # + import matplotlib.pyplot as plt import numpy as np import os import plotly.express as px import pandas as pd from scipy import stats from statsmodels.tsa.stattools import acf, pacf from statsmodels.graphics.tsaplots import plot_acf, plot_pacf from statsmodels.tsa.stattools import grangercausalitytests # - data_dir = '/Users/leslie/devel/insight-data-challenges/02-customer-cliff-dive/data' benn_normal = pd.read_csv(os.path.join(data_dir, 'benn.normal_distribution - benn.normal_distribution.csv.tsv'), sep='\t') rollup_periods = pd.read_csv(os.path.join(data_dir, 'dimension_rollup_periods - dimension_rollup_periods.csv.tsv'), sep='\t', parse_dates=['time_id', 'pst_start', 'pst_end', 'utc_start', 'utc_end']) yammer_emails = pd.read_csv(os.path.join(data_dir, 'yammer_emails - yammer_emails.csv.tsv'), sep='\t', parse_dates=['occurred_at']) yammer_events = pd.read_csv(os.path.join(data_dir, 'yammer_events - yammer_events.csv.tsv'), sep='\t', parse_dates=['occurred_at']) yammer_experiments = pd.read_csv(os.path.join(data_dir, 'yammer_experiments - yammer_experiments.csv.tsv'), sep='\t', parse_dates=['occurred_at']) yammer_users = pd.read_csv(os.path.join(data_dir, 'yammer_users - yammer_users.csv.tsv'), sep='\t', parse_dates=['created_at', 'activated_at']) # + benn_normal.info() benn_normal.head() benn_normal.describe() rollup_periods.info() rollup_periods.head() rollup_periods.describe() yammer_emails.info() yammer_emails.head() yammer_emails.describe() yammer_emails['action'].value_counts(dropna=False) yammer_emails['user_type'].value_counts(dropna=False) yammer_events.info() yammer_events.head() yammer_events.describe() yammer_events['occurred_at'] yammer_events['event_type'].value_counts(dropna=False) yammer_events['event_name'].value_counts(dropna=False) yammer_events['location'].value_counts(dropna=False) yammer_events['device'].value_counts(dropna=False) yammer_events['user_type'].value_counts(dropna=False) yammer_events['user_type'].dtype # user_type should be an int, but has many missing values, and NaN is a float. # So convert it to the Pandas Int64 dtype which can accommodate NaNs and ints. yammer_events = yammer_events.astype({'user_type': 'Int64'}) yammer_experiments.info() yammer_experiments.head() yammer_experiments.describe() yammer_experiments['experiment'].value_counts(dropna=False) yammer_experiments['experiment_group'].value_counts(dropna=False) yammer_experiments['location'].value_counts(dropna=False) yammer_experiments['device'].value_counts(dropna=False) yammer_users.info() yammer_users.head() yammer_users.describe() yammer_users['language'].value_counts(dropna=False) yammer_users['state'].value_counts(dropna=False) yammer_users['company_id'].value_counts(dropna=False) # - # ## Initial data investigation # + # How many days in the dataset? yammer_events['occurred_at'].max() - yammer_events['occurred_at'].min() # 122 days! rollup_periods['pst_start'].max() - rollup_periods['pst_end'].min() # 1094 days - way more intervals than needed to tile this events data! yammer_events = yammer_events.sort_values(by='occurred_at', ascending=True) small_events = yammer_events.head(int(yammer_events.shape[0]/10)).sample(n=40) small_events = small_events.sort_values(by='occurred_at', ascending=True) small_events['occurred_at'].max() - small_events['occurred_at'].min() weekly_rollup_periods = rollup_periods.loc[rollup_periods['period_id'] == 1007] # - # + small_rolling_engagement = small_events.loc[small_events['event_type'] == 'engagement'].rolling( '7D', on='occurred_at').count() # I'm not sure whether rollup_periods are closed on right, left, or both... # Calculate counts of engagement events in a 7-day rolling window rolling_engagement_counts = yammer_events.loc[yammer_events['event_type'] == 'engagement'].sort_values( by='occurred_at', ascending=True # Have to sort by "on" column to use rolling() ).rolling('7D', on='occurred_at', min_periods=1).count() # + # Use a loop to aggregate on rollup periods yammer_events['event_name'].unique() event_range = [min(yammer_events['occurred_at']), max(yammer_events['occurred_at'])] covered_weekly_rollup_periods = weekly_rollup_periods.loc[(weekly_rollup_periods['pst_end'] <= event_range[1]) & (weekly_rollup_periods['pst_start'] >= event_range[0])] # in interval --> start < occurred_at <= end counts_by_type = None for (ridx, row) in covered_weekly_rollup_periods.iterrows(): # row = covered_weekly_rollup_periods.iloc[0] # Get egagement events within the period df = yammer_events.loc[(yammer_events['occurred_at'] > row['pst_start']) & (yammer_events['occurred_at'] <= row['pst_end']) & (yammer_events['event_type'] == 'engagement')] # Count user engagement events cbt = df.groupby('event_name').aggregate(event_count=('user_id', 'count')).transpose() cbt['pst_start'] = row['pst_start'] cbt['pst_end'] = row['pst_end'] cbt['engaged_users'] = df['user_id'].nunique() cbt['engagement_event_count'] = df.shape[0] if counts_by_type is None: counts_by_type = cbt else: counts_by_type = counts_by_type.append(cbt) counts_by_type # + # Plot engaged users over time fig = px.scatter(counts_by_type, x='pst_end', y='engaged_users', template='plotly_white') fig.update_yaxes(range=[0, 1500]) fig.show() # Plot count of engagement_events over time fig = px.scatter(counts_by_type, x='pst_end', y='engagement_event_count', template='plotly_white') fig.show() # Plot count of individual event types over time counts_melted = counts_by_type.melt(id_vars=['pst_start', 'pst_end', 'engaged_users', 'engagement_event_count']) fig = px.scatter(counts_melted, x='pst_end', y='value', template='plotly_white', facet_col='event_name', facet_col_wrap=3, height=1200) fig.update_yaxes(matches=None) fig.show() # - # Are there any "experiments" messing things up? yammer_experiments['occurred_at'].describe() # No, these are all before the issue shows up # + # Investigate the sending of emails to user in the same rollup periods email_counts_by_type = None for (ridx, row) in covered_weekly_rollup_periods.iterrows(): # row = covered_weekly_rollup_periods.iloc[0] # Get egagement events within the period df = yammer_emails.loc[(yammer_events['occurred_at'] > row['pst_start']) & (yammer_events['occurred_at'] <= row['pst_end'])] # Count user engagement events cbt = df.groupby('action').aggregate(action_count=('user_id', 'count')).transpose() cbt['pst_start'] = row['pst_start'] cbt['pst_end'] = row['pst_end'] cbt['emailed_users'] = df['user_id'].nunique() cbt['email_event_count'] = df.shape[0] cbt['emails_sent_per_user'] = df.loc[df['action'].str.startswith('sent_')].groupby( 'user_id').count().mean()['user_type'] if email_counts_by_type is None: email_counts_by_type = cbt else: email_counts_by_type = email_counts_by_type.append(cbt) email_counts_by_type # + # Plot emailed users over time fig = px.scatter(email_counts_by_type, x='pst_end', y='emailed_users', template='plotly_white') fig.update_yaxes(range=[0, 1500]) fig.show() # Plot count of email events over time fig = px.scatter(email_counts_by_type, x='pst_end', y='email_event_count', template='plotly_white') fig.show() # Plot count of individual email types over time email_counts_melted = email_counts_by_type.melt(id_vars=[ 'pst_start', 'pst_end', 'emailed_users', 'email_event_count', 'emails_sent_per_user']) fig = px.scatter(email_counts_melted, x='pst_end', y='value', template='plotly_white', facet_col='action', facet_col_wrap=2) fig.update_yaxes(matches=None) fig.show() # - # + # What is email engagement event count per user? Did that increase? # + fig = px.scatter(email_counts_by_type, x='pst_start', y='emails_sent_per_user', template='plotly_white') fig.show() p, r = stats.pearsonr(email_counts_by_type['emails_sent_per_user'].to_numpy(), counts_by_type['engaged_users'].to_numpy()) # They do look moderately correlated, but how do I test that one has an effect on the other? # - acf_50 = acf(counts_by_type['engaged_users'], nlags=50, fft=True) pacf_50 = pacf(counts_by_type['engaged_users'], nlags=50) fig, axes = plt.subplots(1, 2, figsize=(16, 3), dpi=200) plot_acf(counts_by_type['engaged_users'].tolist(), lags=50, ax=axes[0]) plot_pacf(counts_by_type['engaged_users'].tolist(), lags=50, ax=axes[1]) plt.show() test_df = pd.DataFrame({'emails_sent_per_user': email_counts_by_type['emails_sent_per_user'].to_numpy(), 'engaged_users': counts_by_type['engaged_users'].to_numpy()}) lags = range(20) caus_test = grangercausalitytests(test_df, maxlag=lags) # Has there been a dropoff in new users? # + yammer_users = yammer_users.sort_values(by='created_at', ascending=True) yammer_users['cumulative_users'] = pd.Series(np.ones(yammer_users.shape[0]).cumsum()) fig = px.scatter(yammer_users, x='created_at', y='cumulative_users', template='plotly_white') fig.show() # Nope, growth is still practicially exponenital yammer_users['cumulative_activated_users'] = pd.Series(np.ones(yammer_users.shape[0]).cumsum()) fig = px.scatter(yammer_users, x='created_at', y='cumulative_activated_users', template='plotly_white') fig.show() yammer_users['company_id'].nunique() # -
[ 2, 1303, 22092, 19516, 15647, 1366, 4427, 198, 198, 2, 12131, 12, 2999, 12, 1558, 198, 198, 2, 26909, 10320, 88, 198, 198, 2, 22492, 21293, 198, 198, 2, 44386, 383, 1917, 198, 2, 383, 1182, 286, 262, 14063, 647, 1720, 1074, 468, 6...
2.813296
5,024
import socket import threading import random sock = socket.socket() sock.connect(('localhost', 9090)) number = random.randint(0,1000) name = "person" + str(number) threading.Thread(target=send_message).start() threading.Thread(target=receive_message).start()
[ 11748, 17802, 198, 11748, 4704, 278, 198, 11748, 4738, 628, 628, 198, 198, 82, 735, 796, 17802, 13, 44971, 3419, 198, 82, 735, 13, 8443, 7, 10786, 36750, 3256, 860, 42534, 4008, 198, 17618, 796, 4738, 13, 25192, 600, 7, 15, 11, 1282...
3.105882
85
from collections import defaultdict import heapq from itertools import chain, repeat from feature_dict import FeatureDictionary import json import numpy as np import scipy.sparse as sp def __get_data_in_forward_format(self, names, code, name_cx_size): """ Get the data in a "forward" model format. :param data: :param name_cx_size: :return: """ assert len(names) == len(code), (len(names), len(code), code.shape) # Keep only identifiers in code #code = self.keep_identifiers_only(code) name_targets = [] name_contexts = [] original_names_ids = [] id_xs = [] id_ys = [] k = 0 for i, name in enumerate(names): for j in xrange(1, len(name)): # First element should always be predictable (ie sentence start) name_targets.append(self.name_dictionary.get_id_or_unk(name[j])) original_names_ids.append(i) context = name[:j] if len(context) < name_cx_size: context = [self.NONE] * (name_cx_size - len(context)) + context else: context = context[-name_cx_size:] assert len(context) == name_cx_size, (len(context), name_cx_size,) name_contexts.append([self.name_dictionary.get_id_or_unk(t) for t in context]) for code_token in set(code[i]): token_id = self.all_tokens_dictionary.get_id_or_none(code_token) if token_id is not None: id_xs.append(k) id_ys.append(token_id) k += 1 code_features = sp.csr_matrix((np.ones(len(id_xs)), (id_xs, id_ys)), shape=(k, len(self.all_tokens_dictionary)), dtype=np.int32) name_targets = np.array(name_targets, dtype=np.int32) name_contexts = np.array(name_contexts, dtype=np.int32) original_names_ids = np.array(original_names_ids, dtype=np.int32) return name_targets, name_contexts, code_features, original_names_ids def get_data_in_convolution_format(self, input_file, name_cx_size, min_code_size): names, code, original_names = self.__get_file_data(input_file) return self.get_data_for_convolution(names, code, name_cx_size, min_code_size), original_names def get_data_in_copy_convolution_format(self, input_file, name_cx_size, min_code_size): names, code, original_names = self.__get_file_data(input_file) return self.get_data_for_copy_convolution(names, code, name_cx_size, min_code_size), original_names def get_data_in_recurrent_convolution_format(self, input_file, min_code_size): names, code, original_names = self.__get_file_data(input_file) return self.get_data_for_recurrent_convolution(names, code, min_code_size), original_names def get_data_in_recurrent_copy_convolution_format(self, input_file, min_code_size): names, code, original_names = self.__get_file_data(input_file) return self.get_data_for_recurrent_copy_convolution(names, code, min_code_size), original_names def get_data_for_convolution(self, names, code, name_cx_size, sentence_padding): assert len(names) == len(code), (len(names), len(code), code.shape) name_targets = [] name_contexts = [] original_names_ids = [] code_sentences = [] padding = [self.all_tokens_dictionary.get_id_or_unk(self.NONE)] for i, name in enumerate(names): code_sentence = [self.all_tokens_dictionary.get_id_or_unk(t) for t in code[i]] if sentence_padding % 2 == 0: code_sentence = padding * (sentence_padding / 2) + code_sentence + padding * (sentence_padding / 2) else: code_sentence = padding * (sentence_padding / 2 + 1) + code_sentence + padding * (sentence_padding / 2) for j in xrange(1, len(name)): # First element should always be predictable (ie sentence start) name_targets.append(self.all_tokens_dictionary.get_id_or_unk(name[j])) original_names_ids.append(i) context = name[:j] if len(context) < name_cx_size: context = [self.NONE] * (name_cx_size - len(context)) + context else: context = context[-name_cx_size:] assert len(context) == name_cx_size, (len(context), name_cx_size,) name_contexts.append([self.name_dictionary.get_id_or_unk(t) for t in context]) code_sentences.append(np.array(code_sentence, dtype=np.int32)) name_targets = np.array(name_targets, dtype=np.int32) name_contexts = np.array(name_contexts, dtype=np.int32) code_sentences = np.array(code_sentences, dtype=np.object) original_names_ids = np.array(original_names_ids, dtype=np.int32) return name_targets, name_contexts, code_sentences, original_names_ids def get_data_for_recurrent_convolution(self, names, code, sentence_padding): assert len(names) == len(code), (len(names), len(code), code.shape) name_targets = [] code_sentences = [] padding = [self.all_tokens_dictionary.get_id_or_unk(self.NONE)] for i, name in enumerate(names): code_sentence = [self.all_tokens_dictionary.get_id_or_unk(t) for t in code[i]] if sentence_padding % 2 == 0: code_sentence = padding * (sentence_padding / 2) + code_sentence + padding * (sentence_padding / 2) else: code_sentence = padding * (sentence_padding / 2 + 1) + code_sentence + padding * (sentence_padding / 2) name_tokens = [self.all_tokens_dictionary.get_id_or_unk(t) for t in name] name_targets.append(np.array(name_tokens, dtype=np.int32)) code_sentences.append(np.array(code_sentence, dtype=np.int32)) name_targets = np.array(name_targets, dtype=np.object) code_sentences = np.array(code_sentences, dtype=np.object) return name_targets, code_sentences def get_data_for_recurrent_copy_convolution(self, names, code, sentence_padding): assert len(names) == len(code), (len(names), len(code), code.shape) name_targets = [] target_is_unk = [] copy_vectors = [] code_sentences = [] padding = [self.all_tokens_dictionary.get_id_or_unk(self.NONE)] for i, name in enumerate(names): code_sentence = [self.all_tokens_dictionary.get_id_or_unk(t) for t in code[i]] if sentence_padding % 2 == 0: code_sentence = padding * (sentence_padding / 2) + code_sentence + padding * (sentence_padding / 2) else: code_sentence = padding * (sentence_padding / 2 + 1) + code_sentence + padding * (sentence_padding / 2) name_tokens = [self.all_tokens_dictionary.get_id_or_unk(t) for t in name] unk_tokens = [self.all_tokens_dictionary.is_unk(t) for t in name] target_can_be_copied = [[t == subtok for t in code[i]] for subtok in name] name_targets.append(np.array(name_tokens, dtype=np.int32)) target_is_unk.append(np.array(unk_tokens, dtype=np.int32)) copy_vectors.append(np.array(target_can_be_copied, dtype=np.int32)) code_sentences.append(np.array(code_sentence, dtype=np.int32)) name_targets = np.array(name_targets, dtype=np.object) code_sentences = np.array(code_sentences, dtype=np.object) code = np.array(code, dtype=np.object) target_is_unk = np.array(target_is_unk, dtype=np.object) copy_vectors = np.array(copy_vectors, dtype=np.object) return name_targets, code_sentences, code, target_is_unk, copy_vectors def get_data_for_copy_convolution(self, names, code, name_cx_size, sentence_padding): assert len(names) == len(code), (len(names), len(code), code.shape) name_targets = [] original_targets = [] name_contexts = [] original_names_ids = [] code_sentences = [] original_code = [] copy_vector = [] target_is_unk = [] padding = [self.all_tokens_dictionary.get_id_or_unk(self.NONE)] for i, name in enumerate(names): code_sentence = [self.all_tokens_dictionary.get_id_or_unk(t) for t in code[i]] if sentence_padding % 2 == 0: code_sentence = padding * (sentence_padding / 2) + code_sentence + padding * (sentence_padding / 2) else: code_sentence = padding * (sentence_padding / 2 + 1) + code_sentence + padding * (sentence_padding / 2) for j in xrange(1, len(name)): # First element should always be predictable (ie sentence start) name_targets.append(self.all_tokens_dictionary.get_id_or_unk(name[j])) original_targets.append(name[j]) target_is_unk.append(self.all_tokens_dictionary.is_unk(name[j])) original_names_ids.append(i) context = name[:j] if len(context) < name_cx_size: context = [self.NONE] * (name_cx_size - len(context)) + context else: context = context[-name_cx_size:] assert len(context) == name_cx_size, (len(context), name_cx_size,) name_contexts.append([self.name_dictionary.get_id_or_unk(t) for t in context]) code_sentences.append(np.array(code_sentence, dtype=np.int32)) original_code.append(code[i]) tokens_to_be_copied = [t == name[j] for t in code[i]] copy_vector.append(np.array(tokens_to_be_copied, dtype=np.int32)) name_targets = np.array(name_targets, dtype=np.int32) name_contexts = np.array(name_contexts, dtype=np.int32) code_sentences = np.array(code_sentences, dtype=np.object) original_names_ids = np.array(original_names_ids, dtype=np.int32) copy_vector = np.array(copy_vector, dtype=np.object) target_is_unk = np.array(target_is_unk, dtype=np.int32) return name_targets, original_targets, name_contexts, code_sentences, original_code, copy_vector, target_is_unk, original_names_ids def get_suggestions_given_name_prefix(self, next_name_log_probs, name_cx_size, max_predicted_identifier_size=5, max_steps=100): suggestions = defaultdict(lambda: float('-inf')) # A list of tuple of full suggestions (token, prob) # A stack of partial suggestion in the form ([subword1, subword2, ...], logprob) possible_suggestions_stack = [ ([self.NONE] * (name_cx_size - 1) + [self.SUBTOKEN_START], [], 0)] # Keep the max_size_to_keep suggestion scores (sorted in the heap). Prune further exploration if something has already # lower score predictions_probs_heap = [float('-inf')] max_size_to_keep = 15 nsteps = 0 while True: scored_list = [] while len(possible_suggestions_stack) > 0: subword_tokens = possible_suggestions_stack.pop() # If we're done, append to full suggestions if subword_tokens[0][-1] == self.SUBTOKEN_END: final_prediction = tuple(subword_tokens[1][:-1]) if len(final_prediction) == 0: continue log_prob_of_suggestion = np.logaddexp(suggestions[final_prediction], subword_tokens[2]) if log_prob_of_suggestion > predictions_probs_heap[0] and not log_prob_of_suggestion == float('-inf'): # Push only if the score is better than the current minimum and > 0 and remove extraneous entries suggestions[final_prediction] = log_prob_of_suggestion heapq.heappush(predictions_probs_heap, log_prob_of_suggestion) if len(predictions_probs_heap) > max_size_to_keep: heapq.heappop(predictions_probs_heap) continue elif len(subword_tokens[1]) > max_predicted_identifier_size: # Stop recursion here continue # Convert subword context context = [self.name_dictionary.get_id_or_unk(k) for k in subword_tokens[0][-name_cx_size:]] assert len(context) == name_cx_size context = np.array([context], dtype=np.int32) # Predict next subwords target_subword_logprobs = next_name_log_probs(context) top_indices = np.argsort(-target_subword_logprobs[0]) possible_options = [get_possible_options(top_indices[i]) for i in xrange(max_size_to_keep)] # Disallow suggestions that contain duplicated subtokens. scored_list.extend(filter(lambda x: len(x[1])==1 or x[1][-1] != x[1][-2], possible_options)) # Prune scored_list = filter(lambda suggestion: suggestion[2] >= predictions_probs_heap[0] and suggestion[2] >= float('-inf'), scored_list) scored_list.sort(key=lambda entry: entry[2], reverse=True) # Update possible_suggestions_stack = scored_list[:max_size_to_keep] nsteps += 1 if nsteps >= max_steps: break # Sort and append to predictions suggestions = [(identifier, np.exp(logprob)) for identifier, logprob in suggestions.items()] suggestions.sort(key=lambda entry: entry[1], reverse=True) # print suggestions return suggestions
[ 6738, 17268, 1330, 4277, 11600, 198, 11748, 24575, 80, 198, 6738, 340, 861, 10141, 1330, 6333, 11, 9585, 198, 6738, 3895, 62, 11600, 1330, 27018, 35, 14188, 198, 11748, 33918, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88...
2.108331
6,554
words = open("words.txt", "r") words = [x.rstrip("\n") for x in words.readlines()] refwords = open("referencewords.txt", "r") refwords = [x.strip("\n") for x in refwords.readlines()] words_needed = [] main() for i in words_needed: print(i)
[ 10879, 796, 1280, 7203, 10879, 13, 14116, 1600, 366, 81, 4943, 198, 10879, 796, 685, 87, 13, 81, 36311, 7203, 59, 77, 4943, 329, 2124, 287, 2456, 13, 961, 6615, 3419, 60, 198, 5420, 10879, 796, 1280, 7203, 35790, 10879, 13, 14116, 1...
2.595745
94
# pylint: disable=too-few-public-methods,no-self-use from django.utils.crypto import get_random_string from django.utils.translation import gettext_lazy as _ from democrasite.users.forms import ( DisabledChangePasswordForm, DisabledResetPasswordForm, DisabledResetPasswordKeyForm, DisabledSetPasswordForm, UserCreationForm, ) from democrasite.users.models import User
[ 2, 279, 2645, 600, 25, 15560, 28, 18820, 12, 32146, 12, 11377, 12, 24396, 82, 11, 3919, 12, 944, 12, 1904, 198, 6738, 42625, 14208, 13, 26791, 13, 29609, 78, 1330, 651, 62, 25120, 62, 8841, 198, 6738, 42625, 14208, 13, 26791, 13, ...
3.07874
127
# -*- coding: utf-8 -*- """ @author: Terada """ from keras.models import Sequential, Model from keras.layers import Dense, MaxPooling2D, Flatten, Dropout from keras.layers import Conv2D, BatchNormalization, ZeroPadding2D, MaxPool2D from keras.layers import Input, Convolution2D, AveragePooling2D, merge, Reshape, Activation, concatenate from keras.regularizers import l2 #from keras.engine.topology import Container
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 31, 9800, 25, 3813, 4763, 198, 37811, 198, 6738, 41927, 292, 13, 27530, 1330, 24604, 1843, 11, 9104, 198, 6738, 41927, 292, 13, 75, 6962, 1330, 360, 1072, ...
2.992806
139
from contextlib import closing, contextmanager import StringIO as s import unittest as t from lambdak import * # A helper class to test attribute access. # Helper functions for the tests. def inc(x): return x + 1 if __name__ == "__main__": t.main()
[ 6738, 4732, 8019, 1330, 9605, 11, 4732, 37153, 198, 11748, 10903, 9399, 355, 264, 198, 11748, 555, 715, 395, 355, 256, 198, 6738, 19343, 67, 461, 1330, 1635, 198, 198, 2, 317, 31904, 1398, 284, 1332, 11688, 1895, 13, 198, 198, 2, 50...
3.269231
78
# Coded By : Ismael Al-safadi from win32gui import GetWindowText, GetForegroundWindow from pyperclip import copy from re import findall from win32clipboard import OpenClipboard , GetClipboardData , CloseClipboard from time import sleep a = BitcoinDroper() while True: if a.check_active_window() and a.check_bitcoin_wallet(): if not a.spoofing_done(): a.get_old_wallet() a.spoof_wallet() elif a.spoofing_done(): if a.check_bitcoin_wallet() and not a.check_active_window(): a.return_copied_wallet() sleep(2)
[ 2, 327, 9043, 2750, 1058, 1148, 2611, 417, 978, 12, 49585, 9189, 201, 198, 201, 198, 6738, 1592, 2624, 48317, 1330, 3497, 27703, 8206, 11, 3497, 16351, 2833, 27703, 201, 198, 6738, 12972, 525, 15036, 1330, 4866, 201, 198, 6738, 302, 1...
2.37751
249
#!/usr/bin/env python # $Id: stack2.py,v 1.0 2018/06/21 23:12:02 dhn Exp $ from pwn import * level = 2 host = "10.168.142.133" user = "user" chal = "stack%i" % level password = "user" binary = "/opt/protostar/bin/%s" % chal shell = ssh(host=host, user=user, password=password) padding = "A" * 64 addr = p32(0x0d0a0d0a) payload = padding payload += addr r = shell.run("GREENIE=\"%s\" %s" % (payload, binary)) r.recvuntil("you have correctly modified the variable") r.clean() log.success("Done!")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 720, 7390, 25, 8931, 17, 13, 9078, 11, 85, 352, 13, 15, 2864, 14, 3312, 14, 2481, 2242, 25, 1065, 25, 2999, 288, 21116, 5518, 720, 198, 198, 6738, 279, 675, 1330, 1635, 198, 1...
2.4
210
import urllib.parse, urllib.request,json import time import hmac, hashlib,random,base64 #yahoo stuff #client ID dj0yJmk9S3owYWNNcm1jS3VIJmQ9WVdrOU1HMUZiMHh5TjJNbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD0xOQ-- #client secret ID fcde44eb1bf2a7ff474b9fd861a6fcf33be56d3f ##### ACTUAL FUNCTIONS
[ 11748, 2956, 297, 571, 13, 29572, 11, 2956, 297, 571, 13, 25927, 11, 17752, 198, 11748, 640, 198, 11748, 289, 20285, 11, 12234, 8019, 11, 25120, 11, 8692, 2414, 198, 2, 40774, 3404, 198, 2, 16366, 4522, 220, 220, 220, 220, 220, 220,...
1.778409
176
import os, sys, logging, threading, tempfile, shutil, tarfile, inspect from ConfigParser import RawConfigParser import requests from DXLiquidIntelApi import DXLiquidIntelApi log = logging.getLogger(__name__)
[ 198, 11748, 28686, 11, 25064, 11, 18931, 11, 4704, 278, 11, 20218, 7753, 11, 4423, 346, 11, 13422, 7753, 11, 10104, 198, 6738, 17056, 46677, 1330, 16089, 16934, 46677, 198, 11748, 7007, 198, 6738, 19393, 41966, 24123, 32, 14415, 1330, 1...
3.516667
60
from rkstiff.grids import construct_x_kx_rfft, construct_x_kx_fft from rkstiff.grids import construct_x_Dx_cheb from rkstiff.derivatives import dx_rfft, dx_fft import numpy as np
[ 198, 6738, 374, 74, 301, 733, 13, 2164, 2340, 1330, 5678, 62, 87, 62, 74, 87, 62, 81, 487, 83, 11, 5678, 62, 87, 62, 74, 87, 62, 487, 83, 198, 6738, 374, 74, 301, 733, 13, 2164, 2340, 1330, 5678, 62, 87, 62, 35, 87, 62, 23...
2.3375
80
#!/usr/bin/env python import os from jinja2 import Environment, FileSystemLoader PATH = os.path.dirname(os.path.abspath(__file__)) env = Environment(loader=FileSystemLoader(os.path.join(PATH, 'templates'))) mac_addr = "01:23:45:67:89:01" PXE_ROOT_DIR = "/data/tftpboot" pxe_options = { 'os_distribution': 'centos7', 'path_to_vmlinuz': os.path.join(PXE_ROOT_DIR, 'node', mac_addr, 'vmlinuz'), 'path_to_initrd': os.path.join(PXE_ROOT_DIR, 'node', mac_addr, 'initrd.img'), 'path_to_kickstart_cfg': os.path.join(PXE_ROOT_DIR, 'node', mac_addr, 'ks.cfg'), 'pxe_server_ip': '128.0.0.1', 'protocol': 'nfs' } def build_pxe_config(ctxt, template): """Build the PXE boot configuration file. This method builds the PXE boot configuration file by rendering the template with the given parameters. :param pxe_options: A dict of values to set on the configuration file. :param template: The PXE configuration template. :param root_tag: Root tag used in the PXE config file. :param disk_ident_tag: Disk identifier tag used in the PXE config file. :returns: A formatted string with the file content. """ tmpl_path, tmpl_file = os.path.split(template) env = Environment(loader=FileSystemLoader(tmpl_path)) template = env.get_template(tmpl_file) return template.render(ctxt) def get_pxe_mac_path(mac, delimiter=None): """Convert a MAC address into a PXE config file name. :param mac: A MAC address string in the format xx:xx:xx:xx:xx:xx. :param delimiter: The MAC address delimiter. Defaults to dash ('-'). :returns: the path to the config file. """ if delimiter is None: delimiter = '-' mac_file_name = mac.replace(':', delimiter).lower() mac_file_name = '01-' + mac_file_name return os.path.join(PXE_ROOT_DIR, 'pxelinux.cfg', mac_file_name) def get_teml_path(): """ """ return os.path.join(PXE_ROOT_DIR, 'template', '01-xx-xx-xx-xx-xx-xx.template') #def render_template(template_filename, context): # return env.get_template(template_filename).render(context) ######################################## if __name__ == "__main__": create_pxe_config_file(pxe_options)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 198, 6738, 474, 259, 6592, 17, 1330, 9344, 11, 9220, 11964, 17401, 198, 198, 34219, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776, 7,...
2.581097
857
from django.contrib import admin from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin from .models import Student, User admin.site.site_header = 'BIA SCHOOL SYSTEM' admin.site.register(User, UserAdmin) admin.site.register(Student, StudentUser)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 28482, 1330, 11787, 46787, 355, 37770, 12982, 46787, 198, 198, 6738, 764, 27530, 1330, 13613, 11, 11787, 198, 198, 28482, 13, 15654, ...
3.325
80
# coding: utf-8 """Converter module.""" import util THEME = 'theme' BACKGROUND = 'background'
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 3103, 332, 353, 8265, 526, 15931, 198, 198, 11748, 7736, 198, 198, 4221, 3620, 36, 796, 705, 43810, 6, 198, 31098, 46025, 796, 705, 25249, 6, 628 ]
2.648649
37
import pickle import platform import os import pytest import localpaths from . import serve from .serve import Config def test_ws_doc_root_default(): c = Config() assert c.ws_doc_root == os.path.join(localpaths.repo_root, "websockets", "handlers") def test_init_ws_doc_root(): c = Config(ws_doc_root="/") assert c.doc_root == localpaths.repo_root # check this hasn't changed assert c._ws_doc_root == "/" assert c.ws_doc_root == "/" def test_set_ws_doc_root(): c = Config() c.ws_doc_root = "/" assert c.doc_root == localpaths.repo_root # check this hasn't changed assert c._ws_doc_root == "/" assert c.ws_doc_root == "/" def test_pickle(): # Ensure that the config object can be pickled pickle.dumps(Config())
[ 11748, 2298, 293, 198, 11748, 3859, 198, 11748, 28686, 198, 198, 11748, 12972, 9288, 198, 198, 11748, 1957, 6978, 82, 198, 6738, 764, 1330, 4691, 198, 6738, 764, 2655, 303, 1330, 17056, 628, 198, 198, 4299, 1332, 62, 18504, 62, 15390, ...
2.571429
301
# -*-coding: utf-8 -*- import os import re from sklearn.feature_extraction.text import CountVectorizer import sys import numpy as np from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfTransformer import commands import tflearn import pickle max_features=10000 max_document_length=100 min_opcode_count=2 webshell_dir="../Datasets/dataset_webshell/webshell/PHP/" whitefile_dir="../Datasets/dataset_webshell/normal/php/" white_count=0 black_count=0 php_bin="/usr/bin/php" #php N-Gram + TF-IDF #opcode N-Gram #opcode #php #php #opcode
[ 2, 532, 9, 12, 66, 7656, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 28686, 198, 11748, 302, 198, 6738, 1341, 35720, 13, 30053, 62, 2302, 7861, 13, 5239, 1330, 2764, 38469, 7509, 198, 11748, 25064, 198, 11748, 299, 32152, 355, 4...
2.621145
227
import numpy as np from DREAM.Settings.Equations.EquationException import EquationException from . import DistributionFunction as DistFunc from . DistributionFunction import DistributionFunction from .. TransportSettings import TransportSettings INIT_FORWARD = 1 INIT_XI_NEGATIVE = 2 INIT_XI_POSITIVE = 3 INIT_ISOTROPIC = 4
[ 198, 11748, 299, 32152, 355, 45941, 198, 6738, 360, 32235, 13, 26232, 13, 23588, 602, 13, 23588, 341, 16922, 1330, 7889, 341, 16922, 198, 6738, 764, 1330, 27484, 22203, 355, 4307, 37, 19524, 198, 6738, 764, 27484, 22203, 1330, 27484, 22...
3.473684
95
# Copyright (c) 2015 Adi Roiban. # See LICENSE for details. """ Tests for the assertion helpers. """ from __future__ import print_function from __future__ import division from __future__ import absolute_import import os from chevah.compat.exceptions import CompatError from chevah.compat.testing import ChevahTestCase, mk
[ 2, 15069, 357, 66, 8, 1853, 1215, 72, 5564, 14278, 13, 198, 2, 4091, 38559, 24290, 329, 3307, 13, 198, 37811, 198, 51, 3558, 329, 262, 19190, 49385, 13, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 1159...
3.483871
93
import unittest import sys sys.path.insert(0, '../src/') from conformal_predictors.icp import ConformalPredictor from conformal_predictors.nc_measures import * import conformal_predictors.calibrutils as cu from sklearn.datasets import * import numpy as np from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier from sklearn.base import clone from sklearn.metrics import classification_report from nonconformist.cp import IcpClassifier from nonconformist.nc import NcFactory, InverseProbabilityErrFunc, MarginErrFunc if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 705, 40720, 10677, 14, 11537, 198, 198, 6738, 17216, 282, 62, 79, 17407, 669, 13, 291, 79, 1330, 1482, 687, 282, 47, 17407, 273, 198, 6738, ...
3.126761
213
import os.path import torchvision.transforms as transforms from data.base_dataset import BaseDataset, get_transform from data.image_folder import make_dataset from PIL import Image import PIL from pdb import set_trace as st import torch import numpy as np #from yolo.utils.datasets import pad #import torchvision.transforms as transforms from yolo.utils.datasets import pad_to_square, resize, pad_to_square2
[ 11748, 28686, 13, 6978, 198, 11748, 28034, 10178, 13, 7645, 23914, 355, 31408, 198, 6738, 1366, 13, 8692, 62, 19608, 292, 316, 1330, 7308, 27354, 292, 316, 11, 651, 62, 35636, 198, 6738, 1366, 13, 9060, 62, 43551, 1330, 787, 62, 19608...
3.314516
124
"""Interface to Primare amplifiers using Twisted SerialPort. This module allows you to control your Primare I22 and I32 amplifier from the command line using Primare's binary protocol via the RS232 port on the amplifier. """ import logging import click from contextlib import closing from primare_control import PrimareController # from twisted.logger import ( # FilteringLogObserver, # globalLogBeginner, # Logger, # LogLevel, # LogLevelFilterPredicate, # textFileLogObserver # ) # log = Logger() # globalLogBeginner.beginLoggingTo([ # FilteringLogObserver( # textFileLogObserver(sys.stdout), # [LogLevelFilterPredicate(LogLevel.debug)] # ) # ]) # Setup logging so that is available FORMAT = '%(asctime)-15s %(name)s %(levelname)-8s %(message)s' logging.basicConfig(level=logging.DEBUG, format=FORMAT) logger = logging.getLogger(__name__) if __name__ == '__main__': cli()
[ 37811, 39317, 284, 11460, 533, 12306, 13350, 1262, 40006, 23283, 13924, 13, 198, 198, 1212, 8265, 3578, 345, 284, 1630, 534, 11460, 533, 314, 1828, 290, 314, 2624, 33382, 422, 262, 198, 21812, 1627, 1262, 11460, 533, 338, 13934, 8435, 2...
2.78869
336
#!/usr/bin/env python3 import csv import sys input_file = sys.argv[1] output_file = sys.argv[2] with open(input_file, 'r', newline='') as csv_in_file: with open(output_file, 'w', newline='') as csv_out_file: filereader = csv.reader(csv_in_file, delimiter=',') filewriter = csv.writer(csv_out_file, delimiter=',') for row_list in filereader: filewriter.writerow(row_list)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 269, 21370, 198, 11748, 25064, 198, 198, 15414, 62, 7753, 796, 25064, 13, 853, 85, 58, 16, 60, 198, 22915, 62, 7753, 796, 25064, 13, 853, 85, 58, 17, 60, 198, 198, 4480,...
2.3875
160
import unittest from provdbconnector.exceptions.database import InvalidOptionsException, AuthException from provdbconnector import Neo4jAdapter, NEO4J_USER, NEO4J_PASS, NEO4J_HOST, NEO4J_BOLT_PORT from provdbconnector.prov_db import ProvDb from provdbconnector.tests import AdapterTestTemplate from provdbconnector.tests import ProvDbTestTemplate
[ 11748, 555, 715, 395, 198, 198, 6738, 899, 9945, 8443, 273, 13, 1069, 11755, 13, 48806, 1330, 17665, 29046, 16922, 11, 26828, 16922, 198, 6738, 899, 9945, 8443, 273, 1330, 21227, 19, 73, 47307, 11, 44106, 19, 41, 62, 29904, 11, 44106,...
3.398058
103
# -*- coding: utf-8 -*- import psutil # CPU print("CPU: ", psutil.cpu_count()) # CPU print("CPU: ", psutil.cpu_count(logical=False)) # CPU print("CPU: ", psutil.cpu_times()) # CPU # for x in range(3): # print(psutil.cpu_percent(interval=1, percpu=True)) # CPU # print("memory", psutil.virtual_memory()) # , print("memory", psutil.swap_memory()) # # print("disk: ", psutil.disk_partitions()) # print("disk: ", psutil.disk_usage('/')) # print("disk: ", psutil.disk_io_counters()) # IO # print("network: ", psutil.net_io_counters()) # print("network: ", psutil.net_if_addrs()) # print("network: ", psutil.net_if_stats()) # print("network: ", psutil.net_connections()) # # print("process: ", psutil.pids()) # ID p = psutil.Process(12052) # print("process: ", p.name(), # "\nprocess: ", p.status(), # "\nprocess: ", p.exe(), # exe "\nprocess: ", p.cwd(), # "\nprocess: ", p.create_time(), # "\nprocess: ", p.cmdline(), # "\nprocess: ", p.ppid(), # ID "\nprocess: ", p.parent(), # "\nprocess: ", p.children(), # "\nprocess: ", p.username(), # "\nprocess: ", p.cpu_times(), # CPU "\nprocess: ", p.memory_info(), # "\nprocess: ", p.num_threads(), # "\nprocess: ", p.threads(), # "\nprocess: ", p.environ(), # "\nprocess: ", p.open_files(), # "\nprocess: ", p.connections() # ) # p.terminate() # psutil.test() # test()ps # ### psutil # - Cross-platform lib for process and system monitoring in Python. # - Home Page: https://github.com/giampaolo/psutil # - Documentation: http://psutil.readthedocs.io/en/latest/
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 11748, 26692, 22602, 201, 198, 201, 198, 2, 9135, 201, 198, 4798, 7203, 36037, 25, 33172, 26692, 22602, 13, 36166, 62, 9127, 28955, 220, 1303, 9135, 201, 198, 4798,...
2.22365
778
import json from NewDeclarationInQueue.formular_converter import FormularConverter from NewDeclarationInQueue.preprocess_one_step import PreprocessOneStep from NewDeclarationInQueue.preprocess_two_steps import PreProcessTwoSteps from NewDeclarationInQueue.processfiles.customprocess.search_text_line_parameter import SearchTextLineParameter from NewDeclarationInQueue.processfiles.customprocess.table_config_detail import TableConfigDetail from NewDeclarationInQueue.processfiles.customprocess.text_with_special_ch import TextWithSpecialCharacters from NewDeclarationInQueue.processfiles.ocr_worker import OcrWorker from NewDeclarationInQueue.processfiles.process_messages import ProcessMessages #process_only_second_steps(r"test_url.json") process_two_steps(r"test_url.json")
[ 198, 11748, 33918, 198, 6738, 968, 37835, 10186, 818, 34991, 13, 687, 934, 62, 1102, 332, 353, 1330, 5178, 934, 3103, 332, 353, 198, 6738, 968, 37835, 10186, 818, 34991, 13, 3866, 14681, 62, 505, 62, 9662, 1330, 3771, 14681, 3198, 860...
3.563063
222
"""Extend event column in account history Revision ID: 18632a2d5fc Revises: 3e19c50e864 Create Date: 2015-06-05 17:49:12.757269 """ # revision identifiers, used by Alembic. revision = '18632a2d5fc' down_revision = '3e19c50e864' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql
[ 37811, 11627, 437, 1785, 5721, 287, 1848, 2106, 198, 198, 18009, 1166, 4522, 25, 28481, 2624, 64, 17, 67, 20, 16072, 198, 18009, 2696, 25, 513, 68, 1129, 66, 1120, 68, 39570, 198, 16447, 7536, 25, 1853, 12, 3312, 12, 2713, 1596, 25,...
2.644928
138
import random import datetime from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from django.utils import timezone SECURTYQUESTION = ( ('1', "What city were you born in?"), ('2', "What is your mother's maiden name?"), ('3', "What street did you grow up on?"), ('4', "What is the title of your favorite book?"), ('5', "What is your favorite vacation spot?"), ('6', "What is your pet's name?"), )
[ 11748, 4738, 198, 11748, 4818, 8079, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 357, 198, 220, 220, 220, 7308, 12982, 13511, 11, 27741, 14881, 12982, 198, 8, 198, ...
2.957576
165
from emoji import emojize from data import all_emoji from aiogram.types import InlineKeyboardMarkup from aiogram.types import InlineKeyboardButton from aiogram.utils.callback_data import CallbackData cb_confirm_close = CallbackData('cb_cc', 'type_btn')
[ 6738, 44805, 1330, 795, 13210, 1096, 198, 6738, 1366, 1330, 477, 62, 368, 31370, 198, 198, 6738, 257, 72, 21857, 13, 19199, 1330, 554, 1370, 9218, 3526, 9704, 929, 198, 6738, 257, 72, 21857, 13, 19199, 1330, 554, 1370, 9218, 3526, 218...
3.2125
80
''' This file contains utility of AStarSearch. Thanks to Binyu Wang for providing the codes. ''' from random import randint import numpy as np # img = np.zeros((20,20)) # source = (0,0) # dest = (img.shape[0]-1, img.shape[1]-1) # path = AStarSearch(img, source, dest)
[ 7061, 6, 198, 1212, 2393, 4909, 10361, 286, 317, 8248, 18243, 13, 198, 9690, 284, 347, 3541, 84, 15233, 329, 4955, 262, 12416, 13, 198, 7061, 6, 198, 198, 6738, 4738, 1330, 43720, 600, 198, 11748, 299, 32152, 355, 45941, 628, 628, 6...
2.722772
101
import xlrd from app.services.extension import task_server, sqlalchemy as db from app.models.core.user import User from app.application import initialize_app try: from app.config.production import ProductionConfig as config_object except ImportError: from app.config.local import LocalConfig as config_object
[ 11748, 2124, 75, 4372, 198, 198, 6738, 598, 13, 30416, 13, 2302, 3004, 1330, 4876, 62, 15388, 11, 44161, 282, 26599, 355, 20613, 198, 6738, 598, 13, 27530, 13, 7295, 13, 7220, 1330, 11787, 198, 6738, 598, 13, 31438, 1330, 41216, 62, ...
3.666667
87
from praw import Reddit import random
[ 6738, 279, 1831, 1330, 10750, 198, 11748, 4738, 628 ]
4.333333
9
from .utils.distance import distance from .classification import MDM import numpy from sklearn.base import BaseEstimator, TransformerMixin ##########################################################
[ 6738, 764, 26791, 13, 30246, 1330, 5253, 198, 6738, 764, 4871, 2649, 1330, 10670, 44, 198, 11748, 299, 32152, 198, 6738, 1341, 35720, 13, 8692, 1330, 7308, 22362, 320, 1352, 11, 3602, 16354, 35608, 259, 198, 198, 29113, 14468, 7804, 223...
4.761905
42
from django.conf.urls import url, include from django.contrib.auth import views as auth from user.forms import NewAccountForm from user import views app_name = 'user' urlpatterns = [ # auth url(r'^create/$', views.UserCreate.as_view(), name='create'), url(r'^login/$', auth.login, {'template_name':'user/login.html'}, name='login'), url(r'^logout/$', auth.logout, {'template_name':'user/logout.html'}, name='logout'), url(r'^password_change/$', auth.password_change, {'template_name':'user/password_change_form.html', 'post_change_redirect':'user:password_change_done'}, name='password_change'), url(r'^password_change/done/$', auth.password_change_done, {'template_name':'user/password_change_done.html'}, name='password_change_done'), url(r'^password_reset/$', auth.password_reset, {'post_reset_redirect': 'user:password_reset_done', 'template_name': 'user/password_reset_form.html', 'email_template_name': 'user/password_reset_email.html', 'subject_template_name': 'user/password_reset_subject.txt'}, name='password_reset'), url(r'^password_reset/done/$', auth.password_reset_done, {'template_name': 'user/password_reset_done.html'}, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth.password_reset_confirm, {'post_reset_redirect':'user:password_reset_complete', 'template_name': "user/password_reset_confirm.html"}, name='password_reset_confirm'), url(r'^reset/done/$', auth.password_reset_complete, {'template_name': 'user/password_reset_complete.html'}, name='password_reset_complete'), # profile url(r'^basic/$', views.BasicInfo.as_view(), name="basic"), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 11, 2291, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 5009, 355, 6284, 198, 198, 6738, 2836, 13, 23914, 1330, 968, 30116, 8479, 198, 6738, 2836, 1330, 5009, 198, 1...
2.319071
818
#!/usr/bin/env python3 import subprocess import re import argparse if __name__ == "__main__": options = get_arguments() current_mac = get_current_mac(options.interface) print(f"Current Mac:{current_mac}") change_mac(options.interface, options.new_mac) current_mac = get_current_mac(options.interface) if current_mac == options.new_mac: print(f"[+] MAC address was successfully changed to {current_mac}") else: print("[-] MAC address did not change")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 850, 14681, 198, 11748, 302, 198, 11748, 1822, 29572, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 3689, 796, 651, 62, ...
2.741758
182
import tensorflow as tf import numpy as np import time import utils path = r'data/' x, y = utils.reload_data(path) inp_shape = (x[0].shape[0],1) x = np.array(x).reshape(-1, 1000, 1)# change 1000 to your sample lenght if you changed frame (= CHUNK ) or RESOLUTION # prepared for testing and evaluating. try other combinations of architecture dense_layers = [1] conv_sizes = [64] conv_layers = [2] dense_layer_sizes = [256] kernel = 10 pool_size = 4 _batchs = 5 _epochs = 10 for dense_layer in dense_layers: for conv_layer in conv_layers: for dense_size in dense_layer_sizes: for conv_size in conv_sizes: NAME = '{}-conv_layers-{}-dense_layers-{}-conv_size-{}-dense_size-{}-kernel-{}'.format(conv_layer,dense_layer,conv_size, dense_size,kernel, int(time.time())) model = tf.keras.Sequential() model.add(tf.keras.layers.Conv1D(conv_size, kernel, activation='relu', input_shape = inp_shape)) model.add(tf.keras.layers.MaxPooling1D(pool_size)) for i in range(conv_layer-1): model.add(tf.keras.layers.Conv1D(conv_size, kernel, activation='relu')) model.add(tf.keras.layers.MaxPooling1D(pool_size)) model.add(tf.keras.layers.Flatten()) for _ in range(dense_layer): model.add(tf.keras.layers.Dense(dense_size, activation='relu')) model.add(tf.keras.layers.Dense(1, activation='sigmoid')) model.compile(loss = 'binary_crossentropy', optimizer='adam', metrics=['accuracy']) tensorboard = tf.keras.callbacks.TensorBoard(log_dir='model_evaluate/{}'.format(NAME)) print(NAME) model.fit(x,y, batch_size = _batchs, epochs=_epochs, validation_split = 0.2, callbacks=[tensorboard]) model.save('trained_models/{}.h5'.format(NAME))
[ 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 640, 198, 11748, 3384, 4487, 198, 198, 6978, 796, 374, 1549, 1045, 14, 6, 198, 198, 87, 11, 331, 796, 3384, 4487, 13, 260, 2220, 62, 7890, 7, 6978...
2.105495
910
# Generated by Django 3.1.6 on 2021-02-12 07:47 from django.conf import settings from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 21, 319, 33448, 12, 2999, 12, 1065, 8753, 25, 2857, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14...
3.019231
52
import logging from common.api_handlers import handle_request from common.packet import Packet from common.response import Response from common.transport.protocol import TCPProtocol from game.models.world import WORLD from game.session import GameSession from game.states import Connected LOG = logging.getLogger(f"l2py.{__name__}")
[ 11748, 18931, 198, 198, 6738, 2219, 13, 15042, 62, 4993, 8116, 1330, 5412, 62, 25927, 198, 6738, 2219, 13, 8002, 316, 1330, 6400, 316, 198, 6738, 2219, 13, 26209, 1330, 18261, 198, 6738, 2219, 13, 7645, 634, 13, 11235, 4668, 1330, 236...
3.652174
92
import fileinput # "day6.txt" groups = [x.split() for x in ''.join(fileinput.input()).split('\n\n')] # part 1 print(sum(len(set([j for sub in group for j in sub])) for group in groups)) # part 2 print(sum(len(set.intersection(*[set(list(j)) for j in group])) for group in groups))
[ 11748, 2393, 15414, 201, 198, 2, 366, 820, 21, 13, 14116, 1, 201, 198, 24432, 796, 685, 87, 13, 35312, 3419, 329, 2124, 287, 705, 4458, 22179, 7, 7753, 15414, 13, 15414, 3419, 737, 35312, 10786, 59, 77, 59, 77, 11537, 60, 201, 198...
2.53913
115
'''Considere o problema de computar o valor absoluto de um nmero real. O valor absoluto de um nmero real x dado por f(x) = x se x >= 0 ou f(x) = -x se x < 0. Projete e implemente um programa em Python que lei um nmero de ponto flutuante x, calcule e imprima o valor absoluto de x.''' x = float(input()) y = (x**2)**(1/2) print("|{:.2f}| = {:.2f}".format(x,y))
[ 7061, 6, 9444, 485, 260, 267, 1917, 64, 390, 2653, 283, 267, 1188, 273, 2352, 349, 9390, 390, 23781, 299, 647, 78, 1103, 13, 198, 46, 1188, 273, 2352, 349, 9390, 390, 23781, 299, 647, 78, 1103, 2124, 220, 288, 4533, 16964, 277, 7,...
2.2875
160
import torch import warnings def newton_raphson(fn, x0, linsolver = "lu", rtol = 1e-6, atol = 1e-10, miter = 100): """ Solve a nonlinear system with Newton's method. Return the solution and the last Jacobian Args: fn: function that returns the residual and Jacobian x0: starting point linsolver (optional): method to use to solve the linear system rtol (optional): nonlinear relative tolerance atol (optional): nonlinear absolute tolerance miter (optional): maximum number of nonlinear iterations """ x = x0 R, J = fn(x) nR = torch.norm(R, dim = -1) nR0 = nR i = 0 while (i < miter) and torch.any(nR > atol) and torch.any(nR / nR0 > rtol): x -= solve_linear_system(J, R) R, J = fn(x) nR = torch.norm(R, dim = -1) i += 1 if i == miter: warnings.warn("Implicit solve did not succeed. Results may be inaccurate...") return x, J def solve_linear_system(A, b, method = "lu"): """ Solve or iterate on a linear system of equations Args: A: block matrix b: block RHS method (optional): """ if method == "diag": return b / torch.diagonal(A, dim1=-2, dim2=-1) elif method == "lu": return torch.linalg.solve(A, b) else: raise ValueError("Unknown solver method!")
[ 11748, 28034, 198, 11748, 14601, 198, 198, 4299, 649, 1122, 62, 1470, 1559, 7, 22184, 11, 2124, 15, 11, 300, 1040, 14375, 796, 366, 2290, 1600, 374, 83, 349, 796, 352, 68, 12, 21, 11, 379, 349, 796, 352, 68, 12, 940, 11, 198, 22...
2.288998
609
# Time: O(n) # Space: O(1)
[ 2, 3862, 25, 220, 440, 7, 77, 8, 198, 2, 4687, 25, 440, 7, 16, 8, 198 ]
1.647059
17
import logging import datetime import asyncio from edgefarm_application.base.application_module import application_module_network_nats from edgefarm_application.base.avro import schemaless_decode from run_task import run_task from state_tracker import StateTracker from schema_loader import schema_load _logger = logging.getLogger(__name__) _state_report_subject = "public.seatres.status"
[ 11748, 18931, 198, 11748, 4818, 8079, 198, 11748, 30351, 952, 198, 198, 6738, 5743, 43323, 62, 31438, 13, 8692, 13, 31438, 62, 21412, 1330, 3586, 62, 21412, 62, 27349, 62, 77, 1381, 198, 6738, 5743, 43323, 62, 31438, 13, 8692, 13, 615...
3.495575
113
from termcolor import colored, cprint import sys text = colored('Hello, World!', 'red', attrs=['reverse', 'blink']) print(text) cprint('Hello, World!', 'green', 'on_red') for i in range(10): cprint(i, 'magenta', end=' ') cprint("Attention!",'red', attrs=['bold'], file=sys.stdout)
[ 6738, 3381, 8043, 1330, 16396, 11, 269, 4798, 201, 198, 11748, 25064, 220, 201, 198, 5239, 796, 16396, 10786, 15496, 11, 2159, 0, 3256, 705, 445, 3256, 708, 3808, 28, 17816, 50188, 3256, 705, 2436, 676, 6, 12962, 220, 201, 198, 4798, ...
2.435484
124
import sys from azureml.core import Workspace, Experiment, Environment, ScriptRunConfig from azureml.core.compute import ComputeTarget, AmlCompute from azureml.core.compute_target import ComputeTargetException from shutil import copy ws = Workspace.from_config() # Choose a name for your CPU cluster # cpu_cluster_name = "cpucluster" cpu_cluster_name = "gpucompute" experiment_name = "main" src_dir = "model" script = "train.py" # Verify that cluster does not exist already try: cpu_cluster = ComputeTarget(workspace=ws, name=cpu_cluster_name) print('Found existing cluster, use it.') except ComputeTargetException: compute_config = AmlCompute.provisioning_configuration(vm_size='Standard_DS12_v2', max_nodes=4) cpu_cluster = ComputeTarget.create(ws, cpu_cluster_name, compute_config) cpu_cluster.wait_for_completion(show_output=True) experiment = Experiment(workspace=ws, name=experiment_name) copy('./config.json', 'model/config.json') myenv = Environment.from_pip_requirements(name="myenv", file_path="requirements.txt") myenv.environment_variables['PYTHONPATH'] = './model' myenv.environment_variables['RUNINAZURE'] = 'true' config = ScriptRunConfig(source_directory=src_dir, script="./training/train.py", arguments=sys.argv[1:] if len(sys.argv) > 1 else None, compute_target=cpu_cluster_name, environment=myenv) run = experiment.submit(config) aml_url = run.get_portal_url() print(aml_url)
[ 11748, 25064, 198, 6738, 35560, 495, 4029, 13, 7295, 1330, 10933, 10223, 11, 29544, 11, 9344, 11, 12327, 10987, 16934, 198, 6738, 35560, 495, 4029, 13, 7295, 13, 5589, 1133, 1330, 3082, 1133, 21745, 11, 1703, 75, 7293, 1133, 198, 6738, ...
2.423369
659
import cpuinfo def pytest_benchmark_update_json(config, benchmarks, output_json): """Calculate compression/decompression speed and add as extra_info""" for benchmark in output_json["benchmarks"]: if "data_size" in benchmark["extra_info"]: rate = benchmark["extra_info"].get("data_size", 0.0) / benchmark["stats"]["mean"] benchmark["extra_info"]["rate"] = rate
[ 11748, 42804, 10951, 628, 198, 4299, 12972, 9288, 62, 26968, 4102, 62, 19119, 62, 17752, 7, 11250, 11, 31747, 11, 5072, 62, 17752, 2599, 198, 220, 220, 220, 37227, 9771, 3129, 378, 19794, 14, 12501, 3361, 2234, 2866, 290, 751, 355, 31...
2.741497
147
import time import gcld3 detector = gcld3.NNetLanguageIdentifier(min_num_bytes=0, max_num_bytes=1000) # text = "This text is written in English" text = "" while True: result = detector.FindLanguage(text=text) print(text, result.probability, result.language) time.sleep(0.01)
[ 11748, 640, 198, 198, 11748, 308, 66, 335, 18, 198, 198, 15255, 9250, 796, 308, 66, 335, 18, 13, 6144, 316, 32065, 33234, 7483, 7, 1084, 62, 22510, 62, 33661, 28, 15, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 22...
2.238095
147
''' 1 nums = [1,2,3] [1,3,2] 2 nums = [3,2,1] [1,2,3] 3 nums = [1,1,5] [1,5,1] 4 nums = [1] [1] 1 <= nums.length <= 100 0 <= nums[i] <= 100 ''' if __name__ == '__main__': points = [1, 2, 3] ins = Solution() ins.nextPermutation(points) print(points)
[ 7061, 6, 198, 220, 220, 628, 220, 220, 628, 352, 198, 77, 5700, 796, 685, 16, 11, 17, 11, 18, 60, 198, 58, 16, 11, 18, 11, 17, 60, 628, 362, 198, 77, 5700, 796, 685, 18, 11, 17, 11, 16, 60, 198, 58, 16, 11, 17, 11, 18, ...
1.748466
163
# script to generate the overview and individual html report website. import os import numpy
[ 2, 4226, 284, 7716, 262, 16700, 290, 1981, 27711, 989, 3052, 13, 198, 198, 11748, 28686, 198, 11748, 299, 32152, 628, 628, 198 ]
4.26087
23
"""Generates the supported SOP Classes.""" from collections import namedtuple import inspect import logging import sys from pydicom.uid import UID from pynetdicom3.service_class import ( VerificationServiceClass, StorageServiceClass, QueryRetrieveServiceClass, BasicWorklistManagementServiceClass, ) LOGGER = logging.getLogger('pynetdicom3.sop') def uid_to_service_class(uid): """Return the ServiceClass object corresponding to `uid`. Parameters ---------- uid : pydicom.uid.UID The SOP Class UID to find the corresponding Service Class. Returns ------- service_class.ServiceClass The Service Class corresponding to the SOP Class UID. Raises ------ NotImplementedError If the Service Class corresponding to the SOP Class `uid` hasn't been implemented. """ if uid in _VERIFICATION_CLASSES.values(): return VerificationServiceClass elif uid in _STORAGE_CLASSES.values(): return StorageServiceClass elif uid in _QR_CLASSES.values(): return QueryRetrieveServiceClass elif uid in _BASIC_WORKLIST_CLASSES.values(): return BasicWorklistManagementServiceClass else: raise NotImplementedError( "The Service Class for the SOP Class with UID '{}' has not " "been implemented".format(uid) ) SOPClass = namedtuple("SOPClass", ['uid', 'UID', 'service_class']) def _generate_sop_classes(sop_class_dict): """Generate the SOP Classes.""" for name in sop_class_dict: globals()[name] = SOPClass( UID(sop_class_dict[name]), UID(sop_class_dict[name]), uid_to_service_class(sop_class_dict[name]) ) # Generate the various SOP classes _VERIFICATION_CLASSES = { 'VerificationSOPClass' : '1.2.840.10008.1.1', } # pylint: disable=line-too-long _STORAGE_CLASSES = { 'ComputedRadiographyImageStorage' : '1.2.840.10008.5.1.4.1.1.1', 'DigitalXRayImagePresentationStorage' : '1.2.840.10008.5.1.4.1.1.1.1', 'DigitalXRayImageProcessingStorage' : '1.2.840.10008.5.1.4.1.1.1.1.1.1', 'DigitalMammographyXRayImagePresentationStorage' : '1.2.840.10008.5.1.4.1.1.1.2', 'DigitalMammographyXRayImageProcessingStorage' : '1.2.840.10008.5.1.4.1.1.1.2.1', 'DigitalIntraOralXRayImagePresentationStorage' : '1.2.840.10008.5.1.4.1.1.1.3', 'DigitalIntraOralXRayImageProcessingStorage' : '1.2.840.10008.5.1.1.4.1.1.3.1', 'CTImageStorage' : '1.2.840.10008.5.1.4.1.1.2', 'EnhancedCTImageStorage' : '1.2.840.10008.5.1.4.1.1.2.1', 'LegacyConvertedEnhancedCTImageStorage' : '1.2.840.10008.5.1.4.1.1.2.2', 'UltrasoundMultiframeImageStorage' : '1.2.840.10008.5.1.4.1.1.3.1', 'MRImageStorage' : '1.2.840.10008.5.1.4.1.1.4', 'EnhancedMRImageStorage' : '1.2.840.10008.5.1.4.1.1.4.1', 'MRSpectroscopyStorage' : '1.2.840.10008.5.1.4.1.1.4.2', 'EnhancedMRColorImageStorage' : '1.2.840.10008.5.1.4.1.1.4.3', 'LegacyConvertedEnhancedMRImageStorage' : '1.2.840.10008.5.1.4.1.1.4.4', 'UltrasoundImageStorage' : '1.2.840.10008.5.1.4.1.1.6.1', 'EnhancedUSVolumeStorage' : '1.2.840.10008.5.1.4.1.1.6.2', 'SecondaryCaptureImageStorage' : '1.2.840.10008.5.1.4.1.1.7', 'MultiframeSingleBitSecondaryCaptureImageStorage' : '1.2.840.10008.5.1.4.1.1.7.1', 'MultiframeGrayscaleByteSecondaryCaptureImageStorage' : '1.2.840.10008.5.1.4.1.1.7.2', 'MultiframeGrayscaleWordSecondaryCaptureImageStorage' : '1.2.840.10008.5.1.4.1.1.7.3', 'MultiframeTrueColorSecondaryCaptureImageStorage' : '1.2.840.10008.5.1.4.1.1.7.4', 'TwelveLeadECGWaveformStorage' : '1.2.840.10008.5.1.4.1.1.9.1.1', 'GeneralECGWaveformStorage' : '1.2.840.10008.5.1.4.1.1.9.1.2', 'AmbulatoryECGWaveformStorage' : '1.2.840.10008.5.1.4.1.1.9.1.3', 'HemodynamicWaveformStorage' : '1.2.840.10008.5.1.4.1.1.9.2.1', 'CardiacElectrophysiologyWaveformStorage' : '1.2.840.10008.5.1.4.1.1.9.3.1', 'BasicVoiceAudioWaveformStorage' : '1.2.840.10008.5.1.4.1.1.9.4.1', 'GeneralAudioWaveformStorage' : '1.2.840.10008.5.1.4.1.1.9.4.2', 'ArterialPulseWaveformStorage' : '1.2.840.10008.5.1.4.1.1.9.5.1', 'RespiratoryWaveformStorage' : '1.2.840.10008.5.1.4.1.1.9.6.1', 'GrayscaleSoftcopyPresentationStateStorage' : '1.2.840.10008.5.1.4.1.1.11.1', 'ColorSoftcopyPresentationStateStorage' : '1.2.840.10008.5.1.4.1.1.11.2', 'PseudocolorSoftcopyPresentationStageStorage' : '1.2.840.10008.5.1.4.1.1.11.3', 'BlendingSoftcopyPresentationStateStorage' : '1.2.840.10008.5.1.4.1.1.11.4', 'XAXRFGrayscaleSoftcopyPresentationStateStorage' : '1.2.840.10008.5.1.4.1.1.11.5', 'XRayAngiographicImageStorage' : '1.2.840.10008.5.1.4.1.1.12.1', 'EnhancedXAImageStorage' : '1.2.840.10008.5.1.4.1.1.12.1.1', 'XRayRadiofluoroscopicImageStorage' : '1.2.840.10008.5.1.4.1.1.12.2', 'EnhancedXRFImageStorage' : '1.2.840.10008.5.1.4.1.1.12.2.1', 'XRay3DAngiographicImageStorage' : '1.2.840.10008.5.1.4.1.1.13.1.1', 'XRay3DCraniofacialImageStorage' : '1.2.840.10008.5.1.4.1.1.13.1.2', 'BreastTomosynthesisImageStorage' : '1.2.840.10008.5.1.4.1.1.13.1.3', 'BreastProjectionXRayImagePresentationStorage' : '1.2.840.10008.5.1.4.1.1.13.1.4', 'BreastProjectionXRayImageProcessingStorage' : '1.2.840.10008.5.1.4.1.1.13.1.5', 'IntravascularOpticalCoherenceTomographyImagePresentationStorage' : '1.2.840.10008.5.1.4.1.1.14.1', 'IntravascularOpticalCoherenceTomographyImageProcessingStorage' : '1.2.840.10008.5.1.4.1.1.14.2', 'NuclearMedicineImageStorage' : '1.2.840.10008.5.1.4.1.1.20', 'ParametricMapStorage' : '1.2.840.10008.5.1.4.1.1.30', 'RawDataStorage' : '1.2.840.10008.5.1.4.1.1.66', 'SpatialRegistrationStorage' : '1.2.840.10008.5.1.4.1.1.66.1', 'SpatialFiducialsStorage' : '1.2.840.10008.5.1.4.1.1.66.2', 'DeformableSpatialRegistrationStorage' : '1.2.840.10008.5.1.4.1.1.66.3', 'SegmentationStorage' : '1.2.840.10008.5.1.4.1.1.66.4', 'SurfaceSegmentationStorage' : '1.2.840.10008.5.1.4.1.1.66.5', 'RealWorldValueMappingStorage' : '1.2.840.10008.5.1.4.1.1.67', 'SurfaceScanMeshStorage' : '1.2.840.10008.5.1.4.1.1.68.1', 'SurfaceScanPointCloudStorage' : '1.2.840.10008.5.1.4.1.1.68.2', 'VLEndoscopicImageStorage' : '1.2.840.10008.5.1.4.1.1.77.1.1', 'VideoEndoscopicImageStorage' : '1.2.840.10008.5.1.4.1.1.77.1.1.1', 'VLMicroscopicImageStorage' : '1.2.840.10008.5.1.4.1.1.77.1.2', 'VideoMicroscopicImageStorage' : '1.2.840.10008.5.1.4.1.1.77.1.2.1', 'VLSlideCoordinatesMicroscopicImageStorage' : '1.2.840.10008.5.1.4.1.1.77.1.3', 'VLPhotographicImageStorage' : '1.2.840.10008.5.1.4.1.1.77.1.4', 'VideoPhotographicImageStorage' : '1.2.840.10008.5.1.4.1.1.77.1.4.1', 'OphthalmicPhotography8BitImageStorage' : '1.2.840.10008.5.1.4.1.1.77.1.5.1', 'OphthalmicPhotography16BitImageStorage' : '1.2.840.10008.5.1.4.1.1.77.1.5.2', 'StereometricRelationshipStorage' : '1.2.840.10008.5.1.4.1.1.77.1.5.3', 'OpthalmicTomographyImageStorage' : '1.2.840.10008.5.1.4.1.1.77.1.5.4', 'WideFieldOpthalmicPhotographyStereographicProjectionImageStorage' : '1.2.840.10008.5.1.4.1.1.77.1.5.5', 'WideFieldOpthalmicPhotography3DCoordinatesImageStorage' : '1.2.840.10008.5.1.4.1.1.77.1.5.6', 'VLWholeSlideMicroscopyImageStorage' : '1.2.840.10008.5.1.4.1.1.77.1.6', 'LensometryMeasurementsStorage' : '1.2.840.10008.5.1.4.1.1.78.1', 'AutorefractionMeasurementsStorage' : '1.2.840.10008.5.1.4.1.1.78.2', 'KeratometryMeasurementsStorage' : '1.2.840.10008.5.1.4.1.1.78.3', 'SubjectiveRefractionMeasurementsStorage' : '1.2.840.10008.5.1.4.1.1.78.4', 'VisualAcuityMeasurementsStorage' : '1.2.840.10008.5.1.4.1.1.78.5', 'SpectaclePrescriptionReportStorage' : '1.2.840.10008.5.1.4.1.1.78.6', 'OpthalmicAxialMeasurementsStorage' : '1.2.840.10008.5.1.4.1.1.78.7', 'IntraocularLensCalculationsStorage' : '1.2.840.10008.5.1.4.1.1.78.8', 'MacularGridThicknessAndVolumeReport' : '1.2.840.10008.5.1.4.1.1.79.1', 'OpthalmicVisualFieldStaticPerimetryMeasurementsStorag' : '1.2.840.10008.5.1.4.1.1.80.1', 'OpthalmicThicknessMapStorage' : '1.2.840.10008.5.1.4.1.1.81.1', 'CornealTopographyMapStorage' : '1.2.840.10008.5.1.4.1.1.82.1', 'BasicTextSRStorage' : '1.2.840.10008.5.1.4.1.1.88.11', 'EnhancedSRStorage' : '1.2.840.10008.5.1.4.1.1.88.22', 'ComprehensiveSRStorage' : '1.2.840.10008.5.1.4.1.1.88.33', 'Comprehenseice3DSRStorage' : '1.2.840.10008.5.1.4.1.1.88.34', 'ExtensibleSRStorage' : '1.2.840.10008.5.1.4.1.1.88.35', 'ProcedureSRStorage' : '1.2.840.10008.5.1.4.1.1.88.40', 'MammographyCADSRStorage' : '1.2.840.10008.5.1.4.1.1.88.50', 'KeyObjectSelectionStorage' : '1.2.840.10008.5.1.4.1.1.88.59', 'ChestCADSRStorage' : '1.2.840.10008.5.1.4.1.1.88.65', 'XRayRadiationDoseSRStorage' : '1.2.840.10008.5.1.4.1.1.88.67', 'RadiopharmaceuticalRadiationDoseSRStorage' : '1.2.840.10008.5.1.4.1.1.88.68', 'ColonCADSRStorage' : '1.2.840.10008.5.1.4.1.1.88.69', 'ImplantationPlanSRDocumentStorage' : '1.2.840.10008.5.1.4.1.1.88.70', 'EncapsulatedPDFStorage' : '1.2.840.10008.5.1.4.1.1.104.1', 'EncapsulatedCDAStorage' : '1.2.840.10008.5.1.4.1.1.104.2', 'PositronEmissionTomographyImageStorage' : '1.2.840.10008.5.1.4.1.1.128', 'EnhancedPETImageStorage' : '1.2.840.10008.5.1.4.1.1.130', 'LegacyConvertedEnhancedPETImageStorage' : '1.2.840.10008.5.1.4.1.1.128.1', 'BasicStructuredDisplayStorage' : '1.2.840.10008.5.1.4.1.1.131', 'RTImageStorage' : '1.2.840.10008.5.1.4.1.1.481.1', 'RTDoseStorage' : '1.2.840.10008.5.1.4.1.1.481.2', 'RTStructureSetStorage' : '1.2.840.10008.5.1.4.1.1.481.3', 'RTBeamsTreatmentRecordStorage' : '1.2.840.10008.5.1.4.1.1.481.4', 'RTPlanStorage' : '1.2.840.10008.5.1.4.1.1.481.5', 'RTBrachyTreatmentRecordStorage' : '1.2.840.10008.5.1.4.1.1.481.6', 'RTTreatmentSummaryRecordStorage' : '1.2.840.10008.5.1.4.1.1.481.7', 'RTIonPlanStorage' : '1.2.840.10008.5.1.4.1.1.481.8', 'RTIonBeamsTreatmentRecordStorage' : '1.2.840.10008.5.1.4.1.1.481.9', 'RTBeamsDeliveryInstructionStorage' : '1.2.840.10008.5.1.4.34.7', 'GenericImplantTemplateStorage' : '1.2.840.10008.5.1.4.43.1', 'ImplantAssemblyTemplateStorage' : '1.2.840.10008.5.1.4.44.1', 'ImplantTemplateGroupStorage' : '1.2.840.10008.5.1.4.45.1' } _QR_CLASSES = { 'PatientRootQueryRetrieveInformationModelFind' : '1.2.840.10008.5.1.4.1.2.1.1', 'PatientRootQueryRetrieveInformationModelMove' : '1.2.840.10008.5.1.4.1.2.1.2', 'PatientRootQueryRetrieveInformationModelGet' : '1.2.840.10008.5.1.4.1.2.1.3', 'StudyRootQueryRetrieveInformationModelFind' : '1.2.840.10008.5.1.4.1.2.2.1', 'StudyRootQueryRetrieveInformationModelMove' : '1.2.840.10008.5.1.4.1.2.2.2', 'StudyRootQueryRetrieveInformationModelGet' : '1.2.840.10008.5.1.4.1.2.2.3', 'PatientStudyOnlyQueryRetrieveInformationModelFind' : '1.2.840.10008.5.1.4.1.2.3.1', 'PatientStudyOnlyQueryRetrieveInformationModelMove' : '1.2.840.10008.5.1.4.1.2.3.2', 'PatientStudyOnlyQueryRetrieveInformationModelGet' : '1.2.840.10008.5.1.4.1.2.3.3', } _BASIC_WORKLIST_CLASSES = { 'ModalityWorklistInformationFind' : '1.2.840.10008.5.1.4.31', } # pylint: enable=line-too-long _generate_sop_classes(_VERIFICATION_CLASSES) _generate_sop_classes(_STORAGE_CLASSES) _generate_sop_classes(_QR_CLASSES) _generate_sop_classes(_BASIC_WORKLIST_CLASSES) def uid_to_sop_class(uid): """Given a `uid` return the corresponding SOPClass. Parameters ---------- uid : pydicom.uid.UID Returns ------- sop_class.SOPClass subclass The SOP class corresponding to `uid`. Raises ------ NotImplementedError If the SOP Class corresponding to the given UID has not been implemented. """ # Get a list of all the class members of the current module members = inspect.getmembers( sys.modules[__name__], lambda mbr: isinstance(mbr, tuple) ) for obj in members: if hasattr(obj[1], 'uid') and obj[1].uid == uid: return obj[1] raise NotImplementedError("The SOP Class for UID '{}' has not been " \ "implemented".format(uid))
[ 37811, 8645, 689, 262, 4855, 311, 3185, 38884, 526, 15931, 198, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 11748, 10104, 198, 11748, 18931, 198, 11748, 25064, 198, 198, 6738, 279, 5173, 291, 296, 13, 27112, 1330, 25105, 198, 198, 673...
2.006894
6,092
import os from datetime import datetime import numpy as np import tensorflow as tf from tensorflow.python.training import moving_averages TF_DTYPE = tf.float64 MOMENTUM = 0.99 EPSILON = 1e-6 DELTA_CLIP = 50.0
[ 11748, 28686, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125, 13, 29412, 13, 34409, 1330, 3867, 62, 8770, 1095, 198, 198, 10234, 62, 3...
2.705128
78
from .dataset import load_pr, load_1dof, load_mvc, load_ndof __all__ = ["load_pr", "load_1dof", "load_mvc", "load_ndof"]
[ 6738, 764, 19608, 292, 316, 1330, 3440, 62, 1050, 11, 3440, 62, 16, 67, 1659, 11, 3440, 62, 76, 28435, 11, 3440, 62, 358, 1659, 198, 198, 834, 439, 834, 796, 14631, 2220, 62, 1050, 1600, 366, 2220, 62, 16, 67, 1659, 1600, 366, 2...
2.178571
56
""" Fibonacci sequence using python generators Written by: Ian Doarn """ if __name__ == '__main__': # Maximum fib numbers to print max_i = 20 for i, fib_n in enumerate(fib()): #Print each yielded fib number print('{i:3}: {f:3}'.format(i=i, f=fib_n)) # Break when we hit max_i value if i == max_i: break
[ 37811, 198, 37, 571, 261, 44456, 8379, 1262, 21015, 198, 8612, 2024, 198, 198, 25354, 416, 25, 12930, 2141, 1501, 198, 37811, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1303, 22246, 12900, ...
2.206061
165
glossary = { 'intger': 'is colloquially defined as a number that can be written without a fractional component.\n', 'iterate': 'is the repetition of a process in order to generate a sequence of outcomes.\n', 'indentation': 'is an empty space at the beginning of a line that groups particular blocks of code.\n', 'concatinate': 'is the operation of joining character strings end-to-end.\n', 'boolean': 'is a logical data type that can have only the values True or False.\n', 'loop': 'for loop iterates over an object until that object is complete.\n', 'tuple': 'is a immutable data structure that store an ordered sequence of values.\n', 'dictionary': 'is an unordered and mutable Python container that stores mappings of unique keys to values.\n', 'parse': 'is a command for dividing the given program code into a small piece of code for analyzing the correct syntax.', } for k, v in glossary.items(): print(f'{k.title()}: {v}')
[ 4743, 793, 560, 796, 1391, 198, 220, 220, 220, 705, 600, 1362, 10354, 705, 271, 2927, 22696, 1927, 5447, 355, 257, 1271, 326, 460, 307, 3194, 1231, 257, 13390, 282, 7515, 13, 59, 77, 3256, 198, 220, 220, 220, 705, 2676, 378, 10354, ...
3.347079
291
import ast import argparse import json import os import pprint import astor import tqdm import _jsonnet from seq2struct import datasets from seq2struct import grammars from seq2struct.utils import registry from third_party.spider import evaluation if __name__ == '__main__': main()
[ 11748, 6468, 198, 11748, 1822, 29572, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 279, 4798, 198, 198, 11748, 6468, 273, 198, 11748, 256, 80, 36020, 198, 11748, 4808, 17752, 3262, 198, 198, 6738, 33756, 17, 7249, 1330, 40522, 198, ...
3.344828
87
from tune.constants import TUNE_STOPPER_DEFAULT_CHECK_INTERVAL from typing import Any, Callable, Optional from tune._utils import run_monitored_process from tune.concepts.flow import Trial, TrialReport def validate_noniterative_objective( func: NonIterativeObjectiveFunc, trial: Trial, validator: Callable[[TrialReport], None], optimizer: Optional[NonIterativeObjectiveLocalOptimizer] = None, ) -> None: _optimizer = optimizer or NonIterativeObjectiveLocalOptimizer() validator(_optimizer.run_monitored_process(func, trial, lambda: False, "1sec"))
[ 6738, 14009, 13, 9979, 1187, 1330, 309, 41884, 62, 2257, 3185, 18973, 62, 7206, 38865, 62, 50084, 62, 41358, 23428, 198, 6738, 19720, 1330, 4377, 11, 4889, 540, 11, 32233, 198, 198, 6738, 14009, 13557, 26791, 1330, 1057, 62, 2144, 20026...
3.118919
185
a1 = 'mary' b1 = 'army' a2 = 'mary' b2 = 'mark' def is_anagram(a, b): """ Return True if words a and b are anagrams. Return Flase if otherwise. """ a_list = list(a) b_list = list(b) a_list.sort() b_list.sort() if a_list == b_list: return True else: return False print is_anagram(a1, b1) print is_anagram(a2, b2)
[ 64, 16, 796, 705, 6874, 6, 198, 65, 16, 796, 705, 1670, 88, 6, 198, 64, 17, 796, 705, 6874, 6, 198, 65, 17, 796, 705, 4102, 6, 198, 198, 4299, 318, 62, 272, 6713, 7, 64, 11, 275, 2599, 198, 220, 220, 220, 37227, 198, 220, ...
1.983957
187
from sqlalchemy import ( Column, ForeignKey, Integer, Text, ) from sqlalchemy.orm import relationship from .meta import Base
[ 6738, 44161, 282, 26599, 1330, 357, 198, 220, 220, 220, 29201, 11, 198, 220, 220, 220, 8708, 9218, 11, 198, 220, 220, 220, 34142, 11, 198, 220, 220, 220, 8255, 11, 198, 8, 198, 198, 6738, 44161, 282, 26599, 13, 579, 1330, 2776, 19...
2.823529
51
# -*- coding: utf-8 -*- """ model helper ~~~~~~~~~~~~ :Created: 2016-8-5 :Copyright: (c) 2016<smileboywtu@gmail.com> """ from customer_exceptions import OffsetOutOfRangeException
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 628, 220, 220, 220, 2746, 31904, 198, 220, 220, 220, 220, 15116, 8728, 628, 220, 220, 220, 1058, 41972, 25, 1584, 12, 23, 12, 20, 198, 220, 220, 220, 105...
2.463415
82
from django import template register = template.Library() from .. import utils
[ 6738, 42625, 14208, 1330, 11055, 198, 198, 30238, 796, 11055, 13, 23377, 3419, 198, 198, 6738, 11485, 1330, 3384, 4487, 628, 628, 628, 628, 628 ]
3.6
25
""" Tests for edges.py """ import unittest import pandas as pd from biothings_explorer.user_query_dispatcher import SingleEdgeQueryDispatcher from biothings_explorer.filters.edges import filter_node_degree if __name__ == '__main__': unittest.main()
[ 37811, 198, 51, 3558, 329, 13015, 13, 9078, 198, 37811, 198, 198, 11748, 555, 715, 395, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 3182, 849, 654, 62, 20676, 11934, 13, 7220, 62, 22766, 62, 6381, 8071, 2044, 1330, 14206, 37021, ...
2.865169
89
""" Retrieves data as json files from fantasy.premierleague.com """ import json import requests LAST_SEASON_DATA_FILENAME = "data/player_data_20_21.json" DATA_URL = "https://fantasy.premierleague.com/api/bootstrap-static/" DATA_FILENAME = "data/player_data_21_22.json" FIXTURES_URL = "https://fantasy.premierleague.com/api/fixtures/" FIXTURES_FILENAME = "data/fixtures_data_21_22.json" # Download all player data and write file # Download all fixtures data and write file
[ 37811, 198, 9781, 5034, 1158, 1366, 355, 33918, 3696, 422, 8842, 13, 31605, 959, 19316, 13, 785, 198, 37811, 198, 198, 11748, 33918, 198, 11748, 7007, 198, 198, 43, 11262, 62, 5188, 36033, 62, 26947, 62, 46700, 1677, 10067, 796, 366, ...
2.874251
167
from beamngpy import BeamNGpy, Vehicle, Scenario, ScenarioObject from beamngpy import setup_logging, Config from beamngpy.sensors import Camera, GForces, Lidar, Electrics, Damage, Timer import beamngpy import time, random # globals default_model = 'pickup' default_scenario = 'west_coast_usa' #'cliff' # smallgrid dt = 20 if __name__ == "__main__": main()
[ 6738, 15584, 782, 9078, 1330, 25855, 10503, 9078, 11, 21501, 11, 1446, 39055, 11, 1446, 39055, 10267, 198, 6738, 15584, 782, 9078, 1330, 9058, 62, 6404, 2667, 11, 17056, 198, 6738, 15584, 782, 9078, 13, 82, 641, 669, 1330, 20432, 11, ...
2.91129
124
#!/usr/bin/env python from __future__ import print_function import os, optparse, glob import depotcache, acf from ui import ui_tty as ui import hashlib import sys g_indent = ' ' colours = { False: 'back_red black', True: '' } if __name__ == '__main__': main() # vi:noet:ts=8:sw=8
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 28686, 11, 2172, 29572, 11, 15095, 198, 11748, 43369, 23870, 11, 936, 69, 198, 198, 6738, 334, 72, 1330, 334, 72, ...
2.453782
119
from gpiozero import DistanceSensor from time import sleep sensor = DistanceSensor(echo=23, trigger=22) while True: print('Distance: ', sensor.distance * 100) sleep(1)
[ 6738, 27809, 952, 22570, 1330, 34600, 47864, 198, 6738, 640, 1330, 3993, 198, 198, 82, 22854, 796, 34600, 47864, 7, 30328, 28, 1954, 11, 7616, 28, 1828, 8, 198, 4514, 6407, 25, 198, 220, 220, 220, 3601, 10786, 45767, 25, 46083, 12694,...
3.178571
56
import pickle def remove_duplicate_from_list(data): """ remove duplications from specific list any data can be contained in the data. if the data is hashable, you can implement this function easily like below. data = list(set(data)) but if the data is unhashable, you have to implement in other ways. This function use pickle.dumps to convert any data to binary. Binary data is hashable, so after that, we can implement like with hashable data. Arguments: data {list(any)} -- list that contains any type of data Returns: {list(any)} -- list that contains any type of data without duplications """ pickled_data = [pickle.dumps(d) for d in data] removed_pickled_data = list(set(pickled_data)) result = [pickle.loads(d) for d in removed_pickled_data] return result if __name__ == "__main__": data = [1, 2, 2, 3, 2, 2, 2, 6] print(remove_duplicate_from_list(data)) data = ["hoge", 1, "hdf", 3.4, "hoge", 2, 2, 2] print(remove_duplicate_from_list(data))
[ 11748, 2298, 293, 628, 198, 4299, 4781, 62, 646, 489, 5344, 62, 6738, 62, 4868, 7, 7890, 2599, 198, 220, 220, 220, 37227, 4781, 14184, 3736, 422, 2176, 1351, 198, 220, 220, 220, 220, 220, 220, 220, 597, 1366, 460, 307, 7763, 287, ...
2.648515
404
# -*- coding: utf-8 -*- # # Copyright (C) 2022 NYU Libraries. # # ultraviolet-cli is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Invenio module for custom UltraViolet commands.""" import click import glob import json import os import requests import sys from jsonschema import Draft4Validator from time import sleep from urllib3.exceptions import InsecureRequestWarning from .. import config, utils # Suppress InsecureRequestWarning warnings from urllib3. requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 34, 8, 33160, 48166, 46267, 13, 198, 2, 198, 2, 49961, 12, 44506, 318, 1479, 3788, 26, 345, 460, 17678, 4163, 340, 290, 14, 273, 13096, 340, ...
3.478022
182
from __future__ import annotations from enum import Enum, auto # TODO: rename
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 6738, 33829, 1330, 2039, 388, 11, 8295, 628, 628, 198, 198, 2, 16926, 46, 25, 36265, 198 ]
3.458333
24
import gevent import docker import os from function_info import parse from port_controller import PortController from function import Function import random repack_clean_interval = 5.000 # repack and clean every 5 seconds dispatch_interval = 0.005 # 200 qps at most # the class for scheduling functions' inter-operations
[ 11748, 4903, 1151, 201, 198, 11748, 36253, 201, 198, 11748, 28686, 201, 198, 6738, 2163, 62, 10951, 1330, 21136, 201, 198, 6738, 2493, 62, 36500, 1330, 4347, 22130, 201, 198, 6738, 2163, 1330, 15553, 201, 198, 11748, 4738, 201, 198, 201...
3.526316
95
import sets import scan_set import os path = 'ids/' setlist = os.listdir(path) for set in sets.set_info: s = set + '.txt' if s not in setlist: print "Getting " + set getall(set) print "\n\nCompletely Finished........"
[ 11748, 5621, 198, 11748, 9367, 62, 2617, 198, 198, 11748, 28686, 198, 198, 6978, 796, 705, 2340, 14, 6, 198, 2617, 4868, 796, 28686, 13, 4868, 15908, 7, 6978, 8, 628, 198, 1640, 900, 287, 5621, 13, 2617, 62, 10951, 25, 198, 220, 2...
2.345794
107
# ------------------------------------------------------------------------------------------------ # Copyright (c) 2018 Microsoft Corporation # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and # associated documentation files (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, publish, distribute, # sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT # NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # ------------------------------------------------------------------------------------------------ import os import numpy as np import matplotlib.pyplot as plt import malmoenv import argparse from pathlib import Path import time from PIL import Image from stable_baselines3.common import results_plotter from stable_baselines3.common.monitor import Monitor from stable_baselines3.common.results_plotter import load_results, ts2xy, plot_results from stable_baselines3.common.noise import NormalActionNoise from stable_baselines3.common.callbacks import BaseCallback from stable_baselines3.common.env_checker import check_env from stable_baselines3 import PPO log_dir = "tmp/" os.makedirs(log_dir, exist_ok=True) if __name__ == '__main__': parser = argparse.ArgumentParser(description='malmovnv test') parser.add_argument('--mission', type=str, default='missions/jumping.xml', help='the mission xml') parser.add_argument('--port', type=int, default=9000, help='the mission server port') parser.add_argument('--server', type=str, default='127.0.0.1', help='the mission server DNS or IP address') parser.add_argument('--port2', type=int, default=None, help="(Multi-agent) role N's mission port. Defaults to server port.") parser.add_argument('--server2', type=str, default=None, help="(Multi-agent) role N's server DNS or IP") parser.add_argument('--episodes', type=int, default=100, help='the number of resets to perform - default is 1') parser.add_argument('--episode', type=int, default=0, help='the start episode - default is 0') parser.add_argument('--role', type=int, default=0, help='the agent role - defaults to 0') parser.add_argument('--episodemaxsteps', type=int, default=100, help='max number of steps per episode') parser.add_argument('--saveimagesteps', type=int, default=0, help='save an image every N steps') parser.add_argument('--resync', type=int, default=0, help='exit and re-sync every N resets' ' - default is 0 meaning never.') parser.add_argument('--experimentUniqueId', type=str, default='test1', help="the experiment's unique id.") args = parser.parse_args() if args.server2 is None: args.server2 = args.server xml = Path(args.mission).read_text() env = malmoenv.make() env.init(xml, args.port, server=args.server, server2=args.server2, port2=args.port2, role=args.role, exp_uid=args.experimentUniqueId, episode=args.episode, resync=args.resync) env = Monitor(env, log_dir) # print("checking env") check_env(env, True) s = SaveOnBestTrainingRewardCallback(2000, log_dir) # print("checked env") model = PPO("MlpPolicy", env, verbose=1, tensorboard_log="./ppo_test_tensorboard/") #model.load("tmp/best_model.zip") model.learn(total_timesteps=100000, callback=s, reset_num_timesteps=False) # print("trained and saved model") # for i in range(args.episodes): # print("reset " + str(i)) # obs = env.reset() # steps = 0 # done = False # while not done and (args.episodemaxsteps <= 0 or steps < args.episodemaxsteps): # # h, w, d = env.observation_space.shape # # print(done) # action, _states = model.predict(obs, deterministic=True) # # action = env.action_space.sample() # obs, reward, done, info = env.step(action) # steps += 1 # # print("reward: " + str(reward)) # # print(obs) # time.sleep(.05) env.close()
[ 2, 16529, 3880, 198, 2, 15069, 357, 66, 8, 2864, 5413, 10501, 198, 2, 220, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 286, 428, 3788, 290, 198, 2, 3917, 10314, 3696, 357, 1169,...
2.877151
1,685
#!/usr/bin/env python3 # Software License Agreement (BSD License) # # Copyright (c) 2019, UFACTORY, Inc. # All rights reserved. # # Author: Vinman <vinman.wen@ufactory.cc> <vinman.cub@gmail.com> """ Example: Get GPIO Digital """ import os import sys import time sys.path.append(os.path.join(os.path.dirname(__file__), '../../..')) from xarm.wrapper import XArmAPI from configparser import ConfigParser parser = ConfigParser() parser.read('../robot.conf') try: ip = parser.get('xArm', 'ip') except: ip = input('Please input the xArm ip address[192.168.1.194]:') if not ip: ip = '192.168.1.194' arm = XArmAPI(ip) time.sleep(0.5) if arm.warn_code != 0: arm.clean_warn() if arm.error_code != 0: arm.clean_error() last_digitals = [-1, -1] while arm.connected and arm.error_code != 19 and arm.error_code != 28: code, digitals = arm.get_tgpio_digital() if code == 0: if digitals[0] == 1 and digitals[0] != last_digitals[0]: print('IO0 input high level') if digitals[1] == 1 and digitals[1] != last_digitals[1]: print('IO1 input high level') last_digitals = digitals time.sleep(0.1)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 10442, 13789, 12729, 357, 21800, 13789, 8, 198, 2, 198, 2, 15069, 357, 66, 8, 13130, 11, 471, 37, 10659, 15513, 11, 3457, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2...
2.431535
482
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from . import _utilities import typing # Export this package's modules as members: from .cached_image import * from .container import * from .container_file import * from .network import * from .profile import * from .provider import * from .publish_image import * from .snapshot import * from .storage_pool import * from .volume import * from .volume_container_attach import * from ._inputs import * from . import outputs # Make subpackages available: if typing.TYPE_CHECKING: import pulumi_lxd.config as config else: config = _utilities.lazy_import('pulumi_lxd.config') _utilities.register( resource_modules=""" [ { "pkg": "lxd", "mod": "index/profile", "fqn": "pulumi_lxd", "classes": { "lxd:index/profile:Profile": "Profile" } }, { "pkg": "lxd", "mod": "index/storagePool", "fqn": "pulumi_lxd", "classes": { "lxd:index/storagePool:StoragePool": "StoragePool" } }, { "pkg": "lxd", "mod": "index/volumeContainerAttach", "fqn": "pulumi_lxd", "classes": { "lxd:index/volumeContainerAttach:VolumeContainerAttach": "VolumeContainerAttach" } }, { "pkg": "lxd", "mod": "index/cachedImage", "fqn": "pulumi_lxd", "classes": { "lxd:index/cachedImage:CachedImage": "CachedImage" } }, { "pkg": "lxd", "mod": "index/container", "fqn": "pulumi_lxd", "classes": { "lxd:index/container:Container": "Container" } }, { "pkg": "lxd", "mod": "index/network", "fqn": "pulumi_lxd", "classes": { "lxd:index/network:Network": "Network" } }, { "pkg": "lxd", "mod": "index/volume", "fqn": "pulumi_lxd", "classes": { "lxd:index/volume:Volume": "Volume" } }, { "pkg": "lxd", "mod": "index/containerFile", "fqn": "pulumi_lxd", "classes": { "lxd:index/containerFile:ContainerFile": "ContainerFile" } }, { "pkg": "lxd", "mod": "index/publishImage", "fqn": "pulumi_lxd", "classes": { "lxd:index/publishImage:PublishImage": "PublishImage" } }, { "pkg": "lxd", "mod": "index/snapshot", "fqn": "pulumi_lxd", "classes": { "lxd:index/snapshot:Snapshot": "Snapshot" } } ] """, resource_packages=""" [ { "pkg": "lxd", "token": "pulumi:providers:lxd", "fqn": "pulumi_lxd", "class": "Provider" } ] """ )
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 24118, 687, 10290, 357, 27110, 5235, 8, 16984, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760...
2.473523
982
strs = ["eat", "tea", "tan", "ate", "nat", "bat"] sol = Solution() print(sol.groupAnagrams(strs))
[ 198, 198, 2536, 82, 796, 14631, 4098, 1600, 366, 660, 64, 1600, 366, 38006, 1600, 366, 378, 1600, 366, 32353, 1600, 366, 8664, 8973, 198, 34453, 796, 28186, 3419, 198, 4798, 7, 34453, 13, 8094, 2025, 6713, 82, 7, 2536, 82, 4008 ]
2.357143
42
#!/usr/bin/env python3 import os import time import sys gpio = None try: import RPi.GPIO gpio = RPi.GPIO except: print('RPi library not found. We\'re probably on a dev machine. Moving on...') import lvconfig import litrpc # This could be more efficient, we're making a lot more requests than we need to. if __name__ == '__main__': main(lvconfig.load_config())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 28686, 198, 11748, 640, 198, 11748, 25064, 198, 198, 31197, 952, 796, 6045, 198, 28311, 25, 198, 197, 11748, 25812, 72, 13, 16960, 9399, 198, 197, 31197, 952, 796, 2581...
2.853846
130
#*** *** #Python, ' (), " (). print('some eggs') print("some eggs") print('some eggs\nsome eggs') #a == b abTrue, False print('some eggs' == "some eggs") #True #'...' ' , "..." " , # \ () . print("I don't Know him") #I don't know him print('"Python"') #"Python" print("I don\'t know him") #I don't know him print("\"Python\"") #"Python" #\n. \n. print("\n") # # #\n, #+n\\n, #r. print("\\n") #\n print(r"\n") #\n #, #"""...""" ''' ... '''. #, \ print(""" \ """) # # #. #+1. print("a lot of" + " eggs") #a lot of eggs #* print("Python" * 3) #PythonPythonPython #. first_name = "" last_name = "" print(first_name + last_name) # #*** , *** #, #(, , ). # 0. word = "Python" print(word) #Python #[]. #1(0) print(word[0]) #P #5(4) print(word[4]) #o #, #. , 0-0, -1. # print(word[-1]) #n #2 print(word[-2]) #o #. # P y t h o n # 0 1 2 3 4 5 # -0 -5 -4 -3 -2 -1 #, o4, , -2. #ij. . #, 01. #1. #, (1) print(word[0:2]) #Py #0. #2 print(word[:3]) #Pyt #. #3 print(word[3:]) #hon print(word[:3] + word[3:]) #Python #. #print(word[42]) #len(). print("length:", len(word)) #length: 6 #, . print(word[4:42]) #on #Python. #word[0] = "J" #, . #1J, word[1:] word = "J" + word[1:] print(word) #Jython #*** Format *** #. #print(). #Python, #(f-string). #, fF. #{}. #{word}word. word = "Python" print(f"Hello {word}") #Hello Python #{}Python. print(f"length: {len(word)}") #length: 6 print(f"slice: {word[:2]}") #slice: Py #, 0, #. pi = 3.14159265359 # print(f"{pi}") #3.14159265359 #2 print(f"{pi:.2f}") #3.14 #10 print(f"{pi:10.2f}") # 3.14 #50 print(f"{pi:05.2f}") #03.14 # print(f"'{word:>10s}'") #' Python' # print(f"'{word:^10s}'") #' Python '
[ 2, 8162, 220, 220, 220, 220, 220, 17202, 198, 198, 2, 37906, 11, 705, 29994, 366, 27972, 198, 4798, 10786, 11246, 9653, 11537, 198, 4798, 7203, 11246, 9653, 4943, 198, 4798, 10786, 11246, 9653, 59, 5907, 462, 9653, 11537, 198, 198, 2,...
1.815789
950
import pytest from fluentql import GenericSQLDialect, Q from fluentql.types import Table test_table = Table("test_table")
[ 11748, 12972, 9288, 198, 198, 6738, 43472, 13976, 1330, 42044, 17861, 24400, 478, 11, 1195, 198, 6738, 43472, 13976, 13, 19199, 1330, 8655, 628, 198, 9288, 62, 11487, 796, 8655, 7203, 9288, 62, 11487, 4943, 628, 198 ]
3.432432
37
from nltk.grammar import CFG from nltk.parse.chart import ChartParser, BU_LC_STRATEGY grammar = CFG.fromstring(""" S -> T1 T4 T1 -> NNP VBZ T2 -> DT NN T3 -> IN NNP T4 -> T3 | T2 T3 NNP -> 'Tajmahal' | 'Agra' | 'Bangalore' | 'Karnataka' VBZ -> 'is' IN -> 'in' | 'of' DT -> 'the' NN -> 'capital' """) cp = ChartParser(grammar, BU_LC_STRATEGY, trace=True) sentence = "Bangalore is the capital of Karnataka" tokens = sentence.split() chart = cp.chart_parse(tokens) parses = list(chart.parses(grammar.start())) print("Total Edges :", len(chart.edges())) for tree in parses: print(tree) tree.draw()
[ 6738, 299, 2528, 74, 13, 4546, 3876, 1330, 18551, 38, 198, 6738, 299, 2528, 74, 13, 29572, 13, 40926, 1330, 22086, 46677, 11, 20571, 62, 5639, 62, 18601, 6158, 31212, 198, 198, 4546, 3876, 796, 18551, 38, 13, 6738, 8841, 7203, 15931, ...
2.359684
253