index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
994,600
8692346c9d7d0d0853b0fd68ace790b42072e7fd
from django.shortcuts import render from rest_framework import viewsets from .serializers import EmployeeInfoSerializer from .models import EmployeeInfo # Create your views here. class EmployeeInfoViewSet(viewsets.ModelViewSet): queryset = EmployeeInfo.objects.all().order_by('employeeID') serializer_class = E...
994,601
18e8e5f2c33f846d1b951522bc845a052e4484e9
'''2.5. Escreva um algoritmo que leia 2 valores, insira os em duas variáveis e permute os valores entre elas. Ao fim, imprima o valor das variáveis antes e depois da permutação.''' a = int(input("Número 1: ")) b = int(input("Número 2: ")) print(a, b) aux = a a = b b = aux print(a, b)
994,602
2ac76baf745e4ddb6d71d8ebdb01beb300a24fef
import os from os.path import join from PIL import Image import numpy as np SIZE_FACE = 48 EMOTIONS = ['angry', 'disgusted', 'fearful', 'happy', 'sad', 'surprised', 'neutral'] additional_images_dir = join(".", "images") with open("./finetuning.csv", 'w') as output_file: for image_filename in os.listdir(addition...
994,603
28baad9e78f3bb71ac547026f5a786fe341874a9
# Create your views here. from django.shortcuts import render def sign ( request ) : """comment here""" return render( request, 'consultations/index.html', {} )
994,604
60748347d39b66edee12a44184fc4ca50b0cdc92
import sqlite3 def read_from_db(): cases_dict=dict() conn=sqlite3.connect('agriculture.db') c=conn.cursor() c.execute('SELECT survey_no,name,area,district,phone FROM land_records') data = c.fetchall() return data print(read_from_db())
994,605
3c64c0fd0237bb995916fcdf70428c5c4246119d
from typing import List, Tuple from constants import UTF_8 INPUT_FILE_NAME = "ferry_directions.txt" class Boat: def __init__(self): self.x = 0 self.y = 0 self.waypoint_x = 10 self.waypoint_y = 1 def north(self, delta: int): self.waypoint_y += delta def south(self, delta: int): self.waypoint_y -= de...
994,606
47e424c3c11bc88f65c883d9127203492b5eb29e
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: de...
994,607
fc5d112fe7b718b469b8e67b011c007ca0960e55
#!/usr/bin/env python # -*- coding:utf-8 -*- # 将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。 n = int(input('请输入一个正整数:')) temp = [] while n!=1: for i in range(2,n+1): if n%i == 0: temp.append(i) n = int(n/i) break print(temp)
994,608
8a55d4aab9678915b89477c58df7dc0371f29565
import os.path import pandas as pd def ERCC(): ercc = pd.read_table(os.path.dirname(__file__) + '/ERCC.tsv', index_col=1) return ercc def reference_templates(): ''' Get XML templates to query Biomart with. ''' with open(os.path.dirname(__file__) + '/template_transcriptome.xml') as fh: t...
994,609
42b582db035d367e4b9c6451a7bc9510d8de5967
for i in range(5): for j in range(5): print("({}, {})".format(i, j), end ="\t") print() # R U L D dx = [0, -1, 0, 1] dy = [1, 0, -1, 0] x, y = 1, 1 #data = list(map(str, input().split())) data = 'R R R U D' print(data) for val in data: if(val == 'R'): y += dy[0] elif (val == 'U'...
994,610
545e1b3aa4f590593d8a800f097a2462a7d1f1e6
# -*- coding: utf-8 -*- import rpy2.robjects as robjects from rpy2.robjects import r pi = robjects.r['pi'] pi[0] pi.r_repr() # pi é o objeto do R # pi[0] é o valor # >>> pi # >>> <FloatVector - Python:0x101ae2710 / R:0x1039724e8> # >>> [3.141593] robjects.r.ls(globalenv) robjects.globalenv["a"] = 123 print(robject...
994,611
b7275199675360bd5566c9de15f4d1688b57a21c
#!/usr/bin/python def reverse(a): return ''.join(reversed(a)) s = "Hello" print s, "reversed is", reverse(s)
994,612
c4b1f35249a64ad8d7bb961ec7958e61942522a4
# client.py import socket s = socket.socket() host="192.168.20.25" port = 8080 s.connect((host, port)) f=open("test1.bin", "w") while True: read_len=0 buf={} buf2=bytes() print("2222222222 ") for i in range (1, 9): buf[i]=s.recv(512) read_len += len(buf[i]) if len(buf[i]) == 0: ...
994,613
bb8d3c8cda2185623cbbf1791f6cadc50a41efe1
import cv2 import numpy as np weights = r'/Users/upasanathakuria/Desktop/People-Counting-in-Real-Time/Detectx-Yolo-V3/yolov3.weights' config1 = r'/Users/upasanathakuria/Desktop/People-Counting-in-Real-Time/Detectx-Yolo-V3/cfg/yolov3.cfg' class_labels = r'/Users/upasanathakuria/Desktop/People-Counting-in-Real-Tim...
994,614
b1ed56f695ad398d3e27bfd71d524be250751ab8
from core.interfaces.phylogenymodel import PhylogenyModel from core.phylogeny.graphs.ramresidentgraph import RAMResidentGraph class DAGModel(PhylogenyModel): def __init__(self,threshold): self.threshold = threshold def create(self,malwarecorpus,fingerprintfactory,distancemetric): self.RRG ...
994,615
9ff74f4d3f1b0dc3ec4a4f9b9ada3864df22e465
#!/usr/bin/env python3 #Session 2 Class excercise #print grid like this print("Please make a script generating grid like this.") print(""" + - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - + | | | | | | | ...
994,616
afbda4fd872c22ee0b088cc96c8b7dedc15b590d
def hangaroo(secretWord): print('Hangaroo') print('Guess the word that is', len(secretWord),"letters long.") mistakesmade = 0 lettersGuessed = [] while 8 - mistakesmade > 0: if isWordGuessed(secretWord, lettersGuessed) == True: print('============') print('Con...
994,617
42d6ff59128f8931202dd53cde0df8bf275e0472
while True: numb = input("Give me a number: ") if numb.isdigit(): print (float(numb)**2) break else: print("Invalid")
994,618
bdb738c4fff7530ae7bde52d55a8cdccf70e9216
##teste unitário de CSV externo # 1 - imports import json import pytest import csv import requests from requests import HTTPError # Leitor do Arquivo CSV def ler_dados_do_csv(): teste_dados_csv = [] nome_arquivo = 'usuarios.csv' try: with open(nome_arquivo,newline='') as csvfile: d...
994,619
a290b2cb0e14a9d563bef668073dbd102f72c2b6
# coding: utf-8 # # Ámbitos y funciones decoradoras # #### NOTA: Antes de realizar esta lección debes reiniciar Jupyter Notebook para vaciar la memoria. # In[4]: def Hola(): number = 89 def Bienvenido(): return ("Welcome") print(locals()) return Bienvenido() Hola() pri...
994,620
f8b37d787f1d1bc25dd868f3200f5a3b301c27b7
# -*- coding: utf-8 -*- # import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from original_tools import plot if __name__ == "__main__": # データ読み込み...
994,621
eefc7dc432a8d8193f4bd71e710105b36a48517e
from setuptools import setup, find_packages setup( name="nate", version="0.0.1", install_requires=[ "pandas>=0.25.0", "spacy", #"python-igraph>=0.8.0", "tok", "numba", "joblib", "matplotlib", "networkx", "pillow", "stop_word...
994,622
2682a6abd23c26479fda626e199cc673930a3db2
VERY SIMPLE Python solutions (iterative and recursive), both beat 90% https://leetcode.com/problems/balanced-binary-tree/discuss/35708 * Lang: python3 * Author: agave * Votes: 67 ``` class Solution(object): def isBalanced(self, root): def check(root): if root is None: ...
994,623
4d4d1c218a38190eebe0a78db0c421f35243f56b
class SizeNormalization: def __init__(self, p=None): self.id = None self.effective_date = None self.value = None # cost per unit of energy self.note = None self.account_id = None if p is not None: if "id" in p: self.id = p["id"] ...
994,624
684f16f1284c281e4ee86fd7393ef84307853307
"""Perform beam search on a decoder rnn with head layer""" import torch from torch import nn import numpy as np import torch.nn.utils.rnn as p pack = p.pack_sequence def sample_beam(model, input_embedding, char2idx, idx2char, k=5, maxlen=30, start='START', use_head=True): """Sample using beam sea...
994,625
41bb6c3469c370a68f6e065f1c81bc0f8473ecf7
import unittest from botoflow.decisions import decision_list, decisions class TestDecisionList(unittest.TestCase): def test_delete_decision(self): dlist = decision_list.DecisionList() dlist.append(decisions.CancelTimer(123)) self.assertTrue(dlist) dlist.delete_decision(decisions.C...
994,626
2244cfaf52eb15869292124caac7ae22a0e7519f
import os def deleteBigFiles(max_size): file_list = [f for f in os.listdir() if os.path.isfile(f)] for f in file_list: filesize = os.stat(f).st_size if filesize > max_size: os.remove(f) # print(f'filename: {f} \n file size: {filesize} \n current working directory: {os.ge...
994,627
a403c7b3cf20a2efb3c7846dea60ac5d26c693b7
import os import random import json5 import numpy as np import tensorflow as tf from datetime import datetime from pprint import pformat from .utils.loader import load_data from .utils.logger import Logger from .utils.params import validate_params from .model import Model from .interface import Interface class Trainer...
994,628
dddfcce25745324551bd42c471489b2120ceaec2
import pytest from .. import get_translator from ..translators import TranslationError def test_translation_smoke(): """Translating to morse and back to english should yield the same string in upper case""" english_to_morse = get_translator("english", "morse") morse_to_english = get_translator("morse"...
994,629
9f3a6154eae1d7a02071b32a54f12f2115f4f1da
import argparse import pandas as pd from mlp import KerasDenseMLP from data import DataProcessor parser = argparse.ArgumentParser() """ Define the necessary parameters for running the neural network The number of epochs is not required """ parser.add_argument( "-n", "--neurons", nargs="+", help="Number of ...
994,630
6b63c8bea00523e4f5897088cdf512d889912fce
import bson import click import itertools import logging import pendulum import requests from concurrent.futures import ThreadPoolExecutor from pprint import pprint def iter_date( start_date: pendulum.datetime, end_date: pendulum.datetime, chunk_size=59 ): if end_date < start_date: raise ValueError( ...
994,631
1688cdb0c379f73902a19e6b18e1703bf9530407
# -*- coding: utf-8 -*- """ Created on Tue Apr 05 23:08:50 2016 @author: Nandini Bhosale """ from scipy import linspace,exp from scipy.optimize import fsolve from scipy.integrate import odeint,trapz import random from pylab import plot,show,subplot,figure """PI Controller for cstr""" Fis=2.0 Cais=2.0 ...
994,632
22a2cfed5dacae73f6088e868acc73aa02a57429
from django.urls import path from . import views urlpatterns = [ path('<int:dijete_pk>/novo/', views.NapredakCreateView.as_view(), name="stvori-napredak"), ]
994,633
70be6b382a022645c50a3095a1e39d0e20b32c89
#! /usr/bin/python3 from io import StringIO import os, sys import unittest from unittest.mock import patch, MagicMock from .services import Services from .models import Code path = os.path.dirname(__file__) if path not in sys.path: sys.path.insert(0, path) class TestServices(unittest.TestCase): def setUp(sel...
994,634
bbcea5db2d94ac442074591d186270cb6e2a877b
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from ..core import variables from ..core.kernel import Kernel class KernelMix(Kernel): def __init__( self, kernel_list, normalization = tf.nn.s...
994,635
8b75cd2d47ae1b19766390b99157a645070afcaa
from collections import namedtuple, defaultdict import pandas as pd import numpy as np import pdb import re day_re = re.compile('.*Day\s(\d+).*') assign_re = re.compile('.*Assign.*\s(\d+).*') mid_re = re.compile('.*Mid.*Combi*') def make_tuple(in_dict,tupname='values'): """ make a named tuple from a dictiona...
994,636
31cc385049f28eb5868bbf196b467e5da7ea4ceb
class Solution(object): def removeInvalidParentheses(self, s): """ :type s: str :rtype: List[str] """ # if not s: # return [""] rm_l, rm_r = self.min_rm_paren(s) res = set() self.dfs(res, [], 0, s, rm_l, rm_r, 0) return list(res) ...
994,637
3251cabc21583e701d9dbd4c5681411a79cec486
import gym import numpy as np import minerl import torch import warnings import os import traceback from stable_baselines3.common.utils import get_device from minerl.data import BufferedBatchIter class DummyEnv(gym.Env): """ A simplistic class that lets us mock up a gym Environment that is sufficient for our p...
994,638
7b5ed4cb102e512fff8f8b6b27112c9b50fa4f8b
'''DNA object classes.''' import collections import os import re import shutil import subprocess import tempfile import coral.analysis import coral.reaction import coral.seqio from ._sequence import process_seq, reverse_complement from ._sequence import NucleotideSequence class DNA(NucleotideSequence): '''DNA seq...
994,639
50845c1864c535ee49987719313cc05f6fc96d92
# ============================================================================= # protocol # # Copyright (c) 2014, Cisco Systems # All rights reserved. # # # Author: Klaudiusz Staniek # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following condit...
994,640
a8436cfc5e85bec088b3547c810c801178d717f8
is_has_name = True name = 'Nax' if is_has_name else 'Empty' print(name) IS_ONE = False number = 1 if IS_ONE else 2 print(number) word = 'слово' result = [] for i in range(len(word)): # if i % 2 != 0: # letter = word[i].lower() # else: # letter = word[i].upper() # letter = word[i].low...
994,641
0970ccdc0ea116a50b973a526e5bacfc0879141c
import numpy as np from root_regula_falsi import * osf1 = 14.621 T1 = 0.0 osf2 = 6.413 T2 = 40.0 def calc_osf(T): Ta = T + 273.15 arg = -139.34411 + 1.575701e5/Ta - 6.642308e7/Ta**2 + 1.2438e10/Ta**3 - 8.621949e11/Ta**4 return np.exp(arg) def solve_for_T(osf): def f(T): Ta = T + 273.15 ...
994,642
27145aaf63510bf85766b68af3fcab5d5c9249a0
# coding = <utf-8> """ 버튼 위젯 (ref) https://youtu.be/bKPIcoou9N8?t=526 """ import os import os.path as osp from tkinter import Tk, Button, PhotoImage root = Tk() root.title("My GUI") btn1 = Button(root, text="버튼1") # 버튼 객체 초기화 btn1.pack() # mainloop() 에 버튼이 표출되도록 함 btn2 = Button(root, padx=5, pady=10, text='버...
994,643
c4eeb5319ba47e9d4fef2211d1ed64d5285491fb
# Generated by Django 3.2.5 on 2021-09-02 17:15 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('LeaveApp', '0014_auto_20210902_1249'), ] operations = [ migrations.RenameField( model_name='leaverequest', old_name='cancel_...
994,644
513309d5680748632747529766a69a6c659b7b57
import aioredis from aioredis import Redis from excars import config async def setup(): return await aioredis.create_redis_pool( config.REDIS_HOST, db=config.REDIS_DB, minsize=config.REDIS_POOL_MIN, maxsize=config.REDIS_POOL_MAX ) async def stop(redis_cli: Redis): redis_cli.close() await re...
994,645
373ee3dab8ce61b9034522442bdbd6565cf9c424
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Exibe varios padroes de contadores. @author: Prof. Diogo SM """ contador = 0 print("10 iteracoes com passo 1") while contador < 10: print(contador, end=" ") contador += 1 print() contador = 0 print("11 iteracoes com passo 1") while contador <= 10: ...
994,646
e64b53e1bbbd9f769e9da049bab02bca115b4321
import fnmatch thing = cmds.ls(sl=True) getProject = cmds.workspace(expandName = 'relativePathName') getAssetPath = getProject.split('build/') getAssetName = getAssetPath[1].split('/m') fullPath = (getAssetPath[0] + 'build/'+ getAssetName[0] + '/m_model/textures/wip/hi/') refs = cmds.ls(type='reference') refs.remove...
994,647
db93a7dd105430524758263e560d12ea86177356
FollowedUserNames={'UserName': 'UserName', 'Date': [0, 0, 0]},{'UserName': 'lilarshiaw', 'Date': [2020, 7, 5]} , {'UserName': 'nafc102030', 'Date': [2020, 7, 5]} , {'UserName': 'amir71304', 'Date': [2020, 7, 5]} , {'UserName': 'reza._.zomorodiii', 'Date': [2020, 7, 5]} , {'UserName': 'amir_h_keshavarziyan', 'Date': [20...
994,648
9281907334138a7c6722c2bd62a105ec0e493c09
from moviepy.editor import concatenate_videoclips, VideoFileClip def concatenate(video_clip_paths, output_path, method="compose"): """Concatenates several video files into one video file and save it to `output_path`. Note that extension (mp4, etc.) must be added to `output_path` `method` can be either 'co...
994,649
61aa122acf7db61958d4b43db9f308f381aef736
import scipy.io as sio from function import * mat_content = sio.loadmat('HW3Data.mat') Vocabulary = mat_content['Vocabulary'] XTrain = mat_content['XTrain'].toarray() yTrain = mat_content['yTrain'].flatten() XTest = mat_content['XTest'].toarray() yTest = mat_content['yTest'].flatten() XTrainSmall = mat_content['XTrain...
994,650
130ec6f4858412ae092da706d3070b27929e43d2
#!/usr/bin/env python import os import sys from distutils.util import subst_vars from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS from meta import DIST_META_KEYS, import_dist_meta, get_py_version from errors import LocationError, MetadataError __all__ = [ 'FREEZE_SCHEME', 'SCHEME_KEYS', ...
994,651
6f000c9944026d6d3107e21aa20463e6ad286bb5
#!/usr/bin/env python import paramiko import sys, os, string, threading #user-selected command cmd = "w" def command(host): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(host, username='ubuntu', password='PASSWORD') stdin, stdout, stderr = ...
994,652
5857bf5fc665db1badc113863e98e57f9ea952b7
# # Задание - 1 # # Создайте функцию, принимающую на вход Имя, возраст и город проживания человека # # Функция должна возвращать строку вида "Василий, 21 год(а), проживает в городе Москва" # names = input('В ведите имя: ') ages = input('В ведите возраст: ') city = input('В ведите город: ') def messege( name , ages , c...
994,653
25a9790d8c4f343d7a64d54cbda6af01164eec0d
""" 【问题描述】从键盘输入非0整数,以输入0为输入结束标志,求平均值,统计正数负数个数 【输入形式】 每个整数一行。最后一行是0,表示输入结束。 【输出形式】 输出三行。 第一行是平均值。第二行是正数个数。第三行是负数个数。 【样例输入】 1 1 1 0 【样例输出】 1 3 0 """ nums = [] zheng = 0 fu = 0 while True: number = int(input()) if number == 0: break else: nums.append(number) for i in range(nums....
994,654
9d267c6af3b242e53dab0c4699dfbf22fef90d33
#!python # \author Hans J. Johnson # # Now that all supported compilers simply # use exactly one function signature (i.e. # namely the one provided in the std:: namespace) # there is no need to use the vcl_ aliases. import os import sys from collections import OrderedDict if len(sys.argv) != 2: usage = r""" INCOR...
994,655
c49da458c86dd66d1912c3d6e6e9b45a124fc7ee
from utils import * """ Data completeness audit object in a form of a callback for SAX content handler. This audit class checks compliance to gold standard. The nonconformities can be requested after parsing. This audit is only applied to elements which has a tag element child with k = amenity and v = pharmacy """ cl...
994,656
030e02a7572f4c994238033b678023bbd2f21692
import numpy as np from neural_network_3 import * import matplotlib.cm as cm import matplotlib.pyplot as plt import time from itertools import cycle import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import os from visualize_weights import visualize_weights def get_sorted_f...
994,657
30738df38a9093be5044f832fc555a991c9a663e
from tkinter import * def save_info(): firstname_info = firstname.get() lastname_info = lastname.get() age_info = age.get() print(firstname_info,lastname_info,age_info) file = open("user.txt","w") file.write("Your First Name " + firstname_info) file.write("...
994,658
db41b2bc968a4b410259fe97257d56cab3a6b56d
#!/usr/bin/env python # encoding: utf-8 """ @Author: Beam @Mail:506556658@qq.com @file: server_socket.py @time: 2017/4/15 11:07 """ import socket class Socket(object): def __init__(self): self.sock = socket.socket() #实例化socket对象sock self.sock.bind(('127.0.0.1',36969)) #绑定监听端口 self...
994,659
a4c086d25e1e03fb79f7521d5dbc5f39020a5bdb
class Error(Exception): '''Base class for exceptions in this module.''' pass class ColorError(Error): '''Exception raised for invalid color value given for a GridSquare''' def __init__(self, valuegiven): self.valuegiven = valuegiven self.message = 'ColorError: Expected white, light gra...
994,660
6c9ba2964ece991219405f481301952270fc9306
class Device: def __init__(self, id=None, token=None, platform=None, endpoint=None, created_at=None, updated_at=None): self.id = id self.token = token self.platform = platform self.endpoint = endpoint self.created_at = created_at self.updated_at = updated_at
994,661
2e29196f5b76ded93de194295d7efdedc1372ba4
import pandas as pd data = pd.read_json('/Users/minhdam/PycharmProjects/test/visualization/visualization/spiders/Output/vnexpress.txt', lines=True) data.to_csv('/Users/minhdam/PycharmProjects/test/visualization/visualization/spiders/Output/sosanhgia.csv', encoding='utf8')
994,662
08c6fe7beaba702ed152c7cc0d7c9663c56433c9
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from hwt.code import If from hwt.interfaces.utils import addClkRstn from hwt.synthesizer.param import Param from hwtHls.hls import Hls from hwtHls.platform.virtual import VirtualHlsPlatform from hwtLib.samples.statements.ifStm import SimpleIfStatement class SimpleIfSta...
994,663
583b8ce9327143be3dfebe42593471d3b3b498d7
import pytest from delphin.eds import EDS, Node, from_mrs, EDSWarning from delphin.mrs import MRS, EP, HCons @pytest.fixture def dogs_bark(): return { 'top': 'e2', 'nodes': [Node('e2', '_bark_v_1', type='e', edges={'ARG1': 'x4'}), Node('_1', 'udef_q', edges={'BV': 'x4'}), ...
994,664
9670afc11883311278dff3f78990ba6549c6a1fa
import logging from pyramid.config import Configurator from pyramid.view import view_config from hackohio.mood import Mood from hackohio.secrets import get_secret from hackohio import soundcloud from pyramid.response import Response logger = logging.getLogger(__name__) def main(global_config, **settings): config ...
994,665
45b06dc84ee1b31a870f3ac345f02c6fcb3ad70e
""" The Tribonacci sequence Tn is defined as follows: T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. Given n, return the value of Tn. Input: n = 4 Output: 4 Explanation: T_3 = 0 + 1 + 1 = 2 T_4 = 1 + 1 + 2 = 4 """ # Solution 1 : Memoization class Solution: memo = {0:0, 1:1, 2:1} def tri...
994,666
e1fbdf8372d5f6c2e2e4dac21cca250f1d91af32
from flask import Blueprint bp = Blueprint('message', __name__) @bp.route('/twiml/message/', methods=['POST']) def message(): pass @bp.route('/twiml/message/fallback/', methods=['POST']) def message_fallback(): pass @bp.route('/twiml/message/status/', methods=['POST']) def message_status(): pass
994,667
d7ae76a1f4c06b419811e337959fe19a5ad4ca69
from rest_framework import serializers from curricula.models import LearningLectureStat, LearningLecture, LearningLectureVideo, LearningLectureLiveScribe, LearningLectureText, LearningLectureYoutube from .lecture_content import LearningLectureLiveScribeSerializer, LearningLectureVideoSerializer, LearningLectureTextSeri...
994,668
f41d21c57ae038c17a3ea22dc6dd1362f371d0dc
from typing import Any, Callable, Iterator, TypeVar O = TypeVar('O') T = TypeVar('T') def callUnpacked(predicate: T) -> Callable[[Iterator[Any]], O]: return lambda it: predicate(*it)
994,669
f8a7b4eaed877156e252ec7a3eb327f1c73becab
from datetime import datetime, timedelta from fitcompetition.withings import WithingsService from local_settings import WITHINGS_PASSWORD, WITHINGS_USER_NAME from dateutil.relativedelta import relativedelta from django.contrib.auth.decorators import login_required from django.db.models import Q, Count, Sum from django...
994,670
030ae54b870342a9b5a1452c2540ef37110dce37
#coding = utf-8 import sys,os sys.path.append(os.path.dirname(os.getcwd())) from elasticsearch import Elasticsearch from common import common_log class ElasticObj: def __init__(self, index_name,index_type,ip='127.0.0.1'): self._info = common_log.Common_Log() ''' :param index_name: 索引名称 ...
994,671
873ff11674da8ef0b095f3d5b9ee209b7a90681d
from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.hashers import check_password from accounts.models.user import User from django.conf import settings import json from rest_framework.response import Response from rest_f...
994,672
46594104cd3b99bd91a50979626ed5bdd810bac7
# 给定一个整数数组 asteroids,表示在同一行的行星。 # # 对于数组中的每一个元素,其绝对值表示行星的大小,正负表示行星的移动方向(正表示向右移动,负表示向左移动)。每一颗行星以相同的速度移动。 # # 找出碰撞后剩下的所有行星。碰撞规则:两个行星相互碰撞,较小的行星会爆炸。如果两颗行星大小相同,则两颗行星都会爆炸。两颗移动方向相同的行星,永远不会发生碰撞 # 。 # # # # 示例 1: # # # 输入:asteroids = [5,10,-5] # 输出:[5,10] # 解释:10 和 -5 碰撞后只剩下 10 。 5 和 10 永远不会发生碰撞。 # # 示例 2: # # # 输入:asteroid...
994,673
8027242147f4a535da0b7ffa8caef8d90acb9f76
import sys import numpy as np import matplotlib.pyplot as plt from scipy import optimize from util.my_math_utils import * from sequences.viterbi import viterbi from sequences.forward_backward import forward_backward,sanity_check_forward_backward import sequences.discriminative_sequence_classifier as dsc class CRF_bat...
994,674
469c9bd9bb443eb5b8a47f93a150b11f1521a24e
''' Trains a simple convnet to recognise a smile ''' from __future__ import print_function from os.path import exists import keras from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, BatchNormalization from keras.layers import Conv2D, MaxPooling2D, Activation, SeparableConv2D, Globa...
994,675
0f3b659f2c025fe1bc9d26619d3e26a6be7873d3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import fritzconnection as fc from datetime import timedelta import click ADDRESS = 'fritz.box' PASSWORD = '' # print header print(''' ______ _ _ | ____| (_) | | |__ _ __ _| |_ ____ | __| '__| | __|_ / | | | | | | |_ / / |_| |_| |_|\__/___| ''') @cl...
994,676
a099a8d0610786d24f52cd6289033938d096d358
import copy class Graph(): def __init__(self, nodes): self.nodes = nodes def add_edge(self, from_, to): self.nodes[from_].adjecent.add(to) self.nodes[to].adjecent.add(from_) def print_graph(self): for vertex in self.nodes: for adj in vertex.adjecent: ...
994,677
06f8199272fea7285ea83a5aabc320b6ae907c2e
class Node(object): """A node in a tree""" def __init__(self, data, children=None): self.data = data if children is None: self.children = [] else: self.children = children def __repr__(self): """Reader-friendly representation.""" return "<No...
994,678
f3155c5030e80ee0841f7e365cc740fff221f591
from utils import SupplyResult, clean_after_module from utils.tech import get_dev_channel subreddit = 'all' t_channel = get_dev_channel() def send_post(submission, r2t): total_size = clean_after_module() r2t.send_text('Deleted: ' + str(round(total_size / (1024.0 ** 3), 3)) + 'GB.') return SupplyResult.S...
994,679
30b74c08404237670c83400f1cb0314070a97573
#!/usr/bin/env python # Load required modules import matplotlib matplotlib.use('Agg') import sys, os, argparse, pandas as pd, numpy as np import seaborn as sns, matplotlib.pyplot as plt from sklearn.externals import joblib sns.set_style('whitegrid') # Load mutation signatures visualizations this_dir = os.path.dirname...
994,680
797bc00dfb029400265e57f6168a00682bcf60c1
import json from model.models import User, Dialog from util.datetime_utils import DateTimeUtils class UpdateHistoryManager(object): def __init__(self, dialogs_holder): self.dict_of_users_updates = dict() self.dict_of_users_histories = dict() self.dialogs_holder = dialogs_holder def on...
994,681
04ea0e28afeb9e413de5b8606034893fdd6ce50e
#!/usr/bin/python #script to read in a matcher generated pdb file, figure out the catalytic sidechains, and carry out some basic python commands from pymol import cmd from pymol import util def showdes(desname=None): loaded_objs = cmd.get_names('objects') print loaded_objs if desname == None and n...
994,682
b731d9a3514cfff115f84a2114305872d851a63c
def bath(a,b): count = 0 d = 0 c = 1/2 while b>0: d += c c *= 2 b = b//2 count += 1 return int(d),c for i in range(1,int(input())+1): N,K = map(int,input().split()) de, num= bath(N,K) lis = [(N-de)//int(num)]*int(num) sumi = sum(lis) df = N-de-sumi for j in range(int(df)): ...
994,683
aa09b3e34c941b58b72224b4bbb92bcfe5c34af9
from datetime import datetime from odoo import fields, models class TransactionHistory(models.Model): _name = 'transaction.history' _description = 'book transaction' transaction_id = fields.Many2one('transaction') name = fields.Char(related='transaction_id.name', store=True) date = fields.Date()...
994,684
979201f7a6da2738a899128c15f209d8dd5627b8
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
994,685
42e14747529c7e2a454d4e505e5cc0f8a765cf85
import numpy as np from time import time from .. import func as Z from .. import metric as metric_module from .. import optim from .data.dataset import Dataset from .data.ram_dataset import RamDataset from .data.training_data import TrainingData from . import hook as hook_module from .hook import Hook def _unpack_tr...
994,686
5c4e0d89b447b70f220216494f2da8f88a8d1ca8
from django.db.models import Manager from utils.db.query import GetOrCreateQuery, ObjectExisting class ResourceProviderManager(Manager): def get_or_create_by_name(self, name): if name is None: return ObjectExisting(None, False) return GetOrCreateQuery(self.model).get_or_create(name=n...
994,687
384ab242cd3783049d2f37cb8d2ac5ac9a6d285e
from src.main.MainApplication import MainApplication from src.utils.ClientUtils import create_new_client from src.utils.Utils import clear_all_input, load_record, update_client_list, validate_input from src.logic.AbstractPackingInvoice import AbstractPackingInvoiceClass from utils.logger import log class Packing(Abst...
994,688
db47f2d8f1ba3b41d609874a000bffe2804e9239
from jesse.strategies import Strategy # test_on_reduced_position class Test18(Strategy): def should_long(self): return self.price < 7 def go_long(self): qty = 2 self.buy = qty, 7 self.stop_loss = qty, 5 self.take_profit = [ (1, 15), (1, 13) ...
994,689
43ed6dee07863168140a9b10a2d2109e85489b2a
def input(): return [item.rstrip('\n').split(',') for item in open("input.txt", 'r')] def output(item): open("output.txt", 'w').write(str(item)) def run(data): l1, d1 = makeLines(data[0]) l2, d2 = makeLines(data[1]) con = [] x1 = 0 x2 = 0 y1 = 0 y2 = 0 for i in range(1,len(l1)...
994,690
7b8892bc8a3d67078526d838a8ba1b022b46b174
""" locale.py part of chipFish handles and loads the localisation.txt file. chipFish then looks up (by string) in what is essentially a huge dictionary of language data. """ import sys, os from wx import xrc supported_languages = frozenset(["en-gb"]) language_map = {"en-gb": "Enlish (UK)", "en-us": "English (No...
994,691
dd7d4e4a50bce5ade5f9716b4cda15ad9b608538
''' update the 'earnings_announcement' field on all Ticker objects, using expected earnings report dates retrieved from Moosie's API ''' import urllib import json import datetime import requests from django.conf import settings from django.core.management.base import BaseCommand, CommandError from requests.auth import...
994,692
23c877dc5747494c4ba7246493f10cbab3da9f35
import unittest import subprocess import pexpect import sys import re from tests.base import GraderBase class Part1(GraderBase) : def test_word_is_not_palindrome(self) : '''Testing a non-palindrome word''' with self.run_test(__name__ + ".prog5", 'word', timeout=1) as test : test.s...
994,693
204dca3b13cc644bd643a138b093da599882ab1b
##Simplified battle-ship game in python language from random import randint import getpass def user_mode(): user_mode=int(input("Choose 1 for single player and 2 for two player game: ")) while True: if user_mode == 1 or user_mode == 2: True break else: print("Invalid user input. Please ch...
994,694
03907a98f8e397a0edbf57b573fabcdaf40da10c
import paho.mqtt.client as mqtt import ssl rootca = r'D:\\Sakshi\\programs\\aws\\machine6_aws\\AmazonRootCA1.pem.txt' certificate = r'D:\\Sakshi\\programs\\aws\\machine6_aws\\098be122db-certificate.pem.crt' key_file = r'D:\\Sakshi\\programs\\aws\\machine6_aws\\098be122db-private.pem.key' c = mqtt.Client() c...
994,695
cfc7cc5a98e048d4ebc2b268e6fe6de77772b511
""" .. versionadded:: 0.6.2 Module for converting/creating ``serpentTools`` objects to/from other sources High-level functions implemented here, such as :func:`toMatlab`, help the :ref:`cli` in quickly converting files without launching a Python interpreter. For example, .. code:: $ python -m serpentTools -v to...
994,696
33c65c011eb1b7dbcbd081d530a07ea6dba35898
import sys import math import numpy as np import matplotlib.pyplot as plt import cv2 import skimage.morphology as morphology def tiger_process(filename): source0 = cv2.imread(filename) img = source0[:, :, ::-1] # computed from blur Radius of 3 and stackoverflow: https://stackoverflow.com/questions/21984405/relation...
994,697
0ca1a34e372bf5c4fb314a7f0e84e752482b3324
def raizQuadrada(a): import math return math.sqrt(a)
994,698
bcd02749e856a94009cf8c970b05674a5adc41ce
from PyQt5.Qt import * # 包含一些常用类的汇总 import sys # 1. 创建一个应用程序对象 app = QApplication(sys.argv) # sys.argv接受外部参数 # 2. 控件的操作 # 2.1 创建控件 window = QWidget() # 2.2 设置控件 window.resize(500, 500) # 设置窗口标题名称 window.setWindowTitle("顶层窗口设置") print(window.windowTitle()) # 获取窗口标题文本 # 设置窗口图标 icon = QIcon('ooo.png') window.s...
994,699
cba852340b78b12253f21db4a08074edb3968ecf
# Generated by Django 3.0.8 on 2020-08-18 21:34 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('team', '0003_auto_20200819_0137'), ] operations = [ migrations.CreateModel( ...