language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
732
3.71875
4
[]
no_license
// variables om afstand in km op te tellen var counterup = document.getElementById('counterup'); var numbers = 0; counterup.innerHTML = numbers; function countUp (){ numbers = numbers + 1 counterup.innerHTML = numbers; }; setInterval(countUp,50); // per 50 miliseconden var timeleft = 280000000; //afstand waarvan hij moet aftellen van de data 280.000.000 km var countDown = document.getElementById("countdowntimer") var downloadTimer = setInterval(function(){ timeleft--; countDown.textContent = timeleft; if(timeleft <= 1){ clearInterval(downloadTimer); countDown.textContent = "Finished we zijn op MARS!"; // na het aftellen zegt hij FINSHED WE ZIJN OP MARS } },50); // per 50 miliseconden
C++
UTF-8
512
2.6875
3
[]
no_license
#include <iostream> using namespace std; #define MAX 101 int paper[MAX][MAX]; int main() { int num, x, y, sum=0; cin >> num; for (int i=0; i<num; i++) { cin >> x >> y; for (int j=x; j<x+10; j++) { for (int k=y; k<y+10; k++) { paper[j][k] = 1; } } } for (int i=0; i<MAX; i++) { for (int j=0; j<MAX; j++) { if (paper[i][j] == 1) sum++; } } cout << sum; return 0; }
Java
UTF-8
2,932
2.484375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.fpuna.model; import edu.fpuna.Constants.FormatoFecha; import java.sql.Time; import java.util.HashSet; import java.util.Set; import javax.persistence.*; /** * * @author ghuttemann */ @Entity @Table(name="horario") public class HorarioAtencion extends BaseObject { private Long id; private DiaDeSemana dia; private Time horaInicio; private Time horaFin; private Doctor doctor; private Set<Turno> turnos = new HashSet<Turno>(); @Id @GeneratedValue(strategy=GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name="dia",nullable=false) @Enumerated(EnumType.ORDINAL) public DiaDeSemana getDia() { return dia; } public void setDia(DiaDeSemana dia) { this.dia = dia; } @Transient public String getDiaString() { return this.dia.toString(); } @Column(name="hora_inicio",nullable=false) public Time getHoraInicio() { return horaInicio; } @Transient public String getHoraInicioString() { return super.formatearFecha(horaInicio, FormatoFecha.HORA); } public void setHoraInicio(Time horaInicio) { this.horaInicio = horaInicio; } @Column(name="hora_fin",nullable=false) public Time getHoraFin() { return horaFin; } public void setHoraFin(Time horaFin) { this.horaFin = horaFin; } @Transient public String getHoraFinString() { return super.formatearFecha(horaFin, FormatoFecha.HORA); } @ManyToOne(fetch=FetchType.EAGER,optional=false) @JoinColumn(name="doctor_id",nullable=false) public Doctor getDoctor() { return doctor; } public void setDoctor(Doctor doctor) { this.doctor = doctor; } @OneToMany(fetch=FetchType.EAGER,mappedBy="horario") @OrderBy(value="hora") public Set<Turno> getTurnos() { return turnos; } public void addTurno(Turno turno) { turnos.add(turno); } public void setTurnos(Set<Turno> turnos) { this.turnos = turnos; } @Override public String toString() { return this.getClass().getSimpleName() + "(id=" + this.id + ")"; } @Override public boolean equals(Object o) { if(o == null){ return false; } if (!(o instanceof HorarioAtencion)) return false; final HorarioAtencion horario = (HorarioAtencion) o; if (this.id != null && horario != null && horario.getId() != null && this.id.equals(horario.getId())) return true; return false; } @Override public int hashCode() { return this.id.hashCode(); } }
Markdown
UTF-8
2,758
3.125
3
[]
no_license
*后台开发人员作业* ========= &nbsp; #### **编辑时间:** - **2017年3月28日10:52:02** #### **作业名称:** - **模仿qsort() 实现一个通用排序函数:msort()。** #### **作业截止期限:** - **本周六下午 17:00 前** #### **提醒:** - **模仿qsort() 实现一个通用排序函数:msort()。** &nbsp; **如果采用其他语言,比如python,则不必采用以下文件结构,但是应该‘照猫画虎’,领会以下的各种要求,合适的采用其他语言分别实现其功能:模块分离、运行、测试** &nbsp; #### **必须用到以下几个文件:** - **msort.c 实现排序函数** - **generate_data.h 声明随机数相关函数** - **main.c 这个文件里不实现任何排序相关的内容** - **generate_data.c 根据传入参数,产生指定数量的随机数** - **msort.h 排序相关函数的声明 (可能还需要结构体的声明)** - **test_generate_data.c 测试 generate_data.c 的所有函数** - **test_msort.c 测试 msort.c 的所有函数** - **Makefile 一键编译这个作业** &nbsp; #### **函数依赖:** - **排序算法的时间复杂度应该为 nlog(n)** - **排序时,不可以调用任何第三方排序函数** #### **文件保存在同一级目录下:** - **msort目录** &nbsp; &nbsp; ### **验收要求:** #### **生成验收:** - **在作业目录(msort)下:** - **执行 make 命令,则生成 msort** - **执行 make test, 则生成 test_msort** - **执行 make clean, 则清空所有由 make 相关指令生成的文件** &nbsp; - **执行验收:** - **生成验收通过后,在作业目录(msort)下 执行 ./msort MAX_VALUE TOTAL_NUMS输出数据** - **打印生成的随机数总数,随机数的最大值 TOTAL_NUMS, MAX_VALUE(独占一行** - **打印生成的随机数, 每行规定显示为 10 个,每个数字之间以‘逗号’分开** - **打印排序所耗费的时间 (独占一行)** - **打印排序后的数字,显示格式与2相同** &nbsp; - **测试验收:** - **执行 ./test_msort** - **依次次输出每个函数的‘声明’,然后是四个空格,接着 输出 OK 或者 FAILED** - **OK 需要红色字体** - **FAILED 需要绿色字体** &nbsp; ### **作业提交方式:** - **代码放在 github** - **截图与作业总结放在 blog** - **博文第一行放置作业在 github 的地址** - **通过邮箱发送 自己的作业** - **邮件标题: 姓名-完成时间** - **邮件正文: blog链接** - **随着作业的开展,每完成或者实现一定的功能,则进行提交** - **提交时,注明必要的提交说明** - **完成作业后,应该有不少于5次提交** ----------
C++
UTF-8
2,325
3.578125
4
[]
no_license
#pragma once #include "bit_container.hpp" #include <micro/utils/arrays.hpp> #include <type_traits> namespace micro { /* @brief Array for storing binary values memory-efficiently. Values are stored in 32-bit containers to reduce memory need. * @tparam N Number of values stored in the array. Should be a multiple of 32 for the best efficiency. **/ template <uint32_t N> class bit_array { private: static constexpr uint32_t C = 32; // Container size. static constexpr uint32_t NC = (N + (C - 1)) / C; // Number of containers. typedef bit_container<C> bit_container_type; // The bit container type. typedef typename bit_container_type::type type; // The underlying data type. bit_container_type data[NC]; // Array of containers storing the binary values. public: bit_array() { this->reset(); } /* @brief Casts bit container to an array of an integral type. * @returns The container array. **/ template <typename T, class = typename std::enable_if<std::is_integral<T>::value>::type> operator T*() { return reinterpret_cast<T*>(this->data); } /* @brief Casts bit container to an array of an integral type. * @returns The container array. **/ template <typename T, class = typename std::enable_if<std::is_integral<T>::value>::type> operator const T*() const { return reinterpret_cast<T*>(this->data); } /* @brief Gets given bit of the array. * @param pos The position. * @returns The given bit of the array. **/ bool get(uint32_t pos) const { return this->data[pos / C].get(pos % C); } /* @brief Sets given bit of the array. * @param pos The position. * @param value The bit value to write. **/ void set(uint32_t pos, bool value) { this->data[pos / C].set(pos % C, value); } /* @brief Copies binary array to byte array. * @param The result byte array. **/ void toBytes(uint8_t * const result) { micro::copy<NC>(static_cast<type*>(this->data), reinterpret_cast<type*>(result)); } /* @brief Resets all bits. **/ void reset() { for (uint32_t i = 0; i < NC; ++i) { this->data[i].reset(); } } }; } // namespace micro
C
UTF-8
7,641
2.90625
3
[]
no_license
/***************************************************************************** * 文 件 名 : test_case_select.c * 负 责 人 : yankai * 创建日期 : 2015年12月21日 * 功能描述 : 测试用例 * 其 它 : *****************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<string.h> #include "sqlite3.h" #include "test_case_select.h" char *join(char *a, char *b); void kHelloSQLite(char *tablename); void test_API_sqlite3_exec(); int main() { if(RkHelloSQLite){ kHelloSQLite("info"); } else if(Rtest_minMaxQuery){ test_minMaxQuery(); } else if(Rtest_API_sqlite3_exec){ test_API_sqlite3_exec(); } else if(Rtest_API_Select_Callback){ test_API_Select_Callback(); } return 0; } /***************************************************************************** * 数 据 库 : stu.db * SQL语 句 : create table info(id integer primary key,name varchar(20)); insert into info values(1,'yankai'); insert into info values(2,'Bill'); insert into info values(3,'Jobs'); insert into info values(4,'Gates'); * 创建日期 : 2015年12月21日 * 执行结果 : yankai@ubuntu:~/yankai/sqlite3/cases_test$ make cc -c -o test_case_select.o test_case_select.c gcc -o main test_case_select.o sqlite3.o -lpthread -ldl yankai@ubuntu:~/yankai/sqlite3/cases_test$ ./main 1 | yankai 2 | Bill 3 | Jobs 4 | Gates *****************************************************************************/ void kHelloSQLite(char tablename[]) { int rc,i,ncols; sqlite3 *db; sqlite3_stmt *stmt; char *sql; const char *tail; rc=sqlite3_open("stu.db",&db); //打开数据 if(rc) { fprintf(stderr,"Can't open database:%s\n",sqlite3_errmsg(db)); sqlite3_close(db); exit(1); } sql = join("select * from ",tablename); rc=sqlite3_prepare(db,sql,(int)strlen(sql),&stmt,&tail); if(rc!=SQLITE_OK) { fprintf(stderr,"SQL error:%s\n",sqlite3_errmsg(db)); } rc=sqlite3_step(stmt); ncols=sqlite3_column_count(stmt); while(rc==SQLITE_ROW) { for(i=0;i<ncols;i++) { if(i==0) fprintf(stderr," %3s |",sqlite3_column_text(stmt,i)); else fprintf(stderr," %-10s",sqlite3_column_text(stmt,i)); } fprintf(stderr,"\n"); rc=sqlite3_step(stmt); } sqlite3_finalize(stmt);//释放statement sqlite3_close(db);//关闭数据库 } /***************************************************************************** *功 能 描 述:利用sqlite3_exec()执行SQL语句 * 数 据 库 : stu.db * SQL语 句 : create table app(id integer primary key,name varchar(20)); insert app info values(1,'Facebook'); insert app info values(2,'Twitter'); insert app info values(3,'YouTube'); insert app info values(4,'WeChat'); insert app info values(5,'QQ'); * 创建日期 : 2015年12月22日 * 执行结果 : yankai@ubuntu:~/yankai/sqlite3/cases_test$ make cc -c -o test_case_select.o test_case_select.c gcc -o main test_case_select.o sqlite3.o -lpthread -ldl yankai@ubuntu:~/yankai/sqlite3/cases_test$ ./main 1 | Facebook 2 | Twitter 3 | YouTube 4 | WeChat 5 | QQ *****************************************************************************/ void test_API_sqlite3_exec() { sqlite3 *db; int rc; char *kSQL; char *errmsg; kSQL = "create table app(id integer primary key,name varchar(20));insert into app values(1,'Facebook');insert into app values(2,'Twitter');insert into app values(3,'YouTube');insert into app values(4,'WeChat');insert into app values(5,'QQ');"; rc=sqlite3_open("stu.db",&db); //打开数据 if(rc) { fprintf(stderr,"Can't open database:%s\n",sqlite3_errmsg(db)); sqlite3_close(db); exit(1); } rc = sqlite3_exec(db,kSQL,0,0,&errmsg); if(rc){ fprintf(stderr,"SQLite3 execute failed:%s\n",sqlite3_errmsg(db)); sqlite3_close(db); exit(1); } kHelloSQLite("app"); sqlite3_close(db); } char *join(char *a, char *b) { char *c = (char *) malloc(strlen(a) + strlen(b) + 1); //局部变量,用malloc申请内存 if (c == NULL) exit (1); char *tempc = c; //把首地址存下来 while (*a != '\0') { *c++ = *a++; } while ((*c++ = *b++) != '\0') { ; } //注意,此时指针c已经指向拼接之后的字符串的结尾'\0' ! return tempc;//返回值是局部malloc申请的指针变量,需在函数调用结束后free之 } /***************************************************************************** *功 能 描 述:使用回调查询数据库 *函 数 原 型: typedef int (*sqlite3_callback)(void*,int,char**, char**); * 创建日期 : 2016年01月12日 * 执行结果 : yankai@ubuntu$ ./main 记录包含 2 个字段 字段名:ID -> 字段值:1 字段名:name -> 字段值:走路 ------------------ 记录包含 2 个字段 字段名:ID -> 字段值:2 字段名:name -> 字段值:骑单车 ------------------ 记录包含 2 个字段 字段名:ID -> 字段值:3 字段名:name -> 字段值:坐校车 ------------------ *****************************************************************************/ int loadMyInfo(void *para,int n_column,char **column_value,char ** column_name) { int i; printf("记录包含 %d 个字段\n", n_column ); for( i = 0 ; i < n_column; i ++ ) { printf("字段名:%s -> 字段值:%s\n", column_name[i], column_value[i] ); } printf("------------------\n"); return 0; } int test_API_Select_Callback() { sqlite3 * db; int result; char * errmsg = NULL; result = sqlite3_open("stu2.db", &db ); if( result != SQLITE_OK ) { printf("数据库打开失败!\n"); return -1; } result = sqlite3_exec( db,"create table tWay( ID integer primary key autoincrement, name nvarchar(32) )", NULL, NULL, errmsg ); if(result != SQLITE_OK ) { printf("创建表失败,错误码:%d,错误原因:%s\n", result, errmsg ); } result = sqlite3_exec( db, "insert into tWay( name ) values ( '走路' )", 0, 0, errmsg ); if(result != SQLITE_OK ) { printf("插入记录失败,错误码:%d,错误原因:%s\n", result, errmsg ); } result = sqlite3_exec( db,"insert into tWay( name ) values ( '骑单车')", 0, 0, errmsg ); if(result != SQLITE_OK ) { printf("插入记录失败,错误码:%d,错误原因:%s\n", result, errmsg ); } result = sqlite3_exec( db,"insert into tWay( name ) values ('坐校车')", 0, 0, errmsg ); if(result != SQLITE_OK ) { printf("插入记录失败,错误码:%d,错误原因:%s\n", result, errmsg ); } result = sqlite3_exec( db,"select * from tWay", loadMyInfo, NULL, errmsg ); sqlite3_close( db ); return 0; }
C#
UTF-8
1,766
3.484375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; class Solution { static void Main(String[] args) { var input = Console.ReadLine().Split(' '); var kangaroos = new List<Kangaroo> { new Kangaroo { XPosition = int.Parse(input[0]), Velocity = int.Parse(input[1]) }, new Kangaroo { XPosition = int.Parse(input[2]), Velocity = int.Parse(input[3]) } }; if (kangaroos.First().NextPosition > kangaroos.Second().NextPosition) { kangaroos.Reverse(); } var collision = false; if (!kangaroos.First().CannotCatchUpTo(kangaroos.Second())) { while (kangaroos.First().XPosition <= kangaroos.Second().XPosition) { kangaroos.First().Jump(); kangaroos.Second().Jump(); if (kangaroos.First().XPosition == kangaroos.Second().XPosition) { collision = true; break; } } } Console.WriteLine(collision ? "YES" : "NO"); } class Kangaroo { public int XPosition { get; set; } public int Velocity { get; set; } public int NextPosition => XPosition + Velocity; public void Jump() { XPosition += Velocity; } public bool CannotCatchUpTo(Kangaroo opponent) { return (XPosition <= opponent.XPosition && Velocity < opponent.Velocity) || (XPosition < opponent.XPosition && Velocity <= opponent.Velocity); } } } public static class Extensions { public static T Second<T>(this IEnumerable<T> list) { return list.Skip(1).First(); } }
C
UTF-8
3,158
2.515625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/*! * header.c - header for mako * Copyright (c) 2021, Christopher Jeffrey (MIT License). * https://github.com/chjj/mako */ #include <stdlib.h> #include <stdint.h> #include <string.h> #include <mako/crypto/hash.h> #include <mako/header.h> #include <mako/util.h> #include "impl.h" #include "internal.h" /* * Header */ DEFINE_SERIALIZABLE_OBJECT(btc_header, SCOPE_EXTERN) void btc_header_init(btc_header_t *z) { z->version = 0; btc_hash_init(z->prev_block); btc_hash_init(z->merkle_root); z->time = 0; z->bits = 0; z->nonce = 0; } void btc_header_clear(btc_header_t *z) { (void)z; } void btc_header_copy(btc_header_t *z, const btc_header_t *x) { z->version = x->version; btc_hash_copy(z->prev_block, x->prev_block); btc_hash_copy(z->merkle_root, x->merkle_root); z->time = x->time; z->bits = x->bits; z->nonce = x->nonce; } size_t btc_header_size(const btc_header_t *x) { size_t size = 0; (void)x; size += 4; size += 32; size += 32; size += 4; size += 4; size += 4; return size; } uint8_t * btc_header_write(uint8_t *zp, const btc_header_t *x) { zp = btc_uint32_write(zp, x->version); zp = btc_raw_write(zp, x->prev_block, 32); zp = btc_raw_write(zp, x->merkle_root, 32); zp = btc_time_write(zp, x->time); zp = btc_uint32_write(zp, x->bits); zp = btc_uint32_write(zp, x->nonce); return zp; } int btc_header_read(btc_header_t *z, const uint8_t **xp, size_t *xn) { if (!btc_uint32_read(&z->version, xp, xn)) return 0; if (!btc_raw_read(z->prev_block, 32, xp, xn)) return 0; if (!btc_raw_read(z->merkle_root, 32, xp, xn)) return 0; if (!btc_time_read(&z->time, xp, xn)) return 0; if (!btc_uint32_read(&z->bits, xp, xn)) return 0; if (!btc_uint32_read(&z->nonce, xp, xn)) return 0; return 1; } void btc_header_hash(uint8_t *hash, const btc_header_t *hdr) { btc_hash256_t ctx; btc_hash256_init(&ctx); btc_uint32_update(&ctx, hdr->version); btc_raw_update(&ctx, hdr->prev_block, 32); btc_raw_update(&ctx, hdr->merkle_root, 32); btc_time_update(&ctx, hdr->time); btc_uint32_update(&ctx, hdr->bits); btc_uint32_update(&ctx, hdr->nonce); btc_hash256_final(&ctx, hash); } int btc_header_verify(const btc_header_t *hdr) { uint8_t target[32]; uint8_t hash[32]; if (!btc_compact_export(target, hdr->bits)) return 0; btc_header_hash(hash, hdr); return btc_hash_compare(hash, target) <= 0; } int btc_header_mine(btc_header_t *hdr, uint32_t limit) { btc_hash256_t pre, ctx; uint32_t attempt = 0; uint8_t target[32]; uint8_t hash[32]; CHECK(btc_compact_export(target, hdr->bits)); memset(&pre, 0, sizeof(pre)); btc_hash256_init(&pre); btc_uint32_update(&pre, hdr->version); btc_raw_update(&pre, hdr->prev_block, 32); btc_raw_update(&pre, hdr->merkle_root, 32); btc_time_update(&pre, hdr->time); btc_uint32_update(&pre, hdr->bits); do { ctx = pre; btc_uint32_update(&ctx, hdr->nonce); btc_hash256_final(&ctx, hash); if (btc_hash_compare(hash, target) <= 0) return 1; hdr->nonce++; if (++attempt == limit) return 0; } while (hdr->nonce != 0); return 0; }
Java
UTF-8
1,925
2.421875
2
[]
no_license
package dev.service; import dev.dao.IPlatDao; import dev.entite.Plat; import dev.exception.PlatException; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; @Service public class PlatServiceVersion1 implements IPlatService { private IPlatDao dao; public PlatServiceVersion1 (@Qualifier("platDaoDataJpa") IPlatDao dao) { this.dao = dao; } @Override public List<Plat> listerPlats() { return dao.listerPlats(); } @Override public void ajouterPlat(String nomPlat, Integer prixPlat) { // règle métier if (nomPlat.length() <= 3) { throw new PlatException("un plat doit avoir un nom de plus de 3 caractères"); } if (prixPlat <= 500) { throw new PlatException("le prix d'un plat doit être supérieur à 5 €"); } // persistance uniquement si les règles métiers sont respectées dao.ajouterPlat(nomPlat, prixPlat); } public Plat rechercherPlatParId(Integer id){ return dao.rechercherPlatParId(id); } public List<Plat> rechercherPlatParNom(String nom){ return dao.rechercherPlatParNom(nom); } @Override public void modifierPlat(Plat plat) { // règle métier if (plat.getNom() != null && plat.getNom().length() <= 3) { throw new PlatException("un plat doit avoir un nom de plus de 3 caractères"); } if (plat.getPrixEnCentimesEuros() != null && plat.getPrixEnCentimesEuros() <= 500) { throw new PlatException("le prix d'un plat doit être supérieur à 5 €"); } dao.modifierPlat(plat); } @Override public void supprimerPlat(Integer id) { dao.supprimerPlat(id); } }
Shell
UTF-8
1,011
3.359375
3
[ "Unlicense" ]
permissive
# This sets the environment for accessing the cloud # Make sure that IP Addresses are setup properly # Use PUBLIC IP Here export ORDERER_ADDRESS=18.144.68.240:7050 export ACME_EP=54.183.208.65:7051 export BUDGET_EP=54.183.156.254:7051 export CA_IP=54.193.94.161 export CA_URL=http://$CA_IP:7054 export FABRIC_LOGGING_SPEC=info function usage { echo "Usage: . ./set-env.sh ORG_NAME" echo "Sets the environment for the specific org" } export CURRENT_ORG_NAME=$1 echo "Setting environment for $CURRENT_ORG_NAME" # Set environment variables based on the ORG_Name case $CURRENT_ORG_NAME in "acme") export CORE_PEER_MSPCONFIGPATH=../fabric-ca/client/acme/admin/msp export CORE_PEER_ADDRESS=$ACME_EP export CORE_PEER_LOCALMSPID=AcmeMSP ;; "budget") export CORE_PEER_MSPCONFIGPATH=../fabric-ca/client/budget/admin/msp export CORE_PEER_ADDRESS=$BUDGET_EP export CORE_PEER_LOCALMSPID=BudgetMSP ;; *) usage esac
C++
ISO-8859-1
529
3.75
4
[]
no_license
#include<stdio.h> //uma funo que recebe dois valores (x,y) e retorne a diferena entre eles. int diferenca(int x, int y){ int resul; if(x>y){ resul = x - y; return resul; }else{ resul = x + y; return resul; } } int main(void){ int x,y,retorno; printf("Digite o primeiro numero: "); scanf("%d", &x); printf("Digite o segundo numero: "); scanf("%d", &y); retorno=diferenca(x,y); printf("A diferenca entre os numeros e: %d",retorno); return 0; }
Python
UTF-8
6,458
2.859375
3
[]
no_license
from unittest.mock import inplace import numpy as np import requests from bs4 import BeautifulSoup from bs4 import Comment import pandas as pd # Función para obtener la tabla de los datos de cada llamda que hacemos mediante BeautifulSoup def get_dataframe_data_from_soup(soup): comments = soup.find_all(string=lambda text: isinstance(text, Comment)) tables = [] for each in comments: if 'table' in each: try: tables.append(pd.read_html(each)[0]) except: continue df = tables[0] return df # Función para eliminar los datos genéricos por cada fila de cada llamada def drop_generic_columns(df): df.drop('Jugador', axis=1, inplace=True) df.drop('País', axis=1, inplace=True) df.drop('Posc', axis=1, inplace=True) df.drop('Equipo', axis=1, inplace=True) df.drop('Edad', axis=1, inplace=True) df.drop('Nacimiento', axis=1, inplace=True) df.drop('90 s', axis=1, inplace=True) df.drop('Partidos', axis=1, inplace=True) return df # Función para eliminar las cabeceras que se van poniendo cada X filas en cada llamada def drop_rows_heeaders(df): indexs_drop = df[df['RL'] == 'RL'].index df.drop(index=indexs_drop, inplace=True) return df # Función para eliminar las columnas de las estadísticas básicas que no nos interesan def drop_columns_basic_stats(df_stats_base): # Nos quedamos con los valores de ambas columnas para renombrarlas después col_gls = df_stats_base['Por 90 Minutos']['Gls.'] col_gls_90 = df_stats_base['Por 90 Minutos']['Gls.'] df_stats_base.columns = [col[1] for col in df_stats_base.columns] df_stats_base.drop('Gls.', axis=1, inplace=True) df_stats_base.drop('xG', axis=1, inplace=True) df_stats_base.drop('npxG', axis=1, inplace=True) df_stats_base.drop('xA', axis=1, inplace=True) df_stats_base.drop('npxG+xA', axis=1, inplace=True) df_stats_base.drop('xG+xA', axis=1, inplace=True) df_stats_base.drop('Partidos', axis=1, inplace=True) df_stats_base['Gls.'] = col_gls df_stats_base['Gls/90'] = col_gls_90 return df_stats_base # Función para eliminar las columnas de las estadísticas de disparos que no nos interesan def drop_columns_shoot_stats(df_stats_shoot): df_stats_shoot.columns = [col[1] for col in df_stats_shoot.columns] df_stats_shoot = drop_generic_columns(df_stats_shoot) df_stats_shoot.drop('Gls.', axis=1, inplace=True) df_stats_shoot.drop('TP', axis=1, inplace=True) df_stats_shoot.drop('TPint', axis=1, inplace=True) df_stats_shoot.drop('xG', axis=1, inplace=True) df_stats_shoot.drop('npxG', axis=1, inplace=True) df_stats_shoot.drop('npxG/Sh', axis=1, inplace=True) df_stats_shoot.drop('G-xG', axis=1, inplace=True) df_stats_shoot.drop('np:G-xG', axis=1, inplace=True) return df_stats_shoot def drop_columns_misc_stats(df_stats_misc): df_stats_misc.drop('RL', axis=1, inplace=True) df_stats_misc.drop('TA', axis=1, inplace=True) df_stats_misc.drop('TR', axis=1, inplace=True) df_stats_misc.drop('Pcz', axis=1, inplace=True) df_stats_misc.drop('TklG', axis=1, inplace=True) df_stats_misc.drop('Penal ejecutado', axis=1, inplace=True) return df_stats_misc def modify_country_age(df_stats_base): df_stats_base['País'] = df_stats_base['País'].str[3:] df_stats_base['Edad'] = df_stats_base['Edad'].str[:2] return df_stats_base def get_stats_base(): # Realizamos la llamada a las estadisticas básicas url_stats_base = 'https://fbref.com/es/comps/12/stats/Estadisticas-de-La-Liga' soup_stats_base = BeautifulSoup(requests.get(url_stats_base).text, 'html.parser') # Recuperamos la tabla con los datos que nos interesa df_stats_base = get_dataframe_data_from_soup(soup_stats_base) # Borramos las columnas que opinamos que no son de utilidad df_stats_base = drop_columns_basic_stats(df_stats_base) # Modificamos el formato en el que está el país y la edad df_stats_base = modify_country_age(df_stats_base) # Eliminamos las cabeceras que aparecen cada X filas df_stats_base = drop_rows_heeaders(df_stats_base) return df_stats_base def get_stats_shoot(): # Realizamos la llamada a las estadisticas de disparos url_stats_shoot = 'https://fbref.com/es/comps/12/shooting/Estadisticas-de-La-Liga' soup_stats_shoot = BeautifulSoup(requests.get(url_stats_shoot).text, 'html.parser') # Recuperamos la tabla con los datos que nos interesa df_stats_shoot = get_dataframe_data_from_soup(soup_stats_shoot) # Borramos las columnas que opinamos que no son de utilidad df_stats_shoot = drop_columns_shoot_stats(df_stats_shoot) # Eliminamos las cabeceras que aparecen cada X filas df_stats_shoot = drop_rows_heeaders(df_stats_shoot) df_stats_shoot.drop('RL', axis=1, inplace=True) df_stats_shoot['Dist'].replace(np.nan,'0',inplace=True) # Transformamos la distancia del chute de yardas a metros df_stats_shoot['Dist'] = (pd.to_numeric(df_stats_shoot['Dist'])/1.0936).map('{:,.2f}'.format) return df_stats_shoot def get_stats_misc(): # Realizamos la llamada a las estadisticas diversas url_stats_misc = 'https://fbref.com/es/comps/12/misc/Estadisticas-de-La-Liga' soup_stats_misc = BeautifulSoup(requests.get(url_stats_misc).text, 'html.parser') # Recuperamos la tabla con los datos que nos interesa df_stats_misc = get_dataframe_data_from_soup(soup_stats_misc) df_stats_misc.columns = [col[1] for col in df_stats_misc.columns] df_stats_misc = drop_generic_columns(df_stats_misc) df_stats_misc = drop_rows_heeaders(df_stats_misc) df_stats_misc = drop_columns_misc_stats(df_stats_misc) return df_stats_misc def save_dataset(df_final): # Guardamos el dataframe con todos los datos df_final.to_csv('estadisticas_jugadores_lfp_20_21.csv', sep=';', index=False) df_stats_base = get_stats_base() df_stats_shoot = get_stats_shoot() df_stats_misc = get_stats_misc() # Hacemos una concatenación de los dos tipos de estadisticas, ambas están ordenadas por nombre, por tanto simplemente concatenando es suficiente df_merge = pd.concat([df_stats_base, df_stats_shoot], axis=1) # Hacemos una concatenación del dataframe concatenado más el dataframe de estadísticas varias df_final = pd.concat([df_merge, df_stats_misc], axis=1) save_dataset(df_final)
C++
UTF-8
1,065
3.453125
3
[]
no_license
//This file contains main function. It is used to test a data structure, binary search tree. #include "BSTree.h" #include <iostream> using namespace std; void main() { BSTree<int> bt; int a[8]={25,18,30,11,16,65,33,6}; for(int i=0;i!=8;++i) { bt.insert(a[i]); } cout<<"bt is an int binary search tree, whose initial numbers are 25 18 30 11 16 65 33 and 6"<<endl; cout<<"TEST---------------------------------------------------------ON"<<endl; cout<<"The smallest number of bt is "<<bt.findMin()<<endl<<"The largest number of bt is "<<bt.findMax()<<endl; cout<<"Preorder traversal bt: "<<ends; bt.pre_print(cout); cout<<endl; bt.insert(21); bt.insert(27); bt.remove(65); cout<<"After inserting 21 and 27 and removing 65, preorder traversal bt:"<<ends; bt.pre_print(cout); cout<<endl; bt.remove(11); BSTree<int> bt1(bt); cout<<"After remove 11, mimimum and maximum of bt are "; cout<<bt.findMin()<<ends<<bt.findMax()<<endl; cout<<"bt1 is a copy of bt. Preorder traversal bt1: "<<ends; bt1.pre_print(cout); system("pause"); }
Java
UTF-8
8,844
2.203125
2
[]
no_license
package com.milind.chatapp.activity; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.milind.chatapp.R; import com.milind.chatapp.adapter.MessageListAdapter; import com.milind.chatapp.model.BotQuestions; import com.milind.chatapp.model.Chat; import com.milind.chatapp.model.Message; import com.milind.chatapp.model.User; import com.milind.chatapp.utils.Utility; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Random; import io.realm.Realm; import io.realm.RealmList; import io.realm.RealmResults; public class ChatActivity extends AppCompatActivity { private RecyclerView mMessageRecycler; private MessageListAdapter mMessageAdapter; private RealmList<Message> mMessageList; private User selfUser, botUser; private Button btnSend; private EditText etMessage; ArrayList<String> questions; BotQuestions botQuestions; Message botMessage; Chat chat; // "position" saves the current position of mMessageList. With the help of this position counter we're retrieving the questions from // questions list. int position = 0; int userMessageId = 0; int botMessageId = 0; private Realm mRealm; private static final String TAG = "ChatActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); Toolbar myChildToolbar = findViewById(R.id.toolbar); setSupportActionBar(myChildToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); int randomNumber = Utility.generatedThreeDigitRandomNumber(); userMessageId = randomNumber; botMessageId = randomNumber; mMessageList = new RealmList<>(); //initializing realm Realm.init(this); // creating an instance of Realm mRealm = Realm.getDefaultInstance(); chat = new Chat(); chat.setChatId("C" + randomNumber); initializeViews(); initializeMessageList(); // Here we're creating an object of BotQuestions to get our questions and initializing them in questions ArrayList botQuestions = new BotQuestions(); botQuestions.setQuestions(); questions = botQuestions.getQuestions(); mMessageAdapter = new MessageListAdapter(this, mMessageList); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false); mMessageRecycler.setLayoutManager(linearLayoutManager); mMessageRecycler.setAdapter(mMessageAdapter); mMessageRecycler.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { @Override public void onLayoutChange(View view, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { if (bottom < oldBottom) { mMessageRecycler.smoothScrollToPosition(mMessageAdapter.getItemCount()); } } }); btnSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mMessageRecycler.smoothScrollToPosition(mMessageAdapter.getItemCount()); selfUser = new User("101", "Milind", "https://randomuser.me/api/portraits/thumb/men/65.jpg"); String usersReply = etMessage.getText().toString(); Message userMessage; if (!TextUtils.isEmpty(usersReply)) { userMessage = new Message(getMessageId("me"), etMessage.getText().toString(), selfUser, Utility.getCurrentTime()); mMessageList.add(userMessage); mMessageAdapter.notifyDataSetChanged(); mRealm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.copyToRealmOrUpdate(userMessage); } }); // Check to see if there are no more questions in the questions ArrayList. And here we're generating the JSON. if (position == questions.size()) { generateJson(); etMessage.setText(""); } else { //Log.i(TAG, "onClick: position: " + position + " questions.size(): " + questions.size()); getTheNextQuestion(position); position++; etMessage.setText(""); } } else { Toast.makeText(ChatActivity.this, "Please write your response", Toast.LENGTH_SHORT).show(); } //hideKeyboard(etMessage); } }); } //for getting the next question from questions arraylist private void getTheNextQuestion(int position) { mMessageRecycler.smoothScrollToPosition(mMessageAdapter.getItemCount()); if (mMessageList != null) { botMessage = new Message(getMessageId("bot"), questions.get(position), botUser, Utility.getCurrentTime()); mMessageList.add(botMessage); mRealm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.copyToRealmOrUpdate(botMessage); } }); } } //for hiding the keyboard after typing is complete on EditText private void hideKeyboard(EditText editText) { editText.setText(""); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); } //For generating message Id's private String getMessageId(String userType) { String generatedMessageId; if (userType.equalsIgnoreCase("bot")) { generatedMessageId = "Q" + botMessageId; botMessageId++; return generatedMessageId; } else { generatedMessageId = "A" + userMessageId; userMessageId++; return generatedMessageId; } } //for initializing views private void initializeViews() { mMessageRecycler = findViewById(R.id.recyclerview_message_list); btnSend = findViewById(R.id.btnSend); etMessage = findViewById(R.id.etChatMessage); } //for initializing message list private void initializeMessageList() { botUser = new User("102", "bot", "https://randomuser.me/api/portraits/lego/1.jpg"); if (mMessageList != null) { botMessage = new Message(getMessageId("bot"), "Hello there. Please provide your name?", botUser, Utility.getCurrentTime()); mMessageList.add(botMessage); mRealm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.copyToRealmOrUpdate(botMessage); } }); } } // for generating the json private void generateJson() { Gson gson = new GsonBuilder().create(); String json = gson.toJson(mMessageList); Log.i(TAG, "json: " + json); } // method to add all ArrayList of messages to Realm private void addMessagesToDatabase() { mRealm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { for (Message message : mMessageList) { realm.copyToRealmOrUpdate(message); } } }); } @Override protected void onDestroy() { super.onDestroy(); mRealm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { chat.setMessages(mMessageList); realm.copyToRealmOrUpdate(chat); } }); if (mRealm != null) { mRealm.close(); } } }
C++
UTF-8
689
2.625
3
[]
no_license
#ifndef _HELPERH_ #define _HELPERH_ /* cellList class test */ #include <iostream> #include <sstream> #include <string> #include "cellList.hpp" void listPrint(const cellList& ls){ cellList::node* p = ls.current->prev; cellList::node* n = ls.current->next; cell currCell = ls.current->valCell; std::ostringstream buf; buf << "<--( "; if(p){ buf << p->valCell.getVal(); } else{ buf << "NULL"; } buf << " ) -- ( " << currCell.getVal() << " ) -- ( "; if(n){ buf << n->valCell.getVal(); } else{ buf << "NULL"; } buf << " )-->"; std::cout << buf.str() << std::endl; } #endif
Markdown
UTF-8
670
3.046875
3
[]
no_license
<img align="right" alt="GIF" src="https://user-images.githubusercontent.com/87219816/125399045-7a04d200-e3c9-11eb-9f4f-ddf21d42c619.png" width="205" height="205" /> It was my <b>first</b> ever game in Python. It encouraged me a lot to learn more about progamming. It increased my interest in programming when it ran successfully without any bug. <p> <b>Rules:</b> <br> The familiar game of Rock, Paper, Scissors is played like this: at the same time, two players display one of three symbols: a rock, paper, or scissors. A rock beats scissors, scissors beat paper by cutting it, and paper beats rock by covering it. ... Whenever one player wins, the other loses. </p>
SQL
UTF-8
848
2.53125
3
[]
no_license
\echo ------------------ENTRY_CENTRY_SELECT---------------- select now(); \timing delete from ENTRY_CENTRY_SELECT_GPTMP; insert into ENTRY_CENTRY_SELECT_GPTMP (CMD_TYPE,ENTRY_ID) select CMD_TYPE,ENTRY_ID from ENTRY_CENTRY_SELECT_INC_EXT; delete from ENTRY_CENTRY_SELECT_GPTMP_TODAY using ENTRY_CENTRY_SELECT_GPTMP where ENTRY_CENTRY_SELECT_GPTMP.ENTRY_ID=ENTRY_CENTRY_SELECT_GPTMP_TODAY.ENTRY_ID ; insert into ENTRY_CENTRY_SELECT_GPTMP_TODAY (CMD_TYPE,ENTRY_ID,CREATE_DATE,DECL_PORT,I_E_FLAG,TRADE_CO,AGENT_CODE,TRADE_NAME,AGENT_NAME,OP_ID,SEL_RESULT,RSK_TYPE,RSK_CREATE_DATE,RSK_TYPE_DESC,MANUAL_ARV) select CMD_TYPE,ENTRY_ID,CREATE_DATE,DECL_PORT,I_E_FLAG,TRADE_CO,AGENT_CODE,TRADE_NAME,AGENT_NAME,OP_ID,SEL_RESULT,RSK_TYPE,RSK_CREATE_DATE,RSK_TYPE_DESC,MANUAL_ARV from ENTRY_CENTRY_SELECT_INC_EXT; delete from ENTRY_CENTRY_SELECT_GPTMP; \timing
Java
UTF-8
370
2.0625
2
[]
no_license
public class Deck { // not sure if i need this (DECK) but i can put shared methods for both games here like shuffle and remove cards after they have been used to deal // for the remove card after using it in a deal (so you cant have 2 ace of spades) maybe implement a interface with a filter to check for duplicates. // the above might not be needed. }
Shell
UTF-8
912
2.765625
3
[]
no_license
#!/bin/bash # Install script for woeusb winimage=' _ __ __ _______ ____ | | / /___ ___ / / / / ___// __ ) | | /| / / __ \/ _ \/ / / /\__ \/ __ | | |/ |/ / /_/ / __/ /_/ /___/ / /_/ / |__/|__/\____/\___/\____//____/_____/ Script! by catx0rr Windows Bootable Creator in Linux github: https://github.com/slacka/WoeUSB' echo -e "$winimage" echo sudo apt-get install -y \ libwxgtk3.0-gtk3-dev \ build-essential \ checkinstall \ devscripts \ equivs \ gdebi-core \ git clone https://github.com/slacka/WoeUSB.git && cd WoeUSB ./setup-development-environment.bash && sudo gdebi woeusb-build-deps_3.3.12-2-g5e9a3a7_all.deb dpkg-buildpackage -uc -b sudo gdebi ../woeusb_3.3.12-2-g5e9a3a7_amd64.deb autoreconf --force --install ./configure make sudo make install cd .. rm -f woeusb* rm -rf WoeUSB sleep 0.5 echo "Done." woeusb > woeusb.txt less woeusb.txt rm -f woeusb.txt
C++
UTF-8
3,902
3.40625
3
[]
no_license
#include <iostream> #include <utility> #include <chrono> #include "Matrix.hpp" #include "Rand.hpp" using namespace std; using Clock = std::chrono::high_resolution_clock; using TimePoint = std::chrono::time_point<Clock>; std::mt19937 Rand::sBase( time(nullptr) ); std::uniform_real_distribution<float> Rand::sFloatGen; char sectionBreak[81]; const int iterations = 300; template <class T> Matrix<T> generateMatrix(); template <class T> void profileMatrixMultiplication(); template<class T> void profileMatrixTranspose(); int main() { std::fill(sectionBreak, sectionBreak + 79, '='); sectionBreak[79] = '\n'; sectionBreak[80] = '\0'; cout << "This program measures the execution time of my Matrix class." << endl; cout << "All matrices in this suite are 100x100" << endl; cout << "For each data type, the op is run " << iterations; cout << " times and the average run time is calculated." << endl; cout << sectionBreak; cout << "Profiling FLOAT matrix multiplication" << endl; profileMatrixMultiplication<float>(); cout << sectionBreak; cout << "Profiling DOUBLE matrix multiplication" << endl; profileMatrixMultiplication<double>(); cout << sectionBreak; cout << "Profiling INT matrix multiplication" << endl; profileMatrixMultiplication<int>(); cout << sectionBreak; cout << "Profiling UNSIGNED INT matrix multiplication" << endl; profileMatrixMultiplication<unsigned int>(); cout << sectionBreak; cout << "Profiling SHORT matrix multiplication" << endl; profileMatrixMultiplication<short>(); cout << sectionBreak; cout << "Profiling LONG matrix multiplication" << endl; profileMatrixMultiplication<long>(); cout << sectionBreak; //------------------------------------------------ cout << "Profiling FLOAT matrix transpose" << endl; profileMatrixTranspose<float>(); cout << sectionBreak; cout << "Profiling DOUBLE matrix transpose" << endl; profileMatrixTranspose<double>(); cout << sectionBreak; cout << "Profiling INT matrix transpose" << endl; profileMatrixTranspose<int>(); cout << sectionBreak; cout << "Profiling UNSIGNED INT matrix transpose" << endl; profileMatrixTranspose<unsigned int>(); cout << sectionBreak; cout << "Profiling SHORT matrix transpose" << endl; profileMatrixTranspose<short>(); cout << sectionBreak; cout << "Profiling LONG matrix transpose" << endl; profileMatrixTranspose<long>(); cout << sectionBreak; return 0; } template <class T> void profileMatrixMultiplication() { Clock::duration total(0); for (int i = 0; i < iterations; i++) { auto A = generateMatrix<T>(); auto B = generateMatrix<T>(); auto begin = Clock::now(); A * B; auto end = Clock::now(); total += (end - begin); } cout << endl; cout << "On average, multiplication takes " << chrono::duration_cast<chrono::microseconds>(total).count() / (1000.f * (float)iterations) << " ms" << endl; } template <class T> void profileMatrixTranspose() { Clock::duration total(0); for (int i = 0; i < iterations; i++) { auto A = generateMatrix<T>(); auto begin = Clock::now(); auto B = A.Transpose(); auto end = Clock::now(); total += (end - begin); } cout << endl; cout << "On average, transpose takes " << chrono::duration_cast<chrono::microseconds>(total).count() / (1000.f * (float)iterations) << " ms" << endl; } template <class T> Matrix<T> generateMatrix() { static int rows = 100; static int columns = 100; Matrix<T> A(rows, columns); for (size_t i = 0; i < rows; i++) { for (size_t j = 0; j < columns; j++) { A(i,j) = static_cast<T>(Rand::randInt(100)); } } return A; }
C#
UTF-8
3,210
2.921875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _013_练习 { class Program { static void Main(string[] args) { string diRenName = ""; int diRenLevel; float diRenHp; float diRenKonjili; Console.WriteLine("自定义敌人的名字"); diRenName = Console.ReadLine(); Console.WriteLine("自定义敌人的等级"); diRenLevel = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("自定义敌人的血量"); diRenHp = Convert.ToSingle(Console.ReadLine()); Console.WriteLine("自定义敌人的攻击力"); diRenKonjili = Convert.ToSingle(Console.ReadLine()); Console.WriteLine("敌人名字:" + diRenName); Console.WriteLine("敌人等级:" + diRenLevel); Console.WriteLine("敌人血量:" + diRenHp); Console.WriteLine("敌人攻击力:" + diRenKonjili); Console.WriteLine("自定义敌人的四段击效果"); Console.WriteLine("第一击攻击力乘积"); float diYi = Convert.ToSingle(Console.ReadLine()); Console.WriteLine("第二击攻击乘积"); float diEr = Convert.ToSingle(Console.ReadLine()); Console.WriteLine("第三击攻击力乘积"); float diSan = Convert.ToSingle(Console.ReadLine()); Console.WriteLine("第四击攻击力乘积"); float diSe = Convert.ToSingle(Console.ReadLine()); float zongShuChu = diRenKonjili * (diYi + diEr + diSan + diSe); Console.WriteLine("总输出量:"+zongShuChu); Console.WriteLine("计算梯形面积"); Console.WriteLine("梯形的上底"); float sanDi = Convert.ToSingle(Console.ReadLine()); Console.WriteLine("梯形的下底"); float xiaoDi = Convert.ToSingle(Console.ReadLine()); Console.WriteLine("梯形的高"); float height = Convert.ToSingle(Console.ReadLine()); float mianJi = (sanDi+xiaoDi)*height/2; Console.WriteLine("梯形的面积:" + mianJi); Console.WriteLine("计算圆的面积"); Console.WriteLine("圆的半径"); float banJing = Convert.ToSingle(Console.ReadLine()); float zhouChang = Convert.ToSingle(banJing * 2 * 3.14); float yuanMianJi = Convert.ToSingle(banJing*banJing*3.14); Console.WriteLine("圆的周长:"+zhouChang); Console.WriteLine("圆的面积:"+yuanMianJi); Console.WriteLine("请输入一个三位数的数字"); int shuZi=Convert.ToInt32(Console.ReadLine()); int geWei = shuZi % 10;//一个数字跟10求余得到是这个数字的个分位; int shiWei = (shuZi/10)%10;//一个数字跟10相除的话,相当于去掉这个数字的个分位(xyz/10=xy) int baiWei = shuZi / 100; int daoShu = geWei*100 + shiWei * 10 + baiWei; Console.WriteLine(daoShu); Console.ReadKey(); } } }
Java
UTF-8
371
2.375
2
[]
no_license
package com.class10; public class Homework { public static void main(String[] args) { // TODO Auto-generated method stub int[] numbers=new int[9]; numbers[0]=45; numbers[1]=78; numbers[2]=12; numbers[3]=67; numbers[4]=55; numbers[5]=89; numbers[6]=23; numbers[7]=77; numbers[8]=88; System.out.println(numbers[0]); } }
Markdown
UTF-8
415
2.640625
3
[]
no_license
## static 用static关键字来声明静态方法或静态变量 在静态方法中,不能直接访问非静态成员(包括方法和变量)。因为,非静态的变量是依赖于对象存在的,对象必须实例化之后,它的变量才会在内存中存在 ## 常见报错 ``` Cannot make a static reference to the non-static field list ``` 出错原因是在静态方法中直接访问非静态成员
Java
UTF-8
2,308
1.710938
2
[ "Apache-2.0" ]
permissive
package io.quarkus.smallrye.health.runtime; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.eclipse.microprofile.health.HealthCheckResponse; import org.eclipse.microprofile.health.spi.HealthCheckResponseProvider; import io.quarkus.arc.Arc; import io.quarkus.runtime.ShutdownContext; import io.quarkus.runtime.annotations.Recorder; import io.quarkus.vertx.http.runtime.devmode.FileSystemStaticHandler; import io.quarkus.vertx.http.runtime.webjar.WebJarNotFoundHandler; import io.quarkus.vertx.http.runtime.webjar.WebJarStaticHandler; import io.smallrye.health.SmallRyeHealthReporter; import io.vertx.core.Handler; import io.vertx.ext.web.RoutingContext; @Recorder public class SmallRyeHealthRecorder { public void registerHealthCheckResponseProvider(Class<? extends HealthCheckResponseProvider> providerClass) { try { HealthCheckResponse.setResponseProvider(providerClass.getConstructor().newInstance()); } catch (Exception e) { throw new IllegalStateException( "Unable to instantiate service " + providerClass + " using the no-arg constructor."); } } public Handler<RoutingContext> uiHandler(String healthUiFinalDestination, String healthUiPath, List<FileSystemStaticHandler.StaticWebRootConfiguration> webRootConfigurations, SmallRyeHealthRuntimeConfig runtimeConfig, ShutdownContext shutdownContext) { if (runtimeConfig.enable) { WebJarStaticHandler handler = new WebJarStaticHandler(healthUiFinalDestination, healthUiPath, webRootConfigurations); shutdownContext.addShutdownTask(new ShutdownContext.CloseRunnable(handler)); return handler; } else { return new WebJarNotFoundHandler(); } } public void processSmallRyeHealthRuntimeConfiguration(SmallRyeHealthRuntimeConfig runtimeConfig) { SmallRyeHealthReporter reporter = Arc.container().select(SmallRyeHealthReporter.class).get(); reporter.setAdditionalProperties(runtimeConfig.additionalProperties); reporter.setHealthChecksConfigs(runtimeConfig.check.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().enabled))); } }
PHP
UTF-8
2,345
2.625
3
[]
no_license
<?php namespace JeanForteroche\Blog\Model; require_once("model/Manager.php"); class MembersManager extends Manager { public function searchUserByMail($mail) { $db = $this->dbConnect(); $reqmail = $db->prepare("SELECT * FROM member_space WHERE mail = :mail"); $reqmail->execute(array( 'mail' => $mail )); return $reqmail; } public function searchUserbyPseudo($pseudo) { $db = $this->dbConnect(); $reqpseudo = $db->prepare("SELECT * FROM member_space WHERE pseudo = :pseudo"); $reqpseudo->execute(array( 'pseudo' => $pseudo )); return $reqpseudo; } public function insertNewMembers($pseudo, $mail, $mdpHached) { $db = $this->dbConnect(); $insertmbr = $db->prepare("INSERT INTO member_space (pseudo, mail, password, admin, moderator) VALUES (:pseudo, :mail, :password, 0, 0)"); $insertmbr->execute(array( 'pseudo' => $pseudo, 'mail' => $mail, 'password' => $mdpHached )); return $insertmbr; } public function connectUserByMail($mail) { $db = $this->dbConnect(); $reqmail = $db->prepare("SELECT * FROM member_space WHERE mail = :mail"); $reqmail->execute(array( 'mail' => $mail )); return $reqmail; } public function membersProfile($getid) { $db = $this->dbConnect(); if (isset($_GET['id']) and $_GET['id'] > 0) { $requser = $db->prepare('SELECT * FROM member_space WHERE id = :id'); $requser->execute(array( 'id' => $getid )); } } public function searchUserbySessionID($sessionID) { $db = $this->dbConnect(); $requser = $db->prepare("SELECT * FROM member_space WHERE id = :id"); $requser->execute(array( 'id' => $sessionID )); return $requser; } public function editPasswordbyUser($sessionID, $mdp1Hached) { $db = $this->dbConnect(); $insertmdp = $db->prepare("UPDATE member_space SET password = :password WHERE id = :id"); $insertmdp->execute(array( 'password' => $mdp1Hached, 'id' => $sessionID )); return $insertmdp; } }
Markdown
UTF-8
1,351
2.859375
3
[]
no_license
--- date: 2021-01-14 imdb_id: tt0056291 title: Knife in the Water (1962) grade: B slug: knife-in-the-water-1962 --- A married couple picks up a college-age hitchhiker and invites him aboard their sailboat for an overnight outing in Poland's Lake District. Nothing happens, yet _everything_ happens. <!-- end --> I kept wondering how Polanski shot it. That's a real boat on a real lake. No room for cameras or lights, yet Polanski places us aboard as a fourth passenger. Then there's the subtext. The near middle-aged husband seizes every opportunity to assert dominance over the young man. His wife, about the same age as the young man, morphs from unsure prim librarian to confident sultry sexpot as the voyage unfolds. The young man chafes against control, yet seems drawn to it. The script confines these volatile elements to close-quarters then steps away. I kept waiting for a traditional plot twist, and when none proved forthcoming, felt even more uncomfortable. This brings us to the ending, which I'm still processing. After placing us aboard the boat, Polanski ends his film by inviting us--no, _forcing_ us--to confront how we would react in the couple's shoes. A cinematic dictionary could define “haunting” with the film's closing shot. _Knife in the Water_ isn't a knockout, but a solid blow across the jaw that left me reeling.
Java
UTF-8
4,850
2.09375
2
[]
no_license
package com.example.stanley.hi_fivolunteeringprototype; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class AddFriendsFragment extends Fragment { private FriendsListAdapter adapter; private ListView friendsListView; private EditText etSearch; public static void setListViewHeightBasedOnChildren (ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) return; int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED); int totalHeight = 0; View view = null; for (int i = 0; i < listAdapter.getCount(); i++) { view = listAdapter.getView(i, view, listView); if (i == 0) view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WRAP_CONTENT)); view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED); totalHeight += view.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); listView.requestLayout(); } List<HashMap<String, String>> fList = new ArrayList<HashMap<String, String>>(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment ((MainActivity)getActivity()).hideNavBar(); View view= inflater.inflate(R.layout.fragment_add_friends, container, false); fList = new ArrayList<HashMap<String, String>>(); return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { ((MainActivity) getActivity()).setTitle("Add Friends"); ((MainActivity) getActivity()).addArrow(); String[] name = new String[]{ "Obara Sand", "Oberyn", "Olenna Tyrell", "Olyvar", }; int[] image = new int[]{ R.drawable.friends_1, R.drawable.friends_2, R.drawable.friends_3, R.drawable.friends_4, }; List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); for (int i = 0; i < 4; i++) { HashMap<String, String> hm = new HashMap<String, String>(); hm.put("name", name[i]); hm.put("image", Integer.toString(image[i])); fList.add(hm); } String[] from = {"name", "image"}; int[] to = {R.id.name, R.id.profile_pic}; SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), list, R.layout.friend_list_item, from, to); ListView lv = (ListView) view.findViewById(R.id.event_list); lv.setAdapter(simpleAdapter); setListViewHeightBasedOnChildren(lv); etSearch = getView().findViewById(R.id.search_friend); etSearch.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String text = etSearch.getText().toString().toLowerCase(); List<HashMap<String, String>> filtered_List_final = new ArrayList<HashMap<String, String>>(); for(int i=0; i < fList.size(); i++){ if(fList.get(i).toString().toLowerCase().contains(text)){ filtered_List_final.add(fList.get(i)); } } String[] from = {"name", "image"}; int[] to = {R.id.name, R.id.profile_pic}; SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), filtered_List_final, R.layout.friend_list_item, from, to); ListView lv = (ListView) getView().findViewById(R.id.event_list); lv.setAdapter(simpleAdapter); setListViewHeightBasedOnChildren(lv); } @Override public void beforeTextChanged(CharSequence s, int start, int count,int after) { } @Override public void afterTextChanged(Editable s) { } }); } }
C
UTF-8
997
2.859375
3
[ "Unlicense" ]
permissive
/* Nome: Arremesso de Bolas ID: 1532 Resposta: Accepted Linguagem: C (gcc 4.8.5, -O2 -lm) [+0s] Tempo: 0.000s Tamanho: 829 Bytes Submissao: 18/06/15 18:10:30 */ #include <stdio.h> #include <math.h> int main() { int N, V; unsigned i, j; while( scanf( "%d%d", &N, &V ) && N != 0 ){ int actual_position = 0, counter = 0, flag = 0; for( i = 1; i <= V; i++ ){ j = i; while( actual_position < N && j > 0 ){ actual_position += j; counter++; if( counter == j ){ counter = 0; j--; } } if( actual_position == N ){ flag = 1; break; } actual_position = counter = 0; } if( flag == 1 ){ puts( "possivel" ); } else{ puts( "impossivel" ); } } return 0; }
Swift
UTF-8
710
3.25
3
[]
no_license
// // Card.swift // DeckOfOneCard // // Created by Taylor Phillips on 2/20/17. // Copyright © 2017 Taylor Phillips. All rights reserved. // import Foundation class Card { private let suitKey = "suit" private let valueKey = "value" private let imageKey = "image" let suit: String let value: String let imageURL: String init?(dictionary: [String: Any]) { guard let suit = dictionary[suitKey] as? String, let value = dictionary[valueKey] as? String, let imageURL = dictionary[imageKey] as? String else { return nil } self.suit = suit self.value = value self.imageURL = imageURL } }
Java
UTF-8
1,812
2.359375
2
[]
no_license
package com.example.surfacepro3.week3; import android.app.ActionBar; import android.app.Activity; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; /** * Created by Surface Pro 3 on 14-5-2016. */ public class ShowPopUp extends Activity { PopupWindow popUp; LinearLayout layout; TextView tv; LinearLayout.LayoutParams params; LinearLayout mainLayout; Button but; boolean click =true; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); popUp = new PopupWindow(this); layout = new LinearLayout(this); mainLayout = new LinearLayout(this); tv = new TextView(this); but = new Button(this); but.setText("Click me"); layout.setBackgroundColor(0xFFFFFFFF); but.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(click){ popUp.showAtLocation(mainLayout, Gravity.BOTTOM,10,100); ; popUp.update(50,50,1000,200); click=false; }else{ popUp.dismiss(); click=true; } } }); params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); layout.setOrientation(LinearLayout.VERTICAL); tv.setText("Pop pop"); layout.addView(tv,params); popUp.setContentView(layout); mainLayout.addView(but,params); setContentView(mainLayout); } }
JavaScript
UTF-8
2,102
2.515625
3
[]
no_license
import { getUserTempId, getToken,setToken,removeToken } from '../../utils/userAbout.js'; import { reqUserInfo, reqUserLogin, reqUserLogout, reqUserRegister } from '../../api'; // 管理用户信息相关的数据 const state = { // getUserTempId() 获取临时标示id userTempId:getUserTempId(), // 必须是这个名字 token:getToken(), // 先在localStroge中获取token userInfo:{} } const mutations = { RECEIVE_TOKEN(state, token) { state.token = token }, // 处理用户信息 RECEIVE_USERINFO(state, userInfo) { state.userInfo = userInfo }, RESET_USERINFO(state) { // 包含用户信息和token state.userInfo = {} state.token = "" } } const actions = { // 注册 async userRegister({ commit },userInfo) { const result = await reqUserRegister(userInfo) if (result.code === 200) { return 'ok' } else { return Promise.reject(new Error('failed')) } }, // 获取登录 async userLogin({ commit },userInfo) { const result = await reqUserLogin(userInfo) if (result.code === 200) { commit('RECEIVE_TOKEN', result.data.token) setToken(result.data.token) // 这里要写返回值 return 'ok' } else { return Promise.reject(new Error('failed')) } }, // 获取用户信息 async getUserInfo({ commit }) { const result = await reqUserInfo() if (result.code === 200) { commit('RECEIVE_USERINFO', result.data) return 'ok' } else { return Promise(new reject('failed')) } }, // async resetUserInfo({ commit }) { removeToken() // 调用函数清除localStorage当中的token信息 commit('RESET_USERINFO') }, // 退出登录 async userLogout({ commit }) { const result = await reqUserLogout() if (result.code === 200) { removeToken() // 调用函数清除localStorage当中的token信息 commit('RESET_USERINFO') return 'ok' } else { return Promise.reject(new Error('failed')) } } } const getters = {} export default { state, mutations, actions, getters }
Shell
UTF-8
163
2.796875
3
[]
no_license
#!/bin/bash if [ -n "$1" ]; then sleeptime=$1 else sleeptime=1 fi echo Firing for $sleeptime gpio mode 8 out gpio write 8 1 sleep $sleeptime gpio write 8 0
Java
UTF-8
1,689
3.1875
3
[]
no_license
package com.coursera.randomstory; import com.coursera.edu.duke.FileResource; import com.coursera.gladlib.GladLib; import com.coursera.gladlib.GladLibMap; import java.util.HashMap; import java.util.Map; public class TestClass { public static final String FILE_PATH = "src/main/resources/likeit.txt"; public static void countWords(String myFile) { FileResource fileResource = new FileResource(myFile); Map<String, Integer> wordsFreq = new HashMap<>(); int totalWords = 0; for (String word : fileResource.words()) { word = word.toLowerCase(); if (wordsFreq.containsKey(word)) { wordsFreq.put(word, wordsFreq.get(word) + 1); } else { wordsFreq.put(word, 1); } totalWords += 1; } for (String word : wordsFreq.keySet()) { int occurrences = wordsFreq.get(word); if (occurrences > 200) { System.out.println(word + "\t" + occurrences); } } System.out.println("Total words in the file: " + totalWords); } public static void main(String[] args) { // GladLib storyGenerator = new GladLib(); // storyGenerator.makeStory(); // hashMaps // countWords(FILE_PATH); GladLibMap storyGenerator = new GladLibMap(); storyGenerator.makeStory(); System.out.println(); System.out.println("------------------------------"); System.out.println("Total words in the map: " + storyGenerator.totalWordsInMap()); System.out.println("Total words by used label : " + storyGenerator.totalWordsConsidered()); } }
Java
UTF-8
2,946
2.203125
2
[]
no_license
package com.example.themeal.activity; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import butterknife.BindView; import butterknife.ButterKnife; import android.os.Bundle; import android.os.Handler; import android.view.MenuItem; import android.widget.Toast; import com.example.themeal.R; import com.example.themeal.fragment.FragmentFavorites; import com.example.themeal.fragment.FragmentMenu; import com.example.themeal.fragment.FragmentSearch; import com.example.themeal.fragment.FragmentUser; import com.google.android.material.bottomnavigation.BottomNavigationView; public class MainActivity extends AppCompatActivity { boolean doubleBackToExitPressedOnce = false; @BindView(R.id.bottom_navigation) BottomNavigationView bottomNavigationView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); bottomNavigationView = findViewById(R.id.bottom_navigation); bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.menu: openFragment(FragmentMenu.newInstance()); return true; case R.id.favorites: openFragment(FragmentFavorites.newInstance()); return true; case R.id.users: openFragment(FragmentUser.newInstance()); return true; case R.id.search: openFragment(FragmentSearch.newInstance()); return true; } return false; } }); openFragment(FragmentMenu.newInstance()); } public void openFragment(Fragment fragment) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.frameNavigation, fragment); transaction.addToBackStack(null); transaction.commit(); } @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { super.onBackPressed(); finishAffinity(); // or finish(); return; } this.doubleBackToExitPressedOnce = true; Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce=false; } }, 2000); } }
Markdown
UTF-8
14,730
2.625
3
[]
no_license
--- layout: post comments: false title: "Hány cigány él Magyarországon?" excerpt: "A népszámlálások adataiból az derül ki, hogy Magyarországon 2001 és 2011 között 53%-kal, 205 720 főről 315 583 főre nőtt a cigányok száma. Mennyi a magyarországi cigányok valós száma?" date: 2017-08-07 17:27 categories: tudomany --- A népszámlálások adataiból az derül ki, hogy Magyarországon 2001 és 2011 között 53%-kal, 205 720 főről 315 583 főre nőtt a cigányok száma. A Központi Statisztikai Hivatal (KSH) népszámlálásai a nemzetiségre, az anyanyelvre, a családi, baráti közösségben használt nyelvre, és a kulturális kötődésre kérdeznek rá, de ezekre a válaszadás megtagadható. A nemzetiségi hovatartozásukról nem nyilatkozók száma 2001 és 2011 között két és félszeresére, 543 317 főről 1 398 731 főre emelkedett. Az 1. táblázatban az 1893-2003 közötti időszakban végzett mintavételek, cigányösszeírások eredményeit foglaltam össze. A reprezentatív szociológiai mintavételek a cigányok tényleges, a lakókörnyezet minősítése által meghatározott számát becsülték meg 1971-ben, 1993-ban és 2003-ban. Az 1893. évi cigányösszeírás egyedülálló a maga nevében, mivel hazánkban a mai napig nem történt ehhez hasonló, kifejezetten a cigányok számbavételét célzó kutatás. <figcaption> 1. táblázat: A magyarországi cigányok száma az 1893. évi cigányösszeírás és a szociológiai adatfelvételek alapján (Kertesi G. – Kézdi G. 1998, Kemény I. 2004). * A trianoni határokon belül. </figcaption> <table> <tr> <th>Év </th> <th>Felmérések, ezer fő (középérték) </th> <th>A modell szerint (ezer fő) </th> </tr> <tr> <td>1893</td> <td>59,982*</td> <td>60</td> </tr> <tr> <td>1971</td> <td>270-370 (320)</td> <td>300</td> </tr> <tr> <td>1993</td> <td>449-461 (455)</td> <td>472</td> </tr> <tr> <td>2003</td> <td>520-650 (585)</td> <td>580</td> </tr> <tr> <td>2015</td> <td></td> <td>743</td> </tr> <tr> <td>2020</td> <td></td> <td>823</td> </tr> </table> A cigányság száma **az elmúlt 110 évben megtízszereződött**: **60 ezer főről 600 ezer főre gyarapodott 2003-ig**. 2003-ban az össznépesség 10 millió 142 ezer fő volt, melynek **6%**-a a cigány nemzetiséghez tartozott. A népszámlálások kétszeresen alábecsülték a magyarországi cigányság tényleges számát! A cigányság 2015. évi számának becslésére és 2020-ig való előrejelzésére, egy egyszerű modellt készítettem. A rendelkezésre álló adatfelvételek adatpontjaira egy exponenciális függvényt illesztettem (1. ábra). <img src="{{ site.url }}/assets/gipsy/Cigany_modell-min.jpg" alt="A cigányok számának előrejelzése 2020-ig" class="medium" /> <figcaption>1. ábra: A cigányfelmérések eredményeire számolt exponenciális függvény (Hablicsek L. 2007). (Az R-ben írt kódot lásd az <a href="https://github.com/SalsaBoy990/R-codes" target="_blank">R-codes</a> gyűjteményemben.) </figcaption> Szépen látható, hogy a modell teljesen reprodukálja az 1893. évi összeírás értékét (60 ezer fő). **A cigányság 2015-ös létszámára 743 ezer jött ki, míg 2020-ra meg fogja haladni a 800 ezer főt.** Az 1. táblázatban közöltem a modell alapján visszaszámolt értékeket, amelyek kitűnő egyezést mutatnak a valós értékekkel (r<sup>2</sup>=0,99, p<0,001). A teljes termékenységi arányszám, vagyis az egy szülőképes korú (15-49 év) nőre eső gyerekszám, jó mutatja, hogy 1970 óta a magyar nők kevesebb gyereket szülnek (**a teljes népesség körében 1,3 gyerek/nő**, de ebbe a cigányok is beletartoznak), mint amennyi a népességszám szinten tartásához (2,1 gyerek/szülőképes nő) elegendő lenne. Ezzel szemben, kizárólag **a cigány nők esetén**, a termékenységi arányszám még mindig jelentősen meghaladja az átlagot (**3,0**). A cigányság gyerekszáma gyorsabban nő, mint a magyaroké. A születő magyar gyerekek száma viszont az elöregedő magyar társadalom halálozási ütemét nem képes ellensúlyozni. A cigányság számaránya a népességen belül pedig tovább növekszik, de szerencsére **az utóbbi tíz évben a cigány nők termékenységi arányszáma is lassan csökkenésnek indult** (2. táblázat). <figcaption> 2. táblázat: A teljes női lakosság és a cigány nők termékenységi arányszámai, 1930-31 és 1999-2002 között (Janky B. 2005) </figcaption> <table> <tr> <th>Időszak </th> <th>A teljes lakosság körében </th> <th>A cigány nők körében </th> </tr> <tr> <td>1930-31</td> <td>2,8</td> <td>n/a</td> </tr> <tr> <td>1969-70</td> <td>2,0</td> <td>n/a</td> </tr> <tr> <td>1990-93</td> <td>1,8</td> <td>3,3</td> </tr> <tr> <td>1995-98</td> <td>1,4</td> <td>3,3</td> </tr> <tr> <td>1999-2002</td> <td>1,3</td> <td>3,0</td> </tr> </table> Kizárólag a magyar nők esetén az egy szülőképes nőre jutó gyerekszám katasztrofálisan alacsony: 1,3 alatt van, mivel a cigányok szaporasága javít a statisztikán. Sajnos nem áll rendelkezésemre külön, csak a magyarokra vonatkozó adat. Így is egészen ritka adatokat adok közre. A teljes népesség és a cigányság élveszületési számának és arányának változásából kiderül, hogy **2003-ban már minden hatodik újszülött cigány volt** (3. táblázat) (Kemény I. 2004). A cigányság korösszetétele is teljesen eltér a magyarságétól: **a 15 év alattiak aránya a cigányok esetén megközelíti a 37%-ot**, míg **a 60 éven felüliek aránya 3,9%**-ot tesz ki. Ez fiatalos korszerkezetet jelent. Az össznépesség esetén azonban, a cigányokhoz képest, **a 15 éven aluliak aránya kevesebb, mint feleakkora** (16,1%), illetve **a 60 éven felüliek aránya több, mint ötször akkora** (20,8%). A tizenöt éven aluliak aránya meghaladja a hatvan éven felüliekét, ami elöregedő korszerkezetre utal (4. táblázat). <figcaption> 3. táblázat: Az élveszületések számának és arányának változása a teljes népesség és a cigányság körében 1971-2003 (Kemény I. 2004) </figcaption> <table> <tr> <th>Év </th> <th>A teljes lakosság körében (ezer fő) </th> <th>A cigány népesség körében </th> <th>A cigány születések aránya </th> </tr> <tr> <td>1971</td> <td>151</td> <td>10</td> <td><7%</td> </tr> <tr> <td>1993</td> <td>116</td> <td>13</td> <td>>11%</td> </tr> <tr> <td>2003</td> <td>94,647</td> <td>15</td> <td>15,8%</td> </tr> </table> <figcaption> 4. táblázat: A cigány háztartásokban élő és az országos népesség a 0-14 év közötti és a 60 év feletti korcsoportjainak százalékos megoszlása 2003-ban (Kemény I. 2004) </figcaption> <table> <tr> <th>Korcsoport </th> <th>A teljes népesség esetén </th> <th>A cigányok körében </th> </tr> <tr> <td>15 éven aluliak</td> <td>16,1</td> <td>36,8</td> </tr> <tr> <td>60 éven felüliek</td> <td>20,8</td> <td>3,9</td> </tr> </table> A könnyebb összehasonlíthatóság kedvéért, a 2-3. ábrákon megjelenítettem a cigány és a magyar korfát a 2001. évi népszámlálás adatainak felhasználásával. Megjegyzés: a vízszintes tengely beosztása a két korfán eltérő. A magyar lakosság esetén 39 év az átlagéletkor, míg a cigányoknál csupán 25. <img src="{{ site.url }}/assets/gipsy/Cigany_korfa-min.jpg" alt="A cigányok számának előrejelzése 2020-ig" class="small" /> <figcaption>2. ábra: A cigányságot jellemző korfa piramis alakú (KSH alapján). (Az R-ben írt kódot lásd az <a href="https://github.com/SalsaBoy990/R-codes" target="_blank">R-codes</a> gyűjteményemben.) </figcaption> <img src="{{ site.url }}/assets/gipsy/Magyar_korfa-min.jpg" alt="A cigányok számának előrejelzése 2020-ig" class="small" /> <figcaption>3. ábra: A magyarság korfája elöregedő korszerkezetet tükröz, urna alakú (KSH alapján). (Az R-ben írt kódot lásd az <a href="https://github.com/SalsaBoy990/R-codes" target="_blank">R-codes</a> gyűjteményemben.) </figcaption> **A cigányok 86,9%-ának végzettsége általános iskola** (8 évfolyam vagy annál kevesebb), **egyetemi, főiskolai végzettséggel mindössze 2607 fő rendelkezett** 2011-ben (5. táblázat). <figcaption> 5. táblázat: A magyar és a cigány népesség megoszlása a legmagasabb befejezett iskolai végzettség szerint, 2011-ben (KSH alapján). </figcaption> <table> <tr> <th>Legmagasabb iskolai végzettség </th> <th>Magyar (%) </th> <th>Cigány (%) </th> </tr> <tr> <td>8 évfolyamnál alacsonyabb</td> <td>18,1</td> <td>47,5</td> </tr> <tr> <td>8 évfolyam</td> <td>23,5</td> <td>39,4</td> </tr> <tr> <td>Középfokú iskola érettségi nélkül, szakmai oklevéllel</td> <td>18,0</td> <td>8,8</td> </tr> <tr> <td>Érettségi</td> <td>25,6</td> <td>3,4</td> </tr> <tr> <td>Főiskola, egyetem</td> <td>14,7</td> <td>0,8</td> </tr> </table> A 6. táblázatból világossá válik, hogy a szocializmus időszakában a cigányok foglalkoztatottsága (különösen a férfiak) jóval magasabb volt, egészen a rendszerváltozásig. Onnantól kezdve drasztikusan leesett a cigányok foglalkoztatottsága, és az adatok szerint 2003-ig változatlan volt. **1987-1993 között a férfiak esetén 45,6, a nők esetén 33, míg együtt 39,4%-kal csökkent a dolgozók aránya.** <figcaption> 6. táblázat: A cigány férfiak és nők foglalkoztatottsága 1971-2003 között százalékban (Janky B. 2005). * Az 1971-es, 1993-as és 2003-as országos reprezentatív cigányvizsgálat alapján. N: a minta nagysága, az adatok a 15–54 éves nők és 15–59 éves férfiak százalékában értendők. </figcaption> <table> <tr> <th> </th> <th>1971 </th> <th>1978 </th> <th>1987 </th> <th>1993 </th> <th>2003 </th> </tr> <tr> <td>Férfiak</td> <td>85,2</td> <td>77,3</td> <td>74,4</td> <td>28,8</td> <td>29,2</td> </tr> <tr> <td>Nők</td> <td>30,3</td> <td>47,0</td> <td>49,3</td> <td>16,3</td> <td>16,3</td> </tr> <tr> <td>Együtt</td> <td>n/a</td> <td>62,0</td> <td>62,0</td> <td>22,6</td> <td>22,7</td> </tr> <tr> <td>N</td> <td>n/a</td> <td>2875</td> <td>3888</td> <td>4842</td> <td>3081</td> </tr> </table> ## Végszó A szocializmus alatt kevés volt a „közveszélyes munkakerülő”. A nehézipar, a bányászat sok alacsonyan képzett munkaerőt szívott fel, ami munkát adott, a cigányoknak is. Viszont a rendszerváltoztatás során szétbomlasztották a magyar ipart, jelentősen megnövelve ezzel a munkanélküliséget. Ma a szociális ellátórendszeren élősködnek az Indiából származó cigányok (megélhetési gyerekcsinálók). A cigányokkal pedig csak keményen lehet bánni, hiszen a többségük csak az erőszakból ért. A cigányok beilleszkedési képtelenségét a cigányok viselkedésében kell keresni. Nem a magyarok szegregálják a cigányokat, hanem a cigányok magukat, mert **nem akarnak integrálódni**! A bőnözőket nem luxusbörtönbe kell zárni, hanem kemény munkatáborba, hogy társadalmilag hasznos tevékenységet folytassanak. Ez majd lelohasztja a cigányok bűnözésre való hajlamát. ## Felhasznált irodalom 1. *Hablicsek L.* (2007). [Kísérleti számítások a roma lakosság területi jellemzőinek alakulására és 2021-ig történő előrebecslésére.](http://demografia.hu/kiadvanyokonline/index.php/demografia/article/viewFile/540/483) – Demográfia 50(1), pp. 7-54. 2. *Janky B.* (2005). [A cigány nők társadalmi helyzete és termékenysége.](www.szmm.gov.hu/download.php?ctag=download&docID=20471) – In. Nagy I. – Pongrácz T. –Tóth I. Gy. (szerk.): Szerepváltozások. Jelentés a nők és férfiak helyzetéről, 2005. – TÁRKI, Ifjúsági, Családügyi, Szociális és Esélyegyenlőségi Minisztérium, Budapest. pp. 136–148. 3. *Kemény I.* (2004). [A magyarországi cigány népesség demográfiája.](http://www.demografia.hu/kiadvanyokonline/index.php/demografia/article/download/615/427) – Demográfia 47(3-4), pp. 335-346. 4. *Kertesi G. – Kézdi G.* (1998). [A cigány népesség Magyarországon.](http://econ.core.hu/file/download/Kertesi_Kezdi/A_cigany_nepesseg_Mo-n.pdf) (Dokumentáció és adattár.) – Socio-typo, Budapest. 467 p. * [KSH 2001. évi népszámlálás. 1.1. Nemzetiség.](http://www.nepszamlalas2001.hu/hun/kotetek/04/tabhun/tabl01/load01.html) (letöltve: 2015-05-27) * [KSH 2001. évi népszámlálás. Cigány, roma: 2.1. A népesség korév és nemek szerint, a nemek aránya.](http://www.nepszamlalas2001.hu/hun/kotetek/24/tables/loadcig2_1.html) (letöltve: 2015-05-25) * [KSH 2001. évi népszámlálás. Magyar: 2.1. A népesség korév és nemek szerint, a nemek aránya.](http://www.nepszamlalas2001.hu/hun/kotetek/24/tables/loadmagy2_1.html) (letöltve: 2015-05-25) * [KSH 2011. évi népszámlálás. 2.15.1. A népesség korcsoport, településtípus és nemek szerint, a nemek aránya.](http://www.ksh.hu/nepszamlalas/docs/tablak/nemzetiseg/09_02_15_01.xls) (letöltve: 2015-05-27) * [KSH 2011. évi népszámlálás. 2.1.6.1. A népesség nemzetiség, korcsoport, legmagasabb befejezett iskolai végzettség és nemek szerint.](http://www.ksh.hu/nepszamlalas/docs/tablak/teruleti/00/00_2_1_6_1.xls) (letöltve: 2015-05-26) * [KSH 2011. 1.1. A népesség a nemzetiségi hovatartozást befolyásoló tényezők szerint.](http://www.ksh.hu/nepszamlalas/docs/tablak/nemzetiseg/09_01_01.xls) (letöltve: 2015-05-27)
Python
UTF-8
4,927
3.296875
3
[]
no_license
from random import shuffle from random import randrange from copy import deepcopy def create_grid_checkered(width, height): grid = list() for r in range(height): row = list() for c in range(width): if r == 0 or c == 0 or r == height - 1 or c == width - 1: row.append(1) elif c % 2 and r % 2: row.append(0) else: row.append(1) grid.append(row) return grid def create_grid_blank(width, height): grid = list() for r in range(height): row = list() for c in range(width): row.append(0) grid.append(row) return grid def create_maze_depthfirst(width, height): maze = create_grid_checkered(width, height) w = (width - 1) // 2 h = (height - 1) // 2 vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)] def walk(x, y): vis[y][x] = 1 next_step = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)] shuffle(next_step) for (new_x, new_y) in next_step: if vis[new_y][new_x]: continue if new_x == x: maze[max(y, new_y) * 2][x * 2 + 1] = 0 if new_y == y: maze[y * 2 + 1][max(x, new_x) * 2] = 0 walk(new_x, new_y) walk(randrange(w), randrange(h)) notdone = True i = 1 while i < height and notdone: k = 1 while k < width and notdone: if maze[i][k] == 0: maze[i][k] = 2 notdone = False k += 1 i += 1 notdone = True i = height - 1 while i > -1 and notdone: k = width - 1 while k > -1 and notdone: if maze[i][k] == 0: maze[i][k] = 3 notdone = False k -= 1 i -= 1 return maze def create_new_path(grid, n_pieces=1): '''Removes random piece of wall in between [1/4 width, 1/4 height] and [3/4 width, 3/4 height]''' w = len(grid[0]) h = len(grid) change = 0 while change < n_pieces: x = randrange(int(w / 4), int(w / 4 * 3)) y = randrange(int(h / 4), int(h / 4 * 3)) if grid[y][x] == 1 and ((grid[y + 1][x] == 0 and grid[y - 1][x] == 0) or (grid[y][x - 1] == 0 and grid[y][x + 1] == 0)): grid[y][x] = 0 print(f"Removed wall at [{x},{y}]") change += 1 def create_new_path_bfs(grid, start, end, n_pieces_to_remove=1): def get_frequency(grid, n): w = len(grid[0]) h = len(grid) d = (w**2 + h**2) ** 0.5 return int(d / n) def get_neighbors(grid, grid_width, grid_height, pos): x = pos[0] y = pos[1] ngbs = list() if x > 0 and abs(grid[y][x - 1]) != 1: #add left ngbs.append([x - 1, y]) if x < grid_width - 1 and abs(grid[y][x + 1]) != 1: #add right ngbs.append([x + 1, y]) if y > 0 and abs(grid[y - 1][x]) != 1: #add down ngbs.append([x, y - 1]) if y < grid_height - 1 and abs(grid[y + 1][x]) != 1: #add up ngbs.append([x, y + 1]) return ngbs def new_path(grid, w, h, position): x = position[0] y = position[1] if y > h / 2 and (grid[y - 2][x] == 0 or grid[y - 2][x] == -1): grid[y - 1][x] = 0 print(f"Removed wall at [{x}, {y - 1}]") return [x, y - 1] elif y < h / 2 and (grid[y + 2][x] == 0 or grid[y + 2][x] == -1): grid[y + 1][x] = 0 print(f"Removed wall at [{x}, {y + 1}]") return [x, y + 1] elif x > w / 2 and (grid[y][x - 2] == 0 or grid[y][x - 2] == -1): grid[y][x - 1] = 0 print(f"Removed wall at [{x - 1}, {y}]") return [x - 1, y] elif x < w / 2 and (grid[y][x + 2] == 0 or grid[y][x + 2] == -1): grid[y][x + 1] = 0 print(f"Removed wall at [{x + 1}, {y}]") return [x + 1, y] else: return None tmp = deepcopy(grid) w = len(tmp[0]) h = len(tmp) queue = list() queue.append([start]) cnt = 0 if n_pieces_to_remove: f = get_frequency(grid, n_pieces_to_remove) print(f) while len(queue): path = queue.pop(0) current = path[-1] if current == end: grid[start[1]][start[0]] = 2 return True, path ngb = get_neighbors(tmp, w, h, current) if len(ngb) == 0 and n_pieces_to_remove > 0: cnt += 1 if cnt % f == 0: n_ngb = new_path(grid, w, h, current) if n_ngb: n_pieces_to_remove -= 1 ngb.append(n_ngb) elif cnt > 0: cnt -= 1 for n in ngb: new = list(path) new.append(n) queue.append(new) tmp[current[1]][current[0]] = -1 return False, None def find_start_xy(grid, w, h): i = 1 while i < h: k = 1 while k < w: if grid[i][k] == 2: return [k, i] k += 1 i += 1 return None def find_end_xy(grid, w, h): i = h - 1 while i > -1: k = w - 1 while k > -1: if grid[i][k] == 3: return [k, i] k -= 1 i -= 1 return None def print_grid(grid): for row in grid: for n in row: print(f"{n:2}", end=" ") print() def reset_visited(grid, w, h): i = 0 while i < h: k = 0 while k < h: if grid[i][k] == -1: grid[i][k] = 0 k += 1 i += 1 def create_maze_depthfirst_multipath(width, height, n_pieces_to_remove): maze = create_maze_depthfirst(width, height) create_new_path_bfs(maze, find_start_xy(maze, width, height), find_end_xy(maze, width, height),n_pieces_to_remove) return maze if __name__ == "__main__": h = 11 w = 11 g = create_maze_depthfirst_multipath(w,h, 3) print_grid(g)
C#
UTF-8
2,508
2.71875
3
[]
no_license
using System; using System.Text; namespace DarwinStebs { class MainClass { public static void Main (string[] args) { Console.Title = "DarwinStebs"; StringBuilder asmSourceCode = new StringBuilder (); asmSourceCode.AppendLine ("MOV AL,0F"); asmSourceCode.AppendLine ("MOV BL,50 ;just a comment"); asmSourceCode.AppendLine ("ADD AL,BL"); var compilerMemory = new Memory (0xF, 0xF); var compiler = new StebsCompiler (compilerMemory); compiler.Parse (asmSourceCode.ToString()); var newMem = compiler.memory; //setup cpu var mem = new Memory (); var cpu = new CentralProcessingUnit (); cpu.DefaultMemory = mem; //setup memory by hand byte p = 0x00; //set AL to 10 mem.Write (p++, 0xD0); mem.Write (p++, 0x00); mem.Write (p++, 0xFE); //increment AL mem.Write (p++, 0xA4); mem.Write (p++, 0x00); //jump back before AL if not ZERO mem.Write (p++, 0xC2); mem.Write (p++, 0xFC); //compare AL true mem.Write (p++, 0xDB); mem.Write (p++, 0x00); mem.Write (p++, 0x11); //compare AL false mem.Write (p++, 0xDB); mem.Write (p++, 0x00); mem.Write (p++, 0x12); //write AL to 30 in memory mem.Write (p++, 0xD2); mem.Write (p++, 0x30); mem.Write (p++, 0x00); //end mem.Write (p++, 0x00); //run cpu do { PrintCPUState (cpu); Console.ReadKey (true); } while(!cpu.NextStep ().Equals (0x00)); Console.WriteLine (); Console.WriteLine ("cpu finished!"); } private static void PrintCPUState(CentralProcessingUnit cpu) { Console.Clear (); Console.WriteLine ("Memory:"); for (int y = 0; y < cpu.DefaultMemory.Data.GetLength(0); y++) { for (int x = 0; x < cpu.DefaultMemory.Data.GetLength (1); x++) { byte value = cpu.DefaultMemory.Data[x, y]; if (value == 0x00) Console.ForegroundColor = ConsoleColor.Gray; //calc current x,y int cy = cpu.InstructionPointer >> 4; int cx = cpu.InstructionPointer & 0x0f; if (cx == x && cy == y) { Console.BackgroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.White; } Console.Write(cpu.DefaultMemory.Data[x, y].ToString ("X2")); Console.ResetColor (); Console.Write (" "); } Console.WriteLine (); } Console.ResetColor (); Console.WriteLine (); Console.WriteLine ("Register:"); foreach (Register r in cpu.RegisterBank) Console.WriteLine (r); Console.WriteLine (cpu.StatusRegister); } } }
Java
UTF-8
184
1.6875
2
[]
no_license
package com.pager.movieland.service; import com.pager.movieland.entity.Review; import java.util.List; public interface ReviewService { List<Review> getByMovieId(int movieId); }
C++
UTF-8
981
3.234375
3
[]
no_license
// Session22.cpp : Defines the entry point for the console application. // Accessing members of a structure #include "stdafx.h" #include <stdio.h> #include <conio.h> #include <iostream> using namespace std; struct BCA { char name[20]; long int roll; char blood; int age; } b; void getData(); void putData(); void main() { printf("\t\t\t\tWelcome to program\n\n"); printf("\nEnter data for the student \n"); getData(); putData(); _getch(); } void getData() { printf("\nEnter name of the student: "); gets_s(b.name); printf("Enter roll number: "); scanf_s("%ld", &b.roll); printf("Enter blood type: "); cin >> b.blood; printf("Enter age of that student: "); scanf_s("%d", &b.age); } void putData() { printf("\n\n\n\t\t\t\tAnd here's all the data\n\n\n"); printf("\nName of the student: "); puts(b.name); printf("Age of the student: %d", b.age); printf("\nBlood type of the student: %c", b.blood); printf("\nRoll number of the student: %ld", b.roll); }
Markdown
UTF-8
20,732
3.625
4
[]
no_license
[TOC] # 第11章_关联容器 > 关联容器中的元素是按==关键字==来保存和访问的 > 关联容器与顺序容器的不同之处反映了关键字的作用 - 关联容器支持==高效的==关键字查找和访问 - 两个主要的关联容器 - `map`:元素是一些==关键字--值(key-value)== 对 - 关键字:起索引所用 - 值:表示与索引相关联的数据 - `set`:每个元素只包含==一个关键字== - 支持高效的关键字查询操作(检查一个关键字是否在 set 中) - 标准库提供的关联容器(共 8 个)区别体现在三个维度上: - `set` or `map`: - 关键字是否重复: - 允许重复关键字的容器的名字中都包含单词 `multi` - 是否按顺序保存元素: - 不保持关键字按顺序存储的容器的名字都以单词 `unordered` 开头 - 无序容器使用==哈希函数==来组织元素 - 相关头文件 - 类型 `map` 和 `multimap`:\<map> - `map`: 又称关联数组,保存键值对 - `multimap`: 关键字可重复的 map - 类型 `set` 和 `multiset`:\<set> - `set`: 只保存关键字 - `multiset`: 关键字可重复的 set - 无序容器:\<unordered_map> 和 \<unordered_set> - `unordered_map`: 用哈希函数组织的 map - `unordered_set`: 用哈希函数组织的 set - `unordered_multimap`: 用哈希函数组织的 map,关键字可重复 - `unordered_multiset`: 用哈希函数组织的 set,关键字可重复 --- ## 11.1_使用关联容器 - map: - 关联容器也是模板 - 适用场景:将关键字==映射==为值 - 示例:单词计数 ```C++ map<string, size_t> word_count; string word; while (cin >> word) ++word_cound[word]; // 直接提取 word 的计数器并将其加 1(无论关键字是否已经存在) // 当从 map 中提取一个元素时,会得到一个 pair 类型的对象 // pair 是一个模板类型,保存两个名为 first 和 second 的公有数据成员 // map 使用 pair 的 first 保存关键字,使用 second 保存对应的值 for (const auto &w : word_count) cout << w.first << " occurs" << w.second << ((w.second > 1) ? "times" : "time") << endl; ``` - set - 适用场景:检验一个值(关键字)是否==存在== - 示例:对不在集合中的单词进行计数 ```C++ map<string, size_t> word_count; set<string> exclude = {"The", "But", "And", "Or", "An", "A", "the", "but", "and", "or", "an", "a"}; string word; while (cin >> word) // 集合使用 find 判断关键字是否存在 // 如果不存在,则返回尾后迭代器 // 如果存在,则返回指向关键字的迭代器 if (exclude.find(word) == exclude.end()) ++word_cound[word]; ``` --- ## 11.2_关联容器概述 - 关联容器的操作 - 一般操作: - ==支持== 9.2 节中介绍的==普通容器操作== - ==不支持==顺序容器的位置相关的操作(例如 push_back、push_front 等) - ==不支持==接受一个元素值和一个数量值的构造函数和插入操作 - 特有操作: - ==支持==一些顺序容器不支持的操作和类型别名 - ==提供==一些用来调整哈希性能的操作 - ==关联容器的迭代器都是双向的== ### 11.2.1 定义关联容器 - 定义 map :必须既指明关键字类型,又指明值类型 - 定义 set :只需指明关键字类型 - 定义关联容器(map 或 set) - 每个关联容器都定义了一个默认构造函数:创建一个指定类型的空容器 - 可以将关联容器初始化为另一个同类容器的拷贝 - 可以从一个范围来初始化关联容器(只要这些值可以转化为容器所需的类型) - 可以对关联容器进行值初始化(C++11 新标准) - 示例:初始化 map 和 set ```C++ map<string, size_t> word_count; // 空容器 set<string> exclude = {"the", "but", "and"}; // 列表初始化 set map<string, string> authors = {{"Joy", "James"}, {"Aus", "Jane"}}; // 列表初始化 map ``` - 示例:初始化 multimap 和 multiset ```C++ vector<int> ivec; for (vector<int>::size_type i = 0; i != 10; ++i) { ivec.push_back(i); ivec.push_back(i); // 每个数重复保存一次 } // 范围初始化 set<int> iset(ivec.cbegin(), ivec.cend()); multiset<int> miset(ivec.cbegin(), ivec.cend()); // 输出 cout << ivec.size() << endl; // 打印出 20 cout << iset.size() << endl; // 打印出 10 cout << miset.size() << endl; // 打印出 20 ``` ### 11.2.2 关键字类型的要求 - 对于有序容器(map、multimap、set、multiset),关键字类型必须定义元素比较的方法 - 默认情况系下,标准库使用==关键字类型的 `<` 运算符==来比较两个关键字 - 可以提供自定义的操作来代替关键字上的 `<` 运算符 - 自定义操作必须在关键字类型上==严格弱序==(具备如下基本性质) 1. 两个关键字不能同时**小于等于**对方 1. 如果 k1 **小于等于** k2 且 k2 **小于等于** k3,那么 k1 必须**小于等于** k3 1. 如果两个关键字,任何一个都不**小于等于**另一个,那么两个关键字==等价== - 注意: - 实际编程中,==重要的是==,如果一个类型定义了“行为正常”的 `<` 运算符,则它可以用作==有序容器==的关键字类型 - 对于等价的关键字,容器将它们视作相等来处理 - 使用关键字类型的比较函数 - 注意: - 用来组织一个容器中元素的操作的类型也是该容器类型的一部分 - 为了使用自定义的操作,必须在定义关联容器类型时提供此操作的类型 - 自定义的操作类型必须在尖括号中跟着元素类型给出 - 示例: ```C++ bool compareIsbn(const SalesData &lhs, const SalesData &rhs) { return lhs.isbn() < rhs.isbn(); } // 注意:当用 decltype 来获得一个函数指针类型时,必须加上一个 * 来表示要使用一个给定函数的指针类型 multiset<SalesData, decltype(compareIsbn) *> bookstore(compareIsbn); ``` ### 11.2.3 pair类型 - 头文件:\<utility> - 操作: - `pair<T1, T2> p;`: p 是一个 pair,两个类型分别为 T1 和 T2 的成员都进行了==值初始化== - `pair<T1, T2> p(v1, v2);`: p 是一个成员类型为 T1 和 T2 的 pair;first 和 second 成员分别用 v1 和 v2 进行初始化 - `pair<T1, T2> p = {v1, v2};`: 等价于上一个 - `make_pair(v1, v2);`: 返回一个用 v1 和 v2 初始化的 pair - pair 的类型从 v1 和 v2 的类型推断出来 - `p.first`: 返回 p 的名为 first 的公有数据成员 - `p.second`: 返回 p 的名为 second 的公有数据成员 - `p1 relop p2`: 关系运算符(<, <=, >, >=) 按字典序定义 - 当 p1.first < p2.first 或 !(p2.first < p1.first) && (p1.second < p2.second) 成立时,p1 < p2 为 true - 关系运算符利用元素的 `<` 运算符来实现 - `p1 == p2`: 当 first 和 second 成员分别相等时,两个 pair 相等 - `p1 != p2`: 否则,不相等;相等判断用元素的 `==` 运算符实现 - 示例: ```C++ pair<string, int> process(vector<string> &v) { if (!v.empty()) { return {v.back(), v.back().size()}; // 列表初始化返回值 // return make_pair(v.back(), v.back().size()); // 也可使用 make_pair 生成 pair 对象 } else { return pair<string, int>(); // 隐式构造返回值 } } ``` --- ## 11.3_关联容器操作 - 关联容器==额外的==类型别名 - `key_type`: 此容器类型的关键字类型 - `mapped_type`: 每个关键字关联的类型,==只适用于 map== - `value_type`: - 对于 set,与 key_type 相同 - 对于 map,为 pair<const key_type, mapped_type> - 由于不能改变一个元素的关键字,所以 pair 的关键字部分是 const 的 - 示例: ```C++ set<string>::value_type v1; // v1 是一个 string set<string>::key_type v2; // v2 是一个 string map<string, int>::value_type v3; // v3 是一个 pair<string, int> map<string, int>::key_type v4; // v4 是一个 string map<string, int>::mapped_type v5; // v5 是一个 int ``` ### 11.3.1 关联容器迭代器 - 解引用关联容器的迭代器 - 得到一个类型为容器的 ==value_type== 的值 - 注意:map 的 value_type 是一个 pair(可以改变 pair 的 second 的值,但不能改变 first 关键字成员的值) - 示例: ```C++ auto map_it = word_count.begin(); cout << map_it->first; cout << " " << map_it->second; map_it->first = "new key"; // 错误:关键字是 const 的 ++map_it->second; // 正确 ``` - set 的迭代器是 const 的 - 注意: - 虽然 set 类型同时定义了 iterator 和 const_iterator,但这两种类型都只允许==只读访问== set 中的元素 - set 中的关键字也是 const 的 - 示例: ```C++ set<int> iset = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; set<int>::iterator set_it = iset.begin(); if (set_it != iset.end()) { *set_it = 42; // 错误:set 中的关键字是 const 的 cout << *set_it << endl; // 正确:可以读取关键字 } ``` - 遍历关联容器 - 注意:当使用一个迭代器遍历一个 map、multimap、set 或 multimap 时,==迭代器按关键字升序==遍历元素 - 示例: ```C++ auto map_it = word_count.cbegin(); while (map_it != word_count.cend()) { cout << map_it->first << " occurs " << map_it->second << " times" <<endl; ++map_it; } ``` - 关联容器和算法 - 通常不对关联容器使用泛型算法 - 关键字是 const 这一特性意味着不能将关联容器传递给==修改或重排==容器元素的算法 - 对关联容器使用泛型搜索算法几乎总是个坏主意(效率低) - 关联容器的成员可以直接获取元素 - 泛型算法需要遍历操作才行 - 实际编程中,如果要对一个关联容器使用算法,要么将它当做一个源序列,要么当做一个目的位置 - 例如 copy 算法 ### 11.3.2 添加元素 - 向 map 或 set 添加元素 - 关联容器 insert 操作: - `c.insert(v)`: - v 是 value_type 类型的对象 - 对于 map 和 set,只有当元素的关键字不在 c 中时才插入(或构造) - 返回一个 pair,包含一个迭代器,指向具有指定关键字的元素,以及一个指示插入是否成功的 bool 值 - 对于 multimap 和 multiset,总是会插入(或构造)给定元素 - 返回一个指向新元素的迭代器 - `c.emplace(args)`: - args 用来构造一个元素 - `c.insert(b, e)`: - b 和 e 是迭代器,表示一个 c::value_type 类型值的范围 - 返回 void - 对于 map 和 set,只插入关键字不在 c 中的元素 - 对于 multimap 和 multiset,则会插入范围中的每个元素 - `c.insert(il)`: - il 是上述值的花括号列表 - `c.insert(p, v)`: - 类似 insert(v) - p 是迭代器,用来提示从哪里==开始搜索==新元素应该存储的位置 - 返回一个迭代器,指向具有给定关键字的元素 - `c.emplace(p, args)`: - 类似 emplace(args) - 注意: - 由于 map 和 set(以及对应的无序类型)包含不重复的关键字,因此插入一个==已存在==的元素对容器没有任何影响 - 对一个 map 进行 insert 操作时,必须牢记元素类型是 pair - 在 insert 的参数列表创建一个 pair 的方法 ```C++ word_count.insert({word, 1}); // 建议使用这种方法(C++11 新标准) word_count.insert(make_pair(word, 1)); word_count.insert(pair<string, size_t>(word, 1)); word_count.insert(map<string, size_t>::value_type(word, 1)); ``` - 示例: ```C++ map<string, size_t> word_count; string word; while (cin >> word) { auto ret = word_count.insert({word, 1}); if (!ret.second) // 指示没有成功插入(word 已在 word_count 中) { ++ret.first->second; // ++((ret.first)->second); // 与上式等价的表达式 } } ``` - 向 multiset 或 multimap 添加元素 - 示例:添加具有相同关键字的多个元素 ```C++ multimap<string, string> authors; authors.insert({"Barth, John", "Sot-Weed Factor"}); authors.insert({"Barth, John", "Lost in the Funhouse"}); ``` - 注意:对允许重复关键字的容器,接受单个元素的 insert 操作返回一个指向新元素的迭代器 - 无须返回一个 bool 值,因为 insert 总是向这类容器中加入一个新元素 ### 11.3.3 删除元素 - 从关联容器删除元素的操作 - `c.erase(k)`: 从 c 中删除==每个==关键字为 k 的元素 - 返回一个 size_type 值,指出删除的元素的数量 - 对于不保存重复关键字的容器,返回值总是 0 或 1 - 对允许重复关键字的容器,返回值可能大于 1 - 返回值为 0 表明想要删除的元素不在容器中 - `c.erase(p)`: 从 c 中删除迭代器 p 所指的那个元素 - p 必须指向 c 中一个真实元素(不能等于尾后迭代器) - 返回一个指向 p ==之后==元素的迭代器 - 如果 p 指向 c 中的尾元素,则返回尾后迭代器 - `c.erase(b, e)`: 从 c 中删除 b(含) 和 e(不含) 所表示的范围中的元素 - 返回 e - 示例: ```C++ // 删除一个关键字,返回删除的元素的数量 if (word_count.erase(remove_word)) cout << "ok: " << remove_word << " removed\n"; else cout << "oops: " << remove_word << " not found!\n"; // 对允许重复关键字的容器,返回值可能大于 1 auto cnt = authors.erase("Barth, John"); ``` ### 11.3.4 map的下标操作 - map 和 unordered_map 的下标操作 - `c[k]`:返回关键字为 k 的元素,返回的是==左值== - 如果 k 不在 c 中,==添加==一个关键字为 k 的元素,并对其进行==值初始化== - 由于可能插入新元素,所以只能对==非 const== 的 map 使用下标操作 - `c.at(k)`:访问关键字为 k 的元素,带参数检查 - 如果 k 不在 c 中,==抛出==一个 out_of_range 异常 - 示例: ```C++ map<string, size_t> word_count; word_count["Anna"] = 1; ``` - 注意: - set 类型不支持下标操作:因为 set 没有与关键字相关联的 “值” - multimap 和 unordered_multimap 类型没有下标操作:因为这些容器可能有多个值与一个关键字相关联 - ==与其他容器类型不同的是==: - 当对一个 map 进行下标操作时,得到的是 mapped_type 对象 - 当解引用一个 map 迭代器时,得到的是 value_type 对象 ### 11.3.5 访问元素 - 在一个关联容器中查找元素的操作 - `c.find(k)`: 在容器 c 中查找关键字 k - 返回一个迭代器,指向==第一个==关键字为 k 的元素 - 若 k 不在容器中,返回尾后迭代器 - `c.count(k)`: 在容器 c 中统计关键字 k 出现的次数 - 返回 k 出现的次数 - 对不允许重复关键字的容器,返回值永远是 0 或 1 - `c.lower_bound(k)`: 返回一个迭代器,指向容器 c 中==第一个关键字不小于== k 的元素 - `c.upper_bound(k)`: 返回一个迭代器,指向容器 c 中==第一个关键字大于== k 的元素 - `c.equal_range(k)`: 返回一个迭代器 ==pair==,表示关键字等于 k 的元素的范围 - 若 k 不存在,则 pair 的两个成员均等于尾后迭代器 - 备注: - lower_bound 和 upper_bound 不适用于无序容器 - 如果一个 multimap 或 multiset 中有多个元素具有给定关键字,则这些元素在容器中会==相邻存储== - 判断关键字是否出现在容器中时,如果不统计关键字出现的次数,最好使用 find - 示例: ```C++ if (word_count.find("foobar") == word_count.end()) cout << "foobar is not in the map" << endl; ``` - 示例:输出 map 中指定关键字的所有元素 ```C++ // 写法1 string search_item("Alain de Booton"); auto entries = authors.count(search_item); auto iter = authors.find(search_item); while (entries) { cout << iter->second << endl; ++iter; --entries; } // 写法2 for (auto beg = authors.lower_bound(search_item), end = authors.upper_bound(search_item); beg != end; ++beg) { cout << beg->second << endl; } // 写法3 for (auto pos = authors.equal_range(search_item); pos.first != pos.second; ++pos.first) { cout << pos.first->second << endl; } ``` ### 11.3.6 一个单词转换的map - [示例:11.3](./examples/11/11.3/main.cc) --- ## 11.4_无序容器 - 无序容器(C++11 新标准) - 使用一个==哈希函数==和关键字类型的 `==` 运算符来比较和组织元素(而不是比较运算符) - 哈希函数用来定位哈希桶 - `==` 运算符用来区分桶中的关键字 - 如果关键字类型固有就是无序的,或者性能测试发现问题可以用哈希技术解决,就可以使用无序容器 - 注:hash 函数将给定类型的值映射到整型(size_t) - 相等的值必须映射到相同的整数 - 不相等的值尽可能映射到不同的整数 - 无序容器的操作 - 提供了与有序容器相同的操作 - 因此,可以用一个无序容器替换对应的有序容器(反之亦然) - 此外,还提供了无序容器特有的哈希管理操作 - 桶接口 - `c.bucket_count()`: 正在使用的桶的数目 - `c.max_bucket_count()`: 容器能容纳的最多的桶的数量 - `c.bucket_size(n)`: 第 n 个桶中有多少个元素 - `c.bucket(k)`: 关键字为 k 的元素在哪个桶中 - 桶迭代 - `local_iterator`: 可以用来访问桶中元素的迭代器类型 - `const_local_iterator`: 桶迭代器的 const 版本 - `c.begin(n), c.end(n)`: 桶 n 的首元素迭代器和尾后迭代器 - `c.cbegin(n), c.cend(n)`: 前两个函数的 const 版本 - 哈希策略 - `c.load_factor()`: 每个桶的平均元素数量,返回 float 值 - `c.max_load_factor()`: c 试图维护的平均桶大小,返回 float 值 - c 会在需要时添加新的桶,以使得 load_factor <= max_load_factor - `c.rehash(n)`: 重组存储,使得 bucket_count >= n 且 bucket_count > size / max_load_factor - `c.reserve(n)`: 重组存储,使得 c 可以保存 n 个元素且不必 rehash - 备注: - 无序容器在存储上组织为一组**桶** - 哈希函数用于将元素映射到桶 - 无序容器的性能依赖于哈希函数的质量和桶的数量和大小 - 容器将具有特定哈希值的所有元素保存在相同的桶中 - 如果允许重复关键字 - 所有关键字相同的元素也会在同一个桶中 - 允许将不同关键字的元素映射到相同的桶 - 此时需要搜索桶中的元素来查找具体的关键字对应的元素 - 无序容器对==关键字==类型的要求 - 无需容器使用 - 关键字类型的 `==` 运算符来比较元素 - 一个 hash<key_type> 类型的对象来生成每个元素的哈希值 - 可作为无序容器关键字的类型 - 内置类型(包括指针) - 标准库类型(string、智能指针) - 使用自定义类类型作为无序容器的关键字的两种方法 1. 提供自己的 hash 模板(参考 16.5 节) 1. 重载关键字类型的 `==` 运算符和哈希函数 - 示例:将 SalesData 用作无序容器的关键字 ```C++ size_t hasher(const SalesData &sd) { return hash<string>()(sd.isbn()); } bool eqOp(const SalesData &lhs, const SalesData &rhs) { return lhs.isbn() == rhs.isbn(); } using SD_multiset = unordered_multiset<SalesData, decltype(hasher) *, decltype(eqOp) *>; SD_multiset bookstore(42, hasher, eqoOp); ``` - 注意:如果类已经定义了 `==` 运算符,则可以只重载哈希函数
Python
UTF-8
2,342
2.609375
3
[]
no_license
from bs4 import BeautifulSoup import re import requests headers = {"User-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36"} def crawl_prothom_alo(start_date_str, end_date_str): from datetime import datetime, timedelta base_url = "https://www.prothomalo.com" archive_url = base_url+"/archive/" start_date = datetime.strptime(start_date_str, "%Y-%m-%d") end_date = datetime.strptime(end_date_str, "%Y-%m-%d") delta = end_date - start_date for i in range(delta.days + 1): date = start_date + timedelta(days = i) url = archive_url+date.strftime("%Y-%m-%d") infile = open('Newspaper/prothom_alo_'+ date.strftime("%Y-%m-%d") + ".txt", "w+", encoding = 'utf-8') while url: print("reading url >>> "+url) try: html_content = requests.get(url, headers = headers).content except: print('Connection Problem for url: ', url, '. Skipping it.') break soup = BeautifulSoup(html_content, "lxml") links = soup.findAll('a', {'class': 'link_overlay'}, href = True) for link in links: try: inner_html_content = requests.get(base_url+link['href'], headers = headers).content except: print('Connection Problem for article, url: ', base_url+link['href']) continue inner_soup = BeautifulSoup(inner_html_content, "lxml") articleBody = inner_soup.find('div', {'itemprop': 'articleBody'}) if articleBody: headline = inner_soup.find('div', {'class': 'right_title'}).text print("headline >>> "+headline) infile.write(headline+"\n") infile.write(str(articleBody.text) + '\n\n') pagination_div = soup.find('div', {'class': 'pagination'}) url = None if pagination_div: next_page_link = pagination_div.find('a', {'class': 'next_page'}, href = True) if next_page_link: url = next_page_link['href'] infile.close() # crawl_prothom_alo("2017-03-08","2017-06-01") crawl_prothom_alo("2019-08-03","2019-09-01")
Java
UTF-8
1,249
2.953125
3
[]
no_license
package oop.ex6.main; import java.io.IOException; public class roiTests { public static void main(String[] args) throws IOException { // Parser parseMethods = new Parser(); // String name="hello"; String row = "void foo(int a){"; Parser pars = new Parser(); //// String[] keys = {"void", "final", "if", "while", "true", "false", "return", "int", "double", "boolean", "char", "String"}; // try { // Method testMethod = new Method(null, name, 6, row, 1); // pars.analyzeRow(row,0,2); // System.out.println("done"); // } catch (Exception e) { // e.printStackTrace(); // } String line = " char a ='r',b, c='r' "; try { System.out.println(Parser.extractFirstWord("abc%%", 3)); // pars.updateVariables(0, line, 5, "char"); // System.out.println("update variable is done"); } catch (IllegalException e) { e.printStackTrace(); System.out.println(e.getMessage()); } // ArrayList<Integer> array = new ArrayList<>(); // array.add(3); // array.add(2); // array.add(1); // array.remove(1); // array.add(1,5); } }
Java
UTF-8
7,416
2.078125
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2015 ArcBees 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 applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.arcbees.chosen.client; import java.util.ArrayList; import java.util.List; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Node; import com.google.gwt.dom.client.NodeList; import com.google.gwt.dom.client.OptGroupElement; import com.google.gwt.dom.client.OptionElement; import com.google.gwt.dom.client.SelectElement; import com.google.gwt.dom.client.Style; public class SelectParser { public static class GroupItem extends SelectItem { private int children; private String label; public int getChildren() { return children; } public void setChildren(int children) { this.children = children; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } @Override public boolean isGroup() { return true; } } public static class OptionItem extends SelectItem { private int arrayIndex; private String classes; private boolean disabled; private boolean empty; private int groupArrayIndex; private String html; private int optionsIndex; private boolean selected; private String style = ""; private String text; private String value; public int getArrayIndex() { return arrayIndex; } public void setArrayIndex(int arrayIndex) { this.arrayIndex = arrayIndex; } public String getClasses() { return classes; } public void setClasses(String classes) { this.classes = classes; } public int getGroupArrayIndex() { return groupArrayIndex; } public void setGroupArrayIndex(int groupArrayIndex) { this.groupArrayIndex = groupArrayIndex; } public String getHtml() { return html; } public void setHtml(String html) { this.html = html; } public int getOptionsIndex() { return optionsIndex; } public void setOptionsIndex(int optionsIndex) { this.optionsIndex = optionsIndex; } public String getStyle() { return style; } public void setStyle(String style) { this.style = style; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public boolean isEmpty() { return empty; } public void setEmpty(boolean empty) { this.empty = empty; } @Override public boolean isGroup() { return false; } public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } } public abstract static class SelectItem { protected int arrayIndex; protected boolean disabled; protected String domId; public int getArrayIndex() { return arrayIndex; } public String getDomId() { return domId; } public void setDomId(String domId) { this.domId = domId; } public boolean isDisabled() { return disabled; } public boolean isEmpty() { return false; } public abstract boolean isGroup(); } private final List<SelectItem> parsed; private int optionsIndex; public SelectParser() { optionsIndex = 0; parsed = new ArrayList<SelectItem>(); } public List<SelectItem> parse(SelectElement select) { NodeList<Node> children = select.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node n = children.getItem(i); addNode(n); } return parsed; } private void addGroup(OptGroupElement group) { int position = parsed.size(); GroupItem item = new GroupItem(); item.arrayIndex = position; item.label = group.getLabel(); item.children = 0; item.disabled = group.isDisabled(); parsed.add(item); NodeList<Node> children = group.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node n = children.getItem(i); if ("OPTION".equalsIgnoreCase(n.getNodeName())) { addOption(OptionElement.as((Element) n), position, group.isDisabled()); } } } private void addNode(Node child) { if (!Element.is(child)) { return; } Element e = Element.as(child); if ("OPTGROUP".equalsIgnoreCase(e.getNodeName())) { addGroup(OptGroupElement.as(e)); } else if ("OPTION".equalsIgnoreCase(e.getNodeName())) { addOption(OptionElement.as(e), -1, false); } } private void addOption(OptionElement option, int groupPosition, boolean groupDisabled) { String optionText = option.getText(); OptionItem item = new OptionItem(); item.arrayIndex = parsed.size(); item.optionsIndex = optionsIndex; if (optionText != null && optionText.length() > 0) { if (groupPosition != -1) { ((GroupItem) parsed.get(groupPosition)).children++; } item.value = option.getValue(); item.text = option.getLabel(); if (isNullOrEmpty(item.text)) { item.text = option.getText(); } item.html = option.getInnerHTML(); item.selected = option.isSelected(); item.disabled = groupDisabled ? groupDisabled : option.isDisabled(); item.groupArrayIndex = groupPosition; item.classes = option.getClassName(); item.style = getCssText(option.getStyle()); item.empty = false; } else { item.empty = true; item.groupArrayIndex = -1; } parsed.add(item); optionsIndex++; } private native String getCssText(Style s)/*-{ return s.cssText; }-*/; private boolean isNullOrEmpty(String s) { return s == null || s.isEmpty(); } }
Rust
UTF-8
554
2.859375
3
[ "MIT" ]
permissive
use serde::ser::Serializer; use serde::de::{Deserialize, Deserializer}; pub fn serialize<S>(option: &bool, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { if *option { serializer.serialize_some(&1u8) } else { serializer.serialize_none() } } pub fn deserialize<'de, D>(deserializer: D) -> Result<bool, D::Error> where D: Deserializer<'de> { let opt: Option<u8> = Option::deserialize(deserializer)?; match opt { Some(ref val) if *val == 1u8 => Ok(true), _ => Ok(false), } }
Python
UTF-8
1,839
2.609375
3
[ "MIT" ]
permissive
import os import numpy import toughio hybrid_mesh = toughio.Mesh( points=numpy.array( [ [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0], [0.0, 1.0, 1.0], [0.5, 0.5, 1.5], [0.0, 0.5, 1.5], [1.0, 0.5, 1.5], [2.0, 0.0, 0.0], [2.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [-1.0, 1.0, 0.0], ] ), cells=[ ("hexahedron", numpy.array([[0, 1, 2, 3, 4, 5, 6, 7]])), ("pyramid", numpy.array([[4, 5, 6, 7, 8]])), ("tetra", numpy.array([[4, 8, 7, 9], [5, 6, 8, 10]])), ("wedge", numpy.array([[1, 11, 5, 2, 12, 6], [13, 0, 4, 14, 3, 7]])), ], ) def relative_permeability(model, parameters, sl=None, atol=1.0e-8): import json this_dir = os.path.dirname(os.path.abspath(__file__)) filename = os.path.join( this_dir, "support_files", "relative_permeability_references.json" ) with open(filename, "r") as f: relperm_ref = json.load(f) sl = numpy.linspace(0.0, 1.0, 201) if sl is None else sl perm = model(*parameters) relperm = numpy.transpose(perm(sl)) assert numpy.allclose(relperm, relperm_ref[perm.name], atol=atol) def capillarity(model, parameters, sl=None, atol=1.0e-8): import json this_dir = os.path.dirname(os.path.abspath(__file__)) filename = os.path.join(this_dir, "support_files", "capillarity_references.json") with open(filename, "r") as f: pcap_ref = json.load(f) sl = numpy.linspace(0.0, 1.0, 51) if sl is None else sl cap = model(*parameters) pcap = cap(sl) assert numpy.allclose(pcap, pcap_ref[cap.name][: len(pcap)], atol=atol)
C++
UTF-8
782
3.171875
3
[]
no_license
#include <iostream> #include <regex> #include <string> #include <vector> auto main() -> int { std::regex regex(".*"); std::regex regex0("[0-9]+", std::regex_constants::extended); std::string str = "This is a pen."; std::cout << std::regex_search(str.begin(), str.end(), regex) << std::endl; std::cout << std::regex_search("12345678990", regex0) << std::endl; std::cmatch match; std::regex_search(str.c_str(), match, regex); if(!match.empty()){ std::cout << match.size() << " match." << std::endl; for(std::csub_match subMatch : match) std::cout << subMatch.str() << std::endl; } std::cmatch ma; std::regex regnew("\\w\\s"); std::regex_search(str.c_str(), ma, regnew); for(std::csub_match sub : ma) std::cout << sub.str() << ", "; std::cout << std::endl; }
Java
UTF-8
1,274
2.015625
2
[ "Apache-2.0", "LicenseRef-scancode-other-copyleft", "AGPL-3.0-only", "GPL-1.0-or-later", "AGPL-3.0-or-later" ]
permissive
package org.aksw.simba.quetsal.core.algebra; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import org.aksw.simba.quetsal.core.algebra.TopKSourceStatementPattern.Entry; import org.eclipse.rdf4j.query.algebra.TupleExpr; import com.fluidops.fedx.algebra.FedXExprVisitor; import com.fluidops.fedx.algebra.NTuple; import com.fluidops.fedx.structures.QueryInfo; public class JoinRestarter extends NTuple { private static final long serialVersionUID = 2238788874854683628L; List<TopKSourceStatementPattern.Entry> entries = new ArrayList<TopKSourceStatementPattern.Entry>(); public JoinRestarter(TupleExpr arg, List<TopKSourceStatementPattern> topksrcs, QueryInfo queryInfo) { super(Arrays.asList(arg), queryInfo); for (TopKSourceStatementPattern tksp : topksrcs) { List<Entry> entrs = tksp.getEntries(); entries.addAll(entrs); } } @Override public Set<String> getBindingNames() { return args.get(0).getBindingNames(); } @Override public Set<String> getAssuredBindingNames() { return args.get(0).getAssuredBindingNames(); } @Override public void visit(FedXExprVisitor v) { throw new RuntimeException("not implemented visit"); } public List<Entry> getEntries() { return entries; } }
Go
UTF-8
7,156
3.046875
3
[ "MIT" ]
permissive
// // Copyright (c) 2020 Markku Rossi // // All rights reserved. // package main import ( "fmt" ) var ( _ Expr = BoolValue(false) _ Expr = Int8Value(0) _ Expr = Int16Value(0) _ Expr = Int32Value(0) _ Expr = Int64Value(0) _ Expr = Float64Value(0) _ Expr = &binary{} _ Expr = &unary{} ) // Expr implements an expression. type Expr interface { Eval() (Value, error) } func parseExpr() (Expr, error) { return parseLogicalOR() } func parseLogicalOR() (Expr, error) { return parseLogicalAND() } func parseLogicalAND() (Expr, error) { return parseBitwiseOR() } func parseBitwiseOR() (Expr, error) { return parseBitwiseXOR() } func parseBitwiseXOR() (Expr, error) { return parseBitwiseAND() } func parseBitwiseAND() (Expr, error) { return parseEquality() } func parseEquality() (Expr, error) { return parseRelational() } func parseRelational() (Expr, error) { return parseShift() } func parseShift() (Expr, error) { return parseAdditive() } func parseAdditive() (Expr, error) { left, err := parseMultiplicative() if err != nil { return nil, err } for { if !input.HasToken() { return left, nil } t, err := input.GetToken() if err != nil { return nil, err } switch t.Type { case '+', '-': default: input.UngetToken(t) return left, nil } right, err := parseMultiplicative() if err != nil { return nil, err } left = &binary{ op: t.Type, col: t.Column, left: left, right: right, } } } func parseMultiplicative() (Expr, error) { left, err := parseUnary() if err != nil { return nil, err } for { if !input.HasToken() { return left, nil } t, err := input.GetToken() if err != nil { return nil, err } switch t.Type { case '*', '/', '%': default: input.UngetToken(t) return left, nil } right, err := parseUnary() if err != nil { return nil, err } left = &binary{ op: t.Type, col: t.Column, left: left, right: right, } } } func parseUnary() (Expr, error) { t, err := input.GetToken() if err != nil { return nil, err } switch t.Type { case '-': expr, err := parsePostfix() if err != nil { return nil, err } return &unary{ op: t.Type, col: t.Column, value: expr, }, nil default: input.UngetToken(t) return parsePostfix() } } func parsePostfix() (Expr, error) { t, err := input.GetToken() if err != nil { return nil, err } switch t.Type { case '(': expr, err := parseExpr() if err != nil { return nil, err } t, err = input.GetToken() if err != nil { return nil, err } if t.Type != ')' { return nil, NewError(t.Column, fmt.Errorf("unexpected token '%s'", t)) } return expr, nil case TInteger: return t.IntVal, nil case TFloat: return t.FloatVal, nil default: input.UngetToken(t) return nil, NewError(t.Column, fmt.Errorf("unexpected token '%s'", t)) } } type binary struct { op TokenType col int left Expr right Expr } func (b binary) String() string { return fmt.Sprintf("%s %s %s", b.left, b.op, b.right) } func (b binary) Eval() (Value, error) { v1, err := b.left.Eval() if err != nil { return nil, err } v2, err := b.right.Eval() if err != nil { return nil, err } t, err := ConversionType(v1, v2) if err != nil { return nil, err } switch t { case TypeInt8: i1, err := ValueInt8(v1) if err != nil { return nil, err } i2, err := ValueInt8(v2) if err != nil { return nil, err } var result int8 switch b.op { case '/': result = i1 / i2 case '*': result = i1 * i2 case '%': result = i1 % i2 case '+': result = i1 + i2 case '-': result = i1 - i2 default: return nil, NewError(b.col, fmt.Errorf("unsupport binary operand '%s'", b.op)) } return Int8Value(result), nil case TypeInt16: i1, err := ValueInt16(v1) if err != nil { return nil, err } i2, err := ValueInt16(v2) if err != nil { return nil, err } var result int16 switch b.op { case '/': result = i1 / i2 case '*': result = i1 * i2 case '%': result = i1 % i2 case '+': result = i1 + i2 case '-': result = i1 - i2 default: return nil, NewError(b.col, fmt.Errorf("unsupport binary operand '%s'", b.op)) } return Int16Value(result), nil case TypeInt32: i1, err := ValueInt32(v1) if err != nil { return nil, err } i2, err := ValueInt32(v2) if err != nil { return nil, err } var result int32 switch b.op { case '/': result = i1 / i2 case '*': result = i1 * i2 case '%': result = i1 % i2 case '+': result = i1 + i2 case '-': result = i1 - i2 default: return nil, NewError(b.col, fmt.Errorf("unsupport binary operand '%s'", b.op)) } return Int32Value(result), nil case TypeInt64: i1, err := ValueInt64(v1) if err != nil { return nil, err } i2, err := ValueInt64(v2) if err != nil { return nil, err } var result int64 switch b.op { case '/': result = i1 / i2 case '*': result = i1 * i2 case '%': result = i1 % i2 case '+': result = i1 + i2 case '-': result = i1 - i2 default: return nil, NewError(b.col, fmt.Errorf("unsupport binary operand '%s'", b.op)) } return Int64Value(result), nil case TypeFloat64: i1, err := ValueFloat64(v1) if err != nil { return nil, err } i2, err := ValueFloat64(v2) if err != nil { return nil, err } var result float64 switch b.op { case '/': result = i1 / i2 case '*': result = i1 * i2 case '+': result = i1 + i2 case '-': result = i1 - i2 default: return nil, NewError(b.col, fmt.Errorf("unsupport binary operand '%s'", b.op)) } return Float64Value(result), nil default: return nil, NewError(b.col, fmt.Errorf("unsupport values %s and %s for binary operand '%s'", v1, v2, b.op)) } } type unary struct { op TokenType col int value Expr } func (n unary) String() string { return fmt.Sprintf("-%s", n.value) } func (n unary) Eval() (Value, error) { val, err := n.value.Eval() if err != nil { return nil, err } switch val.Type() { case TypeInt32: ival, err := ValueInt32(val) if err != nil { return nil, err } var result int32 switch n.op { case '-': result = -ival default: return nil, NewError(n.col, fmt.Errorf("unsupported %s unary %s", val.Type(), n.op)) } return Int32Value(result), nil case TypeInt64: ival, err := ValueInt64(val) if err != nil { return nil, err } var result int64 switch n.op { case '-': result = -ival default: return nil, NewError(n.col, fmt.Errorf("unsupported %s unary %s", val.Type(), n.op)) } return Int64Value(result), nil case TypeFloat64: ival, err := ValueFloat64(val) if err != nil { return nil, err } var result float64 switch n.op { case '-': result = -ival default: return nil, NewError(n.col, fmt.Errorf("unsupported %s unary %s", val.Type(), n.op)) } return Float64Value(result), nil default: return nil, NewError(n.col, fmt.Errorf("unsupport %s value %s for unary %s", val.Type(), val, n.op)) } }
C++
WINDOWS-1251
3,915
3.765625
4
[]
no_license
// CHAPTER_8 EXERCISE_1 // engplus.cpp // + Distances #include <iostream> using namespace std; /////////////////////////////////////////////////////////// class Distance // { private: int feet; float inches; public: // Distance() : feet(0), inches(0.0) { } // Distance(int ft, float in) : feet(ft), inches(in) { } // void getdist() { cout << "\n : "; cin >> feet; cout << " : "; cin >> inches; } // void showdist() { cout << feet << "\'-" << inches << '\"'; } // Distance operator+ (Distance) const; Distance operator- (Distance) const; }; /////////////////////////////////////////////////////////// // Distance Distance::operator+ (Distance d2) const { int f = feet + d2.feet; // float i = inches + d2.inches; // if (i >= 12.0) // 12 { i -= 12.0; // 12 f++; // 1 } return Distance(f, i); // } // Distance Distance::operator- (Distance d2) const { int f = feet - d2.feet; float i = inches - d2.inches; if (i < 0 && f > 0)// 0 - { i += 12.0; f--; } if (f<=0 && i<0) { cout << " !" << endl; exit(1); } return Distance(f, i); } /////////////////////////////////////////////////////////// int main() { setlocale(LC_ALL, ""); Distance dist1, dist3, dist4; // dist1.getdist(); // Distance dist2(11, 6.25); // // (dist1) - // (dist2) - (operator+) // dist3 // , feet inches // , .. d2.feet d2.inches // - , - //. , dist3 = dist1 - dist2; // //dist4 = dist1 - dist2 - dist3; // // , cout << "dist1 = "; dist1.showdist(); cout << endl; cout << "dist2 = "; dist2.showdist(); cout << endl; cout << "dist3 = "; dist3.showdist(); cout << endl; cout << "dist4 = "; dist4.showdist(); cout << endl; return 0; }
JavaScript
UTF-8
3,613
2.953125
3
[ "MIT" ]
permissive
// Imports Discord API const Discord = require('discord.js'); const client = new Discord.Client(); // Terms to identify, though not sure if this is case-sensitive. Will have to try out later const term = "study"; const anotherTerm = "STUDY"; const yetAnotherTerm = "Study"; const anotherAnotherTerm = "studying"; const buildUponAnotherStudy = "Studying"; // Added trigger when mentioning fail words const failWord = "fail"; const failWordTwo = "failed"; const failWordThree = "failure"; // Array of random messages mom bot sends. This is not the entire list of phrases she will send, but a rough idea var listOfAnswers = ['Yucky daughter', 'GO STUDY RIGHT NOW U UNGRATEFUL DAUGHTER', 'YOU DISAPPOINTMENT', 'WHY U BORN SO DUMB', 'YOU DISAPPOINT YOUR FAMILY', 'GO DO HOMEWORK! NOW!!!', 'YOUR COUSIN IS DOCTOR ALREADY!!', 'Stop think about girls and think about FUTURE!', 'DISGRACEFUL. GO STUDY', 'YOU DISHONOR ME BY NOT STUDYING!', 'Still no study? GO GET THE RICE PADDLE', 'NO RICE FO YU', 'NO WORK?? NO BOBA MONEY', 'GO TO THE CORNER AND KNEEL', 'NO FRY RICE FOR YOU', 'WHY U NO STUDY AND GET MARRY YET??', 'YOU GET CANCER IF YOU NO STUDY', 'A-SIAN, NOT B-SIAN', 'You forget to study? I forget to feed you.', 'You get below C, I PUT YOU BELOW SEA', 'WHY U GET F IN GENDER HUH????', 'U 1 in billion, now study and get me 1 billion money', 'YOU DISAPPOINT YOUR FAMILY', 'GO DO HOMEWORK NOW!!!', 'You are utter disaPPOINTMENT!!!!!', 'WHY YOU EMBARRASS ME IN FRONT OF CUTE FRIEND. STUDY HARDER', 'You want to be comedian? Go fucking study, who told you you were punny???','I didn\'t raise a bottom now, did I', 'Lazy gay child', 'You cheap just like your grades. Now study' ]; // Turns on bot to detect received messages in server. receivedMessage as an alias for "message" client.on("message", (receivedMessage) => { // Sends a confirmation message to terminal confirming that bot does indeed work console.log("It works!!"); // Prevents bot from responding to itself, like anti-recursion kind of if (receivedMessage.author == client.user) { return; if (message.author.bot) { return; } } // Might've been to bypass the promises error. Checks to see if the message is blank or not in the first few chars if (!receivedMessage.content[0] == " " && !receivedMessage.content[1] == "") { // Checks the user's message for any of the terms mentioned above related to studying. Also added feature to trigger bot when bot is tagged as well as mentions fail words if ((receivedMessage.content.includes(term) || receivedMessage.content.includes(anotherTerm) || receivedMessage.content.includes(yetAnotherTerm) || || receivedMessage.content.includes(failWord) || receivedMessage.content.includes(failWordTwo) || receivedMessage.content.includes(failWordThree) || receivedMessage.content.includes(client.user.id))) { // Gets a random number to call from the array of messages to send var randomNum = Math.floor((Math.random((listOfAnswers.length + 1)) * listOfAnswers.length)); var getAnAnswer = listOfAnswers[randomNum]; // Converts array object to a string that's to be sent var asianResponse = String.toString(getAnAnswer); // Finally parses and sends the message back receivedMessage.channel.send(getAnAnswer); } } }) // Token hidden for privacy. Get your own token pls bot_token = ''; // Logs into Discord API with token and activates this bot client.login(bot_token);
Markdown
UTF-8
4,940
2.703125
3
[ "Apache-2.0" ]
permissive
--- layout: post title: "Like sunday like rain" subtitle: "" date: 2016-07-30 12:00:00 author: "xinwuzu" header-img: "img/post-bg-likesunrain.jpg" header-mask: 0.3 catalog: true tags: - 影评 ---   用了两个晚上看完朋友提到的这部《like sunday like rain》,加上这篇小文几乎是整整一周的业余时间,完全不是我的节奏(也是最近加班太多%>_<%)。一部很棒的人文片,诗意的中文翻译《如晴天,似雨天》已足以让人顿生好感。不管是诗意的意译“如晴天,似雨天”,还是味同嚼蜡的台版直译“像星期天像雨”,很难将影片的内容与它的名字直接联系起来。据说编剧想表达的仅仅是一种淡淡的忧伤,现在看来他得逞了。简单的情节和设定,舒缓的节奏,淡淡的忧愁,“静静地看完,然后得到治愈”。 ![](http://7xqi68.com1.z0.glb.clouddn.com/likesun4.jpg) 然后,在豆瓣上翻了几篇影评: ``` 1.落魄美女与霸道总裁的爱情故事。 ``` hah,豁然开朗,全都是套路!不过这次霸道总裁只有十二岁~ ``` 2.这是一部关于孤独、陪伴、友谊,夏天、阅读和音乐的电影。 ``` 凌乱中。。。到底想要表达什么? ``` 3.相处之下他们在彼此间找到自我。 ``` 这才是文艺片应该有说法的嘛。**找到自我!找到自我?**即便是同一部电影,不同人的理解会因为代入感的差异而变得非常明显。 ### 关于才华   首先被小正太Reggie的才华甚至可以说是天才所感动。小小年纪,就至少同时在数学、音乐、语言方面展现出过人的天赋。数学课上他轻蔑地对老师说,```“Euler was pretty thorough. ”```网友说,```“Reggie的话真是太精彩了!我恨不得都背下来。”```才华横溢的他魅力四射。才华本身带来感动,即便虚构如动漫人物樱木花道那句狂妄的“我果然是个天才!”,抑或是《美丽心灵》中约翰纳什教授疯癫中的天才,依然令人动容不已。人们依靠才华进行创造而不是体力,人生没有才华的点缀和闪耀是非常遗憾的。最近工作变得有些吃力,心态也不怎么好,突然感觉自己好像什么也不会,有些迷失了。“不知从哪儿来的优越感”也不知到哪儿去了。没了灵感,不仅生活没了灵感,工作也没了灵感。做总体设计要是没了灵感,那就只有靠时间的惨淡经营了,自给自足无以为继。   Reggie同时也是强大的,他明确地知道自己想要的是什么,应该怎么做,**他不需要找到自我**。他的忧愁孤独,一个人的孤独,因为没人愿意真正进入他的世界。他主动理解别人,温柔地对待这个世界,同样也希望被温柔地对待。他只是期待这样一个人,能理解他能真正跟他对话。这时,Eleanor出现了。 ![](http://7xqi68.com1.z0.glb.clouddn.com/likesun1.jpg) ### 关于音乐   影片最大的亮点在于同名配乐,故事在这首曲子中开始和结束,情节和音乐配合得天衣无缝。旋律带来的干净、轻柔和淡淡的忧伤,也正是故事的底色。我是先遇到音乐的,在无限循环之后,循着音乐来看了电影。于我,与其讲音乐完美地渗透到故事之中,不如说情节漂亮地融入到音乐之中。图像帮助我更好的理解音乐:```抵挡不住大提琴的声音,大提琴的悲伤无法阻挡。```美美的一首曲子,的确是美。对电影情节内涵和外延的理解是五花八门的,而相比之下,几乎所有人都从音乐中感受到了这种淡淡的忧愁,原来我们生来就懂得聆听音乐。 ![](http://7xqi68.com1.z0.glb.clouddn.com/likesun2.jpg) ### 关于爱情 至于爱情,网友们已经说的相当好了。甚至有人相当复杂地表示: ``` 几个月的相处,他们之间却产生了一种旁人无法想象的, 透彻的相互理解,那是跨越年龄的友谊,超过友谊的亲 近,以及像极了爱情却又绝对无法定义为爱情的东西。 这部电影绝妙地拆解了所有固执的定义,让那些界限分 明的世俗概念在这两个人面前全然失效。 ``` 但我觉得那就是爱情,就像Reggie朗诵的这首诗: ``` Pillow'd upon my fair love's ripening breast, 枕在爱人酥软的胸脯上, To feel for ever its soft fall and swell, 永远感触那舒缓的升起和降落, Awake for ever in a sweet unrest, 醒来心里充满甜蜜的激荡, Still, still to hear her tender-taken breath, 不断,不断听着她细腻的呼吸, And so live ever—or else swoon to death. 就这样活着或昏迷地死去。 BY JOHN KEATS ``` 最后,Reggie的一句```I wonder if anyone will ever love me.```哇,简直泪奔!!! ![](http://7xqi68.com1.z0.glb.clouddn.com/likesun5.jpg)
Java
UTF-8
400
2.171875
2
[]
no_license
package com.winnertel.em.standard.snmp.gui; import com.winnertel.em.framework.model.snmp.SnmpMibBean; public abstract class SnmpTableFilter { /** * Determine whether a row(mib bean) is visible in table. * * @param aMibBean the bean to filter * @return true if the mib bean is filtered out, false otherwise */ public abstract boolean filter(SnmpMibBean aMibBean); }
Java
UTF-8
2,272
2.546875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.banco.controlador.hilos; import com.banco.controlador.Controlador; import com.banco.controlador.Controlador; import com.banco.modelo.vo.Compra; import com.banco.modelo.vo.Cuenta; import javax.swing.JButton; import javax.swing.JTextArea; /** * * @author Luis */ public class ProcesoCompra extends Thread{ Cuenta cuenta; String montoString; JTextArea mensajes; JButton boton; Controlador controlador; public ProcesoCompra(Cuenta cuenta, String monto, JTextArea mensajes, JButton boton, Controlador controlador){ this.cuenta = cuenta; this.montoString = monto; this.mensajes = mensajes; this.controlador = controlador; this.boton = boton; } @Override public void run() { double monto = controlador.calcularMonto(this.montoString); double iva = monto * Compra.IVA; double total = monto + iva; boolean completo = false; for (int i = 0; i < 7; i++) { try { double saldoActual = controlador.getCuentaDao().obtenerCuenta(cuenta.getClabe()).getSaldo(); if(saldoActual>= total){ String id = controlador.generaId(); Compra compra = new Compra(id, cuenta.getClabe(), monto, iva, total); mensajes.append(controlador.registrarCompra_Transaccion(cuenta, compra)); completo = true; break; }else{ mensajes.append("En Espera (Intento " + (i+1) +"/ 7)"); for(int c=0; c<3; c++) { mensajes.append("."); Thread.sleep(500); } mensajes.append("\n"); mensajes.setCaretPosition(mensajes.getDocument().getLength()); } } catch (InterruptedException ex) { System.out.println(ex.getMessage()); } } if(!completo) mensajes.append(Compra.COMPRA_FALLIDA + "\n"); boton.setEnabled(true); } }
Java
UTF-8
329
1.546875
2
[]
no_license
package org.launchcode.skillstrack; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SkillsTrackApplication { public static void main(String[] args) { SpringApplication.run(SkillsTrackApplication.class, args); } }
Python
UTF-8
24,625
3
3
[ "MIT" ]
permissive
from bot_interface import * import math class SeijiBot(BotBase): def __init__(self): self.initialized = False def initialize(self, gamestate): gamestate.log("Initializing...") #Getting UID self.uid = gamestate.bot.uid gamestate.log("This ship has uid " + str(self.uid)) #Getting time step self.step = gamestate.timestep gamestate.log("Initialized with timestep of " + str(self.step) + "s") gamestate.log("Ships have a " + str(gamestate.ships[self.uid].radius) + "m radius") #Setting Global constants self.mass = 1 self.main_thrust = 30 self.side_thrust = 15 self.side_thrust_offset = 2 self.laser_charge_time = .5 self.initialized = True #From here are some useful functions #Side functions def solveQuad(self, a, b, c): if a == 0: return None delta = b**2 - 4*a*c if delta < 0: return None if delta == 0: return (-b)/(2*a), (-b)/(2*a) delta = math.sqrt(delta) return (((-b)-delta)/(2*a), ((-b)+delta)/(2*a)) def dist(self, obj1, obj2): return math.sqrt((obj1.posx - obj2.posx)**2 + (obj1.posy - obj2.posy)**2) def toRad(self, angle): return (float(angle)/180)*math.pi def sign(self, n): if n == 0: return 0 return n/abs(n) def fmod(self, n, k): d = math.floor(n/k) return n - k*d def glob_loc(self, x1, y1, angle, x2, y2): rx, ry = x2 - x1, y2 - y1 tx, ty = math.cos(-angle) * rx - math.sin(-angle) * ry, math.cos(-angle) * ry + math.sin(-angle) * rx return tx, ty def normalize(self, vec): sqrl = 0 for i in vec: sqrl += i**2 l = math.sqrt(sqrl) if l == 0.0: return vec res = [] for i in vec: res.append(i/l) return res def invert(self, vec): return [-i for i in vec] #Movement functions #Change angular speed - It doesn't change linear velocity #Returns -> thruster value def angularSpeed(self, ship, final_speed): k = .1 vel = self.toRad(ship.velang) delta = final_speed - vel ret = delta*k if ret > 1: ret = 1 elif ret < -1: ret = -1 return -ret def angDelta(self, ship, angle): delta = self.fmod(angle + 2*math.pi, 2*math.pi) - self.fmod(self.fmod(self.toRad(ship.ang), 2*math.pi) + 2*math.pi, 2*math.pi) if abs(delta) > math.pi: delta = (2*math.pi - abs(delta))*self.sign(-delta) return delta #Control ship rotation to certain angle - It doesn't change linear velocity #Returns -> thruster value def lookAt(self, ship, final_ang): kP, kD = .6, 3.5 out = -kP*self.angDelta(ship, final_ang) + kD*self.toRad(ship.velang)*self.step if out > 1: out = 1 elif out < -1: out = -1 return out #Accelerate ship towards certain coordinate - It doesn't change velang #Returns -> main thruster value, frontal thruster value, back thruster value def accelerateTo(self, ship, towx, towy, pot = 1): tstep = self.step fmax = self.main_thrust/self.mass angles = self.toRad(ship.ang) x, y = self.glob_loc(ship.posx, ship.posy, angles, towx, towy) res = [0, 0, 0] cx, cy = self.normalize([x, y]) res[0] = -cy*pot res[1] = cx*pot res[2] = cx*pot return res #Estimating objects def estimateObj(self, obj, time = None): if time == None: time = self.step objest = obj objest.posx += objest.velx*time objest.posy += objest.vely*time return objest def estimateRock(self, obj, time = None): if time == None: time = self.step objest = obj objest.posx += objest.velx*time objest.posy += objest.vely*time return objest def estimateShip(self, obj, time = None): if time == None: time = self.step objest = obj objest.posx += objest.velx*time objest.posy += objest.vely*time objest.ang += objest.velang*time return objest def estimateLaser(self, obj, time = None): if time == None: time = self.step objest = obj objest.posx += objest.velx*time objest.posy += objest.vely*time objest.lifetime -= time return objest #Estimating Time of Collision #Returns -> Time(seconds) for collision of obj1 and obj2: MIN, MAX def toC(self, obj1, obj2, error_margin): A = obj1.posx a = obj1.velx B = obj2.posx b = obj2.velx C = obj1.posy c = obj1.vely D = obj2.posy d = obj2.vely R = obj1.radius + error_margin/2 r = obj2.radius + error_margin/2 Asq = A**2 asq = a**2 Bsq = B**2 bsq = b**2 Csq = C**2 csq = c**2 Dsq = D**2 dsq = d**2 Rsq = R**2 rsq = r**2 div = asq - 2*a*b + bsq + csq - 2*c*d + dsq delta = (-Asq*csq + 2*Asq*c*d - Asq*dsq + 2*A*B*csq - 4*A*B*c*d + 2*A*B*dsq + 2*A*C*a*c - 2*A*C*a*d - 2*A*C*b*c + 2*A*C*b*d - 2*A*D*a*c + 2*A*D*a*d + 2*A*D*b*c - 2*A*D*b*d - Bsq*csq + 2*Bsq*c*d - Bsq*dsq - 2*B*C*a*c + 2*B*C*a*d + 2*B*C*b*c - 2*B*C*b*d + 2*B*D*a*c - 2*B*D*a*d - 2*B*D*b*c + 2*B*D*b*d - Csq*asq + 2*Csq*a*b - Csq*bsq + 2*C*D*asq - 4*C*D*a*b + 2*C*D*bsq - Dsq*asq + 2*Dsq*a*b - Dsq*bsq + Rsq*asq - 2*Rsq*a*b + Rsq*bsq + Rsq*csq - 2*Rsq*c*d + Rsq*dsq + 2*R*asq*r - 4*R*a*b*r + 2*R*bsq*r + 2*R*csq*r - 4*R*c*d*r + 2*R*dsq*r + asq*rsq - 2*a*b*rsq + bsq*rsq + csq*rsq - 2*c*d*rsq + dsq*rsq) minusb = (-A*a + A*b + B*a - B*b - C*c + C*d + D*c - D*d) if div == 0 or delta < 0: return None else: res0 = (minusb - math.sqrt(delta))/(div) res1 = (minusb + math.sqrt(delta))/(div) return res0, res1 #Predictive shooting of moving target #Returns -> Time(seconds) for shoot to reach target on line, coordinates x and y for the shoot to be 'centered' def predShoot(self, ship, target, speed, gamestate): tx = target.posx - ship.posx ty = target.posy - ship.posy tvx = target.velx - ship.velx tvy = target.vely - ship.vely a = tvx**2 + tvy**2 - speed**2 b = 2*(tvx*tx + tvy * ty) c = tx**2 + ty**2 r = self.solveQuad(a, b, c) if r == None: return None else: r0, r1 = r if r1 < 0 and r0 < 0: return None elif r0 < 0: coords = (target.posx + tvx*r1, target.posy + tvy*r1) return r1, coords else: coords = (target.posx + tvx*r0, target.posy + tvy*r0) return r0, coords target = None ok = False ltick = 0 def process(self, gamestate): if not self.initialized: self.initialize(gamestate) return Action(0, .1, .1, 0) try: sgargs = gamestate.ships[self.target] except: self.target = None self.ok = False if len(gamestate.ships) > 1 and not self.ok: for i in gamestate.ships: if i is not self.uid: self.ok = True self.target = i gamestate.log("Following ship " + str(i)) break s_ship = gamestate.ships[self.uid] zero = 0 out = [0, 0, 0] avoid = [0, 0, 0] rotation_out = 0 rot_mean = 0 out_s = 0 self.ltick = gamestate.tick #Targeting and shooting for ship_uid in gamestate.ships: if self.uid == ship_uid: continue ship = gamestate.ships[ship_uid] if self.dist(ship, s_ship) < self.dist(gamestate.ships[self.target], s_ship): self.target = ship_uid if(self.target is not None): targetp = self.estimateShip(gamestate.ships[self.target], self.step) shipp = self.estimateShip(s_ship, self.step) prediction0 = None prediction1 = None prediction2 = None shoot_type = 0 min_time = 9999 if shipp.charge >= 3: predictiont = self.predShoot(shipp, targetp, 75, gamestate) if predictiont is not None: time, coords = predictiont time += self.step if time < .8: prediction2 = predictiont if shipp.charge >= 2: predictiont = self.predShoot(shipp, targetp, 50, gamestate) if predictiont is not None: time, coords = predictiont time += self.step if time < .6: prediction1 = predictiont if shipp.charge >= 1: predictiont = self.predShoot(shipp, targetp, 25, gamestate) if predictiont is not None: time, coords = predictiont time += self.step if time < .4: prediction0 = predictiont time, coords = None, None if prediction2 is not None: time, coords = prediction2 time += self.step if abs(self.angDelta(shipp, math.atan2(shipp.posx - coords[0],coords[1] - shipp.posy))) < .1: out_s = 3 if prediction1 is not None: time, coords = prediction1 time += self.step if abs(self.angDelta(shipp, math.atan2(shipp.posx - coords[0],coords[1] - shipp.posy))) < .1: out_s = 2 if prediction0 is not None: time, coords = prediction0 time += self.step if abs(self.angDelta(shipp, math.atan2(shipp.posx - coords[0],coords[1] - shipp.posy))) < .1: out_s = 1 if time is not None: rotation_out += self.lookAt(shipp, math.atan2(shipp.posx - coords[0],coords[1] - shipp.posy )) rot_mean += 1 else: rotation_out += self.lookAt(shipp, math.atan2(shipp.posx - targetp.posx,targetp.posy - shipp.posy )) #Avoidance code #Avoid rocks rock_repel_r = 15 rock_repel_t = 5 rock_less = 9999 rock_less_uid = None for rock_uid in gamestate.rocks: rock = gamestate.rocks[rock_uid] dist = self.dist(s_ship, rock) final = [0, 0, 0] if dist <= rock_repel_r: tmp = self.accelerateTo(s_ship, 2*s_ship.posx - rock.posx, 2*s_ship.posy - rock.posy, math.sqrt((rock_repel_r-dist)/rock_repel_r)) avoid[0] += tmp[0] avoid[1] += tmp[1] avoid[2] += tmp[2] toc = self.toC(rock, s_ship, .1) if not toc == None: if toc[0] > 0: gamestate.log("Rock of uid " + str(rock_uid) + ": Will collide in " + ('%.2f' % toc[0]) + " seconds") shp = self.estimateShip(s_ship, toc[0]) rck = self.estimateRock(rock, toc[0]) if toc[0] <= rock_repel_t: tmp = self.accelerateTo(shp, 2*shp.posx - rck.posx, 2*shp.posy - rck.posy, math.sqrt((rock_repel_t-toc[0])/rock_repel_t)) final[0] += tmp[0] final[1] += tmp[1] final[2] += tmp[2] if rock_less > toc[0]: rock_less = toc[0] rock_less_uid = rock_uid out[0] += final[0] out[1] += final[1] out[2] += final[2] #Avoid lasers laser_repel_r = 15 laser_repel_t = 3 laser_less = 9999 laser_less_uid = None for laser_uid in gamestate.lasers: laser = gamestate.lasers[laser_uid] dist = self.dist(s_ship, laser) final = [0, 0, 0] if dist <= laser_repel_r: tmp = self.accelerateTo(s_ship, 2*s_ship.posx - laser.posx, 2*s_ship.posy - laser.posy, math.sqrt((laser_repel_r-dist)/laser_repel_r)) avoid[0] += tmp[0] avoid[1] += tmp[1] avoid[2] += tmp[2] toc = self.toC(laser, s_ship, .1) if not toc == None: if toc[0] > 0: if toc[0] <= laser.lifetime: gamestate.log("Shot of uid " + str(laser_uid) + " from " + str(laser.owner) + ": Will hit in " + ('%.2f' % toc[0]) + " seconds") shp = self.estimateShip(s_ship, toc[0]) lsr = self.estimateLaser(laser, toc[0]) shipp = self.estimateShip(s_ship, self.step) las = self.estimateLaser(laser, self.step) prediction = self.predShoot(shipp, las, 75, gamestate) if prediction is not None: time, coords = prediction time += self.step gamestate.log(str()) if abs(self.angDelta(shipp, math.atan2(shipp.posx - coords[0],coords[1] - shipp.posy))) < .1: out_s = 3 prediction = self.predShoot(shipp, las, 50, gamestate) if prediction is not None: time, coords = prediction time += self.step if abs(self.angDelta(shipp, math.atan2(shipp.posx - coords[0],coords[1] - shipp.posy))) < .1: out_s = 2 prediction = self.predShoot(shipp, las, 25, gamestate) if prediction is not None: time, coords = prediction time += self.step if abs(self.angDelta(shipp, math.atan2(shipp.posx - coords[0],coords[1] - shipp.posy))) < .1: out_s = 1 if toc[0] <= laser_repel_t: tmp = self.accelerateTo(s_ship, 2*shp.posx - lsr.posx, 2*shp.posy - lsr.posy, math.sqrt((laser_repel_t-toc[0])/laser_repel_t)) final[0] += tmp[0] final[1] += tmp[1] final[2] += tmp[2] if laser_less > toc[0]: laser_less = toc[0] laser_less_uid = laser_uid else: gamestate.log("Shot of uid " + str(laser_uid) + " from " + str(laser.owner) + ": Will not hit. Just " + ('%.2f' % laser.lifetime) + " seconds remaining.") out[0] += final[0] out[1] += final[1] out[2] += final[2] #Try not to collide with the arena arenac = 1 if math.sqrt(s_ship.posx**2 + s_ship.posy**2) > gamestate.arenaRadius - 5: tmp = self.accelerateTo(s_ship, 0, 0, (math.sqrt(s_ship.posx**2 + s_ship.posy**2) - (gamestate.arenaRadius - 5))/5) out[0] += tmp[0]*arenac out[1] += tmp[1]*arenac out[2] += tmp[2]*arenac #Stay at a distance from target attrcnt = .3 if self.target is not None: target_r = 30 dist = self.dist(s_ship, gamestate.ships[self.target]) linpot = 0 if target_r-dist is not zero: linpot = target_r/(dist - target_r) tmp = self.accelerateTo(s_ship, gamestate.ships[self.target].posx, gamestate.ships[self.target].posy, (linpot**8)*self.sign(linpot)) tmp = self.normalize(tmp) mx = max(abs(tmp[0]), abs(tmp[1]), abs(tmp[2])) if mx != 0: mx = 1/mx avoid[0] += tmp[0]*mx*attrcnt avoid[1] += tmp[1]*mx*attrcnt avoid[2] += tmp[2]*mx*attrcnt #Keep track of ship headings/ships targeting self predeyesight = .5 for ship_uid in gamestate.ships: if ship_uid is self.uid: continue ship = gamestate.ships[ship_uid] targetp = self.estimateShip(s_ship, self.step) shipp = self.estimateShip(ship, self.step) prediction = None shoot_type = 0 if shipp.charge < 2 and shipp.charge >= 1: prediction0 = self.predShoot(shipp, targetp, 25, gamestate) prediction1 = None prediction2 = None elif shipp.charge < 3: prediction0 = self.predShoot(shipp, targetp, 25, gamestate) prediction1 = self.predShoot(shipp, targetp, 50, gamestate) prediction2 = None else: prediction0 = self.predShoot(shipp, targetp, 25, gamestate) prediction1 = self.predShoot(shipp, targetp, 50, gamestate) prediction2 = self.predShoot(shipp, targetp, 75, gamestate) if prediction2 is not None: time, coords = prediction2 time += self.step laser = Laser(0) laser.lifetime = 3 laser.owner = ship_uid laser.posx = shipp.posx laser.posy = shipp.posy laser.velx = shipp.velx + 75*math.sin(self.toRad(shipp.ang)) laser.vely = shipp.posy + 75*math.cos(self.toRad(shipp.ang)) if abs(self.angDelta(shipp, math.atan2(shipp.posx - coords[0],coords[1] - shipp.posy))) < 2: if time < 1: shp = self.estimateShip(s_ship, time) lsr = self.estimateLaser(laser, time) tmp = self.accelerateTo(s_ship, 2*shp.posx - lsr.posx, 2*shp.posy - lsr.posy, math.sqrt((laser_repel_t-time)/laser_repel_t)) avoid[0] += tmp[0]*predeyesight avoid[1] += tmp[1]*predeyesight avoid[2] += tmp[2]*predeyesight gamestate.log("Ship " + str(ship_uid) + " is targeting at 75m/s...") elif prediction1 is not None: time, coords = prediction1 time += self.step laser = Laser(0) laser.lifetime = 3 laser.owner = ship_uid laser.posx = shipp.posx laser.posy = shipp.posy laser.velx = shipp.velx + 50*math.sin(self.toRad(shipp.ang)) laser.vely = shipp.posy + 50*math.cos(self.toRad(shipp.ang)) if abs(self.angDelta(shipp, math.atan2(shipp.posx - coords[0],coords[1] - shipp.posy))) < 2: if time < 1: shp = self.estimateShip(s_ship, time) lsr = self.estimateLaser(laser, time) tmp = self.accelerateTo(s_ship, 2*shp.posx - lsr.posx, 2*shp.posy - lsr.posy, math.sqrt((laser_repel_t-time)/laser_repel_t)) avoid[0] += tmp[0]*predeyesight avoid[1] += tmp[1]*predeyesight avoid[2] += tmp[2]*predeyesight gamestate.log("Ship " + str(ship_uid) + " is targeting at 50m/s...") if prediction0 is not None: time, coords = prediction0 time += self.step laser = Laser(0) laser.lifetime = 3 laser.owner = ship_uid laser.posx = shipp.posx laser.posy = shipp.posy laser.velx = shipp.velx + 25*math.sin(self.toRad(shipp.ang)) laser.vely = shipp.posy + 25*math.cos(self.toRad(shipp.ang)) if abs(self.angDelta(shipp, math.atan2(shipp.posx - coords[0],coords[1] - shipp.posy))) < 2: if time < 1: shp = self.estimateShip(s_ship, time) lsr = self.estimateLaser(laser, time) tmp = self.accelerateTo(s_ship, 2*shp.posx - lsr.posx, 2*shp.posy - lsr.posy, math.sqrt((laser_repel_t-time)/laser_repel_t)) avoid[0] += tmp[0]*predeyesight avoid[1] += tmp[1]*predeyesight avoid[2] += tmp[2]*predeyesight gamestate.log("Ship " + str(ship_uid) + " is targeting at 25m/s...") #apply rotations and final weight calculation peravd = 2 out[0] += avoid[0]*peravd out[1] += avoid[1]*peravd out[2] += avoid[2]*peravd mx = 1 #out = self.normalize(out) #mx = max(abs(out[0]), abs(out[1]), abs(out[2])) #if mx != 0: # mx = 1/mx #mx = 1 rotmulti = 1 #out[0] = 0 out[1] += rotation_out*rotmulti out[2] += -rotation_out*rotmulti #out_s = 0 #out = [0, 0, 0] #virtual 'friction' '''kF = .5 vel = [s_ship.posx-s_ship.velx, s_ship.posy-s_ship.vely] mvel = math.sqrt(s_ship.velx**2 + s_ship.vely**2) vel = self.normalize(vel) tmp = self.accelerateTo(s_ship, vel[0], vel[1], kF) out[0] += tmp[0]*(mvel/30) out[1] += tmp[1]*(mvel/30) out[2] += tmp[2]*(mvel/30)''' #Emergency overwrite - in case of iminent danger rotation_out = 0 if rock_less <= 1: out_s = 1 gamestate.log("Overwriting controls: rock 1s of ID " + str(laser_less_uid)) shipp = self.estimateShip(s_ship, self.step) targetp = self.estimateRock(gamestate.rocks[rock_less_uid], self.step) prediction = self.predShoot(shipp, targetp, 25, gamestate) if prediction is not None: time, coords = prediction rotation_out = self.lookAt(shipp, math.atan2(shipp.posx - coords[0],coords[1] - shipp.posy )) if rock_less <= .5: gamestate.log("Overwriting controls: rock .5 of ID " + str(rock_less_uid)) shp = self.estimateShip(s_ship, rock_less) rck = self.estimateRock(gamestate.rocks[rock_less_uid], rock_less) out = self.accelerateTo(shp, 2*shp.posx - rck.posx, 2*shp.posy - rck.posy) out = self.normalize(out) out = self.invert(out) out[1] += rotation_out*rotmulti out[2] += -rotation_out*rotmulti mx = max(abs(out[0]), abs(out[1]), abs(out[2])) if mx != 0: mx = 1/mx if laser_less <= 1.5: out_s = 1 gamestate.log("Overwriting controls: laser 1s of ID " + str(laser_less_uid)) shipp = self.estimateShip(s_ship, self.step) targetp = self.estimateLaser(gamestate.lasers[laser_less_uid], self.step) prediction = self.predShoot(shipp, targetp, 25, gamestate) if prediction is not None: time, coords = prediction rotation_out = self.lookAt(shipp, math.atan2(shipp.posx - coords[0],coords[1] - shipp.posy )) if laser_less <= .5: gamestate.log("Overwriting controls: laser .5 of ID " + str(laser_less_uid)) shp = self.estimateShip(s_ship, laser_less) lsr = self.estimateLaser(gamestate.lasers[laser_less_uid], laser_less) out = self.accelerateTo(s_ship, 2*shp.posx - lsr.posx, 2*shp.posy - lsr.posy) out = self.normalize(out) out = self.invert(out) #@out[0] = -out[0] out[1] += rotation_out*rotmulti out[2] += -rotation_out*rotmulti mx = max(abs(out[0]), abs(out[1]), abs(out[2])) if mx != 0: mx = 1/mx return Action(-out[0]*mx, out[1]*mx, out[2]*mx, out_s) gamestate.log(str(s_ship.vely)) return Action(1, 0, 0, 0) GameState(SeijiBot()).connect()
Java
UTF-8
546
3.40625
3
[]
no_license
import java.util.Scanner; class Min3 { static int min3(int a, int b, int c) { int min = a; if (b < min) min = b; if (c < min) min = c; return min; } public static void main(String[] args) { System.out.println("min3(1,2,3) = " + min3(1,2,3)); System.out.println("min3(1,3,2) = " + min3(1,3,2)); System.out.println("min3(3,1,2) = " + min3(3,1,2)); System.out.println("min3(3,3,0) = " + min3(3,3,0)); System.out.println("min3(0,0,0) = " + min3(0,0,0)); } }
Python
UTF-8
76
3.3125
3
[]
no_license
n = 0 while n < 5: print('Multiplos de 3 = ', n * 3) n = n + 1
Java
UTF-8
1,416
2.328125
2
[]
no_license
package com.umeng.message.entity; import org.json.JSONObject; public class ULocation { private String a; private String b; private String c; private String d; private String e; private String f; private String g; private String h; public ULocation(JSONObject jSONObject) { try { this.a = jSONObject.getString("cenx"); this.b = jSONObject.getString("ceny"); jSONObject = jSONObject.getJSONObject("revergeo"); this.c = jSONObject.getString("country"); this.d = jSONObject.getString("province"); this.e = jSONObject.getString("city"); this.f = jSONObject.getString("district"); this.g = jSONObject.getString("road"); this.h = jSONObject.getString("street"); } catch (JSONObject jSONObject2) { jSONObject2.printStackTrace(); } } public String getLongitude() { return this.a; } public String getLatitude() { return this.b; } public String getCountry() { return this.c; } public String getProvince() { return this.d; } public String getCity() { return this.e; } public String getDistrict() { return this.f; } public String getRoad() { return this.g; } public String getStreet() { return this.h; } }
Markdown
UTF-8
841
2.578125
3
[ "MIT" ]
permissive
## Salt基本使用 ### 常用命令 - `salt "*" test.ping`: 测试节点是否能通 - `salt "192.168.1.123" cmd.run "uname -a"`: 远程执行`uname -a`命令 ### 通过salt操作windows dnscmd #### 删除域名解析: ``` salt "192.168.1.1" cmd.run "dnscmd /Recorddelete codelieche.com hello A /f" ``` 返回结果: > Deleted A record(s) at codelieche.com Command completed successfully. #### 添加域名解析: ``` salt "192.168.5.116" cmd.run "dnscmd /RecordAdd codelieche.com hello A 192.168.1.123 ``` 返回结果: > Add A Record for hello.codelieche.com at codelieche.com Command completed successfully. **注意:** - 传参的时候,开始是顶级域名,比如:`codelieche.com` - 然后传的`hello`是二级域名 - 二级域名 + `.` + 顶级域名就是要解析的域名: `hello.codelieche.com`
Java
UTF-8
777
1.867188
2
[]
no_license
package org.hj.timefilter.controller; import org.hj.timefilter.anno.RequestLimit; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; @Controller public class TestController { @RequestMapping(value = "/testip/{id}",method = RequestMethod.GET) @RequestLimit(count = 1) @ResponseBody public String test(HttpServletRequest request, @PathVariable Integer id){ int i = 10/id; //System.out.println("--------------------"); return "hello"; } }
PHP
UTF-8
2,180
3.390625
3
[]
no_license
<?php /** * Uma classe abstrata é uma classe que nunca serão usadas de fato. Ou seja, * apenas as classes que herdam uma classe abstrata que dará origem a algum objeto. */ /** * A classe foguete será uma classe abstrata. Ela definirá algumas características * de um foguete e apenas as classes que vão herdar ela, que serão mais específicas, * que serão usadas como objetos. */ abstract class Foguete{ var $empuxo; var $cargaMaxima; function __construct($empuxo, $cargaMaxima){ $this->empuxo = $empuxo; $this->cargaMaxima = $cargaMaxima; } } /** * Classes que herda a classe foguete e que será instanciada como objeto */ class falcon9 extends Foguete{ var $nome; var $empresa; var $lancamentos; var $pousos; function __construct($lancamentos, $pousos, $empuxo, $cargaMaxima){ $this->nome = "falcon 9"; $this->empresa = "SpaceX"; $this->lancamentos = $lancamentos; $this->pousos = $pousos; parent::__construct($empuxo, $cargaMaxima); } function imprime(){ echo "Nome: $this->nome\n"; echo "Empresa: $this->empresa\n"; echo "Lancamentos: $this->lancamentos\n"; echo "Pousos: $this->pousos\n"; echo "Empuxo: $this->empuxo kN\n"; echo "cargaMaxima: $this->cargaMaxima kg\n"; } } class saturnV extends Foguete{ var $nome; var $altura; var $lancamentos; var $missoes; function __construct($empuxo, $cargaMaxima){ $this->nome = "Saturn V"; $this->altura = 110.6; $this->lancamentos = 13; $this->missoes = "Apollo e Skylab"; parent::__construct($empuxo, $cargaMaxima); } function imprime(){ echo "Nome: $this->nome\n"; echo "Altura: $this->altura\n"; echo "Quantidade de lançamentos: $this->lancamentos\n"; echo "Usado nas missões: $this->missoes\n"; echo "Empuxo: $this->empuxo kN\n"; echo "cargaMaxima: $this->cargaMaxima kg\n"; } } // Objetos $obj1 = new falcon9(119, 79, 845, 22800); $obj2 = new saturnV(33375006.66, 118000); $obj1->imprime(); echo "\n"; $obj2->imprime();
Java
UTF-8
1,503
3.03125
3
[]
no_license
package hr.fer.zemris.fuzzy.domain; import org.apache.commons.lang3.ArrayUtils; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.StringJoiner; public class DomainElement { private int[] values; public DomainElement(int[] values) { this.values = values; } public static DomainElement of(int... values) { return new DomainElement(values); } public int getNumberOfComponents() { return values.length; } public int getComponentValue(int i) { return values[i]; } public DomainElement reversed() { int[] copy = values.clone(); ArrayUtils.reverse(copy); return DomainElement.of(copy); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DomainElement that = (DomainElement) o; return Arrays.equals(values, that.values); } @Override public int hashCode() { return Arrays.hashCode(values); } @Override public String toString() { if (values.length == 1) { return "Element domene: " + values[0]; } else { StringJoiner sj = new StringJoiner(", "); for (int i = 0, n = values.length; i < n; ++i) { sj.add(String.valueOf(values[i])); } return "Element domene: (" + sj.toString() + ")"; } } }
Markdown
UTF-8
1,058
2.875
3
[]
no_license
# Ruby on Rails Tutorial # ### Learn Web Development with Rails ### ### Michael Hartl ### ###### 目录 ###### 第一章节 从零到部署 * 1.1 [简介]() * 1.1.1 [各种读者的评论]() * 1.1.2 [纵观Rails]() * 1.1.3 [本书的约定]() * 1.2 [建立和运行]() * 1.2.1 [开发环境]() * [IDEs(集成开发环境)]() * Text editors and command lines * Browsers * A note about tools * 1.2.2 Ruby, RubyGems, Rails, and Git * Rails Installer (Windows) * Install Git * Install Ruby * Install RubyGems * Install Rails * 1.2.3 The first application * 1.2.4 Bundler * 1.2.5 rails server * 1.2.6 Model-view-controller (MVC) * 1.3 Version control with Git * 1.3.1 Installation and setup * First-time system setup * First-time repository setup * 1.3.2 Adding and committing * 1.3.3 What good does Git do you? * 1.3.4 GitHub * 1.3.5 Branch, edit, commit, merge * Branch * Edit * Commit * Merge * Push * 1.4 Deploying * 1.4.1 Heroku setup * 1.4.2 Heroku deployment, step one * 1.4.3 Heroku deployment, step two * 1.4.4 Heroku commands * 1.5 Conclusion
JavaScript
UTF-8
2,172
3.328125
3
[]
no_license
// const Ship = require('./ship'); // const Bullet = require('./bullet'); const Util = require('./util'); class MovingObject { constructor(options){ this.pos = options.pos; this.vel = options.vel; this.radius = options.radius; this.color = options.color; this.game = options.game; // this.isWrappable = true; this.isBoundable = true; this.isBouncy = true; } // Write a MovingObect.prototype.draw(ctx) method. Draw a circle of the appropriate radius centered at pos. Fill it with the appropriate color. Refer to the Drunken Circles demo if you need a refresher on Canvas. draw(ctx) { ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc( this.pos[0], this.pos[1], this.radius, 0, 2 * Math.PI ); ctx.fill(); } move() { this.pos = [this.pos[0] + this.vel[0], this.pos[1] + this.vel[1]]; let shift = [1,1]; if (this.game.xBounded(this.pos, this.radius)) {shift[0] = -1;} if (this.game.yBounded(this.pos, this.radius)) {shift[1] = -1;} const outOfBounds = shift[0] === -1 || shift[1] === -1; if (outOfBounds && this.isBoundable) { this.pos = [this.pos[0] - this.vel[0], this.pos[1] - this.vel[1]]; if (this.isBouncy) { this.vel = [this.vel[0] * shift[0], this.vel[1] * shift[1]]; // this.move(); } else { this.vel = [0,0]; } } else if (outOfBounds) { this.game.remove(this); } // const shift = this.game.changeDirection(this.pos); // this.pos = [this.pos[0] + this.vel[0], this.pos[1] + this.vel[1]]; // if (this.isWrappable) { // this.pos = this.game.wrap(this.pos); // } else if (this.game.isOutOfBounds(this.pos)) { // this.game.remove(this); // } } isCollideWith(otherObject) { const minDistance = this.radius + otherObject.radius; const currentDistance = Math.sqrt(Math.pow((this.pos[0] - otherObject.pos[0]), 2) + Math.pow((this.pos[1] - otherObject.pos[1]), 2)); // console.log(minDistance, currentDistance); return (minDistance >= currentDistance); } collideWith(otherObject) { } } module.exports = MovingObject;
Java
UTF-8
1,277
2.40625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package EJB; import java.util.ArrayList; import javax.ejb.EJB; import javax.ejb.Singleton; import utilities.LogEntry; /** * * @author ilario */ @Singleton public class DataManagerBean implements DataManagerBeanLocal{ @EJB ( beanName = "replica1") private ReplicaManagerBeanLocal replicaManagerBean1; @EJB ( beanName = "replica2") private ReplicaManagerBeanLocal replicaManagerBean2; @EJB ( beanName = "replica3") private ReplicaManagerBeanLocal replicaManagerBean3; @EJB ( beanName = "replica4") private ReplicaManagerBeanLocal replicaManagerBean4; @EJB ( beanName = "replica5") private ReplicaManagerBeanLocal replicaManagerBean5; @Override public void add(LogEntry le) { replicaManagerBean1.writeOnDB(le); replicaManagerBean2.writeOnDB(le); replicaManagerBean3.writeOnDB(le); replicaManagerBean4.writeOnDB(le); replicaManagerBean5.writeOnDB(le); } @Override public ArrayList<LogEntry> retrieve (String query){ return replicaManagerBean1.readFromDB(query); } }
Python
UTF-8
425
3.8125
4
[]
no_license
#!/usr/bin/env python3.6 """ Website url http://www.pythonchallenge.com/ Puzzle 00 url: http://www.pythonchallenge.com/pc/def/0.html Calulate 2 to the power of 38 """ def calc_2pow38(): return pow(2, 38) if __name__ == "__main__": num = calc_2pow38() print("Challenge: evaluate 2 to the power of 38.\nAnswer: {}".format(num)) print("Next challenge url: http://www.pythonchallenge.com/pc/def/{}.html".format(num))
Ruby
UTF-8
177
3.03125
3
[ "MIT" ]
permissive
# Cycle through all 24-bit colors and print their values. require 'redgreenblue' RGB.style = 'default' RGB.each_24bit_color do |color| print "\r" + color.inspect end puts
C#
UTF-8
800
3.390625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _12.Fibbonacci { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int firstNumber = 1; int secondNumber = 1; int newNumber = 0; if (n < 2) { Console.WriteLine(1); } else { for (int i = 1; i < n; i++) { newNumber = firstNumber + secondNumber; firstNumber = secondNumber; secondNumber = newNumber; } Console.WriteLine(newNumber); } } } }
Markdown
UTF-8
1,634
3.484375
3
[]
no_license
# 帮助命令 ## 帮助命令:man 命令 manual 在显示的文档中,使用上下键来上翻和下翻,使用空格进行翻页。 建议运行一下 man man 来具体看一下。这样是为了你能理解man有多个帮助级别,从1到9,如果单纯运行 man 命令 的话,默认显示最小的帮助等级,所以应该提前运行一下 man -f 命令 #上面的命令就等于运行 whatis 命令 来查看这个命令到底有多少个帮助等级。 如果忘记了要查找的命令的全称的话,有两种方式,第一种是使用<font color="red">Tab键,在输入命令的开头后,可以双击Tab键来使用提醒,下面就会显示全部以该部分开头的命令。</font> 第二种方式就是使用<font color="blue">man -k 部分命令</font>,来进行查询,会显示全部包含该部分命令的命令。 ## 命令简单查询:命令 --help 内容部分已经翻译成中文了。 ## shell内部命令帮助:help shell内部命令 上面的帮助命令都不能查看shell的内部命令,如cd,所以当部分命令使用上面的方法查询不到时,可以使用help命令来查看。 ## 查看详细帮助命令:info 命令 在进入info的显示页面后,可以使用下面的按键来切换页面: - 回车:进入子帮助页面,有子帮助页面的内容就是像网页中的超链接,一般情况下有*来标志 ,在光标停留在该部分时,会有超链接的下划线 - u:up,进入上一层 - n:next,进入下一个帮助小节 - p:previous,进入上一个帮助小节 - q:quite,推出
JavaScript
UTF-8
4,544
2.71875
3
[]
no_license
function init_color_blocks() { var list=document.querySelectorAll(".colors"); for(var i=0; i<list.length; i++) { list[i].addEventListener("click", color_click); } } function change_on_hover() { this.classList.add("cc"); } function restore_back_after_hover() { this.classList.remove("cc"); } function init_easy() { if(conclusion==true) { conclusion=false; new_col_button.textContent="New Colors"; init_color_blocks(); } outerdiv_elem.style.backgroundColor=orig_state; center_message.textContent="Welcome!"; if(level) { var row=document.querySelector("#row2"); var list=document.querySelectorAll("#row2 .colors"); for(var i=0; i<list.length; i++) { list[i].classList.remove("colors"); list[i].removeEventListener("click", color_click); list[i].style.backgroundColor=orig_back; } } level=false; var list=document.querySelectorAll(".colors"); var random_srno=Math.floor((Math.random()*3)); for(var i=0; i<3; i++) { var r=Math.floor((Math.random()*256)); var g=Math.floor((Math.random()*256)); var b=Math.floor((Math.random()*256)); if(i==random_srno) { targetCID=list[i].id; data.textContent="RGB("+r+", "+g+", "+b+")"; } list[i].style.backgroundColor="rgb("+r+", "+g+", "+b+")"; } } function init_hard() { if(conclusion==true) { conclusion=false; new_col_button.textContent="New Colors"; init_color_blocks(); } center_message.textContent="Welcome!"; outerdiv_elem.style.backgroundColor=orig_state; if(!level) { var row=document.querySelector("#row2"); var list=document.querySelectorAll("#row2 td"); for(var i=0; i<list.length; i++) { list[i].classList.add("colors"); list[i].addEventListener("click", color_click); //list[i].style.visibility="visible"; } } level=true; var list=document.querySelectorAll(".colors"); var random_srno=Math.floor((Math.random()*6)); for(var i=0; i<6; i++) { var r=Math.floor((Math.random()*256)); var g=Math.floor((Math.random()*256)); var b=Math.floor((Math.random()*256)); if(i==random_srno) { targetCID=list[i].id; data.textContent="RGB("+r+", "+g+", "+b+")"; } list[i].style.backgroundColor="rgb("+r+", "+g+", "+b+")"; } } function color_click() { var this_id=this.id; if(this_id==targetCID) { center_message.textContent="Correct!"; new_col_button.textContent="Play Again?"; outerdiv_elem.style.backgroundColor=this.style.backgroundColor; var list=document.querySelectorAll(".colors"); for(var i=0; i<list.length; i++) { list[i].style.backgroundColor=this.style.backgroundColor; //list[i].style.visibility="visible"; list[i].removeEventListener("click", color_click); } conclusion=true; } else { this.style.backgroundColor=orig_back; center_message.textContent="Incorrect!"; } } var data_elem=document.getElementById("data"); var outerdiv_elem=document.getElementById("outerdiv"); var orig_state=getComputedStyle(outerdiv_elem).backgroundColor; var orig_back=getComputedStyle(document.querySelector("body")).backgroundColor; var center_message=document.getElementById("center"); var targetCID=undefined; var new_col_button=document.querySelector("#left span"); var easy_button=document.querySelector("#easy"); var hard_button=document.querySelector("#hard"); var level=true; var conclusion=true; init_hard(); new_col_button.addEventListener("mouseover", change_on_hover); new_col_button.addEventListener("mouseout", restore_back_after_hover); easy_button.addEventListener("mouseover", change_on_hover); easy_button.addEventListener("mouseout", restore_back_after_hover); hard_button.addEventListener("mouseover", change_on_hover); init_color_blocks(); easy_button.addEventListener("click", function() { this.removeEventListener("mouseout", restore_back_after_hover); hard_button.addEventListener("mouseout", restore_back_after_hover); hard_button.classList.remove("cc"); init_easy(); } ); hard_button.addEventListener("click", function() { this.removeEventListener("mouseout", restore_back_after_hover); easy_button.addEventListener("mouseout", restore_back_after_hover); easy_button.classList.remove("cc"); init_hard(); } ); new_col_button.addEventListener("click", function() { if(level) { init_hard(); } else { init_easy(); } });
Java
UTF-8
503
2.109375
2
[ "Apache-2.0" ]
permissive
package id.ac.tazkia.smilemahasiswa.entity; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; @Entity @Data public class MahasiswaCicilan { @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") private String id; @ManyToOne @JoinColumn(name = "id_mahasiswa") private Mahasiswa mahasiswa; @Enumerated(EnumType.STRING) private StatusRecord status = StatusRecord.NONAKTIF; }
C++
UTF-8
1,729
2.625
3
[]
no_license
#pragma once #include "VulkanAPI/Common.h" #include "VulkanAPI/Image.h" #include "VulkanAPI/Queue.h" namespace OmegaEngine { enum class TextureFormat; class MappedTexture; } // namespace OmegaEngine namespace VulkanAPI { // forward declerations class MemoryAllocator; class Image; class ImageView; class Texture { public: Texture(); Texture(vk::Device dev, vk::PhysicalDevice phys, Queue& queue); Texture(vk::Device dev, vk::PhysicalDevice phys); ~Texture(); void init(vk::Device dev, vk::PhysicalDevice phys, Queue& queue); void init(vk::Device dev, vk::PhysicalDevice phys); static vk::Format convertTextureFormatToVulkan(OmegaEngine::TextureFormat format); void createEmptyImage(vk::Format, uint32_t width, uint32_t height, uint8_t mipLevels, vk::ImageUsageFlags usageFlags, uint32_t faces = 1); void map(OmegaEngine::MappedTexture& tex); void createCopyBuffer(std::vector<vk::BufferImageCopy>& copyBuffers); void createArrayCopyBuffer(std::vector<vk::BufferImageCopy>& copyBuffers); vk::ImageView& getImageView(); vk::Format& getFormat() { return format; } Image& getImage() { return image; } uint32_t getWidth() const { return width; } uint32_t getHeight() const { return height; } uint32_t getFaceCount() const { return faceCount; } uint32_t getArrayCount() const { return arrays; } uint32_t getMipLevels() const { return mipLevels; } private: vk::Device device; vk::PhysicalDevice gpu; Queue graphicsQueue; // texture info vk::Format format; uint32_t width = 0; uint32_t height = 0; uint32_t faceCount = 1; uint32_t arrays = 1; uint32_t mipLevels = 1; Image image; ImageView imageView; }; } // namespace VulkanAPI
Markdown
UTF-8
927
3.671875
4
[]
no_license
# Comandos de repetição: continue e break Com as palavras-chave `continue` e `break` podemos pular ou parar a execução de qualquer um dos comandos de repetição mencionados anteriormente, veja o exemplo a seguir: ```php for ($i = 0; $i < 10; $i++) { if ($i == 4 || $i == 6) { continue; } if ($i == 8) { break; } echo $i . ' '; } echo 'Final'; // No final será exibido: // 0 1 2 3 5 7 Final ``` O que aconteceu no exemplo acima é que quando o valor de `$i` for igual a **4** ou **6**, o `for` irá para a próxima execução ignorando tudo depois do `continue`, como o `echo` o final do mesmo, já quando o valor de `$i` for igual a **8** a repetição irá parar e continuar o código fora dela, assim ignorando a repetição cujo valor de `$i` seria **9** e o restante do código. Você também pode usar essas palavras-chaves nos comandos `while`, `do...while` e `foreach`.
C++
UTF-8
1,827
3.171875
3
[]
no_license
// ex.1.23 // en: Modify your program from Exercise 1.22 to plot the number of // edges needed to connect N items, for 100 <= N <= 1000. // ru: Измените программу из упражнения 1.22, чтобы она выводила в // виде графика количество ребер, требующихся для соединения N // элементов, 100 <= N <= 1000. #include <algorithm> #include <iomanip> #include <iostream> #include <random> #include <vector> #include <psv/cli_graph.h> int usage(const char* bin) { std::cout << "Usage: " << bin << " <positive int X> <positive int Y>\n"; return 1; } int CalcEdges(int N) { std::vector<int> id(N); std::vector<int> sz(N, 1); std::iota(id.begin(), id.end(), 0); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> dist(0, N - 1); int unions = 0; int edges = 0; do { ++edges; // find int i; int j; for (i = dist(gen); i != id[i]; i = id[i]) id[i] = id[id[i]]; for (j = dist(gen); j != id[j]; j = id[j]) id[j] = id[id[j]]; if (i != j) { // check size of tree & join with smallest if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; } else { id[j] = i; sz[i] += sz[j]; } ++unions; } } while (unions < N - 1); return edges; } int main(int argc, char* argv[]) { if (argc < 3) { return usage(argv[0]); } int X = std::atoi(argv[1]); int Y = std::atoi(argv[2]); if (X <= 0 || Y <= 0) { return usage(argv[0]); } // magic upper bound psv::DrawCLIGraph(100, 1000, CalcEdges, 0, 7000, X, Y, "N", "edges"); return 0; }
C++
UTF-8
1,089
3.125
3
[]
no_license
// template<class _Ty> inline // _Ty _Pow_int(_Ty _X, int _Y) // {unsigned int _N; // if (_Y >= 0) // _N = (unsigned int)_Y; // else // _N = (unsigned int)(-_Y); // for (_Ty _Z = _Ty(1); ; _X *= _X) // {if ((_N & 1) != 0) // _Z *= _X; // if ((_N >>= 1) == 0) // return (_Y < 0 ? _Ty(1) / _Z : _Z); }} #include <iostream> #include <cmath> #define SPEC_CHAR_ARRY {0, 1, 2, 3, 4, 5, 6, 255} void init_f (void) { char c[] = SPEC_CHAR_ARRY; // do sth ... } // Special version for performance double PowDoubleInt(double x, int n) { if(n<0) return 1.0/(x*PowDoubleInt(x, -(n+1))); double y = 1.0; while(n > 0) { if((n&1) > 0) { y *= x; } n >>= 1; if(!n) return y; x *= x; } return y; } int main(int argc, char** argv) { using namespace std; double x = -2.0; int n = -2147483648; double y = pow(x, n); double ytest = PowDoubleInt(x, n); if (y != ytest) { cout << y - ytest << endl; } double t = 2.3; double result = pow(x, t); return 0; }
JavaScript
UTF-8
8,870
2.796875
3
[]
no_license
(function (window) { 'use strict'; var Modulator = function(params) { if (!params) params = new Object(); // this odd construct is for safari compatibility if (!("audioContext" in window)) window.audioContext = new (window.AudioContext || window.webkitAudioContext)(); this.encoder = new FskEncoder(window.audioContext.sampleRate); // Create a "script node" that will actually generate audio samples. this.script_node = Modulator.prototype.script_node; if (!this.script_node) { Modulator.prototype.script_node = window.audioContext.createScriptProcessor(4096, 2, 2); // If the script node has an invalid buffer size, force one with a nonzero buffer. if (!Modulator.prototype.script_node.bufferSize) { // IE with a polyfill exhibits this problem, and crashes when you try to stop. Modulator.prototype.script_node = window.audioContext.createScriptProcessor(4096, 2, 2); this.prototype.can_stop = false; } this.script_node = Modulator.prototype.script_node; } // Start out in a not-playing state this.playing = false; } Modulator.prototype = { audioCtx: null, // AudioContext object encoder: null, // FskEncoder object outputAudioBuffer: null, // AudioBuffer object uiCallback: null, // UI object for callback scriptNode: null, // Re-used script node object for audio generation can_stop: true, // Whether we can stop (usually we can) // modulate a single packet. The data to modulate should be Uint8 format // This function allocates an audio buffer based on the length of the data and the sample rate // It then calls the fsk modulator, and shoves the returned floating point array // into the audio context for later playback modulate: function(data) { var bufLen = Math.ceil(data.length * 8 * this.encoder.samplesPerBit()); this.outputAudioBuffer = window.audioContext.createBuffer(1, bufLen, window.audioContext.sampleRate); var timeStart = performance.now(); var outputFloatArray = this.outputAudioBuffer.getChannelData(0); this.encoder.modulate(data, outputFloatArray); // writes outputFloatArray in-place // How far into the outputAudioBuffer we are. this.script_node_offset = 0; var timeEnd = performance.now(); var timeElapsed = timeEnd - timeStart; console.log("Rendered " + data.length + " data bytes in " + timeElapsed.toFixed(2) + "ms"); }, silence: function(msecs) { var bufLen = Math.ceil(window.audioContext.sampleRate / (1000.0/msecs)); this.outputAudioBuffer = window.audioContext.createBuffer(1, bufLen, window.audioContext.sampleRate); var outputFloatArray = this.outputAudioBuffer.getChannelData(0); for (var i = 0; i < outputFloatArray.length; i++) outputFloatArray[i] = 0; this.script_node_offset = 0; }, // draw the waveform to the canvas, assuming the proper UI element is provided // for debug, of course drawWaveform: function(canvas) { // comment out now for performonce var b = this.outputAudioBuffer.getChannelData(0); this.drawWaveformToCanvas(b, 0, canvas); }, processAudio: function(ev) { var outl=ev.outputBuffer.getChannelData(0); var outr=ev.outputBuffer.getChannelData(1); // If we're not playing, but still being called, just fill the channel with silence. if (!this.playing) { for (var i = 0; i < outl.length; i++) outl[i] = outr[i] = 0; // Some browsers crash when you stop playing if (this.can_stop) this.script_node.disconnect(); return; } var outputFloatArray = this.outputAudioBuffer.getChannelData(0); for (var i = 0; i < outl.length; i++) { if (this.script_node_offset >= outputFloatArray.length) { // If there's more data to play, reset the output float array. if (this.get_more_data()) outputFloatArray = this.outputAudioBuffer.getChannelData(0); // Otherwise, fill the buffer with 0s, and we'll stop playing on the next iteration. else { for (var j = 0; j < outputFloatArray.length; j++) outputFloatArray[j] = 0; } this.script_node_offset = 0; } outl[i] = outr[i] = outputFloatArray[this.script_node_offset++]; } }, // immediately play the modulated audio exactly once. Useful for debugging single packets playBuffer: function(obj, func) { console.log("-- playAudioBuffer --"); var bufferNode = window.audioContext.createBufferSource(); bufferNode.buffer = this.outputAudioBuffer; bufferNode.connect(window.audioContext.destination); // Connect to speakers bufferNode.addEventListener("ended", function() { var playTimeEnd = performance.now(); var timeElapsed = playTimeEnd - this.playTimeStart; console.log("got audio ended event after " + timeElapsed.toFixed(2) + "ms"); if (obj && func) func.call(obj); }.bind(this)); this.playTimeStart = performance.now(); bufferNode.start(0); // play immediately }, // Plays through an entire file. You need to set the callback so once // a single audio packet is finished, the next can start. The index // tells where to start playing. You could, in theory, start modulating // part-way through an audio stream by setting index to a higher number on your // first call. playLoop: function(obj, end_func, param) { this.get_more_data = function() { if (!end_func.call(obj, param)) { this.playing = false; return false; } return true; }; this.script_node.onaudioprocess = function(ev) { Modulator.prototype.processAudio.call(this, ev); }.bind(this); if (!this.playing) { this.playing = true; this.script_node.connect(window.audioContext.destination); } }, drawWaveformToCanvas: function(buffer, start, canvas) { if (!canvas || !canvas.getContext) return; var strip = canvas.getContext('2d'); // Resize the canvas to be the window size. canvas.width = window.innerWidth; canvas.height = window.innerHeight; var h = strip.canvas.height; var w = strip.canvas.width; strip.clearRect(0, 0, w, h); var y; // Draw scale lines at 10% interval strip.lineWidth = 1.0; strip.strokeStyle = "#55a"; strip.beginPath(); y = 1 * (h/10); strip.moveTo(0, y); strip.lineTo(w, y); y = 2 * (h/10); strip.moveTo(0, y); strip.lineTo(w, y); y = 3 * (h/10); strip.moveTo(0, y); strip.lineTo(w, y); y = 4 * (h/10); strip.moveTo(0, y); strip.lineTo(w, y); y = 5 * (h/10); strip.moveTo(0, y); strip.lineTo(w, y); y = 6 * (h/10); strip.moveTo(0, y); strip.lineTo(w, y); y = 7 * (h/10); strip.moveTo(0, y); strip.lineTo(w, y); y = 8 * (h/10); strip.moveTo(0, y); strip.lineTo(w, y); y = 9 * (h/10); strip.moveTo(0, y); strip.lineTo(w, y); strip.stroke(); strip.strokeStyle = "#fff"; strip.lineWidth = 1.0; var b = start; var lastSample = (buffer[b++] + 1) / 2; // map -1..1 to 0..1 for (var x = 1; x < canvas.width; x++) { var sample = (buffer[b++] + 1) / 2; if (b > buffer.length) break; strip.beginPath(); strip.moveTo(x - 1, h - lastSample * h); strip.lineTo(x, h - sample * h); strip.stroke(); lastSample = sample; } } }; /* Set up the constructor, so we can do "new Modulator()" */ window.Modulator = function(params) { return new Modulator(params); }; }(this));
Python
UTF-8
384
2.890625
3
[]
no_license
import tkinter as tk from tkinter import ttk from PIL import Image, ImageTk root = tk.Tk() root.geometry("800x500") root.title("ImageViewer") frame = tk.Frame(root) imgfile = 'cover1.png' im = ImageTk.PhotoImage(file=imgfile) canvas = tk.Canvas(root, width=800, height=500) canvas.pack() canvasImage = canvas.create_image(0, 0, image=im, anchor="nw") root.mainloop()
Java
UTF-8
4,176
2.015625
2
[]
no_license
package ru.efive.dms.uifaces.beans.dialogs; import org.apache.commons.lang.StringUtils; import org.primefaces.context.RequestContext; import ru.efive.dms.uifaces.beans.IndexManagementBean; import ru.entity.model.document.IncomingDocument; import ru.entity.model.document.RequestDocument; import ru.hitsl.sql.dao.IncomingDocumentDAOImpl; import ru.hitsl.sql.dao.RequestDocumentDAOImpl; import ru.util.ApplicationHelper; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.context.FacesContext; import javax.faces.view.ViewScoped; import javax.inject.Named; import java.io.Serializable; import static ru.hitsl.sql.dao.util.ApplicationDAONames.INCOMING_DOCUMENT_FORM_DAO; import static ru.hitsl.sql.dao.util.ApplicationDAONames.REQUEST_DOCUMENT_FORM_DAO; /** * Author: Upatov Egor <br> * Date: 23.04.2015, 17:45 <br> * Company: Korus Consulting IT <br> * Description: <br> */ @Named("reasonDocumentDialog") @ViewScoped public class ReasonDocumentDialogHolder implements Serializable { @EJB(name = "indexManagement") private IndexManagementBean indexManagementBean; public static final String DIALOG_SESSION_KEY = "DIALOG_REASON_DOCUMENT"; private boolean isIncoming = true; private IncomingDocument incomingSelection; private RequestDocument requestSelection; @PostConstruct public void init() { initializePreSelected(); } /** * Выбрать заранее заднный список пользователей по ключу сессии */ public void initializePreSelected() { final String preselected = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(DIALOG_SESSION_KEY); FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(DIALOG_SESSION_KEY); if (StringUtils.isNotEmpty(preselected)) { final Integer rootDocumentId = ApplicationHelper.getIdFromUniqueIdString(preselected); if (preselected.contains("incoming_")) { incomingSelection = ((IncomingDocumentDAOImpl)indexManagementBean.getContext().getBean(INCOMING_DOCUMENT_FORM_DAO)) .getItemByIdForSimpleView(rootDocumentId); } else if (preselected.contains("request_")) { requestSelection = ((RequestDocumentDAOImpl)indexManagementBean.getContext().getBean(REQUEST_DOCUMENT_FORM_DAO)) .getItemByIdForSimpleView(rootDocumentId); } } } public boolean isIncoming() { return isIncoming; } public void setIsIncoming(final boolean isIncoming) { this.isIncoming = isIncoming; if (isIncoming) { requestSelection = null; } else { incomingSelection = null; } } public String getTitle() { return "Выбор документа основания"; } public void chooseIncoming() { isIncoming = true; } public void chooseRequest() { isIncoming = false; } public IncomingDocument getIncomingSelection() { return incomingSelection; } public void setIncomingSelection(IncomingDocument incomingSelection) { this.incomingSelection = incomingSelection; } public RequestDocument getRequestSelection() { return requestSelection; } public void setRequestSelection(RequestDocument requestSelection) { this.requestSelection = requestSelection; } /** * Закрыть диалог с результатом * * @param withResult флаг указывающий передавать ли результат работы диалога */ public void closeDialog(boolean withResult) { String result=null; if(isIncoming) { if(incomingSelection != null){ result = incomingSelection.getUniqueId(); } } else { if(requestSelection != null){ result = requestSelection.getUniqueId(); } } RequestContext.getCurrentInstance().closeDialog(withResult ? result : null); } }
Python
UTF-8
1,700
3.40625
3
[]
no_license
import torch import string class Vocab(object): def __init__(self, end_token='>', start_token='<', pad_token='#'): self.pad_token = pad_token self.char2idx = {c: i+3 for i, c in enumerate(string.ascii_letters)} self.char2idx[pad_token] = 0 self.char2idx[start_token] = 1 self.char2idx[end_token] = 2 self.idx2char = {i: c for c, i in self.char2idx.items()} def __getitem__(self, char): return self.char2idx[char] def __contains__(self, char): return char in self.char2idx def __setitem__(self, key, value): raise ValueError('Vocab is read-only') def __len__(self): return len(self.char2idx) def chars2indices(self, words): if type(words) == list: return [[self[c] for c in word] for word in words] return [self[c] for c in words] def indices2chars(self, indices): return [self.idx2char[i] for i in indices] def pad_words(self, words): max_length = 0 for word in words: max_length = max(max_length, len(word)) padded_words = [] for word in words: if len(word) < max_length: padded_words.append(word + [self[self.pad_token]] * (max_length - len(word))) else: padded_words.append(word) return padded_words def to_input_tensor(self, words): char_ids = self.chars2indices(words) padded_words = self.pad_words(char_ids) padded_words = torch.tensor(padded_words, dtype=torch.long) return padded_words if __name__ == "__main__": vocab = Vocab() print(vocab.to_input_tensor(['hello']))
C++
UTF-8
554
3.375
3
[]
no_license
#ifndef SINGLETON_H #define SINGLETON_H /** * Guarantees that only a single instance of an object will exist * throughout the lifetime of the program. */ template <class Derived> class Singleton { public: Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static Derived& instance() { if (instance_ == nullptr) instance_ = new Derived(); return *instance_; } protected: Singleton() {} static Derived* instance_; }; template <class Derived> Derived* Singleton<Derived>::instance_ = nullptr; #endif
PHP
UTF-8
4,417
2.78125
3
[]
no_license
<?php $con = mysqli_connect("localhost","root","","db_reproductor"); $DatoMP3["nombre"] = ""; $DatoMP3["ruta"] = ""; $DatoMP3["descripcion"] = ""; if(isset($_REQUEST["que_debo_hacer"])){ switch($_REQUEST["que_debo_hacer"]){ case "agregar_mp3": //print_r($_FILES); copy($_FILES["mp3"]["tmp_name"],"mp3/".$_FILES["mp3"]["name"]); $sql = "insert into mp3 (nombre, descripcion, ruta, fecha_creado) values ('".$_REQUEST["nombre"]."','".$_REQUEST["descripcion"]."','".$_FILES["mp3"]["name"]."',now())"; mysqli_query($con,$sql); break; case "mostrar_para_editar": /*Obtener un solo registro de la tabla mp3*/ $sqlMP3 = "select * from mp3 where id = '".$_REQUEST["idMP3"]."' "; $QueryMP3 = mysqli_query($con,$sqlMP3); $DatoMP3 = mysqli_fetch_array($QueryMP3); break; case "editar_mp3": $sql = "update mp3 set nombre='".$_REQUEST["nombre"]."', descripcion='".$_REQUEST["descripcion"]."', ruta = '".$_REQUEST["ruta"]."' where id = '".$_REQUEST["idMP3"]."' "; mysqli_query($con,$sql); break; case "eliminar_mp3": $sql = "delete from mp3 where id = '".$_REQUEST["idMP3"]."' "; mysqli_query($con,$sql); break; } } /*OBtener todos los registro de la tabla mp3*/ $sql = "select * from mp3 "; $Query = mysqli_query($con,$sql); ?> <!------------------------------------------------------> <!doctype html> <html> <head> <title> Administrar MP3 </title> </head> <body> <fieldset> <legend>Agregar MP3</legend> <form action="" method="post" enctype="multipart/form-data"> <?php if(empty($DatoMP3["nombre"])){ ?> <input type="hidden" name="que_debo_hacer" value="agregar_mp3" /> <?php }else{ ?> <input type="hidden" name="que_debo_hacer" value="editar_mp3" /> <input type="hidden" name="idMP3" value="<?php echo $DatoMP3["id"]; ?>" /> <?php } ?> <input type="text" name="nombre" value="<?php echo $DatoMP3["nombre"]; ?>" placeholder="Nombre MP3"/> <hr/> <input type="file" name="mp3" /> <input type="hidden" name="ruta" placeholder="Ruta MP3" value="<?php echo $DatoMP3["ruta"]; ?>" /> <hr/> <textarea name="descripcion" placeholder="Descripción"><?php echo $DatoMP3["descripcion"]; ?></textarea> <br/> <button type="submit"> Procesar</button> </form> </fieldset> <fieldset> <legend>Listado de MP3</legend> <table border="1"> <tr> <th>Opciones</th> <th>Nombre</th> <th>Ruta</th> <th>Descripción</th> <th>Fecha</th> </tr> <!-------------------------------------------------> <?php while($registro = mysqli_fetch_array($Query)){ ?> <tr> <td><a href="?idMP3=<?php echo $registro["id"]; ?>&que_debo_hacer=mostrar_para_editar">Editar</a> || <a href="?idMP3=<?php echo $registro["id"]; ?>&que_debo_hacer=eliminar_mp3">Eliminar</a> </td> <td><?php echo $registro["nombre"]; ?></td> <td> <audio controls> <source src="mp3/<?php echo $registro["ruta"]; ?>" type="audio/mpeg"> </audio> </td> <td><?php echo $registro["descripcion"]; ?></td> <td><?php echo $registro["fecha_creado"]; ?></td> </tr> <?php } ?> <!-------------------------------------------------> </table> </fieldset> </body> </html>
Java
UTF-8
1,594
3.234375
3
[]
no_license
package com.oschrenk.humangeo.cs; /** * A spherical coordinate * * @see SphericalCoordinateSystem * * @author Oliver Schrenk <oliver.schrenk@gmail.com> */ public class SphericalCoordinate extends PolarCoordinate { private final double phi; /** * @param r * the radius * @param theta * the polar angle */ public SphericalCoordinate(final double r, final double theta) { super(r, theta); phi = 0; } /** * Instantiates a new spherical coordinate. * * @param r * the radius * @param theta * the polar angle * @param phi * the azimuthal angle */ public SphericalCoordinate(final double r, final double theta, final double phi) { super(r, theta); this.phi = phi; } /** * @return the azimuthal angle */ public double getPhi() { return phi; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); long temp; temp = Double.doubleToLongBits(phi); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; SphericalCoordinate other = (SphericalCoordinate) obj; if (Double.doubleToLongBits(phi) != Double.doubleToLongBits(other.phi)) return false; return true; } /* * @see java.lang.Object#toString() */ @Override public String toString() { return "SphericalCoordinate [r=" + getR() + ", phi=" + phi + ", theta=" + getTheta() + "]"; } }
Markdown
UTF-8
1,449
3.03125
3
[ "Unlicense" ]
permissive
# Rubrica con connessione al database Realizzare una applicazione con un'interfaccia che consenta di inserire i dati di una rubrica telefonica: - ID - nome - cognome - indirizzo - telefono - ecc... per poi visualizzarli e cancellarli. --- Relativamente alla cancellazione di un record e relativi messaggi utente sull'esito dell'operazione, dopo aver lanciato la query da codice PHP, utilizzare la funzione _mysqli_affected_rows_ che restituisce il numero di record interessati dalla query appena eseguita: 1. se restituisce il valore 0, la cancellazione non è avvenuta. 1. se restituisce altro allora ha avuto successo ## Database utenteRubrica (ID, nome, cognome, indirizzo, telefono, dataNascita, email) PK = utenteRubrica.ID ### Queries ```sql USE 5ai_19_20_s01118; CREATE TABLE IF NOT EXISTS `200203_utenteRubrica`( `ID` INT(11) NOT NULL AUTO_INCREMENT, `nome` VARCHAR(30) NOT NULL, `cognome` VARCHAR(30) NOT NULL, `indirizzo` VARCHAR(50) DEFAULT NULL, `telefono` VARCHAR(16) NOT NULL, `dataNascita` DATE DEFAULT NULL, `email` VARCHAR(50) DEFAULT NULL, PRIMARY KEY(ID) ); INSERT INTO `200203_utenteRubrica` (`nome`, `cognome`, `indirizzo`, `telefono`, `dataNascita`, `email`) VALUES ('Mario', 'Mastroianni', 'Via Roma, 20', '+39 456 273 3456', '2008-11-11', 'email@email.com'); SELECT * FROM `200203_utenteRubrica` ORDER BY `cognome`, `nome`; DELETE FROM `200203_utenteRubrica` WHERE `ID` = 1; ```
Ruby
UTF-8
1,517
3.375
3
[]
no_license
class SpiralGrid DIRECTIONS = { right: { step: ->(x, y){ [x + 1, y ] }, check: :max_x, next_direction: :up }, up: { step: ->(x, y){ [x , y + 1] }, check: :max_y, next_direction: :left }, left: { step: ->(x, y){ [x - 1, y ] }, check: :min_x, next_direction: :down }, down: { step: ->(x, y){ [x , y - 1] }, check: :min_y, next_direction: :right } } def self.coordinate_of(target) target_val = target current_val = 1 current_coord = [0, 0] direction = :right max_y = 0 min_y = 0 max_x = 0 min_x = 0 while current_val != target_val d_obj = DIRECTIONS[direction] # proceed 1 step # current_coord = d_obj[:step][*current_coord] current_val += 1 # check if we've gone far enough # time_to_turn = case d_obj[:check] when :max_x current_coord[0] == max_x + 1 when :max_y current_coord[1] == max_y + 1 when :min_x current_coord[0] == min_x - 1 when :min_y current_coord[1] == min_y - 1 end if time_to_turn case d_obj[:check] when :max_x max_x += 1 when :max_y max_y += 1 when :min_x min_x -= 1 when :min_y min_y -= 1 end direction = d_obj[:next_direction] end end current_coord end end coord = SpiralGrid.coordinate_of(347991) p coord p coord.reduce(0) { |sum, c| sum + c.abs }
Python
UTF-8
3,876
2.75
3
[ "MIT" ]
permissive
""" http://machinelearningmastery.com/understanding-stateful-lstm-recurrent-neural-networks-python-keras/ http://machinelearningmastery.com/text-generation-lstm-recurrent-neural-networks-python-keras/ http://machinelearningmastery.com/tactics-to-combat-imbalanced-classes-in-your-machine-learning-dataset/ """ from keras.models import Model, load_model from keras.utils import np_utils from keras.preprocessing.sequence import pad_sequences from os.path import isfile, join import numpy as np import sys ds = '../dataset/training/wonderland.txt' t_ds = '../dataset/training/wonderland.txt' modelName = 'Embedding +64E +128LSTM +128LSTM +activation +dropout' def char2vec(dataset): """Convert dataset into an integer array for an Embedding layer x: Embedded array y: one hot encoding array :param dataset: :return: x, y, samples, timestep, features, char_to_int, int_to_char """ try: raw_text = open(dataset, 'r').read().lower() print('[*]', dataset) except: raise chars = sorted(list(set(raw_text))) char_to_int = dict((c, i) for i, c in enumerate(chars)) int_to_char = dict((i, c) for i, c in enumerate(chars)) nb_chars = raw_text.__len__() features = chars.__len__() timestep = seq_length # cut the text in semi-redundant sequences of seq_length step = 3 X = [] Y = [] for i in range(0, nb_chars - seq_length, step): X.append(raw_text[i: i + seq_length]) Y.append(raw_text[i + seq_length]) samples = X.__len__() print('[*] Corpus Length:', nb_chars) # 163817 print('[*] Features:', features) # 61 print('[*] Samples:', samples) # 163761 print('[*] Timestep:', seq_length) # 56 # https://github.com/minimaxir/char-embeddings/blob/master/text_generator_keras.py#L48 # x = np.zeros((len(sentences), maxlen), dtype=np.int) # y = np.zeros((len(sentences), len(chars)), dtype=np.bool) # for i, sentence in enumerate(sentences): # for t, char in enumerate(sentence): # X[i, t] = char_indices[char] # y[i, char_indices[next_chars[i]]] = 1 print('[*] Vectorization...') x = np.zeros((samples, seq_length), dtype=np.int32) y = np.zeros((samples, features), dtype=np.bool) for i, sentence in enumerate(X): for t, char in enumerate(sentence): x[i, t] = char_to_int[char] y[i, char_to_int[Y[i]]] = 1 X = x # x = x / features return X, x, y, samples, timestep, features, char_to_int, int_to_char ############################################################################################# batch_size = 100 seq_length = 100 # input_length epochs = 1000000 initial_epoch = 0 normalize = True X, x, y, samples, timestep, features, char_to_int, int_to_char = char2vec(ds) load_checkpoint = 'checkpoints/weights-improvement-16-1.7885-0.4745.hdf5' model = load_model(load_checkpoint) ############################################################################################# print(model.summary()) start = np.random.randint(0, samples - 1) pattern = list(X[start]) print('Pattern:', ''.join([int_to_char[value] for value in pattern])) results = [] indexes = [] confidence = [] for i in range(200): x_predict = np.reshape(pattern, (1, 100)) if normalize: x_predict = x_predict / features prediction = model.predict(x_predict) index = np.argmax(prediction) confidence.append(prediction[0][index]) result = int_to_char[index] print(result, end='') sys.stdout.flush() results.append(result) indexes.append(str(index)) pattern.append(index) pattern = pattern[1:len(pattern)] # print('results:', ''.join(results)) print('>> END') print('indexes:', ''.join(indexes)) print('confidence: {:.2f}%'.format(int(sum(confidence)/len(confidence)*100)))
C
UTF-8
266
3.671875
4
[]
no_license
#include <stdio.h> #include <stdlib.h> int main() { float v1, v2; printf("type me two values: "); scanf("%f %f", &v1, &v2); if (v1 > v2) { printf("the bigger value is: %f", v1); } else { printf("the bigger value is: %f", v2); } return 0; }
Python
UTF-8
347
3.375
3
[]
no_license
def spam(divideBy): try: return 42/divideBy except ZeroDivisionError: print('error') print(spam(2)) print(spam(12)) print(spam(0)) print(spam(1)) def spam2(divideBy): return 42/divideBy try: print(spam2(2)) print(spam2(12)) print(spam2(0)) print(spam2(1)) except ZeroDivisionError: print('error')
Markdown
UTF-8
11,470
2.6875
3
[ "MIT" ]
permissive
--- title: Linux Centos 命令之 cp,rm,mv date: 2018-04-21 13:50:00 categories: - Linux tags: - Centos --- ## cp - copy 拷贝目录,文件 <!--more--> ### Usage: ```bash Usage: cp [OPTION]... [-T] SOURCE DEST or: cp [OPTION]... SOURCE... DIRECTORY or: cp [OPTION]... -t DIRECTORY SOURCE... Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a previous -i option) -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes (default: mode,ownership,timestamps), if possible additional attributes: context, links, xattr, all -c deprecated, same as --preserve=context --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file -u, --update copy only when the SOURCE file is newer than the destination file or when the destination file is missing -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. ``` ### 常用选项: -a / -p:连同文件属性一起复制(用户组属性受 id 权限限制) -i(interactive):覆盖询问 -r(recursive): 用于目录的递归复制 -u (update):source 比 destination 新才复制 - 覆盖询问 ```bash [root@78063f0fe2e8 ~]# cp ~/.bashrc /tmp/bashrc [root@78063f0fe2e8 ~]# cp -i ~/.bashrc /tmp/bashrc cp: overwrite ‘/tmp/bashrc’? y ``` - 连同文件属性一起复制 ```bash [root@78063f0fe2e8 ~]# cd /tmp [root@78063f0fe2e8 tmp]# cp /var/log/wtmp . [root@78063f0fe2e8 tmp]# ls -l /var/log/wtmp wtmp -rw-rw-r-- 1 root utmp 0 Apr 2 18:38 /var/log/wtmp -rw-r--r-- 1 root root 0 Apr 21 06:23 wtmp [root@78063f0fe2e8 tmp]# cp -a /var/log/wtmp wtmp2 [root@78063f0fe2e8 tmp]# ls -l /var/log/wtmp wtmp2 -rw-rw-r-- 1 root utmp 0 Apr 2 18:38 /var/log/wtmp -rw-rw-r-- 1 root utmp 0 Apr 2 18:38 wtmp2 ``` - 用于目录的递归复制 ```bash [root@78063f0fe2e8 tmp]# cp /etc /tmp cp: omitting directory ‘/etc’ [root@78063f0fe2e8 tmp]# cp -r /etc /tmp ``` {{< asciinemal 177529 >}} ## rm - remove 删除目录或文件 ### Usage: ```bash Usage: rm [OPTION]... FILE... Remove (unlink) the FILE(s). -f, --force ignore nonexistent files and arguments, never prompt -i prompt before every removal -I prompt once before removing more than three files, or when removing recursively; less intrusive than -i, while still giving protection against most mistakes --interactive[=WHEN] prompt according to WHEN: never, once (-I), or always (-i); without WHEN, prompt always --one-file-system when removing a hierarchy recursively, skip any directory that is on a file system different from that of the corresponding command line argument --no-preserve-root do not treat '/' specially --preserve-root do not remove '/' (default) -r, -R, --recursive remove directories and their contents recursively -d, --dir remove empty directories -v, --verbose explain what is being done --help display this help and exit --version output version information and exit By default, rm does not remove directories. Use the --recursive (-r or -R) option to remove each listed directory, too, along with all of its contents. To remove a file whose name starts with a '-', for example '-foo', use one of these commands: rm -- -foo rm ./-foo Note that if you use rm to remove a file, it might be possible to recover some of its contents, given sufficient expertise and/or time. For greater assurance that the contents are truly unrecoverable, consider using shred. ``` ### 常用选项: -f(force):忽略不存在的文件 -i(interactive):询问删除 -r(recursive):递归删除 ```bash sh-4.2# cd /tmp sh-4.2# ls bashrc mingle1 tmpxq2sylvo-ascii.cast wtmp2 ks-script-hE5IPf test1 wtmp yum.log sh-4.2# rm -i bashrc rm: remove regular file ‘bashrc’? y sh-4.2# ls ks-script-hE5IPf mingle1 test1 tmpxq2sylvo-ascii.cast wtmp wtmp2 yum.log sh-4.2# rmdir mingle1 sh-4.2# rmdir test1 rmdir: failed to remove ‘test1’: Directory not empty sh-4.2# rm -rf test1 sh-4.2# ls ks-script-hE5IPf tmpxq2sylvo-ascii.cast wtmp wtmp2 yum.log sh-4.2# touch ./-aaa- sh-4.2# ls -aaa- ks-script-hE5IPf tmpxq2sylvo-ascii.cast wtmp wtmp2 yum.log sh-4.2# rm -f -aaa- rm: invalid option -- 'a' Try 'rm ./-aaa-' to remove the file ‘-aaa-’. Try 'rm --help' for more information. sh-4.2# rm -f ./-aaa- sh-4.2# ls ks-script-hE5IPf tmpxq2sylvo-ascii.cast wtmp wtmp2 yum.log sh-4.2# rm -rf wtmp* sh-4.2# ls ks-script-hE5IPf tmpxq2sylvo-ascii.cast yum.log ``` {{< asciinemal 177530 >}} ## mv - move 移动文件或目录,更名 ### Usage: ```bash Usage: mv [OPTION]... [-T] SOURCE DEST or: mv [OPTION]... SOURCE... DIRECTORY or: mv [OPTION]... -t DIRECTORY SOURCE... Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument -f, --force do not prompt before overwriting -i, --interactive prompt before overwrite -n, --no-clobber do not overwrite an existing file If you specify more than one of -i, -f, -n, only the final one takes effect. --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY move all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file -u, --update move only when the SOURCE file is newer than the destination file or when the destination file is missing -v, --verbose explain what is being done -Z, --context set SELinux security context of destination file to default type --help display this help and exit --version output version information and exit The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups ``` ### 常用选项: -f(force):不询问直接覆盖 -i( interactive): 询问覆盖 -u(update):source 新于 destination 才会 move - 普通移动 ```bash sh-4.2# cd /tmp sh-4.2# cp ~/.bashrc bashrc1 sh-4.2# cp ~/.bashrc bashrc2 sh-4.2# ls bashrc1 bashrc2 ks-script-hE5IPf tmp8u627nsx-ascii.cast yum.log sh-4.2# mkdir mvtest sh-4.2# ls bashrc1 bashrc2 ks-script-hE5IPf mvtest tmp8u627nsx-ascii.cast yum.log sh-4.2# mv bashrc1 bashrc2 mvtest sh-4.2# ls ks-script-hE5IPf mvtest tmp8u627nsx-ascii.cast yum.log sh-4.2# cd mvtest sh-4.2# ls bashrc1 bashrc2 ``` - 重命名 ```bash sh-4.2# cd .. sh-4.2# ls ks-script-hE5IPf mvtest tmp8u627nsx-ascii.cast yum.log sh-4.2# mv mvtest mvtest2 sh-4.2# ls ks-script-hE5IPf mvtest2 tmp8u627nsx-ascii.cast yum.log ``` {{< asciinemal 177531 >}}
Markdown
UTF-8
22,917
3.65625
4
[]
no_license
### DESIGNING A THREAD-SAFE CLASS While it is possible to write a thread-safe program that stores all its state in public static fields, it is a lot harder to verify its thread safety or to modify it so that it remains thread-safe than one that uses encapsulation appropriately. Encapsulation makes it possible to determine that a class is thread-safe without having to examine the entire program. The design process for a thread-safe class should include these three basic elements: - Identify the variables that form the object's state; - Identify the invariants that constrain the state variables; - Establish a policy for managing concurrent access to the object's state. An object's state starts with its fields. If they are all of primitive type, the fields comprise the entire state. **Counter** has only one field, so the value field comprises its entire state. The state of an object with n primitive fields is just the n-tuple of its field values; the state of a 2D **Point** is its (x, y) value. If the object has fields that are references to other objects, its state will encompass fields from the referenced objects as well. For example, the state of a **LinkedList** includes the state of all the link node objects belonging to the list. The synchronization policy defines how an object coordinates access to its state without violating its invariants or postconditions. It specifies what combination of immutability, thread confinement, and locking is used to maintain thread safety, and which variables are guarded by which locks. To ensure that the class can be analyzed and maintained, document the synchronization policy. ```java //annotation will be used as Thread safety policy documentation. @ThreadSafe public class Counter { @GuardedBy("this") private long value = 0; public synchronized long getValue() { return value; } public synchronized long increment() { if(value == Long.MAX_VALUE){ throw new IllegalStateException("counter overflow"); } return value++; } } ``` #### Gathering Synchronization Requirements Making a class thread-safe means ensuring that its invariants hold under concurrent access; this requires reasoning about its state. Objects and variables have a state space: the range of possible states they can take on. The smaller this state space, the easier it is to reason about. By using final fields wherever practical, you make it simpler to analyze the possible states an object can be in. Many classes have **invariants** that identify certain **states as valid or invalid**. The value field in Counter is a long. The state space of a long ranges from Long.MIN_VALUE to Long.MAX_VALUE, but Counter places constraints on value; negative values are not allowed(as intilaized with 0 and always get incremented). Similarly, operations may have **postconditions** that identify certain **state transitions as invalid**. If the current state of a Counter is 17, the only valid next state is 18. When the next state is derived from the current state, the operation is necessarily a compound action.Not all operations impose state transition constraints; when updating a variable that holds the current temperature,its previous state does not affect the computation. Constraints placed on states or state transitions by invariants and postconditions create additional synchronization or encapsulation requirements. If certain states are invalid, then the underlying state variables must be encapsulated, otherwise client code could put the object into an invalid state. If an operation has invalid state transitions, it must be made atomic. A class can also have invariants that constrain multiple state variables.related variables must be fetched or updated in a single atomic operation. You cannot update one, release and reacquire the lock, and then update the others, since this could involve leaving the object in an invalid state when the lock was released. When multiple variables participate in an invariant, the lock that guards them must be held for the duration of any operation that accesses the related variables. You cannot ensure thread safety without understanding an object's invariants and postconditions. Constraints on the valid values or state transitions for state variables can create atomicity and encapsulation requirements. #### State-dependent Operations Class invariants and method postconditions constrain the valid states and state transitions for an object. Some objects also have methods with state-based preconditions. For example, you cannot remove an item from an empty queue; a queue must be in the “nonempty” state before you can remove an element. **Operations with state-based preconditions are called state-dependent** #### State Ownership Ownership is not embodied explicitly in the language, but is instead an element of class design. If you allocate and populate a HashMap, you are creating multiple objects: the HashMap object, a number of Map.Entry objects used by the implementation of HashMap, and perhaps other internal objects as well. The logical state of a HashMap includes the state of all its Map.Entry and internal objects, even though they are implemented as separate objects. For better or worse, garbage collection lets us avoid thinking carefully about ownership. When passing an object to a method in C++, you have to think fairly carefully about whether you are transferring ownership, engaging in a short-term loan, or envisioning long-term joint ownership. In Java, all these same ownership models are possible, but the garbage collector reduces the cost of many of the common errors in reference sharing, enabling less-than-precise thinking about ownership. It is the owner of a given state variable that gets to decide on the locking protocol used to maintain the integrity of that variable's state. Ownership implies control, but once you publish a reference to a mutable object, you no longer have exclusive control; at best, you might have “shared ownership”. A class usually does not own the objects passed to its methods or constructors, unless the method is designed to explicitly transfer ownership of objects passed in ### INSTANCE CONFINEMENT Encapsulation simplifies making classes thread-safe by promoting instance confinement, often just called confinement.When an object is encapsulated within another object, all code paths that have access to the encapsulated object are known and can be therefore be analyzed more easily than if that object were accessible to the entire program. Combining confinement with an appropriate locking discipline can ensure that otherwise non-thread-safe objects are used in a thread-safe manner.Confined objects must not escape their intended scope. PersonSet illustrates how confinement and locking can work together to make a class thread-safe even when its component state variables are not. The state of PersonSet is managed by a HashSet, which is not thread-safe. But because mySet is private and not allowed to escape, the HashSet is confined to the PersonSet. The only code paths that can access mySet are addPerson and containsPerson, and each of these acquires the lock on the PersonSet. All its state is guarded by its intrinsic lock, making PersonSet thread-safe. ```java class PersonSet { private final Set<Person> set = new HashSet<>(); public synchronized void add(Person p){ set.add(p); } public synchronized boolean containsPerson(Person p){ return set.contains(p); } } class Person{ } ``` This example makes no assumptions about the thread-safety of Person, but if it is mutable, additional synchronization will be needed when accessing a Person retrieved from a PersonSet. The most reliable way to do this would be to make Person thread-safe; less reliable would be to guard the Person objects with a lock and ensure that all clients follow the protocol of acquiring the appropriate lock before accessing the Person. Of course, it is still possible to violate confinement by publishing a supposedly confined object; if an object is intended to be confined to a specific scope, then letting it escape from that scope is a bug. Confined objects can also escape by publishing other objects such as iterators or inner class instances that may indirectly publish the confined objects. Confinement makes it easier to build thread-safe classes because a class that confines its state can be analyzed for thread safety without having to examine the whole program. #### The Java Monitor Pattern Following the principle of instance confinement to its logical conclusion leads you to the Java monitor pattern.[2] An object following the Java monitor pattern encapsulates all its mutable state and guards it with the object's own intrinsic lock. The bytecode instructions for entering and exiting a synchronized block are even called monitorenter and monitorexit, and Java's built-in (intrinsic) locks are sometimes called monitor locks or monitors. [***Counter***](Counter.java) above shows a typical example of this pattern. It encapsulates one state variable, value, and all access to that state variable is through the methods of Counter, which are all synchronized. The Java monitor pattern is used by many library classes, such as Vector and Hashtable. The Java monitor pattern is merely a convention; any lock object could be used to guard an object's state so long as it is used consistently. as shown below. ```java class PrivateLock{ private Object lock = new Object(); Widget widget; void someMethod(){ synchronized (lock){ //do something; } } } ``` #### Example: Tracking Fleet Vehicles [***Code***](MonitorVehicleTracker.java) ### DELEGATING THREAD SAFETY In CountingFactorizer on page 23, we added an AtomicLong to an otherwise stateless object, and the resulting composite object was still thread-safe. Since the state of CountingFactorizer is the state of the thread-safe AtomicLong, and since CountingFactorizer imposes no additional validity constraints on the state of the counter, it is easy to see that CountingFactorizer is thread-safe. We could say that CountingFactorizer delegates its thread safety responsibilities to the AtomicLong: CountingFactorizer is thread-safe because AtomicLong is. If count were not final, the thread safety analysis of CountingFactorizer would be more complicated. If CountingFactorizer could modify count to reference a different AtomicLong, we would then have to ensure that this update was visible to all threads that might access the count, and that there were no race conditions regarding the value of the count reference. This is another good reason to use final fields wherever practical. #### Example: Vehicle Tracker Using Delegation As a more substantial example of delegation, let's construct a version of the vehicle tracker that delegates to a thread-safe class. We store the locations in a Map, so we start with a thread-safe Map implementation, ConcurrentHashMap. We also store the location using an immutable Point class instead of MutablePoint Point is thread-safe because it is immutable. Immutable values can be freely shared and published, so we no longer need to copy the locations when returning them. [***Code***](DelegatingVehicleTracker.java) If we had used the original MutablePoint class instead of Point, we would be breaking encapsulation by letting getLocations publish a reference to mutable state that is not thread-safe. Notice that we've changed the behavior of the vehicle tracker class slightly; while the monitor version returned a snapshot of the locations, the delegating version returns an unmodifiable but “live” view of the vehicle locations. This means that if thread A calls getLocations and thread B later modifies the location of some of the points, those changes are reflected in the Map returned to thread A. As we remarked earlier, this can be a benefit (more up-to-date data) or a liability (potentially inconsistent view of the fleet), depending on your requirements. #### Independent State Variables The delegation examples so far delegate to a single, thread-safe state variable. We can also delegate thread safety to more than one underlying state variable as long as those underlying state variables are independent, meaning that the composite class does not impose any invariants involving the multiple state variables. VisualComponent in Listing 4.9 is a graphical component that allows clients to register listeners for mouse and keystroke events. It maintains a list of registered listeners of each type, so that when an event occurs the appropriate listeners can be invoked. But there is no relationship between the set of mouse listeners and key listeners; the two are independent, and therefore VisualComponent can delegate its thread safety obligations to two underlying thread-safe lists. [***Code***](VisualComponent.java) VisualComponent uses a CopyOnWriteArrayList to store each listener list; this is a thread-safe List implementation particularly suited for managing listener lists. Each List is thread-safe, and because there are no constraints coupling the state of one to the state of the other, VisualComponent can delegate its thread safety responsibilities to the underlying mouseListeners and keyListeners objects. #### When Delegation Fails NumberRange is not thread-safe; it does not preserve the invariant that constrains lower and upper. The setLower and setUpper methods attempt to respect this invariant, but do so poorly. Both setLower and setUpper are check-then-act sequences, but they do not use sufficient locking to make them atomic. If the number range holds (0, 10), and one thread calls setLower(5) while another thread calls setUpper(4), with some unlucky timing both will pass the checks in the setters and both modifications will be applied. The result is that the range now holds (5, 4)—an invalid state. So while the underlying AtomicIntegers are thread-safe, the composite class is not. Because the underlying state variables lower and upper are not independent, NumberRange cannot simply delegate thread safety to its thread-safe state variables. If a class has compound actions, as NumberRange does, delegation alone is again not a suitable approach for thread safety. In these cases, the class must provide its own locking to ensure that compound actions are atomic, unless the entire compound action can also be delegated to the underlying state variables. [***Code***](NumberRange.java) If a class is composed of multiple independent thread-safe state variables and has no operations that have any invalid state transitions, then it can delegate thread safety to the underlying state variables. #### Publishing underlying state variables When you delegate thread safety to an object's underlying state variables, under what conditions can you publish those variables so that other classes can modify them as well? Again, the answer depends on what invariants your class imposes on those variables. While the underlying value field in Counter could take on any integer value, Counter constrains it to take on only positive values, and the increment operation constrains the set of valid next states given any current state. If you were to make the value field public, clients could change it to an invalid value, so publishing it would render the class incorrect. On the other hand, if a variable represents the current temperature or the ID of the last user to log on, then having another class modify this value at any time probably would not violate any invariants, so publishing this variable might be acceptable. (It still may not be a good idea, since publishing mutable variables constrains future development and opportunities for subclassing, but it would not necessarily render the class not thread-safe.) If a state variable is thread-safe, does not participate in any invariants that constrain its value, and has no prohibited state transitions for any of its operations, then it can safely be published. For example, it would be safe to publish mouseListeners or keyListeners in VisualComponent. Because VisualComponent does not impose any constraints on the valid states of its listener lists, these fields could be made public or otherwise published without compromising thread safety. #### Example: Vehicle Tracker that Publishes Its State PublishingVehicleTracker derives its thread safety from delegation to an underlying ConcurrentHashMap, but this time the contents of the Map are thread-safe mutable points rather than immutable ones. The getLocation method returns an unmodifiable copy of the underlying Map. Callers cannot add or remove vehicles, but could change the location of one of the vehicles by mutating the SafePoint values in the returned Map. Again, the “live” nature of the Map may be a benefit or a drawback, depending on the requirements. PublishingVehicleTracker is thread-safe, but would not be so if it imposed any additional constraints on the valid values for vehicle locations. If it needed to be able to “veto” changes to vehicle locations or to take action when a location changes, the approach taken by PublishingVehicleTracker would not be appropriate. [***Code***](PublishingVehicleTracker.java) ### ADDING FUNCTIONALITY TO EXISTING THREAD-SAFE CLASSES - The safest way to add a new atomic operation is to modify the original class to support the desired operation, but this is not always possible because you may not have access to the source code or may not be free to modify it. If you can modify the original class, you need to understand the implementation's synchronization policy so that you can enhance it in a manner consistent with its original design. Adding the new method directly to the class means that all the code that implements the synchronization policy for that class is still contained in one source file, facilitating easier comprehension and maintenance. - Another approach is to extend the class, assuming it was designed for extension. Extension is more fragile than adding code directly to a class, because the implementation of the synchronization policy is now distributed over multiple, separately maintained source files. If the underlying class were to change its synchronization policy by choosing a different lock to guard its state variables, the subclass would subtly and silently break, because it no longer used the right lock to control concurrent access to the base class's state. #### Client-side Locking For an ArrayList wrapped with a Collections.synchronizedList wrapper, neither of these approaches—adding a method to the original class or extending the class—works because the client code does not even know the class of the List object returned from the synchronized wrapper factories. A third strategy is to extend the functionality of the class without extending the class itself by placing extension code in a “helper” class. Following code shows a failed attempt to create a helper class with an atomic put-if-absent operation for operating on a thread-safe List. ```java class ListHelper<E>{ public List<E> list = Collections.synchronizedList(new ArrayList<>()); public synchronized boolean putIfAbsent(E element){ if(!list.contains(element)){ return list.add(element); } return false; } } ``` After all, putIfAbsent is synchronized, right? The problem is that it synchronizes on the wrong lock. Whatever lock the List uses to guard its state, it sure isn't the lock on the ListHelper. ListHelper provides only the illusion of synchronization; the various list operations, while all synchronized, use different locks, which means that putIfAbsent is not atomic relative to other operations on the List. So there is no guarantee that another thread won't modify the list while putIfAbsent is executing. To make this approach work, we have to use the same lock that the List uses by using client-side locking or external locking. The documentation for Vector and the synchronized wrapper classes states, albeit obliquely, that they support client-side locking, by using the intrinsic lock for the Vector or the wrapper collection ```java class ListHelper<E>{ public List<E> list = Collections.synchronizedList(new ArrayList<>()); public boolean putIfAbsent(E element){ synchronized (list){ // Lock should be on list as it list is using intrinsic lock if(!list.contains(element)){ return list.add(element); } return false; } } } ``` If extending a class to add another atomic operation is fragile because it distributes the locking code for a class over multiple classes in an object hierarchy, client-side locking is even more fragile because it entails putting locking code for class C into classes that are totally unrelated to C. Exercise care when using client-side locking on classes that do not commit to their locking strategy. Client-side locking has a lot in common with class extension—they both couple the behavior of the derived class to the implementation of the base class. Just as extension violates encapsulation of implementation, client-side locking violates encapsulation of synchronization policy. #### Composition Delegating them to an underlying List instance, and adds an atomic putIfAbsent method. ```java class ImprovedList<E> implements List<E>{ public List<E> list; public ImprovedList(List<E> list) { this.list = list; } public synchronized boolean putIfAbsent(E element){ if(!list.contains(element)){ return list.add(element); } return false; } @Override public int size() { return 0; } @Override public boolean isEmpty() { return false; } .... ``` ImprovedList adds an additional level of locking using its own intrinsic lock. It does not care whether the underlying List is thread-safe, because it provides its own consistent locking that provides thread safety even if the List is not thread-safe or changes its locking implementation. While the extra layer of synchronization may add some small performance penalty ### DOCUMENTING SYNCHRONIZATION POLICIES Document a class's thread safety guarantees for its clients; document its synchronization policy for its maintainers. Each use of synchronized, volatile, or any thread-safe class reflects a synchronization policy defining a strategy for ensuring the integrity of data in the face of concurrent access. That policy is an element of your program's design, and should be documented. Of course, the best time to document design decisions is at design time.
C#
UTF-8
1,911
2.609375
3
[]
no_license
using Microsoft.AspNetCore.Mvc; using SeminarManager.API.Misc; using SeminarManager.Model; using System; namespace SeminarManager.API.Controllers { public class PersonController : Controller { private IRepository repository; public PersonController(IRepository repository) { this.repository = repository; } [Route("/Person/")] [HttpPost] public IActionResult Create([FromBody] Person obj) { repository.Persons.Save(obj); return Json(new OperationResult()); } [Route("/Person/")] [HttpGet] public IActionResult Read() { var objects = repository.Persons.All(); return Json(objects); } [Route("/Person/{id}")] [HttpGet] public IActionResult Read(int id) { var obj = repository.Persons.ById(id); if (obj == null) return Json(new OperationResult("Object not found!")); return Json(obj); } [Route("/Person/{id}")] [HttpPut] public IActionResult Update([FromRoute] int id, [FromForm] Person obj) { if (repository.Persons.ById(id) == null) return Json(new OperationResult("Object not found!")); obj.ID = id; repository.Persons.Save(obj); return Json(new OperationResult()); } [Route("/Person/{id}")] [HttpDelete] public IActionResult Delete(int id) { var user = (Person)HttpContext.Items["user"]; if (id == user.ID) return Json(new OperationResult("Cannot delete current user!")); repository.Persons.Delete(id); return Json(new OperationResult()); } } }
C++
UTF-8
1,400
3.546875
4
[]
no_license
/* * File: main.cpp * Author: Tony Reyes * July, 2 2014 * Purpose: Gaddis 7thEd Chap4 Prob8 Change For A Dollar */ //System Libraries #include <iostream> #include <iomanip> using namespace std; //User Libraries //Global Constants //Function Prototypes //Execution Starts Here! int main(int argc, char** argv) { //Declare variables & Initialize Entries //Inputs int penny, nickel, dime, quarter; //Outputs int dollr= 0; //Enter Number of (Pennies, Nickels, Dimes, Quarters) cout<<"Enter Number Pennies= "; cin>>penny; cout<<"Enter Number Nickels= "; cin>>nickel; cout<<"Enter Number Dimes= "; cin>>dime; cout<<"Enter Number Quarters= "; cin>>quarter; //Calculations //Calculate Winning Ticket dollr= (penny*1)+(nickel*5)+(dime*10)+(quarter*25); //Validate Expressions //Validate Winning Amount & Display Outputs if (dollr < 100) cout<<"You Lose, Under $1.00 "; else if (dollr > 100) cout<<"You Lose Over $1.00 "; else cout<<"You Win Congratulations"; //Display if User "Won" or "Lost" the Game cout<<setprecision(2)<<fixed<<endl; cout<<"Total Amount Entered ($) "<<dollr<<endl; //Exit stage right! return 0; }
Python
UTF-8
863
2.84375
3
[]
no_license
from moviemon.entity.Map import * from moviemon.entity.Player import * import pickle class Game(): def __init__(self): self.mapX = 10 self.mapY = 20 self.fileGame = "game.save" self.map = Map(self.mapX, self.mapY) playerStart = self.map.getPlayerStart() print("New Game : ", playerStart) self.player = Player(1, 10, playerStart.get("x"), playerStart.get("y") ) def load(self): pass def dump(self): pass def get_random_movie(self): pass def load_default_settings(self): pass def get_strength(self): pass def get_movie(self, id): pass def save_game(self): pickle.dump(self, open(self.fileGame, "wb" ) ) def load_game(self): print("After load : ", self.map.getPlayerStart())
Java
ISO-8859-1
2,355
3.078125
3
[]
no_license
package collectionsDetektiv; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; public class Testdriver { public static Set<String> verdaechtige; public static Set<String> hatAlibi; public static Set<String> liebtGold; public static Set<String> zugangZumSafe; public static Set<String> zugangZumSafeSchluessel; public static Set<String> taeter; public static void main(String[] args) { taeter = new HashSet<>(); verdaechtigeAnlegen(); taeter = ermitteln(); System.out.println(taeter); } private static void verdaechtigeAnlegen() { //Die Verdchtigen String herrMueller = "Herr Mller"; String frauMueller = "Frau Mller"; String herrMaier = "Herr Maier"; String frauMaier = "Frau Maier"; String derGaertner = "Der Grtner"; String diePutzfrau = "Die Putzfrau"; String dieDiebischeElster = "Die diebische Elster"; verdaechtige = new HashSet<>(); verdaechtige.add(herrMueller); verdaechtige.add(frauMueller); verdaechtige.add(herrMaier); verdaechtige.add(frauMaier); verdaechtige.add(derGaertner); verdaechtige.add(diePutzfrau); verdaechtige.add(dieDiebischeElster); //Beweisstcke //Beweisstck A hatAlibi = new HashSet<>(); hatAlibi.add(frauMueller); hatAlibi.add(derGaertner); //Beweisstck B liebtGold = new HashSet<>(); liebtGold.add(frauMueller); liebtGold.add(herrMaier); liebtGold.add(derGaertner); liebtGold.add(diePutzfrau); liebtGold.add(dieDiebischeElster); //Beweisstck C zugangZumSafe = new HashSet<>(); zugangZumSafe.add(herrMueller); zugangZumSafe.add(herrMaier); zugangZumSafe.add(derGaertner); zugangZumSafe.add(diePutzfrau); //Beweisstck D zugangZumSafeSchluessel = new HashSet<>(); zugangZumSafeSchluessel.add(herrMueller); zugangZumSafeSchluessel.add(frauMueller); zugangZumSafeSchluessel.add(herrMaier); zugangZumSafeSchluessel.add(frauMaier); zugangZumSafeSchluessel.add(dieDiebischeElster); } private static Set<String> ermitteln() { Set<String> eingrenzung = new HashSet<String>(); eingrenzung = verdaechtige; eingrenzung.removeAll(hatAlibi); eingrenzung.retainAll(liebtGold); eingrenzung.retainAll(zugangZumSafe); eingrenzung.retainAll(zugangZumSafeSchluessel); return eingrenzung; } }
C
UTF-8
1,305
3.234375
3
[]
no_license
#include <stdio.h> #include "func.h" int main(void) { double x = 5; double result; const int n = 6; int a[] = {1,2,3,4,5,6}; int ab[n]; int ac[]={4,3,6,2,1,5}; int ad[n]; do { system("cls"); printf("1 - Task1\n2 - Task2\n3 - Task3\n4 - Task4\n5 - Task5\n6 - Exit\r\n"); char answer = _getch(); system("cls"); switch (answer) { case '1': f(&x, &result); printf("x = %.4lf\nf(x) = %.4lf", x, result); printf("\nEnter x:\n"); scanf("%lf", &x); f(&x, &result); printf("x = %.4lf\nf(x) = %.4lf\n", x, result); break; case '2': writeArray(a, n); printf("\n"); break; case '3': readArray(ab, n); printf("\n"); break; case '4': sort(ac, n); printf("\n"); break; case '5': fullsort(ad, n); printf("\n"); break; case '6': return 0; break; default: printf("Invalid input\n"); break; } system("pause"); } while (1); return 0; }
Go
UTF-8
671
3
3
[ "MIT" ]
permissive
package leetcode538 import ( . "github.com/cxjwin/go-algocasts/datastructure" ) func dfs(root *TreeNode, sum int) int { if root == nil { return sum } cur := dfs(root.Right, sum) root.Val += cur return dfs(root.Left, root.Val) } func convertBST(root *TreeNode) *TreeNode { dfs(root, 0) return root } func convertBSTIterative(root *TreeNode) *TreeNode { if root == nil { return root } cur := root st := make([]*TreeNode, 0) sum := 0 for cur != nil || len(st) != 0 { for cur != nil { st = append(st, cur) cur = cur.Right } cur = st[len(st)-1] st = st[:len(st)-1] cur.Val += sum sum = cur.Val cur = cur.Left } return root }
C
UTF-8
760
2.671875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> //#include "SString.h" #include "HString.h" int main(){ /*SString S; SString T; SString A; SString B;*/ HString S,T,B,A; int next[INITIAL_SIZE]; char* s = "abbaba"; char* t = "a"; char* a = "AA"; //SStrAssign(S, s); //SStrAssign(T, t); //SStrAssign(A, a); /*SStrLength(T); SStrPrint(S); SStrPrint(T); next1(next,T); KMP_SString(S, T,5,next);*/ //StrCompare(S,T); //StrCompare(A,T); //SStrConcat(S,S,A); //Replace_SString(S,T,A); //SStrPrint(S); HStrAssign(&S,s); HStrAssign(&T,t); HStrAssign(&B,""); HStrAssign(&A, a); //HStrPrint(S); HStrPrint(T); //next3_hstr(next,T); //KMP_HString(S,T,1,next); HStrConcat(&B,S,T); HStrPrint(B); Replace_HString(&S,T,A); HStrPrint(S); return 0; }
C
IBM852
2,689
3.5625
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #define DEZ 10 //tamanho da matriz do caa palavras char matriz[DEZ][DEZ]; //matriz do caa palavras //preenche a matriz com zeros, evitando lixos de memoria void inicializa_matriz() { for(int i = 0; i < 10; i++){ memset(matriz[i], 0, DEZ); } } char gera_letra_aleatoria() { char alfabeto[26] = {'A', 'B', 'C', 'D', 'E','F', 'G', 'H', 'I', 'J','K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; int indice_letra = rand() % 26; return alfabeto[indice_letra]; } void preenche_matriz_com_letras(){ for (int i= 0; i < DEZ; i++) { for (int j= 0; j < DEZ; j++) { char letra; letra = gera_letra_aleatoria(); if(matriz[i][j] == 0) matriz[i][j] = letra; } } } void imprime_caca_palavras(){ for(int i = 0; i < DEZ; i++){ for(int j = 0; j < DEZ; j++) printf("%c|", matriz[i][j]); printf("\n"); } } void coloca_palavra_diagonal_decrescente(char palavra[DEZ]){ int i = rand() % (DEZ - strlen(palavra)); //linha da primeira letra da palavra int j = rand() % (DEZ - strlen(palavra)); //coluna da primeira letra da palavra while (matriz[i][j] != 0) { i = rand() % (DEZ - strlen(palavra)); j = rand() % (DEZ - strlen(palavra)); } for(int k =0; k < strlen(palavra); k++) { matriz[i][j] = palavra[k]; i++; j++; } } void coloca_palavra_diagonal_crescente(char palavra[DEZ]){ int i = strlen(palavra) + (rand() % (DEZ - strlen(palavra))); //linha da primeira letra da palavra int j = rand() % (DEZ - strlen(palavra)); //coluna da primeira letra da palavra while (matriz[i][j] != 0) { i = strlen(palavra) + (rand() % (DEZ - strlen(palavra))); j = rand() % (DEZ - strlen(palavra)); } for(int k =0; k < strlen(palavra); k++) { matriz[i][j] = palavra[k]; i--; j++; } } char* inverte_palavra(char palavra[10]){ char *palavra_invertida = malloc(10*sizeof(char)); int i; int f = 0; for (i = (strlen(palavra)-1); i>=0; i--){ palavra_invertida[f] = palavra[i]; f++; } return palavra_invertida; } int main() { srand(time(NULL)); inicializa_matriz(); char palavra1[10] = "raquel"; char *palavra1_invertida = inverte_palavra(palavra1); coloca_palavra_diagonal_decrescente(palavra1); coloca_palavra_diagonal_crescente(palavra1_invertida); preenche_matriz_com_letras(); imprime_caca_palavras(); return 0; }
JavaScript
UTF-8
1,152
3.5625
4
[]
no_license
var words; function preload() { Go = loadStrings("words.txt") } function setup(){ console.log(Go); background(250); var ind= floor(random(Go.length)); text(Go[ind],10,10,80,80) createCanvas(windowWidth, windowHeight); noStroke(); // set up text size on floor textSize(64); // fill style for "loading" text fill(100); text("Go", 600,100); } /* // You could also use the draw function to make the words re-render continuously function draw(){ renderWords(); }*/ function mousePressed(){ renderWords(); } function getWords(){ console.log(json); // for debugging, to view the full json result words = json; renderWords(); } function renderWords(){ background(0); // don't start drawing until there are words in the array if (Go.length > 0){ console.log('got results'); // resilts is an array of strings var y = 0; for (var i=0; i<Go.length; i++){ fill(random(0,85), random(85,170), random(100,255), random(80,100)); // the actual word is stored in the ngram property of the word object text(Go[i],random(width), y);//random(height)); y += 30; } } }
Java
UTF-8
3,555
2.03125
2
[]
no_license
package com.wetrack.ikongtiao.repo.impl.fixer; import com.wetrack.base.dao.api.CommonDao; import com.wetrack.base.page.BaseCondition; import com.wetrack.ikongtiao.domain.Fixer; import com.wetrack.ikongtiao.domain.Sequence; import com.wetrack.ikongtiao.param.FixerQueryForm; import com.wetrack.ikongtiao.repo.api.fixer.FixerRepo; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * Created by zhanghong on 15/12/30. */ @Service public class FixerRepoImpl implements FixerRepo { @Resource CommonDao commonDao; @Override public Fixer save(Fixer fixer) throws Exception { if(fixer.getId() == null) { Long id = commonDao.mapper(Sequence.class).sql("getNextVal").session().selectOne(Fixer.FIXER_SEQUENCE); fixer.setId(id.intValue()); } if(1 == commonDao.mapper(Fixer.class).sql("insertSelective").session().insert(fixer)){ return fixer; }else{ throw new Exception("没有保存成功"); } } @Override public int update(Fixer fixer) throws Exception { return commonDao.mapper(Fixer.class).sql("updateByPrimaryKeySelective").session().update(fixer); } @Override public int countFixerByQueryParam(FixerQueryForm form) throws Exception { if(form.getPhone() != null){ //加上sql like查询通配符 form.setPhone("%" + form.getPhone() + "%"); } if(form.getName() != null){ //加上sql like查询通配符 form.setName("%" + form.getName() + "%"); } if(form.getAddress() != null){ //加上sql like查询通配符 form.setAddress("%" + form.getAddress() + "%"); } BaseCondition baseCondition = commonDao.mapper(Fixer.class).sql("countByQueryParam").session() .selectOne(form); Integer count = baseCondition == null ? 0 : baseCondition.getTotalSize(); return count == null ? 0 : count; } @Override public List<Fixer> listFixerByQueryParam(FixerQueryForm form) throws Exception { if(form.getPhone() != null){ //加上sql like查询通配符 form.setPhone("%" + form.getPhone() + "%"); } if(form.getName() != null){ //加上sql like查询通配符 form.setName("%" + form.getName() + "%"); } if(form.getAddress() != null){ //加上sql like查询通配符 form.setAddress("%" + form.getAddress() + "%"); } return commonDao.mapper(Fixer.class).sql("listByQueryParam").session().selectList(form); } @Override public int lDelete(Integer id) throws Exception { Fixer fixer = new Fixer(); fixer.setId(id); fixer.setDeleted(true); return commonDao.mapper(Fixer.class).sql("updateByPrimaryKeySelective").session().update(fixer); } @Override public int delete(Integer id) throws Exception { return 0; } @Override public Fixer getFixerById(Integer fixId) { return commonDao.mapper(Fixer.class).sql("selectByPrimaryKey").session().selectOne(fixId); } @Override public Fixer getFixerByPhone(String phone) { return commonDao.mapper(Fixer.class).sql("selectByPhone").session().selectOne(phone); } @Override public List<Fixer> listFixerOfIds(List<Integer> ids) { return commonDao.mapper(Fixer.class).sql("selectInIds").session().selectList(ids); } }
Java
UTF-8
747
1.976563
2
[]
no_license
package com.oracle.udai.product.domain.mapper; import com.oracle.udai.api.vo.SkuVO; import com.oracle.udai.product.domain.dto.Sku; import java.util.List; public interface SkuMapper { int deleteByPrimaryKey(Integer id); int insert(Sku record); int insertSelective(Sku record); SkuVO selectByPrimaryKey(Integer id); List<Sku> selectSkuByCategoryId(Integer categoryId); /** * @param spuId * @return * @description 根据产品id查询商品 */ List<Sku> selectBySpuId(Integer spuId); /** * @param * @return * @description 查询所有商品 */ List<Sku> selectAllList(); int updateByPrimaryKeySelective(Sku record); int updateByPrimaryKey(Sku record); }