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
C#
UTF-8
1,100
3
3
[]
no_license
public class Sender { public Sender() { Messenger.Default.Register<NotificationMessage>(this, message => { if ((Type)message.Target == typeof(Sender)) GotResponse(message.Notification); }); } public void SendRequest(string request) { Console.WriteLine("sending:{0}", request); Messenger.Default.Send( new NotificationMessage(this, typeof(Receiver), request)); } private void GotResponse(string response) { Console.WriteLine("received:{0}", response); if (response.Equals("ok")) return; Exception exception = JsonConvert.DeserializeObject<Exception>(response); Console.WriteLine("exception:{0}", exception); try { throw exception; } catch (Exception e) { Console.WriteLine("Indeed, it was {0}", e); } } }
PHP
UTF-8
1,423
2.8125
3
[ "Apache-2.0" ]
permissive
<?php namespace duncan3dc\LaravelTests; use duncan3dc\Laravel\ConditionHandler; use PHPUnit\Framework\TestCase; class ConditionHandlerTest extends TestCase { /** @var ConditionHandler */ private $handler; public function setUp(): void { $this->handler = new ConditionHandler(); } public function testAdd1(): void { $result = $this->handler->add("test", "trim"); $this->assertSame($this->handler, $result); } public function testAdd2(): void { $this->handler->add("test", "trim"); $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage("A conditional by this name already exists: @test"); $this->handler->add("test", "trim"); } public function testCheck1(): void { $this->handler->add("test", "trim"); $result = $this->handler->check("test", " ok "); $this->assertSame("ok", $result); } public function testCheck2(): void { $this->handler->add("test", function () { return true; }); $result = $this->handler->check("test"); $this->assertSame(true, $result); } public function testCheck3(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage("Unknown conditional: @test"); $this->handler->check("test"); } }
Java
UTF-8
414
1.820313
2
[ "MIT" ]
permissive
package com.primeradiants.oniri.novent.dto; import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * Simple bean representing a list of novents * @author Shanira * @since 0.1.0 */ @AllArgsConstructor @NoArgsConstructor @Getter @Setter public class ReaderNoventListGetOutput { private List<ReaderNoventGetOutput> novents; }
C#
UTF-8
3,021
2.609375
3
[ "MIT" ]
permissive
namespace Molten.Graphics { public class ShaderCompilerContext { /// <summary> /// HLSL shader objects stored by entry-point name /// </summary> public Dictionary<string, ShaderCodeResult> Shaders { get; } internal ShaderCompileResult Result { get; } internal IReadOnlyList<ShaderCompilerMessage> Messages => _messages; public bool HasErrors { get; private set; } public ShaderSource Source { get; set; } public ShaderCompileFlags Flags { get; set; } public ShaderType Type { get; set; } public ShaderCompiler Compiler { get; } public string EntryPoint { get; internal set; } List<ShaderCompilerMessage> _messages; Dictionary<Type, Dictionary<string, object>> _resources; public ShaderCompilerContext(ShaderCompiler compiler) { _messages = new List<ShaderCompilerMessage>(); _resources = new Dictionary<Type, Dictionary<string, object>>(); Shaders = new Dictionary<string, ShaderCodeResult>(); Result = new ShaderCompileResult(); Compiler = compiler; } public void AddResource<T>(string name, T resource) where T : EngineObject { if (!_resources.TryGetValue(typeof(T), out Dictionary<string, object> lookup)) { lookup = new Dictionary<string, object>(); _resources.Add(typeof(T), lookup); } lookup.Add(name, resource); } public bool TryGetResource<T>(string name, out T resource) where T : EngineObject { if (!_resources.TryGetValue(typeof(T), out Dictionary<string, object> lookup)) { lookup = new Dictionary<string, object>(); _resources.Add(typeof(T), lookup); } object result = default(T); if(lookup.TryGetValue(name, out result)) { resource = result as T; return true; } resource = default(T); return false; } public void AddMessage(string text, ShaderCompilerMessage.Kind type = ShaderCompilerMessage.Kind.Message) { if (string.IsNullOrWhiteSpace(text)) return; _messages.Add(new ShaderCompilerMessage() { Text = $"[{type}] {text}", MessageType = type, }); if (type == ShaderCompilerMessage.Kind.Error) HasErrors = true; } public void AddError(string text) { AddMessage(text, ShaderCompilerMessage.Kind.Error); } public void AddDebug(string text) { AddMessage(text, ShaderCompilerMessage.Kind.Debug); } public void AddWarning(string text) { AddMessage(text, ShaderCompilerMessage.Kind.Warning); } } }
C#
UTF-8
612
2.578125
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WordpressAutomation.Util { public class FileLogger { public static string logPath = @"C:\iCode\Selenium\Wordpress\WordpressAutomation\WordpressAutomation\Log"; public static string fileName = "log.txt"; public static void WriteToLog(string message) { var fileWriter = File.AppendText(logPath+@"\"+fileName); fileWriter.WriteLine(message); fileWriter.Close(); } } }
JavaScript
UTF-8
1,767
2.6875
3
[]
no_license
import React, {Component, useState, useEffect} from 'react' // export default function PhotoInfo({photo}) { class PhotoInfo extends Component { state = { id: 0, albumId: '', title: '', thumbnailUrl: '' } // let obj = {} // const obj = { // url : '', // id : 5 // } // const [id, setId] = useState(4); // componentDidMount() { return fetch(`https://jsonplaceholder.typicode.com/photos/${this.props.photo}`) .then((response) => response.json()) // .then(response => console.log(response.id)) .then(response => this.setState({ id: response.id, albumId: response.albumId, title: response.title, thumbnailUrl: response.thumbnailUrl })) } // console.log(id) // useEffect(() => { // console.log(id) // }); // return <div>Photo Info here {photo} Obj id: {b.id} </div> // obj.id = 93 // return <div>Photo Info here {photo} ID: {obj.id}</div> render() { return <> <div className="container"> <strong>ID: </strong> {this.state.id} <strong> Album ID: </strong> {this.state.albumId} <strong> Title: </strong> {this.state.title} </div> <div className="card m-1 w-25"> <img src={this.state.thumbnailUrl} alt={this.state.title} className="card-img-top"/> </div> <button className="btn btn-primary" onClick={() => this.props.updateCounter(this.state)} >Buy </button> </> } } export default PhotoInfo
Java
UTF-8
1,932
2.015625
2
[]
no_license
/******************************************************************************* * Copyright (c) 2016, Huawei Technologies Co., Ltd. * * 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 org.openo.crossdomain.commonsvc.decomposer.module; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * abstract base Module, provider module start/stop service * * @since crossdomain 0.5 */ public abstract class AbsBaseModule { /** * logger */ private static final Logger logger = LoggerFactory .getLogger(AbsBaseModule.class); /** * service start action * * @since crossdomain 0.5 */ public final void start() { try { doStart(); init(); } catch (Exception e) { logger.error("module start error", e); } } /** * service stop action * * @since crossdomain 0.5 */ public final void stop() { try { doStop(); destroy(); } catch (Exception e) { logger.error("module start stop", e); } } /** * do start action * * @since crossdomain 0.5 */ protected void doStart() { } /** * do stop action * * @since crossdomain 0.5 */ protected void doStop() { } /** * initialize method * * @since crossdomain 0.5 */ protected abstract void init(); /** * destroy method * * @since crossdomain 0.5 */ protected abstract void destroy(); }
Python
UTF-8
1,654
3.609375
4
[]
no_license
from collections import defaultdict import sys #Class to represent a graph class Graph: def __init__(self,vertices): self.V= vertices self.graph = [] def addEdge(self, u, v, w): self.graph.append([u,v,w]) def find(self, parent, i): if parent[i] == i: return i return self.find(parent, parent[i]) def union(self, parent, rank, x, y): xroot = self.find(parent, x) yroot = self.find(parent, y) if rank[xroot] < rank[yroot]: parent[xroot] = yroot elif rank[xroot] > rank[yroot]: parent[yroot] = xroot else : parent[yroot] = xroot rank[xroot] += 1 def KruskalMST(self): result =[] i = 0 e = 0 self.graph = sorted(self.graph,key=lambda item: item[2]) parent = [] ; rank = [] for node in range(self.V): parent.append(node) rank.append(0) while e < self.V -1 : u,v,w = self.graph[i] i = i + 1 x = self.find(parent, u) y = self.find(parent ,v) if x != y: e = e + 1 result.append([u,v,w]) self.union(parent, rank, x, y) print ("Following are the edges in the constructed MST") for u,v,weight in result: print(u, v, weight) alist=[] for u,v, weight in result: alist.append(weight) print ("The minimum weight = ",sum(alist)) g = Graph(2) g.addEdge(2, 1, 67) g.addEdge(3, 1, 46) g.addEdge(0, 3, 5) g.addEdge(1, 3, 15) g.addEdge(2, 3, 4) g.KruskalMST()
PHP
UTF-8
2,854
2.859375
3
[]
no_license
<?php /** * FileMaker PHP API. * * @package FileMaker * * Copyright � 2005-2006, FileMaker, Inc.� All rights reserved. * NOTE:� Use of this source code is subject to the terms of the FileMaker * Software License which accompanies the code.� Your use of this source code * signifies your agreement to such license terms and conditions.� Except as * expressly granted in the Software License, no other copyright, patent, or * other intellectual property license or right is granted, either expressly or * by implication, by FileMaker. */ /** * Include parent and delegate classesa. */ require_once dirname(__FILE__) . '/../Command.php'; require_once dirname(__FILE__) . '/../Implementation/Command/AddImpl.php'; /** * Add a new record. * * @package FileMaker */ class FileMaker_Command_Add extends FileMaker_Command { /** * Implementation * * @var FileMaker_Command_Add_Implementation * @access private */ var $_impl; /** * Add command constructor. * * @ignore * @param FileMaker_Implementation $fm The FileMaker_Implementation object the command was created by. * @param string $layout The layout to add to. * @param array $values A hash of fieldname => value pairs. Repetions can be set * by making the value for a field a numerically indexed array, with the numeric keys * corresponding to the repetition number to set. */ function FileMaker_Command_Add($fm, $layout, $values = array()) { $this->_impl =& new FileMaker_Command_Add_Implementation($fm, $layout, $values); } /** * Set the new value for a field. * * @param string $field The field to set. * @param string $value The value for the field. * @param integer $repetition The repetition number to set, * defaults to the first repetition. */ function setField($field, $value, $repetition = 0) { return $this->_impl->setField($field, $value, $repetition); } /** * Set the new value for a date, time, or timestamp field from a * unix timestamp value. If the field is not a date or time field, * then an error is returned. Otherwise returns true. * * If we haven't already loaded layout data for the target of this * command, calling this method will cause it to be loaded so that * the type of the field can be checked. * * @param string $field The field to set. * @param string $timestamp The timestamp value. * @param integer $repetition The repetition number to set, * defaults to the first repetition. */ function setFieldFromTimestamp($field, $timestamp, $repetition = 0) { return $this->_impl->setFieldFromTimestamp($field, $timestamp, $repetition); } }
PHP
UTF-8
3,189
2.53125
3
[]
no_license
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Login</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <style> .redborder { border-color:red !important; } </style>; </head> <body> <?php if(isset($_SESSION['u_name'])){ header("Location:http://localhost:8081/Todolist/project1/list/list.php"); exit(); } session_start(); include "create_con.php"; $error=array("username"=>null,"password"=>null); if(isset($_POST['login'])){ $loguser=mysqli_real_escape_string($conn,$_POST['username']); $logpass=mysqli_real_escape_string($conn,$_POST['psw']); if(empty($logpass)){ $error["password"]="fill the password "; } if(empty($loguser)){ $error["username"]="fill the username "; } else { $sql = "select * from users where username='" . $loguser . "'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) < 1) { $error["username"] = "incorrect username"; } else { if ($row = mysqli_fetch_assoc($result)) { $dehashpsw = password_verify($logpass, $row['password']); if ($dehashpsw == false) { $error["password"] = "incorrect password"; } elseif ($dehashpsw == true) { // Log in the user $_SESSION['u_name'] = $row['user_id']; header("Location:list/list.php"); } } } } } ?> <div class="container"> <br> <br> <div> <form action="index.php" method="post"> <div class="form-group"> <label for="username">Username:</label> <input type="text" class="form-control <?= isset($error["username"]) ? 'redborder' : '' ?>" name="username" id="username" placeholder="Enter username" > <span class="a"><?php echo $error["username"] ?></span> </div> <div class="form-group"> <label for="psw">Password:</label> <input type="password" class="form-control <?= isset($error["password"]) ? 'redborder' : '' ?>" " name="psw" id="psw" placeholder="Enter password"> <p><?php echo $error["password"] ?> </p> </div> <input type="submit" class="btn btn-primary" name="login" value="Log in"> <br> <br> <p> Not yet registered? <a href="registration.php">Register</a></p> </form> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html>
PHP
UTF-8
870
2.796875
3
[]
no_license
<?php /** * @file FrxHtmlDoc * Straight html document with no wrapping theme. * @author davidmetzler * */ class FrxHtmlDoc extends FrxDocument { public function render($r, $format, $options = array()) { $css = $this->loadCSSFiles($format); $output = '<html><head>'; $output .= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>'; $title = $r->title; // Add inline styles if ($css || isset($r->rpt_xml->head->style)) { $output .= '<style type="text/css">'; $output .= $css; if (isset($r->rpt_xml->head->style)) { $sheet = (string)$r->rpt_xml->head->style; $output .= $sheet; } $output .= '</style>'; } $output .= '<title>' . $r->title . '</title></head><body class="forena-report"><h1>' . $r->title . '</h1>' . $r->html . '</body></html>'; return $output; } }
C
UTF-8
800
3.375
3
[]
no_license
int is_space(char c) { if (c == ' ' || (c >= '\t' && c <= '\n')) return (1); return (0); } int is_valid(char c, int base) { char hexL[16] = "0123456789abcdef"; char hexU[16] = "0123456789ABCDEF"; while (base-- > 0) { if (c == hexL[base] || c == hexU[base]) return (1); } return (0); } int convert_num(char c) { if (c >= '0' && c <= '9') return (c - '0'); else if (c >= 'a' && c <= 'f') return (c - 'a' + 10); else if (c >= 'A' && c <= 'F') return (c - 'A' + 10); return (0); } int ft_atoi_base(const char *str, int str_base) { int num = 0; int neg = 1; while (is_space(*str)) str++; if (*str == '-') neg = -1; if (*str == '-' || *str == '+') str++; while (is_valid(*str, str_base)) num = num * str_base + convert_num(*str++); return (num * neg); }
PHP
UTF-8
766
2.578125
3
[]
no_license
<?php /** * 输出url * * @param array $params 参数 * @param Smarty $template 模板实例 * @return string 地址 */ function smarty_function_url ($params, $template) { $host = Url::getInstance()->getHost($params['host']); $proxy = isset($params['proxy']) ? trim($params['proxy']) : PROXY_DEFAULT; $path = isset($params['path']) ? trim($params['path']) : '/'; $path = 0 === strpos($path, '/') ? $path : '/' . $path; $query = empty($params['query']) ? '' : http_build_query($params['query']); $url = $proxy . '://' . $host . $path; $url .= empty($query) ? '' : '?' . $query; return $url; }
Markdown
UTF-8
38,951
2.75
3
[]
no_license
# mysql命令总结 本文档在CentOS 6.9操作系统下,基于yum安装的mysql5.1版本完成。 ## 数据库操作 ### 指定字符集创建数据库 create database python default character set utf8 collate utf8_general_ci; ``` mysql> create database python default character set utf8 collate utf8_general_ci; Query OK, 1 row affected (0.00 sec) ``` **说明:** 1. python是我创建的数据库名称,下文会多次使用或出现。 2. 使用utf8字符集。 3. 校验规则使用utf8_general_ci。 ### 查看所有数据库 show databases; ``` mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | python | +--------------------+ 3 rows in set (0.00 sec) ``` ### 查看建库语句 show create database python; ``` mysql> show create database python; +----------+-----------------------------------------------------------------+ | Database | Create Database | +----------+-----------------------------------------------------------------+ | python | CREATE DATABASE `python` /*!40100 DEFAULT CHARACTER SET utf8 */ | +----------+-----------------------------------------------------------------+ 1 row in set (0.00 sec) ``` ### 删除数据库 drop database python; ## 用户与权限 ### 创建用户并授权 create user 'ygw'@'%' identified by '1234'; grant select,insert,update,delete,create on python.* to ygw; ``` mysql> create user 'ygw'@'%' identified by '1234'; Query OK, 0 rows affected (0.00 sec) mysql> grant select,insert,update,delete,create on python.* to ygw; Query OK, 0 rows affected (0.00 sec) ``` **说明:** 1. 字符串‘ygw’是账号名,%表示所有主机,字符串‘1234’是密码。 2. grant授权时使用“python.”表示python数据库,\*表示python数据库的所有表。 ### 刷新权限 flush privileges; ``` mysql> flush privileges; Query OK, 0 rows affected (0.00 sec) ``` ### 查看用户 select host,user from mysql.user; ``` mysql> select host,user from mysql.user; +-----------+------+ | host | user | +-----------+------+ | % | ygw | | 127.0.0.1 | root | | localhost | root | +-----------+------+ 3 rows in set (0.00 sec) ``` ### 查看用户权限 show grants for 'ygw'@'%'; ``` mysql> show grants for 'ygw'@'%'; +----------------------------------------------------------------------------------------------------+ | Grants for ygw@% | +----------------------------------------------------------------------------------------------------+ | GRANT USAGE ON *.* TO 'ygw'@'%' IDENTIFIED BY PASSWORD '*A4B6157319038724E3560894F7F932C8886EBFCF' | | GRANT SELECT, INSERT, UPDATE, DELETE, CREATE ON `python`.* TO 'ygw'@'%' | +----------------------------------------------------------------------------------------------------+ 2 rows in set (0.00 sec) ``` ### 取消insert权限 revoke insert on python.* from 'ygw'@'%'; ``` mysql> revoke insert on python.* from 'ygw'@'%'; Query OK, 0 rows affected (0.00 sec) mysql> show grants for 'ygw'@'%'; +----------------------------------------------------------------------------------------------------+ | Grants for ygw@% | +----------------------------------------------------------------------------------------------------+ | GRANT USAGE ON *.* TO 'ygw'@'%' IDENTIFIED BY PASSWORD '*A4B6157319038724E3560894F7F932C8886EBFCF' | | GRANT SELECT, UPDATE, DELETE, CREATE ON `python`.* TO 'ygw'@'%' | +----------------------------------------------------------------------------------------------------+ 2 rows in set (0.00 sec) ``` ### 取消所有权限 revoke all on python.* from 'ygw'@'%'; ``` mysql> revoke all on python.* from 'ygw'@'%'; Query OK, 0 rows affected (0.00 sec) mysql> show grants for 'ygw'@'%'; +----------------------------------------------------------------------------------------------------+ | Grants for ygw@% | +----------------------------------------------------------------------------------------------------+ | GRANT USAGE ON *.* TO 'ygw'@'%' IDENTIFIED BY PASSWORD '*A4B6157319038724E3560894F7F932C8886EBFCF' | +----------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) ``` ### 授权与创建用户一条命令搞定 grant all privileges on python.* TO 'ygw'@'127.0.0.1'; grant all privileges on python.* TO 'ygw'@'192.168.1.1'; grant all privileges on python.* TO 'ygw'@'192.168.1.2'; ``` mysql> grant all privileges on python.* TO 'ygw'@'127.0.0.1'; Query OK, 0 rows affected (0.00 sec) mysql> grant all privileges on python.* TO 'ygw'@'192.168.1.1'; Query OK, 0 rows affected (0.00 sec) mysql> grant all privileges on python.* TO 'ygw'@'192.168.1.2'; Query OK, 0 rows affected (0.00 sec) mysql> select host,user from mysql.user; +-------------+------+ | host | user | +-------------+------+ | % | ygw | | 127.0.0.1 | root | | 127.0.0.1 | ygw | | 192.168.1.1 | ygw | | 192.168.1.2 | ygw | | localhost | root | +-------------+------+ 6 rows in set (0.00 sec) ``` **说明:** 1. grant授权时的all表示所有权限。 ### 删除用户 delete from mysql.user where user='ygw' and host='127.0.0.1'; ``` mysql> delete from mysql.user where user='ygw' and host='127.0.0.1'; Query OK, 1 row affected (0.00 sec) mysql> select host,user from mysql.user; +-------------+------+ | host | user | +-------------+------+ | % | ygw | | 127.0.0.1 | root | | 192.168.1.1 | ygw | | 192.168.1.2 | ygw | | localhost | root | +-------------+------+ 5 rows in set (0.00 sec) ``` use mysql; drop user 'ygw'@'192.168.1.1'; ``` mysql> use mysql; Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed mysql> drop user 'ygw'@'192.168.1.1'; Query OK, 0 rows affected (0.00 sec) mysql> select host,user from mysql.user; +-------------+------+ | host | user | +-------------+------+ | % | ygw | | 127.0.0.1 | root | | 192.168.1.2 | ygw | | localhost | root | +-------------+------+ 4 rows in set (0.00 sec) ``` ### 修改密码 ``` mysql> update mysql.user set password=PASSWORD("1234")where user="root" and host='127.0.0.1'; Query OK, 0 rows affected (0.00 sec) Rows matched: 1 Changed: 0 Warnings: 0 mysql> flush privileges; Query OK, 0 rows affected (0.00 sec) ``` ## 表操作 ### 建表 | 列名 | 类型 | 长度 | 备注 | 是否可空 | 主键 | | --- | --- | --- | --- | --- | --- | | id | int | 12 | 用户id | 否 | 是 | | name | varchar | 64 | 用户名 | 否 | 否 | | passwd | varchar | 64 | 密码 | 否 | 否 | | job | varchar | 64 | 职务 | 是 | 否 | | age | int | 11 | 年龄 | 是 | 否 | | status | int | 11 | 账号状态,1为禁用,0为启用 | 否 | 否 | | flag | int | 11 | 连续登录的失败次数 | 是 | 否 | CREATE TABLE `users` ( `id` int(12) NOT NULL AUTO_INCREMENT COMMENT '用户id', `name` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '用户名', `passwd` varchar(64) NOT NULL COMMENT '密码', `job` varchar(64) NULL COMMENT '职务', `age` int(11) NULL COMMENT '年龄', `status` int(11) NOT NULL COMMENT '账号状态,1为禁用,0为启用', `flag` int(11) NULL DEFAULT 0 COMMENT '连续登录的失败次数', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci; ``` mysql> CREATE TABLE `users` ( -> `id` int(12) NOT NULL AUTO_INCREMENT COMMENT '用户id', -> `name` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '用户名', -> `passwd` varchar(64) NOT NULL COMMENT '密码', -> `job` varchar(64) NULL COMMENT '职务', -> `age` int(11) NULL COMMENT '年龄', -> `status` int(11) NOT NULL COMMENT '账号状态,1为禁用,0为启用', -> `flag` int(11) NULL DEFAULT 0 COMMENT '连续登录的失败次数', -> PRIMARY KEY (`id`) -> ) ENGINE=InnoDB -> DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci; Query OK, 0 rows affected (0.01 sec) ``` **说明:** 1. id字段递增,主键。 2. COMMENT后面的字符串是注释内容 3. DEFAULT用于设置该字段的默认值。 4. 表名users后面会多次使用、出现。 ### 查看建表语句 show CREATE TABLE users; ``` mysql> show CREATE TABLE `users`; +-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | users | CREATE TABLE `users` ( `id` int(12) NOT NULL AUTO_INCREMENT COMMENT '用户id', `name` varchar(64) NOT NULL DEFAULT '' COMMENT '用户名', `passwd` varchar(64) NOT NULL COMMENT '密码', `job` varchar(64) DEFAULT NULL COMMENT '职务', `age` int(11) DEFAULT NULL COMMENT '年龄', `status` int(11) NOT NULL COMMENT '账号状态,1为禁用,0为启用', `flag` int(11) DEFAULT '0' COMMENT '连续登录的失败次数', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | +-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) ``` ### 查看表的所有字段(为了查看注释) show full fields from users; ``` mysql> show full fields from users; +--------+-------------+-----------------+------+-----+---------+----------------+---------------------------------+---------------------------------------------------+ | Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment | +--------+-------------+-----------------+------+-----+---------+----------------+---------------------------------+---------------------------------------------------+ | id | int(12) | NULL | NO | PRI | NULL | auto_increment | select,insert,update,references | 用户id | | name | varchar(64) | utf8_general_ci | NO | | | | select,insert,update,references | 用户名 | | passwd | varchar(64) | utf8_general_ci | NO | | NULL | | select,insert,update,references | 密码 | | gid | int(11) | NULL | NO | | 1 | | select,insert,update,references | 用户组ID,0是管理组,1是普通用户组 | | job | varchar(64) | utf8_general_ci | YES | | NULL | | select,insert,update,references | 职务 | | age | int(11) | NULL | YES | | NULL | | select,insert,update,references | 年龄 | | status | int(11) | NULL | NO | | NULL | | select,insert,update,references | 账号状态,1为禁用,0为启用 | | flag | int(11) | NULL | YES | | 0 | | select,insert,update,references | 连续登录的失败次数 | +--------+-------------+-----------------+------+-----+---------+----------------+---------------------------------+---------------------------------------------------+ 8 rows in set (0.00 sec) ``` ### 查看所有表名 show tables; ``` mysql> show tables; +------------------+ | Tables_in_python | +------------------+ | users | +------------------+ 1 row in set (0.00 sec) ``` ### 查看表结构 desc users; ``` mysql> desc users; +--------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+----------------+ | id | int(12) | NO | PRI | NULL | auto_increment | | name | varchar(64) | NO | | | | | passwd | varchar(64) | NO | | NULL | | | job | varchar(64) | YES | | NULL | | | age | int(11) | YES | | NULL | | | status | int(11) | NO | | NULL | | | flag | int(11) | YES | | 0 | | +--------+-------------+------+-----+---------+----------------+ 7 rows in set (0.00 sec) ``` ### 修改表结构(增加字段) alter table users add birth date not null default '0000-00-00'; alter table users add gid int not null default 1 comment '用户组ID,0是管理组,1是普通用户组' after passwd; ``` mysql> alter table users add birth date not null default '0000-00-00'; Query OK, 1 row affected (0.02 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql> desc users; +--------+-------------+------+-----+------------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+------------+----------------+ | id | int(12) | NO | PRI | NULL | auto_increment | | name | varchar(64) | NO | | | | | passwd | varchar(64) | NO | | NULL | | | job | varchar(64) | YES | | NULL | | | age | int(11) | YES | | NULL | | | status | int(11) | NO | | NULL | | | flag | int(11) | YES | | 0 | | | birth | date | NO | | 0000-00-00 | | +--------+-------------+------+-----+------------+----------------+ 8 rows in set (0.00 sec) mysql> alter table users add gid int not null default 1 comment '用户组ID,0是管理组,1是普通用户组' after passwd; Query OK, 1 row affected (0.01 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql> desc users; +--------+-------------+------+-----+------------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+------------+----------------+ | id | int(12) | NO | PRI | NULL | auto_increment | | name | varchar(64) | NO | | | | | passwd | varchar(64) | NO | | NULL | | | gid | int(11) | NO | | 1 | | | job | varchar(64) | YES | | NULL | | | age | int(11) | YES | | NULL | | | status | int(11) | NO | | NULL | | | flag | int(11) | YES | | 0 | | | birth | date | NO | | 0000-00-00 | | +--------+-------------+------+-----+------------+----------------+ 9 rows in set (0.00 sec) ``` ### 修改表结构(修改字段) alter table users modify birth int not null default 1 comment '测试修改字段类型等信息'; alter table users change birth birthday int not null default 1 comment '测试修改字段名称'; ``` mysql> alter table users modify birth int not null default 1 comment '测试修改字段类型等信息'; Query OK, 1 row affected, 1 warning (0.01 sec) Records: 1 Duplicates: 0 Warnings: 1 mysql> desc users; +--------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+----------------+ | id | int(12) | NO | PRI | NULL | auto_increment | | name | varchar(64) | NO | | | | | passwd | varchar(64) | NO | | NULL | | | gid | int(11) | NO | | 1 | | | job | varchar(64) | YES | | NULL | | | age | int(11) | YES | | NULL | | | status | int(11) | NO | | NULL | | | flag | int(11) | YES | | 0 | | | birth | int(11) | NO | | 1 | | +--------+-------------+------+-----+---------+----------------+ 9 rows in set (0.00 sec) mysql> alter table users change birth birthday int not null default 1 comment '测试修改字段名称'; Query OK, 1 row affected (0.02 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql> desc users; +----------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+----------------+ | id | int(12) | NO | PRI | NULL | auto_increment | | name | varchar(64) | NO | | | | | passwd | varchar(64) | NO | | NULL | | | gid | int(11) | NO | | 1 | | | job | varchar(64) | YES | | NULL | | | age | int(11) | YES | | NULL | | | status | int(11) | NO | | NULL | | | flag | int(11) | YES | | 0 | | | birthday | int(11) | NO | | 1 | | +----------+-------------+------+-----+---------+----------------+ 9 rows in set (0.00 sec) ``` ### 修改表结构(删除字段) alter table users drop birthday; ``` mysql> alter table users drop birthday; Query OK, 1 row affected (0.01 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql> desc users; +--------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+----------------+ | id | int(12) | NO | PRI | NULL | auto_increment | | name | varchar(64) | NO | | | | | passwd | varchar(64) | NO | | NULL | | | gid | int(11) | NO | | 1 | | | job | varchar(64) | YES | | NULL | | | age | int(11) | YES | | NULL | | | status | int(11) | NO | | NULL | | | flag | int(11) | YES | | 0 | | +--------+-------------+------+-----+---------+----------------+ 8 rows in set (0.00 sec) ``` ### 插入数据 insert into users values(1,'yang','yangpwd','op','12',0,0); ``` mysql> insert into users values(1,'yang','yangpwd','op','12',0,0); Query OK, 1 row affected (0.00 sec) ``` ### 查看所有字段 select * from users; ``` mysql> select * from users; +----+------+---------+------+------+--------+------+ | id | name | passwd | job | age | status | flag | +----+------+---------+------+------+--------+------+ | 1 | yang | yangpwd | op | 12 | 0 | 0 | +----+------+---------+------+------+--------+------+ 1 row in set (0.00 sec) ``` ### 查看指定字段 select name from users; select name,job,age from users; select * from users where name='yang'; ``` mysql> select name from users; +------+ | name | +------+ | yang | +------+ 1 row in set (0.00 sec) mysql> select name,job,age from users; +-------+------+------+ | name | job | age | +-------+------+------+ | ygw1 | ops | 12 | | ygw10 | ops | 12 | | ygw01 | ops | 122 | | ygw02 | ops | 122 | | ygw04 | ops | 122 | | ygw | ops | 122 | | wd | wd | 12 | +-------+------+------+ 7 rows in set (0.00 sec) mysql> select * from users where name='yang'; +----+------+---------+------+------+--------+------+ | id | name | passwd | job | age | status | flag | +----+------+---------+------+------+--------+------+ | 1 | yang | yangpwd | op | 12 | 0 | 0 | +----+------+---------+------+------+--------+------+ 1 row in set (0.00 sec) ``` ### 模糊查找(后补) ``` mysql> select * from user; +----+----------+----------+------+------+-----+---------------+------------+ | id | username | password | job | age | tfa | base32_encode | tfa_status | +----+----------+----------+------+------+-----+---------------+------------+ | 1 | nick | 123 | cxo | 25 | 0 | NULL | 0 | | 2 | nick1 | 123 | cxo | 25 | 0 | NULL | 0 | | 3 | nick2 | 123 | cxo | 25 | 0 | NULL | 0 | | 4 | nick3 | 123 | cxo | 25 | 0 | NULL | 0 | | 5 | nick4 | 123 | cxo | 25 | 0 | NULL | 0 | | 6 | nick11 | 123 | cxo | 22 | 0 | NULL | 0 | | 7 | ygw | ygw | ops | 22 | 0 | NULL | 0 | | 9 | y | y | y | 22 | 0 | NULL | 0 | | 10 | y | y | y | 22 | 0 | NULL | 0 | | 12 | 123 | 123 | 123 | 123 | 0 | NULL | 0 | | 13 | yang | 1234 | op | 12 | 0 | NULL | 1 | +----+----------+----------+------+------+-----+---------------+------------+ 11 rows in set (0.00 sec) mysql> select * from user where username like 'nick%'; +----+----------+----------+------+------+-----+---------------+------------+ | id | username | password | job | age | tfa | base32_encode | tfa_status | +----+----------+----------+------+------+-----+---------------+------------+ | 1 | nick | 123 | cxo | 25 | 0 | NULL | 0 | | 2 | nick1 | 123 | cxo | 25 | 0 | NULL | 0 | | 3 | nick2 | 123 | cxo | 25 | 0 | NULL | 0 | | 4 | nick3 | 123 | cxo | 25 | 0 | NULL | 0 | | 5 | nick4 | 123 | cxo | 25 | 0 | NULL | 0 | | 6 | nick11 | 123 | cxo | 22 | 0 | NULL | 0 | +----+----------+----------+------+------+-----+---------------+------------+ 6 rows in set (0.00 sec) mysql> select * from user where username like 'nick_'; +----+----------+----------+------+------+-----+---------------+------------+ | id | username | password | job | age | tfa | base32_encode | tfa_status | +----+----------+----------+------+------+-----+---------------+------------+ | 2 | nick1 | 123 | cxo | 25 | 0 | NULL | 0 | | 3 | nick2 | 123 | cxo | 25 | 0 | NULL | 0 | | 4 | nick3 | 123 | cxo | 25 | 0 | NULL | 0 | | 5 | nick4 | 123 | cxo | 25 | 0 | NULL | 0 | +----+----------+----------+------+------+-----+---------------+------------+ 4 rows in set (0.00 sec) ``` ### 限制返回的查找结果数量(后补) ``` mysql> select * from user where username like 'nick%'; +----+----------+----------+------+------+-----+---------------+------------+ | id | username | password | job | age | tfa | base32_encode | tfa_status | +----+----------+----------+------+------+-----+---------------+------------+ | 1 | nick | 123 | cxo | 25 | 0 | NULL | 0 | | 2 | nick1 | 123 | cxo | 25 | 0 | NULL | 0 | | 3 | nick2 | 123 | cxo | 25 | 0 | NULL | 0 | | 4 | nick3 | 123 | cxo | 25 | 0 | NULL | 0 | | 5 | nick4 | 123 | cxo | 25 | 0 | NULL | 0 | | 6 | nick11 | 123 | cxo | 22 | 0 | NULL | 0 | +----+----------+----------+------+------+-----+---------------+------------+ 6 rows in set (0.00 sec) mysql> select * from user where username like 'nick%' limit 1; +----+----------+----------+------+------+-----+---------------+------------+ | id | username | password | job | age | tfa | base32_encode | tfa_status | +----+----------+----------+------+------+-----+---------------+------------+ | 1 | nick | 123 | cxo | 25 | 0 | NULL | 0 | +----+----------+----------+------+------+-----+---------------+------------+ 1 row in set (0.00 sec) ``` ### 插入部分值 insert into users(id,name,passwd,job,age,status) values(2,'ygw','ygw','ops',12,1); insert into users(name,passwd,job,age,status) values('ygw','ygw','ops',12,1); ``` mysql> insert into users(id,name,passwd,job,age,status) values(2,'ygw','ygw','ops',12,1); Query OK, 1 row affected (0.00 sec) mysql> select * from users; +----+------+---------+-----+------+------+--------+------+ | id | name | passwd | gid | job | age | status | flag | +----+------+---------+-----+------+------+--------+------+ | 1 | yang | yangpwd | 1 | op | 12 | 0 | 0 | | 2 | ygw | ygw | 1 | ops | 12 | 1 | 0 | +----+------+---------+-----+------+------+--------+------+ 2 rows in set (0.00 sec) mysql> insert into users(name,passwd,job,age,status) values('ygw','ygw','ops',12,1); Query OK, 1 row affected (0.00 sec) mysql> select * from users; +----+------+---------+-----+------+------+--------+------+ | id | name | passwd | gid | job | age | status | flag | +----+------+---------+-----+------+------+--------+------+ | 1 | yang | yangpwd | 1 | op | 12 | 0 | 0 | | 2 | ygw | ygw | 1 | ops | 12 | 1 | 0 | | 3 | ygw | ygw | 1 | ops | 12 | 1 | 0 | +----+------+---------+-----+------+------+--------+------+ 3 rows in set (0.00 sec) ``` ### 修改数据(后补) update users SET flag=0 where name='ygw05'; ``` mysql> select flag from users where name='ygw05'; +------+ | flag | +------+ | 7 | +------+ 1 row in set (0.00 sec) mysql> update users SET flag=0 where name='ygw05'; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select flag from users where name='ygw05'; +------+ | flag | +------+ | 0 | +------+ 1 row in set (0.00 sec) ``` ### 删除数据 delete from users where name='ygw'; ``` mysql> delete from users where name='ygw'; Query OK, 2 rows affected (0.00 sec) mysql> select * from users; +----+------+---------+-----+------+------+--------+------+ | id | name | passwd | gid | job | age | status | flag | +----+------+---------+-----+------+------+--------+------+ | 1 | yang | yangpwd | 1 | op | 12 | 0 | 0 | +----+------+---------+-----+------+------+--------+------+ 1 row in set (0.00 sec) ``` ### 清空表数据 truncate table users; ``` mysql> select * from users; +----+------+---------+-----+------+------+--------+------+ | id | name | passwd | gid | job | age | status | flag | +----+------+---------+-----+------+------+--------+------+ | 1 | yang | yangpwd | 1 | op | 12 | 0 | 0 | +----+------+---------+-----+------+------+--------+------+ 1 row in set (0.00 sec) mysql> truncate table users; Query OK, 0 rows affected (0.00 sec) mysql> select * from users; Empty set (0.00 sec) ``` ### 删除表 drop table my_users; ``` mysql> show tables; +------------------+ | Tables_in_python | +------------------+ | my_users | | users | +------------------+ 2 rows in set (0.00 sec) mysql> drop table my_users; Query OK, 0 rows affected (0.00 sec) mysql> show tables; +------------------+ | Tables_in_python | +------------------+ | users | +------------------+ 1 row in set (0.00 sec) ``` ## 索引 ### 创建唯一索引(专业术语是啥?) 避免字段值重复 ALTER TABLE `users` ADD UNIQUE KEY `userNmae`(`name`); ``` mysql> ALTER TABLE `users` ADD UNIQUE KEY `userNmae`(`name`); Query OK, 1 row affected (0.01 sec) Records: 1 Duplicates: 0 Warnings: 0 ``` ### 查看索引 show index from users; show keys from users; ``` mysql> show index from users; +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | users | 0 | PRIMARY | 1 | id | A | 1 | NULL | NULL | | BTREE | | | users | 0 | userNmae | 1 | name | A | 1 | NULL | NULL | | BTREE | | +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ 2 rows in set (0.00 sec) mysql> show keys from users; +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | users | 0 | PRIMARY | 1 | id | A | 1 | NULL | NULL | | BTREE | | | users | 0 | userNmae | 1 | name | A | 1 | NULL | NULL | | BTREE | | +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ 2 rows in set (0.00 sec) ``` ### 删除索引 drop index userNmae on users; ``` mysql> drop index userNmae on users; Query OK, 1 row affected (0.01 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql> show keys from users; +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | users | 0 | PRIMARY | 1 | id | A | 1 | NULL | NULL | | BTREE | | +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ 1 row in set (0.00 sec) ``` ### 删除主键索引 ALTER TABLE my_users DROP PRIMARY KEY; ``` mysql> DROP TABLE IF EXISTS my_users; Query OK, 0 rows affected (0.00 sec) mysql> CREATE TABLE `my_users` ( -> `name` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '用户名', -> `passwd` varchar(64) NOT NULL COMMENT '密码', -> `job` varchar(64) NULL COMMENT '职务', -> `age` int(11) NULL COMMENT '年龄', -> `status` int(11) NOT NULL COMMENT '账号状态,1为禁用,0为启用', -> `flag` int(11) NULL DEFAULT 0 COMMENT '连续登录的失败次数', -> PRIMARY KEY (`name`), -> CONSTRAINT userName UNIQUE (name) -> ) ENGINE=InnoDB -> DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci; Query OK, 0 rows affected (0.00 sec) mysql> show keys from my_users; +----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | +----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | my_users | 0 | PRIMARY | 1 | name | A | 0 | NULL | NULL | | BTREE | | | my_users | 0 | userName | 1 | name | A | 0 | NULL | NULL | | BTREE | | +----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ 2 rows in set (0.00 sec) mysql> ALTER TABLE my_users DROP PRIMARY KEY; Query OK, 0 rows affected (0.02 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> show keys from my_users; +----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | +----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | my_users | 0 | userName | 1 | name | A | 0 | NULL | NULL | | BTREE | | +----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ 1 row in set (0.00 sec) ``` ## 重置root密码 重置root密码需要停服,生产环境请慎重操作。 ``` [root@python ~]# service mysqld stop 停止 mysqld: [确定] [root@python ~]# netstat -lntp Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:62113 0.0.0.0:* LISTEN 1454/sshd tcp 0 0 127.0.0.1:27107 0.0.0.0:* LISTEN 2674/mongod tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 22456/nginx [root@python ~]# mysqld_safe --skip-grant-tables --user=mysql & [1] 22110 [root@python ~]# 180111 14:21:23 mysqld_safe Logging to '/var/log/mysqld.log'. 180111 14:21:23 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql [root@python ~]# netstat -lntp Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:62113 0.0.0.0:* LISTEN 1454/sshd tcp 0 0 127.0.0.1:27107 0.0.0.0:* LISTEN 2674/mongod tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN 22200/mysqld tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 22456/nginx [root@python ~]# mysql Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1 Server version: 5.1.73 Source distribution Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> update mysql.user set password=PASSWORD("newpass")where user="root" and host='localhost'; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> flush privileges; Query OK, 0 rows affected (0.00 sec) mysql> mysqladmin -uroot -pnewpass shutdownCtrl-C -- exit! Aborted [root@python ~]# mysqladmin -uroot -pnewpass shutdown 180111 14:22:24 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended [1]+ Done mysqld_safe --skip-grant-tables --user=mysql [root@python ~]# netstat -lntp Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:62113 0.0.0.0:* LISTEN 1454/sshd tcp 0 0 127.0.0.1:27107 0.0.0.0:* LISTEN 2674/mongod tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 22456/nginx [root@python ~]# /etc/init.d/mysqld start 正在启动 mysqld: [确定] [root@python ~]# mysql -h 127.0.0.1 -uroot -p1234 ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) [root@python ~]# mysql -h 127.0.0.1 -uroot -pnewpass Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 3 Server version: 5.1.73 Source distribution Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | cmdb | | mysql | | python | +--------------------+ 4 rows in set (0.00 sec) mysql> ```
SQL
UTF-8
475
2.859375
3
[]
no_license
CREATE TYPE category AS ENUM( 'Tea', 'Pills', 'Counseling', 'Plant-based', 'Body-care', 'Recipes' ); CREATE TABLE holistic_users_inventory( id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, user_id INTEGER REFERENCES holistic_users(id), service_name TEXT NOT NULL, price NUMERIC (9, 2) NOT NULL, remaining_inventory INTEGER NOT NULL, description TEXT NOT NULL, product_category category NOT NULL, images TEXT );
TypeScript
UTF-8
434
2.5625
3
[ "Apache-2.0" ]
permissive
import { fmod as _fmod } from "@thi.ng/math"; import { ARGS_VV, defHofOp } from "./internal/codegen"; import { FN2 } from "./internal/templates"; /** * This version of mod uses the same logic as in GLSL, whereas `mod` * merely uses JavaScript's `%` modulo operator, yielding different * results for negative values. * * `a - b * floor(a/b)` * */ export const [fmod, fmod2, fmod3, fmod4] = defHofOp(_fmod, FN2("op"), ARGS_VV);
C++
UTF-8
796
2.578125
3
[]
no_license
#include <iostream> #include <ctime> // Header files #include "weather.h" #include "io_control.h" using namespace std; int main(int argc, char *argv[]) { flags *f = update_flags(argc, argv); init_io(); char weather[20]; bool pressed = false; // While the exit button has not been pressed while (!pressed) { // Reset RGB LED reset_rgb(); // Check current weather weather_today(weather); // Check for the corresponding colour for the weather int colour = det_colour(weather); record_data(f, weather, colour); // Update RGB LED colour update_rgb(colour); // Wait 1 hour before next check pressed = is_exit(); } reset_gpio(); delete f; return 0; }
Java
WINDOWS-1252
544
3.15625
3
[]
no_license
package patterns.builder.case1; public class TextBuilder extends Builder { @Override public void setTitle(String title) { getStr().append("========================\n"); getStr().append("[" + title + "]\n"); } @Override public void addItems(Student[] items) { for(Student s:items) { getStr().append("-----------\n"); getStr().append(":" + s.getName() + "\n"); getStr().append(":" + s.getId() + "\n"); } } @Override public Object getResult() { return this.getStr(); } }
JavaScript
UTF-8
1,249
2.65625
3
[]
no_license
import React, { Component } from 'react'; import Header from './components/Header'; import Present from './components/Present'; import './App.css'; class App extends Component { constructor(props) { super(props) this.state = { presents: [] } }; addItem = ( id ) => { const { presents } = this.state; const present_ids = this.state.presents.map(present => present.id); const max_id = present_ids.length > 0? Math.max(...present_ids) : 0; presents.push({ id: max_id + 1 }); this.setState({ presents }); }; removeItem = (id) => { const presents = this.state.presents.filter(present => present.id !== id); this.setState({ presents }); } render() { return ( <> <Header /> <div className="App"> { this.state.presents.map(present => { return ( <Present key={present.id} present={present} removeItem={this.removeItem} /> ) }) } <div className="buttons"> <button className="add-item" onClick={this.addItem}>Add item</button> <br /> </div> </div> </> ); } } export default App;
Java
UTF-8
2,642
3.296875
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { // AtCoder Beginner Contest 038 // https://atcoder.jp/contests/abc038/tasks/ FastReader sc = new FastReader(); int h1 = sc.nextInt(); int w1 = sc.nextInt(); int h2 = sc.nextInt(); int w2 = sc.nextInt(); if (h1 == h2 || w1 == w2 || h1 == w2 || h2 == w1) { System.out.println("YES"); } else { System.out.println("NO"); } } private static void solveA() { FastReader sc = new FastReader(); String s = sc.next(); if (s.charAt(s.length() - 1) == 'T') { System.out.println("YES"); } else { System.out.println("NO"); } } private static void solveB() { FastReader sc = new FastReader(); int h1 = sc.nextInt(); int w1 = sc.nextInt(); int h2 = sc.nextInt(); int w2 = sc.nextInt(); if (h1 == h2 || w1 == w2 || h1 == w2 || h2 == w1) { System.out.println("YES"); } else { System.out.println("NO"); } } private static void solveC() { FastReader sc = new FastReader(); int n = sc.nextInt(); long res = 0; LinkedList<Integer> stack = new LinkedList<>(); for (int i = 0; i < n; i++) { int num = sc.nextInt(); if (stack.isEmpty()) { stack.push(num); } else { if (num > stack.peek()) { stack.push(num); } else { while (!stack.isEmpty()) { stack.pop(); } stack.push(num); } } res += stack.size(); } System.out.println(res); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Python
UTF-8
958
4.4375
4
[]
no_license
""" Write a function that calculates overtime and pay associated with overtime. * Working 9 to 5: regular hours * After 5pm is overtime Your function gets a list with 4 values: * Start of working day, in decimal format, (24-hour day notation) * End of working day. (Same format) * Hourly rate * Overtime multiplier Your function should spit out: * `$` \+ earned that day (rounded to the nearest hundreth) ### Examples over_time([9, 17, 30, 1.5]) ➞ "$240.00" over_time([16, 18, 30, 1.8]) ➞ "$84.00" over_time([13.25, 15, 30, 1.5]) ➞ "$52.50" 2nd example explained: * From 16 to 17 is regular, so `1 * 30` = 30 * From 17 to 18 is overtime, so `1 * 30 * 1.8` = 54 * `30 + 54` = $84.00 """ def over_time(lst): earn = (lst[1]-lst[0])*lst[2] if lst[0]>=17: earn*=lst[3] elif lst[1]>17: earn+=(lst[1]-17)*(lst[3]-1)*lst[2] tot=str(round(earn*100+10**(-10))) return '$'+tot[:-2]+'.'+tot[-2:]
C#
UTF-8
2,354
2.65625
3
[]
no_license
using GraphQLDemo.Data.Models; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Logging; using Polly; using Polly.Retry; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GraphQLDemo.Data.Context { public class CourseManagementSeeding { public IList<Course> courses = new List<Course>() { new Course{ // Id =1, Title ="Leadership", Description ="Course Description", Duration=5 }, new Course{ // Id =2, Title ="Leadership and Managemetn", Description ="Course Description", Duration=7 }, new Course{ // Id =3, Title ="Technoology", Description ="Course Description", Duration=5 }, new Course{ //Id =4, Title ="Process", Description ="Course Description", Duration=3 } }; public void SeedAsync(CourseManagementContext context, ILogger<CourseManagementSeeding> logger) { logger.LogInformation("Executing Seeding"); var retryPolicy = CreatePolicy(logger, nameof(CourseManagementContext)); retryPolicy.Execute(() => { AddOrUpdateAsync(context); }); logger.LogInformation("Completed Seeding"); } private void AddOrUpdateAsync(CourseManagementContext context) { if (!context.Course.Any()) { try { context.Course.AddRange(courses); context.SaveChanges(); } catch (Exception ex) { throw; } } } private RetryPolicy CreatePolicy(ILogger<CourseManagementSeeding> logger, string prefix, int retries = 3) { return Policy .Handle<SqlException>() .WaitAndRetry( retries, retryAttempt => TimeSpan.FromSeconds(5), (exception, timespan, context) => { logger.LogWarning(exception, "[{prefix}] Exception {ExceptionType} with message {Message}", prefix, exception.GetType().Name, exception.Message); }); } } }
C++
UTF-8
1,360
3.484375
3
[]
no_license
#include "Mat4.hh" mat4::mat4(float val){ for (int i = 0; i < 4; i++){ matrix[i][0] = val; matrix[i][1] = val; matrix[i][2] = val; matrix[i][3] = val; } } mat4::mat4(float a1, float a2, float a3, float a4, float b1, float b2, float b3, float b4, float c1, float c2, float c3, float c4, float d1, float d2, float d3, float d4) { for(int i = 0; i < 4; i++) { if(i == 0) { matrix[i][0] = a1; matrix[i][1] = a2; matrix[i][2] = a3; matrix[i][3] = a4; } else if (i == 1) { matrix[i][0] = b1; matrix[i][1] = b2; matrix[i][2] = b3; matrix[i][3] = b4; } else if (i == 2) { matrix[i][0] = c1; matrix[i][1] = c2; matrix[i][2] = c3; matrix[i][3] = c4; } else { matrix[i][0] = d1; matrix[i][1] = d2; matrix[i][2] = d3; matrix[i][3] = d4; } } } float mat4::operator()(int i, int j) const{ return matrix[i][j]; }; float& mat4::operator()(int i, int j) { return matrix[i][j]; }; mat4 mat4::operator*(const mat4 &m2){ mat4 res; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { res(i,j) = 0; for(int k = 0; k < 4; k++) { res(i,j) += matrix[i][k] * m2(k,j); } } } return res; } mat4 mat4::identity(){ return mat4(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1); }
Markdown
UTF-8
3,075
3.109375
3
[]
no_license
* 介绍如何配置组件,使其能够最大化地利用浏览器的缓存能力来改善页面的性能。 * 长久的Expires头最常用于图片,但应该将其用在所有组件上,包括脚本、样式表和Flash。 ## Expires ## Max-age和mod_expires * Expires头使用一个特定的时间,它要求服务器和客户端的时钟严格同步。另外,过期日期需要经常检查,并且一旦未来这一天 到来了,还需要在服务器配置中提供一个新的日期。 * Cache-Control * 使用带有max-age的Cache-Control可以消除Expires的限制,但对于不支持HTTP1.1的浏览器(尽管这个只占你的访问量的1%), 你可能仍然希望提供Expires头,你可以同时指定这两个响应头——Expires和Cache-Control max-age。如果两者同时出现,HTTP规范规定max-age 指令将重写Expires头。然而,需要关心Expires带来的时钟同步和配置维护的问题。 * mod_expires Apache模块使你在使用Expires头时能够像max-age那样以相对的方式设置日期。通过Expires-Default指令来完成。 ``` <FilesMatch ''\.(gif |jpg | js | css) $''> ExpiresDefault 'access plus 10 years' </FilesMatch> ``` * 时间可以以年、月、日、小时、分钟、秒为单位来设置。它同时向响应中发送Expires头和Cache-Control max-age头。 * 实际的过期日期根据何时接到请求而变,但是即便如此,它永远都是10年以后。由于Cache-Control具有优先权且明确指出了相对 于请求时间所经过的秒数,时钟同步问题就被避免了。不用担心固定日期的更新,它在HTTP1.0浏览器中也能够使用。跨浏览器改善缓存的最佳解决方案就是使用由ExpiresDefault设置的Expires头。 ## 空缓存 VS 完整缓存 * 指的是与你的页面相关的浏览器缓存的状态。如果你的页面中的组件没有放在缓存中,则缓存为空,反之,则是完整的。 ## 不仅仅是图片 * 常久的Expires头应该包括任何不经常变化的组件,包括脚本、样式表和Flash组件。但是HTML文档不应该使用常久的 Expires头,因为它的包含动态内容,这些内容在每次用户请求时都将被更新。 * 理想情况下,页面中的所有组件都应该具有常久的Expires头,并且后续的页面浏览中只需要为HTML文档进行一个HTTP请求。 当文档中所有组件都是从浏览器缓存中读取出来时,响应时间减少50%或更多。 ## 修订文件名 * 为了确保用户能获取组件的最新版本,需要在所有的HTML页面中修改组件的文件名。将版本号嵌在组件的文件名中<例如 yahoo_2.06.js> * 如果一个组件没有长久的Expires头,它仍然会存储在浏览器的缓存中。在后续请求中,浏览器会检查缓存并发现组件已经过期(HTTP术语称之为'陈旧')。为了提高效率,浏览器会像原始服务器发送一个条件GET请求(Conditional Get Reques)。如果组件没有改变,原始服务器可以免于发送整个组件,而是发送一个很小的头,告诉浏览器可以使用其缓存的组件。
C++
UTF-8
679
3.03125
3
[]
no_license
#include <iostream> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* oddEvenList(ListNode* head) { if (!head || !head->next) return head; ListNode odd(0), even(0); odd.next = even.next = head; ListNode *po = &odd, *pe = &even; while (head) { po->next = head; po = po->next; pe->next = head->next; pe = pe->next; head = head->next ? head->next->next : head->next; } po->next = even.next; return odd.next; } }; int main() { return 0; }
PHP
UTF-8
1,181
2.546875
3
[]
no_license
<?php use PHPMailer\PHPMailer\PHPMailer; if (isset($_POST['from']) && isset($_POST['to'])){ $from = $_POST['from']; $to = $_POST['to']; $message = $_POST['message']; require_once "PHPMailer/PHPMailer.php"; require_once "PHPMailer/SMTP.php"; require_once "PHPMailer/Exception.php"; $mail = new PHPMailer; $mail->SMTPDebug = 4; $mail->isSMTP(); $mail->Host = "mailtest.codingoverflow.com"; $mail->SMTPAuth = true; $mail->Username = "bfoot171@gmail.com"; $mail->Password = "greenmac20"; $mail->Port = 587; $mail->SMTPSecure = "tls"; $mail->isHTML(true); $mail->setFrom($from, 'Must Funjabi'); $mail->addAddress("bfoot171@gmail.com"); $mail->Subject = 'First test'; $mail->Body = $message; $send = $mail->send(); if ($send){ $status = "Success"; $response = "Email is sent"; } else{ $status = "failed"; $response = "Email is not send". $mail->ErrorInfo; } exit(json_encode(array("status" => $status, "response" => $response))); } ?>
Java
UTF-8
7,028
1.875
2
[]
no_license
package com.greit.weys.mypage; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.greit.weys.common.AriaUtils; import com.greit.weys.join.JoinDao; import com.greit.weys.user.UserDao; import com.greit.weys.user.UsrVO; @Service public class MypageService { protected Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private MypageDao mypageDao; @Autowired private JoinDao joinDao; @Autowired private UserDao userDao; @Value("#{props['ENC.KEY']}") private String ENC_KEY; public int updateUserDeleteV7(UsrVO reqVO) throws Exception { String ori_pw = mypageDao.selectUsrPw(reqVO.getUsrId() + ""); String pw = AriaUtils.encryptPassword(reqVO.getUsrPw(), String.valueOf(reqVO.getUsrId())); if(pw.equals(ori_pw)){ mypageDao.updateUserDeleteToken(reqVO.getUsrId() + ""); return mypageDao.updateUserDelete(reqVO.getUsrId() + ""); } else return -1; } public int updateUserDelete(UsrVO reqVO) throws Exception { String ori_pw = mypageDao.selectUsrPw(reqVO.getUsrId() + ""); String pw = AriaUtils.encryptPassword(reqVO.getUsrPw(), String.valueOf(reqVO.getUsrId())); if(pw.equals(ori_pw)){ Map<String, Object> reqMap = new HashMap<>(); reqMap.put("usrId", reqVO.getUsrId()); userDao.insertUserUnknown(reqMap); mypageDao.updateUserDeleteToken(reqVO.getUsrId() + ""); mypageDao.updateUserDelete(reqVO.getUsrId() + ""); int unKey = MapUtils.getIntValue(reqMap, "unKey", 0); return unKey; } else return -1; } public List<NoticeVO> selectNoticeList() { List<NoticeVO> resultList = mypageDao.selectNoticeList(); for(NoticeVO temp : resultList){ String content = temp.getContent(); content = "<!DOCTYPE HTML><html><head><meta http-equiv=\"content-type\" " + "content=\"text/html; charset=UTF-8\">" + "<meta name=\"viewport\" content=\"width=device-width, minimum-scale=1, initial-scale=1, shrink-to-fit=no\">" + "<style type=\"text/css\">html { -webkit-text-size-adjust: none; }</style></head>" + "<body>" + content + "</body></html>"; temp.setContent(content); } return resultList; } public NoticeVO selectNotice(String notice_id) { NoticeVO info = mypageDao.selectNotice(notice_id); String content = info.getContent(); content = "<!DOCTYPE HTML><html><head><meta http-equiv=\"content-type\" " + "content=\"text/html; charset=UTF-8\">" + "<meta name=\"viewport\" content=\"width=device-width, minimum-scale=1, initial-scale=1, shrink-to-fit=no\">" + "<style type=\"text/css\">html { -webkit-text-size-adjust: none; }</style></head>" + "<body>" + content + "</body></html>"; info.setContent(content); return info; } public int updateUsrPwd(ChangeVO reqVO) throws Exception { String usrPw = mypageDao.selectUsrPw(reqVO.getUsrId()); String pw = AriaUtils.encryptPassword(reqVO.getOriginPw(), String.valueOf(reqVO.getUsrId())); if(!pw.equals(usrPw)){ return -1; } String newPw = AriaUtils.encryptPassword(reqVO.getNewPw(), String.valueOf(reqVO.getUsrId())); reqVO.setNewPw(newPw); return mypageDao.updateUsrPw(reqVO); } public ProfileVO selectUserInfoV7(String userKey) { Map<String, Object> reqMap = new HashMap<>(); reqMap.put("usrId", userKey); reqMap.put("encKey", ENC_KEY); return mypageDao.selectUserInfoV7(reqMap); } public ProfileVO selectUserInfo(String userKey) { Map<String, Object> reqMap = new HashMap<>(); reqMap.put("usrId", userKey); reqMap.put("encKey", ENC_KEY); ProfileVO result = mypageDao.selectUserInfo(reqMap); int couponCnt = mypageDao.selectCouponCnt(userKey); result.setCouponCnt(couponCnt); return result; } public int updateUsrTel(ChangeVO reqVO) { reqVO.setEncKey(ENC_KEY); int res = mypageDao.checkUsrTel(reqVO); if(res > 0) return -1; return mypageDao.updateUsrTel(reqVO); } public int updateUsrEmail(ChangeVO reqVO) { reqVO.setEncKey(ENC_KEY); int res = mypageDao.checkUsrEmail(reqVO); if(res > 0) return -1; return mypageDao.updateUsrEmail(reqVO); } public int updateUsrAgree(ChangeVO reqVO) { mypageDao.updateUsrPush(reqVO); return mypageDao.updateUsrAgree(reqVO); } public BonusVO selectBonusInfo(String userKey) { return mypageDao.selectBonusInfo(userKey); } public int updateUnknownAgree(ChangeVO reqVO) { return mypageDao.updateUnknownAgree(reqVO); } public Map<String, Object> selectMoreInfo(int usrId, int unKey) { Map<String, Object> resultMap = new HashMap<>(); int eventCnt = 0; String agree = ""; if(usrId > 0){ agree = mypageDao.selectUsrAgree(usrId); eventCnt = mypageDao.selectEventCntUsr(usrId); } else { agree = mypageDao.selectUnKnownAgree(unKey); eventCnt = mypageDao.selectEventCnt(); } resultMap.put("eventCnt", eventCnt); resultMap.put("agree", agree); return resultMap; } public Map<String, Object> selectFrdInfo(String ak) { if(ak == null || ak.equals("unknown")){ return null; } Integer usrId = mypageDao.selectUsrId(ak); if(usrId != null){ Map<String, Object> resultMap = mypageDao.selectMyFrdCd(usrId); int myFrdCnt = mypageDao.selectMyFrdCnt(usrId); if(myFrdCnt > 3) myFrdCnt = 3; List<Map<String, Object>> onMap = new ArrayList<>(); for(int i=1 ; i<=myFrdCnt ; i++){ onMap.add(new HashMap<String, Object>()); } List<Map<String, Object>> offMap = new ArrayList<>(); for(int i=1 ; i<=3-myFrdCnt ; i++){ offMap.add(new HashMap<String, Object>()); } resultMap.put("onMap", onMap); resultMap.put("offMap", offMap); resultMap.put("usrId", usrId); return resultMap; } else { return null; } } public int insertFrd(Map<String, Object> reqMap) { int usrId = MapUtils.getIntValue(reqMap, "usrId"); String frdCd = MapUtils.getString(reqMap, "frdCd"); int targetUsrId = joinDao.selectFrdId(frdCd); if(targetUsrId > 0){ Map<String, Object> frdMap = new HashMap<>(); frdMap.put("targetUsrId", targetUsrId); frdMap.put("reqUsrId", usrId); targetUsrId = joinDao.insertFrdMap(frdMap); } else { return -1; } return targetUsrId; } public Map<String, Object> selectExcList(String userKey) { List<AlrmExcVO> resultList = mypageDao.selectExcList(userKey); Map<String, Object> resultMap = new HashMap<>(); resultMap.put("dataList", resultList); return resultMap; } public int insertAlrmExc(AlrmExcVO reqVO) { return mypageDao.insertAlrmExc(reqVO); } public int updateAlrmExc(AlrmExcVO reqVO) { int resCnt = 0; String alrmSt = reqVO.getAlrmSt(); if(alrmSt.equals("D")){ resCnt = mypageDao.deleteAlrmExc(reqVO); } else { resCnt = mypageDao.updateAlrmExc(reqVO); } return resCnt; } }
C#
UTF-8
2,617
2.6875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TareaTICurso1.Models; using Newtonsoft.Json; namespace TareaTICurso1 { class Program { static void Main(string[] args) { dbPruebaCursoEntities db = new dbPruebaCursoEntities(); DCBanco consulta = new DCBanco(); List<DCBanco> ListaBanco = db.DCBanco.ToList(); List<DCBanco> listado = new List<DCBanco>(); ////foreach (DCBanco item in ListaBanco) ////{ //// Console.WriteLine("IdBanco= " + item.IdBanco); //// Console.WriteLine("TasaInteres= " + item.TasaInteres); //// Console.WriteLine("Cantidad= " + item.Cantidad); //// Console.WriteLine("Finaciado Por = " + item.DCCarro.FinanciadoPor); //// Console.WriteLine("Marca = " + item.DCCarro.Marca); //// Console.WriteLine("Modelo = " + item.DCCarro.Modelo); //// Console.WriteLine("Año = " + item.DCCarro.Año); ////} var datos = (from banco in ListaBanco // db.DCBanco join carro in db.DCCarro on banco.IdBanco equals carro.FinanciadoPor select new { CodigoBanco = banco.IdBanco, TasaInteres = banco.TasaInteres, Cantidad = banco.Cantidad, FinanciadoPor = carro.FinanciadoPor, Marca = carro.Marca, Modelo = carro.Modelo, Año = carro.Año } ).ToList(); var bancod = new DCBanco(); foreach (var item in datos) { DCBanco listaT = new DCBanco(); listaT.IdBanco = item.CodigoBanco; listaT.TasaInteres = item.TasaInteres; listaT.Cantidad = item.Cantidad; listado.Add(listaT); } var Json = Newtonsoft.Json.JsonConvert.SerializeObject(listado, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); Console.WriteLine(Json); // antes Console.ReadLine(); } } }
Python
UTF-8
8,009
3.3125
3
[ "MIT" ]
permissive
import time from ..storage_managing.storage import Storage from .exceptions.wrongloglevelerror import WrongLogLevelError class BotLogger: """ Telegram bot logger writing into DB ... Attributes --- levels: dict, static available log levels enum current_level: str current log level: messages with levels higher or equal to current are sent collection: str DB collection name to send logs to storage: Storage DB wrapper to send or dump logs short_params: bool one-string log params flag (params are cut if True) Methods --- cut_params(params) cuts params values to a single string log_cleaning() logs cleaning old logs from DB with info level write_log(level, event, params) sends log to DB with regard to current log level and flag values clean_old(min_age) deletes logs older than given age dump_last(count) dumps given count of last sent logs log_error(event, params) logs given event with error level log_receive_command(id, command) logs receiving command with info level log_receive_document(id, filename) logs receiving document with info level log_receive_msg(id, text) logs receiving message with info level log_send_document(id, filename) logs sending document with info level log_send_msg(id, text) logs sending message with info level log_start() logs starting bot with info level log_stop() logs stopping bot with info level set_level(level) sets current log level to given """ levels = {'DEBUG': 1, 'INFO': 2, 'WARNING': 3, 'ERROR': 4, 'CRITICAL': 5} def __init__(self, storage: Storage, collection_name: str) -> None: """ Keyword arguments: --- storage: Storage, required DB storage sevice collection_name: str name of DB collection for logs """ self.__current_level: str = 'INFO' self.__collection: str = collection_name self.__storage: Storage = storage self.short_params: bool = True def __cut_params(self, params: dict) -> dict: """ Cuts params values to a single string. If param value contains at least one "\n", replacing it with all content afterwards with " <...>". Keyword arguments: --- params: dict, required params which values need to be cut to a single string """ for param in params: params[param] = str(params[param]) if '\n' in params[param]: params[param] = params[param].split('\n')[0] + ' <...>' return params def __log_cleaning(self) -> None: """ Logs cleaning old logs from DB with info level. """ self.__write_log('INFO', 'Old logs cleaned') def __write_log(self, level: str, event: str, params: dict = None) -> None: """ Sends log to DB with regard to current log level and flag values. Keyword arguments: --- level: str, required level to send log with (if less than current, does not send log) event: str, required main log description params: dict, optional additional params to log """ if self.levels[self.__current_level] > self.levels[level]: return document = { 'time': int(time.time() * 1000), 'event': event } if params: if self.short_params: params = self.__cut_params(params) document['params'] = params self.__storage.insert_one_doc(self.__collection, document) def clean_old(self, min_age: int) -> None: """ Deletes from DB logs older than given age Keyword arguments: --- min_age: int, required minimal age (in milliseconds) to delete logs from """ max_time = int(time.time() * 1000) - min_age self.__storage.remove_many_docs_by_dict(self.__collection, {'time': {'$lte': max_time}}) self.__log_cleaning() def dump_last(self, count: int) -> list: """ Dumps from DB given count of last sent logs Keyword arguments: --- count: int, required number of logs to dump """ return self.__storage.get_data(self.__collection)[-count:] def log_error(self, event: str, params: dict = None) -> None: """ Logs given event with error level. Keyword arguments --- event: str, requrired main log description params: dict, optional additional params to log """ self.__write_log('ERROR', event, params) def log_receive_command(self, id: int, command: str) -> None: """ Logs receiving command with info level. Keyword arguments --- id: int, required telegram id of user who sent command command: str, required received command """ self.__write_log('INFO', 'Command received', {'id': id, 'command': command}) def log_receive_document(self, id: int, filename: str) -> None: """ Logs receiving document with info level. Keyword arguments --- id: int, required telegram id of user who sent document filename: str, required filename of received document """ self.__write_log('INFO', 'Document received', {'id': id, 'filename': filename}) def log_receive_msg(self, id: int, text: str) -> None: """ Logs receiving message with info level. Keyword arguments --- id: int, required telegram id of user who sent message text: str, required received message text """ self.__write_log('INFO', 'Message received', {'id': id, 'text': text}) def log_send_document(self, id: int, filename: str) -> None: """ Logs sending document with info level. Keyword arguments --- id: int, required telegram id of receipient filename: str, required sent document filename """ self.__write_log('INFO', 'Document sent', {'id': id, 'filename': filename}) def log_send_msg(self, id: int, text: str) -> None: """ Logs sending message with info level. Keyword arguments --- id: int, required telegram id of receipient text: str, required sent message text """ self.__write_log('INFO', 'Message sent', {'id': id, 'text': text}) def log_start(self) -> None: """ Logs starting bot with info level. """ self.__write_log('INFO', 'Bot started') def log_stop(self) -> None: """ Logs stopping bot with info level. """ self.__write_log('INFO', 'Bot stopped') def set_level(self, level: str) -> None: """ Sets current log level to given. If given log level does not exist, exception is raised Keyword arguments --- level: str, required log level that current level must be Raisable exceptions --- WrongLogLevelError raised if given log level does not exist """ if level in self.levels: self.__current_level = level else: raise WrongLogLevelError(level)
Markdown
UTF-8
3,035
2.53125
3
[ "MIT" ]
permissive
snooper-config(7) - Configure for Espionage =========================================== ## DESCRIPTION Configuration of `snooper` is controlled through a YAML file. ## FORMAT snooper(1) expects a YAML document of key-value pairs; each pair specifies an option. Unknown options are ignored. Options that can contain a list of values may also be given a single value. ## OPTIONS ### String options * `base_path:` <directory>: Specifies the <directory> that `snooper` should base all relative paths from. This is also the working directory that commands and hooks will inherit. * `command:` <command_string>: Specifies the command string to execute when a file change is detected. ### String Array options * `paths:` <directories>: Specifies a list of <directories> to watch. Directories can be either relative or absolute paths. If no paths are specified the default is to watch `base_path`. * `filters:` <filters>, `ignored:` <filters>: Specifies a list of regular expressions <filters> to use to filter the changes. These should be in a format understood by ruby(1)'s Regex.new method. If none are given then all changes in watched directories trigger testing. A file change satisfies these filters if the file path matches any of the regular expressions in `filters` and none of those in `ignored`. _Note_: as these are regular expressions `\.c` will match both `foo.c` and `bar.cfg`, `\.c$` will only match `.c` files. ### Polling * `force_poll:` <poll>: Specifies if the polling fallback mode should be used and controls the polling frequency in seconds. Include this option if you want to use polling but don't want to have to specify it on the command line. Defaults to false. This mode can be slower and more buggy but is useful for working around bugs in third party applications that hide filesystem events. Known to be required when you are snooping on VirtualBox shared folders, or in Dropbox folders. _Note_: This option can be overridden from the command line with the `--poll` option. ### Hooks Hooks are useful to pefrom special commads upon a subset of the file-change events. Each hook is run a single time if any of the filepaths that satisfy `filters:` and `ignored:` aslo match the `pattern:` of the filter. * `hooks:` <hook_list>: Specifies a list of hooks, where each hook represents a task that should be carried out upon a subset of the triggering events. The hooks key should contain a list of mappings. Each mappign should have the two following keys: * `pattern:` <regexp>: The pattern to run the hook on. This should be of the same format as `filters:` and `ignored:`. Note that hooks can only match a subset of all file changes as controlled by `filters:` and `ignored:`. * `command:` <command_string>: A command to be run when the hook is triggered. This is of the same format as the global `command:` key. ## SEE ALSO snooper(1) ## AUTHORS Will Speak (@willspeak)
Java
UTF-8
1,985
3.328125
3
[]
no_license
/** * This class contains the data for each phone book person and * setter and getter method for them */ package Assignment; import java.util.Date; public class PhoneBookPerson { private String name; private Date birthday; private long phone; private String address; private String email; /** * Constructor with all information * @param name * @param birthday * @param phone * @param email * @param address */ // public PhoneBookPerson(String name, Date birthday, int phone, String email, String address) // { // this.name = name; // this.birthday = birthday; // this.phone = phone; // this.address = address; // this.email= email; // } public PhoneBookPerson(String name) { this.name = name; this.birthday = null; this.address = ""; this.phone = -1; this.email = ""; } public PhoneBookPerson() { this.name = ""; this.birthday = null; this.address = ""; this.phone = -1; this.email = ""; } /** * getters to get name * @return */ public String getName() { return name; } /** * getter to get birthday * @return */ public Date getBirthday() { return birthday; } /** * getter to get phoneNumber * @return */ public long getPhone() { return phone; } /** * getter to get address * @return */ public String getAddress() { return address; } /** * getter to get email address * @return */ public String getEmail() { return email; } /** * setter to set name * @param nm */ public void SetName(String nm) { name = nm; } /** * setter to set birthday * @param birth */ public void SetBirthday(Date birth) { birthday = birth; } /** * setter to set phoneNumber * @param ph */ public void SetPhone(long ph) { phone = ph; } /** * setter to set address * @param addr */ public void SetAddress(String addr) { address = addr; } /** * setter to set email * @param ema */ public void SetEmail(String ema) { email = ema; } }
C++
UTF-8
11,135
3.03125
3
[]
no_license
#ifndef LIST_TEST_H #define LIST_TEST_H #include <test/UnitTest.h> #include <test/UnitTestRunner.h> #include <util/containers/Node.h> #include <util/containers/List.h> using namespace Util; class ListTest : public UnitTest { private: const static int n = 10; typedef int Data; List<Data> list; Node<Data> nodes[n]; public: void setUp(); void tearDown(); void testInitialize(); void testPushBack(); void testPushBack2(); void testPushFront(); void testPopBack(); void testInsertNext1(); void testInsertNext2(); void testInsertPrev1(); void testInsertPrev2(); void testRemove1(); void testRemove2(); void testRemove3(); void testInsert1(); void testInsert2(); void testInsert3(); void testInsert4(); void testInsert5(); void dumpList(); }; void ListTest::setUp() { for (int i=1; i < n; i++) { nodes[i].data() = i*10 + 1; } } void ListTest::tearDown() {} void ListTest::testInitialize() { printMethod(TEST_FUNC); list.initialize(nodes, n); TEST_ASSERT(list.isValid()); } void ListTest::testPushBack() { printMethod(TEST_FUNC); list.initialize(nodes, n); TEST_ASSERT(list.size_ == 0); TEST_ASSERT(list.front_ == 0); TEST_ASSERT(list.back_ == 0); TEST_ASSERT(int(list.lower_ - list.nodes_) == n); TEST_ASSERT(int(list.upper_ - list.nodes_) == -1); list.pushBack(nodes[5]); list.pushBack(nodes[8]); list.pushBack(nodes[3]); TEST_ASSERT(list.isValid()); TEST_ASSERT(list.size_ == 3); TEST_ASSERT(int(list.front_ - list.nodes_) == 5); TEST_ASSERT(int(list.back_ - list.nodes_) == 3); TEST_ASSERT(int(list.lower_ - list.nodes_) == 3); TEST_ASSERT(int(list.upper_ - list.nodes_) == 8); //printf("size_ = %10i\n", list.size_); //printf("front_ = %10i\n", int(list.front_ - list.nodes_)); //printf("back_ = %10i\n", int(list.back_ - list.nodes_)); //printf("lower_ = %10i\n", int(list.lower_ - list.nodes_)); //printf("upper_ = %10i\n", int(list.upper_ - list.nodes_)); //Node<Data> node; //for (int i=0; i < n; i++) { // node = list.nodes_[i]; //} } void ListTest::testPushFront() { printMethod(TEST_FUNC); list.initialize(nodes, n); TEST_ASSERT(list.size_ == 0); TEST_ASSERT(list.front_ == 0); TEST_ASSERT(list.back_ == 0); TEST_ASSERT(int(list.lower_ - list.nodes_) == n); TEST_ASSERT(int(list.upper_ - list.nodes_) == -1); list.pushFront(nodes[5]); list.pushFront(nodes[8]); list.pushFront(nodes[3]); TEST_ASSERT(list.size_ == 3); TEST_ASSERT(int(list.front_ - list.nodes_) == 3); TEST_ASSERT(int(list.back_ - list.nodes_) == 5); TEST_ASSERT(int(list.lower_ - list.nodes_) == 3); TEST_ASSERT(int(list.upper_ - list.nodes_) == 8); TEST_ASSERT(list.isValid()); //printf("size_ = %10i\n", list.size_); //printf("front_ = %10i\n", int(list.front_ - list.nodes_)); //printf("back_ = %10i\n", int(list.back_ - list.nodes_)); //printf("lower_ = %10i\n", int(list.lower_ - list.nodes_)); //printf("upper_ = %10i\n", int(list.upper_ - list.nodes_)); //Node<Data> node; //for (int i=0; i < n; i++) { // node = list.nodes_[i]; //} } void ListTest::testPopBack() { printMethod(TEST_FUNC); list.initialize(nodes, n); list.pushBack(nodes[5]); list.pushBack(nodes[8]); list.pushBack(nodes[3]); list.popBack(); TEST_ASSERT(list.size_ == 2); TEST_ASSERT(int(list.front_ - list.nodes_) == 5); TEST_ASSERT(int(list.back_ - list.nodes_) == 8); TEST_ASSERT(int(list.lower_ - list.nodes_) == 5); TEST_ASSERT(int(list.upper_ - list.nodes_) == 8); TEST_ASSERT(list.isValid()); list.popBack(); TEST_ASSERT(list.size_ == 1); TEST_ASSERT(int(list.front_ - list.nodes_) == 5); TEST_ASSERT(int(list.back_ - list.nodes_) == 5); TEST_ASSERT(int(list.lower_ - list.nodes_) == 5); TEST_ASSERT(int(list.upper_ - list.nodes_) == 5); TEST_ASSERT(list.isValid()); list.popBack(); TEST_ASSERT(list.size_ == 0); TEST_ASSERT(list.front_ == 0); TEST_ASSERT(list.back_ == 0); TEST_ASSERT(int(list.lower_ - list.nodes_) == n); TEST_ASSERT(int(list.upper_ - list.nodes_) == -1); TEST_ASSERT(list.isValid()); } void ListTest::testInsertNext1() { printMethod(TEST_FUNC); list.initialize(nodes, n); list.pushBack(nodes[5]); list.pushBack(nodes[8]); list.pushBack(nodes[3]); list.insertNext(nodes[5], nodes[9]); TEST_ASSERT(list.size_ == 4); TEST_ASSERT(int(list.front_ - list.nodes_) == 5); TEST_ASSERT(int(list.back_ - list.nodes_) == 3); TEST_ASSERT(int(list.lower_ - list.nodes_) == 3); TEST_ASSERT(int(list.upper_ - list.nodes_) == 9); TEST_ASSERT(list.isValid()); } void ListTest::testInsertNext2() { printMethod(TEST_FUNC); list.initialize(nodes, n); list.pushBack(nodes[5]); list.pushBack(nodes[8]); list.pushBack(nodes[3]); list.insertNext(nodes[3], nodes[9]); TEST_ASSERT(list.size_ == 4); TEST_ASSERT(int(list.front_ - list.nodes_) == 5); TEST_ASSERT(int(list.back_ - list.nodes_) == 9); TEST_ASSERT(int(list.lower_ - list.nodes_) == 3); TEST_ASSERT(int(list.upper_ - list.nodes_) == 9); TEST_ASSERT(list.isValid()); } void ListTest::testInsertPrev1() { printMethod(TEST_FUNC); list.initialize(nodes, n); list.pushBack(nodes[5]); list.pushBack(nodes[8]); list.pushBack(nodes[3]); list.insertPrev(nodes[5], nodes[9]); TEST_ASSERT(list.size_ == 4); TEST_ASSERT(int(list.front_ - list.nodes_) == 9); TEST_ASSERT(int(list.back_ - list.nodes_) == 3); TEST_ASSERT(int(list.lower_ - list.nodes_) == 3); TEST_ASSERT(int(list.upper_ - list.nodes_) == 9); TEST_ASSERT(list.isValid()); } void ListTest::testInsertPrev2() { printMethod(TEST_FUNC); list.initialize(nodes, n); list.pushBack(nodes[5]); list.pushBack(nodes[8]); list.pushBack(nodes[3]); list.insertPrev(nodes[3], nodes[9]); TEST_ASSERT(list.size_ == 4); TEST_ASSERT(int(list.front_ - list.nodes_) == 5); TEST_ASSERT(int(list.back_ - list.nodes_) == 3); TEST_ASSERT(int(list.lower_ - list.nodes_) == 3); TEST_ASSERT(int(list.upper_ - list.nodes_) == 9); TEST_ASSERT(list.isValid()); } void ListTest::testRemove1() { printMethod(TEST_FUNC); list.initialize(nodes, n); list.pushBack(nodes[5]); list.pushBack(nodes[8]); list.pushBack(nodes[3]); list.remove(nodes[5]); TEST_ASSERT(list.isValid()); TEST_ASSERT(list.size_ == 2); TEST_ASSERT(int(list.front_ - list.nodes_) == 8); TEST_ASSERT(int(list.back_ - list.nodes_) == 3); TEST_ASSERT(int(list.lower_ - list.nodes_) == 3); TEST_ASSERT(int(list.upper_ - list.nodes_) == 8); } void ListTest::testRemove2() { printMethod(TEST_FUNC); list.initialize(nodes, n); list.pushBack(nodes[5]); list.pushBack(nodes[8]); list.pushBack(nodes[3]); list.remove(nodes[8]); TEST_ASSERT(list.isValid()); TEST_ASSERT(list.size_ == 2); TEST_ASSERT(int(list.front_ - list.nodes_) == 5); TEST_ASSERT(int(list.back_ - list.nodes_) == 3); TEST_ASSERT(int(list.lower_ - list.nodes_) == 3); TEST_ASSERT(int(list.upper_ - list.nodes_) == 5); } void ListTest::testRemove3() { printMethod(TEST_FUNC); list.initialize(nodes, n); list.pushBack(nodes[5]); list.pushBack(nodes[8]); list.pushBack(nodes[3]); list.remove(nodes[3]); TEST_ASSERT(list.isValid()); TEST_ASSERT(list.size_ == 2); TEST_ASSERT(int(list.front_ - list.nodes_) == 5); TEST_ASSERT(int(list.back_ - list.nodes_) == 8); TEST_ASSERT(int(list.lower_ - list.nodes_) == 5); TEST_ASSERT(int(list.upper_ - list.nodes_) == 8); } void ListTest::testInsert1() { printMethod(TEST_FUNC); list.initialize(nodes, n); list.pushBack(nodes[5]); list.pushBack(nodes[8]); list.pushBack(nodes[3]); list.insert(nodes[7]); TEST_ASSERT(list.size_ == 4); TEST_ASSERT(int(list.front_ - list.nodes_) == 5); TEST_ASSERT(int(list.back_ - list.nodes_) == 3); TEST_ASSERT(int(list.lower_ - list.nodes_) == 3); TEST_ASSERT(int(list.upper_ - list.nodes_) == 8); TEST_ASSERT(list.isValid()); } void ListTest::testInsert2() { printMethod(TEST_FUNC); list.initialize(nodes, n); list.pushBack(nodes[5]); list.pushBack(nodes[8]); list.pushBack(nodes[3]); list.insert(nodes[2]); dumpList(); TEST_ASSERT(list.size_ == 4); TEST_ASSERT(int(list.front_ - list.nodes_) == 5); TEST_ASSERT(int(list.back_ - list.nodes_) == 3); TEST_ASSERT(int(list.lower_ - list.nodes_) == 2); TEST_ASSERT(int(list.upper_ - list.nodes_) == 8); TEST_ASSERT(list.isValid()); } void ListTest::testInsert3() { printMethod(TEST_FUNC); list.initialize(nodes, n); list.pushBack(nodes[3]); list.pushBack(nodes[5]); list.pushBack(nodes[8]); list.insert(nodes[2]); dumpList(); TEST_ASSERT(list.size_ == 4); TEST_ASSERT(int(list.front_ - list.nodes_) == 2); TEST_ASSERT(int(list.back_ - list.nodes_) == 8); TEST_ASSERT(int(list.lower_ - list.nodes_) == 2); TEST_ASSERT(int(list.upper_ - list.nodes_) == 8); TEST_ASSERT(list.isValid()); } void ListTest::testInsert4() { printMethod(TEST_FUNC); list.initialize(nodes, n); list.pushBack(nodes[5]); list.pushBack(nodes[8]); list.pushBack(nodes[3]); list.insert(nodes[9]); dumpList(); TEST_ASSERT(list.size_ == 4); TEST_ASSERT(int(list.front_ - list.nodes_) == 5); TEST_ASSERT(int(list.back_ - list.nodes_) == 3); TEST_ASSERT(int(list.lower_ - list.nodes_) == 3); TEST_ASSERT(int(list.upper_ - list.nodes_) == 9); TEST_ASSERT(list.isValid()); } void ListTest::testInsert5() { printMethod(TEST_FUNC); list.initialize(nodes, n); list.pushBack(nodes[3]); list.pushBack(nodes[5]); list.pushBack(nodes[7]); list.insert(nodes[9]); dumpList(); TEST_ASSERT(list.size_ == 4); TEST_ASSERT(int(list.front_ - list.nodes_) == 3); TEST_ASSERT(int(list.back_ - list.nodes_) == 9); TEST_ASSERT(int(list.lower_ - list.nodes_) == 3); TEST_ASSERT(int(list.upper_ - list.nodes_) == 9); TEST_ASSERT(list.isValid()); } /* * Print integer indices of nodes in a linked list. */ void ListTest::dumpList() { if (verbose() > 1 && list.front_ != 0) { Node<Data>* node = list.front_; while (node->next() != 0) { std::cout << int(node - list.nodes_) << std::endl; node = node->next(); } std::cout << int(node - list.nodes_) << std::endl; } } TEST_BEGIN(ListTest) TEST_ADD(ListTest, testInitialize) TEST_ADD(ListTest, testPushBack) TEST_ADD(ListTest, testPushFront) TEST_ADD(ListTest, testPopBack) TEST_ADD(ListTest, testInsertNext1) TEST_ADD(ListTest, testInsertNext2) TEST_ADD(ListTest, testInsertPrev1) TEST_ADD(ListTest, testInsertPrev2) TEST_ADD(ListTest, testRemove1) TEST_ADD(ListTest, testRemove2) TEST_ADD(ListTest, testRemove3) TEST_ADD(ListTest, testInsert1) TEST_ADD(ListTest, testInsert2) TEST_ADD(ListTest, testInsert3) TEST_ADD(ListTest, testInsert4) TEST_ADD(ListTest, testInsert5) TEST_END(ListTest) #endif
Markdown
UTF-8
1,992
3.015625
3
[ "MIT" ]
permissive
# TogglePvP v1.0 ## A Spigot Plugin to Toggle PvP per player. ## Commands * `/togglepvp [player] [on/off] <duration>` - Description: Toggles PvP on/off for a player, with an optional duration. * Example: `/togglepvp Worf2340 off 30m` would disable PvP for Worf2340 for 30m. * `/pvpstatus <player>` - Description: Checks whether a player has PvP protection, and how much longer the protection will apply if applicable. If no player is specified, the sender of the command will be checked. * `/pvplist` - Description: Lists all online PvP protected players. Names in green have permanent protection. Names in yellow have temporary protection, with the duration of the protection in parantheses. ## Permissions * `togglepvp.*`: Gives access to all /togglepvp commands. * `togglepvp.pvpstatus`: Allows players to check their own PvP protection status. * `togglepvp.pvpstatus.others`: Allows players to check other player's PvP protection status. * `togglepvp.pvplist`: Allows players to use /pvplist. * `togglepvp.togglepvp`: Necessary to allow players to use the /togglepvp command, depended on by further permission listed below. * `togglepvp.togglepvp.on`: Allows players to turn PvP on for themselves (disabling protection). * `togglepvp.togglepvp.off`: Allows players to turn PvP off for themselves (enabling protection). * `togglepvp.togglepvp.others.on`: Allows players to turn PvP on for other players (disabling protection). * `togglepvp.togglepvp.others.off`: Allows players to turn PvP off for other players (enabling protection). * `togglepvp.togglepvp.*`: Gives access to all /togglepvp commands. ## Features * Protects against normal PvP, spalsh potions of harming, and lingering potions of harming, and all projectiles. * Add protection for potions of weakness, slowness, and poison. * Warnings at 30m, 15m, 5m, and 1m for PvP protection expiration. * Keep PvP status when player's logout or the server restarts. ## Planned additions. * MySQL support?
Java
UTF-8
2,731
1.835938
2
[]
no_license
package com.kasite.core.serviceinterface.module.order.resp; import com.kasite.core.common.resp.AbsResp; /** * @author linjf * TODO */ public class RespQueryInHospitalCostType extends AbsResp{ private String date; private Integer fee; private String doctor; private String dept; private String deptStation; private String expenseTypeCode; private String expenseTypeName; /**单位**/ private String unit; /**单价**/ private Integer unitPrice; /**数量**/ private Integer objNumber; /**发票项目名称**/ private String invoiceItemName; /**规格**/ private String specifications; /** * @return the specifications */ public String getSpecifications() { return specifications; } /** * @param specifications the specifications to set */ public void setSpecifications(String specifications) { this.specifications = specifications; } /** * @return the unit */ public String getUnit() { return unit; } /** * @param unit the unit to set */ public void setUnit(String unit) { this.unit = unit; } /** * @return the unitPrice */ public Integer getUnitPrice() { return unitPrice; } /** * @param unitPrice the unitPrice to set */ public void setUnitPrice(Integer unitPrice) { this.unitPrice = unitPrice; } /** * @return the objNumber */ public Integer getObjNumber() { return objNumber; } /** * @param objNumber the objNumber to set */ public void setObjNumber(Integer objNumber) { this.objNumber = objNumber; } /** * @return the invoiceItemName */ public String getInvoiceItemName() { return invoiceItemName; } /** * @param invoiceItemName the invoiceItemName to set */ public void setInvoiceItemName(String invoiceItemName) { this.invoiceItemName = invoiceItemName; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public Integer getFee() { return fee; } public void setFee(Integer fee) { this.fee = fee; } public String getDoctor() { return doctor; } public void setDoctor(String doctor) { this.doctor = doctor; } public String getDept() { return dept; } public void setDept(String dept) { this.dept = dept; } public String getDeptStation() { return deptStation; } public void setDeptStation(String deptStation) { this.deptStation = deptStation; } public String getExpenseTypeCode() { return expenseTypeCode; } public void setExpenseTypeCode(String expenseTypeCode) { this.expenseTypeCode = expenseTypeCode; } public String getExpenseTypeName() { return expenseTypeName; } public void setExpenseTypeName(String expenseTypeName) { this.expenseTypeName = expenseTypeName; } }
C#
UTF-8
19,034
3.015625
3
[]
no_license
using System; namespace Lesson03 { class Ships { public string Shot(string str) { string result = null; return result; } static public string[,] GetField(out bool[,] bfld) { char letter = 'A'; int x = 11, y = 11; string[,] field = new string[y, x]; bool[,] boolField = new bool[12, 12]; for (int i = 0; i < field.GetLength(0); i++) { for (int j = 0; j < field.GetLength(1); j++) { if (i == 0) { if (j == 0) { field[i, j] = " "; boolField[i, j] = false; } else { field[i, j] = letter.ToString(); boolField[i, j] = false; letter++; } } else if (j == 0) { field[i, j] = i.ToString() + " "; boolField[i, j] = false; } else { field[i, j] = "O"; boolField[i, j] = true; } } } for (int i = boolField.GetLength(0) - 2; i < boolField.GetLength(0); i++) { for (int j = boolField.GetLength(1) - 2; j < boolField.GetLength(1); j++) { boolField[i, j] = false; } } boolField[10, 10] = true; field[10, 0] = "10 "; bfld = boolField; return field; } static public bool FindShipInRange(string[,] str, int[] pointer) { bool result = false; for (int i = pointer[0] - 1; (i <= pointer[0] + 1) & (i < str.GetLength(0)); i++) { for (int j = pointer[1] - 1; (j <= pointer[1] + 1) & (j < str.GetLength(1)); j++) { if (str[i, j] == "X") { result = true; } } } return result; } static public bool CanGo(string[,] str, bool[,] blfld, int pointerY, int pointerX, out string direction) { bool result = false; direction = null; bool[,] canMap = new bool[3, 3]; int[] pointer = { pointerY, pointerX }; if (FindShipInRange(str, pointer) == false) { for (int i = pointer[0] - 1, mapI = 0; i <= pointer[0] + 1; i++, mapI++) { for (int j = pointer[1] - 1, mapJ = 0; j <= pointer[1] + 1; j++, mapJ++) { canMap[mapI, mapJ] = blfld[i, j]; } } if (canMap[0, 0] & canMap[1, 0] & canMap[2, 0]) { direction = "Left"; result = true; } else if (canMap[0, 0] & canMap[0, 1] & canMap[0, 2]) { direction = "Up"; result = true; } else if (canMap[0, 2] & canMap[1, 2] & canMap[2, 2]) { direction = "Right"; result = true; } else if (canMap[2, 0] & canMap[2, 1] & canMap[2, 2]) { direction = "Down"; result = true; } else if (canMap[1, 1]) { direction = "Stop"; result = true; } else { result = false; } } return result; } static public int GetShipOne(ref string[,] str, ref bool[,] blfld) { int count = 0; int tryes = 0; bool[,] newblfld; Random num = new Random(); int pointerX = num.Next(1, 10); int pointerY = num.Next(1, 10); do { newblfld = blfld; pointerY = num.Next(1, 10); pointerX = num.Next(1, 10); if (CanGo(str, newblfld, pointerY, pointerX, out _)) { str[pointerY, pointerX] = "X"; for (int i = pointerY - 1; i <= pointerY + 1; i++) { for (int j = pointerX - 1; j <= pointerX + 1; j++) { newblfld[i, j] = false; } } count++; blfld = newblfld; } Console.Write("|"); if (tryes == 100) { return 0; } } while (count != 4); return 1; } static public int GetShipTwo(ref string[,] str, ref bool[,] blfld) { string direction; int count = 0; int tryes = 0; Random num = new Random(); int[] pointer = { num.Next(1, 10), num.Next(1, 10) }; do { int pointerY = num.Next(1, 10); int pointerX = num.Next(1, 10); if (CanGo(str, blfld, pointerY, pointerX, out direction) & (direction == "Up")) { if (CanGo(str, blfld, pointerY, pointerX, out _)) { str[pointerY - 1, pointerX] = "X"; str[pointerY, pointerX] = "X"; for (int i = pointerY - 2; i <= pointerY + 1; i++) { for (int j = pointerX - 1; j <= pointerX + 1; j++) { blfld[i, j] = false; } } } count++; } else if (CanGo(str, blfld, pointerY, pointerX, out direction) & (direction == "Down")) { if (CanGo(str, blfld, pointerY, pointerX, out _)) { str[pointerY, pointerX] = "X"; str[pointerY + 1, pointerX] = "X"; for (int i = pointerY - 1; i <= pointerY + 2; i++) { for (int j = pointerX - 1; j <= pointerX + 1; j++) { blfld[i, j] = false; } } } count++; } else if (CanGo(str, blfld, pointerY, pointerX, out direction) & (direction == "Left")) { if (CanGo(str, blfld, pointerY, pointerX - 1, out _)) { str[pointerY, pointerX - 1] = "X"; str[pointerY, pointerX] = "X"; for (int i = pointerY - 1; i <= pointerY + 1; i++) { for (int j = pointerX - 2; j <= pointerX + 1; j++) { blfld[i, j] = false; } } } count++; } else if (CanGo(str, blfld, pointerY, pointerX, out direction) & (direction == "Right")) { if (CanGo(str, blfld, pointerY, pointerX + 1, out _)) { str[pointerY, pointerX + 1] = "X"; str[pointerY, pointerX] = "X"; for (int i = pointerY - 1; i <= pointerY + 1; i++) { for (int j = pointerX - 1; j <= pointerX + 2; j++) { blfld[i, j] = false; } } } count++; } if (tryes == 100) { return 0; } } while (count != 3); return 1; } static public int GetShipThree(ref string[,] str, ref bool[,] blfld) { string direction; int count = 0; int tryes = 0; Random num = new Random(); int pointerX = num.Next(1, 10); int pointerY = num.Next(1, 10); do { pointerY = num.Next(1, 10); pointerX = num.Next(1, 10); if (CanGo(str, blfld, pointerY, pointerX, out direction) & (direction == "Up")) { if ((CanGo(str, blfld, pointerY - 1, pointerX, out direction)) & (direction == "Up")) { if (CanGo(str, blfld, pointerY - 2, pointerX, out direction)) { str[pointerY - 2, pointerX] = "X"; str[pointerY - 1, pointerX] = "X"; str[pointerY, pointerX] = "X"; for (int i = pointerY - 3; i <= pointerY + 1; i++) { for (int j = pointerX - 1; j <= pointerX + 1; j++) { blfld[i, j] = false; } } count++; } } } else if (CanGo(str, blfld, pointerY, pointerX, out direction) & (direction == "Down")) { if (CanGo(str, blfld, pointerY + 1, pointerX, out direction) & (direction == "Down")) { if (CanGo(str, blfld, pointerY + 2, pointerX, out direction)) { str[pointerY, pointerX] = "X"; str[pointerY + 1, pointerX] = "X"; str[pointerY + 2, pointerX] = "X"; for (int i = pointerY - 1; i <= pointerY + 3; i++) { for (int j = pointerX - 1; j <= pointerX + 1; j++) { blfld[i, j] = false; } } count++; } } } else if (CanGo(str, blfld, pointerY, pointerX, out direction) & (direction == "Left")) { if (CanGo(str, blfld, pointerY, pointerX - 1, out direction) & (direction == "Left")) { if (CanGo(str, blfld, pointerY, pointerX - 2, out direction)) { str[pointerY, pointerX - 2] = "X"; str[pointerY, pointerX - 1] = "X"; str[pointerY, pointerX] = "X"; for (int i = pointerY - 1; i <= pointerY + 1; i++) { for (int j = pointerX - 3; j <= pointerX + 1; j++) { blfld[i, j] = false; } } count++; } } } else if (CanGo(str, blfld, pointerY, pointerX, out direction) & (direction == "Right")) { if (CanGo(str, blfld, pointerY, pointerX + 1, out direction) & (direction == "Right")) { if (CanGo(str, blfld, pointerY, pointerX + 2, out direction)) { str[pointerY, pointerX + 2] = "X"; str[pointerY, pointerX + 1] = "X"; str[pointerY, pointerX] = "X"; for (int i = pointerY - 1; i <= pointerY + 1; i++) { for (int j = pointerX - 1; j <= pointerX + 3; j++) { blfld[i, j] = false; } } count++; } } } Console.Write("|"); if (tryes == 100) { return 0; } } while (count != 2); return 1; } static public int GetShipFour(ref string[,] str, ref bool[,] blfld) { string direction; int count = 0; int tryes = 0; Random num = new Random(); int pointerX = num.Next(1, 10); int pointerY = num.Next(1, 10); do { pointerY = num.Next(1, 10); pointerX = num.Next(1, 10); if (CanGo(str, blfld, pointerY, pointerX, out direction) & (direction == "Up")) { if ((CanGo(str, blfld, pointerY - 1, pointerX, out direction)) & (direction == "Up")) { if ((CanGo(str, blfld, pointerY - 2, pointerX, out direction)) & (direction == "Up")) { if (CanGo(str, blfld, pointerY - 3, pointerX, out direction)) { str[pointerY - 3, pointerX] = "X"; str[pointerY - 2, pointerX] = "X"; str[pointerY - 1, pointerX] = "X"; str[pointerY, pointerX] = "X"; for (int i = pointerY - 4; i <= pointerY + 1; i++) { for (int j = pointerX - 1; j <= pointerX + 1; j++) { blfld[i, j] = false; } } count++; } } } } else if (CanGo(str, blfld, pointerY, pointerX, out direction) & (direction == "Down")) { if (CanGo(str, blfld, pointerY + 1, pointerX, out direction) & (direction == "Down")) { if ((CanGo(str, blfld, pointerY + 2, pointerX, out direction)) & (direction == "Down")) { if (CanGo(str, blfld, pointerY + 3, pointerX, out direction)) { str[pointerY, pointerX] = "X"; str[pointerY + 1, pointerX] = "X"; str[pointerY + 2, pointerX] = "X"; str[pointerY + 3, pointerX] = "X"; for (int i = pointerY - 1; i <= pointerY + 4; i++) { for (int j = pointerX - 1; j <= pointerX + 1; j++) { blfld[i, j] = false; } } count++; } } } } else if (CanGo(str, blfld, pointerY, pointerX, out direction) & (direction == "Left")) { if (CanGo(str, blfld, pointerY, pointerX - 1, out direction) & (direction == "Left")) { if ((CanGo(str, blfld, pointerY, pointerX - 2, out direction)) & (direction == "Left")) { if (CanGo(str, blfld, pointerY, pointerX - 3, out direction)) { str[pointerY, pointerX - 3] = "X"; str[pointerY, pointerX - 2] = "X"; str[pointerY, pointerX - 1] = "X"; str[pointerY, pointerX] = "X"; for (int i = pointerY - 1; i <= pointerY + 1; i++) { for (int j = pointerX - 4; j <= pointerX + 1; j++) { blfld[i, j] = false; } } count++; } } } } else if (CanGo(str, blfld, pointerY, pointerX, out direction) & (direction == "Right")) { if (CanGo(str, blfld, pointerY, pointerX + 1, out direction) & (direction == "Right")) { if ((CanGo(str, blfld, pointerY, pointerX + 2, out direction)) & (direction == "Right")) { if (CanGo(str, blfld, pointerY, pointerX + 3, out direction)) { str[pointerY, pointerX + 3] = "X"; str[pointerY, pointerX + 2] = "X"; str[pointerY, pointerX + 1] = "X"; str[pointerY, pointerX] = "X"; for (int i = pointerY - 1; i <= pointerY + 1; i++) { for (int j = pointerX - 1; j <= pointerX + 4; j++) { blfld[i, j] = false; } } count++; } } } } Console.Write("|"); if (tryes == 100) { return 0; } } while (count != 1); return 1; } } }
Java
UTF-8
3,340
2.171875
2
[]
no_license
package com.infomancers.collections.yield.asmbase; import com.infomancers.collections.yield.Yielder; import com.infomancers.collections.yield.asm.TypeDescriptor; import org.objectweb.asm.Opcodes; /** * Copyright (c) 2007, Aviad Ben Dov * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * 3. Neither the name of Infomancers, Ltd. nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /** * Utility class for doing redundant checks on fields, variables and methods while * visiting different classes. */ public final class Util { public static boolean isYieldNextCoreMethod(String name, String desc) { return "yieldNextCore".equals(name) && "()V".equals(desc); } public static boolean isInvokeYieldReturn(int opcode, String name, String desc) { return opcode == Opcodes.INVOKEVIRTUAL && "yieldReturn".equals(name) && "(Ljava/lang/Object;)V".equals(desc); } public static boolean isInvokeYieldBreak(int opcode, String name, String desc) { return opcode == Opcodes.INVOKEVIRTUAL && "yieldBreak".equals(name) && "()V".equals(desc); } public static boolean isYielderClassName(String name) { return "com/infomancers/collections/yield/Yielder".equals(name); } public static int offsetForDesc(String desc) { for (int i = 0; i < TypeDescriptor.values().length; i++) { String cur = TypeDescriptor.values()[i].getDesc(); if (cur.equals(desc)) { return i; } } return -1; } public static TypeDescriptor typeForOffset(int offset) { return TypeDescriptor.values()[offset]; } public static boolean isYielderInHierarchyTree(String className) { String name = className.replace('/', '.'); try { return Yielder.class.isAssignableFrom(Class.forName(name)); } catch (ClassNotFoundException e) { e.printStackTrace(); return false; } } }
C
UTF-8
1,208
4.09375
4
[]
no_license
#include "linkedList.h" #include <stdlib.h> /* Linked list data structure (Singly linked list). Used to store the tasks which are currently waiting. */ /* Initialisation function. */ void linked_list_init(linked_list_t* linked_list) { linked_list->head = NULL; } /* Returns the head of the linked list and updates the head pointer. When used for the wait list, the item returned is a task. */ void* linked_list_remove(linked_list_t* linked_list) { linked_list_element_t* oldHead = linked_list->head; if (oldHead == NULL) { return NULL; } linked_list->head = oldHead->next; void* item = oldHead->item; free(oldHead); return item; } /* Appends the new item to the end of the list. */ void linked_list_append(linked_list_t* linked_list, void* newItem) { linked_list_element_t* newElement = malloc(sizeof(linked_list_element_t)); newElement->item = newItem; newElement->next = NULL; if (linked_list->head == NULL) { linked_list->head = newElement; } else { linked_list_element_t* currentElement = linked_list->head; while (currentElement->next != NULL) { currentElement = currentElement->next; } currentElement->next = newElement; } }
C#
UTF-8
1,887
3.1875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Markdown { public static class TagsConverter { public static string ConvertToNewSpecifications(StringBuilder sourceStrings, IReadOnlyCollection<TagSpecification> currentSpecifications, IReadOnlyCollection<TagSpecification> newSpecifications, IEnumerable<TagsPair> tagsPairs) { var sortedTags = GetTagsFromPairs(tagsPairs); var newString = new StringBuilder(); var currentIndex = 0; foreach (var tag in sortedTags) { newString.Append(sourceStrings, currentIndex, tag.PositionInText - currentIndex); var newTagSpecification = newSpecifications.FirstOrDefault(t => t.TagType == tag.TagType); if (newTagSpecification == null) { throw new ArgumentException($"New specifications does not support tag type {tag.TagType}"); } var newTag = tag.PositionType == PositionType.OpeningTag ? newTagSpecification.StartTag : newTagSpecification.EndTag; newString.Append(newTag); currentIndex = tag.PositionInText + tag.Value.Length; } if (sourceStrings.Length - currentIndex > 0) newString.Append(sourceStrings, currentIndex, sourceStrings.Length - currentIndex); return newString.ToString(); } private static IEnumerable<Tag> GetTagsFromPairs(IEnumerable<TagsPair> tagsPairs) { var sortedTags = new SortedList<int, Tag>(); foreach (var pair in tagsPairs) { sortedTags.Add(pair.StartPosition, pair.StartTag); sortedTags.Add(pair.EndPosition, pair.EndTag); } return sortedTags.Values; } } }
TypeScript
UTF-8
560
2.75
3
[ "MIT" ]
permissive
import { delay } from '../utils'; export interface UserState { dataSource: { name: string; }; todos: number; auth: boolean; } const model = { state: { dataSource: { name: '', }, todos: 0, auth: false, }, reducers: { setTodos(state: UserState, todos: number) { state.todos = todos; }, }, effects: () => ({ async login() { await delay(1000); this.setState({ dataSource: { name: 'Alvin', }, auth: true, }); }, }), }; export default model;
Java
UTF-8
10,358
2.265625
2
[]
no_license
import java.util.concurrent.*; import java.util.Random; import java.math.BigInteger; import java.math.BigDecimal; import java.awt.Graphics; import java.util.concurrent.atomic.AtomicInteger; import java.awt.Color; import java.awt.Graphics; class Celular_automata implements Runnable{ int[] anterior_,siguiente_,regla_; char[] base_k; Object lock_; private int inicio_,fin_,p; public int Ncelulas_,vecindad_,Nestados_; public boolean condicionBarrera; static AtomicInteger Hamming_ = new AtomicInteger(), cuatro_por_generacion_ = new AtomicInteger(); static CyclicBarrier barrera = new CyclicBarrier(4); AtomicInteger[] CelulasEstado_,Celula7Estado_; Celular_automata(int inicio,int fin,Object cerrojo,int[] primera_generacion, int[] iesima_generacion,int Ncells,int r, int k,boolean con,int[] reg,AtomicInteger[] CellsEstado, AtomicInteger[] Celula7Estado) { anterior_ = primera_generacion; siguiente_ = iesima_generacion; Ncelulas_ = Ncells; vecindad_ = r; Nestados_ = k; condicionBarrera = con; Celula7Estado_ = Celula7Estado; CelulasEstado_ = CellsEstado; regla_ = reg; base_k = new char[2*r+1]; inicio_ = inicio; fin_ = fin; lock_ = cerrojo; } public void run(){ for(int i = inicio_ ; i<=fin_ - 1 ; ++i) { int p = 0; if((i-vecindad_)>=0 && (i+vecindad_)<Ncelulas_) { for(int y = i-vecindad_ ; y <= i+vecindad_ ; ++y) { base_k[p]=Character.forDigit(anterior_[y],Nestados_); ++p; } siguiente_[i] = regla_[Integer.parseInt(String.valueOf(base_k),Nestados_)]; } else if(condicionBarrera) { if(i-vecindad_<0 && i+vecindad_<Ncelulas_) { for(int k = Ncelulas_-(vecindad_-i);k<Ncelulas_;++k) { base_k[p]=Character.forDigit(anterior_[k],Nestados_); ++p; } for(int w = 0 ; w<=(i+vecindad_) ; ++w) { base_k[p]=Character.forDigit(anterior_[w],Nestados_); ++p; } siguiente_[i] = regla_[Integer.parseInt(String.valueOf(base_k),Nestados_)]; } else if(i-vecindad_ >= 0 && i+vecindad_ >= Ncelulas_) { for(int z = i-vecindad_ ; z < Ncelulas_ ; ++z) { base_k[p] = Character.forDigit(anterior_[z],Nestados_); ++p; } for(int v = 0; v<(i+vecindad_)%Ncelulas_ ; ++v) { base_k[p] = Character.forDigit(anterior_[v],Nestados_); ++p; } siguiente_[i] = regla_[Integer.parseInt(String.valueOf(base_k),Nestados_)]; } } //probabilidades entropia espacial try{ switch(siguiente_[i]){ case 0: CelulasEstado_[0].incrementAndGet(); if(i==7) Celula7Estado_[0].incrementAndGet(); break; case 1: CelulasEstado_[1].incrementAndGet(); if(i==7) Celula7Estado_[1].incrementAndGet(); break; case 2: CelulasEstado_[2].incrementAndGet(); if(i==7) Celula7Estado_[2].incrementAndGet(); break; case 3: CelulasEstado_[3].incrementAndGet(); if(i==7) Celula7Estado_[3].incrementAndGet(); break; case 4: CelulasEstado_[4].incrementAndGet(); if(i==7) Celula7Estado_[4].incrementAndGet(); break; case 5: CelulasEstado_[5].incrementAndGet(); if(i==7) Celula7Estado_[5].incrementAndGet(); break; default: break; } }catch(IndexOutOfBoundsException e){System.out.println("Se han excedido los limites de Celular_automata::CelulasEstado_");} //distancia de hamming interconfiguracion if(siguiente_[i] != anterior_[i]) Hamming_.incrementAndGet(); } try{ barrera.await(); }catch(BrokenBarrierException e){ e.getMessage(); } catch(InterruptedException e){ e.getMessage(); } for(int j = inicio_ ; j <=fin_ - 1 ; ++j) { anterior_[j] = siguiente_[j]; } try{ barrera.await(); }catch(BrokenBarrierException e){ e.getMessage(); } catch(InterruptedException e){ e.getMessage(); } } public static void main(String[] args) throws InterruptedException{ } } class ca1DSim{ boolean condicionFront; int vecindad,Nestados,Ncelulas,tamRegla,Ngeneraciones; public int[] primeraGen,iesimaGen,regla; private int nucleos = Runtime.getRuntime().availableProcessors(); AtomicInteger[] CelulasEstado,Celula7Estado; ca1DSim(int cells, int[] primGen, int r, int k, boolean conFront,int idRegla) { Ngeneraciones = 0; Ncelulas = cells; vecindad = r; Nestados = k; condicionFront = conFront; tamRegla = (int)Math.pow( (int)k,(int)(2*r + 1)*(k-1) ); regla = new int[tamRegla]; primeraGen = primGen; iesimaGen = new int[Ncelulas]; creaRegla(idRegla); CelulasEstado = new AtomicInteger[Nestados]; Celula7Estado = new AtomicInteger[Nestados]; for(int i=0 ; i<Nestados ; ++i) { CelulasEstado[i]=new AtomicInteger(0); Celula7Estado[i]=new AtomicInteger(0); } } public void creaRegla(int idReg) { for(int j = 0; j<=tamRegla-1 ; ++j) { regla[j] = idReg%Nestados; idReg = (int)idReg/Nestados; } } public void nextGen() { ++Ngeneraciones; int ventana = Ncelulas/nucleos; int inicio = 0, fin = ventana; Object cerrojo = new Object(); Celular_automata.Hamming_ = new AtomicInteger(0);//la distancia de hamming es entre dos configuraciones no entre todas las generaciones generadas ThreadPoolExecutor ejecutor = new ThreadPoolExecutor(nucleos,nucleos,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()); for(int i = 0; i<=nucleos-1 ; ++i) { ejecutor.execute(new Celular_automata(inicio,fin,cerrojo,primeraGen,iesimaGen, Ncelulas,vecindad,Nestados,condicionFront,regla,CelulasEstado,Celula7Estado)); inicio += ventana; fin += ventana; } try{ ejecutor.shutdown(); ejecutor.awaitTermination(1L,TimeUnit.DAYS); }catch(InterruptedException e){} } public double probabilidadCelulaSeaEstado(int i) { try{ //System.out.print("CelulasTotales: "+Ncelulas+"CelulasEstado"+i+": "+CelulasEstado[i]); return (double)CelulasEstado[i].get()/(double)(Ncelulas*Ngeneraciones); }catch(IndexOutOfBoundsException e){ System.out.println("Se han excedido los límites del array ca1DSim::CelulasEstado"); return 0.0; } } public double entropia_espacial() { double entropia=0; for(int i=0 ; i<Nestados ; ++i) { double p = probabilidadCelulaSeaEstado(i); if(p!=0) entropia += p*(Math.log(p)/Math.log(Nestados)); } return (-1)*entropia; } public int distanciaHamming() { return Celular_automata.Hamming_.intValue(); } public double probabilidad_cell7(int estado_i) { try{ return (double)Celula7Estado[estado_i].get()/(double)(Ngeneraciones); }catch(IndexOutOfBoundsException e){ System.out.println("Se han excedido los límites del array ca1DSim::CelulasEstado"); return 0.0; } } public double entropia_temporalCell7() { double entropia = 0; for(int i=0 ; i<Nestados ; ++i) { double p = probabilidad_cell7(i); if(p!=0) entropia += p*(Math.log(p)/Math.log(Nestados)); } return (-1)*entropia; } //filtro /*public static void main(String[] args) { int[] estadoInicial_ = new int[1000]; BigInteger semilla_ = new BigInteger("5"), m_ = new BigInteger("2"), sem = new BigInteger("0"); randomGenerator rand = new randomGenerator(); BigDecimal entropia=new BigDecimal("0"),hamming=new BigDecimal("0"); BigDecimal cero99 = new BigDecimal("0.99"),cero90=new BigDecimal("0.9"),cuatromil=new BigDecimal("4000"); for(int i = 0 ; i <= 1000 - 1 ; ++i) { semilla_ = rand.fishman_moore1(semilla_); sem = semilla_.mod(m_); estadoInicial_[i] = sem.intValue(); } ca1DSim CelularAutomata; for(int i =1 ; i<256 ; ++i) { CelularAutomata = new ca1DSim(1000,estadoInicial_,1,2,false,i); entropia=new BigDecimal("0");hamming=new BigDecimal("0"); for(int j=0 ; j<4000 ;++j) { CelularAutomata.nextGen(); hamming = hamming.add(BigDecimal.valueOf((double)CelularAutomata.distanciaHamming())); entropia = entropia.add(BigDecimal.valueOf(CelularAutomata.entropia_espacial())); } entropia = entropia.divide(cuatromil); hamming = hamming.divide(cuatromil); //System.out.println("Entropia espacial:"+entropia.divide(new BigDecimal("4000"))+" Entropia temporal:" // +CelularAutomata.entropia_temporalCell7()+" Hamming: "+hamming.divide(new BigDecimal("4000"))); if(entropia.compareTo(cero99)>0 && hamming.compareTo(cero90)>0 && CelularAutomata.entropia_temporalCell7()>0.9) System.out.println(i); } }*/ //Codificación public static void main(String[] args) { String cadena=new String("7yÕ.EÉx"); String[] bins=new String[cadena.length()]; for(int i=0;i<cadena.length();++i) { char c=cadena.charAt(i); bins[i]=Integer.toBinaryString(c); while(bins[i].length()<8) { bins[i]="0"+bins[i]; } } int[] firstGen=new int[100]; randomGenerator rand=new randomGenerator(); BigInteger seed=new BigInteger("3"),dos=new BigInteger("2"); for(int i=0;i<100;++i) { seed=rand.fishman_moore1(seed); BigInteger s=seed.mod(dos); firstGen[i]=s.intValue(); } ca1DSim cellAutom = new ca1DSim(100,firstGen,1,2,true,90); char[] character = new char[8]; String[] cifrante = new String[cadena.length()]; for(int i=0;i<cadena.length()*8; ++i) { character[i%8]=(char)(cellAutom.primeraGen[7]+48); if(i%8 == 7) { cifrante[(int)(i/8)]=new String(character); } cellAutom.nextGen(); } String[] cifrada=new String[cadena.length()]; char[] aux=new char[8]; for(int i=0;i<cadena.length();++i) { for(int j=0;j<8;++j) { if(bins[i].charAt(j)!=cifrante[i].charAt(j)) aux[j]=(char)1+48; else aux[j]=(char)0+48; } cifrada[i]=new String(aux); } char[] aux2=new char[cadena.length()]; for(int i=0 ; i<cadena.length() ;++i) { aux2[i]+=(char)Integer.parseInt(cifrada[i],2); } String encrypted=new String(aux2); System.out.println(encrypted); } }
JavaScript
UTF-8
1,638
3.671875
4
[]
no_license
/* * @lc app=leetcode id=1138 lang=javascript * * [1138] Alphabet Board Path * * https://leetcode.com/problems/alphabet-board-path/description/ * * algorithms * Medium (51.51%) * Likes: 568 * Dislikes: 130 * Total Accepted: 35.5K * Total Submissions: 68.2K * Testcase Example: '"leet"' * * On an alphabet board, we start at position (0, 0), corresponding to * character board[0][0]. * * Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown * in the diagram below. * * * * We may make the following moves: * * * 'U' moves our position up one row, if the position exists on the board; * 'D' moves our position down one row, if the position exists on the * board; * 'L' moves our position left one column, if the position exists on the * board; * 'R' moves our position right one column, if the position exists on the * board; * '!' adds the character board[r][c] at our current position (r, c) to the * answer. * * * (Here, the only positions that exist on the board are positions with letters * on them.) * * Return a sequence of moves that makes our answer equal to target in the * minimum number of moves.  You may return any path that does so. * * * Example 1: * Input: target = "leet" * Output: "DDR!UURRR!!DDD!" * Example 2: * Input: target = "code" * Output: "RR!DDRR!UUL!R!" * * * Constraints: * * * 1 <= target.length <= 100 * target consists only of English lowercase letters. * */ // @lc code=start /** * @param {string} target * @return {string} */ var alphabetBoardPath = function(target) { }; // @lc code=end
Java
UTF-8
891
3.390625
3
[]
no_license
package Cap5; public class Ex5_24Diamond { public static void main(String[] args) { int counter2 = 1; for(int counter = 1; counter < 5; ++counter) { for(int space = 5; space > counter; --space) { System.out.print(" "); } for(int asterisk = 1; asterisk <= counter2; ++asterisk) { System.out.print("*"); } for(int space = 5; space > counter; --space) { System.out.print(" "); } counter2 += 2; System.out.println(); } for(int counter = 5; counter <= 10; ++counter) { for(int space = 5; space < counter; ++space) { System.out.print(" "); } for(int asterisk = 1; asterisk <= counter2; ++asterisk) { System.out.print("*"); } for(int space = 5; space < counter; ++space) { System.out.print(" "); } counter2 -= 2; System.out.println(); } } }
PHP
UTF-8
1,252
2.65625
3
[]
no_license
<?php include "connection.php"; session_start(); $email = ""; $password = ""; if($_SERVER["REQUEST_METHOD"]=="POST"){ $email = $connection->real_escape_string($_POST['email']); $password = $connection->real_escape_string($_POST['password']); $hashedpassword = sha1($password); $sql = "SELECT * FROM user WHERE email = ? AND password = ?"; $stmt=$connection->prepare($sql); $stmt->bind_param("ss", $email, $hashedpassword); $stmt->execute(); $result = $stmt->get_result(); $num_of_rows = $result->num_rows; if($num_of_rows > 0){ while($row = $result->fetch_assoc()) { $_SESSION['fname'] = $row["fname"]; $_SESSION['lname'] = $row["lname"]; $_SESSION['email'] = $email; $_SESSION['password'] = $hashedpassword; header("Location: ./Home.php"); } } else{ $message = "Username and/or Password incorrect.\\nTry again."; echo "<script type='text/javascript'>alert('$message');</script>"; header("Location: ./Login.php"); } $stmt->close(); } else{ header("Location: ./Login.php"); } $connection->close(); ?>
Java
UTF-8
1,009
2.390625
2
[]
no_license
/* package com.panda.exception; import com.panda.common.util.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; */ /** * 类功能简述: * 类功能详述: * * @author fanxb * @date 2019/3/19 18:12 *//* @RestControllerAdvice public class ExceptionHandle { private static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); @ExceptionHandler(Exception.class) public Result handleException(Exception e) { CustomException ce; if (e instanceof CustomException) { logger.error("捕获到自定义错误:{}", e.getMessage(), e); ce = (CustomException) e; } else { logger.error("捕获到意外错误:{}", e.getMessage(), e); ce = new CustomException("服务器异常"); } return new Result(ce.getCode(), ce.getMessage(), null); } } */
Java
UTF-8
1,257
3.15625
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 datejunit; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * * @author tue51138 */ public class theDate { final int day; final int month; final int year; theDate(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } public void printDate() { System.out.println(day + "-" + month + "-" + year); } public int getday() { return this.day; } public int getmonth() { return this.month; } public int getyear() { return this.year; } public int totalDays(theDate newDate) { int dateDif = newDate.getday(); int monthDif = newDate.getmonth() * 30; int yearDif = newDate.getyear() * 365; int totalDays; totalDays = dateDif + monthDif + yearDif; int d1Days; d1Days = (this.day) + (this.month * 30) + (this.year * 365); return Math.abs(d1Days - totalDays); } }
Swift
UTF-8
1,136
3.140625
3
[]
no_license
// // ShortestPathQ1334.swift // Algorithms // // Created by Uji Saori on 2021-04-18. // import Foundation class Solution { func findTheCity(_ n: Int, _ edges: [[Int]], _ distanceThreshold: Int) -> Int { let inf = 10001 var d = [[Int]](repeating: [Int](repeating: inf, count: n), count: n) for edge in edges { var u = edge[0] var v = edge[1] var w = edge[2] d[u][v] = w d[v][u] = w } for k in 0..<n { for i in 0..<n { for j in 0..<n { d[i][j] = min(d[i][j], d[i][k] + d[k][j]) } } } var neighbor = 0 var min = (node: 0, neighbor: n) for i in 0..<n { neighbor = 0 for j in 0..<n { if i == j { continue } if d[i][j] <= distanceThreshold { neighbor += 1 } } if neighbor <= min.neighbor { min = (node: i, neighbor: neighbor) } } return min.node } }
C#
UTF-8
3,018
2.53125
3
[]
no_license
using System; using System.Collections.Generic; using RegType = MTUComm.MemoryMap.MemoryMap.RegType; namespace MTUComm.MemoryMap { public class MemoryRegisterDictionary { Dictionary<RegType,dynamic> dictionary; public MemoryRegisterDictionary () { this.dictionary = new Dictionary<RegType,dynamic> (); this.dictionary.Add ( RegType.INT, new List<MemoryRegister<int >> () ); this.dictionary.Add ( RegType.UINT, new List<MemoryRegister<uint >> () ); this.dictionary.Add ( RegType.ULONG, new List<MemoryRegister<ulong >> () ); this.dictionary.Add ( RegType.BOOL, new List<MemoryRegister<bool >> () ); this.dictionary.Add ( RegType.CHAR, new List<MemoryRegister<char >> () ); this.dictionary.Add ( RegType.STRING, new List<MemoryRegister<string>> () ); } public void AddElement<T> ( MemoryRegister<T> register ) { switch ( Type.GetTypeCode ( typeof ( T ) ) ) { case TypeCode.Int32 : this.dictionary[ RegType.INT ].Add ( register ); break; case TypeCode.UInt32 : this.dictionary[ RegType.UINT ].Add ( register ); break; case TypeCode.UInt64 : this.dictionary[ RegType.ULONG ].Add ( register ); break; case TypeCode.Boolean: this.dictionary[ RegType.BOOL ].Add ( register ); break; case TypeCode.Char : this.dictionary[ RegType.CHAR ].Add ( register ); break; case TypeCode.String : this.dictionary[ RegType.STRING ].Add ( register ); break; } } public List<MemoryRegister<int>> GetElements_Int () { return this.dictionary[ RegType.INT ]; } public List<MemoryRegister<uint>> GetElements_UInt () { return this.dictionary[ RegType.UINT ]; } public List<MemoryRegister<ulong>> GetElements_ULong () { return this.dictionary[ RegType.ULONG ]; } public List<MemoryRegister<bool>> GetElements_Bool () { return this.dictionary[ RegType.BOOL ]; } public List<MemoryRegister<char>> GetElements_Char () { return this.dictionary[ RegType.CHAR ]; } public List<MemoryRegister<string>> GetElements_String () { return this.dictionary[ RegType.STRING ]; } public List<dynamic> GetAllElements () { List<dynamic> list = new List<dynamic> (); list.AddRange ( this.dictionary[ RegType.INT ] ); list.AddRange ( this.dictionary[ RegType.UINT ] ); list.AddRange ( this.dictionary[ RegType.ULONG ] ); list.AddRange ( this.dictionary[ RegType.BOOL ] ); list.AddRange ( this.dictionary[ RegType.CHAR ] ); list.AddRange ( this.dictionary[ RegType.STRING ] ); return list; } } }
Python
UTF-8
4,843
3.765625
4
[]
no_license
#!/usr/bin/python # -*- coding: iso-8859-15 -*- import os, sys # Quiz lists: quiz_level =[ "easy", "intermediate", "hard"] quiz_q = [" 3 + 5 = __1__ | 3*5= __2__ | 4/2 = __3__ | 5*4= __4__", "(2+4)*10= __1__ | (0+1)*100= __2__ | (3+6)*10=__3__ | (7*8)+5= __4__ " , "9-3 / 1/3 + 1 =__1__ | (3 + 3 * 3 – 3 + 3) =__2__ | (7+7 / 7+7 * 7-7) =__3__ | 6^2 / 2(3) + 4 = __4__ "] quiz_answers=[[8,15,2,20],[60, 100,90, 61],[1,12,50,58]] parts_of_speech1=["__1__","__2__", "__3__", "__4__" ] class style: #code Source: https://stackoverflow.com/questions/24834876/how-can-i-make-text-bold-in-python BOLD = '\033[1m' END = '\033[0m' def text_format(a): #Adding lines to text return style.BOLD + "\n" + a + "\n" + style.END #I used the same functions explained in lesson 13 ( Mad Libs Continued ) def word_in_pos(word, parts_of_speech): """ Checking each word in list of strings to see if it matches the part of speech we want to replace The inputs are words in string list and parts of speech list """ for pos in parts_of_speech: if pos in word: return pos return None def Check_input(u_input, replacement, correct_answer, word, l): """ This function will check the user input to make sure it is an integer also it will check if it matches the correct answer Inputs: user input - replacement (matching part of speech ) and word to be replaced - Replaced string list to be updated """ try: user_input = int(u_input) except: #In case of value error print text_format("Please, enter a number!") return False else: if user_input != correct_answer: print text_format("Incorrect answer.. Try again!") return False else: print text_format("Correct answer!") word = word.replace(replacement, str(user_input)) l.append(word) return True def start_program(user_input, level, questions, answers): """ This function will start the program, it takes the following inputs: user choice - quiz level - questions and answers to match them with the chosen quiz level. It validate the input ( if it exist in the list of levels) and return the needed values to start the quiz. """ if user_input != None: if user_input in level: #Matching the user input with the correct quiz level string u_input = level.index(user_input1) Question_str = questions[u_input] Answers = answers[u_input] return Question_str , Answers else: #In case user input is incorrect print ("Invalid Input") return False def do_quiz(q_str, parts_of_speech, correct_answers): """ Function to perform the conditions of the quiz Its inputs are: the selected question str- list of parts of speech we want to replace and the correct answers for comparison It checks every word in the question string list, if it matches a "part of speech" it will evaluate the entered answer and replace it when it is correct. Its output: the new str with the correct answers. I started with the same concepts explained in lesson 13 and built upon it """ print text_format(" List of correct answers" + str(correct_answers)) replaced= [] q_str = q_str.split() for word in q_str: replacement = word_in_pos(word, parts_of_speech) while replacement != None: index= parts_of_speech.index(replacement) #returns index number for comparing user input with the #correct answer correct_answer = correct_answers[index] # For displaying the new string of quiz with the entered answers #starting_point= len(replaced) new_str = replaced + q_str[len(replaced): ] print " ".join(new_str) #User input user_input2 = raw_input("Your answer for "+ replacement + " is... " ) if Check_input(user_input2, replacement, correct_answer, word, replaced) == True: break else: replaced.append(word) replaced = " ".join(replaced) return text_format("You have just completed the following string:")+ text_format(replaced) +text_format("Thank you for completing the quiz :)") while True: #returning user_input1 in lowercase letters user_input1= (raw_input("Hello user, please select a quiz level : easy - intermediate - hard")).lower() if start_program(user_input1, quiz_level, quiz_q, quiz_answers): Question_str , Answers = start_program(user_input1, quiz_level, quiz_q, quiz_answers) print do_quiz(Question_str, parts_of_speech1, Answers) break
JavaScript
UTF-8
257
3.5
4
[]
no_license
// Set default value using || Operator var fullName = function (firstName, lastName) { var firstName = firstName || 'john'; var lastName = lastName || 'smith'; console.log(firstName + ' ' +lastName); } fullName('rahul', 'hirve'); fullName();
Java
UTF-8
5,241
2.9375
3
[]
no_license
package be.robbevanherck.javafraggenescan.transitions; import be.robbevanherck.javafraggenescan.entities.*; /** * Represents a transition to an M (forward or reverse) state */ public abstract class MatchTransition extends Transition { /** * Create a new MatchTransition * * @param toState The state to which this transition goes */ public MatchTransition(HMMState toState) { super(toState); } @Override public PathProbability calculatePathProbability(ViterbiStep currentStep) { ViterbiStep previous = currentStep.getPrevious(); HMMParameters parameters = currentStep.getParameters(); /* FROM M STATE */ PathProbability bestValue = getProbabilityFromMatch(parameters, previous, getCodonEndingAtT(currentStep)); /* FROM M STATE, GOING THROUGH (numD) D STATES */ bestValue = PathProbability.max(bestValue, getProbabilityThroughDeletions(parameters, previous, getCodonEndingAtT(currentStep))); /* FROM I STATE */ bestValue = PathProbability.max(bestValue, getProbabilityFromInsertion(parameters, currentStep)); /* FROM START STATE */ bestValue = PathProbability.max(bestValue, getProbabilityFromStart(currentStep, getCodonEndingAtT(currentStep))); return bestValue; } /** * Calculate the probability of going from an I' state to the destination M' state * @param parameters The parameters for HMM * @param currentStep The current Viterbi step * @return The probability */ protected PathProbability getProbabilityFromInsertion(HMMParameters parameters, ViterbiStep currentStep) { ViterbiStep previous = currentStep.getPrevious(); // This is the codon that is present if you ignore the insertions Triple<AminoAcid> codonWithoutInsertions = new Triple<>( AminoAcid.INVALID, AminoAcid.INVALID, AminoAcid.INVALID ); Pair<AminoAcid> aminoAcidBeforeInsert = currentStep.getAminoAcidsBeforeInsert(HMMState.insertStateForMatching(toState)); // Depending on what state we're going to find how the codon would have looked if ((aminoAcidBeforeInsert != null) && (toState == HMMState.MATCH_3 || toState == HMMState.MATCH_6)) { codonWithoutInsertions = aminoAcidBeforeInsert.append(currentStep.getInput()); } else if ((aminoAcidBeforeInsert != null) && (toState == HMMState.MATCH_2 || toState == HMMState.MATCH_5)) { codonWithoutInsertions = new Triple<>( aminoAcidBeforeInsert.getSecondValue(), currentStep.getInput(), currentStep.getNextInput() ); } HMMState insertionState = HMMState.insertStateForMatching(toState); // If it's a stop codon, we can't be in an M' state, but should be in an END' state if (!isCorrectStopCodon(codonWithoutInsertions)) { double probability = previous.getProbabilityFor(insertionState) * // Probability to be in state Ix at t-1 parameters.getInnerTransitionProbability(HMMInnerTransition.INSERT_MATCH) * 0.25; // Probability for transmission + emission (=0.25) for I -> M return new PathProbability(insertionState, probability); } return new PathProbability(insertionState, 0); } /** * Test if the triple is the right (forward/reverse) stop codon * @param tripleToCheck The codon to check * @return true if this can be a stop codon, false otherwise */ protected abstract boolean isCorrectStopCodon(Triple<AminoAcid> tripleToCheck); /** * Calculate the probability to go from an M state to the target M state * @param parameters The HMM parameters * @param previous The previous step * @param codonEndingAtT The codon starting at t-2 and ending at t * @return The probability */ // As long as there is no generified function to get emissions, this stays abstract protected abstract PathProbability getProbabilityFromMatch(HMMParameters parameters, ViterbiStep previous, Triple<AminoAcid> codonEndingAtT); /** * Calculate the probability of going from an M state, through some amount of D states to the destination M state * @param parameters The parameters for HMM * @param previous The previous Viterbi step * @param codonEndingAtT The coding starting at t-2 to t * @return The probability */ // As long as there is no generified function to get emissions, this stays abstract protected abstract PathProbability getProbabilityThroughDeletions(HMMParameters parameters, ViterbiStep previous, Triple<AminoAcid> codonEndingAtT); /** * Calculate the probability of going from a Start state to the destination M state * @param currentStep The current Viterbi step * @param codonEndingAtT The coding starting at t-2 to t * @return The probability */ // As long as there is no generified function to get emissions, this stays abstract protected abstract PathProbability getProbabilityFromStart(ViterbiStep currentStep, Triple<AminoAcid> codonEndingAtT); }
C++
UTF-8
1,154
3
3
[]
no_license
/************************************************************** NAME : SWATI BOTUWAR Z-ID : Z1828087 CSCI/689/Section 1 TA NAME : NITHIN DEVANG ASSIGNMENT NUMBER : 2 DUE DATE : WEDNESDAY, 8th FEBRUARY 2017 ************************************************************/ /** This function contains the formula for calculating tax value of a given income for Married Filing Jointly status category. */ float Married_filing_jointly( float income) { float tax; if( income >= 0 && income < 18550) { tax = 0.1 * income ; } else if (income >= 18550 && income < 75300 ) { tax = 1855.00 + 0.15 * (income - 18550); } else if (income >= 75300 && income < 151900) { tax = 10367.50 + 0.25 * (income - 75300); } else if (income >= 151900 && income < 231450) { tax = 29517.50 + 0.28 * (income - 151900); } else if(income >= 231450 && income < 413350) { tax = 51791.50 + 0.33 * (income - 231450); } else if( income >= 413350 && income < 466950) { tax = 111818.50 + 0.35 * (income - 413350); } else if (income >= 466950) { tax = 130578.50 + 0.396 * (income - 466950); } return tax ; }
Java
UTF-8
540
2.078125
2
[]
no_license
package com.etap.production.metier; import com.etap.production.entity.Lieu; import org.springframework.http.ResponseEntity; import java.net.URISyntaxException; import java.util.Collection; public interface InterfaceLieu { public Collection<Lieu> getAllLocation(); public ResponseEntity<?> getLocationBYId(Long id) ; public ResponseEntity<?> addLocation(Lieu location) throws URISyntaxException; public ResponseEntity<?> updateLocation(Lieu location,Long location_id); public void deleteLocation(Long location_id); }
Java
UTF-8
933
2.28125
2
[]
no_license
package com.gaospot.cms.domain; import java.sql.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; @Entity public class Publish { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private long id; @OneToOne @JoinColumn(name="News") private News news; @Column(name="url") private String url; @Column(name="publishTime") private Date publishTime; public Publish(long id, News news, String url, Date publishTime) { super(); this.id = id; this.news = news; this.url = url; this.publishTime = publishTime; } public long getId() { return id; } public News getNews() { return news; } public String getUrl() { return url; } public Date getPublishTime() { return publishTime; } }
C++
UTF-8
956
3
3
[]
no_license
#include<iostream> #include<cstdio> #include<stack> #include<vector> #include<algorithm> using namespace std; stack<int> st; vector<int> v; int peekMedian(int m) { stack<int> s; v.clear(); while(!st.empty()) { s.push(st.top()); v.push_back(st.top()); st.pop(); } while(!s.empty()) { st.push(s.top()); s.pop(); } sort(v.begin(),v.end()); return v[m]; } int main() { int n, k, m; scanf("%d", &n); string s; while(n--) { cin >> s; if(s == "Pop") { if(st.empty()) printf("Invalid\n"); else { printf("%d\n", st.top()); st.pop(); } } else if(s == "PeekMedian") { if(st.empty()) printf("Invalid\n"); else { if(st.size()%2==0) { m = st.size()/2; m = peekMedian(m-1); printf("%d\n", m); } else{ m = (st.size()+1)/2; m = peekMedian(m-1); printf("%d\n", m); } } } else if(s == "Push") { scanf("%d", &k); st.push(k); } } return 0; }
Markdown
UTF-8
5,209
2.78125
3
[]
no_license
+++ date = "2017-03-11T10:37:20Z" title = "Recycling rates" draft = false categories = ["data", "analysis"] description = "" featuredpath = "date" linktitle = "" type = "post" +++ [An article about my local council’s worsening recycling rate](http://www.hampshirechronicle.co.uk/news/15132003.Winchester_civic_chief_defends_worsening_recycling_record/#) sent me on a quick investigation of the data and to reflect on the context. > “Cllr Jan Warwick, portfolio holder for environment, blamed a fall in the amount of newspapers being recycled.” Hum, what does that mean? I presume it means fewer newspapers in volume are being recycled - rather than the proportion of newspapers being recycled has fallen. [Wikipedia](https://en.wikipedia.org/wiki/List_of_newspapers_in_the_United_Kingdom_by_circulation), citing data from the UK [Audit Bureau of Circulations](https://www.abc.org.uk/), demonstrates that newspaper circulation is falling in the UK. Looking at newspapers with circulations of more than 100,000 copies per day in January 2012; circulation for an average January day fell 12% from 10.1m in 2014 to 8.9m in 2017. So there *are* fewer papers to recycle. Now what [counts as recycling is contentious](http://www.letsrecycle.com/news/latest-news/hampshire-councils-defend-recycling-record/), and the how the rate is calculated is quite complex; but it’s basically the weight of recycled waste divided by the weight of all waste. So a contributory reason for a fall in the recycling rate could be a reduction in ‘recyclable things’, like newspapers - and my council’s spokesperson does make this point: > “The recycling rate in Winchester has plateaued in recent years... However changes to the make-up of rubbish, including changing behaviours like people buying less paper products and improvements in manufacturing making ‘recycled’ products lighter, have led to this plateau.” Finding summary information at the national level for waste and recycling took quite a lot of delving; but here’s the summary for England<sup>1</sup>: | Recycling | 2010 | 2011 | 2012 | 2013 | 2014 | 2015 | |--------------------------------------------------------|-------:|-------:|-------:|-------:|-------:|-------:| | Total collected waste (000s of tonnes) | 22131 | 22170 | 21956 | 21564 | 22355 | 22225 | | Total sent for recycling less rejects (000s of tonnes) | 9112 | 9596 | 9684 | 9523 | 10025 | 9758 | | Recycling rate (based on sent recycling less rejects) | 41.2% | 43.3% | 44.1% | 44.2% | 44.8% | 43.90% | ![Total collected waste and total sent for recycling less rejects](https://res.cloudinary.com/df1mif8sk/image/upload/v1489098146/hugo/image_pv0tdk.png)<br> _Total collected waste and total sent for recycling less rejects_ So it has plateaued across England, although this, of course, hides large variations. And the rates for Winchester, for **non-composted** waste, have indeed fallen<sup>2</sup>: | Non-composted waste | 2012-13 | 2013-14 | 2014-15 | 2015-16 | 2016-17 | |---------|--------:|--------:|--------:|--------:|--------:| | Apr | 25.7% | 24.2% | 23.2% | 23.7% | 22.4% | | May | 25.8% | 23.5% | 21.0% | 20.1% | 22.0% | | Jun | 23.8% | 21.7% | 21.2% | 21.9% | 19.9% | | Jul | 23.6% | 22.5% | 21.0% | 20.7% | 22.3% | | Aug | 23.1% | 23.4% | 22.6% | 21.0% | 22.4% | | Sep | 24.8% | 24.4% | 22.5% | 21.7% | | | Oct | 27.2% | 23.3% | 23.1% | 21.4% | | | Nov | 25.9% | 22.8% | 22.1% | 21.3% | | | Dec | 28.5% | 26.6% | 25.2% | 22.5% | | | Jan | 26.2% | 22.1% | 24.4% | 27.5% | | | Feb | 27.1% | 22.6% | 24.2% | 27.6% | | | Mar | 26.6% | 22.2% | 23.0% | 24.3% | | | **Average** | **25.7%** | **23.3%** | **22.8%** | **22.8%** | **21.8%** | Note the Winchester data is for non-composted waste, whilst the data for England includes composted waste. So the data seems a bit of a mess (pun intended), and open to interpretation - but the important message, as ever, is context. A fall in the recycling rate _might possibly_ not be a bad thing, if it’s a result of reduced volumes of newsprint and lighter cardboard et cetera. Although you’d hope the rate continues to increase if overall packing is reduced and more products are brought into scope of recycling. There’s also a link to the user experience: are ‘recycling products’ designed to help users? For example, better kerbside collection, better design and labelling of bins and bags and clearer information could all increase recycling volumes. _1. Source = [ENV18 - Local authority collected waste: annual results tables](https://www.gov.uk/government/statistical-data-sets/env18-local-authority-collected-waste-annual-results-tables)_ _2. Source = [Winchester City Council - Household waste recycled (percentage)](http://www.winchester.gov.uk/data/performance-measures/environment/percentage-household-waste-recycled/)_
Python
UTF-8
4,782
3.34375
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/python import os import shutil from contextlib import contextmanager from salve.filesys.abstract import Filesys from salve.util import hash_from_path class ConcreteFilesys(Filesys): def lookup_type(self, path): """ Lookup the type of a given path. Args: @path The path to the file, dir, or link to lookup. """ # if no constructor is given, inspect the underlying filesystem if os.path.islink(path): return self.element_types.LINK elif os.path.isdir(path): return self.element_types.DIR elif os.path.isfile(path): return self.element_types.FILE else: return None def access(self, path, mode): """ Transparent implementation of access() using os.access Args: @mode The type of access being inspected """ return os.access(path, mode) def stat(self, path): """ Transparent implementation of stat() using os.lstat """ return os.lstat(path) def chmod(self, path, *args, **kwargs): """ Transparent implementation of chmod() using os.chmod """ return os.chmod(path, *args, **kwargs) def chown(self, path, uid, gid): """ Transparent implementation of chown() using os.lchown """ return os.lchown(path, uid, gid) def exists(self, path): """ Transparent implementation of exists() using os.path.lexists """ return os.path.lexists(path) def hash(self, path): """ Transparent implementation of hash() using salve.util.hash_from_path """ assert self.exists(path) return hash_from_path(path) def copy(self, src, dst): """ Copies the source to the destination on the underlying filesys. Does not necessarily create a new entry registered to the destination. Args: @src The origin path to be copied. When looked up in the filesys, must not be None and must satisfy exists() @dst The destination path for the copy operation. The ancestors of this path must exist so that the file creation will not fail. """ assert self.exists(src) src_ty = self.lookup_type(src) if src_ty == self.element_types.FILE: shutil.copyfile(src, dst) # FIXME: copytree is kind of scary. Eventually would like to replace # this with a NotImplementedError in order to force explicit creates # and file copies elif src_ty == self.element_types.DIR: shutil.copytree(src, dst, symlinks=True) elif src_ty == self.element_types.LINK: os.symlink(os.readlink(src), dst) else: # pragma: no cover assert False @contextmanager def open(self, path, *args, **kwargs): """ Transparent implementation of open() using builtin open """ with open(path, *args, **kwargs) as f: yield f def touch(self, path, *args, **kwargs): """ Touch a file by opening it in append mode and closing it """ with self.open(path, 'a'): pass def symlink(self, path, target): """ Transparent implementation of symlink() using os.symlink """ os.symlink(path, target) def walk(self, path, *args, **kwargs): """ Transparent implementation of walk() using os.walk """ for x in os.walk(path, *args, **kwargs): yield x def mkdir(self, path, recursive=True): """ Use os.mkdir or os.makedirs to create the directory desired, suppressing "already exists" errors. May still return OSError(2, 'No such file or directory') when nonrecursive mkdir calls have missing ancestors. """ try: if recursive: os.makedirs(path) else: os.mkdir(path) except OSError as e: # 'File exists' errno if e.errno == 17: return else: raise e def get_existing_ancestor(self, path): """ Finds the longest prefix to a path that is known to exist. Args: @path An absolute path whose prefix should be inspected. """ # be safe path = os.path.abspath(path) # exists is sufficient because we can stat directories as long as # we have execute permissions while not os.path.exists(path): path = os.path.dirname(path) return path
Ruby
UTF-8
399
2.53125
3
[]
no_license
class ExpectedEvent < ActiveRecord::Base validates :title, presence: true, format: { with: /\A[a-z0-9\s]+\Z/i } validates_uniqueness_of :title has_many :alarms has_many :incoming_events before_save :delete_white_spaces_from_title def alarm! alarms.each do |alarm| alarm.run end end private def delete_white_spaces_from_title self.title = self.title.strip end end
C++
UTF-8
679
2.71875
3
[]
no_license
//https://www.hackerrank.com/challenges/even-tree #include <bits/stdc++.h> using namespace std; vector<int> edges[1000006]; int depth[1000056]; bool vis[10000006]; int dfs(int u){ vis[u] = true; depth[u] = 1; for(int i = 0 ; i < (int)edges[u].size() ; i++) if(!vis[edges[u][i]]) depth[u] += dfs(edges[u][i]); return depth[u]; } int main() { int n,m; cin >> n >> m; for(int i = 0 ; i < m ; i++){ int u,v; cin >> u >> v; edges[u].push_back(v); edges[v].push_back(u); } dfs(1); int ans = 0; for(int i = 2 ; i <= n ; i++) ans += (depth[i] % 2 == 0); cout << ans ; return 0; }
JavaScript
UTF-8
5,689
2.859375
3
[]
no_license
/* eslint-disable no-undef */ const sliderImage = document.querySelector(".double-part-section__img"); const glitch = sliderImage.querySelector(".glitch"); const nextArrow = document.querySelector(".facilities-slider__arrows .next"); const prevArrow = document.querySelector(".facilities-slider__arrows .prev"); const dotsContainer = document.querySelector(".facilities-slider__dots-row") function getSliderCounter(selector) { let counter = document.querySelector(selector); return { elem: counter, current: counter.querySelector(".current"), total: counter.querySelector(".total") }; } let facilitiesCounter = getSliderCounter(".js-facilities-slider-counter"); $(".facilities-slick").on("init", function(event, slickObject, current, next) { initSlickCustomDots(slickObject, dotsContainer); facilitiesCounter.total.innerHTML = slickObject.slideCount < 9 ? "0" + (slickObject.slideCount) : slickObject.slideCount; Array.from(slickObject.customDots).forEach((dot, index) => { handleGlitchChanging(dot, index, slickObject); }) console.log(Array.from(slickObject.customDots)); }); $(".facilities-slick").on("beforeChange", function(event, slickObject, current, next) { switchSlickActiveDot(slickObject, current, next); switchGlitchSlide(slickObject.customDots[next], next, slickObject); glitchTitleEffect(current, next, slickObject); }) function glitchTitleEffect(current, next, slickObject) { slickObject.$slides[current].querySelector('.title').classList.add('glitched-title'); setTimeout(() => { slickObject.$slides[current].querySelector('.title').classList.remove('glitched-title') }, 500); slickObject.$slides[next].querySelector('.title').classList.add('glitched-title'); setTimeout(() => { slickObject.$slides[next].querySelector('.title').classList.remove('glitched-title') }, 1500); } $(".facilities-slick").on("afterChange", function(event, slickObject, current, next) { facilitiesCounter.current.textContent = current < 9 ? "0" + (current + 1) : current + 1; }) $(".facilities-slick").slick({ arrows: false, infinite: false, fade: true, }) nextArrow.addEventListener("click", function(evt) { $(".facilities-slick").slick("slickNext"); }); prevArrow.addEventListener("click", function(evt) { $(".facilities-slick").slick("slickPrev"); }); function enableGlitch() { glitch.classList.add("active"); } function disableGlitch() { glitch.classList.remove("active"); } function changeImage(src) { sliderImage.querySelectorAll(".glitch__img").forEach((image, index) => { setTimeout(() => { image.style.background = `url(${src}) no-repeat 50% 0`; }, index * 500); }) } function handleGlitchChanging(dot, index, slickObject) { dot.addEventListener("click", function() { switchGlitchSlide(dot, index, slickObject); }) } function switchGlitchSlide(dot, index, slickObject) { // console.log(dot, "dot"); // console.log(index, "index"); // console.log(slickObject, "slickObject"); // this.classList.add('active'); console.log(slickObject.$slides[index + 1]); enableGlitch(); setTimeout(() => { changeImage(slickObject.$slides[index].dataset.src) $(".facilities-slick").slick("slickGoTo", dot.dataset.index); }, 1000); setTimeout(() => { disableGlitch(); }, 1500); } /** Slick custom DOTS */ function initSlickCustomDots(slickObject, destination) { renderSlickCustomDots(slickObject.$slides, destination); console.log(); slickObject.customDots = $(`.${destination.classList[0]} .facilities-slider__navigation-dot`); slickObject.customDots.each(function(dot, index) { if (dot === null || dot === 0) slickObject.customDots[0].classList.add("active"); this.addEventListener("click", function() { this.classList.add("active"); }) }); } function renderSlickCustomDots($slides, renderDestination) { $slides.each((slide, index) => { console.log(slide); renderDot(slide, renderDestination); }) } function renderDot(index, container) { let customDot = ` <svg data-index="${index}" class="facilities-slider__navigation-dot" width="26" height="26" viewBox="0 0 26 26" fill="none" xmlns="http://www.w3.org/2000/svg"> <rect class="facilities-slider__navigation-dot-border" x="13" y="0.707107" width="17.3848" height="17.3848" transform="rotate(45 13 0.707107)"/> <rect class="facilities-slider__navigation-dot-inner" x="13.209" y="3.99927" width="13" height="13" transform="rotate(45.1014 13.209 3.99927)" /> </svg> `; container.insertAdjacentHTML("beforeend", customDot); } function switchSlickActiveDot(slickObject, prev, next) { slickObject.customDots[prev].classList.remove("active"); slickObject.customDots[next].classList.add("active"); } /** Slick custom DOTS END */ //mobile screen1 slider sizing var screen1 = document.querySelector('.js-facilities-screen1'); var headerHeight = document.querySelector('.header').getBoundingClientRect().height; var footerFixedHeight = document.querySelector('.fixed-footer').getBoundingClientRect().height; var textBlockHeight = screen1.querySelector('.double-part-section__text').getBoundingClientRect().height; if (document.documentElement.clientWidth < 576) { // screen1.querySelector('picture').style.height = (document.documentElement.clientHeight - textBlockHeight - headerHeight) + 'px'; }
Java
UTF-8
294
2.078125
2
[]
no_license
package com.luisaraujo.app.exceptions; /** * @author Luis Araujo * */ public class MessageLimitException extends Exception { private static final long serialVersionUID = 1L; /** * @param message Exception Message */ public MessageLimitException(String message) { super(message); } }
TypeScript
UTF-8
875
3.359375
3
[]
no_license
// cart helpr fn that calculates total of cart export const calculateTotal = ( products: any ): { cartTotal: string; stripeTotal: number } => { if (!products) { return { cartTotal: '0', stripeTotal: 0 }; } const total = products.reduce((accumulator, item) => { return accumulator + item.product.price * item.quantity; }, 0); // total used to display - prevent rounding errors const cartTotal = ((total * 100) / 100).toFixed(2); // total used for stripe (needed in cents) const stripeTotal = Number((total * 100).toFixed(2)); return { cartTotal, stripeTotal }; }; export const formatAmountForStripe = (price, quantity) => { const total = price * quantity; const stripeTotal = Number((total * 100).toFixed(2)); return stripeTotal; }; // convert price from cents to dollars export const convertPrice = price => (price / 100.0).toFixed(2);
C++
UTF-8
3,722
2.640625
3
[]
no_license
#include "HelloWorldScene.h" #include "Ball.h" USING_NS_CC; Scene* HelloWorld::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = HelloWorld::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } TableView * tv=TableView::create(this,Size(300,300)); tv->setAnchorPoint(Point(0,0)); tv->setPosition(Point(100,100)); tv->setDelegate(this); addChild(tv); //------------------------------------------- //菜单项的用法 // auto menu=Menu::create(MenuItemImage::create("CloseNormal.png", "CloseSelected.png", [](Object* obj){ // log("menu item touched"); // }), NULL); // addChild(menu); //-------------------------------------------- //使用自定义类 // Size visibleSize=Director::getInstance()->getVisibleSize(); // auto b=Ball::create(); // b->setPosition(200,200); // addChild(b); //------------------------------------------------------- //Textfield的使用 // Size visibleSize=Director::getInstance()->getVisibleSize(); // TextFieldTTF *tf=TextFieldTTF::textFieldWithPlaceHolder("在这里输入", "宋体", 20); // tf->setPosition(visibleSize.width/2,visibleSize.height/2); // addChild(tf); // auto listrner=EventListenerTouchOneByOne::create(); // listrner->onTouchBegan=[tf](Touch *t,Event *event){ // if (tf->getBoundingBox().containsPoint(t->getLocation())) { //// log(">>>>>>"); // tf->attachWithIME(); // } // else{ // tf->detachWithIME(); // } // // return false; // }; // Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listrner, tf); //-------------------------------------------- //labelTTF使用 // Size size=Director::getInstance()->getVisibleSize(); // LabelTTF *laber=LabelTTF::create(); // laber->setString("Hello jikexuyuan"); // laber->setPosition(size.width/2,size.height/2); // laber->setFontSize(36); // addChild(laber); return true; } Size HelloWorld::cellSizeForTable(cocos2d::extension::TableView *table){ return Size(300,50); } TableViewCell* HelloWorld::tableCellAtIndex(cocos2d::extension::TableView *table, ssize_t idx){ TableViewCell *cell=table->dequeueCell(); LabelTTF *label; if (cell==NULL) { cell=TableViewCell::create(); label=LabelTTF::create(); label->setTag(2); label->setFontSize(24); label->setAnchorPoint(Point(0,0)); cell->addChild(label); } else{ label=(LabelTTF*)cell->getChildByTag(2); } label->setString(StringUtils::format("Label %d",(int)idx)); return cell; } ssize_t HelloWorld::numberOfCellsInTableView(cocos2d::extension::TableView *table){ return 100; } void HelloWorld::tableCellTouched(cocos2d::extension::TableView *table, cocos2d::extension::TableViewCell *cell){ LabelTTF *label=(LabelTTF*)cell->getChildByTag(2); log("%s",label->getString().c_str()); } void HelloWorld::menuCloseCallback(Ref* pSender) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert"); return; #endif Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif }
C++
UTF-8
207
2.5625
3
[]
no_license
class Solution { public: int hammingWeight(uint32_t n) { // Returns the number of 1's in the two's complement binary // representation of n. return __builtin_popcount(n); } };
Java
UTF-8
4,239
2.3125
2
[]
no_license
package com.carnnjoh.poedatatool.services; import com.carnnjoh.poedatatool.db.inMemory.dao.UniqueDao; import com.carnnjoh.poedatatool.db.model.User; import com.carnnjoh.poedatatool.model.*; import com.carnnjoh.poedatatool.schedulers.SchedulerUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.*; import static com.carnnjoh.poedatatool.model.ItemType.*; @Service public class PrivateStashTabService { private Logger logger = LoggerFactory.getLogger(PrivateStashTabService.class); @Autowired private PrivateStashTabFetcher privateStashTabFetcher; @Autowired private UniqueDao uniqueDao; @Autowired private ExplicitModExtractorService explicitModExtractor; //TODO: find a better way to set this when testing... ? @Value("${services.test.poesessid}") private String testSessionId; private List<ItemType> itemTypes = new ArrayList<>(EnumSet.allOf(ItemType.class)); private final Map<String, InMemoryItem> inMemoryItemMap = new HashMap<>(); public List<PrivateStashTab> requestStashTabs(Integer[] activeTabs, User user) { List<PrivateStashTab> fetchedTabs = new ArrayList<>(); try { // need to loop through all "active" tabs from subscription, API call to retrieve private stash tab does not support fetching more than one at a time for (Integer activeTab : activeTabs) { Optional<PrivateStashTab> currentlyFetchedTab = privateStashTabFetcher .fetchStashItems(createPrivateStashTabRequest(user, activeTab)); currentlyFetchedTab.ifPresent(fetchedTabs::add); // Need to sleep between calls, to not get rate limited. Thread.sleep(SchedulerUtils.HTTP_REQUEST_SLEEP); } } catch (Exception e) { logger.warn(e.getMessage()); throw new RuntimeException(e); } return fetchedTabs; } public <T extends StashTab> void saveItems(List<T> stashTabs) { if (!stashTabs.isEmpty()) { logger.debug("before adding/removing ItemMap size: " + inMemoryItemMap.size()); //Used to control the size of the in memory map of items. List<String> itemsToBeRemoved = new ArrayList<>(inMemoryItemMap.keySet()); for (StashTab stashTab : stashTabs) { if(stashTab.items == null || stashTab.items.isEmpty()) { continue; } for (Item item : stashTab.items) { if (item != null && item.isIdentified) { InMemoryItem inMemoryItem = new InMemoryItem(item); applyItemType(inMemoryItem); applyExplicitMods(inMemoryItem); inMemoryItemMap.putIfAbsent(item.itemId, inMemoryItem); itemsToBeRemoved.remove(item.itemId); } } } for(String itemId : itemsToBeRemoved) { inMemoryItemMap.remove(itemId); } logger.debug("after adding/removing ItemMap size: " + inMemoryItemMap.size()); } } private void applyItemType(InMemoryItem inMemoryItem) { //Looking up the item name / type from static data to determine the itemType. lookUpItemIfSpecialItem(inMemoryItem); if(inMemoryItem.getItemType() != null) { return; } // if it doesn't find the itemType above this will test all for(ItemType itemType : itemTypes) { if(itemType.filter != null && itemType.filter.test(inMemoryItem)) { inMemoryItem.setItemType(itemType); break; } } } private void lookUpItemIfSpecialItem(InMemoryItem item) { uniqueDao.applyItemTypeIfGem(item); uniqueDao.applyItemTypeIfUnique(item); } private void applyExplicitMods(InMemoryItem inMemoryItem) { explicitModExtractor.extractAndApplyMods(inMemoryItem); } public Item getItemFromInMemoryMap(String itemId) { return inMemoryItemMap.get(itemId); } public Map<String, InMemoryItem> getInMemoryItemMap() { return inMemoryItemMap; } private PrivateStashTabRequest createPrivateStashTabRequest(User user, int activeTab) { String sessionId = (testSessionId == null || testSessionId.isEmpty()) ? user.getSessionId() : testSessionId; logger.debug("Current session id: " + sessionId); return new PrivateStashTabRequest( user.getLeague(), user.getRealm(), user.getAccountName(), false, activeTab, sessionId ); } }
Python
UTF-8
8,635
3.015625
3
[]
no_license
import Tkinter from Tkinter import * import tkMessageBox import PIL from PIL import Image import tkFont a=Tkinter.Tk() a.title("CAR COMPARE") tkMessageBox.showinfo("Welcome","Welcome to AUTOMOTO \n Compare cars \nEnjoy ;-)") """=========================================================================================""" img_cmp1=PhotoImage(file="cmp1.gif")#main page image 1 img_close=PhotoImage(file="close.gif")#close img_search=PhotoImage(file="search.gif") def abdev():#about developer Function c=Tkinter.Tk() c.title("About Software")#title about developer Tkinter.Button(c,command=c.destroy,text="X",background="red").pack(anchor="ne") text=Text(c) text.insert(INSERT,"\t \t \t Made By Arpit & Vishrant\n") text.insert(INSERT,"\t \t \t INSPIRED BY : CARDEKHO.COM \n") text.insert(INSERT,"\t \t \t VERSION:1.0 \n \n \n") text.insert(INSERT,"This program compares cars of some well known brands like \n") text.insert(INSERT,"\t \t MERCEDES; AUDI; LAMBOGHINI; BMW; PORSCHE; ROLLS ROYCE \n") text.insert(INSERT,"On the basis of :\n \t \t ENGINE; PRICE; TOP SPEED; MILEAGE \n ") text.insert(INSERT," \n") text.insert(INSERT,"With some UPCOMING CARS: \n \n") text.insert(INSERT,"\tBENTLEY BENTAYGA \n\tJAGUAR F-PACE \n\tROLLS ROYCE DAWN \n\tFERRARI 488") text.insert(INSERT,"\tPORSCHE MISSION E \n\t LAMBORGHINI URUS \n\tMERCEDES IAA \n \n") text.insert(INSERT,"Any queries feel free to contact us at:\t carhdwallpaper.weebly.com/contact \n") text.insert(INSERT,"\t \t \t \t \t abc@gmail.com \n") text.pack() text.config(background="gold") c.config(background="black") c.mainloop() #------------------------------------------------------------------------------------------- def Upcoming(): # DROP DOWN MENU c=Tkinter.Tk() c.title("UPCOMING") Tkinter.Button(c,command=c.destroy,text="X",background="red").pack(anchor="ne") def upcoming_car(): valcar=upcoming_cars.get()#taking value of upcoming cars if(valcar=="DAWN"): im=Image.open("dawn.jpg") im.show() if(valcar=="488 GTB"): im=Image.open("488.jpg") im.show() if(valcar=="BENTAYGA"): im=Image.open("bentayga.jpg") im.show() if(valcar=="URUS"): im=Image.open("urus.jpg") im.show() if(valcar=="MISSION E"): im=Image.open("mission-e.jpg") im.show() if(valcar=="MERCEDES IAA"): im=Image.open("iaa.jpg") im.show() if(valcar=="F PACE"): im=Image.open("fpace.jpg") im.show() #------------------------------------------------------------------------------------------ upcoming_cars=Tkinter.StringVar(c) upcoming_cars.set("UPCOMING CARS") choices=["DAWN","488 GTB","BENTAYGA","URUS","MISSION E","MERCEDES IAA","F PACE"] option=Tkinter.OptionMenu(c,upcoming_cars,*choices).pack(anchor="w") Tkinter.Button(c,command=upcoming_car,text="Select",background="gold").pack(anchor="center") c.config(background="black") c.mainloop() def Facts(): #Facts c=Tkinter.Tk() c.title("Facts About Cars") Tkinter.Button(c,command=c.destroy,text="X",background="red").pack(anchor="ne") text=Text(c) text.insert(INSERT,"A}The Spirit Of Ecstasy On The Rolls Royce Is Worth $40 Million \n \n") text.insert(INSERT,"B} Rolls Royce Logo On Its Wheel Always Remains Upright \n \n") text.insert(INSERT,"C}Lamborghinis Murcielago Is The Real Batmobile \n \n") text.insert(INSERT,"D}Daniel Craig Has A Lifelong Access to Aston Martin Cars \n \n") text.insert(INSERT,"E}Lamborghini Initially Manufactured Tractors \n \n") text.insert(INSERT,"F}The Symbol Of Toyota Is Not Merely A T \n \n") text.insert(INSERT,"G}Aston Martin Has Been Owned By 11 Different Owners \n \n") text.insert(INSERT,"H}Volkswagen Isnt Called The Peoples Car For No Reason! \n \n") text.insert(INSERT,"I}The Name Of Lamborghini Countach Is Inspired From A Cuss Word \n \n") text.insert(INSERT,"J}The Mercedes Silver Arrow Was Initially Grey \n \n") text.pack() text.config(background="gold") c.config(background="black") #------------------------------------------------------------- #menubar b=Menu(a) Aboutmenu=Menu(b) Aboutmenu.add_command(label="About Software",command=abdev) b.add_cascade(label="About", menu=Aboutmenu) Upcomingmenu=Menu(b) #upcoming menu Upcomingmenu.add_command(label="Upcoming",command=Upcoming) b.add_cascade(label="Upcoming",menu=Upcomingmenu) Factsmenu=Menu(b) #facts menu Factsmenu.add_command(label="Facts About Cars",command=Facts) b.add_cascade(label="Facts About Cars",menu=Factsmenu) def Select_Brand(): val_ddmenu=var.get() #taking values of drop down menu if(val_ddmenu=="AUDI" or val_ddmenu=="MERCEDES" or val_ddmenu=="BMW" or val_ddmenu=="LAMBORGHINI" or val_ddmenu=="PORSCHE" or val_ddmenu=="ROLLS ROYCE"): tkMessageBox.showinfo("Error","Select a model not brand") else : if(val_ddmenu==" R8 SPYDER"):#r8spyder im=Image.open("r8spy.jpg") im.show() #showing image if(val_ddmenu==" RS7"): im=Image.open("rs7.jpg") im.show() #showing imageRS7 if(val_ddmenu==" TT"): im=Image.open("tt.jpg") im.show() #Showing image TT #bmw if(val_ddmenu==" BMW i8"): im=Image.open("i8.jpg") im.show() #showing image hybrid if(val_ddmenu==" M4"): im=Image.open("m4.jpg") im.show() #showing image M4 if(val_ddmenu==" 7SERIES"): im=Image.open("7series.jpg") im.show() #showing image 7series """----------------------------------------------porsche------------------------""" if(val_ddmenu==" PORSCHE 918"): im=Image.open("918.jpg") im.show() #showing image 918 if(val_ddmenu==" CAYMAN"): im=Image.open("cayman.jpg") im.show() #showing image cayman if(val_ddmenu==" 911"): im=Image.open("911.jpg") im.show() #showing image 911 """---------------------------------------------mercedes---------------------""" if(val_ddmenu==" G63"): im=Image.open("g63.jpg") im.show() #showing image G63 if(val_ddmenu==" AMG GT"): im=Image.open("amggt.jpg") im.show() #showing image AMG GT if(val_ddmenu==" GL-63"): im=Image.open("gl63.jpg") im.show() """--------------------------------------------lamborghini-------------------""" if(val_ddmenu==" HURACAN"): im=Image.open("huracan.jpg") im.show() #-------------------------------------------- if(val_ddmenu==" AVENTDOR"): im=Image.open("aventdor.jpg") im.show() #---------------------------------------------- if(val_ddmenu==" GALLARDO"): im=Image.open("gallardo.jpg") im.show() """-----------------------------------------rolls-royce--------------------""" if(val_ddmenu==" GHOST"): im=Image.open("ghost.jpg") im.show() #--------------------------------------------- if(val_ddmenu==" WRAITH"): im=Image.open("wraith.jpg") im.show() #------------------------------------------- if(val_ddmenu==" PHANTOM"): im=Image.open("phantom.jpg") im.show() b.mainloop() #---------------------------------------------------------------------------------------------------------------------------------------------------------- var=Tkinter.StringVar(a) var.set("S E L E C T B R A N D ") choices=["AUDI"," R8 SPYDER"," RS7"," TT","\n", "BMW"," BMW i8"," M4"," 7SERIES","\n", "LAMBORGHINI"," HURACAN"," GALLARDO"," AVENTDOR","\n", "PORSCHE"," PORSCHE 918"," CAYMAN"," 911","\n", "MERCEDES"," G63"," AMG GT"," GL-63","\n", "ROLLS ROYCE"," PHANTOM"," GHOST"," WRAITH"] Tkinter.Button(a,command=a.destroy,image=img_close,background="black").pack(anchor="ne") option=Tkinter.OptionMenu(a,var,*choices).pack(anchor="nw") Tkinter.Button(a,command=Select_Brand,image=img_search).pack(anchor="n") label=Label(image=img_cmp1,width=1360,height=600).pack() a.config(background="black") a.config(menu=b) a.mainloop()
Markdown
UTF-8
1,421
2.53125
3
[ "MIT" ]
permissive
# Hybrid-Cloud-Automation-Using-Ansible-ManageIQ- Now a days, Automation is the mother of all the inventions, that give rise to all the new technologies. Most of the latest technologies are the reason to automation. This project is one of our try to automate hybrid cloud using ManageIQ and Ansible. A hybrid cloud is the one with the combination of both i.e. private as well as public cloud with the specified specifications. ManageIQ is an open source cloud management platform by Red Hat. It is written in Ruby with RoR (Ruby on Rails) as platform. Ansible is software that automates software provisioning, configuration management, and application deployment. Playbooks are Ansible’s configuration, deployment, and orchestration language. ### Book Navigation - [**_Chapter 1_**](chapter1/README.md): ManageIQ installation, its appliance console and basic configuration is also discussed. - [**_Chapter 2_**](chapter2/README.md): ManageIQ database configuration i.e restoring custom database of ManageIQ. - [**_Chapter 3_**](chapter3/README.md): Automation of tasks discussed in [chapter 2](chapter2/README.md). with the help of Ansible ### Resources - Project Reference - https://github.com/Ompragash/Hybrid-Cloud-Automation-Using-Ansible-ManageIQ - ManageIQ Docs - http://manageiq.org/docs/ - ManageIQ Forum - http://talk.manageiq.org/ - Ansible Docs - https://docs.ansible.com/ansible/latest/index.html
TypeScript
UTF-8
1,193
2.59375
3
[]
no_license
var glob = require( "glob" ); function getIncludeFiles ( include: Array<string>, exclude: Array<string> ): any { let includeCheckFiles: number[] = []; let excludeCheckFiles: number[] = []; // 包含文件 if ( include && include.length != 0 ) { for ( let i = 0; i < include.length; i++ ) { let files: number[] = glob.sync( include[ i ], { cwd: process.cwd() } ); includeCheckFiles = includeCheckFiles.concat( files ); } } //排除文件 if ( exclude && exclude.length != 0 ) { for ( let i = 0; i < exclude.length; i++ ) { let files: number[] = glob.sync( exclude[ i ], { cwd: process.cwd() } ); excludeCheckFiles = excludeCheckFiles.concat( files ); } } //最终需要检测的文件 if ( excludeCheckFiles && excludeCheckFiles.length > 0 ) { for ( let i = 0; i < excludeCheckFiles.length; i++ ) { let index: number = includeCheckFiles.indexOf( excludeCheckFiles[ i ] ); if ( index != -1 ) { includeCheckFiles.splice( index, 1 ); } } } return includeCheckFiles; } export = getIncludeFiles;
Markdown
UTF-8
4,169
2.59375
3
[]
no_license
--- layout: default --- ## Be Awesome to Each Other The mission of [The London Django Meetup Group](http://www.djangolondon.com/) is to provide fun, welcoming and professional environments so that diverse groups of people - regardless of age, race, gender identity or expression, background, disability, appearance, sexuality, walk of life, or religion - can get together to learn from and be inspired by each other about all things related to Django, the high-level Python Web framework. The London Django Meetup Group asks all our members, speakers, volunteers, attendees and guests to adopt the following principles to help us with our mission. We are a diverse community. Sometimes this means we need to work harder to ensure we're creating an environment of trust and respect where all who come to participate feel comfortable and included. We value your participation and appreciate your help in realising this goal. ## Be Respectful Respect yourself, and respect others. Be courteous to those around you. If someone indicates they don't wish to be photographed, respect that wish. If someone indicates they would like to be left alone, let them be. Our meetup venues and online spaces may be shared with members of the public; please be considerate to all patrons of these locations. ## Be Inclusive All presentation material should be suitable for people aged 12 and above. All public presentations are subject to this code of conduct and thus may not contain: - sexual or violent imagery - exclusionary language - language which is inappropriate for an all-ages audience For the avoidance of doubt, public presentations include but are not limited to: keynotes, presentations, lightning talks, addresses, IRC, mailing list posts, and forums. If you are in doubt, consider it covered. If presenters are unsure whether their material is suitable, they are encouraged to show it to the meetup host or an organiser before their session. ## Be Aware We ask everyone to be aware that we will not tolerate intimidation, harassment, or any abusive, discriminatory, or derogatory behaviour by anyone at any event, or online. Complaints can be made to the [meetup organisers](http://www.meetup.com/djangolondon/members/?op=leaders) either face to face at a meetup, or via the Meetup website. Any complaints made to event organisers will remain confidential, be taken seriously, and be treated appropriately with discretion. Should an event organiser consider it appropriate, the complainee may be: - told to apologise - told to stop/modify their behaviour appropriately - warned that enforcement action may be taken if the behaviour continues - asked to leave the venue immediately - prohibited from continuing to attend the event When necessary, an incident will be reported to the appropriate authorities. ## What Does That Mean for Me? All participants, including event attendees and speakers, must not engage in any intimidation, harassment, or abusive or discriminatory behaviour. Here are some examples of behaviours which are not appropriate: - offensive verbal or written remarks related to gender, sexual orientation, disability, physical appearance, body size, race, or religion - sexual or violent images in public spaces (including presentation slides) - deliberate intimidation - stalking or following - unwanted photography or recording - sustained disruption of talks or other events - intoxication at an event venue - inappropriate physical contact - unwelcome sexual attention - sexist, racist, or other exclusionary jokes - unwarranted exclusion from conference or related events based on age, gender, sexual orientation, disability, physical appearance, body size, race, or religion. **We Want Everyone to Have a Good Time at our Events** ## Questions? If you're not sure about anything you've just read please contact the [Meetup organisers](http://www.meetup.com/djangolondon/members/?op=leaders). You can message us through the [Meetup page](http://www.meetup.com/djangolondon/). ## Credits The original version of this Code of Conduct was created by [linux.conf.au](http://lcabythebay.org.au/code-of-conduct/). v1.0.1
Swift
UTF-8
5,112
2.8125
3
[]
no_license
// // SceneDelegate.swift // UITabBarControllerDemo // // Created by Trista on 2021/2/10. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). //guard let _ = (scene as? UIWindowScene) else { return } if let windowScene = (scene as? UIWindowScene) { //建立一個 UIWindow ,用來顯示應用程式所有畫面的視窗 //iOS下只會有一個視窗,就是self.window self.window = UIWindow(windowScene: windowScene) //設置底色 self.window!.backgroundColor = UIColor.white //設置rootViewController,也就是應用程式啟動後進到的第一個View //UINavigationController只是一個容器,也需要設置一個rootViewController,所以設置成已經存在的ViewController,也可以依照需求設置成自己另外建立的 UIViewController //建立 UITabBarController let myTabBar = UITabBarController() //設置標籤列 //使用 UITabBarController 的屬性 tabBar 的各個屬性設置 myTabBar.tabBar.backgroundColor = UIColor.clear //建立頁面:使用系統圖示 let mainViewController = ViewController() mainViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .favorites, tag: 100) //建立頁面:使用自定義圖示-有預設圖片及按下時圖片 let articleViewController = ArticleViewController() articleViewController.tabBarItem = UITabBarItem( title: "文章", image: UIImage(named: "article"), selectedImage: UIImage(named: "articleSelected")) //建立頁面:使用自定義圖示-只有預設圖片 let introViewController = IntroViewController() introViewController.tabBarItem = UITabBarItem( title: "介紹", image: UIImage(named: "profile"), tag: 300) //建立頁面:使用自定義圖示,可使用 tabBarItem 的屬性各自設定 let settingViewController = SettingViewController() settingViewController.tabBarItem = UITabBarItem( title: "設定", image: UIImage(named: "setting"), tag:400) //加入到 UITabBarController myTabBar.viewControllers = [mainViewController , articleViewController,introViewController, settingViewController] //預設開啟的頁面(從 0 開始算起) myTabBar.selectedIndex = 2 //將self.window的rootViewController設為UITabBarController self.window!.rootViewController = myTabBar //將 UIWindow 以makeKeyAndVisible()方法設置為可見的,完成手動建立頁面 self.window!.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
Python
UTF-8
630
3.375
3
[]
no_license
def day9_a(input): new_input = input while "!" in new_input: index = new_input.find("!") new_input = new_input[:index] + new_input[index+2:] while "<" in new_input: start = new_input.find("<") end = new_input.find(">") new_input = new_input[:start] + new_input[end + 1:] group = 0 group_sum = 0 for c in new_input: if c == "{": group += 1 group_sum += group elif c == "}": group -= 1 print(group_sum) file_obj = open("input.txt", 'r') input = file_obj.read() file_obj.close() day9_a(input)
Markdown
UTF-8
1,267
2.734375
3
[ "MIT" ]
permissive
# HttpErrorCats Replace your HTTP error codes with cats As seen here https://www.flickr.com/photos/girliemac/sets/72157628409467125/ ## Installation Add this line to your application's Gemfile: gem 'http_error_cats' And then execute: $ bundle Or install it yourself as: $ gem install http_error_cats ## Usage Configuration options in `config/application.rb` # Layout to use for error page rendering. Default: false HttpErrorCats.layout = false # Cat codes to server. Default :all HttpErrorCats.codes = :all # or HttpErrorCats.codes = [404, 500] # Html used to render the error code. # Default: # Proc.new do |status_code| # image_tag "/assets/http_error_cats/#{status_code}.jpg", alt: "Status code #{status_code}" # end HttpErrorCats.html = Proc.new {|code| "<h2>Error #{code}</h2>"} ## License Images (c) girlimac - https://www.flickr.com/photos/girliemac/ ## Contributing 1. Fork it ( https://github.com/[my-github-username]/http_error_cats/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request
PHP
UTF-8
4,121
2.625
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php /** * This file is part of the Zimbra API in PHP library. * * © Nguyen Van Nguyen <nguyennv1981@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Zimbra\Mail\Request; use Zimbra\Common\TypedSequence; use Zimbra\Mail\Struct\CalTZInfo; use Zimbra\Mail\Struct\ExpandedRecurrenceCancel; use Zimbra\Mail\Struct\ExpandedRecurrenceInvite; use Zimbra\Mail\Struct\ExpandedRecurrenceException; /** * ExpandRecur request class * Expand recurrences * * @package Zimbra * @subpackage Mail * @category Request * @author Nguyen Van Nguyen - nguyennv1981@gmail.com * @copyright Copyright © 2013 by Nguyen Van Nguyen. */ class ExpandRecur extends Base { /** * Timezones * @var TypedSequence<CalTZInfo> */ private $_tz; /** * Constructor method for CheckRecurConflicts * @param int $s * @param int $e * @param array $tz * @param ExpandedRecurrenceInvite $comp * @param ExpandedRecurrenceException $except * @param ExpandedRecurrenceCancel $cancel * @return self */ public function __construct( $s, $e, array $tz = array(), ExpandedRecurrenceInvite $comp = null, ExpandedRecurrenceException $except = null, ExpandedRecurrenceCancel $cancel = null ) { parent::__construct(); $this->property('s', (int) $s); $this->property('e', (int) $e); $this->_tz = new TypedSequence('Zimbra\Mail\Struct\CalTZInfo', $tz); if($comp instanceof ExpandedRecurrenceInvite) { $this->child('comp', $comp); } if($except instanceof ExpandedRecurrenceException) { $this->child('except', $except); } if($cancel instanceof ExpandedRecurrenceCancel) { $this->child('cancel', $cancel); } $this->on('before', function(Base $sender) { if($sender->tz()->count()) { $sender->child('tz', $sender->tz()->all()); } }); } /** * Gets or sets s * End time in milliseconds * * @param int $s * @return int|self */ public function s($s = null) { if(null === $s) { return $this->property('s'); } return $this->property('s', (int) $s); } /** * Gets or sets e * Start time in milliseconds * * @param int $e * @return int|self */ public function e($e = null) { if(null === $e) { return $this->property('e'); } return $this->property('e', (int) $e); } /** * Add tz * * @param CalTZInfo $tz * @return self */ public function addTz(CalTZInfo $tz) { $this->_tz->add($tz); return $this; } /** * Gets tz sequence * * @return Sequence */ public function tz() { return $this->_tz; } /** * Gets or sets comp * * @param ExpandedRecurrenceInvite $comp * @return ExpandedRecurrenceInvite|self */ public function comp(ExpandedRecurrenceInvite $comp = null) { if(null === $comp) { return $this->child('comp'); } return $this->child('comp', $comp); } /** * Gets or sets except * * @param ExpandedRecurrenceException $except * @return ExpandedRecurrenceException|self */ public function except(ExpandedRecurrenceException $except = null) { if(null === $except) { return $this->child('except'); } return $this->child('except', $except); } /** * Gets or sets cancel * * @param ExpandedRecurrenceCancel $cancel * @return ExpandedRecurrenceCancel|self */ public function cancel(ExpandedRecurrenceCancel $cancel = null) { if(null === $cancel) { return $this->child('cancel'); } return $this->child('cancel', $cancel); } }
Python
UTF-8
1,283
3.203125
3
[ "MIT" ]
permissive
#!/bin/python import sys import notify2 import subprocess from time import sleep def notification(message: str): """ Display notification to the desktop Task: 1. show() -> it will generate a complete new pop 2. update() -> it will update the payload part of same notification pop-up, not issuing any new one. Usage : python <filename.py> typeObj:str value:int objective:str typeObj: RAM/SWAP/NORMAL value: current usage of RAM or SWAP (for NORMAL, the value = 0) objective: show/update """ # initialize the notification notify2.init("notifywhenLOAD") notifyObj = notify2.Notification("Emergency Alert!", message) notifyObj.set_timeout(12000) return notifyObj def main(): a = notification(f"{sys.argv[1]} exceeds {sys.argv[2]}") if sys.argv[1] in ["RAM", "SWAP"] and sys.argv[3] == "update": a.update(f"{sys.argv[1]} Alert!! Warning for death") # a.update('river') a.set_urgency(2) a.show() elif sys.argv[1] in ["RAM", "SWAP"] and sys.argv[3] == "show": a.set_timeout(10000) a.set_urgency(1) a.show() elif sys.argv[1] == "NORMAL": a.update("ChiLLax!!! Nothing to worry about") a.set_urgency(0) a.show() main()
Markdown
UTF-8
4,065
2.796875
3
[]
no_license
--- id: 220 title: 'My Steam Box - PVR power management' date: 2014-05-07T20:00:50+00:00 author: mark layout: post guid: https://barrenfrozenwasteland.com/?p=220 permalink: /2014/05/my-steam-box-pvr-power-management/ categories: - HTPC --- **Update:** Updated post-record bash script for Ubuntu 16.04, and re-wrote ruby script to use HTTP instead of Telnet. I mentioned before that I&#8217;m using tvheadend and XBMC as a PVR on my Steam box/HTPC. This allows me to schedule recordings and do things like series link recordings to ensure I dont miss an episode. However, it does have the slight disadvantage that I need to leave a full-power PC on all the time, otherwise it can&#8217;t record. I needed a smarter solution for the sake of my electricity bill, so I devised a way to have the PC turn on when a recording is scheduled, do the recording, then power off again when its done. ## Power on to record My first discovery when hunting for a solution was the ACPI wake alarm feature. This allows you to set an alarm on your hardware clock at which point the computer will turn itself on, even if it&#8217;s completely powered off, just as though you&#8217;d pressed the power button. There&#8217;s a couple of steps I needed to enable this feature, found thanks to the [MythTV wiki](http://www.mythtv.org/wiki/ACPI_Wakeup#Using_.2Fsys.2Fclass.2Frtc.2Frtc0.2Fwakealarm). Firstly, it needed to be enabled in the BIOS/UEFI. The setting for my motherboard was called something like &#8220;Hardware Clock Wake Up&#8221;. Secondly, Ubuntu&#8217;s shutdown scripts overwrite the hardware clock with the current time, erasing any alarm set, so a small modification to /etc/init/hwclock-save.conf was required. This ensures that the alarm is written back to the hardware clock. With the feature enabled, I then needed a command to set the alarm. XBMC&#8217;s TV settings have a &#8220;Power Saving&#8221; section, with a &#8220;Set wakeup command&#8221; option. This lets you give a command which will be called with the unix timestamp of the next recording as an argument. I set this to `sudo /home/xbmc/wakeup.sh`. I used sudo since I needed permission to write to the wakealarm device, and added a sudoers rule to let XBMC run the command without a password: `xbmc ALL=NOPASSWD: /home/xbmc/wakeup.sh` Finally, the script itself: The business is all on lines 4 and 5. 4 clears any previous alarms, and 5 sets a new one using the passed timestamp. XBMC has a &#8220;Wakeup before recording&#8221; option which lets you adjust the timestamp arugment to be a few minutes ahead of the actual record time. This script is triggered whenever XBMC is shut down. ## Power off after recording Powering off was a bit of a trickier business. Tvheadend has a &#8220;Post-processor command&#8221; setting which executes after a recording completes, which is simple enough. However, just putting `shutdown -h now` in there isn&#8217;t enough, since it wont cause XBMC to call its wakeup script, meaning the next recording could be missed. XBMC&#8217;s shutdown or exit command has to be called explicitly for this to happen. Furthermore, I didn&#8217;t always want the system to turn off &#8211; what if I was watching something, or playing a game at the time? After some poking around, I found that using the shutdown button in XBMC&#8217;s web interface was sufficient to trigger the wakeup script. Furthermore, this was using XBMC&#8217;s JSONRPC interface, which could be fed commands by sending raw JSON strings over telnet. This gave me a way of triggering the shutdown and wakeup from a script, with the added bonus of giving me a way to find out if XBMC was currently playing something. This led to the creating of this ruby script and a bash script to call it: The bash script is the command actually called by tvheadend, which calls the ruby script. The ruby script checks that no other users are logged in, no video is playing in XBMC, then calls XBMC&#8217;s shut down routine, which in turn sets the alarm for the next recording. Job done!
Java
UTF-8
3,098
2.140625
2
[]
no_license
package com.zjtc.model; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.extension.activerecord.Model; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.Date; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * @author lianghao * @date 2021/01/15 */ @ApiModel(value ="用水单位监控表", description = "用水单位监控表") @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) @TableName("t_w_use_water_unit_monitor") public class UseWaterUnitMonitor extends Model<UseWaterUnitMonitor>{ @ApiModelProperty("主键") @TableId(value = "id", type = IdType.UUID) private String id; @ApiModelProperty("节点编码") @TableField(value = "node_code",exist = true) private String nodeCode; @ApiModelProperty("用水单位id") @TableField(value = "use_water_unit_id",exist = true) private String useWaterUnitId; @ApiModelProperty("单位编号") @TableField(value = "unit_code",exist = true) private String unitCode; @ApiModelProperty("单位名称") @TableField(value = "unit_name",exist = true) private String unitName; @ApiModelProperty("单位地址") @TableField(value = "unit_address",exist = true) private String unitAddress; @ApiModelProperty("所属行业id") @TableField(value = "industry",exist = true) private String industry; @ApiModelProperty("所属行业名称") @TableField(value = "industry_name",exist = true) private String industryName; @ApiModelProperty("年份") @TableField(value = "year",exist = true) private Integer year; @ApiModelProperty("监控类型") @TableField(value = "monitor_type",exist = true) private String monitorType; @ApiModelProperty("是否逻辑删除,1是0否") @TableField(value = "deleted",exist = true) private String deleted; @ApiModelProperty("创建人id") @TableField(value = "create_person_id",exist = true) private String createPersonId; @JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8") @ApiModelProperty("创建时间") @TableField(value = "create_time",exist = true,fill = FieldFill.INSERT) private Date createTime; @JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8") @ApiModelProperty("删除时间") @TableField(value = "delete_time",exist = true) private Date deleteTime; @ApiModelProperty("用户类型(查看时权限)") @TableField(value = "unit_code_type",exist = true) private String unitCodeType; /** * 实例化 */ public UseWaterUnitMonitor() { super(); } @Override protected Serializable pkVal() { return this.id; } }
Markdown
UTF-8
2,700
3.140625
3
[]
no_license
# project-basement Personal project, just fun for author. ## Version 1. 2017/07/10:发布1.0版本 2. 2017/07/14:发布2.0版本 3. 2017/07/17:发布3.0/3.1版本 4. 2017/07/19:发布3.2版本 5. 2017/07/31:发布4.1版本 ## 1.StringUtils.isEmpty() 与 StringUtils.isBlank()区别 1.1 isEmpty() : 判断字符串是否为空,当字符串为null、""时返回为true,当字符串为" "、"abc"时返回为false;<br/> 1.2 isBlank() : 判断字符串是否为空白,当字符串为null、""、" "时,返回为true,当字符串为"abc"时,返回为false;<br/> 1.3 isAnyBlank() : 判断参数可以是多个字符串,当多个字符串都满足isBlank()是返回true;<br/> 1.4 isNoneBlank() : 判断参数可以是多个字符串,底层逻辑是对isAnyBlank()取反;<br/> 1.5 isAnyEmpty() : 多个字符串参数,都满足isEmpty()是返回true;<br/> 1.6 isNoneEmpty() : 多个字符串参数,底层是对isAnyEmpty()取反;<br/> ## 2.集合是否为空的判断 2.1 单列集合(Set/List)判断使用CollectionUtils.isEmpty(Set/List set/list);<br/> 2.2 双列集合(Map)判断使用MapUtils.isEmpty(Map map);<br/> ## 3.数组为空的判断 3.1 判断数组是否为空,使用ArrayUtils.isEmpty(Object[] array);<br/> ## 4.spring-ioc操作 4.1 使用配置文件的方式,完成spring对bean的创建和管理;<br/> 4.2 通过配置文件,向bean对象中注入数组、集合、map等,以及注入其他对象;<br/> ## 5.spring-aop操作 5.1 使用配置文件小试面向切面操作;<br/> 5.2 注解方式使用向实现aop操作;<br/> 5.3 增强类中的方法实现aop;<br/> ## 6.重新管理项目 6.1 重新构建项目,新建maven子项目;<br/> ## 7.spring boot中使用定时任务 7.1 修改入口程序中使用<code>@EnableScheduling</code>注解实现定时任务: <pre><code>import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class MongoApplication { public static void main(String[] args) { SpringApplication.run(MongoApplication.class, args); } } </code></pre> 7.2 创建定时任务类,并使用<code>@Scheduled</code>实现定时任务; <pre><code>@Component //将定时任务类加入到spring容器中 public class MyTimer { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 3000) //每隔3秒中指定一次 public void timerRate() { System.out.println(sdf.format(new Date())); } } </code></pre> ## 8.Java8 8.1 Java8中stream的使用;<br/> 8.2 Java8中函数式接口的使用;<br/>
Java
UTF-8
530
1.8125
2
[]
no_license
package com.dp.nlp.review.udf; /** * Created by qiangwang on 15/3/13. */ public class ShopCategory { private static final int BEAUTY = 50; private static final int HAIR = 157; private static final int DANCE = 149; private static final int MANICURE = 160; private static final int YOGA = 148; private static final int COSMETIC = 123; private static final int FACE = 158; private static final int RESHAPE = 183; private static final int TEETH = 182; private static final int SLIM = 159; }
C#
UTF-8
2,396
2.71875
3
[ "MIT" ]
permissive
using System.Diagnostics; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; using SharpLearning.CrossValidation.TrainingTestSplitters; using SharpLearning.DecisionTrees.Learners; using SharpLearning.Examples.Properties; using SharpLearning.InputOutput.Csv; using SharpLearning.Metrics.Regression; namespace SharpLearning.Examples.CrossValidation { [TestClass] public class TrainTestSplitExamples { [TestMethod] public void TrainingTestSplitter_SplitSet() { #region Read data // Use StreamReader(filepath) when running from filesystem var parser = new CsvParser(() => new StringReader(Resources.winequality_white)); var targetName = "quality"; // read feature matrix (all columns different from the targetName) var observations = parser.EnumerateRows(c => c != targetName) .ToF64Matrix(); // read targets var targets = parser.EnumerateRows(targetName) .ToF64Vector(); #endregion // creates training test splitter, observations are shuffled randomly var splitter = new RandomTrainingTestIndexSplitter<double>(trainingPercentage: 0.7, seed: 24); var trainingTestSplit = splitter.SplitSet(observations, targets); var trainingSet = trainingTestSplit.TrainingSet; var testSet = trainingTestSplit.TestSet; var learner = new RegressionDecisionTreeLearner(); var model = learner.Learn(trainingSet.Observations, trainingSet.Targets); // predict test set var testPredictions = model.Predict(testSet.Observations); // metric for measuring model error var metric = new MeanSquaredErrorRegressionMetric(); // The test set provides an estimate on how the model will perform on unseen data Trace.WriteLine("Test error: " + metric.Error(testSet.Targets, testPredictions)); // predict training set for comparison var trainingPredictions = model.Predict(trainingSet.Observations); // The training set is NOT a good estimate of how well the model will perfrom on unseen data. Trace.WriteLine("Training error: " + metric.Error(trainingSet.Targets, trainingPredictions)); } } }
Markdown
UTF-8
367
2.671875
3
[]
no_license
## shell编程中的函数 --- ### 函数的定义 - 定义方式1 ```sh function name { commands return #可选 } ``` - 定义方式2 ```sh name() { commands return #可选 } ``` >注意:若函数体和花括号在一行中,则{和第一个命令,最后一个命令和}之间都需要一个空格 ### 函数中变量的作用域
C++
UTF-8
2,520
3.0625
3
[]
no_license
// Edge.cpp: implementation of the Edge class. #include <stdio.h> #include <math.h> #include <cstdlib> #include "Edge.h" #include "mEntity.h" #include "Vertex.h" Edge::Edge(Vertex *v1, Vertex *v2, gEntity *classification) //older function. { //currently being kept to keep splitting//refinement compatible edgeType=EDGE; //GRANT theAdjacencies[0] = new mDownwardAdjacencyContainer (2); theAdjacencies[0]->add(v1); theAdjacencies[0]->add(v2); theClassification = classification; unsigned long int i1 = v1->getId(); unsigned long int i2 = v2->getId(); iD = v1->getRAND() + v2->getRAND(); } Edge::Edge(vector<Vertex*>& v,int geomO, gEntity *classification) { vector<Vertex*>::iterator it; iD=0; theAdjacencies[0] = new mDownwardAdjacencyContainer (v.size()); edgeType=EDGE; geomOrder = geomO; theClassification = classification; //Note:In the older version, id's were assigned as for (it = v.begin(); it != v.end(); it++) //unsigned long ints but not used. what was this for? { //GRANT theAdjacencies[0]->add(*it); iD+=(*it)->getRAND(); } } Edge::~Edge() { //printf("Deleting edge with id = %d \n",iD); int j, nb; if (theAdjacencies[0]) { nb = theAdjacencies[0]->size(); for (j=0;j<nb;++j) //deleting pointers to this element from its vertices theAdjacencies[0]->get(j)->del(this); } if (theAdjacencies[1]) { nb = theAdjacencies[1]->size(); //deleting pointer to this element from its parent(?) or child(?) for (j=0;j<nb;++j) theAdjacencies[1]->get(j)->del(this); } if (theAdjacencies[2]) { printf("faces should be destructed first \n"); exit(0); } if (theAdjacencies[3]) { printf("~Edge: don't know how to destruct in3D\n"); exit(0); } } int Edge::getNbTemplates(int what)const //returns the number of vertices { if(what == 0) return (theAdjacencies[0]->size()); else return 0; } Vertex *Edge::vertex(int i) const { return (Vertex*)theAdjacencies[0]->get(i); } Vertex *Edge::commonVertex(Edge *other) const { //Note that the secondary vertices are not compared //as this information is currently irrelevant. if(other->vertex(0) == vertex(0))return vertex(0); if(other->vertex(1) == vertex(0))return vertex(0); if(other->vertex(0) == vertex(1))return vertex(1); if(other->vertex(1) == vertex(1))return vertex(1); return 0; } void Edge::print()const { printf("edge %p with Id %d and vertices ",this,iD); for (int i = 0;i<(geomOrder+1);i++) printf("%d ",get(0,i)->getId()); printf("\n"); }
Java
UTF-8
516
2.6875
3
[]
no_license
package kit.pse.hgv.controller.commandController.commands; /** * This class manages the commands that register an extension */ public class RegisterExtensionCommand extends ExtensionCommand { private final String path; /** * The constructor creates an element of this class * * @param path Path of the extension that should be added in the system */ public RegisterExtensionCommand(String path) { this.path = path; } @Override public void execute() { } }
Markdown
UTF-8
2,433
2.984375
3
[]
no_license
# BGA Style Guide ## Github pages The BGA Style Guide runs on a github pages hosting platform, this means that the website is written in html, scss, markdown and liquid, and uses jekyll to compile into a site. The website can be compiled locally using jekyll, or can be pushed to a github repository using the branch name `gh-pages`, where github will compile it and host it. The site is hosted at [https://ausgov.github.io/bga-style-guide](https://ausgov.github.io/bga-style-guide/). ## Pulling the style guide To pull the bga style guide, go to [https://github.com/AUSGov/bga-style-guide](https://github.com/AUSGov/bga-style-guide) and clone the site to a local directory. In order to run the site locally, follow the steps for installation found at [https://jekyllrb.com/docs/installation/](https://jekyllrb.com/docs/installation). If you are trying to run the site on a windows machine, then try following to steps for windows found at [https://jekyllrb.com/docs/windows/#installation](https://jekyllrb.com/docs/windows/#installation) (I have not tried these steps). Once you have Jekyll installed on your machine, use terminal to cd into the project directory. ```cd ~/Desktop/bga-style-guide``` Once in the project directory, run the following command to fire up a local server and compile the directory. ```jekyll serve --baseurl ''``` `jekyll serve` fires up a local server, the `--baseurl ''` tells jekyll to override the `baseurl` variable in `_config.yml` to and empty string. The `baseurl` is set to `/bga-style-guide` otherwise - so that the relative links work once it's hosted on github. After running the jekyll serve command, you will see that you project directory now has a subdirectory called `_site`, this is where the compiled files sit. They are ignored by the `.gitignore` file, as they shouldn't be pushed to the remote repository. Navigate to localhost:4000 to see the local version of the compiled site. ## The future The future aim of this site is to provide guideance on UI and design decisions, as well as to provide information on what styles should be used for consistency across bga websites. As a part of this, we hope to be able to use this site to link to scss files, such as a _variables.scss file that can be pulled down and used as the base for all sites. This way if any changes are made to code that is common across sites, it can be pulled down, tested and implemented.
Ruby
UTF-8
225
2.9375
3
[]
no_license
def mydecorator(f): def swrap_f(*args, **kw): print(__name__) print('function will be called') return f(*args, **kw) return swrap_f @mydecorator def hello_decorator(): print('be called') hello_decorator()
Python
UTF-8
363
3.28125
3
[]
no_license
def print_formatted(number): # your code goes here #Octal i=1 l=''; while i<=number: o=str(oct(i));h=str(hex(i));b=str(bin(i)); o1=str(o[2:]);h1=str(h[2:]);b1=str(b[2:]); l=l+str(i)+' '+o1+' '+h1+' '+b1+'\n' i+=1 print(l) return if __name__ == '__main__': n = int(input()) print_formatted(n)
C++
UTF-8
686
3.1875
3
[]
no_license
#include <vector> #include <iostream> #include <algorithm> using namespace std; void partition(vector <int> ar) { int pivot = ar[0]; int i=0, j=1; int t = 0; for(; j<ar.size(); j++) { if(ar[j] < pivot ) { i++; int temp = j; int value = ar[j]; for(; temp>i; temp-- ) swap(ar[temp] , ar[temp-1]); } } for(int k=0; k<i; k++) swap(ar[k], ar[k+1]); for(int i=0; i<ar.size(); i++) cout<<ar[i]<<" "; cout<<endl; } int main(void) { vector <int> _ar; int _ar_size; cin >> _ar_size; for(int _ar_i=0; _ar_i<_ar_size; _ar_i++) { int _ar_tmp; cin >> _ar_tmp; _ar.push_back(_ar_tmp); } partition(_ar); return 0; }
SQL
UTF-8
769
3.390625
3
[ "Apache-2.0" ]
permissive
use ejercicio1; create table medico ( id int primary key auto_increment, nombre varchar(10) not null, apellidos varchar(20) not null, telefono int not null, especialidad varchar(20) ); create table paciente ( id int primary key auto_increment, codigo_postal int not null, telefono int, fecha_nacimiento datetime not null, nombre varchar(10) not null, apellidos varchar(20) not null, direccion varchar(255) not null, poblacion varchar(20) not null, provincia varchar (20) not null ); create table ingreso ( id int primary key auto_increment, num_habitacion int not null, cama int not null, fecha datetime not null, id_paciente int not null, id_medico int not null, foreign key (id_paciente) references paciente(id), foreign key (id_medico) references medico(id) );
SQL
UTF-8
2,259
2.875
3
[]
no_license
CREATE DATABASE IF NOT EXISTS `bdeducacio` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_spanish_ci */; USE `bdeducacio`; -- MySQL dump 10.13 Distrib 5.6.13, for Win32 (x86) -- -- Host: 127.0.0.1 Database: bdeducacio -- ------------------------------------------------------ -- Server version 5.6.14 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `assignatures` -- DROP TABLE IF EXISTS `assignatures`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `assignatures` ( `idassignatures` int(11) NOT NULL, `nom` varchar(45) COLLATE utf8_spanish_ci DEFAULT NULL, `nota` int(11) DEFAULT NULL, PRIMARY KEY (`idassignatures`), CONSTRAINT `id` FOREIGN KEY (`idassignatures`) REFERENCES `alumne` (`idalumne`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `assignatures` -- LOCK TABLES `assignatures` WRITE; /*!40000 ALTER TABLE `assignatures` DISABLE KEYS */; /*!40000 ALTER TABLE `assignatures` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2014-02-12 12:21:56
Java
UTF-8
2,791
2.34375
2
[]
no_license
package com.mtuci.bsu1701.is.controllers; import com.mtuci.bsu1701.is.configs.JwtTokenUtil; import com.mtuci.bsu1701.is.entities.dtos.RegistrationUserRequestDto; import com.mtuci.bsu1701.is.entities.dtos.securityDtos.JwtRequest; import com.mtuci.bsu1701.is.entities.dtos.securityDtos.JwtResponse; import com.mtuci.bsu1701.is.exceptions.securityExceptions.exceptions.LogInError; import com.mtuci.bsu1701.is.exceptions.securityExceptions.exceptions.UserAlreadyExistsException; import com.mtuci.bsu1701.is.services.UserService; import lombok.AllArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; @AllArgsConstructor @RestController public class AuthController { private final UserService userService; private final JwtTokenUtil jwtTokenUtil; private final AuthenticationManager authenticationManager; @PostMapping("/auth") public ResponseEntity<?> createAuthToken(@RequestBody JwtRequest authRequest) { try { authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword())); } catch (BadCredentialsException ex) { return new ResponseEntity<>(new LogInError(HttpStatus.UNAUTHORIZED.value(), "Incorrect username or password"), HttpStatus.UNAUTHORIZED); } UserDetails userDetails = userService.loadUserByUsername(authRequest.getUsername()); String token = jwtTokenUtil.generateToken(userDetails); return ResponseEntity.ok(new JwtResponse(token)); } @PostMapping("/registration") public ResponseEntity<?> registerNewUser(@Valid @RequestBody RegistrationUserRequestDto registrationUserRequestDto) { try { userService.tryToRegisterUser(registrationUserRequestDto); } catch (UserAlreadyExistsException ex) { return new ResponseEntity<>(new LogInError(HttpStatus.BAD_REQUEST.value(), String.format("Пользователь с никнеймом %s уже существует!",registrationUserRequestDto.getUsername())), HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(new LogInError(HttpStatus.OK.value(), "Регистрация прошла успешно!"), HttpStatus.OK); } }
C#
UTF-8
687
3.21875
3
[ "MIT" ]
permissive
namespace AnimalKindom.Models { using AnimalKindom.Interfaces; public class PetHamster : Hamster, IPet { public PetHamster() { this.Owner = "Pesho"; } public string Owner { get; private set; } public decimal Price { get { throw new System.NotImplementedException(); } } public override string ProvokeHappiness() { //извиква от базовия клас ProvokeHappiness return base.ProvokeHappiness() + "his name is" + this.Owner; } //{ //System.Console.WriteLine("{0} is happy", this.Owner); //} } }
Java
UTF-8
16,671
2.0625
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 clinicadesktop; import DOA.PacienteDao; import DOA.RastreioDao; import MODEL.PacienteModel; import MODEL.RastreioModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * * @author joao.c */ public class Rastreio extends javax.swing.JPanel { DefaultComboBoxModel paciente_list = new DefaultComboBoxModel(); private JFrame frame; public Rastreio() { initComponents(); for(PacienteModel _paciente : new PacienteDao().getAll()){ paciente_list.addElement(_paciente); } NamePaciente.setModel(paciente_list); DefaultComboBoxModel status_list = new DefaultComboBoxModel(); status_list.addElement("Moderado"); status_list.addElement("Urgente"); status_list.addElement("Grave"); EstadoSelect.setModel(status_list); frame = new JFrame(); frame.setSize(1500, 900); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); TemperaturaInput = new javax.swing.JTextField(); PressaoInput = new javax.swing.JTextField(); PesoInput = new javax.swing.JTextField(); NomePacienteLabel = new javax.swing.JLabel(); TemperatursLabel = new javax.swing.JLabel(); PessaoLabel = new javax.swing.JLabel(); PesoLabel = new javax.swing.JLabel(); RegistarBtn = new javax.swing.JButton(); CancelarBtn = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); NamePaciente = new javax.swing.JComboBox(); EstadoLabel = new javax.swing.JLabel(); EstadoSelect = new javax.swing.JComboBox(); TemperaturaInput.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TemperaturaInputActionPerformed(evt); } }); PressaoInput.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { PressaoInputActionPerformed(evt); } }); PesoInput.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { PesoInputActionPerformed(evt); } }); NomePacienteLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N NomePacienteLabel.setText("Nome do paciente"); TemperatursLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N TemperatursLabel.setText("Temperatura"); PessaoLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N PessaoLabel.setText("Pressão"); PesoLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N PesoLabel.setText("Peso"); RegistarBtn.setBackground(new java.awt.Color(0, 204, 0)); RegistarBtn.setForeground(new java.awt.Color(255, 255, 255)); RegistarBtn.setText("Registar"); RegistarBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RegistarBtnActionPerformed(evt); } }); CancelarBtn.setBackground(new java.awt.Color(255, 255, 255)); CancelarBtn.setText("Cancelar"); CancelarBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CancelarBtnActionPerformed(evt); } }); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 48)); // NOI18N jLabel5.setForeground(new java.awt.Color(0, 51, 51)); jLabel5.setText("FAZER RASTREIO"); jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Assets/logotipo.png"))); // NOI18N NamePaciente.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); NamePaciente.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NamePacienteActionPerformed(evt); } }); EstadoLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N EstadoLabel.setText("Estado"); EstadoSelect.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); EstadoSelect.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EstadoSelectActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(121, 121, 121) .addComponent(jLabel7) .addGap(90, 90, 90) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(PessaoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(PressaoInput, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel5) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(TemperatursLabel) .addGap(18, 18, 18)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(NomePacienteLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(2, 2, 2)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(PesoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(NamePaciente, javax.swing.GroupLayout.PREFERRED_SIZE, 398, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TemperaturaInput, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(PesoInput, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EstadoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EstadoSelect, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(RegistarBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CancelarBtn))))) .addContainerGap(248, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(162, 162, 162) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(48, 48, 48) .addComponent(jLabel5) .addGap(31, 31, 31) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(NamePaciente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(NomePacienteLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(TemperatursLabel) .addComponent(TemperaturaInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(12, 12, 12) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(PressaoInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(PessaoLabel)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(PesoInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(PesoLabel) .addComponent(EstadoLabel) .addComponent(EstadoSelect, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(RegistarBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(CancelarBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(234, 234, 234)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(205, 205, 205)))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 13, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void CancelarBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelarBtnActionPerformed MainClinica init = new MainClinica(); frame.add(init); frame.setVisible(true); }//GEN-LAST:event_CancelarBtnActionPerformed private void RegistarBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RegistarBtnActionPerformed // TODO add your handling code here: try{ PacienteModel current_paciente = (PacienteModel)NamePaciente.getSelectedItem(); String estado = (String)EstadoSelect.getSelectedItem(); int temperatura = Integer.parseInt(TemperaturaInput.getText());; int peso = Integer.parseInt(PesoInput.getText());; int pressao = Integer.parseInt(PressaoInput.getText());; RastreioModel new_rastreio = new RastreioModel(); new_rastreio.setTemperatura(temperatura); new_rastreio.setPeso(peso); new_rastreio.setPressao(pressao); new_rastreio.setEstado(estado); new_rastreio.setId_paciente(current_paciente.getId_paciente()); RastreioDao dao = new RastreioDao(); boolean response = dao.Create(new_rastreio); if(response){ JOptionPane.showMessageDialog(null, "Paciente rastreado com sucesso"); initForm(); MainClinica init = new MainClinica(); frame.add(init); frame.setVisible(true); } }catch(Exception e){ JOptionPane.showMessageDialog(null, e.getMessage()); } }//GEN-LAST:event_RegistarBtnActionPerformed private void PesoInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PesoInputActionPerformed // TODO add your handling code here: }//GEN-LAST:event_PesoInputActionPerformed private void PressaoInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PressaoInputActionPerformed // TODO add your handling code here: }//GEN-LAST:event_PressaoInputActionPerformed private void TemperaturaInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TemperaturaInputActionPerformed // TODO add your handling code here: }//GEN-LAST:event_TemperaturaInputActionPerformed private void NamePacienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NamePacienteActionPerformed }//GEN-LAST:event_NamePacienteActionPerformed private void EstadoSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EstadoSelectActionPerformed // TODO add your handling code here: }//GEN-LAST:event_EstadoSelectActionPerformed public void initForm(){ TemperaturaInput.setText(""); PressaoInput.setText(""); PesoInput.setText(""); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton CancelarBtn; private javax.swing.JLabel EstadoLabel; private javax.swing.JComboBox EstadoSelect; private javax.swing.JComboBox NamePaciente; private javax.swing.JLabel NomePacienteLabel; private javax.swing.JTextField PesoInput; private javax.swing.JLabel PesoLabel; private javax.swing.JLabel PessaoLabel; private javax.swing.JTextField PressaoInput; private javax.swing.JButton RegistarBtn; private javax.swing.JTextField TemperaturaInput; private javax.swing.JLabel TemperatursLabel; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel1; // End of variables declaration//GEN-END:variables }
Markdown
UTF-8
1,150
2.890625
3
[]
no_license
# SpringBootLog O objetivo foi criar uma aplicação em Java para fazer o upload de um arquivo de logs populando o banco de dados. Para isso, será necessário uma interface para o upload do arquivo de logs e uma para inserir/editar/listar/consultar/pesquisar (CRUD). Implementar o back-end com (Spring ou JavaEE/MicroProfile usando java 11) e front-end Angular 6+. Detalhes do back-end Definir o modelo de dados no PostgreSQL; Definir serviços para envio do arquivo de logs fornecido, e inserção dos logs em massa usando JPA (não utilizar spring-data-jpa); Definir serviços para inserção de logs manuais (CRUD) Implementar filtros ou pesquisas de logs; Testes Unitários; (BÔNUS) Testes de Integração. Detalhes do front-end Tela para inserção de logs manuais (CRUD). Tela para inserção de logs usando o arquivo modelo. (BÔNUS) Uma tela (dashboard) para exibir os logs feitos por um determinado IP, por hora, user-agent (agregação). Detalhes do arquivo de log Data, IP, Request, Status, User Agent (delimitado por aspas duplas); O delimitador do arquivo de log é o caracter pipe |; Formato de data: yyyy-MM-dd HH:mm:ss.SSS;
Markdown
UTF-8
1,809
2.671875
3
[]
no_license
# Irregularly Clipped Sparse Regression Codes [arXiv](https://arxiv.org/abs/2106.01573), [PDF](https://arxiv.org/pdf/2106.01573.pdf) ## Authors - Wencong Li - Lei Liu - Brian M. Kurkoski ## Abstract Recently, it was found that clipping can significantly improve the section error rate (SER) performance of sparse regression (SR) codes if an optimal clipping threshold is chosen. In this paper, we propose irregularly clipped SR codes, where multiple clipping thresholds are applied to symbols according to a distribution, to further improve the SER performance of SR codes. Orthogonal approximate message passing (OAMP) algorithm is used for decoding. Using state evolution, the distribution of irregular clipping thresholds is optimized to minimize the SER of OAMP decoding. As a result, optimized irregularly clipped SR codes achieve a better tradeoff between clipping distortion and noise distortion than regularly clipped SR codes. Numerical results demonstrate that irregularly clipped SR codes achieve 0.4 dB gain in signal-to-noise-ratio (SNR) over regularly clipped SR codes at code length$\,\approx2.5\!\times\! 10^4$ and SER$\,\approx10^{-5}$. We further show that irregularly clipped SR codes are robust over a wide range of code rates. ## Comments 6 pages, 4 figures, submitted to IEEE ITW 2021 ## Source Code Official Code Community Code - [https://paperswithcode.com/paper/irregularly-clipped-sparse-regression-codes](https://paperswithcode.com/paper/irregularly-clipped-sparse-regression-codes) ## Bibtex ```tex @misc{li2021irregularly, title={Irregularly Clipped Sparse Regression Codes}, author={Wencong Li and Lei Liu and Brian M. Kurkoski}, year={2021}, eprint={2106.01573}, archivePrefix={arXiv}, primaryClass={cs.IT} } ``` ## Notes Type your reading notes here...
Markdown
UTF-8
1,142
2.875
3
[]
no_license
# Quete_Entity_Framework_LINQ La protection de la faune La diversité de la faune terrienne est en chute libre. Cela est principalement du à nos actes en tant qu'humains mais aussi à cause des lois de l'évolution. Quoiqu'il en soit, en tant qu'association de protection de la faune, nous désirons pouvoir mettre au point un système permettant de tracer l'évolution des espèces protégées. # Challenge Tenir compte des espèces protégées Tu vas faire un programme qui permet de tenir compte des espèces protégées dans le monde. Il y a trois espèces que nous cherchons à protéger: Les cougars blancs - Il en reste 3 Les tigres blancs - Il en reste 100 Les tortues albinos - Il en reste 15 # Critères de validation Le programme affiche dans un MessageBox par espèce le nombre d'animaux recensés, chaque espèce à la ligne La base de données est générée grâce à l'approche Code-First de EntityFramework Une entité Animal qui représente un animal. L'animal appartient à une et une seule espèce Une entité Species qui représente une espèce d'animal Les méthodes LINQ sont utilisées pour recenser les animaux
JavaScript
UTF-8
360
2.6875
3
[]
no_license
export const heroes = [ {id:1, name: 'Batman', owner: 'DC'}, {id:2, name: 'Spiderman', owner: 'Marvel'}, {id:3, name: 'Peter Stancheck', owner: 'Valiant'} ] export const getHeroeById = (id) => heroes.find( (heroe) => heroe.id === id ); // find?, filter export const getHeroesByOwner = ( owner ) => heroes.filter( (heroe) => heroe.owner === owner );
Python
UTF-8
3,139
2.578125
3
[]
no_license
import pyaudio from aip import AipSpeech from xpinyin import Pinyin def RecodeSound(): import wave CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 8000 RECORD_SECONDS = 10 WAVE_OUTPUT_FILENAME = "audio.wav" APP_ID='19165306' API_KEY='F0NWZzLVAnModNc6OG820Gu7' SECRET_KEY=' M8enxlGmxLqSeFxpV9XHgwI50sHk6486' client =AipSpeech(APP_ID,API_KEY,SECRET_KEY) p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) stream.start_stream() print("* 开始录音......") frames = [] for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) stream.stop_stream() #录音结束 wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb') wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) wf.writeframes(b''.join(frames)) wf.close() with open('audio.wav','rb') as fp: wave=fp.read() print("*正在识别......",len(wave)) result=client.asr(wave,'wav',16000,{'dev_pid':1537}) #print(result) if '。' in result['result'][0]: result['result'][0]=result['result'][0].replace('。','') if result["err_no"]==0: k='' for t in result['result']: k+=t command=MinecraftCommand(k) else: print("没有识别到语音\n",result["err_no"]) return 'Error' if command[0]=='w' or command[0]=='a' or command[0]=='s' or command[0]=='d': if command[1]>9: print('距离较远,开始传送') else: pass return command else: print('指令有误,请重新读入') return RecodeSound() def NumSel(text): num='' for i in text: if i>='0' and i<='9': num=num+i else: pass print(num) return int(num) def MinecraftCommand(text): cmd=[] p = Pinyin() ptxt = p.get_pinyin(text) print(ptxt) if p.get_pinyin('前进') in ptxt: cmd.append('w') elif p.get_pinyin('后退') in ptxt: cmd.append('s') elif p.get_pinyin('左转') in ptxt or p.get_pinyin('向左') in ptxt: cmd.append('a') elif p.get_pinyin('右转') in ptxt or p.get_pinyin('向右') in ptxt: cmd.append('d') else: pass if '一' in text: cmd.append(1) elif '二' in text: cmd.append(2) elif '三' in text: cmd.append(3) elif '四' in text: cmd.append(4) elif '五' in text: cmd.append(5) elif '六' in text: cmd.append(6) elif '七' in text: cmd.append(7) elif '八' in text: cmd.append(8) elif '九' in text: cmd.append(9) else: cmd.append(NumSel(text)) return cmd if __name__=='__main__': CMD=RecodeSound() print(CMD)
Python
UTF-8
645
2.53125
3
[]
no_license
import numpy as np round_to = 5 r = np.array([11,16,5]) C_1 = np.array([40,38,22]) C_s = 28371 T = 42 def task2(r, C_1, C_s, T, t_s=None, if_print=True): if t_s is None: t_s = round(np.sqrt((2*C_s)/sum(C_1*r)), round_to) q = r*t_s D = round(sum(C_1*r)*t_s*T/2 + C_s*T/t_s, round_to) else: q = r*t_s D = round(sum(C_1*r)*t_s*T/2 + C_s*T/t_s, round_to) if if_print: print(f'\ t_s = {t_s}\ q_i = {q}\ D = {D}\ ') return (t_s, q, D) optimum = task2(r, C_1, C_s, T) half_ts = task2(r,C_1, C_s,T, t_s=3.5) two_ts = task2(r,C_1, C_s,T, t_s=14)
Markdown
UTF-8
1,189
2.984375
3
[]
no_license
# 网络图片批量下载 当我在写 [36Photo](https://github.com/dolphin836/36Photo) 项目时,需要从网络上下载一些免费的图片,于是就有了这个项目。 目前已经支持的网站 | 名称 | 地址 | 存储目录 | 命令 | | -------- | :----- | :----- | :----- | | Unsplash | [https://unsplash.com](https://unsplash.com) | /Photo/Unsplash | php unsplash.php | | Awesome Wallpapers | [https://alpha.wallhaven.cc](https://alpha.wallhaven.cc) | /Photo/Wallhaven | php wallhaven.php | | Bing | [https://bing.ioliu.cn](https://bing.ioliu.cn) | /Photo/Bing | php bing.php | | Konachan | [https://konachan.com](https://konachan.com) | /Photo/Konachan | php konachan.php | | Shopify | [https://burst.shopify.com](https://burst.shopify.com) | /Photo/Shopify | php shopify.php | ## 使用 1. 通过 Git 拉取项目到本地 ``` $ git clone https://github.com/dolphin836/Photo.git ``` 2. 进入项目根目录(默认名称 Photo),安装项目 ``` $ composer install ``` 3. 在根目录下创建 Photo 照片存储目录,并在 Photo 目录下创建每个网站各自对应的存储目录,Linux 系统注意首字母大写; 4. 运行下载命令
PHP
UTF-8
1,371
2.734375
3
[]
no_license
<?php /** * BaseModel, EVERY model extends form this * * @author Flavio Kleiber <flaverkleiber@yahoo.de> * @copyright 2016-2018 Flavio Kleiber */ namespace Solaria\Framework\Application\Mvc; use Solaria\Framework\Core\Application; class BaseModel { public function save($obj) { $entityManager = Application::$di->get('EntityManager'); $entityManager->persist($obj); $entityManager->flush(); return $obj; } public function update($obj) { $entityManager = Application::$di->get('EntityManager'); $entityManager->merge($obj); $entityManager->flush(); return true; } public function delete($obj) { $entityManager = Application::$di->get('EntityManager'); $entityManager->remove($obj); $entityManager->flush(); return true; } public static function findAll() { return self::getRepo()->findAll(); } public static function findBy($search) { return self::getRepo()->findBy($search); } public static function find($id) { $entityManager = Application::$di->get('EntityManager'); return $entityManager->find(get_called_class(), $id); } private static function getRepo() { $entityManager = Application::$di->get('EntityManager'); $repo = $entityManager->getRepository(get_called_class()); return $repo; } }
Swift
UTF-8
1,045
2.6875
3
[]
no_license
// // SettingVC.swift // WeatherAppDemo // // Created by vivek G on 13/09/21. // import UIKit class SettingVC: UIViewController { @IBOutlet weak var txtCelcious : UITextField! @IBOutlet weak var txtFarenhite : UITextField! @IBOutlet weak var lblCelConvResult : UILabel! @IBOutlet weak var lblFarConvResult : UILabel! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Setting" // Do any additional setup after loading the view. } @IBAction func CelciousToFeranhite(sender:Any) { self.view.endEditing(true) let iFarenheit = Decimal(string: txtCelcious.text ?? "0.0")?.celciousToFarenheit self.lblCelConvResult.text = "Fahrenheit : \(iFarenheit ?? "0.0")" } @IBAction func FeranhiteToCelcious(sender:Any) { self.view.endEditing(true) let iCelcious = Decimal(string: txtFarenhite.text ?? "0.0")?.FarenheitToCelcious self.lblFarConvResult.text = "Celcious :\(iCelcious ?? "0.0") " } }
Ruby
UTF-8
524
3.5
4
[]
no_license
def is_palindrome (instr) return instr == instr.reverse end def find_palindromes (input) print input, ": " seen = {} for start in 0 .. input.length - 1 do for endstr in start .. input.length - 1 do cand = input[start .. endstr] if is_palindrome(cand) and not seen[cand] then print cand, " " seen[cand] = 1 end end end puts " " end for test in ["redivider", "rotors", "challenge"] do find_palindromes(test) end