index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
900
502e0f0c6376617dc094fcdd47bea9773d011864
def filter_lines(in_filename, in_filename2,out_filename): """Read records from in_filename and write records to out_filename if the beginning of the line (taken up to the first comma at or after position 11) is found in keys (which must be a set of byte strings). """ proper_convert = 0 missing_...
901
a17abd3947a946daf2c453c120f2e79d2ba60778
# 赛场统分 # 【问题】在编程竞赛中,有10个评委为参赛的选手打分,分数为0 ~ 100分。 # 选手最后得分为:去掉一个最高分和一个最低分后其余8个分数的平均值。请编写一个程序实现。 sc_lst = [] i = 1 while len(sc_lst) < 10: try: sc = int(input('请第%d位评委打分:' % i)) if sc > 0 and sc < 101: sc_lst.append(sc) i += 1 else: print('超出范围,输入无效') ex...
902
04670041dab49f8c2d4a0415030356e7ea92925f
from tempfile import mkdtemp from shutil import rmtree from os.path import join import os MAX_UNCOMPRESSED_SIZE = 100e6 # 100MB # Extracts a zipfile into a directory safely class ModelExtractor(object): def __init__(self, modelzip): self.modelzip = modelzip def __enter__(self): if not self._...
903
cf3b66a635c6549553af738f263b035217e75a7a
count=0 def merge(a, b): global count c = [] h = j = 0 while j < len(a) and h < len(b): if a[j] <= b[h]: c.append(a[j]) j += 1 else: count+=(len(a[j:])) c.append(b[h]) h += 1 if j == len(a): for i in b[h:]: ...
904
d2298ad1e4737b983ba6d1f2fff59750137510b5
import json import os import uuid from django.core.files.uploadedfile import SimpleUploadedFile from django.conf import settings from django.contrib.contenttypes.models import ContentType from nautobot.dcim.models import Site from nautobot.extras.choices import JobResultStatusChoices from nautobot.extras.jobs import ...
905
48f2cc5b6d53c7317ad882947cabbc367cda0fb7
import random import numpy as np import pandas as pd def linear_combination_plus_error(X, num_dependent_cols=5, parameter_mean=0, parameter_std=1, error_mean=0, error_std=1): """ Generate a column that is a random linear combination of X1, X2 and X3 plus some random error """ length = X.shape[0] ...
906
6ae529a5e5658ba409ec3e7284d8b2911c60dd00
import os from linkedin_scraper import get_jobs chrome_driver_path = os.path.join(os.path.abspath(os.getcwd()), 'chromedriver') df = get_jobs('Data Scientist', 40, False, chrome_driver_path) df.to_csv('linkedin_jobs.csv', index= False)
907
d268f8d563aac28852457f6f130b2fb4ea6269a2
import nltk from nltk import bigrams from lm import * # Oppgave 1: # opretter LM klasse til aa perpleksitere news og adventure m = LM() # Henter news og adventure for videre bruk news=nltk.corpus.brown.sents(categories='news') adventure=nltk.corpus.brown.sents(categories='adventure') # initial parametre perpNews = 0...
908
2f489a87e40bea979000dd429cc4cb0150ff4c3b
from flask import escape import pandas as pd import json import requests with open('result.csv', newline='') as f: df = pd.read_csv(f) def get_level_diff(word, only_common=False): if only_common: word_df = df[(df['word']==word) & (df['common']==1)] else: word_df = df[df['word']==word] ...
909
7a65a5522db97a7a113a412883b640feede5bcee
from layout import UIDump import Tkinter from Tkinter import * from ScriptGenerator import ScriptGen class Divide_and_Conquer(): def __init__(self, XY): self.XY = XY self.user_val = 'None' self.flag = 'green' print self.XY def bounds_Compare(self, bounds, filename): """ Compares the bounds with Master...
910
7ce679d5b889493f278de6deca6ec6bdb7acd3f5
#Author: Abeer Rafiq #Modified: 11/23/2019 3:00pm #Importing Packages import socket, sys, time, json, sqlite3 import RPi.GPIO as GPIO from datetime import datetime, date #Creating a global server class class GlobalServer: #The constructor def __init__(self, port, room_ip_addrs, app_ip_addrs):...
911
08a5a903d3757f8821554aa3649ec2ac2b2995a5
/Users/tanzy/anaconda3/lib/python3.6/_dummy_thread.py
912
09d31df9c76975377b44470e1f2ba4a5c4b7bbde
import sys import logging import copy import socket from . import game_map class GameUnix: """ :ivar map: Current map representation :ivar initial_map: The initial version of the map before game starts """ def _send_string(self, s): """ Send data to the game. Call :function:`done_...
913
891588327046e26acb9a691fa8bb9a99420712d6
from django.conf.urls import url, include from django.contrib import admin from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='Pastebin API') urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^doc_u/', schema_view), url(r'^', include('o.urls', )), url(...
914
a6f3c51d4115a6e0d6f01aa75bf5e6e367840d43
from typing import (Any, Callable, Dict, List, Optional, Set, Tuple, Type, Union, overload) from pccm.stubs import EnumClassValue, EnumValue from cumm.tensorview import Tensor class ConvMainUnitTest: @staticmethod def implicit_gemm(input: Tensor, weight: Tensor, output: Tensor, padding: L...
915
0dd361239d85ed485594ac0f5e7e2168f0684544
import pytest import gadget @pytest.mark.parametrize('invalid_line', [ 'beginningGDG::', 'beginning::end', 'nothing', ]) def test_parse_invalid_line(invalid_line): assert gadget.parse_log_line(invalid_line) is None
916
7de19a85a6a05bd2972b11571d5f05219c6beb1a
import os import shutil # root_path = '../from_1691' root_path = 'C:/Users/koyou/Desktop/test' # 실수할 수도 있으므로 dry_run 을 설정해서 로그만 찍을 것인지 # 실제 작동도 진행할 것인지 결정한다. # dry_run = True dry_run = False def move_directory(input_directory_path, output_directory_path): print("moving %s to %s" % (input_directory_path, output_d...
917
c85d7e799a652e82bfaf58e1e8bfa9c4606a8ecb
import ast import datetime from pathlib import Path from typing import Any, Dict import yaml from .lemmatizer import LemmatizerPymorphy2, Preprocessor def get_config(path_to_config: str) -> Dict[str, Any]: """Get config. Args: path_to_config (str): Path to config. Returns: Dict[str, An...
918
73ff1444b5ab1469b616fe449ee6ab93acbbf85a
import time from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtSql import * from PyQt5.QtWidgets import * from qgis.core import QgsFeature, QgsGeometry, QgsProject from shapely import wkb print(__name__) # Function definition def TicTocGenerator(): # Generator that returns time differences ti...
919
4d9575c178b672815bb561116689b9b0721cb5ba
# -*- coding: utf-8 -*- """ Created on Thu Jun 25 15:14:15 2020 @author: luisa """ horast = int(input("Horas Trabajadas: "+"\n\t\t")) tarifa = int(input("Tarifa por hora: "+"\n\t\t")) descu = int(input("Descuentos: "+"\n\t\t")) resp0 = horast - descu resp1 = (resp0 * tarifa)/2 resp2 = (horast * tarifa) ...
920
8479c70fed36dc6f1e6094c832fb22d8c2e53e3a
import os import time from datetime import datetime, timedelta from git import Repo class CommitAnalyzer(): """ Takes path of the repo """ def __init__(self, repo_path): self.repo_path = repo_path self.repo = Repo(self.repo_path) assert not self.repo.bare def get_conflict_commits(self): conflict_commits...
921
a41d00c86d0bdab1bced77c275e56c3569af4f4e
from django.apps import AppConfig from django.conf import settings import importlib import importlib.util class RestAdminAppConfig(AppConfig): name = 'libraries.django_rest_admin' verbose_name = 'Rest Admin' loaded = False def ready(self): autodiscover() def autodiscover(): """ Auto...
922
e0435b0b34fc011e7330ab8882865131f7f78882
import pytest import responses from auctioneer import constants, controllers, entities from common.http import UnExpectedResult def test_keywordbid_rule_init(kwb_rule, account): assert kwb_rule.get_max_bid_display() == kwb_rule.max_bid * 1_000_000 assert kwb_rule.get_bid_increase_percentage_display() == kwb_...
923
66904cbe3e57d9cc1ee385cd8a4c1ba3767626bd
#!/usr/bin/env python # -*- coding: utf-8 -*- # sphinx_gallery_thumbnail_number = 3 import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import NullFormatter # useful for `logit` scale import matplotlib.ticker as ticker import matplotlib as mpl mpl.style.use('classic') # Data for plotting ch...
924
a01ca49c3fa8ea76de2880c1b04bf15ccd341edd
# coding=UTF-8 """ View for managing accounts """ from django.contrib import messages from django.http import Http404, HttpResponse from django.shortcuts import redirect from django import forms from athena.core import render_to_response from athena.users.models import User from athena.users import must_be_admin def...
925
9adff5da4e26088def9f0e32aa712a1f2b0336ba
class Step: def __init__(self, action): self.action = action def __str__(self) -> str: return f'Step: {{action: {self.action.__str__()}}}' def __repr__(self) -> str: return f'Step: {{action: {self.action.__str__()}}}'
926
668a8005f2f66190d588fb9289293d73a608f767
# -*- coding: utf-8-*- import random import re from datetime import datetime, time from phue import Bridge import os import glob WORDS = [] def handle(text, mic, profile): messages1 = ["Naturally Sir ","Of course Sir ","I'll get right at it"] final = random.choice(messages1) mic.say(final) command = "ssh pi@...
927
2257f73a290dfd428a874e963c26e51f1c1f1efa
# -*- coding: utf-8 -*- """The app module, containing the app factory function.""" from flask import Flask, render_template from flask_cors import CORS from flask_misaka import Misaka from flask_mailman import Mail from flask_talisman import Talisman from werkzeug.middleware.proxy_fix import ProxyFix from micawber.pro...
928
d39e3a552a7c558d3f5b410e0b228fb7409d732a
# -*- coding:utf-8 -*- """ Author:xufei Date:2021/1/21 """
929
c18c407476375fb1647fefaedb5d7ea0e0aabe3a
import pandas as pd import numpy as np import csv #import nltk #nltk.download('punkt') from nltk.tokenize import sent_tokenize csv_file=open("/home/debajit15/train+dev.csv") pd.set_option('display.max_colwidth', None) df=pd.read_csv(csv_file,sep=','); df = df[pd.notnull(df['Aspects'])] #print(df['Opinion_Words'].iloc[0...
930
74b0ccb5193380ce596313d1ac3f898ff1fdd2f3
from .mail_utils import send_mail from .request_utils import get_host_url
931
4e1f7fddb6bd3413dd6a8ca21520d309af75c811
import sys import os sys.path.insert(0, "main") import main workspace = os.path.abspath(sys.argv[1]) main.hammer(workspace)
932
db1e3a109af2db2c8794a7c9c7dfb0c2ccee5800
#!/usr/bin/python3 """0. How many subs""" def number_of_subscribers(subreddit): """return the number of subscribers from an Reddit API""" import requests resInf = requests.get("https://www.reddit.com/r/{}/about.json" .format(subreddit), headers={"Us...
933
d20e41dd7054ff133be264bebf13e4e218710ae5
from django.shortcuts import resolve_url as r from django.test import TestCase class coreGetHome(TestCase): def setUp(self): self.resp = self.client.get(r('core:core_home')) def test_template_home(self): self.assertTemplateUsed(self.resp, 'index.html') def test_200_template_home(self): ...
934
ff7a865822a4f8b343ab4cb490c24d6d530b14e1
#!/usr/bin/env python kube_description= \ """ Compute Server """ kube_instruction= \ """ Not instructions yet """ # # Standard geni-lib/portal libraries # import geni.portal as portal import geni.rspec.pg as PG import geni.rspec.emulab as elab import geni.rspec.igext as IG import geni.urn as URN # # PhantomNet ext...
935
a93884757069393b4d96de5ec9c7d815d58a2ea5
# coding: utf-8 import logging import uuid import json import xmltodict import bottle from bottle import HTTPError from bottle.ext import sqlalchemy from database import Base, engine from database import JdWaybillSendResp, JdWaybillApplyResp jd = bottle.Bottle(catchall=False) plugin = sqlalchemy.Plugin( engine, ...
936
0cc1aaa182fcf002ff2ae6cbcd6cbb84a08a3bc1
# Basic script which send some request via rest api to the test-management-tool. # Be sure you setup host and api_token variable import http.client host = "localhost:8000" api_token = "fuukp8LhdxxwoVdtJu5K8LQtpTods8ddLMq66wSUFXGsqJKpmJAa1YyqkHN3" # Connection conn = http.client.HTTPConnection(host) # Create a heade...
937
5bd8cee2595215fda6ab523a646cf918e3d84a50
from django.urls import path,include from.import views from user.views import DetailsChangeView, HomeView, PasswordChangeView,SignUpView,LoginView,SettingsView,LogoutView,CreatePostView,CommentPostView,PasswordChangeView urlpatterns = [ path('', HomeView.as_view(), name = 'HomeView'), path('LoginView/', LoginV...
938
18dce1ce683b15201dbb5436cbd4288a0df99c28
from const import BORN_KEY, PRESIDENT_KEY, CAPITAL_KEY, PRIME_KEY, MINISTER_KEY, POPULATION_KEY, \ GOVERNMENT_KEY,AREA_KEY, WHO_KEY, IS_KEY, THE_KEY, OF_KEY, WHAT_KEY, WHEN_KEY, WAS_KEY from geq_queries import capital_of_country_query, area_of_country_query, government_of_country_query, \ population_of_country...
939
1968923cd923e68dc5ff2148802f18e40a5e6c33
''' Created on Nov 16, 2013 @author: mo ''' import unittest from Board import TicTacToe_Board from ComputerPlayer import ComputerPlayer from utils import debug_print as d_pr from main import StartNewGame class Test(unittest.TestCase): def setUp(self): self.the_board = TicTacToe_Board() de...
940
8e629ee53f11e29aa026763508d13b06f6ced5ba
# -*- coding:utf-8 -*- __author__ = 'yangxin_ryan' """ Solutions: 题目要求非递归的中序遍历, 中序遍历的意思其实就是先遍历左孩子、然后是根结点、最后是右孩子。我们按照这个逻辑,应该先循环到root的最左孩子, 然后依次出栈,然后将结果放入结果集合result,然后是根的val,然后右孩子。 """ class BinaryTreeInorderTraversal(object): def inorderTraversal(self, root: TreeNode) -> List[int]: result = list() ...
941
bc837d95ef22bd376f8b095e7aeb1f7d15c0e22e
"""Write a program that asks the user to enter a word and then capitalizes every other letter of that word. So if the user enters "rhinoceros", the program should print "rHiNoCeRoS""" word=str(input("please enter the word\n")) count=0 for char in word: if count==0: print(char.upper(),end="") count=1 ...
942
da34eb25ec08c8311fa839a0cdcd164eff036a5d
import bnn #get #!wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz #!wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz #unzip #!gzip -d t10k-images-idx3-ubyte.gz #!gzip -d t10k-labels-idx1-ubyte.gz #read labels print("Reading labels") labels = [] with open("/home/xilinx/jupyter_notebooks/...
943
04b5df5cfd052390f057c6f13b2e21d27bac6449
""" This example shows how to communicate with a SH05 (shutter) connected to a KSC101 (KCube Solenoid). """ # this "if" statement is used so that Sphinx does not execute this script when the docs are being built if __name__ == '__main__': import os import time from msl.equipment import EquipmentRecord, Co...
944
11f29508d52e856f4751a5dc8911a1f1c9832374
def test(d_iter): from cqlengine import columns from cqlengine.models import Model from cqlengine.query import ModelQuerySet from cqlengine import connection from cqlengine.management import sync_table from urllib2 import urlopen, Request from pyspark.sql import S...
945
71cdddfdd7c1327a8a77808dbdd0ff98d827231f
from flask.ext.restful import Resource, abort from flask_login import current_user, login_required from peewee import DoesNotExist from redash.authentication.org_resolving import current_org from redash.tasks import record_event class BaseResource(Resource): decorators = [login_required] def __init__(self, ...
946
0b3f16ee9b287c6c77acde674abec9deb4053c83
import tensorflow as tf import keras import numpy as np def house_model(y_new): xs = np.array([0, 1, 2, 4, 6, 8, 10], dtype=float) # Your Code Here# ys = np.array([0.50, 0.100, 1.50, 2.50, 3.50, 4.50, 5.50], dtype=float) # Your Code Here# model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape...
947
1754bce54a47cb78dce3b545d3dce835a4e0e69f
#!/usr/bin/env python # coding: utf-8 import logging import config def get_common_logger(name='common', logfile=None): ''' args: name (str): logger name logfile (str): log file, use stream handler (stdout) as default. return: logger obj ''' my_logger = logging.getLogger(name) ...
948
6affc182f5d3353d46f6e9a21344bc85bf894165
from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() # pylint: disable=dangerous-default-value,wrong-import-position,unused-import, import-outside-toplevel def create_app(settings_override={}): app = Flask(__name__) app.config.from_object('zezin.settings.Configuration') app.c...
949
9abf2b9b90d18332ede94cf1af778e0dda54330b
# Stubs for docutils.parsers.rst.directives.tables (Python 3.6) # # NOTE: This dynamically typed stub was automatically generated by stubgen. import csv from docutils.statemachine import StringList from docutils.nodes import Node, system_message, table, title from docutils.parsers.rst import Directive from typing impo...
950
94e8f0532da76c803b23fe2217b07dc8cf285710
# -*- coding: utf-8 -*- """ Created on Mon May 27 17:38:50 2019 @author: User """ import numpy as np import pandas as pd dataset = pd.read_csv('University_data.csv') print(dataset.info()) features = dataset.iloc[:, :-1].values labels = dataset.iloc[:, -1:].values from sklearn.preprocessing import LabelEncoder la...
951
f5d353694a719472320f4d6fa28bc9d2cc5a69b0
# -*- coding: utf-8 -*- """ This is the very first A.I. in this series. The vision is to devlop 'protocol droid' to talk to, to help with tasks, and with whom to play games. The droid will be able to translate langages and connect ppl. """ import speech_recognition as sr import pyttsx3 import pywhatkit ...
952
27a12a0f5ea6120036b66ee1cdd903da868a037f
# coding=utf-8 import base64 from sandcrawler.scraper import ScraperBase, SimpleScraperBase class Hdmovie14Ag(SimpleScraperBase): BASE_URL = 'http://www1.solarmovie.net' OTHER_URLS = ['http://solarmovie.net', 'http://hdmovie14.ag'] SCRAPER_TYPES = [ ScraperBase.SCRAPER_TYPE_OSP, ] LANGUAGE = 'eng' ...
953
aba2a0a262c14f286c278f21ba42871410c174f0
from django.shortcuts import render from django.shortcuts import redirect # Create your views here. from .forms import AddBookForm ,UpdateBookForm,BookCreateModelForm,SearchForm,RegistrationForm,SignInForm from book.models import Books from django.contrib.auth import authenticate,login,logout def book_add(reques...
954
d5903698eb8ed6be531b0cc522d4feff6b79da4e
import argparse import pandas as pd import random import time class Deck: def __init__(self, num_cols, front, back): self.flashcards = [] self.num_cols = num_cols self.front = front self.back = back class Flashcard: def __init__(self, deck, front, back, column, row): self.deck = deck self.front = front ...
955
48291ab3deb1ca1ba672d3e642d55635a7270171
import serial from settings import * class CommunicationController: def __init__(self): global board board = serial.Serial(ROBOT_SERIAL, BAUDRATE, serial.EIGHTBITS, timeout=0) self.count = 0 print("Communication controller") def sendCommand(self, right, back, left): self...
956
d7b0ff6549d854d21ad1d2d0f5a9e7f75f4ac1d5
from django.test import TestCase from recruitmentapp.apps.core.models import Competence class CompetenceTest(TestCase): def setUp(self): self.competence = Competence.objects.create(name='mining') self.competence.set_current_language('sv') self.competence.name = 'gruvarbete' self.c...
957
8457cdde8f8ad069505c7729b8217e5d272be41e
from apps.mastermind.core.domain.domain import Color, Game from apps.mastermind.infrastructure.mongo_persistence.uow import MongoUnitOfWork from composite_root.container import provide class GameMother: async def a_game( self, num_slots: int, num_colors: int, max_guesses: int, ...
958
690e7cc9047b3a445bf330524df52e2b359f1f13
AuthorPath = 'data/Author.csv' PaperPath = 'buff/Paper.TitleCut.csv' PaperAuthorPath = 'data/PaperAuthor.csv' AffilListPath = 'buff/AffilList2.csv' StopwordPath='InternalData/en.lst'
959
7a9515b1f8cc196eb7551137a1418d5a387e7fd3
import pandas as pd import numpy as np import difflib as dl import sys def get_close(x): if len(x) == 0: return "" return x[0] list_file = sys.argv[1] rating_file = sys.argv[2] output_file = sys.argv[3] movie_list = open(list_file).read().splitlines() movie_data = pd.DataFrame({'movie': movie_list}) rating_data ...
960
19aad7d45416e311530aa2ce3e854cf1f65d18f5
import multiprocessing import time def foo(): time.sleep(0.1) p = multiprocessing.Process(target=foo) p.start() print("process running: ", p, p.is_alive()) p.terminate() print("process running: ", p, p.is_alive()) p.join() print("process running: ", p, p.is_alive()) print("process exit code:", p.exitcode)
961
623bd858923d5f9cc109af586fdda01cd3d5fff3
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import InputRequired, Length, EqualTo, ValidationError from passlib.hash import pbkdf2_sha256 from models import User def invalid_credentials(form, field): ''' Username and password checker ''' userna...
962
9abc5f18e2eb07afe6bc31d6bd27298350707d1d
""" 爱丽丝和鲍勃有不同大小的糖果棒:A[i] 是爱丽丝拥有的第 i 根糖果棒的大小,B[j] 是鲍勃拥有的第 j 根糖果棒的大小。 因为他们是朋友,所以他们想交换一根糖果棒,这样交换后,他们都有相同的糖果总量。(一个人拥有的糖果总量是他们拥有的糖果棒大小的总和。) 返回一个整数数组 ans,其中 ans[0] 是爱丽丝必须交换的糖果棒的大小,ans[1] 是 Bob 必须交换的糖果棒的大小。 如果有多个答案,你可以返回其中任何一个。保证答案存在。 """ def fairCandySwap(A, B): sumA, sumB = sum(A), sum(B) setA, setB = set(A), se...
963
6f698196e9391d73bd99cda0a098a5bf7a3832ff
from turtle import * while True: n=input("Right or left? ") if n == 'right': right(60) forward(100) elif n == 'left': left(60) forward(100)
964
b4d412e8b45722a855a16dd64b7bce9b303d0ffe
from collections import defaultdict class Graph: def __init__(self): self._graph = defaultdict(list) self._odd_vertices = [] def add_vertex(self, v): if not v in self._graph: self._graph[v] = list() def add_edge(self, v1, v2): self._graph[v1].append(v2) ...
965
bab78e8a88f9a26cc13fe0c301f82880cee2b680
from django.contrib import admin from .models import Predictions @admin.register(Predictions) class PredictionsAdmin(admin.ModelAdmin): pass
966
fd450b5454b65ed69b411028788c587f9674760c
#!/usr/bin/env python """ Script that generates the photon efficiency curves and stores them in a root file. For the moment only the pT curves for the different eta bins are created """ import re import json import ROOT as r r.PyConfig.IgnoreCommandLineOptions = True import numpy as np import sympy as sp from utils...
967
176ffac7ad47f5c43a24acc664631f8353ec5100
import matplotlib.pyplot as plt import numpy as np steps = 10 num_tests = 100 res = [] with open('txt.txt', 'r') as f: data = f.readlines() line = 0 for i in range(10, 110, 10): agg = 0 for j in range(num_tests): agg += int(data[line]) line += 1 res.append(...
968
b3d26d01d45c073192d06c8e94c06f7eae267b14
old_file = open("new.csv", "r") new_file = open("new1,csv", "w") for line in old_file.readlines(): cleaned_line =line.replace(',','.') new_file.write(cleaned_line) old_file.close new_file.close
969
aa13278a4686e9bab7948c2f212f87f9bd6eee00
import socket END = bytearray() END.append(255) print(END[0]) def recvall(sock): # Odbiór danych BUFF_SIZE = 4096 # 4 KiB data = b'' while True: # odbieramy dane, pakiety 4KiB part = sock.recv(BUFF_SIZE) data += part if len(part) < BUFF_SIZE: # 0 lub koniec danych ...
970
736fee6f9a46b8568b2dd217b81d54d689306630
#!/usr/bin/python # -*- coding: utf-8 -*- import pandas as pd import numpy as np import datetime import time from sys import exit from matplotlib import colors, pyplot as plt from functools import reduce import matplotlib.cm as cm import seaborn as sns from astropy.io import ascii, fits from astropy.wcs import wcs fr...
971
dbe3aa107de8e62822803d1740773a4b22f41edf
import sys, os sys.path.append(os.pardir) import numpy as np from dataset.mnist import load_mnist from two_layer_net import TwoLayerNet (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label = True) train_loss_list = [] #hiper param iters_num = 1000 train_size = x_train.shape[0] batch_size =...
972
3f9be81c86852a758440c6a144b8caba736b3868
# Generated by Django 3.1.7 on 2021-02-20 02:52 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('usuarios', '0001_initial'), ('plataforma', '0005_auto_20210219_2343'), ] operations = [ migrations....
973
e06b740f27e41b9f120c962fd76a38a29d54af3c
from more_itertools import ilen from my.body import weight, shower, food, water def test_body() -> None: for func in (weight, shower, food, water): assert ilen(func()) >= 1
974
1fd4d1a44270ef29512e601af737accb916dc441
from estmd import ESTMD input_directory = "test.avi" e = ESTMD() e.open_movie(input_directory) e.run(by_frame=True) r = e.create_list_of_arrays() print "Done testing!"
975
c7c412fe4e2d53af1b4f2a55bd3453496767890d
from time import sleep import pytest import allure from app.debug_api import DebugAPI from app.check_api import HandlersAPI from locators.movies_details_locators import MoviesDetailsPageLocators from locators.movies_locators import MoviesPageLocators from locators.shedule_locators import ShedulePageLocators from scree...
976
327371d373819273a2f77f63e0cedee6950dbc46
#!/usr/bin/env python """ ############################################################################## Software Package Risk Analysis Development Environment Specific Work Book View ############################################################################## """ # -*- coding: utf-8 -*- # # rtk.softw...
977
136215a3ba99f74160373181c458db9bec4bb6b7
#PortableKanban 4.3.6578.38136 - Encrypted Password Retrieval #Python3 -m pip install des #or #pip install des import json import base64 from des import * #python3 -m pip install des, pip install des import sys def decode(hash): hash = base64.b64decode(hash.encode('utf-8')) key = DesKey(b"7ly6UznJ") r...
978
cc46485a3b5c68e4f77a2f9a033fd2ee2859b52b
from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split import pandas as pd import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import cross_val_score iris_dataset=load_iris() X=iris_dataset['data'] y=iris_dataset['target'] X_tra...
979
ce98c13555c474de0a9cb12e99a97b2316312b00
yuki = list(map(int, input().split())) S = input() enemy = [S.count('G'), S.count('C'), S.count('P')] ans = 0 for i in range(3): ans += min(yuki[i], enemy[(i+1)%3]) * 3 yuki[i], enemy[(i+1)%3] = max(0, yuki[i]-enemy[(i+1)%3]), max(0, enemy[(i+1)%3]-yuki[i]) for i in range(3): ans += min(yuki[i], enemy[i]) ...
980
3f3ed0165120dc135a4ce1f282dbdf9dad57adf8
# coding: UTF-8 -*- import os.path PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) EMOTICONS = { "O:)": "angel", "o:)": "angel", "O:-)": "angel", "o:-)": "angel", "o:-3": "angel", "o:3": "angel", "O;^)": "angel", ">:[": "annoyed/disappointed", ":-(": "annoyed/disappointed...
981
3cc894570189fe545f5db3150d0b69c16dc211dc
class player: def __init__(self, name: str, symbol: str): self._name = name self._symbol = symbol def decide_next_move(self): """ Checks all possible combinations to decide best next move :return: board position """ pass def get_next_move(self): ...
982
3f8b8b8cfbe712f09734d0fb7302073187d65a73
''' def Sort(a): i=1 while i<len(a): j=i while j>0 and a[j-1] > a[j]: temp = a[j-1] a[j-1] = a[j] a[j] = temp j-=1 i+=1 return a ''' def Sort(a): i=1 n=len(a) while i<len(a): j=i print(i-1,'\t',i) whi...
983
e95de58828c63dc8ae24efff314665a308f6ce0c
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-12-13 02:06 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ('stores', '0001_initial'), ...
984
a406efcab62b2af67484da776f01fc4e6d20b697
#!/usr/bin/env python3 def twoNumberSum(array, targetSum): # Write your code here. # O(n^2) time | O(1) space ''' Double for loop, quadratic run time No variables increase as the input size increases, therefore constant space complexity. ''' for i in range(len(array) - 1): firstNu...
985
d265781c6b618752a1afcf65ac137052c26388a6
import xarray as xr import pandas as pd import numpy as np import matplotlib.pyplot as plt import pickle import seaborn as sns %load_ext autoreload %autoreload 2 %matplotlib data_dir = Path('/Volumes/Lees_Extend/data/ecmwf_sowc/data/') # READ in model (maybe want to do more predictions on historical data) from src.m...
986
15edb1c051ccbc6f927c0a859288511f94a3d853
from types import MappingProxyType from typing import Any, Dict, Mapping, Type, TypeVar, Union import yaml from typing_extensions import Protocol from mashumaro.serializer.base import DataClassDictMixin DEFAULT_DICT_PARAMS = { "use_bytes": False, "use_enum": False, "use_datetime": False, } EncodedData = ...
987
274185896ab5c11256d69699df69fc2c0dde4f2d
''' extract package names from the Meteor guide and write them to packages-guide Uses the content folder of https://github.com/meteor/guide ''' from collections import defaultdict import os import sys import markdown from bs4 import BeautifulSoup def get_links_from_markdown(path, name): try: with op...
988
21e86e4719cda5c40f780aca6e56eb13c8c9b8e5
# encoding: utf-8 '''🤠 PDS Roundup: A step takes you further towards a complete roundup''' from enum import Enum from .util import commit, invoke import logging, github3, tempfile, zipfile, os _logger = logging.getLogger(__name__) class Step(object): '''An abstract step; executing steps comprises a roundup'''...
989
333914f99face050376e4713ca118f2347e50018
""" URL Configuration to test mounting created urls from registries """ from django.contrib import admin from django.urls import include, path from staticpages.loader import StaticpagesLoader staticpages_loader = StaticpagesLoader() urlpatterns = [ path("admin/", admin.site.urls), # Add base pages urls usi...
990
5ef7c838d8e9a05a09bd974790a85ff36d56a336
import mock def exc(): print 'here should raise' def recursion(): try: print 'here' return exc() except StandardError: print 'exc' return recursion() def test_recursion(): global exc exc = mock.Mock(side_effect = [StandardError, StandardError, mock.DEFAULT]) r...
991
88b3dd7414a68de65bafb317fbd4da2b1bc933fc
import json def corec_set(parameter, value): params_fn = "corec_parameters.json" with open(params_fn) as f: params = json.load(f) params[parameter] = value with open(params_fn, 'w') as f: json.dump(params, f, indent=4) def corec_get(parameter): params_fn = "corec_parameters.json" with open(params_fn)...
992
095374aa7613f163fedbd7d253219478108d4f42
# Celery配置文件 # 指定消息队列为Redis broker_url = "redis://120.78.168.67/10" CELERY_RESULT_BACKEND = "redis://120.78.168.67/0" CELERY_TIMEZONE = 'Asia/Shanghai'
993
2c1de638ac25a9f27b1af94fa075b7c1b9df6884
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'PhoneUser.last_contacted' db.add_column(u'smslink_phoneuser', 'last_contacted', ...
994
18bad56ff6d230e63e83174672b8aa8625c1ebb4
RANGES = { # Intervalles de la gamme majeure 0: [1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1], # Intervalles de la gamme mineure naturelle 1: [1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0], # Intervalles de la gamme mineure harmonique 2: [1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1] } RANGES_NAMES = { 'fr': ['Maje...
995
364ac79e0f885c67f2fff57dfe3ddde63f0c269e
import os import unittest import json from flask_sqlalchemy import SQLAlchemy from flaskr import create_app from models import setup_db, Question DB_HOST = os.getenv('DB_HOST', '127.0.0.1:5432') DB_USER = os.getenv('DB_USER', 'postgres') DB_PASSWORD = os.getenv('DB_PASSWORD', 'postgres') DB_NAME = os.getenv('DB_NAME'...
996
34c81b9318d978305748d413c869a86ee6709e2c
# import visual_servoing_utils_main as utils from autolab_core import rigid_transformations as rt from yumipy import YuMiState class YumiConstants: T_gripper_gripperV = rt.RigidTransform(rotation=[[-1, 0, 0], [0, 1, 0], [0, 0, -1]], from_frame='gripper', to_frame='obj') ...
997
04099c46c029af37a08b3861809da13b3cc3153b
""" OBJECTIVE: Given a list, sort it from low to high using the QUICK SORT algorithm Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays. The steps are: 1. Pick an element, called a pivot, from the array. 2. Par...
998
9a6d6637cd4ecf2f6e9c8eb8e702be06e83beea4
from app import create_app __author__ = '七月' app = create_app() if __name__ == '__main__': app.run(debug=app.config['DEBUG'])
999
f405a3e9ccabbba6719f632eb9c51809b8deb319
import boto3 from botocore.exceptions import ClientError import logging import subprocess import string import random import time import os import sys import time import json from ProgressPercentage import * import logging def upload_file(file_name, object_name=None): RESULT_BUCKET_NAME = "worm4047bucket2" s...