index
int64
0
10k
blob_id
stringlengths
40
40
step-1
stringlengths
0
305k
step-2
stringlengths
6
1.1M
step-3
stringlengths
15
1.23M
step-4
stringlengths
23
1.34M
step-5
stringlengths
55
1.2M
step-ids
listlengths
1
5
200
1a7e83fe9528b177246d6374ddaf2a76a0046e83
<mask token> def cos_dist(a, b): if len(a) != len(b): return None part_up = 0.0 a_sq = 0.0 b_sq = 0.0 for a1, b1 in zip(a, b): part_up += a1 * b1 a_sq += a1 ** 2 b_sq += b1 ** 2 part_down = math.sqrt(a_sq * b_sq) if part_down == 0.0: return None ...
<mask token> reload(sys) sys.setdefaultencoding('utf-8') <mask token> def cos_dist(a, b): if len(a) != len(b): return None part_up = 0.0 a_sq = 0.0 b_sq = 0.0 for a1, b1 in zip(a, b): part_up += a1 * b1 a_sq += a1 ** 2 b_sq += b1 ** 2 part_down = math.sqrt(a_sq ...
<mask token> reload(sys) sys.setdefaultencoding('utf-8') <mask token> sentence1 = sys.argv[1] sentence2 = sys.argv[2] Divlist1 = jieba.lcut(sentence1, cut_all=True) Divlist2 = jieba.lcut(sentence2, cut_all=True) Sen = [' '.join(Divlist1), ' '.join(Divlist2)] vectorizer = CountVectorizer() transformer = TfidfTransformer...
import jieba import os import sys import math reload(sys) sys.setdefaultencoding('utf-8') from sklearn import feature_extraction from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import CountVectorizer sentence1 = sys.argv[1] sentence2 = sys.argv[2] Divlist1 = jieba.lcut(...
# coding:utf-8 import jieba import os import sys import math reload(sys) sys.setdefaultencoding('utf-8') from sklearn import feature_extraction from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import CountVectorizer #import csv #import pandas #import numpy sente...
[ 1, 2, 3, 4, 5 ]
201
7e7e96fb9377e4dc59a46a46951f5057ecae419a
<mask token>
<mask token> print(np.linalg.norm(mat))
<mask token> a = np.log(2) / 25 apdataX = np.random.random((5, 35)) quarter_way_arr = [False, False, False] quarter_way_arr[0] = True quarter_way_arr[1] = True quarter_way_arr[2] = True mat = np.eye(3) print(np.linalg.norm(mat))
import random import gym import numpy as np from collections import deque from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam from simulation_utils import box, simulation from kinematics import pose3D a = np.log(2) / 25 apdataX = np.random.random((5, 35)) quarter_way_arr...
# -*- coding: utf-8 -*- import random import gym import numpy as np from collections import deque from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam from simulation_utils import box, simulation from kinematics import pose3D a = np.log(2)/25 apdataX = np.random.random(...
[ 0, 1, 2, 3, 4 ]
202
b6183daa943cc63fd2959e3e54fc1e6af5d761de
<mask token>
<mask token> print('valor de D: %.4f' % D) print('valor de Rey: %.4f' % Rey) print('valor de k: %.4f' % k)
<mask token> f = float(input('Digite o valor de f: ')) L = float(input('Digite o valor de L: ')) Q = float(input('Digite o valor de Q: ')) DeltaH = float(input('Digite o valor de DeltaH: ')) v = float(input('Digite o valor de v: ')) g = 9.81 e = 2e-06 D = (8 * f * L * Q * Q / (math.pi * math.pi * g * DeltaH)) ** 0.2 Re...
import math f = float(input('Digite o valor de f: ')) L = float(input('Digite o valor de L: ')) Q = float(input('Digite o valor de Q: ')) DeltaH = float(input('Digite o valor de DeltaH: ')) v = float(input('Digite o valor de v: ')) g = 9.81 e = 2e-06 D = (8 * f * L * Q * Q / (math.pi * math.pi * g * DeltaH)) ** 0.2 Rey...
# -*- coding: utf-8 -*- import math #COMECE SEU CÓDIGO AQUI f = float(input('Digite o valor de f: ')) L = float(input('Digite o valor de L: ')) Q = float(input('Digite o valor de Q: ')) DeltaH = float(input('Digite o valor de DeltaH: ')) v = float(input('Digite o valor de v: ')) g = 9.81 e = 0.000002 #PROCESSAMENTO D =...
[ 0, 1, 2, 3, 4 ]
203
1490fecd6e983c0e3093a45d77d6fb8afdb54718
<mask token> def graph_sketching(args): with open('graphs/graphs_' + args.filename + '.json') as jsonfile: graphs = json.load(jsonfile) print('[ ', len(graphs), ' ] graphs read successfully') sketch = Sketch() sketch_file = sketch.shingle_sketch(graphs, args) print('\n Done Batch Sketching...
<mask token> def graph_sketching(args): with open('graphs/graphs_' + args.filename + '.json') as jsonfile: graphs = json.load(jsonfile) print('[ ', len(graphs), ' ] graphs read successfully') sketch = Sketch() sketch_file = sketch.shingle_sketch(graphs, args) print('\n Done Batch Sketching...
<mask token> def parse_args(): """ Usual pythonic way of parsing command line arguments :return: all command line arguments read """ args = argparse.ArgumentParser('GODIT') args.add_argument('-d', '--sketch_size', default=256, type=int, help= 'Sketch Vector Size') args.add_argument...
import argparse from sketching import Sketch from anomaly_detection import AnomalyDetection from graph_utils import GraphUtils import glob import numpy as np import json from collections import OrderedDict from json import JSONDecoder import pandas as pd import matplotlib.pyplot as plt from sklearn import metrics from ...
# ****************************************************************************** # main.py # # Date Name Description # ======== ========= ======================================================== # 6/5/19 Paudel Initial version, # ***********************************************************************...
[ 1, 2, 6, 9, 10 ]
204
e5d7cc65041d65f915d4882b4fdad5bebf79a067
<mask token> class TokenizerPair(SourceTargetMixin): def __init__(self, tokenizer_class=Tokenizer): self.source = tokenizer_class() self.target = tokenizer_class() @property def is_tokenized(self) ->bool: return hasattr(self.source, 'word_index') and hasattr(self.target, ...
<mask token> class BaseDataset(SourceTargetMixin): <mask token> <mask token> <mask token> class TokenizerPair(SourceTargetMixin): def __init__(self, tokenizer_class=Tokenizer): self.source = tokenizer_class() self.target = tokenizer_class() @property def is_tokenized(self) ...
<mask token> class SourceTargetMixin: <mask token> def __getitem__(self, item): if item in ['source', 'target']: return getattr(self, item) raise TypeError( 'Subscription is available only with "source" and "target" keywords' ) class BaseDataset(SourceTar...
from collections import defaultdict from typing import Union, Iterable, Sized import numpy as np from cached_property import cached_property from keras.utils import to_categorical from keras.preprocessing.sequence import pad_sequences from keras.preprocessing.text import Tokenizer, text_to_word_sequence class SourceT...
from collections import defaultdict from typing import Union, Iterable, Sized import numpy as np from cached_property import cached_property from keras.utils import to_categorical from keras.preprocessing.sequence import pad_sequences from keras.preprocessing.text import Tokenizer, text_to_word_sequence class Source...
[ 18, 19, 24, 26, 27 ]
205
e221553f866de8b3e175197a40982506bf8c1ef9
<mask token> class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.predict = torch.nn.Linear(n_hidden, n_output) def forward(self, x): h1 = F.relu(self.hidden(x)) ...
<mask token> class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.predict = torch.nn.Linear(n_hidden, n_output) def forward(self, x): h1 = F.relu(self.hidden(x)) ...
<mask token> class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.predict = torch.nn.Linear(n_hidden, n_output) def forward(self, x): h1 = F.relu(self.hidden(x)) ...
import torch import torch.nn.functional as F import csv class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.predict = torch.nn.Linear(n_hidden, n_output) def forward(self, x...
import torch import torch.nn.functional as F import csv class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.predict = torch.nn.Linear(n_hidden, n_output) def forward(self, x...
[ 3, 4, 5, 6, 7 ]
206
39dda191ab2137b5f5538660f17e39b0a1358bf4
<mask token>
<mask token> for i in range(nodes): r, g, b = colorsys.hsv_to_rgb(float(i) / nodes, 1.0, 1.0) R, G, B = int(255 * r), int(255 * g), int(255 * b) color = [R, G, B] print(color) img[markers == i + 2] = list(color) <mask token> cv2.putText(img, text, (160, 20), font, 0.5, (0, 0, 0), 1, cv2.LINE_AA) plt...
<mask token> img = cv2.imread('coins.jpg') b, g, r = cv2.split(img) rgb_img = cv2.merge([r, g, b]) gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) grayBlur = cv2.medianBlur(gray, 3) ret, thresh = cv2.threshold(grayBlur, 200, 255, cv2.THRESH_BINARY_INV) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) opening ...
import numpy as np import cv2 import colorsys from matplotlib import pyplot as plt img = cv2.imread('coins.jpg') b, g, r = cv2.split(img) rgb_img = cv2.merge([r, g, b]) gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) grayBlur = cv2.medianBlur(gray, 3) ret, thresh = cv2.threshold(grayBlur, 200, 255, cv2.THRESH_BINARY_INV) ...
import numpy as np import cv2 import colorsys from matplotlib import pyplot as plt img = cv2.imread('coins.jpg') b,g,r = cv2.split(img) rgb_img = cv2.merge([r,g,b]) gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # Blurring image grayBlur = cv2.medianBlur(gray, 3) # Binary threshold ret, thresh = cv2.threshold(grayBl...
[ 0, 1, 2, 3, 4 ]
207
0e6e84a31b626639e2aa149fd1ef89f3ef251cd7
<mask token> class Context(Base): def __init__(self, dataset='', capsys=None): super(Context, self).__init__(capsys=capsys) self.dataset = '' self.dataset = dataset <mask token> def set_dataset(self, dataset): self.dataset = dataset <mask token>
<mask token> class Context(Base): def __init__(self, dataset='', capsys=None): super(Context, self).__init__(capsys=capsys) self.dataset = '' self.dataset = dataset def get_dataset(self): return self.dataset def set_dataset(self, dataset): self.dataset = dataset ...
<mask token> class Context(Base): def __init__(self, dataset='', capsys=None): super(Context, self).__init__(capsys=capsys) self.dataset = '' self.dataset = dataset def get_dataset(self): return self.dataset def set_dataset(self, dataset): self.dataset = dataset ...
from synda.tests.context.models import Context as Base from synda.tests.tests.constants import DATASET_EXAMPLE class Context(Base): def __init__(self, dataset='', capsys=None): super(Context, self).__init__(capsys=capsys) self.dataset = '' self.dataset = dataset def get_dataset(self)...
# -*- coding: utf-8 -*- ################################## # @program synda # @description climate models data transfer program # @copyright Copyright "(c)2009 Centre National de la Recherche Scientifique CNRS. # All Rights Reserved" # @license CeCILL (https://raw.g...
[ 3, 4, 5, 6, 7 ]
208
c0d71d970b2632dbf182a5ee8bad27d3e41578f6
<mask token> def sumInput(text): f = open(text, 'r') sum = 0 count = 1 for line in f: count += 1 line = line.strip() if line[0] == '+': sum += int(line[1:]) else: sum -= int(line[1:]) f.close() return sum <mask token>
<mask token> def sumInput(text): f = open(text, 'r') sum = 0 count = 1 for line in f: count += 1 line = line.strip() if line[0] == '+': sum += int(line[1:]) else: sum -= int(line[1:]) f.close() return sum def main(): print(sumInput(...
<mask token> def sumInput(text): f = open(text, 'r') sum = 0 count = 1 for line in f: count += 1 line = line.strip() if line[0] == '+': sum += int(line[1:]) else: sum -= int(line[1:]) f.close() return sum def main(): print(sumInput(...
import sys def sumInput(text): f = open(text, 'r') sum = 0 count = 1 for line in f: count += 1 line = line.strip() if line[0] == '+': sum += int(line[1:]) else: sum -= int(line[1:]) f.close() return sum def main(): print(sumInput('i...
#!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 import sys def sumInput(text): f = open(text, 'r') sum = 0 count = 1 for line in f: count += 1 line = line.strip() if (line[0] == '+'): sum += int(line[1:]) else: sum -= int(line[1:...
[ 1, 2, 3, 4, 5 ]
209
f14d46bedd5f6e0081a982251ad45e95860ef310
class HashTable: <mask token> <mask token> <mask token> <mask token>
class HashTable: <mask token> def hash(self, chave): return int(chave) <mask token> <mask token>
class HashTable: <mask token> def hash(self, chave): return int(chave) def __put(self, int, chave, valor): self.dados.append({chave: valor}) <mask token>
class HashTable: def __init__(self): self.dados = [] def hash(self, chave): return int(chave) def __put(self, int, chave, valor): self.dados.append({chave: valor}) <mask token>
class HashTable: def __init__(self): self.dados = [] def hash(self, chave): return int(chave) def __put(self, int, chave, valor): self.dados.append({chave: valor}) """ backup = dados dados = novo_array(t * 2) for elemento in backup: hash = hash(elemento.chave) __put(...
[ 1, 2, 3, 4, 5 ]
210
21a41356fcedb36223498db0fe783e4a9e8e1ba6
<mask token>
with open('Book1.txt', 'r') as file1: with open('20k.txt', 'r') as file2: same = set(file1).intersection(file2) same.discard('\n') with open('notin20kforBook1.txt', 'w') as file_out: for line in same: file_out.write(line) with open('Book2.txt', 'r') as file3: with open('20k.txt', 'r') as fil...
# help from https://stackoverflow.com/questions/19007383/compare-two-different-files-line-by-line-in-python with open('Book1.txt', 'r') as file1: with open('20k.txt', 'r') as file2: same = set(file1).intersection(file2) same.discard('\n') with open('notin20kforBook1.txt', 'w') as file_out: for line i...
null
null
[ 0, 1, 2 ]
211
de7b5e44c5c213e4ab70b0f8c0c402edaf4926e0
<mask token>
<mask token> app_name = 'user' urlpatterns = [url('^$', views.index, name='index'), url('login/', views. login, name='login'), url('regist/', views.regist, name='regist'), url( '^getuser\\w*/(?P<id>\\d*)', views.getUserById, name='getuser'), url( '^sendmessage\\w*/(?P<user_telephone>\\d*)', views.sendMessag...
from django.conf.urls import url from . import views app_name = 'user' urlpatterns = [url('^$', views.index, name='index'), url('login/', views. login, name='login'), url('regist/', views.regist, name='regist'), url( '^getuser\\w*/(?P<id>\\d*)', views.getUserById, name='getuser'), url( '^sendmessage\\w*/(?P...
from django.conf.urls import url from .import views app_name='user' # user子路由 urlpatterns = [ # user首页 url(r'^$',views.index,name='index'), # 用户登录 url('login/', views.login, name='login'), # 用户注册 url('regist/', views.regist, name='regist'), # 根据id判断用户是否存在 url(r'^getuser\w*/(?P<id>\...
null
[ 0, 1, 2, 3 ]
212
cc7f1f38efcd4d757c1d11e2bd53695fca44e15a
<mask token>
<mask token> with onto: class Pizza(Thing): pass class MeatPizza(Pizza): pass class Topping(Thing): pass class has_Topping((Pizza >> Topping)): pass print(Pizza) <mask token> print(Pizza.subclasses()) <mask token> print(MeatPizza.is_a) <mask token> print(MeatPizza...
<mask token> onto = get_ontology('http://test1.org/onto.owl') with onto: class Pizza(Thing): pass class MeatPizza(Pizza): pass class Topping(Thing): pass class has_Topping((Pizza >> Topping)): pass print(Pizza) <mask token> print(Pizza.subclasses()) <mask token> p...
<mask token> from owlready2 import * onto = get_ontology('http://test1.org/onto.owl') with onto: class Pizza(Thing): pass class MeatPizza(Pizza): pass class Topping(Thing): pass class has_Topping((Pizza >> Topping)): pass print(Pizza) <mask token> print(Pizza.subc...
'For learning OWL and owlready2' 'From "https://qiita.com/sci-koke/items/a650c09bf77331f5537f"' 'From "https://owlready2.readthedocs.io/en/latest/class.html"' '* Owlready2 * Warning: optimized Cython parser module "owlready2_optimized" is not available, defaulting to slower Python implementation' '↑ This wartning mean...
[ 0, 1, 2, 3, 4 ]
213
a2e2528f560f6117d4ceeb9cd20d3f6f6b2a30a7
<mask token>
def testeum(): a = 10 print(id(a)) <mask token>
def testeum(): a = 10 print(id(a)) def testedois(): a = 10 print(id(a))
# -*- coding: utf-8 -*- def testeum(): a = 10 print(id(a)) def testedois(): a = 10 print(id(a))
null
[ 0, 1, 2, 3 ]
214
e09af436f2fb37d16427aa0b1416d6f2d59ad6c4
<mask token> def append_log(log, message): f = open(log, 'a+') today = datetime.now() f.write('%s %s \n' % (today.strftime('%Y-%m-%d %H:%M:%S'), message)) f.close() def get_root_pass(): with open('/root/.my.cnf') as fp: lines = fp.read().splitlines() for line in lines: grep =...
<mask token> def append_log(log, message): f = open(log, 'a+') today = datetime.now() f.write('%s %s \n' % (today.strftime('%Y-%m-%d %H:%M:%S'), message)) f.close() def get_root_pass(): with open('/root/.my.cnf') as fp: lines = fp.read().splitlines() for line in lines: grep =...
<mask token> def append_log(log, message): f = open(log, 'a+') today = datetime.now() f.write('%s %s \n' % (today.strftime('%Y-%m-%d %H:%M:%S'), message)) f.close() def get_root_pass(): with open('/root/.my.cnf') as fp: lines = fp.read().splitlines() for line in lines: grep =...
<mask token> def append_log(log, message): f = open(log, 'a+') today = datetime.now() f.write('%s %s \n' % (today.strftime('%Y-%m-%d %H:%M:%S'), message)) f.close() def get_root_pass(): with open('/root/.my.cnf') as fp: lines = fp.read().splitlines() for line in lines: grep =...
#!/usr/bin/env python3 import argparse import os import sys,shutil from shutil import make_archive import pathlib from phpManager import execute,execute_outputfile from datetime import date,datetime import re import pymysql import tarfile def append_log(log,message): f = open(log, "a+") today = datetime.now()...
[ 6, 9, 12, 13, 15 ]
215
46adb1834f6013ca0f13a64f280182a805d76278
<mask token>
<mask token> def parse_command_line(argv): """Parse command line argument. See -h option :param argv: arguments on the command line must include caller file name. """ formatter_class = argparse.RawDescriptionHelpFormatter parser = argparse.ArgumentParser(description=module, formatter_class= ...
<mask token> module = sys.modules['__main__'].__file__ __author__ = 'FFX' __version__ = '1.0' log = logging.getLogger(module) def parse_command_line(argv): """Parse command line argument. See -h option :param argv: arguments on the command line must include caller file name. """ formatter_class = argp...
import sys import argparse import logging from pathlib import Path module = sys.modules['__main__'].__file__ __author__ = 'FFX' __version__ = '1.0' log = logging.getLogger(module) def parse_command_line(argv): """Parse command line argument. See -h option :param argv: arguments on the command line must includ...
#!/usr/bin/python3 # encoding: utf-8 import sys import argparse import logging from pathlib import Path module = sys.modules['__main__'].__file__ __author__ = 'FFX' __version__ = '1.0' log = logging.getLogger(module) def parse_command_line(argv): """Parse command line argument. See -h option :param argv: ...
[ 0, 2, 4, 5, 6 ]
216
c63e5a2178e82ec6e0e1e91a81145afb735bf7bf
<mask token> class MyTestCase(unittest.TestCase): def test_1(self): a = t(2) b = t(1) a.left = b self.assertEqual(sr.searchRange(a, 0, 4), [1, 2]) def test_2(self): a = t(20) b = t(1) a.left = b c = t(40) a.right = c d = t(35) ...
<mask token> class MyTestCase(unittest.TestCase): def test_1(self): a = t(2) b = t(1) a.left = b self.assertEqual(sr.searchRange(a, 0, 4), [1, 2]) def test_2(self): a = t(20) b = t(1) a.left = b c = t(40) a.right = c d = t(35) ...
__author__ = 'lei' <mask token> class MyTestCase(unittest.TestCase): def test_1(self): a = t(2) b = t(1) a.left = b self.assertEqual(sr.searchRange(a, 0, 4), [1, 2]) def test_2(self): a = t(20) b = t(1) a.left = b c = t(40) a.right = c ...
__author__ = 'lei' import unittest from ch3.node import TreeNode as t import ch3.searchRange as sr class MyTestCase(unittest.TestCase): def test_1(self): a = t(2) b = t(1) a.left = b self.assertEqual(sr.searchRange(a, 0, 4), [1, 2]) def test_2(self): a = t(20) ...
__author__ = 'lei' import unittest from ch3.node import TreeNode as t import ch3.searchRange as sr class MyTestCase(unittest.TestCase): def test_1(self): a = t(2) b=t(1) a.left = b self.assertEqual(sr.searchRange(a,0,4), [1,2]) def test_2(self): a = t(20) b = ...
[ 3, 4, 5, 6, 7 ]
217
b77da75b01e96ff89f873f4c5764a62cf68cd576
<mask token> class SeriesListSerializer(serializers.ModelSerializer): class Meta: model = Serie fields = 'name', class CatalogCoinListSerializer(serializers.ModelSerializer): class Meta: model = CatalogCoin fields = ('id', 'face_value', 'currency', 'country', 'year', ...
<mask token> class CountriesListSerializer(serializers.ModelSerializer): class Meta: model = Country fields = 'name', 'flag' class SeriesListSerializer(serializers.ModelSerializer): class Meta: model = Serie fields = 'name', class CatalogCoinListSerializer(serializers.M...
<mask token> __all__ = ('CatalogCoinListSerializer', 'CatalogCoinSerializer', 'SeriesListSerializer', 'CoinListSerializer', 'CoinSerializer', 'CountriesListSerializer') class CountriesListSerializer(serializers.ModelSerializer): class Meta: model = Country fields = 'name', 'flag' class...
from rest_framework import serializers from .models import * __all__ = ('CatalogCoinListSerializer', 'CatalogCoinSerializer', 'SeriesListSerializer', 'CoinListSerializer', 'CoinSerializer', 'CountriesListSerializer') class CountriesListSerializer(serializers.ModelSerializer): class Meta: model =...
from rest_framework import serializers from .models import * __all__ = ( 'CatalogCoinListSerializer', 'CatalogCoinSerializer', 'SeriesListSerializer', 'CoinListSerializer', 'CoinSerializer', 'CountriesListSerializer', ) class CountriesListSerializer(serializers.ModelSerializer): class Meta: mode...
[ 7, 8, 9, 10, 11 ]
218
1f0695f0e9745912d8ee3a87e6c9b1272e9ebbae
<mask token>
<mask token> with open(filename, 'a') as handle: handle.write(str(current_time)) handle.write('\n')
<mask token> filename = 'record_time.txt' current_time = time.strftime('%a %H:%M:%S') with open(filename, 'a') as handle: handle.write(str(current_time)) handle.write('\n')
<mask token> import time filename = 'record_time.txt' current_time = time.strftime('%a %H:%M:%S') with open(filename, 'a') as handle: handle.write(str(current_time)) handle.write('\n')
""" Writes day of the week and time to a file. Script written for crontab tutorial. Author: Jessica Yung 2016 """ import time filename = "record_time.txt" # Records time in format Sun 10:00:00 current_time = time.strftime('%a %H:%M:%S') # Append output to file. 'a' is append mode. with open(filename, 'a') as hand...
[ 0, 1, 2, 3, 4 ]
219
142a2ba3ec2f6b35f4339ed9fffe7357c1a85fa0
<mask token> def search(url): browser = webdriver.Chrome(executable_path= 'C:\\Users\\inaee\\Downloads\\chromedriver_win32\\chromedriver.exe') browser.get(url) time.sleep(1) element = browser.find_element_by_tag_name('body') for i in range(30): element.send_keys(Keys.PAGE_DOWN) ...
<mask token> def search(url): browser = webdriver.Chrome(executable_path= 'C:\\Users\\inaee\\Downloads\\chromedriver_win32\\chromedriver.exe') browser.get(url) time.sleep(1) element = browser.find_element_by_tag_name('body') for i in range(30): element.send_keys(Keys.PAGE_DOWN) ...
<mask token> def search(url): browser = webdriver.Chrome(executable_path= 'C:\\Users\\inaee\\Downloads\\chromedriver_win32\\chromedriver.exe') browser.get(url) time.sleep(1) element = browser.find_element_by_tag_name('body') for i in range(30): element.send_keys(Keys.PAGE_DOWN) ...
import requests import time import urllib import argparse from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys from fake_useragent import UserAgent from multiprocessing import Pool from lxml.html import fromstring import os, sys def search(url): browser = we...
import requests import time import urllib import argparse from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys from fake_useragent import UserAgent from multiprocessing import Pool from lxml.html import fromstring import os, sys #text = 'chowchowbaby' #url='https...
[ 1, 2, 3, 4, 5 ]
220
2a19c2d6e51e9c123236c58f82de1a39e5db40f4
import numpy as np # Copyright 2011 University of Bonn # Author: Hannes Schulz def cnan(x): """ check for not-a-number in parameter x """ if np.isnan(x).sum()>0: import pdb pdb.set_trace() def get_curve_3D(eig, alpha=0.25,g23=0.5,g12=0.5): # renumerated according to sato et al: l3 is smallest...
null
null
null
null
[ 0 ]
221
550f5ad4fef77d5795db0393ae0701f679143e72
<mask token>
<mask token> if os.environ.get('MOCKPROGRAM_INOUT_FILE_OVERRIDE'): mockProgramInOutFilePath = os.environ.get('MOCKPROGRAM_INOUT_FILE_OVERRIDE' ) else: mockProgramInOutFilePath = '.mockprogram_inout.txt' if not os.path.exists(mockProgramInOutFilePath): print('Error: ' + mockProgramInOutFilePath + ' i...
<mask token> inputArgs = ' '.join(sys.argv[1:]) if os.environ.get('MOCKPROGRAM_INOUT_FILE_OVERRIDE'): mockProgramInOutFilePath = os.environ.get('MOCKPROGRAM_INOUT_FILE_OVERRIDE' ) else: mockProgramInOutFilePath = '.mockprogram_inout.txt' if not os.path.exists(mockProgramInOutFilePath): print('Error:...
import sys import os inputArgs = ' '.join(sys.argv[1:]) if os.environ.get('MOCKPROGRAM_INOUT_FILE_OVERRIDE'): mockProgramInOutFilePath = os.environ.get('MOCKPROGRAM_INOUT_FILE_OVERRIDE' ) else: mockProgramInOutFilePath = '.mockprogram_inout.txt' if not os.path.exists(mockProgramInOutFilePath): print...
#!/usr/bin/env python # @HEADER # ************************************************************************ # # TriBITS: Tribal Build, Integrate, and Test System # Copyright 2013 Sandia Corporation # # Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, # the U.S. Govern...
[ 0, 1, 2, 3, 4 ]
222
4fa9d16f979acf3edce05a209e1c6636e50fc315
<mask token> class Menu: <mask token> <mask token> <mask token> <mask token>
<mask token> class Menu: <mask token> def get_menu(self, type, openid): try: if type == 'mine': self.sql = ( "SELECT * FROM get_menu WHERE openid='%s' order by watch DESC " % openid) self.resql = self.mysqlClass.sele...
<mask token> class Menu: def __init__(self): self.mysqlClass = Mysql.MySQL() self.timeClass = Utils.Time() def get_menu(self, type, openid): try: if type == 'mine': self.sql = ( "SELECT * FROM get_menu WHERE openid='%s' order by watch D...
from jox_api import label_image, Mysql, Utils from jox_config import api_base_url import json class Menu: def __init__(self): self.mysqlClass = Mysql.MySQL() self.timeClass = Utils.Time() def get_menu(self, type, openid): try: if type == 'mine': self.sql =...
from jox_api import label_image,Mysql,Utils from jox_config import api_base_url import json class Menu(): def __init__(self): self.mysqlClass = Mysql.MySQL() self.timeClass = Utils.Time() def get_menu(self,type,openid): try: if type == 'mine': self.sql = "SEL...
[ 1, 3, 5, 6, 7 ]
223
e5e012e40a71dee9f4dbd9913590aef125b758df
<mask token> class Visualiser: <mask token> <mask token> <mask token> def __build_map(self): """ Creates the array of the battlefield. Should never be used for logical operations :return: """ columns = [] for i in range(self.__dimensions): c...
<mask token> class Visualiser: <mask token> <mask token> def __init__(self): self.map = [] self.__build_map() def __build_map(self): """ Creates the array of the battlefield. Should never be used for logical operations :return: """ columns = []...
<mask token> class Visualiser: coordinate_map = 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' __dimensions = 8 def __init__(self): self.map = [] self.__build_map() def __build_map(self): """ Creates the array of the battlefield. Should never be used for logical operations ...
from classes.Board import Board class Visualiser: coordinate_map = 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' __dimensions = 8 def __init__(self): self.map = [] self.__build_map() def __build_map(self): """ Creates the array of the battlefield. Should never be used for lo...
from classes.Board import Board class Visualiser: coordinate_map = ("a", "b", "c", "d", "e", "f", "g", "h") __dimensions = 8 def __init__(self): self.map = [] self.__build_map() def __build_map(self): """ Creates the array of the battlefield. Should never be used for ...
[ 4, 5, 6, 7, 8 ]
224
c4e4e54ac93c2acdbd3a1cd22b200341a6e45688
import pyaudio import numpy as np from collections import OrderedDict import utils class MasterPlayer(object): def __init__(self, volume=1., samplesPerSecond=44100): self.p = pyaudio.PyAudio() self.volume = volume self.samplesPerSecond = samplesPerSecond self.individual_callbacks =...
null
null
null
null
[ 0 ]
225
27e9e63338d422b5fca6f7a67fa3d255602a3358
<mask token> class V_test_abstract(V): def __init__(self): super(V_test_abstract, self).__init__() <mask token> def forward(self): z = self.beta[:self.dim] r1_local = self.beta[self.dim:2 * self.dim] r2_local = self.beta[2 * self.dim:3 * self.dim] r1_local_plus = ...
<mask token> class V_test_abstract(V): def __init__(self): super(V_test_abstract, self).__init__() def V_setup(self, y, X, nu): self.explicit_gradient = False self.need_higherorderderiv = True self.dim = X.shape[1] self.beta = nn.Parameter(torch.zeros(self.dim * 5 + 4...
<mask token> class V_test_abstract(V): def __init__(self): super(V_test_abstract, self).__init__() def V_setup(self, y, X, nu): self.explicit_gradient = False self.need_higherorderderiv = True self.dim = X.shape[1] self.beta = nn.Parameter(torch.zeros(self.dim * 5 + 4...
from abstract_class_V import V import torch import torch.nn as nn class V_test_abstract(V): def __init__(self): super(V_test_abstract, self).__init__() def V_setup(self, y, X, nu): self.explicit_gradient = False self.need_higherorderderiv = True self.dim = X.shape[1] ...
from abstract_class_V import V import torch import torch.nn as nn class V_test_abstract(V): def __init__(self): super(V_test_abstract, self).__init__() def V_setup(self,y,X,nu): self.explicit_gradient = False self.need_higherorderderiv = True self.dim = X.shape[1] self...
[ 3, 4, 5, 6, 7 ]
226
ec4348c61cd1c9130543bb20f9ca199399e1caff
class Solution(object): def restoreIpAddresses(self, s): """ :type s: str :rtype: List[str] """ def helper(sb, string, level): if len(string) == 0: if level == 4: ans.append(sb[:-1]) return if level ...
null
null
null
null
[ 0 ]
227
d0a3f332e04627eb275168972bd92cd1ea9b9447
<mask token> class TestTTT(unittest.TestCase): def test_mcts(self): if 0 in skip: print('Skipping ai self-play') return ttt = TTT() for i in range(1000): mcts = MCTS(ttt) state = mcts.root.state while not mcts.board.ending_state(...
<mask token> class TestTTT(unittest.TestCase): def test_mcts(self): if 0 in skip: print('Skipping ai self-play') return ttt = TTT() for i in range(1000): mcts = MCTS(ttt) state = mcts.root.state while not mcts.board.ending_state(...
<mask token> skip = [0] class TestTTT(unittest.TestCase): def test_mcts(self): if 0 in skip: print('Skipping ai self-play') return ttt = TTT() for i in range(1000): mcts = MCTS(ttt) state = mcts.root.state while not mcts.board.en...
from board.ttt import TTT from mctsai.mcts import MCTS import unittest skip = [0] class TestTTT(unittest.TestCase): def test_mcts(self): if 0 in skip: print('Skipping ai self-play') return ttt = TTT() for i in range(1000): mcts = MCTS(ttt) s...
from board.ttt import TTT from mctsai.mcts import MCTS import unittest # skip = [0, 1] skip = [0] class TestTTT(unittest.TestCase): def test_mcts(self): if 0 in skip: print("Skipping ai self-play") return ttt = TTT() for i in range(1000): mcts = MCTS(tt...
[ 6, 7, 8, 9, 10 ]
228
e95bda8be2294c295d89f1c035bc209128fa29c8
def merge_the_tools(string, k): # your code goes here num_sub_strings = len(string)/k #print num_sub_strings for idx in range(num_sub_strings): print "".join(set(list(string[idx * k : (idx + 1) * k])))
null
null
null
null
[ 0 ]
229
f85a703b47d981397ed6048e941030a3fbee7b6d
<mask token>
<mask token> class Migration(migrations.Migration): <mask token> <mask token>
<mask token> class Migration(migrations.Migration): dependencies = [('talk', '0023_auto_20180207_1121')] operations = [migrations.AddField(model_name='talkmedia', name= 'codelink', field=models.CharField(blank=True, max_length=255, verbose_name='Source code'))]
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('talk', '0023_auto_20180207_1121')] operations = [migrations.AddField(model_name='talkmedia', name= 'codelink', field=models.CharField(blank=True, max_length=255, ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2018-04-27 08:05 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('talk', '0023_auto_20180207_1121'), ] operations = [ migrations.AddField( ...
[ 0, 1, 2, 3, 4 ]
230
23375760c0943ca177b7009031d9d17a91165c5c
#!/usr/bin/env python #--coding: utf8-- import time if __name__ == '__main__': date = time.strftime('%m-%d') if date == '03-08': print '女神节' elif date == '02-14': print '情人节' else: print '发红包' print '这是一个测试题'
null
null
null
null
[ 0 ]
231
f8d815bcdc74452b66a1b3b33bf0fbe976e728c8
<mask token> def dataX(features, set): data_x = np.array([]) count = 0 for filepath in glob.iglob(set): globpath = filepath + '\\*.jpg' for filepath in glob.iglob('' + globpath): count = count + 1 img = Image.open(filepath).convert('L') data = list(img.g...
<mask token> def next_batch(num, data, labels): """ Return a total of `num` random samples and labels. """ idx = np.arange(0, len(data)) np.random.shuffle(idx) idx = idx[:num] data_shuffle = [data[i] for i in idx] labels_shuffle = [labels[i] for i in idx] return np.asarray(data_shu...
<mask token> def next_batch(num, data, labels): """ Return a total of `num` random samples and labels. """ idx = np.arange(0, len(data)) np.random.shuffle(idx) idx = idx[:num] data_shuffle = [data[i] for i in idx] labels_shuffle = [labels[i] for i in idx] return np.asarray(data_shu...
import tensorflow as tf from tensorflow.keras import datasets, layers, models import matplotlib.pyplot as plt import numpy as np from PIL import Image import glob def next_batch(num, data, labels): """ Return a total of `num` random samples and labels. """ idx = np.arange(0, len(data)) np.random.s...
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. import tensorflow as tf from tensorflow.keras import datasets, layers, models import matplotlib.pyplot as plt import numpy ...
[ 1, 4, 5, 6, 7 ]
232
ef85f94282bfd7c9491c4e28bab61aaab5c792a5
<mask token> class Ui_Tab(object): <mask token> <mask token>
<mask token> class Ui_Tab(object): <mask token> def retranslateUi(self, Tab): _translate = QtCore.QCoreApplication.translate Tab.setWindowTitle(_translate('Tab', 'Form')) self.btn_enterPassword.setText(_translate('Tab', 'Enter Password'))
<mask token> class Ui_Tab(object): def setupUi(self, Tab): Tab.setObjectName('Tab') Tab.resize(762, 523) self.verticalLayout = QtWidgets.QVBoxLayout(Tab) self.verticalLayout.setObjectName('verticalLayout') self.hLayout = QtWidgets.QHBoxLayout() self.hLayout.setObje...
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Tab(object): def setupUi(self, Tab): Tab.setObjectName('Tab') Tab.resize(762, 523) self.verticalLayout = QtWidgets.QVBoxLayout(Tab) self.verticalLayout.setObjectName('verticalLayout') self.hLayout = QtWidgets.QHBoxLayout(...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'src/ui_LibraryTab.ui' # # Created: Tue Jun 9 21:46:41 2015 # by: PyQt5 UI code generator 5.4 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Tab(object): def setupUi(se...
[ 1, 2, 3, 4, 5 ]
233
8c8bbbc682889c8d79c893f27def76ad70e8bf8d
<mask token>
DATABASE_NAME = 'user_db'
DATABASE_NAME = "user_db"
null
null
[ 0, 1, 2 ]
234
9d904225afd4f4d0cf338ae16f031f8ab41639ad
<mask token> class FragmentMakoChain(Fragment): <mask token> <mask token> <mask token> <mask token> <mask token> def __init__(self, content=None, base=None, lookup_dirs=None): """ Класс, позволяющий последовательно оборачивать экземпляры Fragment друг в друга. ...
<mask token> class FragmentMakoChain(Fragment): <mask token> <mask token> <mask token> <mask token> <mask token> def __init__(self, content=None, base=None, lookup_dirs=None): """ Класс, позволяющий последовательно оборачивать экземпляры Fragment друг в друга. ...
<mask token> class FragmentMakoChain(Fragment): """ Класс, позволяющий последовательно оборачивать экземпляры Fragment друг в друга. Для того, чтобы цепочка отработала, шаблон должен наследоваться от шаблона ifmo_xblock_base и определять блок block_body. Порядок оборачивания не определён. ...
from mako.template import Template from xblock.fragment import Fragment from .lookup import TemplateLookup from .utils import deep_update class FragmentMakoChain(Fragment): """ Класс, позволяющий последовательно оборачивать экземпляры Fragment друг в друга. Для того, чтобы цепочка отработала, шаблон ...
# -*- coding=utf-8 -*- from mako.template import Template from xblock.fragment import Fragment from .lookup import TemplateLookup # xblock_ifmo.lookup from .utils import deep_update class FragmentMakoChain(Fragment): """ Класс, позволяющий последовательно оборачивать экземпляры Fragment друг в друга. ...
[ 6, 7, 10, 11, 12 ]
235
8cc0393082448bb8f61068b5c96e89ef3aee77ed
<mask token> class LdapSync(Thread): def __init__(self, settings): Thread.__init__(self) self.settings = settings def run(self): if self.settings.enable_group_sync: migrate_dn_pairs(settings=self.settings) self.start_sync() self.show_sync_result() <mas...
<mask token> class LdapSync(Thread): def __init__(self, settings): Thread.__init__(self) self.settings = settings def run(self): if self.settings.enable_group_sync: migrate_dn_pairs(settings=self.settings) self.start_sync() self.show_sync_result() <mas...
<mask token> class LdapSync(Thread): def __init__(self, settings): Thread.__init__(self) self.settings = settings def run(self): if self.settings.enable_group_sync: migrate_dn_pairs(settings=self.settings) self.start_sync() self.show_sync_result() def...
<mask token> def migrate_dn_pairs(settings): grp_dn_pairs = get_group_dn_pairs() if grp_dn_pairs is None: logger.warning( 'get group dn pairs from db failed when migrate dn pairs.') return grp_dn_pairs.reverse() for grp_dn_pair in grp_dn_pairs: for config in setting...
#coding: utf-8 import logging from threading import Thread from ldap import SCOPE_BASE from seafevents.ldap_syncer.ldap_conn import LdapConn from seafevents.ldap_syncer.utils import bytes2str, add_group_uuid_pair from seaserv import get_group_dn_pairs logger = logging.getLogger(__name__) def migrate_dn_pairs(set...
[ 7, 8, 9, 10, 13 ]
236
21af630bf383ee1bdd0f644283f0ddadde71620a
#!/bin/usr/python2.7.x import os, re, urllib2 def main(): ip = raw_input(" Target IP : ") check(ip) def check(ip): try: print "Loading Check File Uploader...." print 58*"-" page = 1 while page <= 21: bing = "http://www.bing.com/search?q=ip%3A" + \ ip + "+upload&count=50&first=" + str(...
null
null
null
null
[ 0 ]
237
eb853e430b996a81dc2ef20c320979a3e04d956a
<mask token> class Beautyleg7Spider(scrapy.Spider): <mask token> <mask token> <mask token> <mask token> <mask token> def start_requests(self): mysql_host = self.crawler.settings.get('MYSQL_HOST') mysql_port = self.crawler.settings.get('MYSQL_PORT') mysql_user = self.cr...
<mask token> class Beautyleg7Spider(scrapy.Spider): <mask token> <mask token> <mask token> <mask token> <mask token> def start_requests(self): mysql_host = self.crawler.settings.get('MYSQL_HOST') mysql_port = self.crawler.settings.get('MYSQL_PORT') mysql_user = self.cr...
<mask token> class Beautyleg7Spider(scrapy.Spider): name = 'Beautyleg7Spider' category_list = ['siwameitui', 'xingganmeinv', 'weimeixiezhen', 'ribenmeinv'] start_urls = [('http://www.beautyleg7.com/' + category) for category in category_list] const.REPEATED_THRESHOLD = 10 def __in...
import hashlib import re from datetime import datetime import gevent import requests import scrapy from gevent.pool import Pool from lxml import etree from scrapy.http import HtmlResponse from sqlalchemy import create_engine, func from sqlalchemy.orm import sessionmaker from ..items import Album, AlbumImageRelationItem...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- import hashlib import re from datetime import datetime import gevent import requests import scrapy from gevent.pool import Pool from lxml import etree from scrapy.http import HtmlResponse from sqlalchemy import create_engine, func from sqlalchemy.orm import sessionmaker ...
[ 7, 8, 11, 12, 13 ]
238
bc4684d255a46427f708d8ce8bda2e12fb8c8ffe
<mask token> def main(): r4m = Route4Me(API_KEY) route = r4m.route response = route.get_routes(limit=1, offset=0) if isinstance(response, dict) and 'errors' in response.keys(): print('. '.join(response['errors'])) else: route_id = response[0]['route_id'] print('Route ID: {}...
<mask token> def main(): r4m = Route4Me(API_KEY) route = r4m.route response = route.get_routes(limit=1, offset=0) if isinstance(response, dict) and 'errors' in response.keys(): print('. '.join(response['errors'])) else: route_id = response[0]['route_id'] print('Route ID: {}...
<mask token> API_KEY = '11111111111111111111111111111111' def main(): r4m = Route4Me(API_KEY) route = r4m.route response = route.get_routes(limit=1, offset=0) if isinstance(response, dict) and 'errors' in response.keys(): print('. '.join(response['errors'])) else: route_id = respon...
from route4me import Route4Me API_KEY = '11111111111111111111111111111111' def main(): r4m = Route4Me(API_KEY) route = r4m.route response = route.get_routes(limit=1, offset=0) if isinstance(response, dict) and 'errors' in response.keys(): print('. '.join(response['errors'])) else: ...
# -*- coding: utf-8 -*- from route4me import Route4Me API_KEY = "11111111111111111111111111111111" def main(): r4m = Route4Me(API_KEY) route = r4m.route response = route.get_routes(limit=1, offset=0) if isinstance(response, dict) and 'errors' in response.keys(): print('. '.join(response['err...
[ 1, 2, 3, 4, 5 ]
239
d015a1b27a3a9e7f5e6614da752137064000b905
<mask token> class my_model: <mask token> def make_model(self, param): """makes the model""" self.lr = param[0][0] dr = param[0][1] layer_units0 = param[0][2] layer_units1 = param[0][3] layer_units2 = param[0][4] def learning_rate(epoch): "...
<mask token> class my_model: """A model bassed on xception""" def make_model(self, param): """makes the model""" self.lr = param[0][0] dr = param[0][1] layer_units0 = param[0][2] layer_units1 = param[0][3] layer_units2 = param[0][4] def learning_rate(e...
<mask token> class my_model: """A model bassed on xception""" def make_model(self, param): """makes the model""" self.lr = param[0][0] dr = param[0][1] layer_units0 = param[0][2] layer_units1 = param[0][3] layer_units2 = param[0][4] def learning_rate(e...
<mask token> import tensorflow.keras as K from GPyOpt.methods import BayesianOptimization import pickle import os import numpy as np class my_model: """A model bassed on xception""" def make_model(self, param): """makes the model""" self.lr = param[0][0] dr = param[0][1] layer...
#!/usr/bin/env python3 """Transfer learning with xception""" import tensorflow.keras as K from GPyOpt.methods import BayesianOptimization import pickle import os import numpy as np class my_model(): """A model bassed on xception""" def make_model(self, param): """makes the model""" self.lr = ...
[ 3, 4, 5, 6, 7 ]
240
ef6f55bf27982f53441215da6822cfcdc80706a5
<mask token> def display_meta(request): context_dict = {'meta_dict': request.META} return render_to_response('display_meta.html', context_dict)
<mask token> def current_datetime(request): current_date = datetime.datetime.now() locals_prams = {'locals': locals()} return render_to_response('current_datetime.html', locals_prams) def display_meta(request): context_dict = {'meta_dict': request.META} return render_to_response('display_meta.ht...
__author__ = 'Yun' __project__ = 'DjangoBookTest2' <mask token> def current_datetime(request): current_date = datetime.datetime.now() locals_prams = {'locals': locals()} return render_to_response('current_datetime.html', locals_prams) def display_meta(request): context_dict = {'meta_dict': request.M...
__author__ = 'Yun' __project__ = 'DjangoBookTest2' from django.shortcuts import render_to_response import datetime def current_datetime(request): current_date = datetime.datetime.now() locals_prams = {'locals': locals()} return render_to_response('current_datetime.html', locals_prams) def display_meta(r...
# -*- coding: utf-8 -*- __author__ = 'Yun' __project__ = 'DjangoBookTest2' # from django.template import Template, Context # from django.template.loader import get_template # from django.http import HttpResponse from django.shortcuts import render_to_response import datetime def current_datetime(request): # now ...
[ 1, 2, 3, 4, 5 ]
241
e8226ab6be5c21335d843cba720e66646a2dee4e
import os import requests import sqlite3 from models import analytics, jcanalytics def populate(): url = 'https://api.clicky.com/api/stats/4?site_id=100716069&sitekey=93c104e29de28bd9&type=visitors-list' date = '&date=last-30-days' limit = '&limit=all' output = '&output=json' total = url+date+limi...
null
null
null
null
[ 0 ]
242
e616d14827beaa08ab08219421cbf7990cf163fd
<mask token> class AlipayInsSceneEcommerceInsureCheckModel(object): def __init__(self): self._insure_admit_dto_list = None self._partner_org_id = None self._product_code = None self._scene_code = None self._user_client = None @property def insure_admit_dto_list(se...
<mask token> class AlipayInsSceneEcommerceInsureCheckModel(object): def __init__(self): self._insure_admit_dto_list = None self._partner_org_id = None self._product_code = None self._scene_code = None self._user_client = None @property def insure_admit_dto_list(se...
<mask token> class AlipayInsSceneEcommerceInsureCheckModel(object): def __init__(self): self._insure_admit_dto_list = None self._partner_org_id = None self._product_code = None self._scene_code = None self._user_client = None @property def insure_admit_dto_list(se...
<mask token> class AlipayInsSceneEcommerceInsureCheckModel(object): def __init__(self): self._insure_admit_dto_list = None self._partner_org_id = None self._product_code = None self._scene_code = None self._user_client = None @property def insure_admit_dto_list(se...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.InsureAdmitDTO import InsureAdmitDTO class AlipayInsSceneEcommerceInsureCheckModel(object): def __init__(self): self._insure_admit_dto_list = None self._partn...
[ 8, 12, 13, 14, 16 ]
243
c4ca4b5c77c3c912b44a4853be30298ec845c4fd
<mask token>
<mask token> print(owog.find('e')) print(owog.count('e')) print(owog[2:10]) <mask token> if a > b: print('a too ih') elif a == b: print('tentsuu') else: print('b too ih') <mask token> for i in range(a, b + 1): print(i)
owog = 'Delger' print(owog.find('e')) print(owog.count('e')) print(owog[2:10]) a = 21 b = 21 if a > b: print('a too ih') elif a == b: print('tentsuu') else: print('b too ih') a, b = input().split() for i in range(a, b + 1): print(i)
#str owog="Delger" # len()- urt # lower()- jijigruuleh # upper()- tomruulah # capitalize()- ehnii useg tomruulah # replace()- temdegt solih print(owog.find("e")) print(owog.count("e")) print(owog[2:10]) a=21 b=21 if a>b: print("a too ih") elif a==b: print("tentsuu") else: print("b to...
null
[ 0, 1, 2, 3 ]
244
050e2207ac7331444d39305869c4b25bcbc53907
<mask token>
<mask token> print( 'Note: total_earnings values were scaled by multiplying by {:.10f} and adding {:.6f}' .format(scaler.scale_[8], scaler.min_[8])) <mask token> scaled_training_df.to_csv('sales_data_training_scaled.csv', index=False) scaled_training_df.to_csv('sales_data_test_scaled.csv', index=False)
<mask token> training_data_df = pd.read_csv('sales_data_training.csv') test_data_df = pd.read_csv('sales_data_test.csv') scaler = MinMaxScaler(feature_range=(0, 1)) scaled_training = scaler.fit_transform(training_data_df) scaled_testing = scaler.transform(test_data_df) print( 'Note: total_earnings values were scale...
import pandas as pd from sklearn.preprocessing import MinMaxScaler training_data_df = pd.read_csv('sales_data_training.csv') test_data_df = pd.read_csv('sales_data_test.csv') scaler = MinMaxScaler(feature_range=(0, 1)) scaled_training = scaler.fit_transform(training_data_df) scaled_testing = scaler.transform(test_data_...
import pandas as pd from sklearn.preprocessing import MinMaxScaler #loading data from CSV training_data_df = pd.read_csv("sales_data_training.csv") test_data_df = pd.read_csv("sales_data_test.csv") #scaler scaler = MinMaxScaler(feature_range=(0,1)) #scale both inputs and outputs scaled_training = scaler.fit_transfor...
[ 0, 1, 2, 3, 4 ]
245
df64d769ffba8cddac34282a526122e3c941249d
#!/usr/bin/env python import os import tempfile import shutil import math import sys import subprocess from irank.config import IrankOptionParser, IrankApp from irank import db as irank_db STATUS = 0 def main(): p = IrankOptionParser('%prog -d DEST playlist_name [playlist_name ...]') p.add_option('-d', '--dest', he...
null
null
null
null
[ 0 ]
246
21b295e28a7e4443ea116df1b22ff5074dca955a
<mask token>
<mask token> for i in range(1, n + 1): print(i)
n = int(input('nhap gia tri')) for i in range(1, n + 1): print(i)
n =int(input("nhap gia tri")) for i in range(1,n+1): print(i)
null
[ 0, 1, 2, 3 ]
247
93737e4c409d0efb1ae2263cb60d4b03d9aad0d8
<mask token>
<mask token> ap.add_argument('-D', '--dir', required=False, help='Directory to sort') <mask token> if args['dir'] == None: DIR = os.getcwd() elif os.path.exists(args['dir']): DIR = args['dir'] for file in os.listdir(DIR): if not os.path.isdir(os.path.join(DIR, file)): name, ext = os.path.splitext(fi...
<mask token> ap = argparse.ArgumentParser() ap.add_argument('-D', '--dir', required=False, help='Directory to sort') args = vars(ap.parse_args()) if args['dir'] == None: DIR = os.getcwd() elif os.path.exists(args['dir']): DIR = args['dir'] for file in os.listdir(DIR): if not os.path.isdir(os.path.join(DIR, ...
import os import shutil import argparse ap = argparse.ArgumentParser() ap.add_argument('-D', '--dir', required=False, help='Directory to sort') args = vars(ap.parse_args()) if args['dir'] == None: DIR = os.getcwd() elif os.path.exists(args['dir']): DIR = args['dir'] for file in os.listdir(DIR): if not os.pa...
import os import shutil import argparse ap = argparse.ArgumentParser() ap.add_argument('-D','--dir', required=False, help='Directory to sort') args = vars(ap.parse_args()) if args['dir'] == None: DIR = os.getcwd() elif os.path.exists(args['dir']): DIR = args['dir'] for file in os.listdir(DIR): if not os....
[ 0, 1, 2, 3, 4 ]
248
b5611c668a40e1735c92d6d00867885023ad713f
<mask token> def f(A): if len(A) == 1: return 0 else: rightStart = len(A) // 2 leftArray = A[0:rightStart] righArray = A[rightStart:] B, b = count_and_sort(leftArray) C, c = count_and_sort(righArray) D, d = count_and_sort_split(B, C) return b + c...
<mask token> def f(A): if len(A) == 1: return 0 else: rightStart = len(A) // 2 leftArray = A[0:rightStart] righArray = A[rightStart:] B, b = count_and_sort(leftArray) C, c = count_and_sort(righArray) D, d = count_and_sort_split(B, C) return b + c...
<mask token> with open('IntegerArray.txt', 'r') as f: target = f.readlines() for x in range(len(target)): target[x] = int(target[x]) def f(A): if len(A) == 1: return 0 else: rightStart = len(A) // 2 leftArray = A[0:rightStart] righArray = A[rightStart:] B, b = c...
target = [] with open('IntegerArray.txt', 'r') as f: target = f.readlines() for x in range(len(target)): target[x] = int(target[x]) def f(A): if len(A) == 1: return 0 else: rightStart = len(A) // 2 leftArray = A[0:rightStart] righArray = A[rightStart:] B, b = co...
target=[] with open('IntegerArray.txt','r') as f: target=f.readlines() for x in range(len(target)): target[x]=int(target[x]) def f(A): if len(A)==1: return 0 else: rightStart=len(A)//2 leftArray=A[0:rightStart] righArray=A[rightStart:] B,b=count_and_sort(leftArray) C,c=count_and_sort(righA...
[ 2, 3, 4, 5, 6 ]
249
09f032301fa9389f6b07687e0ee13844e0b4ddf3
from artichoke import DefaultManager, Config from artichoke.helpers import read, prompt from fabric.api import env, task, run import os chars = ''.join(chr(c) if chr(c).isupper() or chr(c).islower() else '_' for c in range(256)) class MagicDefaultManager(DefaultManager): def __init__(self, env): self.en...
null
null
null
null
[ 0 ]
250
68b967ecf18d576758cf05e889919944cfc34dcd
<mask token> class Entity(Agent): <mask token> def __init__(self, unique_id, model): super().__init__(unique_id, model) self.type = '' self.position = '' self.log = [] self.move_probability = None self.retire_probability = None self._next_state = None ...
<mask token> class Entity(Agent): <mask token> def __init__(self, unique_id, model): super().__init__(unique_id, model) self.type = '' self.position = '' self.log = [] self.move_probability = None self.retire_probability = None self._next_state = None ...
<mask token> class Entity(Agent): """ superclass for vacancy and actor agents not intended to be used on its own, but to inherit its methods to multiple other agents """ def __init__(self, unique_id, model): super().__init__(unique_id, model) self.type = '' self.position =...
<mask token> from mesa import Agent from random import shuffle import numpy as np class Entity(Agent): """ superclass for vacancy and actor agents not intended to be used on its own, but to inherit its methods to multiple other agents """ def __init__(self, unique_id, model): super().__in...
""" generalised behaviour for actors and vacancies """ from mesa import Agent from random import shuffle import numpy as np class Entity(Agent): """ superclass for vacancy and actor agents not intended to be used on its own, but to inherit its methods to multiple other agents """ def __init__(sel...
[ 6, 7, 8, 9, 10 ]
251
46babde9c26a944c9d29121b6bbf89a32f242a81
<mask token>
<mask token> def sun_prepare(xpoint, ypoint, radius, color, angle): delta_list = [] radius_list = [] for delta in range(0, 360, angle): delta_list.append(delta) radius_list.append(random.randint(radius - 10, radius + 10)) return xpoint, ypoint, color, radius, delta_list, radius_list ...
<mask token> def sun_prepare(xpoint, ypoint, radius, color, angle): delta_list = [] radius_list = [] for delta in range(0, 360, angle): delta_list.append(delta) radius_list.append(random.randint(radius - 10, radius + 10)) return xpoint, ypoint, color, radius, delta_list, radius_list ...
import simple_draw as sd import random def sun_prepare(xpoint, ypoint, radius, color, angle): delta_list = [] radius_list = [] for delta in range(0, 360, angle): delta_list.append(delta) radius_list.append(random.randint(radius - 10, radius + 10)) return xpoint, ypoint, color, radius, ...
import simple_draw as sd import random # sd.resolution = (1400, 900) # Prepare data for the sun function def sun_prepare(xpoint, ypoint, radius, color, angle): delta_list = [] radius_list = [] for delta in range(0, 360, angle): delta_list.append(delta) radius_list.append(random.randint(ra...
[ 0, 1, 2, 3, 4 ]
252
e736991f364ba9ff709348e4b1f612b1e9673281
<mask token>
<mask token> app = Flask(__name__) <mask token>
from flask import * app = Flask(__name__) from app import views from app import admin_views from app import usr_reg from app import cookie from app import db_connect
from flask import * app=Flask(__name__) from app import views from app import admin_views from app import usr_reg from app import cookie from app import db_connect
null
[ 0, 1, 2, 3 ]
253
07215403750be53994ae36727b6f790202b88697
# Inspiration: [Fake Album Covers](https://fakealbumcovers.com/) from IPython.display import Image as IPythonImage from PIL import Image from PIL import ImageFont from PIL import ImageDraw import requests from xml.etree import ElementTree as ET def display_cover(top,bottom ): name='album_art_raw.png' alb...
null
null
null
null
[ 0 ]
254
18d3f58048b7e5d792eb2494ecc62bb158ac7407
<mask token> @app.route('/') def hello_world(): return render_template('index.html') @app.route('/on/') def on(): state = powerswitch.on() return json.dumps(state) @app.route('/off/') def off(): state = powerswitch.off() return json.dumps(state) @app.route('/toggle/') def toggle(): state...
<mask token> @app.route('/') def hello_world(): return render_template('index.html') @app.route('/on/') def on(): state = powerswitch.on() return json.dumps(state) @app.route('/off/') def off(): state = powerswitch.off() return json.dumps(state) @app.route('/toggle/') def toggle(): state...
<mask token> app = Flask(__name__) @app.route('/') def hello_world(): return render_template('index.html') @app.route('/on/') def on(): state = powerswitch.on() return json.dumps(state) @app.route('/off/') def off(): state = powerswitch.off() return json.dumps(state) @app.route('/toggle/') d...
from flask import Flask from flask import render_template from flask import make_response import json from lib import powerswitch app = Flask(__name__) @app.route('/') def hello_world(): return render_template('index.html') @app.route('/on/') def on(): state = powerswitch.on() return json.dumps(state) ...
from flask import Flask from flask import render_template from flask import make_response import json from lib import powerswitch app = Flask(__name__) @app.route('/') def hello_world(): return render_template('index.html') @app.route('/on/') def on(): state = powerswitch.on() return json.dumps(state) ...
[ 5, 6, 7, 8, 9 ]
255
869284fa531a93c1b9812ed90a560d0bb2f87e97
<mask token>
<mask token> def fibonaci(n): for i in range(0, n): j = 1 i = i + j j = i return fibonaci
def ep(m, h, el, g=9.8): E = m * h * g if E < el: print('le plus grand est : el') else: print('le plus grand est : E') <mask token> def fibonaci(n): for i in range(0, n): j = 1 i = i + j j = i return fibonaci
def ep(m, h, el, g=9.8): E = m * h * g if E < el: print('le plus grand est : el') else: print('le plus grand est : E') ep(3, 4, 5) def fibonaci(n): for i in range(0, n): j = 1 i = i + j j = i return fibonaci
# fonction pour voir quel est le plus grand entre l'energie limite et l'enerve potentiel def ep (m,h,el,g=9.8): E=m*h*g if E<el: print ("le plus grand est : el") else: print ("le plus grand est : E") ep(3,4,5) #fontion fibonaci 0 1 1 2 3 5 8 13 def fibonaci(n): for i in range(0,n,): ...
[ 0, 1, 2, 3, 4 ]
256
d126efa91b964a3a374d546bb860b39ae26dfa22
<mask token> class TestGetNumber(unittest.TestCase): <mask token> def test_fib(self): self.assertEqual(Fib(5), 8) <mask token>
<mask token> class TestGetNumber(unittest.TestCase): def test_ok(self): self.assertEqual(GetNumber(), 42) def test_fib(self): self.assertEqual(Fib(5), 8) <mask token>
<mask token> class TestGetNumber(unittest.TestCase): def test_ok(self): self.assertEqual(GetNumber(), 42) def test_fib(self): self.assertEqual(Fib(5), 8) if __name__ == '__main__': unittest.main()
<mask token> import unittest from bazel_tutorial.examples.py.lib import GetNumber from bazel_tutorial.examples.py.fibonacci.fib import Fib class TestGetNumber(unittest.TestCase): def test_ok(self): self.assertEqual(GetNumber(), 42) def test_fib(self): self.assertEqual(Fib(5), 8) if __name_...
"""A tiny example binary for the native Python rules of Bazel.""" import unittest from bazel_tutorial.examples.py.lib import GetNumber from bazel_tutorial.examples.py.fibonacci.fib import Fib class TestGetNumber(unittest.TestCase): def test_ok(self): self.assertEqual(GetNumber(), 42) def test_fib(self): ...
[ 2, 3, 4, 5, 6 ]
257
e582787a912f479830ed99575b2c6adb8088b4e5
<mask token> @app.route('/search_general', methods=['POST']) def query(): message = None searchQuery = request.json['searchQuery'] result = qp.generateQuery(searchQuery) response = jsonify(result) response.headers.add('Access-Control-Allow-Origin', '*') return response @app.route('/search_fa...
<mask token> CORS(app) <mask token> @app.route('/search_general', methods=['POST']) def query(): message = None searchQuery = request.json['searchQuery'] result = qp.generateQuery(searchQuery) response = jsonify(result) response.headers.add('Access-Control-Allow-Origin', '*') return response ...
<mask token> app = Flask(__name__) CORS(app) qp = QueryProcessor() @app.route('/search_general', methods=['POST']) def query(): message = None searchQuery = request.json['searchQuery'] result = qp.generateQuery(searchQuery) response = jsonify(result) response.headers.add('Access-Control-Allow-Orig...
from flask import Flask, request from flask import jsonify from preprocessing import QueryProcessor from flask_cors import CORS app = Flask(__name__) CORS(app) qp = QueryProcessor() @app.route('/search_general', methods=['POST']) def query(): message = None searchQuery = request.json['searchQuery'] result...
from flask import Flask, request from flask import jsonify from preprocessing import QueryProcessor from flask_cors import CORS app = Flask(__name__) CORS(app) qp = QueryProcessor() @app.route('/search_general', methods=['POST']) def query(): message = None searchQuery = request.json['searchQuery'] resul...
[ 2, 3, 4, 5, 6 ]
258
cf0cf028d5f67e8deca8ebd3ad76d9c1e3563002
#!/usr/bin/python2 import sys import argparse """ This program generates an extract table having the following format: <S1> <S2> <S3> ... <Sn> ||| <T1> <T2> <T3> ... <Tk> ||| 0-0 Each line is a mapping from a source sentence to target sentence with special delimiter characters. You can give the output of this s...
null
null
null
null
[ 0 ]
259
f8bf7e2d8f06bbd00f04047153833c07bf483fd3
<mask token>
<mask token> class PyrpgConfig(AppConfig): <mask token>
<mask token> class PyrpgConfig(AppConfig): name = 'PyRPG'
from django.apps import AppConfig class PyrpgConfig(AppConfig): name = 'PyRPG'
null
[ 0, 1, 2, 3 ]
260
48677d73f6489ce789884a9dff5d50c23f47d8b3
<mask token> class WindowFeatureExtractor(object): <mask token> <mask token> def fit(self, X, y=None): """ X : list of list of str list of word windows y : ignored returns : numpy ar...
<mask token> class WindowFeatureExtractor(object): <mask token> def __init__(self, feature_extractors, min_feat_frequency, sparse=True, feature_val=1): """ feature_extractors : list of fns feature extraction fns min_feat_frequency : in...
__author__ = 'simon.hughes' <mask token> class WindowFeatureExtractor(object): """ A simple wrapper class that takes a number of window based feature extractor functions and applies them to a dataset of windows, and then vectorizes with the sklearn DictVectorizer class """ def __init__(self, ...
__author__ = 'simon.hughes' from sklearn.feature_extraction import DictVectorizer from WindowFeatures import compute_middle_index from collections import Counter class WindowFeatureExtractor(object): """ A simple wrapper class that takes a number of window based feature extractor functions and applies the...
__author__ = 'simon.hughes' from sklearn.feature_extraction import DictVectorizer from WindowFeatures import compute_middle_index from collections import Counter class WindowFeatureExtractor(object): """ A simple wrapper class that takes a number of window based feature extractor functions and applies the...
[ 5, 6, 8, 9, 10 ]
261
65aa85675393efa1a0d8e5bab4b1dbf388018c58
indelCost = 1 swapCost = 13 subCost = 12 noOp = 0 def alignStrings(x,y): nx = len(x) ny = len(y) S = matrix(nx+1, ny+1) #?? for i in range (nx+1) for j in range (ny+1) if i == 0: #if the string is empty S[i][j] = j #this will put all the letters from j in i elif j == 0: #if the second string ...
null
null
null
null
[ 0 ]
262
47c1ad4bd1ceffa38eef467ea8eb59dbd2fc2ebb
<mask token> class PacketSender: <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> def handle_ack(data): global acked_packets global seq_num global acked_all_packets global acked...
<mask token> class PacketSender: <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> def reset(self): global seq_num global sent_packets global next_seq_num global acked_packets global acke...
<mask token> class PacketSender: """ Packet represents a simulated UDP packet. """ seq_num = 0 next_seq_num = 0 sent_packets = 0 acked_packets = [] acked_all_packets = False acked_packets_lock = threading.Lock() was_reset = False def reset(self): global seq_num ...
from packet import Packet from packetConstructor import PacketConstructor import threading import time class PacketSender: """ Packet represents a simulated UDP packet. """ seq_num = 0 next_seq_num = 0 sent_packets = 0 acked_packets = [] acked_all_packets = False acked_packets_lock...
from packet import Packet from packetConstructor import PacketConstructor import threading import time class PacketSender: """ Packet represents a simulated UDP packet. """ # The next seq num for sent packets seq_num = 0 # The next seq num for acks that we're waiting for next_seq_num = 0 ...
[ 4, 6, 9, 10, 11 ]
263
24cdbbadc8ff1c7ad5d42eeb518cb6c2b34724a2
<mask token> class EfficientDoubleExchange(AnsatzElement): <mask token> <mask token> <mask token> <mask token> class EfficientDoubleExcitation2(AnsatzElement): def __init__(self, qubit_pair_1, qubit_pair_2): self.qubit_pair_1 = qubit_pair_1 self.qubit_pair_2 = qubit_pair_2 ...
<mask token> class EfficientDoubleExchange(AnsatzElement): def __init__(self, qubit_pair_1, qubit_pair_2, rescaled_parameter=False, parity_dependence=False, d_exc_correction=False): self.qubit_pair_1 = qubit_pair_1 self.qubit_pair_2 = qubit_pair_2 self.rescaled_parameter = rescale...
<mask token> class EfficientDoubleExchange(AnsatzElement): def __init__(self, qubit_pair_1, qubit_pair_2, rescaled_parameter=False, parity_dependence=False, d_exc_correction=False): self.qubit_pair_1 = qubit_pair_1 self.qubit_pair_2 = qubit_pair_2 self.rescaled_parameter = rescale...
<mask token> class EfficientDoubleExchange(AnsatzElement): def __init__(self, qubit_pair_1, qubit_pair_2, rescaled_parameter=False, parity_dependence=False, d_exc_correction=False): self.qubit_pair_1 = qubit_pair_1 self.qubit_pair_2 = qubit_pair_2 self.rescaled_parameter = rescale...
from openfermion import QubitOperator, FermionOperator from openfermion.transforms import jordan_wigner from src.utils import QasmUtils, MatrixUtils from src.ansatz_elements import AnsatzElement, DoubleExchange import itertools import numpy class EfficientDoubleExchange(AnsatzElement): def __init__(self, qubit_...
[ 5, 6, 7, 9, 11 ]
264
2843845848747c723d670cd3a5fcb7127153ac7e
<mask token>
<mask token> @app.route('/<sensor_id>', methods=['GET']) def sensor_details(sensor_id): sensor_pos = search_index_by_id(sensor_id) if sensor_pos >= 0: return {'sensor': sensors[sensor_pos]} else: return {'kind': 'error', 'payload': f'Sensor {sensor_id} not found'} @app.route('/<sensor_id...
<mask token> def search_index_by_id(sensor_id: str): for pos, sensor in enumerate(sensors): if sensor.id == sensor_id: return pos return -1 @app.route('/<sensor_id>', methods=['GET']) def sensor_details(sensor_id): sensor_pos = search_index_by_id(sensor_id) if sensor_pos >= 0: ...
<mask token> app = Flask(__name__) sensors = [ToggleSensor(id='s-01', description='lampadina'), ToggleSensor( id='s-02', description='lampadina'), ToggleSensor(id='s-03', description='allarme atomico'), ToggleSensor(id='s-04', description= 'porta aperta'), Sensor(id='temperature-01', description= 'senso...
from flask import Flask from sim.toggle import ToggleSensor from sim.sensor import Sensor app = Flask(__name__) sensors = [ ToggleSensor(id="s-01", description="lampadina"), ToggleSensor(id="s-02", description="lampadina"), ToggleSensor(id="s-03", description="allarme atomico"), ToggleSensor(id="s-04...
[ 0, 3, 4, 5, 7 ]
265
f5bd41f4aaff616a332d80ec44c364ffc91c58f0
<mask token>
<mask token> def skewness_log(df): df['SalePrice_New'] = np.log(df['SalePrice']) df['GrLivArea_New'] = np.log(df['GrLivArea']) skewed_slPri = skew(df['SalePrice_New']) skewness_grLiv = skew(df['GrLivArea_New']) return skewness_grLiv, skewed_slPri
<mask token> data = pd.read_csv('data/train.csv') def skewness_log(df): df['SalePrice_New'] = np.log(df['SalePrice']) df['GrLivArea_New'] = np.log(df['GrLivArea']) skewed_slPri = skew(df['SalePrice_New']) skewness_grLiv = skew(df['GrLivArea_New']) return skewness_grLiv, skewed_slPri
from scipy.stats import skew import pandas as pd import numpy as np data = pd.read_csv('data/train.csv') def skewness_log(df): df['SalePrice_New'] = np.log(df['SalePrice']) df['GrLivArea_New'] = np.log(df['GrLivArea']) skewed_slPri = skew(df['SalePrice_New']) skewness_grLiv = skew(df['GrLivArea_New'])...
# %load q03_skewness_log/build.py from scipy.stats import skew import pandas as pd import numpy as np data = pd.read_csv('data/train.csv') # Write code here: def skewness_log(df): df['SalePrice_New'] = np.log(df['SalePrice']) df['GrLivArea_New'] = np.log(df['GrLivArea']) skewed_slPri = skew(df['SalePrice...
[ 0, 1, 2, 3, 4 ]
266
d65f858c3ad06226b83d2627f6d38e03eae5b36c
<mask token>
<mask token> def line_evaluation(param_list, param_eval, file_name='line evaluation', ** kwargs): """ Evaluates a list of parameter pairs across repeated trials and aggregates the result. Parameters ---------- param_list : array_like List of values to test for parameter of interest. ...
<mask token> def grid_evaluation(param_list_one, param_list_two, param_eval, n_trials=16, aggr_method=np.mean, save_dir='data/', file_name='grid evaluation', save_to_disk=True, save_each=1000, chunksize=1.0): """ Evaluates a grid of parameter pairs across repeated trials and aggregates the result. ...
<mask token> import utils import datetime import itertools import numpy as np import recovery as rec import sampling as smp import graphs_signals as gs import pathos.multiprocessing as mp from tqdm import tqdm def grid_evaluation(param_list_one, param_list_two, param_eval, n_trials=16, aggr_method=np.mean, save_d...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Phase transition module """ import utils import datetime import itertools import numpy as np import recovery as rec import sampling as smp import graphs_signals as gs import pathos.multiprocessing as mp from tqdm import tqdm ## MAIN FUNCTIONS ## def grid_evalua...
[ 0, 1, 2, 3, 4 ]
267
f97a892e6e0aa258ad917c4a73a66e89b0dc3253
<mask token>
<mask token> sys.path.extend(['detection', 'train']) <mask token> if test_mode in ['RNet', 'ONet']: detectors[1] = Detector(R_Net, 24, batch_size[1], model_path[1]) if test_mode == 'ONet': detectors[2] = Detector(O_Net, 48, batch_size[2], model_path[2]) <mask token> if config.input_mode == '1': path...
<mask token> sys.path.extend(['detection', 'train']) <mask token> test_mode = 'ONet' thresh = [0.6, 0.7, 0.9] min_face_size = 24 stride = 2 detectors = [None, None, None] scale_factor = 0.79 model_path = ['model/PNet/', 'model/RNet/', 'model/ONet'] batch_size = config.batches detectors[0] = FcnDetector(P_Net, model_pat...
import sys sys.path.extend(['detection', 'train']) from MtcnnDetector import MtcnnDetector from detector import Detector from fcn_detector import FcnDetector from model_factory import P_Net, R_Net, O_Net import config as config from preprocess.utils import iou import cv2 import os from os.path import join, split import...
# coding: utf-8 # In[1]: import sys sys.path.extend(['detection', 'train']) # from detection folder from MtcnnDetector import MtcnnDetector from detector import Detector from fcn_detector import FcnDetector # from train folder from model_factory import P_Net, R_Net, O_Net import config as config from preprocess.uti...
[ 0, 1, 2, 3, 4 ]
268
f19d8aa2104240cc93a0146f1b14c635e7cd3a41
#! /usr/bin/env python import ldac from numpy import * import shearprofile as sp import sys import os, subprocess import pylab if len(sys.argv) != 6: sys.stderr.write("wrong number of arguments!\n") sys.exit(1) catfile= sys.argv[1] clusterz=float(sys.argv[2]) center= map(float,sys.argv[3].split(',')) pixsc...
null
null
null
null
[ 0 ]
269
0e58834120c34b5152026bde6d089be19244e21a
import os from MdApi import MdApi class Adapter(MdApi): def __init__(self): super(Adapter, self).__init__() def connect(self): self.createFtdcMdApi(os.getcwd()) self.registerFront('tcp://180.168.146.187:10010') def onFrontConnected(self): print 'front succ...
null
null
null
null
[ 0 ]
270
df40b0628d6a180a98cd385145ee7c65ecb78256
<mask token> def bytes_feature(value): assert isinstance(value, Iterable) return tf.train.Feature(bytes_list=tf.train.BytesList(value=value)) <mask token> class TFRecordProducer: def remove_list(self, list1, list2): i, j = 0, 0 tmp_list1 = [] tmp_list2 = [] while i < l...
<mask token> def bytes_feature(value): assert isinstance(value, Iterable) return tf.train.Feature(bytes_list=tf.train.BytesList(value=value)) def convert_to_example(target, mixed, speaker, target_phase=None, mixed_phase=None, target_mel=None, mixed_mel=None): raw_target = target.tostring() raw_m...
<mask token> def bytes_feature(value): assert isinstance(value, Iterable) return tf.train.Feature(bytes_list=tf.train.BytesList(value=value)) def convert_to_example(target, mixed, speaker, target_phase=None, mixed_phase=None, target_mel=None, mixed_mel=None): raw_target = target.tostring() raw_m...
import os import tensorflow as tf import torch from tqdm import tqdm from glob import glob import numpy as np from collections.abc import Iterable from utils.hparams import HParam def bytes_feature(value): assert isinstance(value, Iterable) return tf.train.Feature(bytes_list=tf.train.BytesList(value=value)) ...
import os import tensorflow as tf import torch from tqdm import tqdm from glob import glob import numpy as np from collections.abc import Iterable from utils.hparams import HParam #from utils.audio import Audio #import librosa #python encoder_inference.py --in_dir training_libri_mel/train/ --gpu_str 5 #python tfrecord...
[ 5, 7, 8, 9, 10 ]
271
ed7b29a4d7f3a48884434373418c3528f2f397ac
<mask token> def generate_script(seed_text, model, charset): sys.stdout.write(seed_text) sys.stdout.flush() next_char = None should_stop = False while not should_stop: prev_char = next_char next_char = sample(model, seed_text, charset, temp=0.2) sys.stdout.write(next_char) ...
<mask token> def main(): print('Loading model...') model, charset = load_model(MODEL_NAME) print(charset) seed_text = input('Enter a String: ').strip() print() generate_script(seed_text, model, charset) def generate_script(seed_text, model, charset): sys.stdout.write(seed_text) sys.s...
<mask token> def main(): print('Loading model...') model, charset = load_model(MODEL_NAME) print(charset) seed_text = input('Enter a String: ').strip() print() generate_script(seed_text, model, charset) def generate_script(seed_text, model, charset): sys.stdout.write(seed_text) sys.s...
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ['KERAS_BACKEND'] = 'tensorflow' import numpy as np import sys from util import load_model from keras.preprocessing.text import hashing_trick from keras.preprocessing.sequence import pad_sequences from southpark.southpark_generative import string_one_hot, cha...
#!/usr/bin/python3 import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2' os.environ['KERAS_BACKEND'] = 'tensorflow' import numpy as np import sys from util import load_model from keras.preprocessing.text import hashing_trick from keras.preprocessing.sequence import pad_sequences from southpar...
[ 2, 4, 5, 7, 8 ]
272
b6d8a918659f733919fe3bb4be9037e36ad32386
<mask token> def hwToidx(x: int, y: int, weight: int): return y * weight + x <mask token> def idxToXY(idx, cellw: int): curpoint = idxTohw(idx, cellw) curpoint[0], curpoint[1] = curpoint[0] * 10, curpoint[1] * 10 return curpoint class Graph: def __init__(self, V: int, W: int): self....
<mask token> def hwToidx(x: int, y: int, weight: int): return y * weight + x def idxTohw(idx, weight: int): return [idx % weight, idx // weight] def idxToXY(idx, cellw: int): curpoint = idxTohw(idx, cellw) curpoint[0], curpoint[1] = curpoint[0] * 10, curpoint[1] * 10 return curpoint class Gr...
<mask token> def hwToidx(x: int, y: int, weight: int): return y * weight + x def idxTohw(idx, weight: int): return [idx % weight, idx // weight] def idxToXY(idx, cellw: int): curpoint = idxTohw(idx, cellw) curpoint[0], curpoint[1] = curpoint[0] * 10, curpoint[1] * 10 return curpoint class Gr...
import queue import sys import logging from superai.common import InitLog logger = logging.getLogger(__name__) def hwToidx(x: int, y: int, weight: int): return y * weight + x def idxTohw(idx, weight: int): return [idx % weight, idx // weight] def idxToXY(idx, cellw: int): curpoint = idxTohw(idx, cellw...
import queue import sys import logging from superai.common import InitLog logger = logging.getLogger(__name__) # 2维到1维 def hwToidx(x: int, y: int, weight: int): return y * weight + x # 1维到2维 def idxTohw(idx, weight: int): return [idx % weight, idx // weight] # 10x10 cell idx 到 [x,y] def idxToXY(idx, cel...
[ 16, 18, 19, 23, 24 ]
273
7930bb813bd546747c7c65b661900939f5ba93f1
<mask token>
<mask token> for n in range(len(user_input)): explosion_strength = 0 if user_input[n] == '>': explosion_strength += int(user_input[n + 1]) if user_input[n + explosion_strength] != '>': exploded_str = user_input[:n] + user_input[n + explosion_strength + 1:] ...
user_input = input() exploded_str = user_input for n in range(len(user_input)): explosion_strength = 0 if user_input[n] == '>': explosion_strength += int(user_input[n + 1]) if user_input[n + explosion_strength] != '>': exploded_str = user_input[:n] + user_input[n + ex...
user_input = input() #abv>1>1>2>2asdasd exploded_str = user_input for n in range(len(user_input)): explosion_strength = 0 if user_input[n] == ">": explosion_strength += int(user_input[n+1]) if user_input[n+explosion_strength] != ">": exploded_str = user_input[:n] + user_input[n+ex...
null
[ 0, 1, 2, 3 ]
274
c6cf085330f47ffb139c5acc91d91e9758f5396a
<mask token> class MainPage(PageObject): <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> def __init__(self, webdriver, root_uri=None): super(MainPage, self).__init__(webdriver, root_uri) self.open_level_menu() self.clo...
<mask token> class MainPage(PageObject): <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> def __init__(self, webdriver, root_uri=None): super(MainPage, self).__init__(webdriver, root_uri) self.open_level_menu() self.clo...
<mask token> class MainPage(PageObject): <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> def __init__(self, webdriver, root_uri=None): super(MainPage, self).__init__(webdriver, root_uri) self.open_level_menu() self.clo...
from page_objects import PageObject, PageElement class MainPage(PageObject): level_menu_opened = False level_menu_created = False css_input = PageElement(css='input.input-strobe') level_text_span = PageElement(css='span.level-text') instruction_h2 = PageElement(css='h2.order') enter_button = P...
from page_objects import PageObject, PageElement class MainPage(PageObject): level_menu_opened = False level_menu_created = False css_input = PageElement(css='input.input-strobe') level_text_span = PageElement(css='span.level-text') instruction_h2 = PageElement(css='h2.order') enter_button = P...
[ 4, 6, 7, 11, 12 ]
275
c2ddf31bce4a5f3ae2b0d5455bbc9942f92bff40
<mask token>
<mask token> with open(MODEL_LABELS_FILENAME, 'rb') as f: lb = pickle.load(f) <mask token> for root, dirs, files in os.walk(CAPTCHA_IMAGE_FOLDER): for name in tqdm(files, desc='Solving captchas'): kernel = 5, 5 image = cv2.imread(os.path.join(root, name)) image = cv2.cvtColor(image, cv2....
<mask token> os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' <mask token> c1_correct = 0 c2_correct = 0 c3_correct = 0 c4_correct = 0 c5_correct = 0 total_correct = 0 incorrectly_segmented = 0 correct_guesses_dict = {} MODEL_FILENAME = 'captcha_model.hdf5' MODEL_LABELS_FILENAME = 'model_labels.dat' CAPTCHA_IMAGE_FOLDER = 'tes...
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' from keras.models import load_model from utils import resize_to_fit, clear_chunks, stack_windows from imutils import paths import numpy as np import imutils import cv2 as cv2 import pickle from tqdm import tqdm c1_correct = 0 c2_correct = 0 c3_correct = 0 c4_correct = ...
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' from keras.models import load_model from utils import resize_to_fit, clear_chunks, stack_windows from imutils import paths import numpy as np import imutils import cv2 as cv2 import pickle from tqdm import tqdm c1_correct = 0 c2_correct = 0 c3_correct = 0 c4_correct ...
[ 0, 1, 2, 3, 4 ]
276
75e6554ea3c327c87a2a65710a7f1d55e9933bb0
<mask token> def train(): args = get_args() os.makedirs(args.model_path, exist_ok=True) set_seed(args.seed) """ To follow this training routine you need a DataLoader that yields the tuples of the following format: (Bx3xHxW FloatTensor x, BxHxW LongTensor y, BxN LongTensor y_cls) where ...
<mask token> def build_network(snapshot, backend): epoch = 0 backend = backend.lower() net = models[backend]() if snapshot is not None: _, epoch = os.path.basename(snapshot).split('_') epoch = int(epoch) net.load_state_dict(torch.load(snapshot)) logging.info('Snapshot f...
__author__ = 'BeiYu' <mask token> models = {'squeezenet': lambda : PSPNet(sizes=(1, 2, 3, 6), psp_size=512, deep_features_size=256, backend='squeezenet', n_classes=3), 'densenet': lambda : PSPNet(sizes=(1, 2, 3, 6), psp_size=1024, deep_features_size= 512, backend='densenet', n_classes=3), 'resnet18': lambda...
__author__ = 'BeiYu' from utils.init_env import set_seed from utils.options import * import os import logging import torch from torch import nn from torch import optim from torch.optim.lr_scheduler import MultiStepLR from torch.autograd import Variable from torch.utils.data import DataLoader from modules.seg_dataset im...
# Author: BeiYu # Github: https://github.com/beiyuouo # Date : 2021/2/21 21:57 # Description: __author__ = "BeiYu" from utils.init_env import set_seed from utils.options import * import os import logging import torch from torch import nn from torch import optim from torch.optim.lr_scheduler import MultiStepLR from ...
[ 1, 3, 4, 5, 6 ]
277
58f3b8c5470c765c81f27d39d9c28751a8c2b719
<mask token>
<mask token> print(f'Sua frase tem {n_a} letras a') print(f'A letra A aparece pela primeira vez na {f_a}° posição') print(f'A letra A apaerece pela ultima vez na {l_a}° posição')
<mask token> frase = str(input('Digite uma frase: ')).strip().lower() n_a = frase.count('a') f_a = frase.find('a') + 1 l_a = frase.rfind('a') - 1 print(f'Sua frase tem {n_a} letras a') print(f'A letra A aparece pela primeira vez na {f_a}° posição') print(f'A letra A apaerece pela ultima vez na {l_a}° posição')
"""Ex026 Faça um programa que leia uma frase pelo teclado e mostre: Quantas vezes aparece a letra "A". Em que posição ela aparece a primeira vez. Em que posição ela aparece pela última vez.""" frase = str(input('Digite uma frase: ')).strip().lower() n_a = frase.count('a') f_a = frase.find('a')+1 l_a= frase.rfind('a')-1...
null
[ 0, 1, 2, 3 ]
278
d83f2d9bb25a46bc7344b420ce65bf729165e6b9
<mask token>
<mask token> class FosAppConfig(AppConfig): <mask token>
<mask token> class FosAppConfig(AppConfig): name = 'fos_app'
from django.apps import AppConfig class FosAppConfig(AppConfig): name = 'fos_app'
from django.apps import AppConfig class FosAppConfig(AppConfig): name = 'fos_app'
[ 0, 1, 2, 3, 4 ]
279
d2b05c5653ca6c6b7219f6c0393e81c9425b5977
<mask token>
<mask token> print(bucket) if bucket is None: raise Exception('No Input Bucket set') def handler(event: Dict, context: Dict): """AWS Lambda handler.""" granule = event.get('granule') prefix = granule[0:-6] print(prefix) response = s3.list_objects_v2(Bucket=bucket, Prefix=prefix) print(resp...
<mask token> s3 = boto3.client('s3') bucket = os.getenv('SENTINEL_INPUT_BUCKET', None) print(bucket) if bucket is None: raise Exception('No Input Bucket set') def handler(event: Dict, context: Dict): """AWS Lambda handler.""" granule = event.get('granule') prefix = granule[0:-6] print(prefix) ...
<mask token> from typing import Dict import os import re import boto3 from botocore.errorfactory import ClientError from datetime import date s3 = boto3.client('s3') bucket = os.getenv('SENTINEL_INPUT_BUCKET', None) print(bucket) if bucket is None: raise Exception('No Input Bucket set') def handler(event: Dict, c...
""" HLS: Check if Twin Granule Exists """ from typing import Dict import os import re import boto3 from botocore.errorfactory import ClientError from datetime import date s3 = boto3.client("s3") bucket = os.getenv("SENTINEL_INPUT_BUCKET", None) print(bucket) if bucket is None: raise Exception("No Input Bucket set"...
[ 0, 2, 3, 4, 5 ]
280
c73a199d1c1c1867f3d53ceebf614bc9b65c0d5e
<mask token> @admin.register(UserTicket) class UserTicketAdmin(admin.ModelAdmin): pass
<mask token> @admin.register(AuxiliaryTicket) class AuxiliaryTicketAdmin(admin.ModelAdmin): pass @admin.register(UserTicket) class UserTicketAdmin(admin.ModelAdmin): pass
<mask token> @admin.register(Ticket) class TicketAdmin(admin.ModelAdmin): pass @admin.register(AuxiliaryTicket) class AuxiliaryTicketAdmin(admin.ModelAdmin): pass @admin.register(UserTicket) class UserTicketAdmin(admin.ModelAdmin): pass
from django.contrib import admin from ticket.models import Ticket, UserTicket, AuxiliaryTicket @admin.register(Ticket) class TicketAdmin(admin.ModelAdmin): pass @admin.register(AuxiliaryTicket) class AuxiliaryTicketAdmin(admin.ModelAdmin): pass @admin.register(UserTicket) class UserTicketAdmin(admin.Model...
from django.contrib import admin from ticket.models import Ticket, UserTicket, AuxiliaryTicket @admin.register(Ticket) class TicketAdmin(admin.ModelAdmin): pass @admin.register(AuxiliaryTicket) class AuxiliaryTicketAdmin(admin.ModelAdmin): pass @admin.register(UserTicket) class UserTicketAdmin(admin.Mode...
[ 1, 2, 3, 4, 5 ]
281
e564e0d05c3c0e60f356422722803df510d9dd0b
<mask token> @njit(parallel=True) def parallel_test(subject_array, typeII_error, typeI_error, num): test_result = np.zeros(subject_array.shape, dtype=int) random_table = np.random.uniform(0, 1, (subject_array.shape[0], num)) for i in range(len(subject_array)): subject = subject_array[i, 1] ...
<mask token> @njit(parallel=True) def parallel_test(subject_array, typeII_error, typeI_error, num): test_result = np.zeros(subject_array.shape, dtype=int) random_table = np.random.uniform(0, 1, (subject_array.shape[0], num)) for i in range(len(subject_array)): subject = subject_array[i, 1] ...
<mask token> @jit(parallel=True) def conventional_test(subject_array, typeII_error, typeI_error, repeat=1, seq=True): """ A function gives the test results to a subject array given the probability of type II error, the probability of Type I error, and the number of repeatition, and setting of sequ...
<mask token> @jit(parallel=True) def conventional_test(subject_array, typeII_error, typeI_error, repeat=1, seq=True): """ A function gives the test results to a subject array given the probability of type II error, the probability of Type I error, and the number of repeatition, and setting of sequ...
import numpy as np import pandas as pd from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report from sklearn.metrics import precision_score, recall_score, f1_score from scipy.optimize import fsolve import numba from numba import njit,jit # @jit(parallel = True) def conventional_tes...
[ 11, 12, 17, 18, 20 ]
282
9bc13c608c079cbf23ed04f29edd1fd836214cde
<mask token> class CommentViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins .RetrieveModelMixin): <mask token> def get_serializer_class(self): if self.action == 'retrieve': if self.get_object().level < 3: return CommentSerializer return AllCommentS...
<mask token> class CommentViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins .RetrieveModelMixin): queryset = Comment.objects.all() def get_serializer_class(self): if self.action == 'retrieve': if self.get_object().level < 3: return CommentSerializer ...
<mask token> class PostViewSet(viewsets.ModelViewSet): <mask token> <mask token> class CommentViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins .RetrieveModelMixin): queryset = Comment.objects.all() def get_serializer_class(self): if self.action == 'retrieve': i...
from rest_framework import viewsets, mixins from .models import Comment, Post from .serializer import CommentSerializer, PostSerializer, AllCommentSerializer class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() class CommentViewSet(viewsets.GenericViewSet...
from rest_framework import viewsets, mixins from .models import Comment, Post from .serializer import CommentSerializer, PostSerializer, AllCommentSerializer class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() class CommentViewSet(viewsets.GenericViewSet...
[ 2, 3, 4, 6, 7 ]
283
b11e2837d3ba9c14770b8039186a2175adc41ea1
<mask token> def http_server(file: str=None, host: str='localhost', port: int=5050 ) ->CanvasServer: """Creates a new HTTP server for displaying the network, using WebSockets to transmit data. The server will only start once its :meth:`~server.CanvasServer.start` method is called. After the server has...
<mask token> def http_server(file: str=None, host: str='localhost', port: int=5050 ) ->CanvasServer: """Creates a new HTTP server for displaying the network, using WebSockets to transmit data. The server will only start once its :meth:`~server.CanvasServer.start` method is called. After the server has...
<mask token> try: from .jupyter import JupyterCanvas, create_jupyter_canvas HAS_JUPYTER = True except: HAS_JUPYTER = False JupyterCanvas = None def http_server(file: str=None, host: str='localhost', port: int=5050 ) ->CanvasServer: """Creates a new HTTP server for displaying the network, using...
from .server import CanvasServer try: from .jupyter import JupyterCanvas, create_jupyter_canvas HAS_JUPYTER = True except: HAS_JUPYTER = False JupyterCanvas = None def http_server(file: str=None, host: str='localhost', port: int=5050 ) ->CanvasServer: """Creates a new HTTP server for displayin...
from .server import CanvasServer try: from .jupyter import JupyterCanvas, create_jupyter_canvas HAS_JUPYTER = True except: HAS_JUPYTER = False JupyterCanvas = None # type: ignore def http_server( file: str = None, host: str = "localhost", port: int = 5050 ) -> CanvasServer: """Creates a new...
[ 1, 2, 3, 4, 5 ]
284
2da7892722afde5a6f87e3bd6d5763c895ac96c9
<mask token> class Lang: def __init__(self): super(Lang, self).__init__() self.word2index = {} self.word2count = {} self.index2word = {} self.n_words = 0 def index_words(self, sentence): for word in sentence: self.index_word(word) def index_wo...
<mask token> class Lang: def __init__(self): super(Lang, self).__init__() self.word2index = {} self.word2count = {} self.index2word = {} self.n_words = 0 def index_words(self, sentence): for word in sentence: self.index_word(word) def index_wo...
<mask token> nltk.download('stopwords') <mask token> class Lang: def __init__(self): super(Lang, self).__init__() self.word2index = {} self.word2count = {} self.index2word = {} self.n_words = 0 def index_words(self, sentence): for word in sentence: ...
<mask token> nltk.download('stopwords') nltk_stopwords = nltk.corpus.stopwords.words('english') data_path = '/home/joey.bose/dblp_papers_v11.txt' save_path_base = '/home/joey.bose/aminer_data/' load_path_rank_base = '/home/joey.bose/aminer_data_ranked/fos/' save_path_graph_base = '/home/joey.bose/aminer_data_ranked/gra...
import json import os import ipdb from tqdm import tqdm import argparse from os import listdir from os.path import isfile, join import pickle import joblib from collections import Counter from shutil import copyfile import networkx as nx import spacy import nltk import numpy as np nltk.download('stopwords') nltk_stopw...
[ 4, 8, 10, 11, 13 ]
285
e38ae7f91deed1be00e60b7516210ea1feefe23e
<mask token> def folders_with_documents(pat_ids, main_dir_name, doc_prog_folder): str_pat_ids = [str(pat_id) for pat_id in pat_ids] str_pat_folder_names = [os.path.join(main_dir_name, os.path.join( str_pat_id, doc_prog_folder)) for str_pat_id in str_pat_ids] for pid, folder in zip(str_pat_ids, str...
<mask token> def folders_with_documents(pat_ids, main_dir_name, doc_prog_folder): str_pat_ids = [str(pat_id) for pat_id in pat_ids] str_pat_folder_names = [os.path.join(main_dir_name, os.path.join( str_pat_id, doc_prog_folder)) for str_pat_id in str_pat_ids] for pid, folder in zip(str_pat_ids, str...
<mask token> logger = logging.getLogger(__name__) DOCUMENTS = 1 PROGRESS_NOTES = 2 DOC_TYPE = {DOCUMENTS: {'file_type': 'Document', 'folder': 'Documents', 'class': DocumentIndex, 'log': 'd', 'dates': ['CREATED_TIMESTAMP', 'POST_DATE'], 'converters': {'FILENAME': strip, 'DISPLAY_DESC': strip, 'DOC_COMMENT': ...
import sys import os from configparser import ConfigParser import logging from mod_argparse import setup_cli from checkers.IndexFile import DocumentIndex, ProgressNoteIndex from checkers import source_files from utilities import write_to_file, strip logger = logging.getLogger(__name__) DOCUMENTS = 1 PROGRESS_NOTES = 2 ...
import sys import os from configparser import ConfigParser import logging from mod_argparse import setup_cli from checkers.IndexFile import DocumentIndex, ProgressNoteIndex from checkers import source_files from utilities import write_to_file, strip # , write_to_db_isok # import pandas as pd logger = logging.getLogger...
[ 4, 5, 6, 7, 8 ]
286
069338b188f3cf16357b2502cbb3130b69918bd9
<mask token>
<mask token> if __name__ == '__main__': exit(cli.main(prog_name='htmap'))
from .cli import cli if __name__ == '__main__': exit(cli.main(prog_name='htmap'))
from .cli import cli if __name__ == "__main__": exit(cli.main(prog_name="htmap"))
null
[ 0, 1, 2, 3 ]
287
b52269237d66ea50c453395b9536f25f1310bf2e
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import re from blessings import Terminal from validate_email import validate_email import requests import sys _site_ = sys.argv[1] _saida_ = sys.argv[2] _file_ = open(_saida_, "w") t = Terminal() r = requests.get(_site_, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6....
null
null
null
null
[ 0 ]
288
8c539dbbb762717393b9a71ddca8eb3872890854
<mask token>
<mask token> def process_names(): """ Opening, reading name file and building name array. """ with open(input_names_file, 'r') as data: plaintext = data.read() name_array = plaintext.split('\n') final_name_list = [] for name in name_array: if len(name.split(',')) == 2: ...
<mask token> instruments_file = os.path.abspath('instruments.csv') input_names_file = os.path.abspath('names.txt') output_names_file = os.path.abspath('names.csv') inst_name_file = os.path.abspath('name_instrument.csv') reg_ex = '; |, |\\*|\n' name_header = ['first_name', 'last_name'] def process_names(): """ ...
import re import os import pandas as pd instruments_file = os.path.abspath('instruments.csv') input_names_file = os.path.abspath('names.txt') output_names_file = os.path.abspath('names.csv') inst_name_file = os.path.abspath('name_instrument.csv') reg_ex = '; |, |\\*|\n' name_header = ['first_name', 'last_name'] def p...
import re import os import pandas as pd instruments_file = os.path.abspath("instruments.csv") input_names_file = os.path.abspath("names.txt") output_names_file = os.path.abspath("names.csv") inst_name_file = os.path.abspath("name_instrument.csv") reg_ex = '; |, |\\*|\n' name_header = ["first_name", "last_name"] def ...
[ 0, 1, 2, 3, 4 ]
289
0db0daf9bea254cffaec1280cd13b2d70368cd94
<mask token>
<mask token> for i in range(B): p1 = 0.0 for j in range(N1): if rnd.uniform(0, 1) < p1mle: p1 += 1 p1 /= N1 p2 = 0.0 for j in range(N2): if rnd.uniform(0, 1) < p2mle: p2 += 1 p2 /= N2 estimate.append(p2 - p1) <mask token> for t in allt: cur = np.me...
<mask token> B = 100000 N1 = 50 N2 = 50 p1mle = 0.3 p2mle = 0.4 taumle = p2mle - p1mle estimate = [] for i in range(B): p1 = 0.0 for j in range(N1): if rnd.uniform(0, 1) < p1mle: p1 += 1 p1 /= N1 p2 = 0.0 for j in range(N2): if rnd.uniform(0, 1) < p2mle: p2 +=...
import numpy.random as rnd import numpy as np B = 100000 N1 = 50 N2 = 50 p1mle = 0.3 p2mle = 0.4 taumle = p2mle - p1mle estimate = [] for i in range(B): p1 = 0.0 for j in range(N1): if rnd.uniform(0, 1) < p1mle: p1 += 1 p1 /= N1 p2 = 0.0 for j in range(N2): if rnd.uniform...
import numpy.random as rnd import numpy as np B=100000 N1=50 N2=50 p1mle=0.3 p2mle=0.4 taumle=p2mle-p1mle estimate=[] for i in range(B): p1=0.0 for j in range(N1): if(rnd.uniform(0,1)<p1mle): p1+=1 p1/=N1 p2=0.0 for j in range(N2): if(rnd.uniform(0,1)<p2mle): p2+=1 p2/=N2 estimate.append(p2-p...
[ 0, 1, 2, 3, 4 ]
290
a90b7e44cc54d4f96a13e5e6e2d15b632d3c4983
<mask token> class GroupSignature: def __init__(self, groupObj): global util, group util = SecretUtil(groupObj, debug) self.group = groupObj def pkGen(self, h1str): gstr = ( '[6172776968119684165170291368128433652817636448173749093457023424948260385279837018774774...
<mask token> class GroupSignature: def __init__(self, groupObj): global util, group util = SecretUtil(groupObj, debug) self.group = groupObj def pkGen(self, h1str): gstr = ( '[6172776968119684165170291368128433652817636448173749093457023424948260385279837018774774...
<mask token> class GroupSignature: def __init__(self, groupObj): global util, group util = SecretUtil(groupObj, debug) self.group = groupObj def pkGen(self, h1str): gstr = ( '[6172776968119684165170291368128433652817636448173749093457023424948260385279837018774774...
import random import string import steembase import struct import steem from time import sleep from time import time from steem.transactionbuilder import TransactionBuilder from steembase import operations from steembase.transactions import SignedTransaction from resultthread import MyThread from charm.toolbox.pairingg...
import random import string import steembase import struct import steem from time import sleep from time import time from steem.transactionbuilder import TransactionBuilder from steembase import operations from steembase.transactions import SignedTransaction from resultthread import MyThread from charm.toolbox.pairingg...
[ 22, 26, 28, 30, 31 ]
291
ee80169afd4741854eff8619822a857bbf757575
<mask token> class Test(unittest.TestCase): def test_take(self): x = np.linspace(0, 100) idx = np.random.random_integers(0, 50, 20) result = indexing.take(x, idx) expected = np.take(x, idx) np.testing.assert_array_equal(expected, result) def test_take_comparison(self)...
<mask token> class Test(unittest.TestCase): def test_take(self): x = np.linspace(0, 100) idx = np.random.random_integers(0, 50, 20) result = indexing.take(x, idx) expected = np.take(x, idx) np.testing.assert_array_equal(expected, result) def test_take_comparison(self)...
<mask token> class Test(unittest.TestCase): def test_take(self): x = np.linspace(0, 100) idx = np.random.random_integers(0, 50, 20) result = indexing.take(x, idx) expected = np.take(x, idx) np.testing.assert_array_equal(expected, result) def test_take_comparison(self)...
<mask token> import matplotlib.pyplot as plt from numerical_functions import Timer import numerical_functions.numba_funcs.indexing as indexing import numpy as np import unittest class Test(unittest.TestCase): def test_take(self): x = np.linspace(0, 100) idx = np.random.random_integers(0, 50, 20) ...
''' Created on 27 Mar 2015 @author: Jon ''' import matplotlib.pyplot as plt from numerical_functions import Timer import numerical_functions.numba_funcs.indexing as indexing import numpy as np import unittest class Test(unittest.TestCase): def test_take(self): x = np.linspace( 0, 100 ) ...
[ 6, 7, 8, 11, 12 ]
292
ce6dba2f682b091249f3bbf362bead4b95fee1f4
<mask token>
<mask token> from .book import book from . import style, to, read, dist
""" .. currentmodule:: jotting .. automodule:: jotting.book :members: .. automodule:: jotting.to :members: .. automodule:: jotting.read :members: .. automodule:: jotting.style :members: """ from .book import book from . import style, to, read, dist
null
null
[ 0, 1, 2 ]
293
99c839eddcbe985c81e709878d03c59e3be3c909
#coding=utf-8 ######################################### # dbscan: # 用法说明:读取文件 # 生成路径文件及簇文件,输出分类准确率 ######################################### from matplotlib.pyplot import * import matplotlib.pyplot as plt from collections import defaultdict import random from math import * import numpy import datetime ...
null
null
null
null
[ 0 ]
294
bf8bbeb408cb75af314ef9f3907456036e731c0b
<mask token>
def solution(S): log_sep = ',' num_sep = '-' time_sep = ':' from collections import defaultdict bill = defaultdict(int) total = defaultdict(int) calls = S.splitlines() maximal = 0 free_number = 0 for call in calls: hhmmss, number = call.split(log_sep) hh, mm, ss =...
def solution(S): # write your code in Python 3.6 # Definitions log_sep = ',' num_sep = '-' time_sep = ':' # Initialization from collections import defaultdict # defaultdict initialize missing key to default value -> 0 bill = defaultdict(int) total = defaultdict(int) calls = S...
null
null
[ 0, 1, 2 ]
295
35ae9c86594b50bbe4a67d2cc6b20efc6f6fdc64
<mask token>
<mask token> sys.path.append(dir_path) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gulishop.settings') <mask token> django.setup() <mask token> for lev1 in row_data: cat1 = GoodsCategory() cat1.name = lev1['name'] cat1.code = lev1['code'] if lev1['code'] else '' cat1.category_type = 1 cat1.save...
<mask token> file_path = os.path.abspath(__file__) dir_path = os.path.dirname(file_path) sys.path.append(dir_path) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gulishop.settings') <mask token> django.setup() <mask token> for lev1 in row_data: cat1 = GoodsCategory() cat1.name = lev1['name'] cat1.code = l...
import os, sys file_path = os.path.abspath(__file__) dir_path = os.path.dirname(file_path) sys.path.append(dir_path) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gulishop.settings') import django django.setup() from goods.models import GoodsCategory from db_tools.data.category_data import row_data for lev1 in row_d...
#配置我们文件所在目录的搜寻环境 import os,sys #第一步先拿到当前文件的路径 file_path = os.path.abspath(__file__) #第二步 根据这个路径去拿到这个文件所在目录的路径 dir_path = os.path.dirname(file_path) #第三步:讲这个目录的路径添加到我们的搜寻环境当中 sys.path.append(dir_path) #第四步,动态设置我们的setting文件 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gulishop.settings") #第五步,让设置好的环境初始化生效 ...
[ 0, 1, 2, 3, 4 ]
296
d34159536e860719094a36cfc30ffb5fcae72a9a
<mask token>
<mask token> print('Retriving', url) <mask token> print('Retrived', len(data), 'characters') <mask token> print(json.dumps(js, indent=4)) print('Place id', js['results'][0]['place_id']) <mask token>
<mask token> target = 'http://py4e-data.dr-chuck.net/json?' local = input('Enter location: ') url = target + urllib.parse.urlencode({'address': local, 'key': 42}) print('Retriving', url) data = urllib.request.urlopen(url).read() print('Retrived', len(data), 'characters') js = json.loads(data) print(json.dumps(js, inden...
import urllib.error, urllib.request, urllib.parse import json target = 'http://py4e-data.dr-chuck.net/json?' local = input('Enter location: ') url = target + urllib.parse.urlencode({'address': local, 'key': 42}) print('Retriving', url) data = urllib.request.urlopen(url).read() print('Retrived', len(data), 'characters')...
#API End Points by Mitul import urllib.error, urllib.request, urllib.parse import json target = 'http://py4e-data.dr-chuck.net/json?' local = input('Enter location: ') url = target + urllib.parse.urlencode({'address': local, 'key' : 42}) print('Retriving', url) data = urllib.request.urlopen(url).read() print('Retrive...
[ 0, 1, 2, 3, 4 ]
297
c382b298cce8d7045d6ce8a84f90b3800dba7717
<mask token>
<mask token> class Migration(migrations.Migration): <mask token> <mask token>
<mask token> class Migration(migrations.Migration): dependencies = [('products', '0003_auto_20200615_1225')] operations = [migrations.AlterField(model_name='product', name= 'harmonizacao', field=models.TextField(null=True)), migrations. AlterField(model_name='product', name='history', field=mo...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('products', '0003_auto_20200615_1225')] operations = [migrations.AlterField(model_name='product', name= 'harmonizacao', field=models.TextField(null=True)), migrations. AlterField(model_name='produc...
# Generated by Django 3.0.7 on 2020-06-15 15:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0003_auto_20200615_1225'), ] operations = [ migrations.AlterField( model_name='product', name='harmoniza...
[ 0, 1, 2, 3, 4 ]
298
3372d98ff91d90558a87293d4032820b1662d60b
<mask token>
<mask token> urlpatterns = patterns('', url('appmanagement', views.appmanagement, name= 'appmanagement'), url('^.*', views.index, name='index'))
from django.conf.urls import patterns, url from riskDashboard2 import views urlpatterns = patterns('', url('appmanagement', views.appmanagement, name= 'appmanagement'), url('^.*', views.index, name='index'))
from django.conf.urls import patterns, url from riskDashboard2 import views urlpatterns = patterns('', #url(r'getdata', views.vulnData, name='getdata'), url(r'appmanagement', views.appmanagement, name='appmanagement'), url(r'^.*', views.index, name='index'), )
null
[ 0, 1, 2, 3 ]
299
0465e33d65c2ce47ebffeec38db6908826bf4934
<mask token>
<mask token> if people < cats: print('Too many cats') elif people > cats: print('Not many cats') else: print('we cannnot decide')
people = 20 cats = 30 dogs = 15 if people < cats: print('Too many cats') elif people > cats: print('Not many cats') else: print('we cannnot decide')
people = 20 cats = 30 dogs = 15 if people < cats: print("Too many cats") elif people > cats: print("Not many cats") else: print("we cannnot decide")
null
[ 0, 1, 2, 3 ]