index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
8,800 | 5ff0c6bde8f3ffcb1f5988b0bbd1dfdd7fa2e818 | # The project is based on Tensorflow's Text Generation with RNN tutorial
# Copyright Petros Demetrakopoulos 2020
import tensorflow as tf
import numpy as np
import os
import time
# The project is based on Tensorflow's Text Generation with RNN tutorial
# Copyright Petros Demetrakopoulos 2020
import tensorflow as tf
impor... |
8,801 | 9276c4106cbe52cf0e2939b5434d63109910a45c | from pymoo.model.duplicate import ElementwiseDuplicateElimination
class ChrDuplicates(ElementwiseDuplicateElimination):
"""Detects duplicate chromosome, which the base ElementwiseDuplicateElimination then removes."""
def is_equal(self, a, b):
"""
Checks whether two character chromosome elemen... |
8,802 | cc6e827eec5256ce0dbe13958b6178c59bcd94a7 | from scipy.stats import rv_discrete
import torch
import torch.nn.functional as F
import numpy as np
from utils import *
def greedy_max(doc_length,px,sentence_embed,sentences,device,sentence_lengths,length_limit=200,lamb=0.2):
'''
prob: sum should be 1
sentence embed: [doc_length, embed_dim]
'''
x = list(range(do... |
8,803 | e54078f21176bbb7accb4164e7b56633b13cc693 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
BATCH_START=0
TIME_STEPS=20
BATCH_SIZE=50
INPUT_SIZE=1
OUTPUT_SIZE=1
CELL_SIZE=10
LR=0.006
#generate data
def get_batch():
global BATCH_START,TIME_STEPS
xs=np.arange(BATCH_START,BATCH_START+TIME_STEPS*BATCH_SIZE).reshape((BATCH_SIZE,T... |
8,804 | b3cb94a44f64091714650efb81c4cad27b211cef | import os
import math
import shutil
from evoplotter import utils
from evoplotter.dims import *
from evoplotter import printer
import numpy as np
CHECK_CORRECTNESS_OF_FILES = 1
STATUS_FILE_NAME = "results/status.txt"
OPT_SOLUTIONS_FILE_NAME = "opt_solutions.txt"
class TableGenerator:
"""Generates table from dat... |
8,805 | 027e53d69cfece0672556e34fa901412e483bc3e | class Solution:
def uniquePaths(self, A, B):
# A - rows
# B - columns
if A == 0 or B == 0:
return 0
grid = [[1 for _ in range(B)] for _ in range(A)]
for i in range(1, A):
for j in range(1, B):
grid[i][j] = grid[i-1][j] + grid[i][j-1]
return grid[A-1][B-1]
s = Solution... |
8,806 | 3c2fb3d09edab92da08ac8850f650a2fa22fad92 | from django.db import transaction
from django.forms import inlineformset_factory
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView, UpdateView
from forms.models.fund_operation import FundOperation
from forms.forms.fund_operation_forms import FundOperati... |
8,807 | 3f80c4c212259a8f3ff96bcc745fd28a85dac3ba | # Import
import sys
from .step import Step
from .repeat import Repeat
# Workout
class Workout(object):
def __init__(self):
self.workout = []
self.steps = []
self.postfixEnabled = True
# TODO: check that len(name) <= 6
def addStep(self, name, duration):
self.workout.append(... |
8,808 | c4ac7ff5d45af9d325f65b4d454a48ca0d8f86df | N, M = map(int, input().split()) # Nはスイッチの数、Mは電球の数
lights = [[0] * N for _ in range(M)]
for i in range(M):
temp = list(map(int, input().split())) # 0番目はスイッチの個数、1番目以降はスイッチを示す
k = temp[0]
switches = temp[1:]
for j in range(k):
lights[i][switches[j]-1] = 1
P = list(map(int, input().split())) # 個数を... |
8,809 | 24bc43c1fe035430afde05fec1330e27fb5f1d86 | import sys
import re
import math
s=sys.stdin.read()
digits=re.findall(r"-?\d+",s)
listline= [int(e) for e in digits ]
x=listline[-1]
del(listline[-1])
n=len(listline)//2
customers=listline[:n]
grumpy=listline[n:]
maxcus=0
if x==n:
print(sum(customers))
else:
for i in range(n-x):
total=0
for j in... |
8,810 | 2402188380bc0189b88e3cfcbaabf64a9919b3d5 | import pygame
import sys
# класс для хранения настроек
class Settings():
"""docstring for Setting"""
def __init__(self):
# параметры экрана
self.colour = (230, 230, 230)
self.screen_width = 1200
self.screen_height = 800
# параметры коробля
self.ship_speed = 1.5
# параметры пули
self.bullet_speed = ... |
8,811 | 9c751dece67ef33ba8e5cb8281f024d2143e0808 | import os
import sys
import winreg
import zipfile
class RwpInstaller:
railworks_path = None
def extract(self, target):
with zipfile.ZipFile(target) as z:
if z.testzip():
return self.output('Corrupt file {}\n'.format(target))
self.output('{} file valid\n\n'.for... |
8,812 | 97d128694709c4fe0d9ec2b2749d8e4ec5df7322 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from fieldsets import getSingleField, SortAsc
from sqlalchemy import func
from ladderdb import ElementNotFoundException, EmptyRankingListException
from db_entities import Player, Result
from bottle import route,request
from globe import db,env
@route('/player')
def output( ):... |
8,813 | 347d468f15dee8a8219d201251cedffe21352f7c | from django.contrib.auth.models import User
from django.test import Client
from django.utils.timezone import localdate
from pytest import fixture
from operations.models import ToDoList
@fixture
def user(db):
return User.objects.create(
username='test', email='saidazimovaziza@gmail.com',
password=... |
8,814 | 8cc97ebe0ff7617eaf31919d40fa6c312d7b6f94 | # accessing array elements rows/columns
import numpy as np
a = np.array([[1, 2, 3, 4, 5, 6, 7], [9, 8, 7, 6, 5, 4, 3]])
print(a.shape) # array shape
print(a)
print('\n')
# specific array element [r,c]
# item 6
print(a[0][5])
# item 8
print(a[1][1]) # or
print(a[1][-6])
# get a specific row/specific column
print(a... |
8,815 | a1b33d0a8a074bc7a2a3e2085b1ff01267e00d3b | def minutes to hours(minutes) :
hours = minutes/60
return hours
print(minutes to hours(70))
|
8,816 | 070330f8d343ff65852c5fbb9a3e96fe1bfc55b5 | # pylint: disable=not-callable, no-member, invalid-name, missing-docstring, arguments-differ
import argparse
import itertools
import os
import torch
import torch.nn as nn
import tqdm
import time_logging
from hanabi import Game
def mean(xs):
xs = list(xs)
return sum(xs) / len(xs)
@torch.jit.script
def swis... |
8,817 | 88af8b4eeb40ecf19622ecde1a5dea9a078bb66c | # Percy's playground.
from __future__ import print_function
import sympy as sp
import numpy as np
import BorderBasis as BB
np.set_printoptions(precision=3)
from IPython.display import display, Markdown, Math
sp.init_printing()
R, x, y = sp.ring('x,y', sp.RR, order=sp.grevlex)
I = [ x**2 + y**2 - 1.0, x + y ]
R, x, y... |
8,818 | 38a79f5b3ce1beb3dc1758880d42ceabc800ece7 | # Generated by Django 3.0 on 2019-12-15 16:20
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('blog', '0013_auto_20191215_1619'),
]
operations = [
migrations.AlterField(
m... |
8,819 | 32e60c672d6e73600d442c4344743deccaed6796 | from .core import S3FileSystem, S3File
from .mapping import S3Map
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
|
8,820 | 9fbf994cb99369ba0c20383007ce52c99248bacf |
# code below
#taking filename as pyscript.py
from distutils.core import setup
import py2exe
setup(console=['pyscript.py'])
# command to run
# python setup.py pytoexe
|
8,821 | 78761eda403ad8f54187e5858a23c23d3dd79b09 | """"Module for miscellaneous behavior stuff
For example, stuff like extracting lick times or choice times.
TrialSpeak shouldn't depend on stuff like that.
# Also get the pldf and use that to get lick times
ldf = ArduFSM.TrialSpeak.read_logfile_into_df(bdf.loc[idx, 'filename'])
# Get the lick times
... |
8,822 | f76a3fac75e7e2b156f4bff5094f11009b65b599 | # Generated by Django 3.1.7 on 2021-03-25 00:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('restaurante', '0003_auto_20210324_1932'),
]
operations = [
migrations.AlterModelOptions(
name='comprobantemodel',
options={'... |
8,823 | 6e9fd8ee2a187888df07c9dd1c32fe59a111c869 | #downloads project detail reports from the web and places them in the correct project folder created by makeFolders.py
import os, openpyxl, time, shutil
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
wb = openpyxl.load_workbook('ProjectSummary.xlsx')
sheet = wb.active
browser = webdri... |
8,824 | c5605f4770d61d435cc1817bad4d5cbe0aaf1d18 | from sys import stdin
read = lambda: stdin.readline().strip()
class Trie:
def __init__(self, me, parent=None):
self.me = me
self.parent = parent
self.children = {}
def get_answer(trie, count):
print(("--" * count) + trie.me)
trie.children = dict(sorted(trie.children.items(), key... |
8,825 | 3dd9ce6d5d1ba0bebadae4068e2c898802180e1d | #!/usr/bin/env python
# $Id: iprscan5_urllib2.py 2809 2015-03-13 16:10:25Z uludag $
# ======================================================================
#
# Copyright 2009-2014 EMBL - European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file ex... |
8,826 | 5cced6d9f5e01b88951059bc89c5d10cfd160f60 | """
Write two functions:
1. `to_list()`, which converts a number to an integer list of its digits.
2. `to_number()`, which converts a list of integers back to its number.
### Examples
to_list(235) ➞ [2, 3, 5]
to_list(0) ➞ [0]
to_number([2, 3, 5]) ➞ 235
to_number([0]) ➞ 0
### No... |
8,827 | 46b1fc975fbeedcafaa66c85c378e2249a495647 |
def read_int():
return int(input().strip())
def read_ints():
return list(map(int, input().strip().split(' ')))
def solve():
K, S = read_ints()
# X+Y+Z = S
# 0 <= X,Y,Z <= K
total = 0
for X in range(K+1):
if S-X < 0:
break
# Y+Z=S-X
Y_min = max(S-X-K,... |
8,828 | 8ce468460a81c7869f3abb69035a033c58e0f699 | import numpy as np
"""
function for calculating integrals using the trapezoid method
x is a vector of independent variables
y is a vector of dependent variables
a is the initial value
b is the final value
n is the number of intervals
y_generator is the function to be integrated
"""
def tra... |
8,829 | e2f6e6e872f95471ebbc8b25bde08247fe8f7e61 | import media
import fresh_tomatoes
toy_story = media.Movie("Toy Story",
"A story of a boy and his toys that come to life",
'<p><a href="https://en.wikipedia.org/wiki/File:Toy_Story.jpg#/media/File:Toy_Story.jpg"><img src="https://upload.wikimedia.org/wikipedia/en/1/13/To... |
8,830 | 03f3fcb38877570dea830a56460061bd3ccb8927 | import os
import matplotlib.pyplot as plt
import cv2
import numpy as np
def divide_img(img_path, img_name, save_path):
imgg = img_path +'\\' +img_name
print(imgg)
img = cv2.imread(imgg)
print(img)
# img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
h = img.shape[0]
w = img.shape[1]
n = 8
... |
8,831 | 23f491bbf26ede9052ecdab04b8c00cc78db5a7e | from sklearn import preprocessing
from random import shuffle
import numpy as np
import collections
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from tensorflow.keras.layers import Dense, Dropout, Activation, Conv1D, GlobalMaxPooling1D
from tensorflow.keras.models import Sequential, model_from_json
from t... |
8,832 | f5f14e4d114855b7eef555db182ee991bdf26c39 | from django.contrib.auth.models import BaseUserManager
class MyUserManager(BaseUserManager):
def create_user(self, email, password, full_name, national_code, mobile, address):
if not email :
raise ValueError('ایمیل الزامی است')
if not full_name :
raise ValueError('نام و نام... |
8,833 | 75270fb4ed059f134b47b8937717cb7fe05d9499 | from threading import Lock
from typing import Callable, Any
from remote.domain.commandCallback import CommandCallback
from remote.domain.commandStatus import CommandStatus
from remote.service.remoteService import RemoteService
from ui.domain.subroutine.iSubroutineRunner import ISubroutineRunner
class RemoteSubroutin... |
8,834 | 8f1e6ea93b2dd7add256cb31d2c621aa69721609 | import wx
import os
# os.environ["HTTPS_PROXY"] = "http://user:pass@192.168.1.107:3128"
import wikipedia
import wolframalpha
import pyttsx3
import webbrowser
import winshell
import json
import requests
import ctypes
import random
from urllib.request import urlopen
import speech_recognition as sr
import ssl
import urlli... |
8,835 | 661b622708692bd9cd1b3399835f332c86e39bf6 | class Error(Exception):
pass
class TunnelInstanceError(Error):
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TunnelManagerError(Error):
def __init__(self, expression, message):
self.expression = expression
self.messag... |
8,836 | 11db76cba3dd76cad0d660a0e189d3e4c465071b | from typing import Any, Optional
from aiogram import types
from aiogram.dispatcher.middlewares import BaseMiddleware
from scene_manager.loader.loader import Loader
from scene_manager.utils import content_type_checker
class ScenesMiddleware(BaseMiddleware):
def __init__(self, *, loader: Optional[Loader] = None, ... |
8,837 | f14ff29a1a76c2916cb211c476a56aaa5061bf71 | # -*- coding: utf-8 -*-
import sys
import setuptools
from distutils.core import setup
with open("README.md", "r") as fh:
long_description = fh.read()
def get_info():
init_file = 'PIKACHU/__init__.py'
with open(init_file, 'r') as f:
for line in f.readlines():
if "=" in line:
... |
8,838 | decd5d50025fc3b639be2f803d917ff313cf7219 | from collections import Counter
N = int(input())
lst = list(map(int, input().split()))
ans = []
for i in range(N):
ans.append(abs(i+1-lst[i]))
s = Counter(ans)
rst = []
for i in s:
rst.append([i, s[i]])
rst.sort(key=lambda x: x[0], reverse=True)
for i in rst:
if i[1] > 1:
print(i[0], i[1])
|
8,839 | 728f9402b3ce4b297be82b3ba1a17c4180ac7c0d | '''
Statistics models module. This module contains the database models for the
Statistics class and the StatisticsCategory class.
@author Hubert Ngu
@author Jason Hou
'''
from django.db import models
class Statistics(models.Model):
'''
Statistics model class. This represents a single tuple in the
... |
8,840 | ae475dc95c6a099270cf65d4b471b4b430f02303 | """
Kernel desnity estimation plots for geochemical data.
"""
import copy
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MaxNLocator
from ...comp.codata import close
from ...util.log import Handle
from ...util.meta import get_additional_params, subkwargs
from ...util.plot.axes import... |
8,841 | 96086885e5353f3b4b3277c1daf4ee74831c3b73 | from kivy.uix.boxlayout import BoxLayout
from kivy.graphics import *
from kivy.clock import Clock
from kivy.properties import StringProperty, BooleanProperty
from kivy.uix.popup import Popup
import time
from math import sin, pi
from kivy.lang import Builder
from ui.custom_widgets import I18NPopup, I18NLabel
Builder.... |
8,842 | 4ca4d4bd684802b056417be4ee3d7d10e8f5dc85 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from .authority import *
from .ca_pool import *
fro... |
8,843 | e553da92b1bb5dfaa0fb7c702f5be4f66201c75b | # coding: UTF-8
import fileinput
import io
from locale import str
import os
__author__ = 'lidong'
def getDirList( p ):
p = p.replace( "/","\\")
if p[ -1] != "\\":
p = p+"\\"
a = os.listdir( p )
for x in a:
if(os.path.isfile( p + x )):
a, b = os.path.splitext( p + x )
... |
8,844 | ca7b0553e55e1c5e6cd23139a158101e72456a50 | from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from django.contrib.auth.models import User, Group
class UserTests(APITestCase):
def test_user_list(self):
# must be rejected without validation
response = self.client.get('/api/us... |
8,845 | 252d6b381af09dbafb1d10c188eb154e53213033 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 15 06:50:48 2018
@author: Tony
"""
import glob
import pandas as pd
path =r'C:\Users\Tony\Downloads\daily_dataset\daily_dataset' # use your path
frame = pd.DataFrame()
list_ = []
def aggSumFn(path,grpByCol):
allFiles = glob.glob(path + "/*.csv")
... |
8,846 | 118380f58cd173d2de5572a1591766e38ca4a7f8 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
from datetime import datetime
class Config(object):
# ...
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'postgres' or 'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
MONGODB_DB... |
8,847 | 53cf2dfe3319c39ca6f1dc890eea578fae654b5b | # Evolutionary Trees contains algorithms and methods used in determining phylogenetic inheritance of various species.
# Main algos UPGMA and CLUSTALW
from dataclasses import dataclass
import FormattingET
@dataclass
class Node:
age: int
num: int
label: str
alignment: []
def __init__(self, child1=Non... |
8,848 | 65bb3743ca569c295d85016c82c4f6f043778d3f | from django.contrib import admin
from .models import Recipe, Ingredient, ChosenIngredient, timezone
# Register your models here.)
admin.site.register(Ingredient)
admin.site.site_header = "Chef's Apprentice Admin"
admin.site.site_title = "Chef's Apprentice Admin Portal"
admin.site.index_title = "Welcome to Chef's Appre... |
8,849 | 72bbbe78db746febc9a36a676e0fa2d97bf5e81e | """ Crie um programa onde o usuario possa digitar sete valores numericos e cadastre-os em uma lisa unicaque mantenha
separados os valores pares e impares. No final, mostre os valores ares e impares em ordem crescente """
n = [[],[]]
for c in range(0,7):
num = int(input(f'Digite o {c+1} valor: '))
res = num % ... |
8,850 | 81f49c55edff7678e9d1745e39a8370e2c31c9ea | """
___________________________________________________
| _____ _____ _ _ _ |
| | __ \ | __ (_) | | | |
| | |__) |__ _ __ __ _ _ _| |__) || | ___ | |_ |
| | ___/ _ \ '_ \ / _` | | | | ___/ | |/ _ \| __| |
| | | | __/ | | | (_| | |_| | | | | |... |
8,851 | 52426ec670dd5ca522c7fb0b659e3a42b16ff326 | #!/usr/bin/python
import sys
f = open('/etc/passwd','r')
users_and_ids = []
for line in f:
u,_,id,_ = line.split(':',3)
users_and_ids.append((u,int(id)))
users_and_ids.sort(key = lambda pair:pair[1])
for id,usr in users_and_ids:
print id,usr
|
8,852 | 806bdb75eed91d1429d8473a50c136b58a736147 | """
Visualize the predictions of a GQCNN on a dataset Visualizes TP, TN, FP, FN..
Author: Vishal Satish
"""
import copy
import logging
import numpy as np
import os
import sys
from random import shuffle
import autolab_core.utils as utils
from autolab_core import YamlConfig, Point
from perception import BinaryImage, Co... |
8,853 | 06339e9cd506f147d03c54aee82473e233b4ec2e | from .routes import generate_routes |
8,854 | 5f50b20bd044471ebb8e1350d1a75a250b255d8f | # ********************************************************************************** #
# #
# Project: Data Frame Explorer #
# Author: Pawel Rosikiewicz ... |
8,855 | 601ef4e1000348059dcfe8d34eec5f28368f2464 | /Users/alyssaliguori/anaconda3/lib/python3.7/tokenize.py |
8,856 | bbd5eb1f80843efdd2709aa19a65bf325a88f473 | # Developed by Lorenzo Mambretti, Justin Wang
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://github.com/jtwwang/hanabi/blob/master/LICENSE
#
# Unless required by applic... |
8,857 | 0b4f070d30642449536118accffa371a89dd3075 | # views which respond to ajax requests
from django.contrib import messages
from django.conf import settings
from django.contrib.auth.models import User
from social.models import Like, Post, Comment, Notification
from social.notifications import Notify
from social.forms import CommentForm
from django.http impor... |
8,858 | 4fc4bb81d47a33e4669df46033033fddeca6544e | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 1 11:52:48 2022
@author: ccamargo
"""
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import os
# 1. get filelist
path = "/Volumes/LaCie_NIOZ/data/steric/data/"
path_to_original_files = path + "original/"
flist = [file for ... |
8,859 | d267bf82aee2eca29628fcd1d874a337adc1ae09 | import math
class Solution:
# @param {integer} n
# @param {integer} k
# @return {string}
def getPermutation(self, n, k):
res = ''
k -= 1
nums = [str(i) for i in range(1, n+1)]
while n > 0:
tmp = math.factorial(n-1)
res += nums[k/tmp]
d... |
8,860 | ad5cdcfd9d7a3c07abcdcb701422f3c0fdc2b374 | from Bio import BiopythonWarning, SeqIO
from Bio.PDB import MMCIFParser, Dice, PDBParser
from Bio.SeqUtils import seq1
import time
import requests
import re
import warnings
warnings.simplefilter('ignore', BiopythonWarning)
def get_response(url):
response = requests.get(url)
cnt = 20
while cnt != 0:
... |
8,861 | b005f4657a1036044c2e6051207641fe621eb17e | # Constructor without arguments
class Demo:
def __init__(self):
print("\nThis is constructor")
obj = Demo()
# Constructor with arguments
class Demo2:
def __init__(self, number1, number2):
sumOfNumbers = number1 + number2
print(sumOfNumbers)
obj2 = Demo2(50,75... |
8,862 | 4f84cf80292e2764ca3e4da79858058850646527 | import json, requests, math, random
#import datagatherer
# Constants:
start_elo = 0 # Starting elo
decay_factor = 0.9 # Decay % between stages
k = 30 # k for elo change
d = 200 # Difference in elo for 75% expected WR
overall_weight = 0.60 # Weigts for different types o... |
8,863 | de287d1bc644fdfd0f47bd8667580786b74444d0 | class Solution(object):
def smallestGoodBase(self, n):
"""
:type n: str
:rtype: str
"""
# k is the base and the representation is
# m bits of 1
# We then have from math
# (k**m - 1) / (k-1) = n
# m = log_k (n * k - n + 1)
# m needs to b... |
8,864 | 6a4a5eac1b736ee4f8587adba298571f90df1cf9 | from .queue_worker import QueueWorker
import threading
class WorkersOrchestrator:
@classmethod
def worker_func(cls, worker):
worker.start_consumption()
def run_orchestrator(self, num_of_workers):
worker_list = []
for i in range(num_of_workers):
worker_list.append(Queu... |
8,865 | 61179dc734069017adaabd53804ed0102d9416e3 | from django.contrib.auth.models import User
from django.db import models
class Chat(models.Model):
category = models.CharField(unique=True, max_length=100)
def __str__(self):
return self.category
class ChatMessage(models.Model):
context = models.CharField(max_length=1000)
user = models.Fore... |
8,866 | f5513bea4ca5f4c2ac80c4bf537a264a4052d1e9 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import random
a = random.sample(range(100), 10)
print("All items: {}".format(a))
it = iter(a) # call a.__iter__()
print("Num01: {}".format(next(it))) # call it.__next__()
print("Num02: {}".format(next(it)))
print("Num03: {}".format(it.__next__()))
it = iter(a)
i = 1
while... |
8,867 | 67793c8851e7107c6566da4e0ca5d5ffcf6341ad | import csv
from functools import reduce
class Csvread:
def __init__(self, fpath):
self._path=fpath
with open (fpath) as file:
read_f=csv.reader(file)
print(read_f) #<_csv.reader object at 0x000002A53144DF40>
self._sheet = list(read_f)[1:] #utworzenie listy
... |
8,868 | 67ac5d82bc37b67cfdae73b6667b73b70ed33cfb | '''
Paulie Jo Gonzalez
CS 4375 - os
Lab 0
Last modified: 02/14/2021
This code includes a reference to C code for my_getChar method provided by Dr. Freudenthal.
'''
from os import read
next_c = 0
limit = 0
def get_char():
global next_c, limit
if next_c == limit:
next_c = 0
limit = read(0, 10... |
8,869 | 62c28b5eb31b90191dfbab4456fc5373ba51bf64 | import pytest
import os
import pandas as pd
import numpy as np
import math
import scipy
from scipy import stats
from sklearn import metrics, linear_model
from gpmodel import gpkernel
from gpmodel import gpmodel
from gpmodel import gpmean
from gpmodel import chimera_tools
n = 200
d = 10
X = np.random.random(size=(n, ... |
8,870 | d49aa03cd6b8ba94d68a1bc1e064f77fded65000 | from bs4 import BeautifulSoup
from bs4 import BeautifulSoup
import requests,pymysql,random,time
import http.cookiejar
from multiprocessing import Pool,Lock
def get_proxies_ip():
db = pymysql.connect("localhost","root","xxx","xxx",charset='utf8')
cursor = db.cursor()
sql = "SELECT * FROM proxies_info;"
... |
8,871 | f410a77d4041514383110d9fd16f896178924d59 | # coding: UTF-8
import os
import sys
if len(sys.argv) == 3:
fname = sys.argv[1]
out_dir = sys.argv[2]
else:
print "usage: vcf_spliter <input file> <output dir>"
exit()
count = 0
if not os.path.exists(out_dir):
os.makedirs(out_dir)
with open(fname, 'r') as f:
for l in f:
if l.strip()... |
8,872 | 25550cbaf6e0e5bdbbe3852bb8cdc05ac300d315 | # 运算符的优先级
# 和数学中一样,在Python运算也有优先级,比如先乘除 后加减
# 运算符的优先级可以根据优先级的表格来查询,
# 在表格中位置越靠下的运算符优先级越高,优先级越高的越优先计算
# 如果优先级一样则自左向右计算
# 关于优先级的表格,你知道有这么一个东西就够了,千万不要去记
# 在开发中如果遇到优先级不清楚的,则可以通过小括号来改变运算顺序
a = 1 + 2 * 3
# 一样 and高 or高
# 如果or的优先级高,或者两个运算符的优先级一样高
# 则需要先进行或运算,则运算结果是3
# 如果and的优先级高,则应该先计算与运算
# 则运算结果是1
a = 1 or 2 and 3
... |
8,873 | 062b6133ba4de24f7eaf041e4b6c039501b47b9a | n_m_q=input().split(" ")
n=int(n_m_q[0])
m=int(n_m_q[1])
q=int(n_m_q[2])
dcc=[]
for i in range(n):
a=[]
dcc.append(a)
available=[]
for i in range(m):
x=input().split(" ")
a=int(x[0])
b=int(x[1])
available.append([a,b])
dcc[a-1].append(b)
dcc[b-1].append(a)
for i in range(q):
x=input(... |
8,874 | 887ae9b7c629be679bf4f5fb4311c31bff605c73 | import os
import shutil
from tqdm import tqdm
from pathlib import Path
from eval_mead import PERCENT
DATAPATH = '../../../data/test'
# MEAD_DIR = 'mead'
MEAD_DIR = os.path.abspath('mead')
MEAD_DATA_PATH = f'{MEAD_DIR}/data'
MEAD_BIN = f'{MEAD_DIR}/bin'
MEAD_LIB = f'{MEAD_DIR}/lib'
MEAD_FORMATTING_ADDONS = f'{MEAD_BIN}... |
8,875 | 74c60c9e37e4e13ed4c61f631c3426b685b5d38f | from django.conf.urls import patterns, include, url
from views.index import Index
from views.configuracoes import Configuracoes
from views.parametros import *
urlpatterns = patterns('',
url(r'^$', Index.as_view(), name='core_index'),
url(r'^configuracoes/', Configuracoes.as_view(), name='core.core_c... |
8,876 | a5c19ad60ac6312631273858cebaae944a2008ec | def contador_notas(multiplo, numero):
if(numero % multiplo == 0):
notas = numero / multiplo
return notas
else:
return -1
entrada = int(input())
resultado = contador_notas(100, entrada)
if (resultado != -1):
print("{} nota(s) de R$ {}".format(resultado, 100)) |
8,877 | 905d8be76ef245a2b8fcfb3f806f8922d351ecf0 | import pickle
import numpy as np
import math
class AdaBoostClassifier:
'''A simple AdaBoost Classifier.'''
def __init__(self, weak_classifier, n_weakers_limit):
'''Initialize AdaBoostClassifier
Args:
weak_classifier: The class of weak classifier, which is recommend to be sklearn.t... |
8,878 | c6d8b9faa610e817c449eee94d73c61cb62fa272 | print('test 123123')
|
8,879 | 92e7a7825b3f49424ec69196b69aee00bc84da68 | #!/usr/bin/python
# Copyright 2012 Google Inc. All Rights Reserved.
"""Antirollback clock user space support.
This daemon serves several purposes:
1. Maintain a file containing the minimum time, and periodically
update its value.
2. At startup, write the minimum time to /proc/ar_clock.
The kernel will n... |
8,880 | 6dafb60b79a389499ae2a0f17f9618426faf45a9 | def Return():
s = raw_input('Enter a s: ')
i = 0
s1 = ''
leng = len(s)
while i < leng:
if s[i] == s[i].lower():
s1 += s[i].upper()
else:
s1 += s[i].lower()
i += 1
return s1
if __name__ == '__main__':
print Return()
|
8,881 | 97fb2388777bcb459b9818495121fdf8318095ca | '''
check if word appear in file
'''
# easier solution :
def findKeyInFile(word, filepath):
with open(filepath) as f:
for line in f.readlines():
if line.count(word) > 0:
return line
return None
|
8,882 | b1622aa65422fcb69a16ad48a26fd9ed05b10382 | import pytest
from components import models
pytestmark = pytest.mark.django_db
def test_app_models():
assert models.ComponentsApp.allowed_subpage_models() == [
models.ComponentsApp,
models.BannerComponent,
]
def test_app_required_translatable_fields():
assert models.ComponentsApp.get_r... |
8,883 | 5f490d6a3444b3b782eed5691c82ab7e4b2e55db | from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdri... |
8,884 | 493b29433f0c3646e7f80fca2f656fc4a5256003 | from functools import wraps
class aws_retry:
"""retries the call (required for some cases where data is not consistent yet in AWS"""
def __init__(self, fields):
self.fields = fields # field to inject
def __call__(self, function):
pass
#code ... |
8,885 | 292c66bd5b7f56ee8c27cabff01cd97ff36a79dc | from django.contrib import admin
from .models import Wbs, Equipment_Type
class WbsAdmin(admin.ModelAdmin):
list_display = ('code','description','equipment_type')
list_filter = ('code','description','equipment_type')
readonly_fields = ('code','description')
class Equipment_TypeAdmin(admin.ModelAdmi... |
8,886 | 8b18f098080c3f5773aa04dffaff0639fe7fa74f | g=int(input())
num=0
while(g>0):
num=num+g
g=g-1
print(num)
|
8,887 | 62e0c3b6095a65a4508eddfa9c0a1cb31d6c917b | #OpenCV create samples commands
#opencv_createsamples -img watch5050.jpg -bg bg.txt -info info/info.lst -pngoutput info -maxxangle 0.5 -maxyangle 0.5 -maxzangle 0.5 -num 1950
#opencv_createsamples -info info/info.lst -num 1950 -w 20 -h 20 -vec positives.vec
#Training command
#opencv_traincascade -data data -vec p... |
8,888 | 1ba39cfc1187b0efc7fc7e905a15de8dc7f80e0d | from textmagic.rest import TextmagicRestClient
username = 'lucychibukhchyan'
api_key = 'sjbEMjfNrrglXY4zCFufIw9IPlZ3SA'
client = TextmagicRestClient(username, api_key)
message = client.message.create(phones="7206337812", text="wow i sent a text from python!!!!")
|
8,889 | dd91ba13177aefacc24ef4a004acae0bffafadf0 | #!/usr/bin/env conda-execute
# conda execute
# env:
# - python >=3
# - requests
# run_with: python
from configparser import NoOptionError
from configparser import SafeConfigParser
import argparse
import base64
import inspect
import ipaddress
import json
import logging
import logging.config
import o... |
8,890 | 28a0ae0492fb676044c1f9ced7a5a4819e99a8d9 | import math
import numpy as np
import cv2
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans
from sklearn import metrics
from scipy.spatial.distance import cdist
if (__name__ == "__main__"):
cap = cv2.VideoCapture('dfd1.mp4')
mog = cv2.createBackgroundSubtractorMOG2(detectSha... |
8,891 | b838d2230cb3f3270e86807e875df4d3d55438cd | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 8 22:11:53 2020
@author: Rick
"""
sum= 0;
with open('workRecord.txt') as fp:
for line in fp.readlines():
idx= line.rfind('x',len(line)-8,len(line))
if idx>=0:
sum+= float(line.rstrip()[idx+1:len(line)])
else:
sum+= 1
pr... |
8,892 | fd54bbfbc81aec371ad6c82bf402a5a3673a9f24 | # -*- encoding:ascii -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 6
_modified_time = 1383550959.0389481
_template_filename='templates/webapps/tool_shed/repository/browse_repository.mako'
_template_uri='/webapps/tool_shed/r... |
8,893 | 89e5e82c073f7f87c00fc844c861c6c5cbe6a695 |
import smart_imports
smart_imports.all()
class LogicTests(utils_testcase.TestCase):
def setUp(self):
super(LogicTests, self).setUp()
game_logic.create_test_map()
self.account_1 = self.accounts_factory.create_account()
self.account_1_items = prototypes.AccountItemsPrototype.ge... |
8,894 | efed5c113e085e5b41d9169901c18c06111b9077 | from snake.snake import Snake
# Start application
if __name__ == '__main__':
s = Snake()
s.run() |
8,895 | 2d4680b63cdd05e89673c4bd6babda7ac6ebb588 | from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
from crud.serializers import TodoListSerializer
from crud.models import TodoList
# Create your views here.
class TodoListViewSet(viewsets.ModelViewSet):
queryset = TodoList.objects.all()
seri... |
8,896 | e4fb932c476ca0222a077a43499bf9164e1f27d0 | import configparser
config = configparser.ConfigParser()
config.read('config.ini')
settings=config['Settings']
colors=config['Colors']
import logging
logger = logging.getLogger(__name__)
logLevel = settings.getint('log-level')
oneLevelUp = 20
#I don't know if this will work before loading the transformers module?
#s... |
8,897 | 0738fc48bc367f1df75567ab97ce20d3e747dc18 | cassandra = {
'nodes': ['localhost'],
'keyspace': 'coffee'
}
|
8,898 | 4b5794ff79371c2e49c5d2b621805b08c4ff7acb | from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from ex.models import Teacher,Student,Group,Report,TeamEvaluation,PrivateLetter,ChatBoxIsOpen
from django.core import serializers
from rest_framework.views import APIView
from rest_framework.response import Response
from django.cont... |
8,899 | a98d03b169b59704b3b592cee0b59f5389fd77b3 | #! /usr/bin/env python3
import sys
def stage_merge_checksums(
old_survey=None,
survey=None,
brickname=None,
**kwargs):
'''
For debugging / special-case processing, read previous checksums, and update them with
current checksums values, then write out the result.
'''
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.