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
563
2.671875
3
[]
no_license
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApplication11.Controllers { public class HelloWorldController : Controller { public string Index() { return "Default action"; } public string Welcome(string name) { return $"welcome {name}"; } public string Info(string name,int age) { return $"welcome {name} your age is {age}"; } } }
Java
UTF-8
298
1.757813
2
[]
no_license
public class KnowledgeBase { static boolean arrowUsed = false; static int agentX = 0, agentY = 0; static String facing = "right"; static int score = 0, timesAtStart = 0; static boolean noSafeMoves = false, scream = false; static Slot[][] knowledgeBoard = new Slot[4][4]; }
Python
UTF-8
802
2.875
3
[ "MIT" ]
permissive
import collections import datetime import arrow def none_default_namedtuple(typename, field_names, default_values=()): """ Helper function for defining a namedtuple with defined defaults """ T = collections.namedtuple(typename, field_names) T.__new__.__defaults__ = (None,) * len(T._fields) if isinstance(default_values, collections.Mapping): prototype = T(**default_values) else: prototype = T(*default_values) T.__new__.__defaults__ = tuple(prototype) return T def normalise_to_isoformat(val): if isinstance(val, dict): d = {} for k, v in val.iteritems(): d[k] = normalise_to_isoformat(v) return d return arrow.get(val).isoformat() if isinstance(val, (datetime.datetime, datetime.date)) else val
Rust
UTF-8
2,848
2.921875
3
[]
no_license
use log::debug; use super::CrosswordGrid; impl CrosswordGrid { pub fn count_all_words(&self) -> usize { self.word_map.len() } pub fn count_placed_words(&self) -> usize { self.word_map.values().filter(|w| w.is_placed()).count() } pub fn count_unplaced_words(&self) -> usize { self.word_map.values().filter(|w| !w.is_placed()).count() } pub fn count_intersections(&self) -> usize { let mut intersections: usize = 0; for cell in self.cell_map.values() { if cell.is_intersection() { intersections += 1 } } intersections } pub fn get_grid_dimensions_with_buffer(&self) -> (usize, usize) { let nrows: usize = (self.bottom_right_cell_index.0 - self.top_left_cell_index.0 + 1) as usize; let ncols: usize = (self.bottom_right_cell_index.1 - self.top_left_cell_index.1 + 1) as usize; (nrows, ncols) } pub fn get_grid_dimensions(&self) -> (usize, usize) { let nrows: usize = (self.bottom_right_cell_index.0 - self.top_left_cell_index.0 - 1) as usize; let ncols: usize = (self.bottom_right_cell_index.1 - self.top_left_cell_index.1 - 1) as usize; (nrows, ncols) } pub fn count_filled_cells(&self) -> usize { self.cell_map.values().filter(|c| c.contains_letter()).count() } pub fn count_empty_cells(&self) -> usize { let (nrows, ncols) = self.get_grid_dimensions(); nrows * ncols - self.count_filled_cells() } pub fn average_intersections_per_word(&self) -> f64 { let mut percent_intersection_per_word: Vec<f64> = vec![]; for word in self.word_map.values() { if let Some((start, _end, direction)) = word.get_location() { let mut intersections: f64 = 0.0; let mut cells: f64 = 0.0; let mut location = start; debug!("{:?}", word); for _i in 0..word.word_text.len() { let cell = self.cell_map.get(&location).unwrap(); debug!("{:?}", cell); assert!(cell.contains_letter(), "Expected cell {:?} in word {:?} to contain letter",location, word); cells += 1.0; if cell.is_intersection() { intersections += 1.0; } location = location.relative_location_directed(1, direction); } debug!("{:.0}/{:.0} = {:.2}", intersections, cells, intersections / cells); percent_intersection_per_word.push(intersections / cells); } } debug!("{:?}", percent_intersection_per_word); percent_intersection_per_word.iter().sum::<f64>() / (percent_intersection_per_word.len() as f64) } }
PHP
UTF-8
5,286
2.5625
3
[ "MIT" ]
permissive
<?php namespace Game\ItemBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping\DiscriminatorColumn; use Doctrine\ORM\Mapping\DiscriminatorMap; /** * Item * * @ORM\Entity(repositoryClass="Game\ItemBundle\Entity\Repository\ItemRepository") * @ORM\Table() * @ORM\InheritanceType("JOINED") * @DiscriminatorColumn(name="type", type="smallint") * @DiscriminatorMap({ * "1" = "Game\ItemBundle\Entity\Weapon", * "2" = "Game\ItemBundle\Entity\Armor", * "3" = "Game\ItemBundle\Entity\Potion"}) */ abstract class Item { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * @var integer * * @ORM\Column(name="value", type="integer") */ private $value; /** * @var string * * @ORM\Column(name="image", type="string", length=255, nullable=true) */ private $image; /** * @ORM\OneToMany(targetEntity="Game\CharacterBundle\Entity\CharacterItem", mappedBy="item") */ protected $characterItems; /** * @ORM\OneToMany(targetEntity="Game\ShopBundle\Entity\ShopItem", mappedBy="item") */ protected $shopItems; /** * @ORM\OneToMany(targetEntity="Game\MonsterBundle\Entity\LootItem", mappedBy="item") */ protected $lootItems; /** * @var boolean * * @ORM\Column(name="is_equipable", type="boolean") */ private $isEquipable; /** * @var boolean * * @ORM\Column(name="is_usable", type="boolean") */ private $isUsable; public function __construct() { } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * @return Item */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Add characterItems * * @param \Game\CharacterBundle\Entity\CharacterItem $characterItems * @return Item */ public function addCharacterItem(\Game\CharacterBundle\Entity\CharacterItem $characterItems) { $this->characterItems[] = $characterItems; return $this; } /** * Remove characterItems * * @param \Game\CharacterBundle\Entity\CharacterItem $characterItems */ public function removeCharacterItem(\Game\CharacterBundle\Entity\CharacterItem $characterItems) { $this->characterItems->removeElement($characterItems); } /** * Get characterItems * * @return \Doctrine\Common\Collections\Collection */ public function getCharacterItems() { return $this->characterItems; } /** * Set value * * @param integer $value * @return Item */ public function setValue($value) { $this->value = $value; return $this; } /** * Get value * * @return integer */ public function getValue() { return $this->value; } /** * Add shopItems * * @param \Game\ShopBundle\Entity\ShopItem $shopItems * @return Item */ public function addShopItem(\Game\ShopBundle\Entity\ShopItem $shopItems) { $this->shopItems[] = $shopItems; return $this; } /** * Remove shopItems * * @param \Game\ShopBundle\Entity\ShopItem $shopItems */ public function removeShopItem(\Game\ShopBundle\Entity\ShopItem $shopItems) { $this->shopItems->removeElement($shopItems); } /** * Get shopItems * * @return \Doctrine\Common\Collections\Collection */ public function getShopItems() { return $this->shopItems; } /** * @param string $image */ public function setImage($image) { $this->image = $image; } /** * @return string */ public function getImage() { return $this->image; } /** * @param mixed $lootItems * @return $this */ public function setLootItems($lootItems) { $this->lootItems = $lootItems; return $this; } /** * @return mixed */ public function getLootItems() { return $this->lootItems; } /** * @param boolean $isEquipable * @return $this */ public function setIsEquipable($isEquipable) { $this->isEquipable = $isEquipable; return $this; } /** * @return boolean */ public function getIsEquipable() { return $this->isEquipable; } /** * @param boolean $isUsable * @return $this */ public function setIsUsable($isUsable) { $this->isUsable = $isUsable; return $this; } /** * @return boolean */ public function getIsUsable() { return $this->isUsable; } }
PHP
UTF-8
4,453
2.8125
3
[]
no_license
<?php // Starting the session session_start(); require_once('MiniTemplator.class.php'); require_once('twitteroauth-master/twitteroauth/OAuth.php'); require_once('twitteroauth-master/twitteroauth/twitteroauth.php'); require_once('twitteroauth-master/config.php'); // Get user access tokens out of the session $access_token = $_SESSION['access_token']; // Create a TwitterOauth object with consumer/user tokens $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']); // If method is set change API call made. Test is called by default //$content = $connection->get('account/verify_credentials'); function getWine() { // Connect to the database require_once('db.php'); $pdo = new PDO("mysql:host=localhost;dbname=winestore", DB_USER, DB_PW); // All errors with throw exceptions $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Get data from form $_SESSION['wineName'] = $_GET['wineName']; $wineryName = $_GET['wineryName']; $region = $_GET['region']; $variety = $_GET['variety']; $minRange = $_GET['lowerBound']; $maxRange = $_GET['upperBound']; $minWinesInStock = $_GET['minInStock']; $minWinesOrdered = $_GET['minOrdered']; $minCostRange = $_GET['minCost']; $maxCostRange = $_GET['maxCost']; $query = "SELECT wine_name, variety, year, winery_name, region_name, cost, on_hand, qty, price FROM wine JOIN winery w ON wine.winery_id = w.winery_id JOIN region r ON w.region_id = r.region_id JOIN wine_variety wv ON wine.wine_id = wv.wine_id JOIN grape_variety gv ON wv.variety_id = gv.variety_id JOIN items ON wine.wine_id = items.wine_id JOIN inventory ON wine.wine_id = inventory.wine_id WHERE wine_name LIKE '%" . $_SESSION['wineName'] . "%' "; if(!empty($wineryName)) { $query .= " AND winery_name LIKE '%$wineryName%'"; } if(!empty($region)) { $query .= " AND region_name LIKE '%$region%'"; } if(!empty($variety)) { $query .= " AND variety LIKE '%$variety%'"; } if((!empty($minRange)) && (!empty($maxRange))) { if($minRange > $maxRange) { echo "Min Year Range cannot be higher than Max Year Range!"; } else { $query .= " AND year BETWEEN '{$minRange}' AND '{$maxRange}'"; } } if(!empty($minWinesInStock)) { $query .= " AND on_hand >= '{$minWinesInStock}'"; } if(!empty($minWinesOrdered)) { $query .= " AND qty >= '{$minWinesOrdered}'"; } if((!empty($minCostRange)) && (!empty($maxCostRange))) { if($minCostRange > $maxCostRange) { echo "Min Cost Range cannot be higher than Max Cost Range!"; } else { $query .= " AND price between '{$minCostRange}' AND '{$maxCostRange}'"; } } //if((empty($wineName)) && (empty($wineryName)) && (empty($region)) && (empty($variety)) // && (empty($minRange)) && (empty($maxRange)) && (empty($minWinesInStock)) && // (empty($minWinesOrdered)) && (empty($minCostRange)) && (empty($maxCostRange))) { // echo "<p>You did not enter anything!</p>"; // } // execute the query return $pdo->query($query); } function generatePage() { $t = new MiniTemplator; $t->readTemplateFromFile("winestore_template.htm"); $results = getWine(); while($row = $results->fetch(PDO::FETCH_ASSOC)) { $t->setVariable('wineName', $row['wine_name']); $t->setVariable('variety', $row['variety']); $t->setVariable('year', $row['year']); $t->setVariable('wineryName', $row['winery_name']); $t->setVariable('region', $row['region_name']); $t->setVariable('cost', $row['cost']); $t->setVariable('stock', $row['on_hand']); $t->setVariable('sold', $row['qty']); $t->setVariable('sales', $row['cost']*$row['qty']); $t->addBlock("wine"); //echo $row['wine_name']; //echo $_SESSION['wines]; $_SESSION['wines'] = $row['wine_name']; } $t->generateOutput(); // If no matches found, display message $row_count = $results->rowCount(); if($row_count == 0) { echo "<p>No matches found</p>"; } } generatePage(); echo "<p><a href='search.php'>< go back to search page</a></p>"; // Close the connection $pdo = null; ?> <p><a href="?end">End Session</a></p> <form action="session.php" method="get"> <input type="submit" name="submit" value="View List of Wines" /> <input type="hidden" name="wineName" value="<?php echo $_SESSION['wines']; ?>"> </form> <?php if(isset($_GET['end'])) { session_destroy(); } ?>
Java
UTF-8
473
1.648438
2
[]
no_license
package controller.util; public interface ProfissionalParamsUtils { public static String PROFISSAO = "Profissao"; public static String SERVICOS = "Servicos"; public static String PSICOLOGO = "Psicologo"; public static String PSIQUIATRA = "Psiquiatra"; public static String DENTISTA = "Dentista"; public static String NUTRICIONISTA = "Nutricionista"; public static String FISIOTERAPEUTA = "Fisioterapeuta"; public static String ANOINICIOCARREIRA = "Ano Inicio"; }
Go
UTF-8
6,048
2.546875
3
[]
no_license
package api import ( "my_mange_system-gin/common" "my_mange_system-gin/model" "my_mange_system-gin/server" "net/http" "strconv" "strings" "time" "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" ) type UserLoginParams struct { Username string `form:"username"` Password string `form:"password"` City string `form:"city"` } type UserListParams struct { Username string `form:"username"` Roleid int `form:"roleid"` Offset int `form:"offset"` Limit int `form:"limit"` } type UserHandleParams struct { Username string `form:"username"` Password string `form:"password"` UserId string `form:"userid"` Roleid string `form:"roleid"` City string `form:"city"` Offset int `form:"offset"` Limit int `form:"limit"` } type ChangePassword struct { Username string `form:"username"` OldPassword string `form:"oldpassword"` NewPassword string `form:"newpassword"` UserId int `form:"userid"` } func UserLogin(ctx *gin.Context) { var params UserHandleParams var res common.Result if ctx.ShouldBind(&params) == nil { result, user := server.CheckOutUser(ctx, params.Username, params.Password) if result == true { server.UpdateLoginInfo(params.City, params.Username) res = common.Result{Httpcode: http.StatusOK, Msg: "登录成功", Data: gin.H{"username": user.Username, "userid": user.ID, "roleid": user.RoleId}} } else { res = common.Result{Httpcode: http.StatusNoContent, Err: "账号密码错误"} } } else { res = common.Result{Httpcode: http.StatusBadRequest, Err: "用户数据解析失败"} } ctx.Set("Res", res) ctx.Next() } func UserLogout(ctx *gin.Context) { s := sessions.Default(ctx) s.Clear() s.Save() res := common.Result{Httpcode: http.StatusOK, Msg: "退出登录成功"} ctx.Set("Res", res) ctx.Next() } func UserInfo(ctx *gin.Context) { user := common.GetSession(ctx, "user") if user == nil { res := common.Result{Httpcode: http.StatusInternalServerError, Err: "无法获取用户信息"} ctx.Set("Res", res) ctx.Next() return } userinfo := user.(model.User) data := gin.H{ "username": userinfo.Username, "roleid": userinfo.RoleId, "city": userinfo.City, "lastlogintime": time.Unix(userinfo.LastLoginTime, 0).Format("2006-01-02 15:04:05"), } res := common.Result{Httpcode: http.StatusOK, Msg: "获取信息成功", Data: data} ctx.Set("Res", res) ctx.Next() } func UserChangePassword(ctx *gin.Context) { var params ChangePassword var res common.Result user := common.GetSession(ctx, "user") if user == nil { res := common.Result{Httpcode: http.StatusInternalServerError, Err: "无法获取用户信息"} ctx.Set("Res", res) ctx.Next() return } userinfo := user.(model.User) if ctx.ShouldBind(&params) == nil { if uint(params.UserId) != userinfo.ID { res = common.Result{Httpcode: http.StatusBadRequest, Err: "只能修改自己用户信息"} } else { result, msg := server.ChangeUserPassword(uint(params.UserId), params.OldPassword, params.NewPassword) if result == true { res = common.Result{Httpcode: http.StatusOK, Msg: msg} } else { res = common.Result{Httpcode: http.StatusBadRequest, Err: msg} } } } else { res = common.Result{Httpcode: http.StatusBadRequest, Err: "用户数据解析失败"} } ctx.Set("Res", res) ctx.Next() } func UserList(ctx *gin.Context) { var params = UserHandleParams{ Username: "", Roleid: "0", Offset: 1, Limit: 10, } var res common.Result ctx.ShouldBindQuery(&params) roleid, err := strconv.Atoi(params.Roleid) if err != nil { res = common.Result{Httpcode: http.StatusBadRequest, Err: "用户数据解析失败"} } else { users, total := server.GetUsetList(params.Username, roleid, (params.Offset-1)*params.Limit, params.Limit) res = common.Result{Httpcode: http.StatusOK, Msg: "获取信息成功", Data: gin.H{"users": users, "total": total}} } ctx.Set("Res", res) ctx.Next() } func UserDelete(ctx *gin.Context) { var params UserHandleParams var res common.Result user := common.GetSession(ctx, "user") if user == nil { res := common.Result{Httpcode: http.StatusInternalServerError, Err: "无法获取用户信息"} ctx.Set("Res", res) ctx.Next() return } userinfo := user.(model.User) if userinfo.RoleId != 1 { res := common.Result{Httpcode: http.StatusUnauthorized, Err: "非管理员无法删除"} ctx.Set("Res", res) ctx.Next() return } if ctx.ShouldBind(&params) == nil { userids := strings.Split(params.UserId, ",") roleids := strings.Split(params.Roleid, ",") result, msg := server.DeleteUserList(userids, roleids, userinfo) if result == false { res = common.Result{Httpcode: http.StatusNoContent, Err: msg} } else { res = common.Result{Httpcode: http.StatusOK, Msg: msg} } } else { res = common.Result{Httpcode: http.StatusBadRequest, Err: "用户数据解析失败"} } ctx.Set("Res", res) ctx.Next() } func SystemInfo(ctx *gin.Context) { meminfo := server.ReadSystemInfo("/proc/meminfo") data := gin.H{ "MemTotal": meminfo["MemTotal"], "MemFree": meminfo["MemFree"], "Buffers": meminfo["Buffers"], "Cached": meminfo["Cached"], "MemAvailable": meminfo["MemAvailable"], } res := common.Result{Httpcode: http.StatusOK, Msg: "获取信息成功", Data: data} ctx.Set("Res", res) ctx.Next() } func Registered(ctx *gin.Context) { var params UserHandleParams var res common.Result var total int64 DB := model.DB.Model(&model.User{}) if ctx.ShouldBind(&params) == nil { user := model.User{ Username: params.Username, Password: params.Password, } DB.Where("username = ?", params.Username).Count(&total) if total > 0 { res = common.Result{Httpcode: http.StatusBadRequest, Err: "用户名已存在"} } else { DB.Create(&user) res = common.Result{Httpcode: http.StatusOK, Msg: "注册成功"} } } else { res = common.Result{Httpcode: http.StatusBadRequest, Err: "用户数据解析失败"} } ctx.Set("Res", res) ctx.Next() }
C
UTF-8
837
2.65625
3
[ "MIT" ]
permissive
/* * Display the fingerprints of the PGP Master Keys to the user. * * (This is in its own file rather than in uxcons.c, because it's * appropriate even for Unix GUI apps.) */ #include "putty.h" void pgp_fingerprints(void) { fputs("These are the fingerprints of the PuTTY PGP Master Keys. They can\n" "be used to establish a trust path from this executable to another\n" "one. See the manual for more information.\n" "(Note: these fingerprints have nothing to do with SSH!)\n" "\n" "PuTTY Master Key as of " PGP_MASTER_KEY_YEAR " (" PGP_MASTER_KEY_DETAILS "):\n" " " PGP_MASTER_KEY_FP "\n\n" "Previous Master Key (" PGP_PREV_MASTER_KEY_YEAR ", " PGP_PREV_MASTER_KEY_DETAILS "):\n" " " PGP_PREV_MASTER_KEY_FP "\n", stdout); }
Markdown
UTF-8
23,832
3.75
4
[]
no_license
ECMAScript 中所有值都属于以下6种数据类型之一 基本数据类型(5) - Undefined - Null - Boolean - Number - String 复杂数据类型(1) - Object(无序键值对) # 基本类型 ## Undefined - Undefined 类型只有一个值,```undifined```,可以用来比较 - 使用```var```声明,但是没有初始化的变量,值为 ```undefined``` - 不要将变量显式设置为```undefined``` ```javascript var item; alert(item === undefined); // true ``` ## Null - Null 类型只有一个值,```null```,表示空对象指针 - 可以将变量显式设置为 ```null```,以表示是用于保存对象的变量 ```javascript var item = null; alert(item === null); // true ``` ## Boolean - 简介 - Boolean 类型有两个值 : ```true```、```false```(区分大小写) - 类型转换 - 所有类型都可以转换成 Boolean 类型 - 转型函数```Boolean()``` - 自动类型转换(条件语句等) - 转换规则 | 数据类型 | 转换为```true```的值 | 转换为```false```的值 | | :-------: | :------------------: | :-------------------: | | Boolean | ```true``` | ```false``` | | String | 非空字符串 | "" | | Number | 非0 | 0、```NaN``` | | Object | 任何对象 | ```null``` | | Undefined | | ```undefined``` | ## Number ```javascript var number = 1; var number1 = 1.1; var number2 = 1.1e7; // 11000000 var number3 = 1/0; // NaN ``` - ###### ```NaN``` - ```NaN```(Not a Number),非数值,表示应该返回数值却未返回数值的情况(任何数除以0) - 任何涉及 ```NaN``` 的操作都会返回 ```NaN``` - ```NaN``` 与任何值都不相等,包括自身 - ###### ```isNaN()``` - 接受任何类型变量,返回布尔值,用于确定是否"不可转换为数值" - 原理 - 参数为基本类型 - 尝试将参数转换为数值 - 可以转换,返回```false``` - 不可转换,返回```true``` - 参数为引用类型 - 调用对象的``` valueOf()```方法,尝试将返回值转换为数值 - 可以转换,返回``` false``` - 不可转换,基于``` valueOf()```返回值调用``` toString()```方法,尝试将返回值转换为数值 - 可以转换,返回``` false``` - 不可转换,返回``` true``` - ```javascript alert(isNaN(NaN)); // true alert(isNaN(10)); // false alert(isNaN("10")); // false alert(isNaN("blue")) // true alert(isNaN(true)) // false ``` - ###### 数值转换(p30) - ```Number()``` - 参数 : 任意类型 - 返回 : 数值/```NaN``` - 规则 : - ```undefined``` : ```NaN``` - ```null``` : 0 - Boolean : - ```true``` : 1 - ```false``` : 0 - String - "" : 0 - 只包含数字 : 按十进制转换(忽略前面的0) - 包含有效的浮点格式 : 转换为浮点数(忽略前面的0) - 包含有效的十六进制格式 : 按十六进制转换 - 包含除去以上的其他字符 : ```NaN``` - Object - ```valueOf()```后进行转换,如果返回 ```NaN```,再次调用``` toString()``` - ```parseInt()``` - 参数 : 字符串,进制(为了避免错误解析,无论何时都要指定进制类型) - 返回 : 数字/``` NaN``` - 原理 - 忽略字符串前面的空格 - 判断第一个非空字符是不是数字或负号 - 不是,返回```NaN``` - 是,继续向后解析,直到字符串结束/遇到非数字字符(非数字字符会被忽略) - ```javascript var num1 = parseInt("10",2); // 2(二进制解析) var num2 = parseInt("10",8); // 8(八进制解析) var num3 = parseInt("10",10); // 10(十进制解析) var num4 = parseInt("10",16); // 16(十六进制解析) ``` - 注:`parseInt(number, 10)`有取整的功能 - ```parseFloat()```(p32) ## String - ("")/('') - 字符串不可变,想改变必须创建新字符串 - 获取字符串长度 : ```length()``` - 拼接字符串 : ```+``` - 类型转换 - ```toString()``` - 参数(可选) : 进制类型(无参数时,默认使用十进制) - 返回 : 字符串 - Boolean、Number、String、Object 都有该方法(**String 调用 ```toString()```返回字符串副本**) - Undefined、Null 没有该方法 - ```javascript var num = 10; alert(num.toString()); // "10" alert(num.toString(2)); // "1010" alert(num.toString(8)); // "12" alert(num.toString(10)); // "10" alert(num.toString(16)); // "a" var boo = true; var booAsString = boo.toString(); // "true" ``` - ```String()``` - 参数 : 任何类型 - 返回 : 字符串 - 原理 - 调用```toString()``` - 没有``` toString()``` - 参数是```undefined```,返回"undefined" - 参数是``` null```,返回"null" # 引用类型 引用类型是什么? > 无序键值对的集合,保存在堆中 对象是什么? > 引用类型的实例 如何创建对象? > new + 构造函数 > > ```javascript > var person = new Person(); > ``` 如何访问对象的属性? > - 点 > - 方括号 + 属性字符串(可以使用变量访问属性) > > ```javascript > // 用点访问属性 > var person = new Person("tom"); > alert(person.name); > > // 用方括号 + 属性字符串访问属性 > alert(person["name"]); > ``` ## Object 所有对象都是 Object 类型的实例,所有引用类型的父类 Object 类型有哪些属性? > - ```constructor``` : 指向构造函数 > - ```hasOwnProperty()``` > - 检查属性是否实例属性 > - 参数 : 字符串 > - ```propertyIsEnumerable()``` > - 检查属性是否可```for-in```枚举 > - 参数 : 字符串 > - ```isPrototypeOf()``` > - 检查传入对象是否是当前对象原型 > - 参数 : 对象 > - ```toString()``` : 转换为 String > - ```toLocalString()``` : 转换为本地 String > - ```valueOf()``` : 转换为 Boolean / Number / String,一般与``` toString()```返回值相同 如何创建 Object 类型的实例? > ```javascript > // new 操作符 + 构造函数 > var person = new Object(); > > // 字面量(不调用构造函数) > var person1 = { > name:"sdf", > age:11 > }; > ``` ## Array ### 特性 > - 数组每一项可以保存任意类型的数据 > - 数组长度不固定,随数据的添加自动增长 ### 创建实例 > ```javascript > var items = new Array(); > var names = ["tom","jerry"]; > ``` ### ```length``` > - 数组的属性,表示数组长度,值为0或更大数值 > > - 数组长度变化时会自动同步 > > - 可读可写,修改```length```属性可以延长数组长度或缩短数组长度 > > - 延长,会新增数组成员,新增的每一项自动赋值```undefined``` > - 缩短,会移除原本的最后若干项,移除后的成员还能通过数组访问,但是自动赋值```undefined``` > > - 可以用来在数组末尾添加新成员 > > - ```javascript > // 因为数组中,最后一项的索引始终是 length-1,所以新增项的索引始终是 length > var names = ["tom","jerry"]; > names[length] = "david"; > ``` > > - 数组长度有上限:4294967295 ### 检测类型 > - 实例与要检测的 Array 构造函数在同一个全局作用域中:```instanceof```操作符 > - 不在用一个全局作用域(实例从另外的框架传过来):```Array.isArray()```(IE9+) > - ```Object.prototype.toString.call(value)```:返回构造函数名 ### 转换为字符串 > - ```toString()```,```toLocalString()```,```valueOf()```:调用数组中每个成员的同名方法,将结果拼接成字符串返回,分隔符是"," > - ```join()```:自定义分隔符 > - 参数:分隔符 > - 返回:原理同```toString()```,用传入的分隔符进行拼接,返回拼接后字符串 ### 数组排序 > - ```reverse()``` > - 不接受参数,返回倒序数组 > - ```sort()``` > - 参数:比较函数(可选) > - 该函数有两个参数 > - 如果第一个参数排在第二个参数之前,比较函数要返回负值 > - 如果两个参数相等,比较函数要返回```0``` > - 如果第一个参数排在第二个参数之后,比较函数要返回正值 > - 返回:排序后数组 > - 不接受参数时,将每个成员转化为 String 进行比较,返回升序结果(每个成员调用```toString()```转化成字符串,然后比较对应位置的字符编码) > - 接受参数时,使用传入的比较函数进行排序,返回排序结果 ### 复制数组 基于所有项复制 > ```concat()``` > - 参数:任意数量、任何类型,数据、数组 > - 功能:基于数组所有项创建新数组,将传入参数添加到新数组末尾 > - 返回:新数组 基于部分项复制 > ```slice()``` > - 参数:一个或两个 > - 一个参数:开始索引 > - 两个参数:开始索引、结束索引 > - 功能 > - 传入一个参数时,选取从开始索引到数组末尾的成员创建新数组 > - 传入两个参数时,选取开始索引到结束索引(但不包含结束索引)的成员,创建新数组 > - 返回:新数组 > - 注意 > - 如果传入索引有负数,自动与数组```length```相加 > - 如果开始索引 < 结束索引,返回空数组 ### 操作数组 栈方法(操作数组末尾) > - ```push()``` > - 接受任意数量参数,添加到数组末尾,数组```length```值增加,返回数组 ```length```值 > - ```pop()``` > - 移除数组最后一项并返回,数组```length```减1 队列方法(操作数组开头) > - ```shift()``` > - 移除数组第一项并返回,数组```length```减1 > - ```unshift()``` > - 接受任意个参数,添加到数组最前端,数组```length```增加,返回数组```length``` 操作数组中间 > - ```splice()``` > - 参数:开始索引(必须),删除项的数量(必须),插入的项(可选) > - 功能 > - 删除成员:删除任意数量的数组成员,需要传入开始索引和要删除的成员数量 > - 添加成员:添加任意数量的数组成员,需要传入开始索引、0(删除数量)、插入的成员 > - 替换成员:删除任意数量的数组成员,并添加任意数量的数组成员,需要传入开始索引、删除数量、插入的成员 ### 位置查询 > ```indexOf()```、```lastIndexOf()``` > > - 参数:查询项,查询开始索引(可选) > - 功能 > - 使用全等(===)对查询项与数组每一项进行比较 > - ```indexOf()```从前向后找 > - ```lastIndexOf()```从后向前找 > - 返回 > - 找到相同项,返回索引 > - 没找到相同项,返回```-1``` ### 遍历方法 ```every()``` > - 参数:函数(接收三个参数,数组成员、数组成员的索引、数组)、函数作用域对象(可选) > - 功能:数组每一项都调用传入函数 > - 返回 > - 如果函数对每一项都返回```true```,这个方法返回```true``` > - 否则返回 false ```some()``` > - 参数:函数(接收三个参数,数组成员、数组成员的索引、数组)、函数作用域对象(可选) > - 功能:数组每一项都调用传入函数 > - 返回 > - 如果函数对任意一项返回```true```,这个方法返回```true``` > - 否则返回 ```false``` ```filter()``` > - 参数:函数(接收三个参数,数组成员、数组成员的索引、数组)、函数作用域对象(可选) > - 功能:数组每一项都调用传入函数 > - 返回 > - 函数返回值为 ```true```的成员构成的数组 ```forEach()``` > - 参数:函数(接收三个参数,数组成员、数组成员的索引、数组)、函数作用域对象(可选) > - 功能:数组每一项都调用传入函数 > - 返回:无 ```map()``` > - 参数:函数(接收三个参数,数组成员、数组成员的索引、数组)、函数作用域对象(可选) > - 功能:数组每一项都调用传入函数 > - 返回:所有成员调用函数的结果组成的数组 用法 > - 查看数组成员是否满足某些条件:```every()```、```some``` > - 筛选出满足某些条件的数组成员:```filter()``` > - 单纯遍历数组:```forEach()``` > - 遍历数组并返回结果数组:```map()``` > > - 限制:IE9+ ### 归并方法 迭代数组所有项,构建一个最终返回值 ```javascript var arr = [1,2,3,4]; var sum = arr.reduce(function(prev,cur,index,array){ return prev + cur; }) sun // 10 ``` > - 数组中每一项执行某些操作,结果自动传给下一项,返回最 终结果 > - ```reduce()```:从前向后迭代 > - ```reduceRight()```:从后向前迭代 > - 限制:IE9+ ## Date ### 原理 > 使用自 UTC(1970年1月1日0时)的毫秒数保存日期 ### 创建对象 > ```javascript > // 获得当前日期和时间 > var now = new Date(); > // 使用参数创建日期(返回1970年1月1日到指定日期的毫秒数) > var time1 = Date.UTC(2018,0,1,0,0,0); // 年、月(0-11)、日(1-31)、时(0-23)、分、秒 > // 使用参数创建日期 > var time = new Date(year,month,day,hour,minute,second)// 年、月(0-11)、日(1-31)、时(0-23)、分、秒 > > // 获取调用时间(IE9+) > var start = Date.now(); > var stop = Date.now() || +new Date(); // 兼容 > ``` ### 获取时间 > ```javascript > const date = new Date() > const year = date.getFullYear() // 年份,四位数字 > const month = date.getMonth() // 月份,0-11 > const day = date.getDate() // 日期,1-31 > const hour = date.getHours() // 小时,2-23 > const minute = date.getMinutes() // 分钟,0-59 > const second = date.getSeconds() // 秒数,0-59 > const time = date.getTIme() // 从1970年1月1日至今的毫秒数 > ``` ### 设置时间 > ```javascript > const date = new Date() > date.setFullYear() // 设置年份,四位数字 > date.setMonth() // 设置月份,0-11 > date.setDate() // 设置日期,1-31 > date.setHours() // 设置小时,0-23 > date.setMinutes() // 设置分钟,0-59 > date.setSeconds() // 设置秒数,0-59 > date.setTime() // 用1970年1月1日至今的毫秒数 > ``` ### 转化为字符串 > - Date 类型的格式化方法在各浏览器中表现不一致,无法使用 > - 通过```getXXX```获取时间各部分,自己组成字符串 ## RegExp 正则表达式对象 ## Function 函数是 Function 类型的实例,本质上是一个对象:有属性和方法、可以作为参数传递,可以作为返回值返回 函数名本质上是一个引用(指针),指向函数对象,与变量没有区别,所以一个函数可能有多个函数名(多个引用) 函数声明与函数表达式的区别? > 使用函数声明创建的函数在任何地方都可以直接调用,而通过函数表达式创建的函数只有在这行代码之后才可以使用 > 在执行代码之前,解析器会进行函数声明提升(将函数声明提升到代码树顶部),所以可以在代码任意处使用函数 > > 函数表达式本质上是一个变量声明,也进行了变量声明提升,但是在执行到赋值代码之前,访问这个变量的值是 undefined > 是否可以同时使用函数声明和表达式?例如:```var doSome = function do(){};``` > 不可以,在 Safari 中会报错 函数实例属性 > - ```arguments```:类数组对象,传入函数的参数保存其中 > - ```arguments```对象有一个```callee```属性,指向拥有```arguments```对象的函数 > - ```this```:指向函数的拥有者(调用者) > - 在全局作用域中定义的函数,```this```指向全局作用域,(浏览器中是```window```)(在浏览器中,全局作用域是 ```window```对象,所以全局变量都是```window```对象的属性) > - 匿名函数 this 指向全局环境(浏览器中是 window) > - 函数只能访问当前作用域中的 this 和 arguments,如果想要访问外部作用域中的 this 和 arguments,需要将 this 和 arguments 的引用保存到闭包能访问到的变量中 > - ```length```:命名参数的个数 > - ```prototype```:指向原型对象,不可枚举(```for-in```无法发现) > - ```caller```:指向该函数的调用函数 > - 在全局作用域中调用函数,```caller```值为 ```null``` 函数实例方法 > - ```call()``` > - 参数:函数执行环境、函数各个参数 > - ```apply()``` > - 参数:函数执行环境、函数的参数数组 > - ```bind()```(IE9+) > - 参数:函数执行环境 > > 这三个函数可以修改某个函数的执行环境(也就是作用域、函数拥有者、函数```this```属性的指向),重新定义了函数可以访问的数据 > > **这三个函数的作用** > > - 将对象与方法解耦 > - 实现继承 函数继承来的方法(从 Object) > - ```toString()``` > - ```toLocalString()``` > - ```valueOf()``` > > 这三个函数都返回函数代码 ### 参数 参数保存在哪? > 保存在函数的属性,arguments,一个类数组对象中 函数传参原理? > 值传递 > > - 基本类型,传递时进行复制 > - 引用类型,传递时进行指针传递。所以在函数内部的修改,会影响到函数外部 函数不限制传入参数个数、数据类型,为什么? > 传入参数保存在函数的``` arguments``` 属性中,是一个类似数组的对象,长度由传入参数个数决定 ```arguments```如何使用? > ```javascript > function sayHi(name,message){ > alert(arguments[0]); // 访问传入参数 > alert(arguments.length); // 获取传入参数个数 > } > ``` ```arguments```与命名参数的关系? > 参数保存在 arguments 中,命名参数按顺序去 arguments 中取值 为什么调用函数的时候,既可以直接传入参数数组,也可以一个一个传参数?(参考 call() 和 apply()) > 因为参数本质上是保存在函数的 arguments 属性中 > > - 传入参数数组时,数组被拆分,所有成员都被保存到 arguments 对象中 > - 传入单个参数时,每个参数都被保存在 arguments 对象中 没有传入的命名参数,值是什么? > ```undefined``` 如果参数数量过多,怎么优化? > 必须参数使用命名参数,可选参数用 Object 对象封装 ### 返回值 ```javascript function sayHi(name,message){ return name+message; // 有返回值 } function sayHello(name,message){ return; // 返回 undefined } function sayNothing(name,message){ alert("nothing"); // 没有返回值 } ``` ### 重载 Javascript 中,存在函数重载么? > 不存在 > > 因为函数本质上是一个对象,函数名是该对象的引用(指针)。如果声明两个名字相同的函数,相当于对一个引用进行两次赋值,那么引用会保留第二次的赋值结果 有什么办法模拟重载? > 因为函数传入参数个数没有限制,所以可以传入不同数量的参数来模拟重载 ## Global 全局对象(全局作用域),是一个概念,并不存在,所有全局变量都是 Global 对象的属性(在浏览器中,Global 对象由 window 对象实现,所以全局变量都是 window 对象的属性) ##### 方法 > - ```isNaN()``` > - ```parseInt()``` > - ```parseFloat()``` > - ```encodeURI```、```decodeURI```:用的少,对整个 URI 进行编码 > - ```encodeURIComponent```、```decodeURIComponent```:用的多,对部分 URI 进行编码(查询参数) > - ```eval()``` > - 参数:字符串 > - 功能:像一个解析器,将传入字符串解析成代码,然后执行,执行结果插入原位置 > - 特点 > - ```eval()```没有创建块级作用域,```eval()```中的代码属于当前作用域(跟当前作用域有相同的作用域链,当前作用域也可以访问```eval()```中声明的变量) > - ```eval()```中声明的变量和函数不会提升。因为在```eval()```执行前,它们是字符串,```eval()```执行后才被创建出来 ##### 属性 > - 特殊值 > - ```undefined``` > - ```NaN``` > - ```Infinity``` > - 构造函数 > - ```Object``` > - ```Array``` > - ```Date``` > - ```RegExp``` > - ```Function``` > - ```Boolean``` > - ```Number``` > - ```String``` > - ```Error``` > - ```EvalError``` > - ```RangeError``` > - ```ReferenceError``` > - ```SyntaxError``` > - ```TypeError``` > - ```URIError``` ## Math > - ```min()``` > - ```max()``` > - ```random()``` ## 基本包装类型 **不要显示创建基本包装类型实例(用 new操作符)!** 基本包装类型用于对基本类型进行操作时: > - 创建基本包装类型的实例 > - 调用方法 > - 销毁实例 基本包装类型与其他引用类型的区别? > 生命周期不同 > > 基本包装类型在执行完操作后立即销毁 ### Boolean > - ```toString()``` > - ```toLocalString()``` > - ```valueOf()``` ### Number > - ```toString()``` > - ```toLocalString()``` > - ```valueOf()``` > - ```toFixed()```:返回指定小数位数的字符串表示 > - ```toExponential()```:返回指数表示法的字符串表示 > - ```toPrecision()```:返回最合适的表示方法字符串,```toFixed()```的值或```toExponential()```的值 ### String > - ```toString()```:复制字符串 > - ```toLocalString()``` > - ```valueOf()``` 访问字符 > - ```charAt()``` > - ```charCodeAt()``` > - 像数组一样使用方括号 字符串拼接 > - ```concat()```、"+" 获取子字符串 > - ```slice(startIndex,lastIndex)``` > - ```subString(startIndex,lastIndex)``` > - ```subStr(startIndex,length)``` 删除前后空格 > - ```trim()```(IE9+) 正则匹配 > - ```match()``` > - ```search()``` 字符串替换 > - ```replace()``` 字符串拆分 > - ```split(分隔符,数组最大长度)``` 比较字符串 > - ```localCompare()``` 字符编码转换成字符串 > - ```fromCharCode()``` 查询字符串 > - ```indexOf()```(从前向后找)、```lastIndexOf()```(从后向前找) > - 参数:要查询的字符串、查询开始位置索引(可选) > - 返回 > - 找到字符串,返回字符串开始索引 > - 没有找到,返回```-1``` 大小写转换 > - ```toLowerCase()``` > - ```toUpperCase()``` > - ```toLocalLowerCase()``` > - ```toLocalUpperCase()``` # 类型检测 如何检测基本类型? > ```typeof```操作符 > > - 参数:任意类型 > - 返回:字符串 > > | 用于检查的类型 | 返回值 | > | :----------------------------------------------------------: | :---------: | > | Undefined | "undefined" | > | Null(空对象指针)、Object | "object" | > | Boolean | "boolean" | > | Number | "number" | > | String | "string" | > | 函数(本质上是对象,但是 ```typeof``` 操作符给了一个特殊值) | "function" | 如何检测引用类型? > - constructor 属性 > - ```Object.prototype.toString.call(value)``` > - 无法检测自定义构造函数,所有自定义构造函数都返回【object Object】 > - ```instanceof```操作符
Markdown
UTF-8
1,363
2.78125
3
[ "MIT" ]
permissive
--- title: Zelda + a11y? author: lon layout: post categories: - posts - meetups when: 2018-07-17T19:30:00-05:00 --- {% assign speakr = 'Dave Rupert' %} {% assign twiturl = 'https://twitter.com/davatron5000' %} {% assign huburl = 'https://github.com/davatron5000/' %} Accessibility is hard. Oftentimes, it’s difficult to understand what users and assistive technology expect from your markup and designs. Can accessibility be easier to learn? Can it be&hellip;fun? In this talk, <a href="{{ twiturl }}">{{ speakr }}</a> will approach accessibility the way we might tackle a video game—looking at a handful of common UI patterns like popup, tabs, accordions, and modals; how to test them; and how to defeat them while leveling up your skillset along the way. ### Our speaker <div class="media-object speaker-bio"> <a href="{{ twiturl }}"> <img alt="{{ speakr }} @davatron5000 on Twitter" src="https://avatars1.githubusercontent.com/u/42218?s=460&v=4" /> </a> <div> <a href="{{ twiturl }}"><strong>{{ speakr }}</strong></a> Lead developer at Paravel. Purveyor of tiny jQueries. </div> </div> Make sure to thank our gracious hosts [Spredfast][]! {% include give-em-the-business.html location='spredfast' %} Check back here or <a href="{{ site.twitter.url }}">follow us on Twitter</a> for updates. [Spredfast]: https://www.spredfast.com/
Markdown
UTF-8
1,254
3.109375
3
[]
no_license
# CourseProj_GetCleanData CourseProject Coursera Getting_Cleaning Data This script is very simple. Simply locate the script "run_analysis.R" in the folder "UCI HAR Dataset" (that shlud contains folders "test" and "train" and other files. Open R. In the prompt type "dataset<-run_analysis() and after few time dataset contains a tidy dataset corresponding to point 5 in Course Project. In a nutshell. it contains the mean values for each column for each combination (subset) of subject and activity. The dataset variable is a dataframe containing columns: Col 1: Subjects Col 2: Activity Col 3 till 81: variables In the code, -Data1 (line 10) contains the dataset as required in point 1 of Course Project (#1.Merges the training and the test sets to create one data set. -Dataset_only_mean_std (Point #2.Extracts only the measurements on the mean and standard deviation for each measurement.) -DataWithActNames(Point#3.Uses descriptive activity names to name the activities in the data set) -DataSet_Correct_Names( Point #4.Appropriately labels the data set with descriptive variable names. ) -BigDataSet(#5.From the data set in step 4, creates a second,independent tidy data set with the average of each variable for each activity and each subject)
Ruby
UTF-8
1,475
3
3
[]
no_license
require_relative '../utils/printer' require_relative '../utils/input_reader' require_relative '../../universe/ship/amplifiers_chain' require_relative '../../universe/ship/amplifiers_loop' include Utils::Printer input_reader = Utils::InputReader.new(File.expand_path('input.txt')) program = input_reader.one_line.split_with(',').to_integer.read info "Calculating amplifiers phases with #{program.length} operators in controller" info "Trying out phase combinations for amplifiers chain" chain_phase_sequence = [0, 1, 2, 3, 4] amplifiers_chain = Universe::Ship::AmplifiersChain.new(program) chain_outputs = chain_phase_sequence.permutation.map do |phases| output = amplifiers_chain.output_for(phases) info "Amplifier output for phases #{phases} is: #{output}" [phases, output] end max_output = chain_outputs.max { |output1, output2| output1.last <=> output2.last } info "Maximal chain output #{max_output.last} is reached with phase #{max_output.first}" info "Trying out phase for amplifiers loops" loop_phase_sequence = [9, 8, 7, 6, 5] amplifiers_loop = Universe::Ship::AmplifiersLoop.new(program) loop_outputs = loop_phase_sequence.permutation.map do |phases| output = amplifiers_loop.output_for(phases) info "Amplifier output for phases #{phases} is: #{output}" [phases, output] end max_output = loop_outputs.max { |output1, output2| output1.last <=> output2.last } info "Maximal loop output #{max_output.last} is reached with phase #{max_output.first}"
Java
UTF-8
19,727
1.640625
2
[]
no_license
package com.imsweb.datagenerator.naaccr.rule.tumor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.imsweb.datagenerator.naaccr.NaaccrDataGeneratorOptions; import com.imsweb.datagenerator.naaccr.NaaccrDataGeneratorRule; import com.imsweb.datagenerator.random.RandomUtils; import com.imsweb.decisionengine.Endpoint.EndpointType; import com.imsweb.staging.Staging; import com.imsweb.staging.cs.CsDataProvider; import com.imsweb.staging.cs.CsDataProvider.CsVersion; import com.imsweb.staging.cs.CsSchemaLookup; import com.imsweb.staging.cs.CsStagingData; import com.imsweb.staging.cs.CsStagingData.CsInput; import com.imsweb.staging.cs.CsStagingData.CsOutput; import com.imsweb.staging.entities.StagingColumnDefinition; import com.imsweb.staging.entities.StagingEndpoint; import com.imsweb.staging.entities.StagingSchema; import com.imsweb.staging.entities.StagingSchemaInput; import com.imsweb.staging.entities.StagingStringRange; import com.imsweb.staging.entities.StagingTable; import com.imsweb.staging.entities.StagingTableRow; public class CollaborativeStageRule extends NaaccrDataGeneratorRule { // unique identifier for this rule public static final String ID = "collaborative-stage"; // Map of NAACCR record field names to CS table lookup keys private static final Map<String, String> _CS_FIELDS; static { _CS_FIELDS = new LinkedHashMap<>(); _CS_FIELDS.put("csExtension", "extension"); _CS_FIELDS.put("csTumorSizeExtEval", "extension_eval"); _CS_FIELDS.put("csLymphNodes", "nodes"); _CS_FIELDS.put("csExtension", "extension"); _CS_FIELDS.put("csTumorSizeExtEval", "extension_eval"); _CS_FIELDS.put("csLymphNodes", "nodes"); _CS_FIELDS.put("regionalNodesPositive", "nodes_pos"); _CS_FIELDS.put("regionalNodesExamined", "nodes_exam"); _CS_FIELDS.put("csMetsAtDx", "mets"); _CS_FIELDS.put("csTumorSize", "size"); _CS_FIELDS.put("csLymphNodesEval", "nodes_eval"); _CS_FIELDS.put("csMetsEval", "mets_eval"); _CS_FIELDS.put("lymphVascularInvasion", "lvi"); _CS_FIELDS.put("csSiteSpecificFactor1", "ssf1"); _CS_FIELDS.put("csSiteSpecificFactor2", "ssf2"); _CS_FIELDS.put("csSiteSpecificFactor3", "ssf3"); _CS_FIELDS.put("csSiteSpecificFactor4", "ssf4"); _CS_FIELDS.put("csSiteSpecificFactor5", "ssf5"); _CS_FIELDS.put("csSiteSpecificFactor6", "ssf6"); _CS_FIELDS.put("csSiteSpecificFactor7", "ssf7"); _CS_FIELDS.put("csSiteSpecificFactor8", "ssf8"); _CS_FIELDS.put("csSiteSpecificFactor9", "ssf9"); _CS_FIELDS.put("csSiteSpecificFactor10", "ssf10"); _CS_FIELDS.put("csSiteSpecificFactor11", "ssf11"); _CS_FIELDS.put("csSiteSpecificFactor12", "ssf12"); _CS_FIELDS.put("csSiteSpecificFactor13", "ssf13"); _CS_FIELDS.put("csSiteSpecificFactor14", "ssf14"); _CS_FIELDS.put("csSiteSpecificFactor15", "ssf15"); _CS_FIELDS.put("csSiteSpecificFactor16", "ssf16"); _CS_FIELDS.put("csSiteSpecificFactor17", "ssf17"); _CS_FIELDS.put("csSiteSpecificFactor18", "ssf18"); _CS_FIELDS.put("csSiteSpecificFactor19", "ssf19"); _CS_FIELDS.put("csSiteSpecificFactor20", "ssf20"); _CS_FIELDS.put("csSiteSpecificFactor21", "ssf21"); _CS_FIELDS.put("csSiteSpecificFactor22", "ssf22"); _CS_FIELDS.put("csSiteSpecificFactor23", "ssf23"); _CS_FIELDS.put("csSiteSpecificFactor24", "ssf24"); } // staging object private final Staging _staging = Staging.getInstance(CsDataProvider.getInstance(CsVersion.v020550)); /** * Constructor. */ public CollaborativeStageRule() { super(ID, "Collaborative Stage fields"); } @Override public List<String> getRequiredProperties() { return Arrays.asList("primarySite", "histologyIcdO3", "behaviorIcdO3", "grade", "dateOfDiagnosisYear", "ageAtDx", "vitalStatus", "typeOfReportingSource"); } @Override public void execute(Map<String, String> record, List<Map<String, String>> otherRecords, NaaccrDataGeneratorOptions options) { // Collaborative Stage was used only in 2004-2015 if (!inDxYearRange(record, 2004, 2015)) return; List<StagingSchema> lookup = _staging.lookupSchema(new CsSchemaLookup(record.get("primarySite"), record.get("histologyIcdO3"))); // get first schema - if multiple schemas returned, this will only be used to get a discriminator, and lookup will be repeated StagingSchema schema = _staging.getSchema(lookup.get(0).getId()); Map<String, StagingSchemaInput> inputMap = schema.getInputMap(); String schemaId = schema.getId(); // assign discriminator to ssf25 record.put("csSiteSpecificFactor25", getRandomValueFromTable(inputMap.get("ssf25").getTable(), "ssf25", record, schemaId)); if (lookup.size() == 0) return; // if multiple schemas were returned, use discriminator to make another lookup if (lookup.size() > 1) { lookup = _staging.lookupSchema(new CsSchemaLookup(record.get("primarySite"), record.get("histologyIcdO3"), record.get("csSiteSpecificFactor25"))); if (lookup.size() == 0) return; schema = _staging.getSchema(lookup.get(0).getId()); inputMap = schema.getInputMap(); schemaId = schema.getId(); } // loop over input fields, putting values into the record for (Entry<String, String> entry : _CS_FIELDS.entrySet()) { List<String> validValues = getAllValidValues(entry.getValue(), record, schemaId); if (validValues == null) // there are no restrictions on the valid values for this key - look up random value from tables record.put(entry.getKey(), getRandomValueFromTable(inputMap.get(entry.getValue()).getTable(), entry.getValue(), record, schemaId)); else // there are restrictions on this key; select a random value from the valid values list record.put(entry.getKey(), validValues.get(RandomUtils.nextInt(validValues.size()))); } record.put("csVersionInputCurrent", "020550"); record.put("csVersionOriginal", "020550"); CsStagingData data = new CsStagingData(); data.setInput(CsInput.PRIMARY_SITE, record.get("primarySite")); data.setInput(CsInput.HISTOLOGY, record.get("histologyIcdO3")); data.setInput(CsInput.BEHAVIOR, record.get("behaviorIcdO3")); data.setInput(CsInput.GRADE, record.get("grade")); data.setInput(CsInput.DX_YEAR, record.get("dateOfDiagnosisYear")); data.setInput(CsInput.CS_VERSION_ORIGINAL, record.get("csVersionOriginal")); data.setInput(CsInput.TUMOR_SIZE, record.get("csTumorSize")); data.setInput(CsInput.EXTENSION, record.get("csExtension")); data.setInput(CsInput.EXTENSION_EVAL, record.get("csTumorSizeExtEval")); data.setInput(CsInput.LYMPH_NODES, record.get("csLymphNodes")); data.setInput(CsInput.LYMPH_NODES_EVAL, record.get("csLymphNodesEval")); data.setInput(CsInput.REGIONAL_NODES_POSITIVE, record.get("regionalNodesPositive")); data.setInput(CsInput.REGIONAL_NODES_EXAMINED, record.get("regionalNodesExamined")); data.setInput(CsInput.METS_AT_DX, record.get("csMetsAtDx")); data.setInput(CsInput.METS_EVAL, record.get("csMetsEval")); data.setInput(CsInput.LVI, record.get("lymphVascularInvasion")); data.setInput(CsInput.AGE_AT_DX, record.get("ageAtDx")); data.setSsf(1, record.get("csSiteSpecificFactor1")); data.setSsf(2, record.get("csSiteSpecificFactor2")); data.setSsf(3, record.get("csSiteSpecificFactor3")); data.setSsf(4, record.get("csSiteSpecificFactor4")); data.setSsf(5, record.get("csSiteSpecificFactor5")); data.setSsf(6, record.get("csSiteSpecificFactor6")); data.setSsf(7, record.get("csSiteSpecificFactor7")); data.setSsf(8, record.get("csSiteSpecificFactor8")); data.setSsf(9, record.get("csSiteSpecificFactor9")); data.setSsf(10, record.get("csSiteSpecificFactor10")); data.setSsf(11, record.get("csSiteSpecificFactor11")); data.setSsf(12, record.get("csSiteSpecificFactor12")); data.setSsf(13, record.get("csSiteSpecificFactor13")); data.setSsf(14, record.get("csSiteSpecificFactor14")); data.setSsf(15, record.get("csSiteSpecificFactor15")); data.setSsf(16, record.get("csSiteSpecificFactor16")); data.setSsf(17, record.get("csSiteSpecificFactor17")); data.setSsf(18, record.get("csSiteSpecificFactor18")); data.setSsf(19, record.get("csSiteSpecificFactor19")); data.setSsf(20, record.get("csSiteSpecificFactor20")); data.setSsf(21, record.get("csSiteSpecificFactor21")); data.setSsf(22, record.get("csSiteSpecificFactor22")); data.setSsf(23, record.get("csSiteSpecificFactor23")); data.setSsf(24, record.get("csSiteSpecificFactor24")); data.setSsf(25, record.get("csSiteSpecificFactor25")); _staging.stage(data); // set flag to 1 (AJCC fields derived from CS) or blank if not derived (before 2004) record.put("derivedAjccFlag", "1"); record.put("derivedSs1977Flag", "1"); record.put("derivedSs2000Flag", "1"); // If Year of DX > 2003, the following CS Data Items cannot be blank record.put("csVersionDerived", data.getOutput(CsOutput.CSVER_DERIVED)); record.put("derivedAjcc6T", data.getOutput(CsOutput.STOR_AJCC6_T)); record.put("derivedAjcc6N", data.getOutput(CsOutput.STOR_AJCC6_N)); record.put("derivedAjcc6M", data.getOutput(CsOutput.STOR_AJCC6_M)); record.put("derivedAjcc6TDescriptor", data.getOutput(CsOutput.STOR_AJCC6_TDESCRIPTOR)); record.put("derivedAjcc6NDescriptor", data.getOutput(CsOutput.STOR_AJCC6_NDESCRIPTOR)); record.put("derivedAjcc6MDescriptor", data.getOutput(CsOutput.STOR_AJCC6_MDESCRIPTOR)); record.put("derivedAjcc6StageGroup", data.getOutput(CsOutput.STOR_AJCC6_STAGE)); record.put("derivedAjcc7T", data.getOutput(CsOutput.STOR_AJCC7_T)); record.put("derivedAjcc7N", data.getOutput(CsOutput.STOR_AJCC7_N)); record.put("derivedAjcc7M", data.getOutput(CsOutput.STOR_AJCC7_M)); record.put("derivedAjcc7TDescriptor", data.getOutput(CsOutput.STOR_AJCC7_TDESCRIPTOR)); record.put("derivedAjcc7NDescriptor", data.getOutput(CsOutput.STOR_AJCC7_NDESCRIPTOR)); record.put("derivedAjcc7MDescriptor", data.getOutput(CsOutput.STOR_AJCC7_MDESCRIPTOR)); record.put("derivedAjcc7StageGroup", data.getOutput(CsOutput.STOR_AJCC7_STAGE)); record.put("derivedSs1977", data.getOutput(CsOutput.STOR_SS1977_STAGE)); record.put("derivedSs2000", data.getOutput(CsOutput.STOR_SS2000_STAGE)); if (record.get("csMetsAtDx").equals("00")) { record.put("csMetsAtDxBone", "0"); record.put("csMetsAtDxBrain", "0"); record.put("csMetsAtDxLung", "0"); record.put("csMetsAtDxLiver", "0"); } else if (record.get("csMetsAtDx").equals("98") && !schemaId.equals("ill_defined_other")) { record.put("csMetsAtDxBone", "8"); record.put("csMetsAtDxBrain", "8"); record.put("csMetsAtDxLung", "8"); record.put("csMetsAtDxLiver", "8"); } else { // if any of these are 1, csMetsAtDx must not be 00 or 99 record.put("csMetsAtDxBone", "9"); record.put("csMetsAtDxBrain", "9"); record.put("csMetsAtDxLung", "9"); record.put("csMetsAtDxLiver", "9"); } } /** * Takes a table name and key and returns a random value for the given key * @param tableName CS Table name * @param key table key name * @return random value */ private String getRandomValueFromTable(String tableName, String key, Map<String, String> record, String schemaId) { String value; StagingTable table = _staging.getTable(tableName); // get a random row from the table List<StagingTableRow> tableRows = getValidTableRows(table, key, record, schemaId); StagingTableRow randomRow = tableRows.get(RandomUtils.nextInt(tableRows.size())); // get a random value or value range from the row using key List<StagingStringRange> stringRange = randomRow.getColumnInput(key); StagingStringRange randomStringRange = stringRange.get(RandomUtils.nextInt(stringRange.size())); // if no range, return high value, otherwise pick a random value in range and return it if (randomStringRange.getHigh().equals(randomStringRange.getLow())) value = randomStringRange.getHigh(); else { int high = Integer.parseInt(randomStringRange.getHigh()); int low = Integer.parseInt(randomStringRange.getLow()); value = Integer.toString(RandomUtils.nextInt(high - low + 1) + low); } return value; } /** * Takes a staging table and filters out any rows from the table that contain invalid or obsolete codes. It returns a list * of all valid rows. If there are no invalid codes in the table, the results of this method will be the same as table.getTableRows() in StagingTable. * @param table table containing rows for filtering * @param key table key being looked up * @param record tumor record * @param schemaId schema for this tumor * @return list of rows containing valid key values */ private List<StagingTableRow> getValidTableRows(StagingTable table, String key, Map<String, String> record, String schemaId) { List<StagingTableRow> validRows = new ArrayList<>(); // get the index number of the description column Integer descriptionColumnNumber = null; // find the description column number List<StagingColumnDefinition> stagingColumnDefinitions = table.getColumnDefinitions(); for (int i = 0; i < stagingColumnDefinitions.size(); i++) if (stagingColumnDefinitions.get(i).getType().toString().equals("DESCRIPTION")) descriptionColumnNumber = i; List<StagingTableRow> tableRows = table.getTableRows(); List<List<String>> tableRawRows = table.getRawRows(); int rowsInTable = tableRows.size(); for (int i = 0; i < rowsInTable; i++) { StagingTableRow row = tableRows.get(i); // check invalid values list - omit any input values that are marked invalid List<StagingStringRange> inputs = row.getColumnInput(key); boolean isInvalidValue = !inputs.isEmpty() && getInvalidValues(key, record, schemaId).contains(inputs.get(0).getHigh()); // check for error in endpoints - omit these from table List<StagingEndpoint> endpoints = row.getEndpoints(); boolean isErrorEndPoint = false; if (endpoints != null && !endpoints.isEmpty()) for (StagingEndpoint endpoint : endpoints) isErrorEndPoint |= endpoint.getType().equals(EndpointType.ERROR); // check for obsolete note in description - omit these boolean isObsoleteInDesc = descriptionColumnNumber != null && tableRawRows.get(i).get(descriptionColumnNumber).contains("OBSOLETE"); if (!isObsoleteInDesc && !isInvalidValue && !isErrorEndPoint) validRows.add(tableRows.get(i)); } // TODO: need better fix to remove 988 without leaving table empty if (validRows.size() > 1) { int i; for (i = 0; i < validRows.size(); i++) if (validRows.get(i).getColumnInput(key).get(0).getHigh().equals("988")) validRows.remove(i); } return validRows; } /** * Returns a list of all valid values for a specific key or null if it cannot define all the valid values. If a list is returned, only values in the list * may be used when randomly selecting. If null is returned, it can be assumed all possible values are valid unless later identified as invalid. * @param key table key being looked up * @param record tumor record * @param schemaId schema for this tumor * @return list of all acceptable values for the key, or null if all acceptable values cannot be defined. */ private List<String> getAllValidValues(String key, Map<String, String> record, String schemaId) { List<String> validValues = null; switch (key) { case "ssf4": case "ssf5": if (schemaId.equals("breast") && !record.get("csLymphNodes").equals("000")) validValues = new ArrayList<>(Collections.singletonList("987")); break; case "ssf13": if (schemaId.equals("breast") && record.get("csSiteSpecificFactor7").equals("998")) validValues = Collections.singletonList("988"); break; case "nodes_pos": case "nodes_exam": if (record.get("typeOfReportingSource").equals("7") || schemaId.equals("heme_retic") || schemaId.equals("lymphoma") || schemaId.equals("brain") || schemaId.equals("cns_other") || schemaId.equals("ill_defined_other") || schemaId.equals("placenta") || schemaId.equals("intracranial_gland") || schemaId.equals("myeloma_plasma_cell_disorder")) validValues = Collections.singletonList("99"); break; default: } return validValues; } /** * Returns a list of all invalid values for the specific key. When scanning the key's table, these are omitting from random selection * @param key table key being looked up * @param record tumor record * @param schemaId schema for this tumor * @return list of invalid values for the key */ private List<String> getInvalidValues(String key, Map<String, String> record, String schemaId) { List<String> invalidValues = new LinkedList<>(); switch (key) { case "size": case "nodes_eval": case "mets_eval": // for living patients (VS=1), remove eval values specifying evidence from autopsy if (record.get("vitalStatus").equals("1")) invalidValues.add("8"); break; case "extension_eval": // for living patients (VS=1), remove eval values specifying evidence from autopsy if (record.get("vitalStatus").equals("1")) if (schemaId.equals("prostate")) invalidValues.addAll(Arrays.asList("3", "8")); else invalidValues.addAll(Arrays.asList("2", "8")); break; case "ssf4": case "ssf5": if (schemaId.equals("breast") && record.get("csLymphNodes").equals("000")) invalidValues.add("987"); break; case "ssf13": if (schemaId.equals("breast") && !record.get("csSiteSpecificFactor12").equals("998")) invalidValues.add("998"); break; default: } return invalidValues; } }
JavaScript
UTF-8
3,500
2.703125
3
[]
no_license
// imports require('dotenv').config(); const passport = require('passport'); const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const { JWT_SECRET } = process.env; // Database const db = require('../models'); const { User } = require('../models'); const { Error } = require('mongoose'); //controllers const test = (req, res) => { res.json({ message: 'User enpoint OK!'}) } const register = (req, res) => { // POST - adding new user to the database console.log('======> Inside of /register in contollers/user.js') console.log('====> req.bofy') console.log(req.body) db.User.findOne({ email: req.body.email}) .then(user => { // if email already exist, a user will come back if (user){ // send a 400 response return res.status(400).json({ message: 'Email already exists'}) } else { // create a new user const newUser = new db.User({ name: req.body.name, email: req.body.email, password: req.body.password }) // Salt and hash the password before saving the user bcrypt.genSalt(10, (err, salt) => { if (err) throw Error; bcrypt.hash(newUser.password, salt, (err, hash) => { if (err) throw Error; // Change the password in newuser to the hash newUser.password = hash; newUser.save() .then(createdUser => res.json(createdUser)) .catch(err => console.log(err)) }) }) } }) .catch(err => console.log('Error finding the user', err)) } const login = async(req, res) => { // POST find user and return the user console.log('======> Inside of ^^^/login^^^ in contollers/user.js') console.log('====> req.bofy') console.log(req.body) const foundUser = await db.User.findOne({ email: req.body.email }) if (foundUser){ // user is in the DB let isMatch = await bcrypt.compare(req.body.password, foundUser.password) if (isMatch){ // console.log(isMatch); // If user match, send json web token // Create a token payload // add an const payload = { id: foundUser.id, email: foundUser.email, name: foundUser.name } jwt.sign(payload, JWT_SECRET, { expiresIn: 3600 }, (err, token) => { if (err){ res.status(400).json({ message: "Session has ended, please log in again!" }) } const legit = jwt.verify(token, JWT_SECRET, { expiresIn: 60 }) console.log('========> legit') console.log(legit) res.json({ success: true, token: `Bearer ${token}`, userData: legit }) }) } else { return res.status(400).json({ message: 'Email or Password are inccorect!'}) } }else { return res.status(400).json({ message: 'User not Found!' }) } } // Private const profile = (req, res) => { console.log('=======> inside /profile') console.log(req.body) console.log('=======> user') console.log(req.user) const { id, name, email } = req.user; res.json({ id, name, email }) } //Exports module.exports = { test, register, login, profile, }
C
UTF-8
2,675
2.609375
3
[]
no_license
struct StringNode { int cnt; int len; char *pCurStr; struct StringNode *pChildNxt; struct StringNode *pSubStrNxt; }; int CntToSubStrEnd(char *s) { int RetVal = 0; while (*s && ((*s < '0') || (*s > '9')) && (*s != '[') && (*s != ']')) { s++; RetVal++; } return RetVal; } int GetNum(char *s, int *pNum) { int RetVal = 0; *pNum = 0; while (*s && (*s >= '0') && (*s <= '9')) { *pNum = *pNum * 10; *pNum = *pNum + *s - '0'; RetVal++; s++; } return RetVal; } int CntSymboInterval(char *s) { int Flag = 1; int RetVal = 0; while (*s != '[') s++; s++; while (*s && Flag) { if (*s == '[') Flag++; else if (*s == ']') Flag--; RetVal++; s++; } RetVal--; return RetVal; } int StringProc(char *s, int len, struct StringNode **pNode) { int i; int CurStrLen = 0; int AccumStrLen = 0; int ProcLen = 0; struct StringNode *pCurNode; pCurNode = (struct StringNode *)calloc(1, sizeof(struct StringNode)); *pNode = pCurNode; while (ProcLen < len) { if ((*s >= '0') && (*s <= '9')) { CurStrLen = GetNum(s, &(pCurNode->cnt)); s += CurStrLen; ProcLen += CurStrLen; CurStrLen = CntSymboInterval(s); pCurNode->len = StringProc(s + 1 , CurStrLen , &(pCurNode->pChildNxt)); s = s + 2 + CurStrLen; AccumStrLen += ((pCurNode->len) * (pCurNode->cnt)); ProcLen += (CurStrLen + 2); } else { CurStrLen = CntToSubStrEnd(s); pCurNode->cnt = 1; pCurNode->len = CurStrLen; pCurNode->pCurStr = (char *)malloc((CurStrLen + 1) * sizeof(char)); for (i = 0; i < CurStrLen; i++) { *(pCurNode->pCurStr + i) = *(s + i); } *(pCurNode->pCurStr + i) = 0; s += CurStrLen; AccumStrLen += CurStrLen; ProcLen += CurStrLen; } if (ProcLen < len) { pCurNode->pSubStrNxt = (struct StringNode *)calloc(1, sizeof(struct StringNode)); pCurNode = pCurNode->pSubStrNxt; } } return AccumStrLen; } void FillInStr(struct StringNode *pHead, char *pDst) { int i, j; struct StringNode *pSubN; while (pHead) { for (i = 0; i < pHead->cnt; i++) { if (pHead->pCurStr) { for (j = 0; j < pHead->len; j++) { *(pDst + j) = *(pHead->pCurStr + j); } pDst = pDst + pHead->len; } else { pSubN = pHead->pChildNxt; FillInStr(pSubN, pDst); pDst = pDst + pHead->len; } } pHead = pHead->pSubStrNxt; } } char* decodeString(char* s) { char *pRet; int len = strlen(s); struct StringNode *pHead = NULL; if (len == 0) { pRet = (char *)malloc(sizeof(char)); *pRet = 0; return pRet; } len = StringProc(s, len, &pHead); pRet = (char *)malloc((len + 1) * sizeof(char)); FillInStr(pHead, pRet); *(pRet + len) = 0; return pRet; }
Ruby
UTF-8
755
2.96875
3
[ "BSD-2-Clause" ]
permissive
require "rfetch/rfetch" class GenericCommand def initialize(name, description) @name = name @description = description @parse = nil @options = {} end attr_accessor :name attr_accessor :description def init() parser = OptionParser.new do |parse| @parse = parse @parse.banner = "+ #{@name} -> #{@description}" initOptions() end parser.parse! end def run() if validOptions() runCommand() else help() end end def help() puts @parse end protected def initOptions end def validOptions return true end def runCommand() raise NotImplementedError.new() end end
JavaScript
UTF-8
2,894
2.734375
3
[]
no_license
import React, { Component, useEffect, useState } from "react"; import { useSelector, useDispatch } from "react-redux"; import ReactPaginate from 'react-paginate'; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { fetchPosts } from "../actions/postActions"; const Posts = () => { //get the data from the redux store using the useSelector. const posts = useSelector((state) => state.posts); console.log('posts',posts); //filter using the hooks state and not using reducer. //1. search is the even.target value that is captureed on change. //2 we set search using the setSerch Method i.e setSearch(event.target.value) this is equivalent to search. const [search ,setSearch] = useState(""); //4.we set the state of the filteresd posts using setFilteredPost //from the useEffect method we set the state to be filteredPosts. //then we use the filterdPosts to map the data. const [filteredPosts,setFilteredPosts] = useState([]); ///this is for pagination. const [offset,setOffset] = useState(0); const [perPage] = useState(20); const [pageCount,setPageCount] = useState(0); const dispatch = useDispatch(); useEffect(() => { const loadPosts = async () => { await dispatch(fetchPosts()); }; loadPosts(); }, []); useEffect(() => { setFilteredPosts( posts.items.filter((post) => post.title.toLowerCase().includes(search.toLowerCase()) ) ); setPageCount(Math.ceil(filteredPosts.length/perPage)); }, [search, posts]); const handlePageClick = (e) => { const selectedPage = e.selected; setOffset(selectedPage + 1) }; const slice = filteredPosts.slice(offset,offset + perPage); console.log('sliece',slice); const postItems = slice.map((post) => ( <div key={post.id}> <h3>{post.title}</h3> <p>{post.body}</p> </div> ) ).reverse(); // setData(postItems) // setPageCount(Math.ceil(filteredPosts.length/perPage)); return ( <div> search <div> <input type="text" name="search" placeholder="Search" onChange={(e) => { setSearch(e.target.value); }} /> </div> <hr></hr> <h1>Posts</h1> {postItems} <ReactPaginate previousLabel={"prev"} nextLabel={"next"} breakLabel={"..."} breakClassName={"break-me"} pageCount={pageCount} marginPagesDisplayed={2} pageRangeDisplayed={5} onPageChange={handlePageClick} containerClassName={"pagination"} subContainerClassName={"pages pagination"} activeClassName={"active"}/> </div> ); }; export default Posts;
C++
UTF-8
172
2.53125
3
[]
no_license
#include<stdio.h> int main() { int m,max=0; scanf("%d",&m); for(int i=0;i<m;i++) { int a,b; scanf("%d%d",&a,&b); if(a+b>max) max=a+b; } printf("%d\n",max); }
Markdown
UTF-8
2,079
2.609375
3
[ "MIT" ]
permissive
# Brainstorming for Final Project ## CS 462 - Distributed Systems Blaine Backman Braden Hitchcock Jonathon Meng ### Fast Flower Delivery **Underlying Data Structures** - DeliveryRequest - Driver - Store **Pico Types** - Driver Pico - Store Pico **Events** | Domain | Type | Description | |-----------|---------------------------|-----------------------------------------------| | driver | new_driver | creates a new driver | | | driver_added | upon successfully creating a new driver | | | remove_driver | removes a driver | | | driver_removed | upon successfully removing a driver | | | update_profile | changes a driver's profile information | | | profile_updated | upon successfully updating profile info | | | register_request | requests driver registration with a store | | | register_request_accepted | upon approving a driver registration request | | | register_request_denied | upon denying a driver registration request | | delivery | new_request | creates a new delivery request | | | request_created | upon successfully creating a new delivery req.| | | cancel_request | cancels a previously created request | | | accept_request | when a driver accepts a request | | | finish_delivery | request has been successfully delivered | **API Functions** | Ruleset | Function | Result | |-------------------|-------------------|---------------------------------------------------| | driver_manager | drivers | a list of drivers registered with the manager | | request_storage | delivery_requests | a list of current delivery requests (filterable) |
Go
UTF-8
524
3.9375
4
[ "MIT" ]
permissive
/* A 10-second "bomb" to show the awesomeness and simplicity of Go * * Based off one of the Go Tour examples to show channel usage * */ package main import ( "fmt" "time" ) func main() { tick := time.Tick(1 * time.Second) boom := time.After(10 * time.Second) counter := 10 fmt.Println(counter) counter-- for { select { case <- tick: fmt.Println(counter) counter-- case <- boom: fmt.Println("BOOM!") return default: fmt.Println(" .") time.Sleep(250 * time.Millisecond) } } }
Markdown
UTF-8
1,439
2.6875
3
[]
no_license
# Scrape Fandom Fandom.com provides Wiki dumps at https://*.fandom.com/wiki/Special:Statistics, but most of the dumps are outdated, and require contacting an admin to produce a new dump. This script scrapes Fandom.com for an updated Wiki dump. It scrapes the Special:AllPages to get a list of article names and requests a wiki dump from Special:Export. Instructions to get a corpus for natural language processing and training is provided. Works only for English fandom sites. Some slight modifications are needed for other languages. # Notes The requirements.txt file should list all Python libraries that your notebooks depend on, and they will be installed using: `pip install -r requirements.txt` # Usage `python3 ScrapeFandom.py NAME_OF_FANDOM` For example, NAME_OF_FANDOM will be `harrypotter` for `https://harrypotter.fandom.com` To subsequently extract the WikiDump, one can use the fork: https://github.com/ujiuji1259/wikiextractor/tree/fix_colon # Further Instructions 1. Clone the extractor locally (https://github.com/ujiuji1259/wikiextractor/tree/fix_colon) 2. Open the terminal and cd your way to the repo dir 3. Run `python3 setup.py install` 4. After it finishes, you'll be able to use the extractor. Run wikiextractor `fandom_name.xml --no-templates --json --o extracted_files` 5. extracted_files folder will be created. cd into it and run the converter `python3 json2txt.py extracted_files/AA output_file.txt`
Java
UTF-8
3,540
2.296875
2
[ "MIT" ]
permissive
package reka.modules.admin; import static com.google.common.base.Preconditions.checkArgument; import static reka.util.Util.deleteRecursively; import static reka.util.Util.runtime; import static reka.util.Util.unwrap; import static reka.util.Util.unzip; import java.io.File; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reka.app.Application; import reka.app.manager.ApplicationManager; import reka.app.manager.ApplicationManager.DeploySubscriber; import reka.config.FileSource; import reka.data.Data; import reka.data.MutableData; import reka.data.content.Content; import reka.data.content.types.BinaryContent; import reka.flow.ops.AsyncOperation; import reka.flow.ops.OperationContext; import reka.identity.Identity; import reka.util.Path; import reka.util.dirs.AppDirs; import reka.util.dirs.BaseDirs; public class RekaDeployOperation implements AsyncOperation { private final Logger log = LoggerFactory.getLogger(getClass()); private final ApplicationManager manager; private final BaseDirs basedirs; private final Function<Data,Path> dataPathFn; private final Function<Data,Path> appPathFn; public RekaDeployOperation(ApplicationManager manager, BaseDirs basedirs, Function<Data, Path> dataPathFn, Function<Data,Path> appPathFn) { this.manager = manager; this.basedirs = basedirs; this.dataPathFn = dataPathFn; this.appPathFn = appPathFn; } @Override public void call(MutableData data, OperationContext ctx, OperationResult res) { Path dataPath = dataPathFn.apply(data); Path appPath = appPathFn.apply(data); data.putString("identity", appPath.slashes()); int version = manager.nextVersion(appPath); AppDirs dirs = basedirs.resolve(appPath, version); Data val = data.at(dataPath); if (!val.isPresent()) throw runtime("no data at %s", dataPath.dots()); if (!val.isContent()) throw runtime("not content at %s", dataPath.dots()); if (!val.content().type().equals(Content.Type.BINARY)) throw runtime("must be binary content at %s", dataPath.dots()); BinaryContent bc = (BinaryContent) val.content(); if (!"application/zip".equals(bc.contentType())) throw runtime("must be application/zip content at %s", dataPath.dots()); log.info("unpacking {} to {}", appPath.slashes(), dirs.app()); dirs.mkdirs(); deleteRecursively(dirs.app()); unzip(bc.asBytes(), dirs.app()); File appdir = dirs.app().toFile(); File mainreka = dirs.app().resolve("main.reka").toFile(); checkArgument(appdir.exists(), "app dir does not exist [%s]", appdir); checkArgument(appdir.isDirectory(), "app dir is not directory [%s]", appdir); checkArgument(mainreka.exists(), "main.reka does not exist"); checkArgument(!mainreka.isDirectory(), "main.reka is a directory"); log.info("deploying {}", appPath.slashes()); manager.deploySource(appPath, -1, FileSource.from(mainreka), new DeploySubscriber() { @Override public void ok(Identity identity, int version, Application application) { log.info("deploying {} ok", identity); data.putString("message", "created application!"); res.done(); // delete a few old versions... for (int v = version - 3; v >= 0; v--) { deleteRecursively(basedirs.resolve(identity.path(), v).app()); } } @Override public void error(Identity identity, Throwable t) { t = unwrap(t); log.error("failed to deploy [{}] - {}", identity.name(), t.getMessage()); res.error(t); deleteRecursively(dirs.app()); } }); } }
Java
UTF-8
2,857
1.960938
2
[]
no_license
package com.codejoys.company.mapper; import com.codejoys.company.entity.DeptManager; import com.codejoys.company.entity.DeptManagerExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface DeptManagerMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dept_manager * * @mbg.generated */ long countByExample(DeptManagerExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dept_manager * * @mbg.generated */ int deleteByExample(DeptManagerExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dept_manager * * @mbg.generated */ int deleteByPrimaryKey(@Param("empNo") Integer empNo, @Param("deptNo") String deptNo); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dept_manager * * @mbg.generated */ int insert(DeptManager record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dept_manager * * @mbg.generated */ int insertSelective(DeptManager record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dept_manager * * @mbg.generated */ List<DeptManager> selectByExample(DeptManagerExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dept_manager * * @mbg.generated */ DeptManager selectByPrimaryKey(@Param("empNo") Integer empNo, @Param("deptNo") String deptNo); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dept_manager * * @mbg.generated */ int updateByExampleSelective(@Param("record") DeptManager record, @Param("example") DeptManagerExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dept_manager * * @mbg.generated */ int updateByExample(@Param("record") DeptManager record, @Param("example") DeptManagerExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dept_manager * * @mbg.generated */ int updateByPrimaryKeySelective(DeptManager record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dept_manager * * @mbg.generated */ int updateByPrimaryKey(DeptManager record); }
Java
UTF-8
3,269
2.171875
2
[]
no_license
package com.epam.preprod.bohdanov.controller.servlet; import java.io.IOException; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import com.epam.preprod.bohdanov.controller.Path; import com.epam.preprod.bohdanov.model.bean.LoginFormBean; import com.epam.preprod.bohdanov.model.entity.User; import com.epam.preprod.bohdanov.service.UserService; import com.epam.preprod.bohdanov.utils.validator.AnnotationValidator; public class Login extends HttpServlet { private static final Logger LOG = Logger.getLogger(Login.class); private static final long serialVersionUID = 1L; private UserService userService; private final String NO_SUCH_USER = "No such user"; public void init(ServletConfig servletConfig) throws ServletException { ServletContext context = servletConfig.getServletContext(); userService = (UserService) context.getAttribute("userService"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); request.setAttribute("form", session.getAttribute("form")); request.setAttribute("errors", session.getAttribute("errors")); LOG.trace("form: " + session.getAttribute("form")); LOG.trace("errors: " + session.getAttribute("errors")); session.removeAttribute("form"); session.removeAttribute("errors"); RequestDispatcher rd = request.getRequestDispatcher(Path.LOGIN_JSP); rd.forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LoginFormBean form = new LoginFormBean(request.getParameter("email"), request.getParameter("password")); AnnotationValidator validator = new AnnotationValidator(form); Map<String, String> errors = validator.validate(); if (errors.isEmpty()) { User user = (User) userService.login(form.getEmail(), form.getPassword()); if (user != null) { user.setPassword(null); HttpSession session = request.getSession(); session.setAttribute("isLogin", true); session.setAttribute("user", user); if (StringUtils.isNotBlank(request.getParameter("action"))) { response.sendRedirect(request.getParameter("action")); } else { response.sendRedirect(Path.CATEGORY_SERVLET); } return; } else { errors.put("login_error", NO_SUCH_USER); } } HttpSession session = request.getSession(); session.setAttribute("errors", errors); session.setAttribute("form", form); response.sendRedirect(Path.LOGIN_SERVLET); } }
PHP
UTF-8
6,021
2.53125
3
[]
no_license
<?php require_once($_SERVER['DOCUMENT_ROOT'].'/v1/controls/utilities/Guid.php'); /** * Created by PhpStorm. * User: Maestro * Date: 10/7/2015 * Time: 4:24 PM */ class ModelEntity { const SELECT_SEATS_BY_ID = <<<EOF SELECT u.*, b.seatId, b.date FROM seating_chart u JOIN seatId b ON u.id = b.userId WHERE b.date = (SELECT MAX(date) FROM balance WHERE userId = u.id); EOF; const SELECT_BETWEEN_DATE_RANGE = <<<EOF SELECT *, start_date, end_date FROM seating_chart WHERE date(now()) BETWEEN start_date AND end_date EOF; const SELECT_ALL_SQL = <<<EOF SELECT id, link, modelImageFile, user_id FROM model_mode ORDER BY id DESC EOF; const SELECT_BY_ID_SQL = <<<EOF SELECT * FROM model_modei WHERE id = ? EOF; const SELECT_ALL_BY_USER_SQL = <<<EOF SELECT * FROM model_mode WHERE user_id = ? EOF; const SELECT_BY_LINK_SQL = <<<EOF SELECT modelName, modelDescription, modelFile, modelAsset, user_id FROM model_mode WHERE link = ? LIMIT 1 EOF; const INSERT_SQL = <<<EOF INSERT INTO `model_mode` (`modelId`, `modelName`, `modelDescription`, `modelFile`, `modelAsset`, `link`, `modelImageFile`, `user_id`, `createdAtDate`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) EOF; const UPDATE_SQL = <<<EOF UPDATE `model_mode` SET `modelName`=:modelName, `modelDescription`=:modelDescription, `modelImageFile`=:modelImageFile WHERE `modelId`=:modelId EOF; protected $modelId; protected $modelName; protected $modelDescription; protected $modelFile; protected $modelAsset; protected $modelPageLink; protected $modelImageFile; //protected $author; //protected $license; protected $user_id; protected $createdAtDate; public function __construct() { $this->table = 'model_mode'; $createId = new Guid(); $guId = $createId->guid(); $this->setModelId($guId); } public function mapData($data) { $this->setModelName($data['name']); $this->setModelDescription($data['description']); $this->setModelFile($data['file']); $this->setModelAsset($data['asset']); $this->setModelPageLink($data['link']); $this->setModelImageFile($data['image']); //$this->setAuthor($data['author']); //$this->setLicense($data['license']); $this->setUserId($data['user_id']); $this->setCreatedAtDate(); } public function getSelectAllSql() { return self::SELECT_ALL_SQL; } public function getInsertSql() { return self::INSERT_SQL; } public function getSelectByURLSql() { return self::SELECT_BY_LINK_SQL; } public function getSelectAllByUserIdSql() { return self::SELECT_ALL_BY_USER_SQL; } public function getUpdateSql() { return self::UPDATE_SQL; } /** * @return mixed */ public function getModelId() { return $this->modelId; } /** * @param mixed $modelId */ public function setModelId($modelId) { $this->modelId = $modelId; } /** * @return mixed */ public function getModelName() { return $this->modelName; } /** * @param mixed $modelName */ public function setModelName($modelName) { $this->modelName = $modelName; } /** * @return mixed */ public function getModelDescription() { return $this->modelDescription; } /** * @param mixed $modelDescription */ public function setModelDescription($modelDescription) { $this->modelDescription = $modelDescription; } /** * @return mixed */ public function getModelFile() { return $this->modelFile; } /** * @param mixed $modelFile */ public function setModelFile($modelFile) { $this->modelFile = $modelFile; } /** * @return mixed */ public function getModelAsset() { return $this->modelAsset; } /** * @param mixed $modelAsset */ public function setModelAsset($modelAsset) { $this->modelAsset = $modelAsset; } /** * @return mixed */ public function getModelPageLink() { return $this->modelPageLink; } /** * @param mixed $modelPageLink */ public function setModelPageLink($modelPageLink) { $this->modelPageLink = $modelPageLink; } /** * @return mixed */ public function getModelImageFile() { return $this->modelImageFile; } /** * @param mixed $modelImageFile */ public function setModelImageFile($modelImageFile) { $this->modelImageFile = $modelImageFile; } /** * @return mixed */ /*public function getAuthor() { return $this->author; }*/ /** * @param mixed $author */ /*public function setAuthor($author) { $this->author = $author; }*/ /** * @return mixed */ /*public function getLicense() { return $this->license; }*/ /** * @param mixed $license */ /*public function setLicense($license) { $this->license = $license; }*/ /** * @return mixed */ public function getUserId() { return $this->user_id; } /** * @param mixed $user_id */ public function setUserId($user_id) { $this->user_id = $user_id; } /** * @return mixed */ public function getCreatedAtDate() { return $this->createdAtDate; } /** * */ public function setCreatedAtDate() { $this->createdAtDate = date("Y-m-d H:i:s"); } }
TypeScript
UTF-8
1,812
2.625
3
[]
no_license
import * as fromApp from "../../../../../../store/app.reducers"; import { EditSectionActions, EditSectionActionTypes } from "./edit-section.actions"; import { createFeatureSelector, createSelector } from "@ngrx/store"; export interface EditSectionState { loading: boolean; error: boolean; success: boolean; } export const initialState: EditSectionState = { loading: false, error: false, success: false }; export interface State extends fromApp.State { guideEditSection: EditSectionState; } export function reducer(state = initialState, action: EditSectionActions) { switch (action.type) { case EditSectionActionTypes.ResetState: return initialState; case EditSectionActionTypes.EditSection: return { ...state, loading: true, error: false, success: false }; case EditSectionActionTypes.EditSectionSuccess: return { ...state, loading: false, success: true, error: false }; case EditSectionActionTypes.EditSectionError: return { ...state, loading: false, error: true }; } return state; } export const getGuideEditSectionState = createFeatureSelector<State, EditSectionState>("guideEditSection"); export const getGuideEditSectionLoading = createSelector(getGuideEditSectionState, (state: EditSectionState) => state.loading); export const getGuideEditSectionError = createSelector(getGuideEditSectionState, (state: EditSectionState) => state.error); export const getGuideEditSectionSuccess = createSelector(getGuideEditSectionState, (state: EditSectionState) => state.success);
Java
UTF-8
1,349
1.796875
2
[ "Apache-2.0" ]
permissive
package com.soundink.lib; import android.content.Context; import android.os.AsyncTask; import com.soundink.lib.b.b; import java.io.IOException; import org.json.JSONException; final class a extends AsyncTask<Void, Void, String> { static String a = ""; private d b = new d(this.c); private String c = com.soundink.lib.c.a.b().toString(); private String d; protected final /* synthetic */ Object doInBackground(Object... objArr) { return a(); } protected final /* synthetic */ void onPostExecute(Object obj) { String str = (String) obj; if (str != null) { try { a = e.a(str); } catch (JSONException e) { e.printStackTrace(); } } } public a(Context context) { com.soundink.lib.c.a aVar = new com.soundink.lib.c.a(context); } protected final void onPreExecute() { } private String a() { try { this.d = this.b.a(SoundInkInterface.getAppKey(), this.c); } catch (com.soundink.lib.b.a e) { e.printStackTrace(); } catch (b e2) { e2.printStackTrace(); } catch (IOException e3) { e3.printStackTrace(); } catch (JSONException e4) { e4.printStackTrace(); } return this.d; } }
Java
UTF-8
1,100
2.171875
2
[]
no_license
package jokrey.utilities.network.link2peer.node.protocols_old; /** * @author jokrey */ public class WhoAmIProtocolOld { // static int R_WHO_AM_I_ANSWER = -999; // public static P2Link asInitiator(P2LNodeInternal parent, InetSocketAddress to) throws IOException { // return P2Link.from(parent.tryReceive(P2LHeuristics.DEFAULT_PROTOCOL_ATTEMPT_COUNT, P2LHeuristics.DEFAULT_PROTOCOL_ATTEMPT_INITIAL_TIMEOUT, () -> // P2LFuture.before(() -> // parent.sendInternalMessage(to, P2LMessage.createSendMessageWith(SL_WHO_AM_I)), // parent.expectInternalMessage(to, R_WHO_AM_I_ANSWER)) // ).asBytes()); // } // public static void asAnswerer(P2LNodeInternal parent, DatagramPacket receivedPacket) throws IOException { // parent.sendInternalMessage((InetSocketAddress) receivedPacket.getSocketAddress(), P2LMessage.Factory.createSendMessage(R_WHO_AM_I_ANSWER, // new P2Link.Direct(receivedPacket.getAddress().getCanonicalHostName(), receivedPacket.getPort()).toBytes() // )); // } }
Markdown
UTF-8
9,511
3.359375
3
[]
no_license
# Getting Started As part of this module we will set up the development environment to develop an application to copy data from JSON Files to a target database (Postgres). * Problem Statement - Data Copier * Setup Docker * Quick Overview of Docker * Prepare Dataset * Setup Postgres Database * Overview of Postgres * Setup Project using PyCharm * Managing Dependencies * Create GitHub Repository ## Problem Statement - Data Copier Let us go through the problem statement for our project. We would like to develop the code to copy data which are in files using JSON Format to Postgres Database. Data is available in another repository called as [retail_db_json](https://github.com/itversity/retail_db_json). We will see how to setup the repository later. But we will review the data now. ## Setup Docker Let us understand different options to setup Docker using different environments. We will also see how to set up Docker on Cloud9 * If your Mac or PC have 16 GB RAM and Quad Core, I would recommend to setup Docker Desktop. Just Google and Set it up. * For Windows, there might be some restrictions on Windows 10 Home and older versions. * If you do not want to install locally, you can setup the whole development environment using AWS Cloud9. Make sure to choose Ubuntu as OS while setting up AWS Cloud9. ## Quick Overview of Docker Docker is one of the key technology to learn. Let us quickly review some of the key concepts related to Docker. * Overview of Docker Images * Managing Docker Images * Overview of Docker Containers * Starting Containers using Images * Managing Docker Containers * Usage and Characteristics of Docker Containers * Images are reusable * Containers are ephemeral (stateless) * Production Databases should not be running on Docker Containers * Production Applications are typically deployed using Docker Containers ## Prepare Dataset Let us prepare dataset to play around. Dataset is part of GitHub Repository. * The data set is called as **retail_db**. It is a hypothetical data set provided by Cloudera as part of Cloudera QuickStart VM. * Clone **retail_db** repository from GitHub. We will use this repository to setup tables and load data as part of the database. ```shell script git clone https://www.github.com/itversity/retail_db_json.git ``` * It has some scripts as well as json separated files as well. * As part of this usecase we will use scripts which will create tables as well as load data sets. * **create_db_tables_pg.sql** is the script which will facilitate us to create tables alone. It will not load data into the tables. ## Setup Postgres Database Let us setup a database using Postgres as part of Docker Container. * Pull image `docker pull postgres` * Create folder for Postgres Database ```shell script mkdir retail_pg ``` * Create and start container using `docker run` ```shell script docker run \ --name retail_pg \ -e POSTGRES_PASSWORD=itversity \ -d \ -v `pwd`/data/retail_db_json:/data/retail_db_json \ -v `pwd`/retail_pg:/var/lib/postgresql/data \ -p 5452:5432 \ postgres # Windows using Powershell docker run --name retail_pg -e POSTGRES_PASSWORD=itversity -d -v C:\Users\dgadiraju\Projects\data-copier\retail_pg:/var/lib/postgresql/data -v C:\Users\dgadiraju\Projects\retail_db_json:/retail_db_json -p 5452:5432 postgres ``` * We can review the logs by using `docker logs -f pg_retail_db` command. * Make sure retail_db is either mounted or copied on to the Docker Container. * Connect to Postgres database using `docker exec` ```shell script docker exec \ -it retail_pg \ psql -U postgres # On Windows docker exec -it retail_pg psql -U postgres ``` * Create Database and User as part of Postgres running in Docker ```sql CREATE DATABASE retail_db; CREATE USER retail_user WITH ENCRYPTED PASSWORD 'itversity'; GRANT ALL PRIVILEGES ON DATABASE retail_db TO retail_user; ``` * Run **/retail_db_json/create_db_tables_pg.sql** to create tables using Postgres CLI. ```shell script docker exec \ -it retail_pg \ psql -U retail_user \ -d retail_db \ -f /data/retail_db/create_db_tables_pg.sql # On Windows docker exec -it retail_pg psql -U retail_user -d retail_db -f /retail_db_json/create_db_tables_pg.sql ``` ## Overview of Postgres Let us get a quick overview of Postgres Database. * Postgres is multi tenant database server. It means there can be multiple databases per server. * We typically create databases and users then grant different types of permissions for different users. * Here are the details about our database: * Database Name: **retail_db** * Database User: **retail_user** * Permissions: **ALL** (DDL, DML, Queries) * Login to the system or Docker container where Postgres is running. In my case I am connecting to Docker container. ```shell script docker exec \ -it retail_pg \ bash ``` * Login to Postgres Database ```shell script psql -U retail_user \ -d retail_db \ -W ``` * Let us create additional table with 2 fields. ```sql CREATE TABLE t ( i INT, s VARCHAR(10) ); ``` * CRUD Operations (DML) * C - Create -> INSERT * R - Read -> Querying using SELECT * U - Update -> UPDATE * D - Delete -> DELETE * CRUD Operations are achieved using Data Manipulation Language (DML). * Syntax with respect DML Statements is same with most of the RDBMS Databases. * Let us insert data into the table. * Inserting one row at a time. ```sql INSERT INTO t VALUES (1, 'Hello'); INSERT INTO t VALUES (2, 'World'); SELECT * FROM t; ``` * Inserting multiple rows at a time (bulk insert or batch insert) ```sql INSERT INTO t VALUES (1, 'Hello'), (2, 'World'); SELECT * FROM t; ``` * Let us update data in the table. ```sql UPDATE t SET s = lower(s); SELECT * FROM t; UPDATE t SET s = 'Hello' WHERE s = 'hello'; SELECT * FROM t; ``` * Let us delete data from the table. ```sql DELETE FROM t WHERE s = 'Hello'; SELECT * FROM t; DELETE FROM t; -- Deletes all the data from a given table. SELECT * FROM t; ``` * We can also clean up the whole table using DDL Statement. `TRUNCATE` is faster to clean up the data compared to `DELETE` with out conditions. ```sql TRUNCATE TABLE t; SELECT * FROM t; ``` * We can drop the table using `DROP` Command. ```sql DROP TABLE t; ``` * SQL Commands starts with `CREATE`, `ALTER`, `TRUNCATE`, `DROP` etc are called as Data Definition Language or DDL Commands. ## Setup Project using PyCharm Let us setup project using PyCharm. I will be using PyCharm Enterprise Edition. However, you can use Community Edition as well. * Create New Project by name **data-copier**. * Make sure virtual environment is created with name **dc-venv**. It will make sure we are in appropriate virtual environment related to our project. * Create a program by name **app.py**. * Add below code to it and validate using PyCharm. ```python def main(): print("Hello World!") if __name__ == "__main__": main() ``` ## Managing Dependencies Let us see how we can manage dependencies for Python Projects. * We use Pip to manage dependencies for Python based Projects. * Here is the typical life cycle. * Search for Python libraries using [https://pypi.org](https://pypi.org). * One can install directly using `pip install` Command. For example `pip install configparser`. * To overcome compatibility issues, we need to decide on versions. * We can also pass version of the library to `pip install` command. For example `pip install configparser==5.0.0`. * For projects we keep track of all the external libraries using a text file - e.g. **requirements.txt**. * We can add libraries to our project using **requirements.txt**. For example, here we are adding Pandas to our project. ```text pandas==1.3.2 ``` * We will take care of other libraries later. * Once libraries are defined as part of **requirements.txt**, we can run `pip install -r requirements.txt`. * We can also uninstall all the libraries using relevant command. ## Create GitHub Repository As we have skeleton of the project, let us setup GitHub repository to streamline future code changes. * GitHub can be used to version our application. * We can initialize GitHub repository by saying `git init`. It will create **.git** directory to keep track of changes. * GitHub should only contain source code related to our application. Hence, we should ignore non source code files and folders such as following: * **.idea** - a folder created by PyCharm to keep track of IDE preferences and settings. * **__pycache__** - a file which contain bytecode of the program which can be interpreted by Python interpreter. * **data-copier-env** - a directory which is created when virtual environment is added to our project. * We might add other files in future. ```text dc-venv __pycache__ .idea ``` * Add the source code files to keep track of changes and then commit. ```shell script git add . # Adds all the files recursively from the directory in which command is executed # We can also add specific files or directories git commit # Review all the files and make sure only source code files are included along with README.md # Add commit message and save. If you are not comfortable with command line you can use Pycharm Git Plugin. # You can also give commit message with git commit itself git commit -m "Initial Commit" ``` * Now go to [GitHub Website](https://www.github.com) and add a repository as demonstrated. Make sure to sign up if you do not have account. * Follow the instructions provided after repository is created to push the existing repository.
Python
UTF-8
553
4.03125
4
[]
no_license
""" 챕터: day3 주제: set (mutable) 작성자: 주동석 작성일: 2018. 9. 11 """ s = {7, 8, 9} print(s) # set은 순서 의미 없음. 중복은 허용하지 않는다. fruits = {'a' : '사과', 'b' : '배', 'c' : '복숭아', 'd' : '딸기'}; print(set(fruits)) # [3, 4, 5]를 set으로 형변환하여 s에 저장하고, 이를 출력하라. print(set([3, 4, 5])) # 인덱스를 사용할 수 없음. 위치가 의미 없으므로. s.add(10) print(s) # remove로 삭제 s.remove(10) print(s) # 정렬한 결과가 넘어옴 print(sorted(s))
Java
UTF-8
1,184
2.359375
2
[]
no_license
package uk.ac.ucl.jsh.Parser; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import uk.ac.ucl.jsh.Parser.Call.*; import uk.ac.ucl.jsh.Parser.CommandLine.*; import uk.ac.ucl.jsh.Visitor.CallVisitor; import uk.ac.ucl.jsh.Visitor.CommandLineVisitor; import uk.ac.ucl.jsh.Visitor.Visitable; import java.util.ArrayList; public class Parser { public static Visitable parseCMD(String cmdline) { CommandLineGrammarLexer lexer = new CommandLineGrammarLexer(CharStreams.fromString(cmdline)); CommandLineGrammarParser parser = new CommandLineGrammarParser(new CommonTokenStream(lexer)); CommandLineGrammarParser.StartContext compile_unit = parser.start(); return new CommandLineVisitor().visitStart(compile_unit); } public static ArrayList<String> parseCallCommand (String callCommand) { CallGrammarLexer lexer = new CallGrammarLexer(CharStreams.fromString(callCommand)); CallGrammarParser parser = new CallGrammarParser(new CommonTokenStream(lexer)); CallGrammarParser.StartContext compile_unit = parser.start(); return new CallVisitor().visitStart(compile_unit); } }
Java
UTF-8
2,682
2.296875
2
[]
no_license
package cs190i.cs.ucsb.edu.recyclerviewtest; import android.content.Intent; import android.os.Parcelable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.AdapterView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { public List<Town> towns; public static final String EXTRA_IMAGEID = "MESSAGE_DETAIL_IMAGE"; public static final String EXTRA_TEXT = "MESSAGE_TEXT"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); //mRecyclerView.setHasFixedSize(true); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext()); mRecyclerView.setLayoutManager(linearLayoutManager); initData(); Adapter mAdapter = new Adapter(towns); mRecyclerView.setAdapter(mAdapter); mRecyclerView.addOnItemTouchListener( new RecyclerItemClickListener(getApplicationContext(), mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { //Log.i("addOnItemTouchListener", "onItemClick position =" + position); Intent intent = new Intent(getApplicationContext(), DetailActivity.class); intent.putExtra(EXTRA_IMAGEID, towns.get(position).imageID); intent.putExtra(EXTRA_TEXT,towns.get(position).name); startActivity(intent); } @Override public void onLongItemClick(View view, int position) { } }) ); } private void initData() { towns = new ArrayList<>(); towns.add(new Town("Town 1", R.drawable.img1)); towns.add(new Town("Town 2", R.drawable.img2)); towns.add(new Town("Town 3", R.drawable.img3)); towns.add(new Town("Town 4", R.drawable.img4)); towns.add(new Town("Town 5", R.drawable.img5)); towns.add(new Town("Town 6", R.drawable.img6)); towns.add(new Town("Town 7", R.drawable.img1)); towns.add(new Town("Town 8", R.drawable.img2)); } }
C#
UTF-8
1,369
2.8125
3
[ "MIT" ]
permissive
namespace MagicModels.Schemas { using System; using System.Collections.Generic; using System.Reflection; using MagicModels.Attributes; public sealed class RenderableClassSchema { /// <summary> /// Renderer component type. When null, default renderer will be used. /// </summary> public Type? Renderer { get; } /// <summary> /// Model type. /// </summary> public Type ClassType { get; } /// <summary> /// Property schemas. /// </summary> public IReadOnlyList<RenderablePropertySchema> PropertySchemas { get; } public RenderableClassSchema(Type? renderer, Type classType, IReadOnlyList<RenderablePropertySchema> propertySchemas) { Renderer = renderer; ClassType = classType; PropertySchemas = propertySchemas; } /// <summary> /// Checks whether type is a valid renderable class. /// </summary> public static bool IsRenderableClassType(Type type) { if (type.IsAbstract || type.IsInterface || type.IsGenericType) { return false; } return type.IsDefined(typeof(RenderableClassAttribute)); } } }
Python
UTF-8
1,127
3.609375
4
[]
no_license
# -*- coding: utf-8 -*- # @Time : 2020/6/21 14:33 # @Author : Mamamooo # @Site : # @File : ht_40.py # @Software: PyCharm """ 题目描述 现有一组砝码,重量互不相等,分别为m1,m2,m3…mn; 每种砝码对应的数量为x1,x2,x3...xn。现在要用这些砝码去称物体的重量(放在同一侧),问能称出多少种不同的重量。 注: 称重重量包括0 输入描述: 输入包含多组测试数据。 对于每组测试数据: 第一行:n --- 砝码数(范围[1,10]) 第二行:m1 m2 m3 ... mn --- 每个砝码的重量(范围[1,2000]) 第三行:x1 x2 x3 .... xn --- 每个砝码的数量(范围[1,6]) 输出描述: 利用给定的砝码可以称出的不同的重量数 """ while True: try: n = int(input()) m = list(map(int,input().split())) x = list(map(int,input().split())) print(n,m,x,sep='\n') height = [0] for r in range(n): h_1 = [m[r] * i for i in range(x[r] + 1)] height = list(set([a+b for a in h_1 for b in height])) print(height) print(len(height)) except: break
C#
UTF-8
1,683
2.578125
3
[]
no_license
using PMAircraftIngress.Context; using System; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; namespace PMAircraftIngress.App_Utils { internal class ApplicationLog { private string LogPath { get; set; } protected ApplicationLog(string logPath) { this.LogPath = logPath; } public static ApplicationLog AcquireLog(IngressContext context) { ApplicationLog returnValue = null; try { string logPath = context.ApplicationLogPath; if (!string.IsNullOrEmpty(logPath)) { DateTime now = DateTime.Now; string logName = string.Format("{0}.log", now.ToString("MMddyyy_HHmmss")); if (logPath.StartsWith(".")) { string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); logPath = logPath.TrimStart(new char[] { '.', '/', '\\' }); logPath = Path.Combine(appPath, logPath); } if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } logPath = Path.Combine(logPath, logName); returnValue = new ApplicationLog(logPath); } } catch (Exception exception) { } return returnValue; } public void Report(string reportData) { this.Report(reportData, null); } public void Report(string format, params object[] formatObjects) { string logData = format; if (formatObjects != null) { logData = string.Format(format, formatObjects); } DateTime now = DateTime.Now; logData = string.Format("{0}\t{1}", now.ToString("HH:mm:ss:fff"), logData); using (StreamWriter writer = new StreamWriter(this.LogPath, true)) { writer.WriteLine(logData); } } } }
Java
UTF-8
1,200
3.90625
4
[]
no_license
/** * 有一个类似结点的数据结构TreeNode,包含了val属性和指向其它结点的指针。 * 请编写一个方法,将二叉查找树转换为一个链表,其中二叉查找树的数据结构用TreeNode实现,链表的数据结构用ListNode实现。 * 给定二叉查找树的根结点指针root,请返回转换成的链表的头指针。 */ public class Ex_68 { public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } ListNode listNode = new ListNode(-1); ListNode cur = listNode; public ListNode treeToList(TreeNode root) { // write code here inOrderTraverse(root); return listNode.next; } private void inOrderTraverse(TreeNode node) { if (node == null) { return; } inOrderTraverse(node.left); cur.next = new ListNode(node.val); cur = cur.next; inOrderTraverse(node.right); } }
PHP
UTF-8
99
2.625
3
[]
no_license
<?php $word = "hello world"; $num = 2019; echo $word.$num; echo '<br>'; echo "hello world".$num; ?>
Java
UTF-8
7,869
1.828125
2
[]
no_license
package org.ace.insurance.system.common.ggiorganization; import java.io.Serializable; import java.util.Date; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.AssociationOverride; import javax.persistence.AttributeOverride; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import org.ace.insurance.common.CommonCreateAndUpateMarks; import org.ace.insurance.common.ContentInfo; import org.ace.insurance.common.PermanentAddress; import org.ace.insurance.common.TableName; import org.ace.insurance.system.common.branch.Branch; import org.ace.java.component.FormatID; import org.ace.java.component.idgen.service.IDInterceptor; @Entity @Table(name = TableName.GGIORGANIZATION) @TableGenerator(name = "GGIORGANIZATION_GEN", table = "ID_GEN", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VAL", pkColumnValue = "GGIORGANIZATION_GEN", allocationSize = 10) @EntityListeners(IDInterceptor.class) @Access(value = AccessType.FIELD) public class GGIOrganization implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Transient private String id; private String name; @Transient private String prefix; @Column(name = "CODE_NO") private String codeNo; @Column(name = "REG_NO") private String regNo; @Column(name = "OWNER_NAME") private String OwnerName; private int activePolicy; @Temporal(TemporalType.TIMESTAMP) private Date activedDate; private String description; @Embedded @AttributeOverride(name = "permanentAddress", column = @Column(name = "ADDRESS")) @AssociationOverride(name = "township", joinColumns = @JoinColumn(name = "TOWNSHIP_ID")) private PermanentAddress address; @Embedded private ContentInfo contentInfo; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "BRANCHID", referencedColumnName = "ID") private Branch branch; @Embedded private CommonCreateAndUpateMarks commonCreateAndUpateMarks; private int version; public GGIOrganization() { address = new PermanentAddress(); contentInfo = new ContentInfo(); commonCreateAndUpateMarks = new CommonCreateAndUpateMarks(); } public int getVersion() { return version; } @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "GGIORGANIZATION_GEN") @Access(AccessType.PROPERTY) public String getId() { return id; } public void setId(String id) { if (id != null) { this.id = FormatID.formatId(id, getPrefix(), 10); } } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getCodeNo() { return codeNo; } public void setCodeNo(String codeNo) { this.codeNo = codeNo; } public String getRegNo() { return regNo; } public void setRegNo(String regNo) { this.regNo = regNo; } public String getOwnerName() { return OwnerName; } public void setOwnerName(String ownerName) { OwnerName = ownerName; } public int getActivePolicy() { return activePolicy; } public void setActivePolicy(int activePolicy) { this.activePolicy = activePolicy; } public Date getActivedDate() { return activedDate; } public void setActivedDate(Date activedDate) { this.activedDate = activedDate; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public PermanentAddress getAddress() { return address; } public void setAddress(PermanentAddress address) { this.address = address; } public ContentInfo getContentInfo() { return contentInfo; } public void setContentInfo(ContentInfo contentInfo) { this.contentInfo = contentInfo; } public Branch getBranch() { return branch; } public void setBranch(Branch branch) { this.branch = branch; } public CommonCreateAndUpateMarks getCommonCreateAndUpateMarks() { return commonCreateAndUpateMarks; } public void setCommonCreateAndUpateMarks(CommonCreateAndUpateMarks commonCreateAndUpateMarks) { this.commonCreateAndUpateMarks = commonCreateAndUpateMarks; } public void setVersion(int version) { this.version = version; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((OwnerName == null) ? 0 : OwnerName.hashCode()); result = prime * result + activePolicy; result = prime * result + ((activedDate == null) ? 0 : activedDate.hashCode()); result = prime * result + ((address == null) ? 0 : address.hashCode()); result = prime * result + ((branch == null) ? 0 : branch.hashCode()); result = prime * result + ((codeNo == null) ? 0 : codeNo.hashCode()); result = prime * result + ((commonCreateAndUpateMarks == null) ? 0 : commonCreateAndUpateMarks.hashCode()); result = prime * result + ((contentInfo == null) ? 0 : contentInfo.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((prefix == null) ? 0 : prefix.hashCode()); result = prime * result + ((regNo == null) ? 0 : regNo.hashCode()); result = prime * result + version; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GGIOrganization other = (GGIOrganization) obj; if (OwnerName == null) { if (other.OwnerName != null) return false; } else if (!OwnerName.equals(other.OwnerName)) return false; if (activePolicy != other.activePolicy) return false; if (activedDate == null) { if (other.activedDate != null) return false; } else if (!activedDate.equals(other.activedDate)) return false; if (address == null) { if (other.address != null) return false; } else if (!address.equals(other.address)) return false; if (branch == null) { if (other.branch != null) return false; } else if (!branch.equals(other.branch)) return false; if (codeNo == null) { if (other.codeNo != null) return false; } else if (!codeNo.equals(other.codeNo)) return false; if (commonCreateAndUpateMarks == null) { if (other.commonCreateAndUpateMarks != null) return false; } else if (!commonCreateAndUpateMarks.equals(other.commonCreateAndUpateMarks)) return false; if (contentInfo == null) { if (other.contentInfo != null) return false; } else if (!contentInfo.equals(other.contentInfo)) return false; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (prefix == null) { if (other.prefix != null) return false; } else if (!prefix.equals(other.prefix)) return false; if (regNo == null) { if (other.regNo != null) return false; } else if (!regNo.equals(other.regNo)) return false; if (version != other.version) return false; return true; } }
Java
UTF-8
7,728
2.15625
2
[]
no_license
/** * * @author Miriam */ package cat.xtec.ioc.ctrlr; import cat.xtec.ioc.domini.Familiar; import cat.xtec.ioc.domini.Model; import cat.xtec.ioc.servei.ModelService; import cat.xtec.ioc.servei.OptionsService; import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.MatrixVariable; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @Controller public class ConcessionariController { @Autowired private OptionsService optionsService; @Autowired private ModelService modelService; @RequestMapping(value = "/", method = RequestMethod.GET) public ModelAndView homeRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ModelAndView modelView = new ModelAndView("home"); modelView.getModelMap().addAttribute("banner", "Programa de Gestió del Concessionari!"); modelView.getModelMap().addAttribute("tagline", ""); modelView.getModelMap().addAttribute("options", optionsService.getOptionsInici()); return modelView; } @RequestMapping(value = "/add", method = RequestMethod.GET) public ModelAndView addModelRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ModelAndView modelView = new ModelAndView("home"); modelView.getModelMap().addAttribute("banner", "Programa de Gestió del Concessionari!"); modelView.getModelMap().addAttribute("tagline", ""); modelView.getModelMap().addAttribute("options", optionsService.getOptionsAdd()); return modelView; } @RequestMapping(value = "/get", method = RequestMethod.GET) public ModelAndView getModelFormRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ModelAndView modelView = new ModelAndView("getModelForm"); modelView.getModelMap().addAttribute("banner", "Programa de Gestió del Concessionari!"); return modelView; } @RequestMapping(value = "/get", method = RequestMethod.POST) public ModelAndView getModelByCodiRequest(@RequestParam("codi") String codi, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String codiModel = (String) request.getParameter("codi"); ModelAndView modelView = new ModelAndView("infoModel"); modelView.getModelMap().addAttribute("banner", "Programa de Gestió del Concessionari!"); modelView.getModelMap().addAttribute("tagline", "Dades d'un model de cotxe"); modelView.getModelMap().addAttribute("r", modelService.getModelByCodi(codiModel)); return modelView; } @RequestMapping(value = "/filter", method = RequestMethod.GET) public ModelAndView getModelByFilter(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ModelAndView modelView = new ModelAndView("helpFilter"); modelView.getModelMap().addAttribute("banner", "Programa de Gestió del Concessionari!"); modelView.getModelMap().addAttribute("tagline", "Ajuda per la creació d'un filtre"); return modelView; } @RequestMapping(value = "/filter/{ByCriteria}", method = RequestMethod.GET) public ModelAndView getModelByFilter(@MatrixVariable(pathVar = "ByCriteria") Map<String, List<String>> filterParams, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ModelAndView modelView = new ModelAndView("listModelByFilter"); modelView.getModelMap().addAttribute("banner", "Programa de Gestió del Concessionari!"); modelView.getModelMap().addAttribute("tagline", "Llistat de Models de cotxe que compleixen els requisits"); modelView.getModelMap().addAttribute("model", modelService.getModelByFilter(filterParams)); return modelView; } @RequestMapping(value = "/budget", method = RequestMethod.GET) public ModelAndView getPressupost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ModelAndView modelView = new ModelAndView("helpPressupost"); modelView.getModelMap().addAttribute("banner", "Programa de Gestió del Concessionari!"); modelView.getModelMap().addAttribute("tagline", "Ajuda per la creació d'un pressupost"); return modelView; } @RequestMapping(value = "/getModel/{codi}", method = RequestMethod.GET) public ModelAndView getModelByCodiPressupostRequest(@PathVariable("codi") String codi, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ModelAndView modelView = new ModelAndView("infoModel"); modelView.getModelMap().addAttribute("banner", "Programa de Gestió del Concessionari!"); modelView.getModelMap().addAttribute("tagline", "Dades d'un model de cotxe"); modelView.getModelMap().addAttribute("r", modelService.getModelByCodi(codi)); return modelView; } @RequestMapping(value = "/add/{tipus}", method = RequestMethod.GET) public ModelAndView addModelForm(@PathVariable("tipus") String tipus, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ModelAndView modelView = new ModelAndView("add" + tipus); modelView.getModelMap().addAttribute("banner", "Programa de Gestió del Concessionari!"); modelView.getModelMap().addAttribute("tagline", "Afegir un model de tipus " + tipus); try { modelView.getModelMap().addAttribute("newModel", Class.forName("cat.xtec.ioc.domini." + tipus).newInstance()); } catch (Exception e) { } return modelView; } @RequestMapping(value = "/add/{tipus}", method = RequestMethod.POST) public String addModelForm(@PathVariable("tipus") String tipus, @ModelAttribute("newModel") Model newModelToAdd, BindingResult result) { /*el Model passat per parametre ha perdut la identitat i no es compleix el instanceof per lo que alhora de fer un filtre per classe no apareixerà si que d'afegeix al cataleg i es pot cercar per codi i fer un pressupost */ /*if (newModelToAdd instanceof Familiar) { System.out.println("FAMILIAR"); }*/ String[] suppressedFields = result.getSuppressedFields(); if (suppressedFields.length > 0) { throw new RuntimeException("Attempting to bind disallowed fields: " + StringUtils.arrayToCommaDelimitedString(suppressedFields)); } modelService.addModel(newModelToAdd); return "redirect:/"; } @InitBinder public void initialiseBinder(WebDataBinder binder) { binder.setDisallowedFields("numPressupost"); } }
JavaScript
UTF-8
999
4.125
4
[]
no_license
// 605. 种花问题 // 假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。 // 给你一个整数数组 flowerbed 表示花坛,由若干 0 和 1 组成,其中 0 表示没种植花,1 表示种植了花。另有一个数 n , // 能否在不打破种植规则的情况下种入 n 朵花?能则返回 true ,不能则返回 false。 // 示例 1: // 输入:flowerbed = [1,0,0,0,1], n = 1 // 输出:true // 示例 2: // 输入:flowerbed = [1,0,0,0,1], n = 2 // 输出:false function canPlaceFlowers(flowerbed, n) { let num = 0 flowerbed.unshift(0) flowerbed.push(0) for (let i = 1; i < flowerbed.length - 1; i++) { if ( flowerbed[i - 1] === flowerbed[i] && flowerbed[i] === flowerbed[i + 1] ) { num += 1 flowerbed[i] += 1 } } return num >= n } console.log(canPlaceFlowers([1, 0, 0, 0, 0, 1], 2))
Python
UTF-8
1,897
2.65625
3
[ "Apache-2.0" ]
permissive
from django.test import TestCase class TestCreateAccount(TestCase): def testcase_create_account(self): customer_id = 'customer1' from wallet.models import Account account_details = Account.create_account(customer_id) self.assertEquals(account_details['customer_id'], customer_id, 'Issue with customer_id') self.assertNotEqual(account_details['account_id'], None, 'Issue with account_id') def testcase_create_multiple_accounts_for_different_users(self): customer_id_1 = 'customer1' customer_id_2 = 'customer2' from wallet.models import Account account_details_1 = Account.create_account(customer_id_1) account_details_2 = Account.create_account(customer_id_2) self.assertEquals(account_details_1['customer_id'], customer_id_1, 'Issue with customer_id') self.assertEquals(account_details_2['customer_id'], customer_id_2, 'Issue with customer_id') self.assertNotEqual(account_details_1['account_id'], account_details_2['account_id']) def testcase_multiple_accounts_for_same_user(self): customer_id = 'customer1' from wallet.models import Account Account.create_account(customer_id) self.assertRaises(Exception, lambda: Account.create_account(customer_id)) def testcase_joint_account_holder(self): customer_id_1 = 'customer1' customer_id_2 = 'customer2' from wallet.models import Account account_id = '200802022' Account._assign_account_id_to_customer(account_id=account_id, customer_id=customer_id_1) self.assertRaises(Exception, lambda: Account._assign_account_id_to_customer(account_id=account_id, customer_id=customer_id_2))
Markdown
UTF-8
2,102
2.890625
3
[]
no_license
Profit maximization from LendingClub investment. From Wikipedia: “LendingClub is a US peer-to-peer lending company, headquartered in San Francisco, California.[3] It was the first peer-to-peer lender to register its offerings as securities with the Securities and Exchange Commission (SEC), and to offer loan trading on a secondary market. LendingClub is the world's largest peer-to-peer lending platform.” Lending Club is a company that matches borrowers who are looking for a loan and investors who lend money and make a profit from return. Borrower submit an application, providing necessary info, like loan amount, employment info, financial history, loan purpose and etc.. Lending Club evaluates borrower’s credit report information and assigns an interest rate to the loan. Approved loans are listed on the Lending Club website. Then investors can select recently approved loans. My Goal: I will build a model that will predict if a borrower will pay back his/her loan or not based on historical data from Lending Club? As an investor, I would like to maximize my profit selecting loans that will give me the maximum profit. LendingClub DataSet from Kaggle: https://www.kaggle.com/wordsforthewise/lending-club I decided to collect only loans from 2018 since we need to use most current data for loan prediction. After preprocessing and normalizing data, I came up with 87 features . This dataset is highly imbalanced: Positive: 96.52% Negative 3.48% We have small fraction of negative samples. We want to have the classifier heavily weight the negative examples. You do this by passing Keras weights for every class through a parameter. These will push the model to "pay attention" to samples from an underrepresented class. I tried to play with different number of layers and different hyperparameters. The best accuracy(72% ) using 3 hidden layers. My own model. Resampling using SMOTE did not improve accuracy. Keras Tuner: BayesianOptimization found best result with 76% accuracy. TensorBoard link: https://tensorboard.dev/experiment/IZqUohVfRm6DFjVV39O4lw/
PHP
UTF-8
4,131
3.015625
3
[]
no_license
<?php /** * @namespace */ namespace Fw\Mvc; use Fw\Library\Arrayable; /** * Class Model */ abstract class Model implements Arrayable, \JsonSerializable { /** * @var string|array Name the primary key field */ protected static $primaryKey; /** * @var array */ private static $reservedProperties = [ 'reservedProperties', 'primaryKey', 'isSaved', ]; /** * @var bool True if the record taken from the storage */ private $isSaved = false; /** * Property isSaved establishes the true * * @return self */ private function setIsSaved() { $this->isSaved = true; return $this; } /** * True if the record taken from the storage * * @return bool */ public function isSaved() { return $this->isSaved; } /** * @param array|string $properties * @return self */ protected function appendReservedProperties($properties) { self::$reservedProperties = array_merge(self::$reservedProperties, (array) $properties); return $this; } /** * @return array */ public function getReservedProperties() { return self::$reservedProperties; } /** * @return array */ public function getAffordableProperties() { $reservedProperties = $this->getReservedProperties(); $allProperties = array_keys(get_object_vars($this)); return array_values(array_diff($allProperties, $reservedProperties)); } /** * @param string $property * @param mixed $value * @return self */ public function setProperty($property, $value = null) { $properties = $this->getAffordableProperties(); if (in_array($property, $properties)) { $this->$property = $value; } return $this; } /** * @param array $data * @return self */ public function setProperties(array $data) { $properties = $this->getAffordableProperties(); foreach ($properties as $property) { $value = null; if (isset($data[$property])) { $value = $data[$property]; } $this->$property = $value; } return $this; } /** * Finds record by primary key * * @param mixed $pkValue * @return self */ public static function findByPk($pkValue) { $data = self::executeQuery(static::$primaryKey, $pkValue); if (!$data) { return null; } return (new static()) ->setIsSaved() ->setProperties($data); } /** * Execute query to the data store * * @param array|string * @param array|mixed * @return array */ private static function executeQuery($fields, $values) { $data = [ 'App\Model\User' => [ 'id' => [ '1' => [ 'id' => '1', 'firstname' => 'Zeev', 'lastname' => 'Surasky', 'age' => '42', ], ], ], ]; $modelName = get_called_class(); $keyForFind = implode('_', (array) $fields); $valueForFind = implode('_', (array) $values); if (isset($data[$modelName][$keyForFind][$valueForFind])) { return $data[$modelName][$keyForFind][$valueForFind]; } return null; } /** * Implements the Arrayable interface * * @return array */ public function toArray() { $data = []; $properties = $this->getAffordableProperties(); foreach ($properties as $property) { $data[$property] = $this->$property; } return $data; } /** * Implements the JsonSerializable interface * * @return array */ public function JsonSerialize() { return $this->toArray(); } }
Java
UTF-8
7,529
2.171875
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. */ /** * * @author gizachew */ /* * 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 Entities; import java.io.Serializable; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.validation.constraints.Pattern; @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn (name="disc",discriminatorType = DiscriminatorType.STRING) @DiscriminatorValue("account") @NamedQueries({ @NamedQuery(name = "Account.findByemail", query = "SELECT a FROM Account a WHERE a.email = :email") // @NamedQuery(name = "Account.disc", // query = "SELECT a.DISC FROM Account a WHERE a.email = :email") }) public class Account implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String fname; private String lname; @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\." +"[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@" +"(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="{invalid.email}") private String email; @Pattern(regexp = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message = "{invalid.phonenumber}") protected String phone; private String password; private String street; private String city; private String state; private String zip; public Account() { } public Account(String fname, String lname, String email, String phone, String password, String street, String city, String state, String zip) { this.fname = fname; this.lname = lname; this.email = email; this.password = password; this.phone = phone; this.street = street; this.city = city; this.state = state; this.zip = zip; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } public String getLname() { return lname; } public void setLname(String lname) { this.lname = lname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Account)) { return false; } Account other = (Account) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "Entities.Account[ id=" + id + " ]"; } } /* @Entity @Table(name="Account") @Inheritance(strategy=SINGLE_TABLE) @DiscriminatorColumn(name="Account_TYPE") public class Account implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String account_Type; private String full_name; private String phone_NO; private String city; private String state; private String zipCode; private String email_address; private String password; public String getAccount_Type() { return account_Type; } public void setAccount_Type(String account_Type) { this.account_Type = account_Type; } public String getFull_name() { return full_name; } public void setFull_name(String full_name) { this.full_name = full_name; } public String getPhone_NO() { return phone_NO; } public void setPhone_NO(String phone_NO) { this.phone_NO = phone_NO; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getEmail_address() { return email_address; } public void setEmail_address(String email_address) { this.email_address = email_address; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Account)) { return false; } Account other = (Account) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "Entities.Account[ id=" + id + " ]"; } } */
C
UTF-8
589
3.078125
3
[ "Unlicense" ]
permissive
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <fcntl.h> int main(){ char buf[BUFSIZ]; // BUFSIZ to makro z stdio.h zwracajace optymalny rozmiar bufora (na solarisach 1024) (wielkosc bloku dyskowego w systemie) int fp; int nread; if((fp=open("fifo",O_WRONLY))==-1){ perror("open fifo"); exit(1); } for(;;){ if((nread=read(0,buf,BUFSIZ))==-1){ perror("read"); exit(1); } if(nread<BUFSIZ) buf[nread]='\0'; // ustawia koniec bufora zeby nam nie drukowalo krzakow write(fp,buf,BUFSIZ); } }
JavaScript
UTF-8
6,962
2.59375
3
[]
no_license
// React var React = require('react') var ReactDOM = require('react-dom') // Google Maps var ReactGMaps = require('react-gmaps') var {Gmaps, Marker,InfoWindow} = ReactGMaps // Movie data var movieData = require('./data/movies.json') var theatres = require('./data/theatres.json') // Components var Header = require('./components/Header') var MovieDetails = require('./components/MovieDetails') var MovieList = require('./components/MovieList') var NoCurrentMovie = require('./components/NoCurrentMovie') var SortBar = require('./components/SortBar') // There should really be some JSON-formatted data in movies.json, instead of an empty array. // I started writing this command to extract the data from the learn-sql workspace // on C9, but it's not done yet :) You must have the csvtojson command installed on your // C9 workspace for this to work. // npm install -g csvtojson // sqlite3 -csv -header movies.sqlite3 'select "imdbID" as id, "title" from movies' | csvtojson --maxRowLength=0 > movies.json // Firebase configuration var Rebase = require('re-base') var base = Rebase.createClass({ apiKey: "AIzaSyA_Kb7vGfcxj5k2qYW2vwlHtkQGJbjtULs", // replace with your Firebase application's API key databaseURL: "https://final-6928c.firebaseio.com", // replace with your Firebase application's database URL }) var App = React.createClass({ movieClicked: function(movie) { this.setState({ currentMovie: movie }) }, movieWatched: function(movie) { var existingMovies = this.state.movies var moviesWithWatchedMovieRemoved = existingMovies.filter(function(existingMovie) { return existingMovie.id !== movie.id }) this.setState({ movies: moviesWithWatchedMovieRemoved, currentMovie: null }) }, sortMovieList: function(view,moviesList) { var moviesSort if(view === 'latest') { moviesSort = moviesList.sort(this.movieCompareByReleased) } else //alpha { moviesSort = moviesList.sort(this.movieCompareByTitle) } this.setState({ movies: moviesSort, currentView: view }) }, resetMovieListClicked: function() { this.sortMovieList(this.state.currentView,movieData) }, viewChanged: function(view) { // View is either "latest" (movies sorted by release), "alpha" (movies // sorted A-Z), or "map" (the data visualized) // We should probably do the sorting and setting of movies in state here. // You should really look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort this.sortMovieList(view,this.state.movies) /*this.setState({ currentView: view }) */ }, renderMovieDetails: function() { if (this.state.currentMovie == null) { return <NoCurrentMovie resetMovieListClicked={this.resetMovieListClicked} /> } else { return <MovieDetails movie={this.state.currentMovie} movieWatched={this.movieWatched} /> } }, onMapCreated: function(map) { map.setOptions({ disableDefaultUI: true }); }, toggleInfoWindow: function(data) { console.log('toggleInfoWindow: '+data) var infoWindows if(data == null) { infoWindows = null } else { infoWindows = {lat:data.lat ,long: data.long,content:data.content} } this.setState({ currentInfoWindows: infoWindows }) }, renderInfoWindows: function() { console.log('renderInfoWindows') var currentInfo = this.state.currentInfoWindows if(currentInfo != null) { return (<InfoWindow lat={currentInfo.lat} lng={currentInfo.long} content={currentInfo.content} onCloseClick={() => this.toggleInfoWindow(null)} /> ) } else { return "" } }, renderMarkers: function() { var this2 = this; return theatres.map( function(theatre, index) { var data={lat: theatre.lat, long: theatre.long, content:theatre.name} return (<Marker key={index} lat={theatre.lat} lng={theatre.long} onClick={() => this2.toggleInfoWindow(data)} /> ) }) }, renderMainSection: function() { // https://gist.github.com/MicheleBertoli/cdd3960f608574e49e24 if (this.state.currentView === 'map') { var currentInfo = this.state.currentInfoWindows if(currentInfo == null) { currentInfo = theatres[0] } return ( <div className="col-sm-12"> <h3>Map of movie theaters where to watch good movies</h3> <Gmaps width={'700px'} height={'500px'} lat={currentInfo.lat} lng={currentInfo.long} zoom={12} loadingMessage={'movie theaters'} params={{v: '3.exp'}} onMapCreated={this.onMapCreated} ref="gmaps" > {this.renderMarkers()} {this.renderInfoWindows()} </Gmaps> </div> ) } else { return ( <div> <MovieList movies={this.state.movies} movieClicked={this.movieClicked} /> {this.renderMovieDetails()} </div> ) } }, movieCompareByTitle: function(movieA, movieB) { if (movieA.title < movieB.title) { return -1 } else if (movieA.title > movieB.title) { return 1 } else { return 0 } }, movieCompareByReleased: function(movieA, movieB) { if (movieA.released > movieB.released) { return -1 } else if (movieA.released < movieB.released) { return 1 } else { return 0 } }, getInitialState: function() { return { movies: movieData.sort(this.movieCompareByReleased), currentMovie: null, currentView: 'latest', currentInfoWindows: null } }, componentDidMount: function() { // We'll need to enter our Firebase configuration at the top of this file and // un-comment this to make the Firebase database work base.syncState('/movies', { context: this, state: 'movies', asArray: true }) }, render: function() { return ( <div> <Header currentUser={this.state.currentUser} /> <SortBar movieCount={this.state.movies.length} viewChanged={this.viewChanged} currentView={this.state.currentView} /> <div className="main row"> {this.renderMainSection()} </div> </div> ) } }) ReactDOM.render(<App />, document.getElementById("app"))
Java
UTF-8
1,600
2.53125
3
[]
no_license
package com.powerdata.openpa.psse; public abstract class SwitchList extends PsseBaseList<Switch> { public static final SwitchList Empty = new SwitchList() { @Override public Bus getFromBus(int ndx) {return null;} @Override public Bus getToBus(int ndx) {return null;} @Override public String getObjectID(int ndx) {return null;} @Override public int size() {return 0;} @Override public long getKey(int ndx) {return -1;} }; protected SwitchList(){super();} public SwitchList(PsseModel model) {super(model);} /** Get a Switch by it's index. */ @Override public Switch get(int ndx) { return new Switch(ndx,this); } /** Get an SwitchIn by it's ID. */ @Override public Switch get(String id) { return super.get(id); } public abstract Bus getFromBus(int ndx) throws PsseModelException; public abstract Bus getToBus(int ndx) throws PsseModelException; @Deprecated // use getObjectName, this is redundant public String getName(int ndx) throws PsseModelException {return "";} public SwitchState getState(int ndx) throws PsseModelException {return SwitchState.Closed;} public void setState(int ndx, SwitchState state) throws PsseModelException {} public boolean canOperateUnderLoad(int ndx) throws PsseModelException {return true; } public String getI(int ndx) throws PsseModelException {return getFromBus(ndx).getObjectID();} public String getJ(int ndx) throws PsseModelException {return getToBus(ndx).getObjectID();} public boolean isInSvc(int ndx) throws PsseModelException {return true;} public void setInSvc(int ndx, boolean state) throws PsseModelException {} }
Java
UTF-8
1,203
2.203125
2
[]
no_license
package com.test.firstAutoamtionFramework.ulTestingAutomation.homePage; import org.apache.log4j.Logger; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.test.firstAutoamtionFramework.ulTestingAutomation.testBase.TestBase; import com.test.firstAutoamtionFramework.ulTestingAutomation.uiActions.Homepage; public class TC001_VerifyLoginWithInvalidCredentials extends TestBase { public static final Logger log = Logger.getLogger(TC001_VerifyLoginWithInvalidCredentials.class.getName()); Homepage homepage; @BeforeTest public void setUp() { init(); } @Test public void verifyLoginWithInvalidCredentials() { log.info("********************Starting VerifyLoginWithInvalidCredentials test*******************"); homepage = new Homepage(driver); homepage.loginToApplication("test@automation.com", "password123"); Assert.assertEquals(homepage.getInvalidLoginText(), "Authentication failed."); log.info("********************Ending VerifyLoginWithInvalidCredentials test*******************"); } @AfterClass public void endTest() { driver.close(); } }
C++
UTF-8
1,034
2.5625
3
[]
no_license
#include <RcppEigen.h> #include <Eigen/Dense> #include <Eigen/Cholesky> #include <cmath> #include <valarray> #include <iostream> #include "covNonSep.h" using namespace Eigen; using namespace Rcpp; //' @export // [[Rcpp::depends(RcppEigen)]] // [[Rcpp::export]] Eigen::MatrixXd covNonSep(const Eigen::MatrixXd DS, const Eigen::MatrixXd DT, double c, double thetas, double thetat ){ int P = DS.rows(); Eigen::MatrixXd psi = (( (1-c) / (thetat*(DT.array()).pow(2) + 1) ).cwiseProduct( (- thetas*DS.array().pow(2) / (thetat*(DT.array()).pow(2) + 1 ) ).exp())).matrix(); psi.diagonal() = Eigen::VectorXd(P).setOnes(); return(psi); } /*** R # tests theta0 = c(0.2,0.3,0.4) P = 6 loctim = cbind(sx = c(1:6), sy = c(1:6), t = c(1:6)) DS = as.matrix(dist(loctim[,-3])) DT = as.matrix(dist(loctim[,3]),p=1) test <- covNonSep(DS, DT, theta0[1],theta0[2],theta0[3]) testR = (1-theta0[1])/(theta0[3]*(P*DT)^2+1)*exp(-theta0[2]*DS^2/(theta0[3]*(P*DT)^2+1)) diag(testR) = 1 sum(test != testR) */
Java
UTF-8
6,815
1.796875
2
[]
no_license
package views.core.soap_web_services; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for ActivityModel complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ActivityModel"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="activity_lavel" type="{soap_web_services.core.views}ActivityModel_activity_lavelType" minOccurs="0"/> * &lt;element name="end_date" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/> * &lt;element name="start_date" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/> * &lt;element name="patient_id" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="is_violated" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="is_normal" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ActivityModel", propOrder = { "id", "activityLavel", "endDate", "startDate", "patientId", "isViolated", "isNormal" }) public class ActivityModel { protected Long id; @XmlElementRef(name = "activity_lavel", namespace = "soap_web_services.core.views", type = JAXBElement.class, required = false) protected JAXBElement<String> activityLavel; @XmlElementRef(name = "end_date", namespace = "soap_web_services.core.views", type = JAXBElement.class, required = false) protected JAXBElement<XMLGregorianCalendar> endDate; @XmlElementRef(name = "start_date", namespace = "soap_web_services.core.views", type = JAXBElement.class, required = false) protected JAXBElement<XMLGregorianCalendar> startDate; @XmlElementRef(name = "patient_id", namespace = "soap_web_services.core.views", type = JAXBElement.class, required = false) protected JAXBElement<Long> patientId; @XmlElementRef(name = "is_violated", namespace = "soap_web_services.core.views", type = JAXBElement.class, required = false) protected JAXBElement<Boolean> isViolated; @XmlElementRef(name = "is_normal", namespace = "soap_web_services.core.views", type = JAXBElement.class, required = false) protected JAXBElement<Boolean> isNormal; /** * Gets the value of the id property. * * @return * possible object is * {@link Long } * */ public Long getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link Long } * */ public void setId(Long value) { this.id = value; } /** * Gets the value of the activityLavel property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getActivityLavel() { return activityLavel; } /** * Sets the value of the activityLavel property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setActivityLavel(JAXBElement<String> value) { this.activityLavel = value; } /** * Gets the value of the endDate property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public JAXBElement<XMLGregorianCalendar> getEndDate() { return endDate; } /** * Sets the value of the endDate property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public void setEndDate(JAXBElement<XMLGregorianCalendar> value) { this.endDate = value; } /** * Gets the value of the startDate property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public JAXBElement<XMLGregorianCalendar> getStartDate() { return startDate; } /** * Sets the value of the startDate property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public void setStartDate(JAXBElement<XMLGregorianCalendar> value) { this.startDate = value; } /** * Gets the value of the patientId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public JAXBElement<Long> getPatientId() { return patientId; } /** * Sets the value of the patientId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public void setPatientId(JAXBElement<Long> value) { this.patientId = value; } /** * Gets the value of the isViolated property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Boolean }{@code >} * */ public JAXBElement<Boolean> getIsViolated() { return isViolated; } /** * Sets the value of the isViolated property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Boolean }{@code >} * */ public void setIsViolated(JAXBElement<Boolean> value) { this.isViolated = value; } /** * Gets the value of the isNormal property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Boolean }{@code >} * */ public JAXBElement<Boolean> getIsNormal() { return isNormal; } /** * Sets the value of the isNormal property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Boolean }{@code >} * */ public void setIsNormal(JAXBElement<Boolean> value) { this.isNormal = value; } }
Java
UTF-8
4,569
2.265625
2
[]
no_license
package com.ljtao3.service; import com.google.common.base.Preconditions; import com.ljtao3.common.MyRequestHolder; import com.ljtao3.dao.SysDeptMapper; import com.ljtao3.dao.SysUserMapper; import com.ljtao3.exception.ParamException; import com.ljtao3.model.SysDept; import com.ljtao3.param.DeptParam; import com.ljtao3.util.IpUtil; import com.ljtao3.util.LevelUtils; import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Date; import java.util.List; @Service public class SysDeptService { @Resource private SysDeptMapper sysDeptMapper; @Resource private SysUserMapper sysUserMapper; @Resource private SysLogService sysLogService; public void save(DeptParam param){ if(checkExist(param.getParentId(),param.getName(),param.getId())){ throw new ParamException("同一层级下存在相同名称的部门!"); } SysDept dept=SysDept.builder().name(param.getName()).parentId(param.getParentId()) .seq(param.getSeq()).remark(param.getRemark()).build(); dept.setLevel(LevelUtils.calculateLevel(getLevel(param.getParentId()),param.getParentId())); dept.setOperator(MyRequestHolder.getCurrentUser().getUsername()); dept.setOperateIp(IpUtil.getRemoteIp(MyRequestHolder.getCurrentRequest())); dept.setOperateTime(new Date()); sysDeptMapper.insertSelective(dept); sysLogService.saveDeptLog(null,dept); } public void update(DeptParam param) { SysDept before=sysDeptMapper.selectByPrimaryKey(param.getId()); Preconditions.checkNotNull(before,"待更新的部门不存在"); if(checkExist(param.getParentId(),param.getName(),param.getId())){ throw new ParamException("同一层级下存在相同名称的部门!"); } SysDept after=SysDept.builder().id(param.getId()).name(param.getName()).parentId(param.getParentId()) .seq(param.getSeq()).remark(param.getRemark()).build(); after.setLevel(LevelUtils.calculateLevel(getLevel(param.getParentId()),param.getParentId())); after.setOperator(MyRequestHolder.getCurrentUser().getUsername()); after.setOperateTime(new Date()); after.setOperateIp(IpUtil.getRemoteIp(MyRequestHolder.getCurrentRequest())); updateWithChild(before,after); sysLogService.saveDeptLog(before,after); } /* 字符串 0.1% 去查询 0.1以下的所有子部门 */ @Transactional public void updateWithChild(SysDept before,SysDept after ){ //List<SysDept> childDeptListByLevel = sysDeptMapper.getChildDeptListByLevel("0"); String newLevelPrefix=after.getLevel(); String oldLevelPrefix=before.getLevel(); if(!newLevelPrefix.equals(oldLevelPrefix)){ List<SysDept> childDeptListByLevel = sysDeptMapper.getChildDeptListByLevel(LevelUtils.calculateLevel(oldLevelPrefix,before.getId())); if(CollectionUtils.isNotEmpty(childDeptListByLevel)){ for(SysDept dept:childDeptListByLevel){ //拼接成一个新的层级 // 原0.1 , 0.1.6 --> 0.1.7 , 0.1.7.6 dept.setLevel(newLevelPrefix+dept.getLevel().substring(oldLevelPrefix.length())); } sysDeptMapper.batchUpdateLevel(childDeptListByLevel); } } sysDeptMapper.updateByPrimaryKeySelective(after); } private boolean checkExist(Integer parentId,String deptName,Integer deptId){ return sysDeptMapper.countByIdAndNameAndParentId(deptId,deptName,parentId)>0; } private String getLevel(Integer deptId){ SysDept dept=sysDeptMapper.selectByPrimaryKey(deptId); if(dept==null){ return null; } return dept.getLevel(); } public void deleteById(Integer deptId) { SysDept sysDept=sysDeptMapper.selectByPrimaryKey(deptId); Preconditions.checkNotNull(sysDept,"待删除的部门不存在!"); if(sysDeptMapper.countByParentId(sysDept.getId())>0){ throw new ParamException("该部门存在子部门,无法删除!"); } if(sysUserMapper.countByDeptId(deptId)>0){ throw new ParamException("该部门下存在用户,无法删除!"); } System.out.println("执行删除:"+deptId); //sysDeptMapper.deleteByPrimaryKey(deptId); } }
JavaScript
UTF-8
36,967
2.828125
3
[]
no_license
<!-- var alertError; // 放到网上的时候可以禁止别的页面调用,但是在本地测试的时候要先注销掉 /* var arrHost = window.location.host.split ( '.' ); var domain = arrHost[arrHost.length - 2] + '.' + arrHost[arrHost.length - 1]; if ( document.domain != domain ) { document.domain = domain; } */ /* window.onerror = handle_error; function handle_error ( e, uri, ln ) { // alert ( "Error: " + e + "\nURL: " + uri + "\nLine: " + ln ); return true; } */ function $ ( objId ) { return document.getElementById ( objId ); } // 保存 Cookie function setCookie ( name, value ) { expires = new Date(); expires.setTime(expires.getTime() + (1000 * 86400 * 365)); document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() + "; path=/"; } // 获取 Cookie function getCookie ( name ) { cookie_name = name + "="; cookie_length = document.cookie.length; cookie_begin = 0; while (cookie_begin < cookie_length) { value_begin = cookie_begin + cookie_name.length; if (document.cookie.substring(cookie_begin, value_begin) == cookie_name) { var value_end = document.cookie.indexOf ( ";", value_begin); if (value_end == -1) { value_end = cookie_length; } return unescape(document.cookie.substring(value_begin, value_end)); } cookie_begin = document.cookie.indexOf ( " ", cookie_begin) + 1; if (cookie_begin == 0) { break; } } return null; } // 清除 Cookie function delCookie ( name ) { var expireNow = new Date(); document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT" + "; path=/"; } // 获取 URL 变量 //queryVar 正则表达式变量 function getURLVar ( queryVar, url ) { var url = url == null ? window.location.href : url; var re = new RegExp ( ".*[\?|&]" + queryVar + "=([^&#]+).*", "g" ); if ( url.match ( re ) ) { var queryVal = url.replace ( re, "$1" ); return queryVal; } return ''; } // 获取当前域名 function getURLHost ( url ) { if ( url == null ) { return window.location.host; } var re = new RegExp ( "([^\/]*)\/\/([^\/]*)\/.*", "g" ); if ( url.match ( re ) ) { var urlHost = url.replace ( re, "$1//$2" ); return urlHost; } return ''; } function setSelectOptions ( the_form, the_select, do_check ) { var selectObject = document.forms[the_form].elements[the_select]; var selectCount = selectObject.length; for (var i = 0; i < selectCount; i++) { selectObject.options[i].selected = do_check; } return true; } function setChecked ( val, obj, name ) { len = obj.elements.length; var i=0; for( i=0 ; i<len ; i ++ ) { if ( obj.elements[i].name == name ) { obj.elements[i].checked = val; } } } // 在指定对象显示信息 function showMessage ( msg, objName ) { var obj; if ( typeof (objName) == 'string' ) { obj = $ ( objName ); } else { obj = objName; } process.finish (); if ( obj ) { obj.innerHTML = msg; if ( obj.className.indexOf ( 'dialog_box' ) >= 0 ) { obj.style.zIndex = gzIndex; if ( msg.indexOf ( 'dialog.close' ) < 0 ) { appendCloseButton ( obj ); } } try { obj.focus (); obj.scrollTop = 0; } catch (e) {} } else { showDialogBox ( msg, objName, true ); } // 解析 Script execScript ( msg ); } // 添加关闭按钮 function appendCloseButton ( obj, closeScript, hideMask ) { var closeButton = document.createElement ( 'div' ); closeButton.className = 'dialog_close'; if ( hideMask == null ) hideMask = true; closeButton.onclick = function () { if ( closeScript != null ) eval ( closeScript ); dialog.close(this, hideMask);// //removeDialogBox(obj, hideMask); } closeButton.onmouseover = function () { this.style.marginTop = '1px'; } closeButton.onmouseout = function () { this.style.marginTop = '0px'; } obj.appendChild(closeButton);//closeButton } // 添加最小化按钮 function appendMiniButton ( obj, miniScript ) { var miniButton = document.createElement ( 'div' ); miniButton.className = 'dialog_mini'; miniButton.onclick = function () { var lastWidth = obj.offsetWidth; if ( obj.style.left.indexOf ( '-' ) == 0 ) obj.style.left = '0px'; if ( obj.style.top.indexOf ( '-' ) == 0 ) obj.style.top = '0px'; if ( miniScript != null ) eval ( miniScript ); } miniButton.onmouseover = function () { this.style.marginTop = '1px'; } miniButton.onmouseout = function () { this.style.marginTop = '0px'; } obj.appendChild ( miniButton ); } // 解析 Script function execScript ( msg ) { var _re = /<script[^>]*>([^\x00]+)$/i var _msgs = msg.split ( "<\/script>" ); for ( var _i in _msgs ) { var _strScript; if ( _strScript = _msgs[_i].match ( _re ) ) { var _strEval = _strScript[1].replace ( /<!--/, '' ); try { eval ( _strEval ); } catch (e) {} } } } // 移除对话框 function removeDialogBox ( objName, hideMask ) { if ( objName == null ) { objName = 'dialog_box' + mask.maskIndex; } if ( hideMask == null ) hideMask = true; if ( hideMask ) mask.hide (); removeItems ( objName ); gzIndex --; } // 移除物件 function removeItems ( objName ) { var obj; objs = getObjects ( objName ); for ( var i in objs ) { try { obj = objs[i]; obj.parentNode.removeChild ( obj ); } catch (e) {} } } // 显示提示窗口 var gzIndex = 999; function showDialogBox ( msg, objId, noClose, title ) { var objClass = 'dialog_box'; if(title==null)title="XBA" if ( objId == null ) { objId = objClass + mask.maskIndex; } var msgBox = document.getElementById ( objId ); if ( msgBox ) { msgBox.parentNode.removeChild ( msgBox ); mask.hide (); } if ( msg != '' ) mask.show (); msgBox = document.createElement ( 'div' ); msgBox.id = objId; msgBox.className = objClass; document.body.appendChild ( msgBox ); msgBox.style.zIndex = gzIndex ++; var strDiv = ""; strDiv+="<table width=\"400\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" id=\"floatmain\">" +"<tr><td>" +"<table border=\"0\" width=\"99.5%\" cellspacing=\"0\" cellpadding=\"0\" id=\"floatborder\">" //+"<tr><td id=\"floatop\">"+title+"</td></tr>" +"<tr><td id=\"floatcontent\">"+msg+"</td></tr>" +"</table>" +"</td></tr>" +"</table>"; msgBox.innerHTML = strDiv; if ( noClose == null ) noClose = false; if ( !noClose && msg.indexOf ( 'dialog.close' ) < 0 ) { appendCloseButton( msgBox ); } centerDiv ( msgBox ); } // 显示帮助窗口 function showHelpBox ( msg, objId, title, posTop ) { var objClass = 'dialog_box_help'; if ( objId == null ) objId = 'helpDialog'; if ( title == null ) title = '足球经理手册'; var contentId = objId + 'Content'; var msgBox = $ ( objId ); if ( !msgBox ) { msgBox = document.createElement ( 'div' ); msgBox.id = objId; msgBox.className = objClass; if ( posTop != null ) { msgBox.style.top = posTop + 'px'; } document.body.appendChild ( msgBox ); if ( document.all ) { var showHideScript = 'var obj = $(\"' + contentId + '\"); if ( obj.style.display != \"none\" ) { obj.style.display = \"none\"; } else { obj.style.display = \"\"; }'; } else { var showHideScript = 'var obj = $(\"' + contentId + '\"); if ( obj.style.visibility != \"hidden\" ) { obj.style.width = \"0px\"; obj.style.height = \"0px\"; obj.style.visibility = \"hidden\"; } else { obj.style.width = \"auto\"; obj.style.height = \"auto\"; obj.style.visibility = \"visible\"; }'; } msgBox.innerHTML = "<div class='title' onmousedown='setDragObj (\"" + objId + "\", 1);'>" + title + "</div><div id='" + contentId + "' class='content' style='visibility:'>" + msg + "</div>"; appendMiniButton ( msgBox, showHideScript ); appendCloseButton ( msgBox, null, false ); } else { var objContent = $ ( contentId ); if ( document.all ) { objContent.style.display = ''; } else { objContent.style.visibility = 'visible'; objContent.style.width = 'auto'; objContent.style.height = 'auto'; } } msgBox.style.zIndex = gzIndex ++; } // 字数限制函数 function lengthLimit ( obj, Limit, objShow, objAlert ) { var Len = obj.value.replace(/([^\x00-\xff])/g,"EE").length; if ( Len > Limit ) { //obj.value = obj.value.substring ( 0, Limit ); Len = Limit; showMessage ( String.sprintf ( "字数超出限制, 最多 %d 字!", Limit ), objAlert ); } if ( objShow = document.getElementById ( objShow ) ) { objShow.innerHTML = Len; } } // 列表搜索 function clientSearch ( value, obj ) { if ( value != '' ) { for ( var i = obj.selectedIndex + 1; i < obj.options.length; i ++ ) { if ( obj.options[i].text.indexOf ( value, 0 ) >= 0 ) { obj.selectedIndex = i; return true; } } } obj.selectedIndex = 0; } // 列表项目移动 function moveOptions ( objFrom, objTo, errMsg, moveList ) { moveList = moveList != null ? moveList : ''; moveList = ',' + moveList + ','; if ( objFrom.selectedIndex == -1 && errMsg != null ) { alert ( errMsg ); } for ( var i = 0; i < objFrom.options.length; i ++ ) { if ( moveList.match ( ',-1,' ) || moveList.match ( ',' + objFrom.options[i].value + ',' ) || objFrom.options[i].selected ) { objTo.options.add ( new Option ( objFrom.options[i].text, objFrom.options[i].value ) ); objFrom.options[i--] = null; } } } // 设置状态栏 function setStatus ( w, id ) { window.status = w; return true; } function clearStatus () { window.status = ''; } // 显示物件 function showItem ( obj ) { if ( typeof (obj) == 'string' ) { obj = document.getElementById ( obj ); } try { obj.style.display = ''; } catch (e) {} } // 隐藏物件 function hideItem ( obj ) { if ( typeof (obj) == 'string' ) { obj = document.getElementById ( obj ); } try { obj.style.display = 'none'; } catch (e) {} } // 交替显示/隐藏物件 function itemShowHide ( obj ) { if ( typeof ( obj ) == 'string' ) { obj = document.getElementById ( obj ); } try { if ( obj.style.display != '' ) { showItem ( obj ); } else { hideItem ( obj ); } } catch (e) { } } // 获取错误信息 function getError ( string ) { var errorFlag = '<ERROR>'; if ( string.substring ( 0, errorFlag.length ) == errorFlag ) { return string.substring ( errorFlag.length, string.length ); } else { return false; } } // 根据标签获取物件 function getTag ( obj, tagName, index ) { if ( typeof ( obj ) == 'string' ) obj = $ ( obj ); var tags = obj.getElementsByTagName ( tagName ); if ( index != null ) return tags[index]; else return tags; } // Ajax 通用回调函数 function ajaxCallback ( ret, obj ) { var errorMsg = getError ( ret ); if ( errorMsg ) { if ( !window.onErrorMsg ) { window.onErrorMsg = true; showMessage ( errorMsg ); } } else if ( ret != '' ) { showMessage ( ret, obj ); } } function ajaxCallbackNo ( ret, obj ) { var errorMsg = getError ( ret ); if ( errorMsg ) { if ( !window.onErrorMsg ) { window.onErrorMsg = true; showMessage ( errorMsg ); } } else if ( ret != '' ) { showMessageNo ( ret, obj ); } } // 固定 Div function stayDiv ( obj, top, left ) { if ( typeof ( obj ) == 'string' ) { obj = document.getElementById ( obj ); } top = top != null ? top : 0; left = left != null ? left : 0; obj.style.top = top + document.documentElement.scrollTop + 'px'; obj.style.left = left + document.documentElement.scrollLeft + 'px'; setTimeout ( "stayDiv('" + obj.id + "'," + top + "," + left + ")", 100 ); } // Div 居中 function centerDiv ( obj, repeat ) { if ( typeof ( obj ) == 'string' ) { obj = document.getElementById ( obj ); } if ( obj ) { obj.style.top = '50%'; obj.style.left = '50%'; try { obj.style.marginLeft = ( - obj.scrollWidth / 2 + document.documentElement.scrollLeft ) + 'px'; obj.style.marginTop = ( - obj.scrollHeight / 2 + document.documentElement.scrollTop ) + 'px'; } catch (e) {} if ( repeat == null ) repeat = true; if ( repeat ) { setTimeout ( "centerDiv('" + obj.id + "')", 500 ); } } } // 设置背景色 function setBg ( obj, color ) { if ( typeof ( obj ) == 'string' ) { obj = document.getElementById ( obj ); } try { obj.style.backgroundColor = color; } catch (e) { } } // html 特殊字符 function htmlchars ( string ) { string = string.replace ( /\"/g, '&quot;' ); string = string.replace ( /\'/g, '&#039;' ); return string; } // 格式化输出 function sprintf () { if ( sprintf.arguments.length < 2 ) { return; } var data = sprintf.arguments[ 0 ]; for( var k=1; k<sprintf.arguments.length; ++k ) { switch( typeof( sprintf.arguments[ k ] ) ) { case 'string': data = data.replace( /%s/, sprintf.arguments[ k ] ); break; case 'number': data = data.replace( /%d/, sprintf.arguments[ k ] ); break; case 'boolean': data = data.replace( /%b/, sprintf.arguments[ k ] ? 'true' : 'false' ); break; default: break; } } return( data ); } if ( !String.sprintf ) String.sprintf = sprintf; // 图层定位 function moveDivHere ( obj, loadingMsg ) { try { if ( obj != null ) { if ( loadingMsg != null ) obj.innerHTML = loadingMsg; // 获取当前鼠标坐标 var posX = clsMouseCoords.x + 5; var posY = clsMouseCoords.y + 5; obj.style.left = posX + 'px'; obj.style.top = posY + 'px'; } } catch (e) { } } // 复制URL地址 function setCopy (_sTxt) { if ( navigator.userAgent.toLowerCase().indexOf ( 'ie' ) > -1 ) { clipboardData.setData ( 'Text', _sTxt ); alert ( '网址“' + _sTxt + '”\n已经复制到您的剪贴板中\n您可以使用Ctrl+V快捷键粘贴到需要的地方' ); } else { prompt ( '请复制网站地址:', _sTxt ); } } // 设为首页 function setHomePage ( url ) { var obj = getSrcElement (); if ( document.all ) { obj.style.behavior='url(#default#homepage)'; obj.setHomePage ( url ); } else { if ( window.netscape ) { try { netscape.security.PrivilegeManager.enablePrivilege ( "UniversalXPConnect" ); } catch (e) { alert ( "您的浏览器不支持自动设置首页,请自行手动设置。"); } } var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch); prefs.setCharPref ( 'browser.startup.homepage', url ); } } // 加入收藏 function addBookmark ( site, url ) { if ( document.all ) { window.external.addFavorite ( url, site ); } else if ( window.sidebar ) { window.sidebar.addPanel ( site, url, "" ) } else if ( navigator.userAgent.toLowerCase().indexOf ( 'opera' ) > -1 ) { alert ( '请使用 Ctrl+T 将本页加入收藏夹' ); } else { alert ( '请使用 Ctrl+D 将本页加入收藏夹' ); } } // 语言包支持 function lang () { var strInput = langPackage[lang.arguments[0]]; var strParams = ''; for( var k=1; k < lang.arguments.length; ++k ) { switch( typeof( lang.arguments[ k ] ) ) { case 'string': strParams += ", '" + lang.arguments[ k ] + "'"; break; case 'number': strParams += ", " + lang.arguments[ k ] + ""; break; } } if ( strParams != '' ) { strEval = "strOutput = String.sprintf ( strInput" + strParams + " );"; eval ( strEval ); } else { strOutput = strInput; } return ( strOutput ); } // 获取鼠标坐标 function mouseCoords () { this.x = 0; this.y = 0; this.getMouseCoords = function () { var ev = searchEvent (); try { if ( ev.pageX || ev.pageY ) { this.x = ev.pageX; this.y = ev.pageY; } else { this.x = ev.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft; this.y = ev.clientY + document.documentElement.scrollTop - document.documentElement.clientTop; } } catch (e) {} } } // 设置拖动物件 var clsMouseCoords = new mouseCoords (); var dragObj = false; var dragModeX = 0; // 0: left, 1: right var dragModeY = 0; // 0: top, 1: bottom var dragAlpha = 0; // 透明度 var dragObjFilter = ''; function setDragObj ( obj, modeX, modeY, alpha ) { if ( typeof ( obj ) == 'string' ) obj = $( obj ); if ( modeX == null ) modeX = 0; if ( modeY == null ) modeY = 0; if ( alpha == null ) dragAlpha = 0; mask.show ( false, obj.style.zIndex ); clsMouseCoords.getMouseCoords (); dragObj = obj; dragModeX = modeX; dragModeY = modeY; dragAlpha = alpha; if ( dragModeX == 0 ) window.dragX = clsMouseCoords.x - dragObj.offsetLeft; else window.dragX = clsMouseCoords.x - dragObj.offsetLeft - dragObj.offsetWidth; if ( dragModeY == 0 ) window.dragY = clsMouseCoords.y - dragObj.offsetTop; else window.dragY = clsMouseCoords.y - dragObj.offsetTop - dragObj.offsetHeight; dragObjFilter = dragObj.style.filter; if ( dragAlpha > 0 ) { dragObj.style.filter = 'alpha(opacity=' + dragAlpha + ')'; dragObj.style.opacity = dragAlpha / 100; // setAlpha ( dragObj.id, 100, 60 ); } document.onmousemove = doDragObj; document.onmouseup = clearDragObj; } function clearDragObj () { if ( typeof ( dragObj ) == 'object' ) { if ( dragModeX == 0 ) { if ( dragObj.style.left.indexOf ( '-' ) == 0 ) dragObj.style.left = '0px'; } else { if ( dragObj.style.right.indexOf ( '-' ) == 0 ) dragObj.style.right = '0px'; } if ( dragModeY == 0 ) { if ( dragObj.style.top.indexOf ( '-' ) == 0 ) dragObj.style.top = '0px'; } else { if ( dragObj.style.bottom.indexOf ( '-' ) == 0 ) dragObj.style.bottom = '0px'; } if ( dragAlpha > 0 ) { dragObj.style.filter = dragObjFilter; dragObj.style.opacity = '1.0'; // setAlpha ( dragObj.id, 60, 100 ); } dragObj.focus (); dragObj = false; mask.hide (); } } function setAlpha ( objId, opacity, maxOpacity, step ) { if ( opacity == maxOpacity ) { return true; } else { var obj = $ ( objId ); if ( step == null ) step = 10; opacity += opacity > maxOpacity ? - step : step; obj.style.filter = 'alpha(opacity=' + opacity + ')'; setTimeout ( "setAlpha ( '" + objId + "', " + opacity + ", " + maxOpacity + " )", 100 ); } } function doDragObj () { if ( typeof ( dragObj ) == 'object' ) { clsMouseCoords.getMouseCoords (); if ( dragModeX == 0 ) { dragObj.style.left = ( clsMouseCoords.x - window.dragX ) + 'px'; } else { var objHTML = document.getElementsByTagName('html').item(0); dragObj.style.right = ( objHTML.offsetWidth - clsMouseCoords.x + window.dragX ) + 'px'; } if ( dragModeY == 0 ) { dragObj.style.top = ( clsMouseCoords.y - window.dragY ) + 'px'; } else { var objHTML = document.getElementsByTagName('html').item(0); dragObj.style.bottom = ( objHTML.offsetHeight - clsMouseCoords.y + window.dragY ) + 'px'; } } } // 更改所有名称为 objName 的物件的 innerHTML function setValue ( objName, value ) { try { objs = getObjects ( objName ); for ( var i in objs ) { objs[i].innerHTML =value; } } catch (e){} } // 获取物件 function getObjects ( objName ) { var objs = new Array (); if ( idObjs = document.getElementById ( objName ) ) { objs.push ( idObjs ); } if ( document.all ) // IE { var objTypes = new Array ( 'table', 'tr', 'td', 'div', 'li', 'span', 'a' ); for ( var tagType in objTypes ) { var typeObjs = document.getElementsByTagName ( objTypes[tagType] ); for ( var i in typeObjs ) { try { if ( typeObjs[i].name == objName ) { objs.push ( typeObjs[i] ); } }catch(e){} } } } else // 其他浏览器 { nameObjs = document.getElementsByName ( objName ); for ( var i in nameObjs ) { objs.push ( nameObjs[i] ); } } return objs; } // 获得焦点 function setFocus ( objName, select ) { var obj; var objs = document.getElementsByName ( objName ); if ( objs.length > 0 ) { obj = objs.item(0); } else { obj = document.getElementById ( objName ); } if ( obj ) { if ( select == null ) select = false; if ( select ) { obj.select (); } else { obj.focus (); } } } // 高亮物件 function highlight ( obj, highlightClass ) { if ( typeof ( obj ) == 'string' ) { obj = $ ( obj ); } if ( highlightClass == null ) { highlightClass = 'highlight'; } try { for ( var i in obj.parentNode.childNodes ) { if ( obj.parentNode.childNodes[i].className != null ) { var re = new RegExp ( "[ ]*" + highlightClass ); obj.parentNode.childNodes[i].className = obj.parentNode.childNodes[i].className.replace ( re, '' ); } } obj.className = obj.className+" "+highlightClass } catch ( e ) {} } // 球衣高亮 function selectclothes ( obj , Number, Type, highlightClass ) { if ( typeof ( obj ) == 'string' ) { obj = document.getElementById ( obj ); } if ( highlightClass == null ) { highlightClass = 'picurrent'; } try { for ( var i in obj.parentNode.childNodes ) { if ( obj.parentNode.childNodes[i].className != null ) { var re = new RegExp ( "[ ]*" + highlightClass ); obj.parentNode.childNodes[i].className = obj.parentNode.childNodes[i].className.replace ( re, 'clothes' ); } } if(Type==1) document.getElementById("hdClubLogo").value=Number; else if(Type==2) document.getElementById("hdhostClother").value=Number; else document.getElementById("hdvisitClother").value=Number; obj.className = highlightClass; } catch ( e ) {} } // 载入物件 function objLoader () { this.timeStamp = null; this.loadedJs = ''; this.loadedCss = ''; // 载入指定页面到指定物件 /* loadUrl : 载入页面的 URL targetObj : 目标容器物件 ID queryString : 附加提交变量 loadJs : 附加 Js 文件 loadingMsg : 载入中提示文字 method: 以某种方式传输 GET和POST 两种,GET会受到65535字节的限制,POST不会受到该限制 */ this.get = function ( loadUrl, targetObj, queryString, loadingMsg, callbackFunc, loadJs ) { this.load ( 'GET', loadUrl, targetObj, queryString, loadingMsg, callbackFunc, loadJs ); } this.post = function ( loadUrl, targetObj, queryString, loadingMsg, callbackFunc, loadJs ) { this.load ( 'POST', loadUrl, targetObj, queryString, loadingMsg, callbackFunc, loadJs ); } this.load = function ( method, loadUrl, targetObj, queryString, loadingMsg, callbackFunc, loadJs ) { this.refreshCache (); if ( !loadUrl ) return; var obj; if ( typeof ( targetObj ) == 'string' ) { obj = $ ( targetObj ); } else { obj = targetObj; } if ( obj ) { if ( loadingMsg != null ) obj.innerHTML = loadingMsg; } if ( callbackFunc == null ) { callbackFunc = ajaxCallback; } this.getTimeStamp (); var re = new RegExp ( "timeStamp=([0-9]+)" ); if ( loadUrl.match ( re ) ) { loadUrl = loadUrl.replace ( re, 'timeStamp=' + this.timeStamp ); } else { loadUrl += loadUrl.indexOf ( '?' ) == -1 ? '?' : '&'; loadUrl += 'timeStamp=' + this.timeStamp; } if ( queryString == null ) queryString = ''; if ( window.ajaxProxy && loadUrl.indexOf ( getURLHost ( $( 'ajaxProxy' ).src ) ) >= 0 ) { var clsAjax = new ajaxProxy.Ajax ( loadUrl, queryString, callbackFunc, targetObj ); } else { var clsAjax = new Ajax ( loadUrl, queryString, callbackFunc, targetObj ); } if ( loadJs != null ) { this.loadJs ( loadJs ); } if ( method.toLowerCase () == 'post' ) { clsAjax.post (); } else { clsAjax.get (); } //mask.show(); } // 载入 Js this.loadJs = function ( file, reload ) { if ( !document.getElementById ) { return; } if ( reload == null ) reload = false; var fileref = ''; if ( reload || this.loadedJs.indexOf ( file ) == -1 ) { fileref = document.createElement ( 'script' ); fileref.setAttribute ( 'type', 'text/javascript' ); fileref.setAttribute ( 'src', file ); } if ( fileref != '' ) { document.getElementsByTagName('head').item(0).appendChild ( fileref ); this.loadedJs += file + ' '; } return fileref; } // 载入 Css this.loadCss = function ( file, reload ) { if ( !document.getElementById ) { return; } if ( reload == null ) reload = false; var fileref = ''; if ( reload || this.loadedCss.indexOf ( file ) == -1 ) { fileref=document.createElement ( 'link' ); fileref.setAttribute ( 'rel', 'stylesheet' ); fileref.setAttribute ( 'type', 'text/css' ); fileref.setAttribute ( 'href', file ); } if ( fileref != '' ) { document.getElementsByTagName('head').item(0).appendChild ( fileref ); this.loadedCss += file + ' '; } } // 设置时间戳, 用于控制页面缓存 this.refreshCache = function () { this.timeStamp = this.makeTimeStamp (); } // 生成时间戳 this.makeTimeStamp = function () { var dateTime = new Date (); var timeStamp = dateTime.getTime (); if ( typeof ( timeStamp ) == 'undefined' || timeStamp == null ) { timeStamp = Math.floor ( Math.random () * 10000 * 10000 ); } return timeStamp; } // 获取缓存时间戳 this.getTimeStamp = function () { if ( typeof ( this.timeStamp ) == 'undefined' || this.timeStamp == null ) this.timeStamp = this.makeTimeStamp (); return this.timeStamp; } } var loader = new objLoader (); loader.refreshCache (); // 遮罩 var noMask = false; function clsMask () { this.maskId = 'mask'; this.maskIndex = 0; this.lastHTMLStyle = null; this.show = function ( showFrame, zIndex ) { if ( noMask ) return false; if ( showFrame == null ) showFrame = true; this.maskIndex ++; var maskName = this.maskId + this.maskIndex; var mask = document.getElementById ( maskName ); if ( mask ) { mask.parentNode.removeChild ( mask ); } mask = document.createElement ( 'div' ); mask.id = maskName; mask.className = 'mask'; zIndex = parseInt ( zIndex ); if ( isNaN ( zIndex ) ) zIndex = ++ gzIndex; mask.style.zIndex = zIndex; if ( showFrame ) { mask.className += ' alhpa'; var maskFrame = document.createElement ( 'iframe' ); maskFrame.id = maskName + '_frame'; maskFrame.className = this.maskId; maskFrame.style.zIndex = zIndex; document.body.appendChild ( maskFrame ); } document.body.appendChild ( mask ); var objHTML = document.getElementsByTagName('html').item(0); if ( this.lastHTMLStyle == null ) this.lastHTMLStyle = objHTML.style.overflow; objHTML.style.overflow = 'hidden'; } this.hide = function () { if ( noMask ) return false; var maskFrame = document.getElementById ( this.maskId + this.maskIndex + '_frame' ); if ( maskFrame ) { try { maskFrame.parentNode.removeChild ( maskFrame ); } catch ( e ) { } } var mask = document.getElementById ( this.maskId + this.maskIndex ); if ( mask ) { var objHTML = document.getElementsByTagName('html').item(0); mask.parentNode.removeChild ( mask ); this.maskIndex --; gzIndex --; if ( this.maskIndex == 0 ) { objHTML.style.overflow = this.lastHTMLStyle; } } } } var mask = new clsMask (); var objHTML = document.getElementsByTagName('html').item(0); // 处理过程提示框 function clsProcess ( dialogName, className ) { this.processing = false; this.dialogName = dialogName; this.chkTimeOut = null; this.timeOut = 15; // 超时秒数 this.showMask = false; if ( className == null ) className = 'process'; this.className = className; if ( this.dialogName == null ) this.dialogName = 'processing_box'; // 正在处理 this.start = function ( procMsg ) { if ( !this.processing ) { if ( procMsg == null ) procMsg = '正在处理,请稍候...'; showDialogBox ( '<table class="box" style="width:300px;height:60px;"><tr><td align="center"><table align="center"><tr><td align="left" class="message">&nbsp;&nbsp;' + procMsg + '</td></tr></table></td></tr><table>', this.dialogName, true ); setFocus ( this.dialogName ); this.processing = true; if ( this.timeOut > 0 ) { this.chkTimeOut = setTimeout ( this.className + ".timeOut()", this.timeOut * 1000 ); } } } // // 正在处理无关闭 // this.startno = function ( procMsg ) // { // if ( !this.processing ) // { // if ( procMsg == null ) procMsg = '正在处理,请稍候...'; // showDialogBoxNo ( '<table class="box" style="width:300px;height:60px;"><tr><td align="center"><table align="center"><tr><td align="left" class="message"><img alt="" align="absmiddle" src="http://static.9way.cn/football/icons/icon-loading.gif" />&nbsp;&nbsp;' + procMsg + '</td></tr></table></td></tr><table>', this.dialogName); // setFocus ( this.dialogName ); // this.processing = true; // if ( this.timeOut > 0 ) // { // this.chkTimeOut = setTimeout ( this.className + ".timeOut()", this.timeOut * 1000 ); // } // } // } // 处理完成 this.finish = function () { if ( this.processing ) { objContentBody = document.getElementById ( 'body' ); // objContentBody.scrollTop = 0; removeDialogBox ( this.dialogName ); this.processing = false; clearTimeout ( this.chkTimeOut ); } } this.timeOut = function () { this.finish (); show_alert ( '网络连接超时,请重试!' ); } } var process = new clsProcess (); // 数值操作类 function clsNumber ( clsName, funcCallback, callbackParams ) { this.clsName = clsName; this.adding = 0; this.interval = null; this.callback = funcCallback != null ? funcCallback : null; // 回调函数 this.callbackParams = callbackParams != null ? callbackParams : null; // 回调函数参数 this.value = 0; this.minValue = 0; this.maxValue = -1; this.check = function ( obj ) { if ( typeof ( obj ) == 'string' ) { obj = document.getElementById ( obj ); } objValue = Math.round ( obj.value ); if ( isNaN ( objValue ) || objValue < this.minValue ) { obj.value = this.minValue; } else if ( this.maxValue >= 0 && objValue > this.maxValue ) { obj.value = this.maxValue; } this.value = obj.value; if ( this.callback != null ) { this.callback ( this.callbackParams ); } } this.add = function ( objId, quantity, minValue, maxValue ) { if ( minValue == null ) minValue = this.minValue; if ( maxValue == null ) maxValue = this.maxValue; obj = document.getElementById ( objId ); obj.value = Math.round ( obj.value ) + quantity; if ( this.adding > 5 ) { obj.value = Math.round ( obj.value / 10 ) * 10; } if ( this.minValue >= 0 && obj.value <= this.minValue && quantity < 0 ) { obj.value = minValue; } else if ( maxValue >= 0 && obj.value >= maxValue && quantity > 0 ) { obj.value = maxValue; } this.value = obj.value; this.check ( obj ); } this.startAdd = function ( objId, quantity, minValue, maxValue ) { if ( minValue == null ) minValue = this.minValue; if ( maxValue == null ) maxValue = this.maxValue; if ( this.adding == 0 ) { this.adding = true; this.doAdd ( objId, quantity, minValue, maxValue ); } } this.doAdd = function ( objId, quantity, minValue, maxValue ) { if ( this.adding > 0 ) { this.adding ++; var addQuantity = Math.max ( 1, Math.floor ( this.adding / 5 ) * 10 ) * quantity; this.add ( objId, addQuantity, minValue, maxValue ); this.interval = setTimeout ( this.clsName + ".doAdd('" + objId + "'," + quantity + "," + minValue + "," + maxValue + ")", 100 ); } else { clearTimeout ( this.interval ); } } this.finishAdd = function () { this.adding = 0; } } var number = new clsNumber ( 'number' ); // 载入完成后调用函数 function callAfterLoaded ( callback, script ) { if ( document.all ) // IE 支持 { script.onreadystatechange = function () { if ( script.readyState == 'loaded' || script.readyState == 'complete' ) { callback(); } } } else // Firefox 支持 { script.onload = callback; } } // 按 td 的 c 属性对查看表格 function table_view_by ( objList, c ) { if ( typeof ( objList ) == 'string' ) { objList = document.getElementById ( objList ); } if ( !objList ) { return false; } var objSubs = objList.getElementsByTagName ( 'td' ); for ( var i in objSubs ) { try { var itemCate = objSubs[i].getAttribute ( 'c' ); if ( itemCate == c ) { objSubs[i].style.display = ''; } else if ( itemCate != null ) { objSubs[i].style.display = 'none'; } } catch (e) {} } } // 随机数 function get_rand ( min, max ) { var range = max - min; var rand = Math.random(); return ( min + Math.round ( rand * range ) ); } // 预载入图片 function pre_load_image () { var doc = document; if ( doc.images ) { doc.preLoadImages = new Array (); var args = pre_load_image.arguments; for ( var i = 0; i < args.length; i ++ ) { doc.preLoadImages[i] = new Image (); doc.preLoadImages[i].src = args[i]; } } } // 判定数组中是否存在 function in_array ( value, array ) { for ( var i in array ) { if ( array[i] == value ) { return true; } } return false; } // 显示图片或 Flash function show_object ( filename, width, height, objId ) { var parts = filename.split ( '.' ); var fileType = parts.pop (); var html; var strObjId = strObjName = ''; if ( objId != null ) { strObjId = ' id="' + objId + '"'; strObjName = ' name="' + objId + '"'; } switch ( fileType ) { case 'swf': { html = '<object' + strObjId + ' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="' + width + '" height="' + height + '"><param name="movie" value="' + filename + '" /><param name="allowscriptaccess" value="always" /><param name="quality" value="high" /><param name="menu" value="false" /><param name="wmode" value="transparent" /><embed' + strObjName + ' src="' + filename + '" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" menu="false" wmode="transparent" width="' + width + '" height="' + height + '" allowscriptaccess="always" swLiveConnect="true"></embed></object>'; break; } default : { html = '<img' + strObjId + ' alt="" src="' + filename + '" />'; } } return html; } // 限制文本框字数 function maxLength ( obj, length, showAlert ) { if ( obj.value.replace(/([^\x00-\xff])/g,"EE").length > length ) { //obj.value = obj.value.substring ( 0, length ); if ( showAlert != null ) { show_alert ( '<center>很抱歉,您最多只能输入 ' + length + ' 个字符</center>' ); } return false; } } // 查找 Event 对象 function searchEvent () { if ( window.event ) return window.event; var func = searchEvent.caller; while ( func != null ) { var firstArg = func.arguments[0]; if ( firstArg ) { if ( firstArg.constructor == MouseEvent || firstArg.constructor == Event ) return firstArg; } func = func.caller; } return null; } function getSrcElement () { try { var evt = searchEvent (); var srcElem = evt.target; if ( typeof ( evt.target ) != 'object' ) { var srcElem = evt.srcElement; } return srcElem; } catch (e) { return null; } } // 获取上级对话框 function getParentDialog ( obj, className ) { if ( typeof ( obj ) == 'string' ) { obj = $ ( obj ); } if ( className == null ) className = 'dialog_box'; if ( typeof ( obj ) == 'object' && obj.className && obj.className.indexOf ( className ) == 0 ) return obj; var pObj = obj.parentNode; if ( pObj == null ) return null; if ( pObj.className == className ) return pObj; else return getParentDialog ( pObj ); }
Markdown
UTF-8
2,089
2.734375
3
[ "MIT" ]
permissive
--- template: HomePage slug: "" title: Ellelly featuredImage: https://ucarecdn.com/ca8fc208-001b-4343-a3d1-3e5e13e5ddfe/ subtitle: >- ***Your Total Period Solution*** The self-sufficient, durable and reusable period pants and pads that are practical, comfortable, sustainable and affordable for all menstruating people. Everything you need and want for your whole cycle, to meet the needs of every flow. meta: description: Practical, comfortable, sustainable and affordable replacements for single use tampons, pads, towels and cups for all menstruating people. title: Reusable Period Pants and Pads for All Menstruating People --- # Our Vision A world where reusable period products are the cost effective, practical, preferred option. # Our Mission To re-define period products by making sustainable, practical, comfortable, durable and affordable reusable period pants for all menstruating people the norm. * DESIGN affordable, durable, practical, comfortable and totally sustainable period underwear using the best modern practices and materials. * PRODUCE and make available to the general population at low cost via major sellers and accessible means as an affordable alternative to disposable and less sustainable options. * SUPPLY to schools and charities at minimal cost as a practical, comfortable and highly economical alternative to disposable products. ## Our Key Features * **Sustainably** sourced materials * **Manufacturing** techniques using modern resources and technology * **Practical** leak proof design for day and night based on years of testing and knowledge of the needs of menstruating people * **Comfortable** designs for all body types when they are feeling most vulnerable * **Reusable** protection to maximise sustainability while being easily washable * **Affordable** fair trade materials and manufacturing sourced efficiently to keep cost to the consumer as low as possible making these products a viable and financially attractive alternative to disposable and less sustainable options ** ...are all the heart of out work**
JavaScript
UTF-8
2,470
3.375
3
[]
no_license
var game = function (gameID) { this.playerA = null; this.playerB = null; this.playerC = null; this.playerD = null; this.id = gameID; this.gameState = "0 JOINT"; //"A" means A won, "B" means B won, "ABORTED" means the game was aborted }; game.prototype.transitionStates = {}; game.prototype.transitionStates["0 JOINT"] = 0; game.prototype.transitionStates["1 JOINT"] = 1; game.prototype.transitionStates["2 JOINT"] = 2; game.prototype.transitionStates["3 JOINT"] = 3; game.prototype.transitionStates["4 JOINT"] = 4; game.prototype.transitionStates["A"] = 5; //A won game.prototype.transitionStates["B"] = 6; //B won game.prototype.transitionStates["C"] = 7; //C won game.prototype.transitionStates["D"] = 8; //D won game.prototype.transitionStates["ABORTED"] = 9; // game.prototype.transitionMatrix = [ // [1, 0, 0, 0, 0, 0, 0, 0, 0, 0] //0 joint // [0, 1, 0, 0, 0, 0, 0, 0, 0, 0] //1 joint // [0, 0, 1, 0, 0, 0, 0, 0, 0, 0] //2 joint // [0, 0, 0, 1, 0, 0, 0, 0, 0, 0] //3 joint // [0, 0, 0, 0, 1, 0, 0, 0, 0, 0] //4 joint // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] //A won // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] //B won // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] //C won // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] //D won // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ///ABORTED // ]; //the function for the dice function dice_roll(){ var dice_sound = new Audio("../sounds/dice.wav"); dice_sound.play(); document.getElementById("dice_image").src="../images/EmptyDice.png"; setTimeout(function(){ var diceNumber = getRandomInt(1, 6); if(diceNumber == 1){ document.getElementById("dice_image").src="../images/Dice1.png"; } else if(diceNumber == 2){ document.getElementById("dice_image").src="../images/Dice2.png"; } else if(diceNumber == 3){ document.getElementById("dice_image").src="../images/Dice3.png"; } else if(diceNumber == 4){ document.getElementById("dice_image").src="../images/Dice4.png"; } else if(diceNumber == 5){ document.getElementById("dice_image").src="../images/Dice5.png"; } else if(diceNumber == 6){ document.getElementById("dice_image").src="../images/Dice6.png"; } } ,2000); } function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } function player_turn(){ var playernumber = (1, 2, 3, 4); var turnnumber = (1, 2, 3, 4); if(turnnumber == 1){ document.getElementById("dice_image").disabled = true; } }
Java
UTF-8
4,063
1.710938
2
[]
no_license
package org.tgcloud.zhanzhang.entity.base; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.IBean; /** * Generated by JFinal, do not modify this file. */ @SuppressWarnings("serial") public abstract class BaseZFindworker<M extends BaseZFindworker<M>> extends Model<M> implements IBean { public void setId(java.lang.Integer id) { set("id", id); } public java.lang.Integer getId() { return get("id"); } public void setTitle(java.lang.String title) { set("title", title); } public java.lang.String getTitle() { return get("title"); } public void setProvinceId(java.lang.Integer provinceId) { set("province_id", provinceId); } public java.lang.Integer getProvinceId() { return get("province_id"); } public void setCityId(java.lang.Integer cityId) { set("city_id", cityId); } public java.lang.Integer getCityId() { return get("city_id"); } public void setCountyId(java.lang.Integer countyId) { set("county_id", countyId); } public java.lang.Integer getCountyId() { return get("county_id"); } public void setSex(java.lang.Integer sex) { set("sex", sex); } public java.lang.Integer getSex() { return get("sex"); } public void setAge(java.lang.String age) { set("age", age); } public java.lang.String getAge() { return get("age"); } public void setIncome(java.lang.String income) { set("income", income); } public java.lang.String getIncome() { return get("income"); } public void setChoice(java.lang.String choice) { set("choice", choice); } public java.lang.String getChoice() { return get("choice"); } public void setRestday(java.lang.String restday) { set("restday", restday); } public java.lang.String getRestday() { return get("restday"); } public void setWorktime(java.lang.String worktime) { set("worktime", worktime); } public java.lang.String getWorktime() { return get("worktime"); } public void setDegrees(java.lang.String degrees) { set("degrees", degrees); } public java.lang.String getDegrees() { return get("degrees"); } public void setRemarks(java.lang.String remarks) { set("remarks", remarks); } public java.lang.String getRemarks() { return get("remarks"); } public void setImgs(java.lang.String imgs) { set("imgs", imgs); } public java.lang.String getImgs() { return get("imgs"); } public void setLinkman(java.lang.String linkman) { set("linkman", linkman); } public java.lang.String getLinkman() { return get("linkman"); } public void setTel(java.lang.String tel) { set("tel", tel); } public java.lang.String getTel() { return get("tel"); } public void setShowtel(java.lang.Integer showtel) { set("showtel", showtel); } public java.lang.Integer getShowtel() { return get("showtel"); } public void setShowcontact(java.lang.Integer showcontact) { set("showcontact", showcontact); } public java.lang.Integer getShowcontact() { return get("showcontact"); } public void setCreatetime(java.sql.Date createtime) { set("createtime", createtime); } public java.sql.Date getCreatetime() { return get("createtime"); } public void setStatus(java.lang.Integer status) { set("status", status); } public java.lang.Integer getStatus() { return get("status"); } public void setUserId(java.lang.Integer userId) { set("user_id", userId); } public java.lang.Integer getUserId() { return get("user_id"); } public void setCompanyname(java.lang.String companyname) { set("companyname", companyname); } public java.lang.String getCompanyname() { return get("companyname"); } public void setTrade(java.lang.String trade) { set("trade", trade); } public java.lang.String getTrade() { return get("trade"); } public void setIntroduce(java.lang.String introduce) { set("introduce", introduce); } public java.lang.String getIntroduce() { return get("introduce"); } public void setNums(java.lang.String nums) { set("nums", nums); } public java.lang.String getNums() { return get("nums"); } }
JavaScript
UTF-8
2,209
2.65625
3
[]
no_license
// Generated by CoffeeScript 1.6.3 (function() { var color, force, height, svg, width; width = 1200; height = 900; svg = d3.select("body").append("svg").attr("width", width).attr("height", height); color = d3.scale.category10(); force = d3.layout.force().charge(-120).linkDistance(30).size([width, height]); d3.json("data.json", function(error, graph) { var link, node; force.nodes(graph.nodes).links(graph.links).start(); link = svg.selectAll(".link").data(graph.links).enter().append("line").attr("class", "link").style("stroke-width", function(d) { return Math.sqrt(d.value); }).style("stroke", "#999").style("stroke-opacity", ".6"); node = svg.selectAll(".node").data(graph.nodes).enter().append("circle").attr("class", "node").attr("r", 5).style("fill", function(d) { return color(d.group); }).style("stroke", "#fff").style("stroke-width", "1px").call(force.drag); node.append("title").text(function(d) { return d.name; }); return force.on("tick", function() { link.attr("x1", function(d) { return d.source.x; }).attr("y1", function(d) { return d.source.y; }).attr("x2", function(d) { return d.target.x; }).attr("y2", function(d) { return d.target.y; }); return node.attr("cx", function(d) { return d.x; }).attr("cy", function(d) { return d.y; }); }); }); $(function() { return $("#slider-range-min").slider({ range: "min", value: -120, min: -500, max: 0, slide: function(event, ui) { force.charge(ui.value); return force.start(); } }); }); $(function() { return $("#slider-range-min2").slider({ range: "min", value: 30, min: 1, max: 1000, slide: function(event, ui) { force.linkDistance(ui.value); return force.start(); } }); }); $(function() { return $("#slider-range-min3").slider({ range: "min", value: 0.1, min: 0.1, max: 10, slide: function(event, ui) { force.gravity(ui.value); return force.start(); } }); }); }).call(this);
Java
UTF-8
5,610
1.90625
2
[ "MIT" ]
permissive
package com.jannchie.biliob.model; import com.fasterxml.jackson.annotation.JsonInclude; import org.bson.types.ObjectId; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.util.Date; import java.util.List; /** * @author jannchie */ @JsonInclude(JsonInclude.Include.NON_NULL) @Document(collection = "bangumi") public class Bangumi { @Id private ObjectId id; private Long sid; private Long mid; private String name; private String foreignName; private String copyright; // 专题类型/专题分区,其中1:番剧,4:国创 private Short type; // 专题状态(-1: 下架, 2:免费, 13:大会员抢先/专享) private Byte state; private Date pubDate; private Boolean isSerializing; private Boolean isFinished; private Long cView; private Long cCoin; private Long oldFollow; private Long newFollow; private Float score; private Long scoreCount; private String cover; private String smallCover; private String charge; private String area; private Date updateTime; private List<BangumiData> bangumiHistoryData; public Bangumi(Long sid, Long mid, String name, String foreignName, String copyright, Short type, Byte state, Date pubDate, Boolean isSerializing, Boolean isFinished, Long cView, Long cCoin, Long oldFollow, Long newFollow, Float score, Long scoreCount, String cover, String smallCover, String charge, String area, Date updateTime) { this.sid = sid; this.mid = mid; this.name = name; this.foreignName = foreignName; this.copyright = copyright; this.type = type; this.state = state; this.pubDate = pubDate; this.isSerializing = isSerializing; this.isFinished = isFinished; this.cView = cView; this.cCoin = cCoin; this.oldFollow = oldFollow; this.newFollow = newFollow; this.score = score; this.scoreCount = scoreCount; this.cover = cover; this.smallCover = smallCover; this.charge = charge; this.area = area; this.updateTime = updateTime; } public Long getSid() { return sid; } public void setSid(Long sid) { this.sid = sid; } public Long getMid() { return mid; } public void setMid(Long mid) { this.mid = mid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getForeignName() { return foreignName; } public void setForeignName(String foreignName) { this.foreignName = foreignName; } public String getCopyright() { return copyright; } public void setCopyright(String copyright) { this.copyright = copyright; } public Short getType() { return type; } public void setType(Short type) { this.type = type; } public Byte getState() { return state; } public void setState(Byte state) { this.state = state; } public Date getPubDate() { return pubDate; } public void setPubDate(Date pubDate) { this.pubDate = pubDate; } public Boolean getSerializing() { return isSerializing; } public void setSerializing(Boolean serializing) { isSerializing = serializing; } public Boolean getFinished() { return isFinished; } public void setFinished(Boolean finished) { isFinished = finished; } public Long getcView() { return cView; } public void setcView(Long cView) { this.cView = cView; } public Long getcCoin() { return cCoin; } public void setcCoin(Long cCoin) { this.cCoin = cCoin; } public Long getOldFollow() { return oldFollow; } public void setOldFollow(Long oldFollow) { this.oldFollow = oldFollow; } public Long getNewFollow() { return newFollow; } public void setNewFollow(Long newFollow) { this.newFollow = newFollow; } public Float getScore() { return score; } public void setScore(Float score) { this.score = score; } public Long getScoreCount() { return scoreCount; } public void setScoreCount(Long scoreCount) { this.scoreCount = scoreCount; } public String getCover() { return cover; } public void setCover(String cover) { this.cover = cover; } public String getSmallCover() { return smallCover; } public void setSmallCover(String smallCover) { this.smallCover = smallCover; } public String getCharge() { return charge; } public void setCharge(String charge) { this.charge = charge; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public List<BangumiData> getBangumiHistoryData() { return bangumiHistoryData; } public void setBangumiHistoryData(List<BangumiData> bangumiHistoryData) { this.bangumiHistoryData = bangumiHistoryData; } public ObjectId getId() { return id; } public void setId(ObjectId id) { this.id = id; } }
Java
UTF-8
246
2.75
3
[]
no_license
public class main { public static void main(String[] args) { Human humanObject = new Human(); System.out.println(humanObject.name); Food something = new Food(12, "pizza"); humanObject.eat(something); } }
C#
WINDOWS-1252
9,933
2.765625
3
[]
no_license
#region Using Directives and Copyright Notice // Copyright (c) 2007-2010, Computer Consultancy Pty Ltd // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * 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. // * Neither the name of the Computer Consultancy Pty 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 COMPUTER CONSULTANCY PTY LTD 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. using System; #endregion namespace Interlace.Geo { [Serializable] public struct Position { public double Longitude, Latitude; public static Position FromDegrees(double longitude, double latitude) { return new Position(Math.PI * longitude / 180.0, Math.PI * latitude / 180.0); } public void ToDegrees(out double longitude, out double latitude) { longitude = 180.0 * this.Longitude / Math.PI; latitude = 180.0 * this.Latitude / Math.PI; } public Position ToDegrees() { return new Position(180.0 * this.Longitude / Math.PI, 180.0 * this.Latitude / Math.PI); } public Position ToRadians() { return new Position(Math.PI * this.Longitude / 180.0, Math.PI * this.Latitude / 180.0); } public Position(double longitude, double latitide) { this.Longitude = longitude; this.Latitude = latitide; } public double X { get { return Longitude; } set { Longitude = value; } } public double Y { get { return Latitude; } set { Latitude = value; } } public static Position operator - (Position lhs, Position rhs) { return new Position(lhs.X - rhs.X, lhs.Y - rhs.Y); } public static Position operator + (Position lhs, Position rhs) { return new Position(lhs.X + rhs.X, lhs.Y + rhs.Y); } public static double DotProduct(Position lhs, Position rhs) { return lhs.X * rhs.X + lhs.Y * rhs.Y; } public static double SquaredDistance(Position lhs, Position rhs) { return (lhs.X - rhs.X) * (lhs.X - rhs.X) + (lhs.Y - rhs.Y) * (lhs.Y - rhs.Y); } public double SquaredDistanceFromOrigin() { return X * X + Y * Y; } public Position GetPointFromTargetAndDistance(Position target, double distance) { Position delta = target - this; double delta_length = Math.Sqrt(delta.SquaredDistanceFromOrigin()); double udx = delta.X / delta_length; double udy = delta.Y / delta_length; return new Position(this.X + udx * distance, this.Y + udy * distance); } private static double Radians(double d) { return Math.PI * d / 180; } public static bool PointsEqual(Position a, Position b, double tolerance) { return Math.Abs(a.Latitude - b.Latitude) <= tolerance && Math.Abs(a.Longitude - b.Longitude) <= tolerance; } public static double CartesianDistance(Position a, Position b) { return Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y)); } // Calculates the distance between two points, using the method // described in: // // Vincenty, T. Direct and Inverse Solutions of Geodesics of the // Ellipsoid with Applications of Nested Equations, Survey Review, // No. 176, 1975. // // Points that are nearly antipodal yield no solution; a // Double.NaN is returned. public static double CalculateDistance(Position a, Position b, Ellipsoid e) { double distance; Angle bearing; CalculateDistanceAndBearing(a, b, e, out distance, out bearing); return distance; } public static void CalculateDistanceAndBearing(Position a, Position b, Ellipsoid e, out double distance, out Angle bearing) { if (PointsEqual(a, b, 1e-12)) { distance = 0.0; bearing = Angle.FromAngleInDegrees(0.0); } double lambda = Radians(b.Longitude - a.Longitude); double last_lambda = 2 * Math.PI; double U1 = Math.Atan((1 - e.F) * Math.Tan(Radians(a.Latitude))); double U2 = Math.Atan((1 - e.F) * Math.Tan(Radians(b.Latitude))); double sin_U1 = Math.Sin(U1); double sin_U2 = Math.Sin(U2); double cos_U1 = Math.Cos(U1); double cos_U2 = Math.Cos(U2); double alpha, sin_sigma, cos_sigma, sigma, cos_2sigma_m, sqr_cos_2sigma_m; int loop_limit = 30; const double threshold = 1e-12; do { double sin_lambda = Math.Sin(lambda); double cos_lambda = Math.Cos(lambda); sin_sigma = Math.Sqrt( Math.Pow(cos_U2 * sin_lambda, 2) + Math.Pow(cos_U1 * sin_U2 - sin_U1 * cos_U2 * cos_lambda, 2) ); cos_sigma = sin_U1 * sin_U2 + cos_U1 * cos_U2 * cos_lambda; sigma = Math.Atan2(sin_sigma, cos_sigma); alpha = Math.Asin(cos_U1 * cos_U2 * sin_lambda / sin_sigma); double sqr_cos_alpha = Math.Pow(Math.Cos(alpha), 2); cos_2sigma_m = cos_sigma - 2 * sin_U1 * sin_U2 / sqr_cos_alpha; sqr_cos_2sigma_m = Math.Pow(cos_2sigma_m, 2); double C = e.F / 16 * sqr_cos_alpha * (4 + e.F * (4 - 3 * sqr_cos_alpha)); last_lambda = lambda; lambda = Radians(b.Longitude - a.Longitude) + (1 - C) * e.F * Math.Sin(alpha) * (sigma + C * sin_sigma * (cos_2sigma_m + C * cos_sigma * (-1 + 2 * sqr_cos_2sigma_m)) ); loop_limit -= 1; } while (Math.Abs(lambda - last_lambda) > threshold && loop_limit > 0); // As in Vincenty 1975, "The inverse formula may give no // solution over a line between two nearly antipodal points": if (loop_limit == 0) { distance = double.NaN; bearing = Angle.FromAngleInDegrees(0.0); return; } double sqr_u = Math.Pow(Math.Cos(alpha), 2) * (e.A * e.A - e.B * e.B) / (e.B * e.B); double A = 1 + sqr_u / 16384 * (4096 + sqr_u * (-768 + sqr_u * (320 - 175 * sqr_u))); double B = sqr_u / 1024 * (256 + sqr_u * (-128 + sqr_u * (74 - 47 * sqr_u))); double delta_sigma = B * sin_sigma * (cos_2sigma_m + B / 4 * (cos_sigma * (-1 + 2 * sqr_cos_2sigma_m) - B / 6 * cos_2sigma_m * (-3 + 4 * Math.Pow(sin_sigma, 2)) * (-3 + 4 * sqr_cos_2sigma_m) )); distance = e.B * A * (sigma - delta_sigma); bearing = Angle.FromHeadingInDegrees(180.0 / Math.PI * Math.Atan2(cos_U2 * Math.Sin(lambda), cos_U1 * sin_U2 - sin_U1 * cos_U2 * Math.Cos(lambda))); } private static void TotalDegreesToDegreesMinutesSeconds(double totalDegrees, out int degrees, out int minutes, out double seconds) { degrees = (int)totalDegrees; double totalMinutes = (Math.Abs(totalDegrees - degrees)) * 60.0; minutes = (int)totalMinutes; seconds = (Math.Abs(totalMinutes - minutes)) * 60.0; } private static string TotalDegreesToString(double totalDegrees, string positiveHemisphere, string negativeHemisphere) { int degrees, minutes; double seconds; TotalDegreesToDegreesMinutesSeconds(totalDegrees, out degrees, out minutes, out seconds); return String.Format("{0} {1}' {2:0.000}\" {3}", Math.Abs(degrees), minutes, seconds, degrees >= 0.0 ? positiveHemisphere : negativeHemisphere); } public string LatitudeString { get { return TotalDegreesToString(Latitude, "N", "S"); } } public string LongitudeString { get { return TotalDegreesToString(Longitude, "E", "W"); } } public override bool Equals(object obj) { if (!(obj is Position)) return false; Position rhs = (Position)obj; return Longitude == rhs.Longitude && Latitude == rhs.Latitude; } public override int GetHashCode() { return Longitude.GetHashCode() ^ Latitude.GetHashCode(); } public static bool operator==(Position lhs, Position rhs) { return lhs.Longitude == rhs.Longitude && lhs.Latitude == rhs.Latitude; } public static bool operator!=(Position lhs, Position rhs) { return lhs.Longitude != rhs.Longitude || lhs.Latitude != rhs.Latitude; } } }
C++
UTF-8
624
2.84375
3
[]
no_license
//13:13 start //13:19 error answer //13:21 finish #include <iostream> #include <iomanip> using namespace std; int main() { float x[4],y[4]; int centeri, centerj; while(1){ for(int i=0;i<4;i++){ cin>>x[i]>>y[i]; } if(cin.eof())break; for(int i=0;i<4;i++) for(int j=i+1;j<4;j++){ if(x[i]==x[j] && y[i]==y[j]){ centeri=i; centerj=j; } } float ansx=0,ansy=0; for(int i=0;i<4;i++){ if(i!=centeri && i!=centerj){ ansx+=x[i]-x[centeri]; ansy+=y[i]-y[centeri]; } } cout<<fixed<<setprecision(3); cout<<(ansx+x[centeri])<<" "; cout<<(ansy+y[centeri])<<endl; } return 0; }
C++
UTF-8
1,461
3.125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { int n=1; int length; cin >> length; vector<double> a(length); for (int i = 0;i < length;i++) { cin >> a[i]; } while (n < length) { n *= 2; } int merge_size = 2; int submerge_size; double tem; int temsize; for (;merge_size <= n;merge_size *= 2) { for (int index = 0;index < n;index += merge_size) for (int pointer = 0;pointer < merge_size / 2;pointer++){ if (pointer+index < length&&index + merge_size - pointer - 1 < length && a[pointer+index] > a[index + merge_size - pointer - 1 ]) { tem = a[pointer+index]; a[pointer+index] = a[index + merge_size - pointer - 1]; a[index + merge_size - pointer - 1] = tem; } } cout << "m "; for (int i = 0;i < length;i++) { cout << a[i] << ' '; } cout << endl; submerge_size = merge_size / 2; for (;submerge_size > 1;submerge_size /= 2) { temsize = submerge_size / 2; for (int index = 0;index < n;index += submerge_size) { for (int pointer = index;pointer < index + temsize;pointer++) { if (pointer < length && pointer + temsize<length && a[pointer] > a[pointer + temsize]) { tem = a[pointer]; a[pointer] = a[pointer + temsize]; a[pointer + temsize] = tem; } } } cout << "s "; for (int i = 0;i < length;i++) { cout << a[i] << ' '; } cout << endl; } } for (int i = 0;i < length;i++) { cout << a[i] << ' '; } return 0; }
Markdown
UTF-8
5,706
2.65625
3
[]
no_license
--- description: "Simple Way to Make Favorite Okonomiyaki" title: "Simple Way to Make Favorite Okonomiyaki" slug: 60-simple-way-to-make-favorite-okonomiyaki date: 2020-09-27T12:34:16.460Z image: https://img-global.cpcdn.com/recipes/e1345aebe03f11ab/751x532cq70/okonomiyaki-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/e1345aebe03f11ab/751x532cq70/okonomiyaki-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/e1345aebe03f11ab/751x532cq70/okonomiyaki-recipe-main-photo.jpg author: Landon Howard ratingvalue: 5 reviewcount: 14 recipeingredient: - "1/10 th of a cabbage shredded" - "1/4 th cup allpurpose Flour" - "1 tbsp Tapioca flour" - "1 egg" - "1/2 tsp hondashi seasoning" - " Benishoga diced something pickled" - " Leftover rotisserie chicken diced" - " Seaweed crumbled or Aonori if you have it" - "2 stalks Green onion diced" - " Japanese mayo" - " Okonomiyaki or Takoyaki sauce" - " Dried bonito flakes Katsuobushi" - " Sesame seeds" recipeinstructions: - "Mix the cabbage, flours, hondashi, chicken, beni-shoga, half of the green onions, and just enough water to make the batter come together. More cabbage &gt; less batter." - "Traditionally, grated Nagaimo would create a bouncy texture; but I used Tapioca flour as a replacement. Should have the same gooey-ish consistency." - "In a wide, shallow pan over medium heat, pour in your batter and flatten to create a circle. Heat on both sides til lightly charred. Set on a plate." - "Here’s the fun part. Smother the okonomiyaki sauce around the pancake like pizza sauce." - "Drizzle the mayo" - "Top with the seaweed and katsuobushi" - "..the rest of your green onions and sesame seeds. Enjoy!" categories: - Recipe tags: - okonomiyaki katakunci: okonomiyaki nutrition: 150 calories recipecuisine: American preptime: "PT11M" cooktime: "PT31M" recipeyield: "4" recipecategory: Lunch --- ![Okonomiyaki](https://img-global.cpcdn.com/recipes/e1345aebe03f11ab/751x532cq70/okonomiyaki-recipe-main-photo.jpg) Hello everybody, it's Brad, welcome to my recipe page. Today, we're going to prepare a special dish, okonomiyaki. One of my favorites food recipes. This time, I'm gonna make it a little bit tasty. This is gonna smell and look delicious. Okonomiyaki is one of the most favored of current trending foods in the world. It's enjoyed by millions daily. It is simple, it's fast, it tastes yummy. They are nice and they look wonderful. Okonomiyaki is something that I have loved my entire life. Okonomiyaki (literally means &#39;grilled as you like it&#39;) is a savory version of Japanese pancake, made with flour, eggs, shredded cabbage, meat/ protein and topped with a variety of condiments. Okonomiyaki o-konomi-yaki is a Japanese savory pancake containing a variety of ingredients. The name is derived from the word okonomi. To begin with this recipe, we have to prepare a few ingredients. You can cook okonomiyaki using 13 ingredients and 7 steps. Here is how you cook that. <!--inarticleads1--> ##### The ingredients needed to make Okonomiyaki: 1. Make ready 1/10 th of a cabbage; shredded 1. Get 1/4 th cup all-purpose Flour 1. Prepare 1 tbsp Tapioca flour 1. Take 1 egg 1. Get 1/2 tsp hondashi seasoning 1. Take Beni-shoga; diced (something pickled) 1. Prepare Leftover rotisserie chicken; diced 1. Get Seaweed; crumbled (or Aonori; if you have it) 1. Make ready 2 stalks Green onion; diced 1. Take Japanese mayo 1. Make ready Okonomiyaki or Takoyaki sauce 1. Take Dried bonito flakes (Katsuobushi) 1. Prepare Sesame seeds Okonomiyaki - Japanese savoury pancake containing loads of shredded cabbage topped with egg, meat and bonito flakes. Eat with sweet sauce and mayonnaise! Okonomi means &#34;how you want it,&#34; and an okonomiyaki is one of the world&#39;s most infinitely adaptable dishes. The shredded or chopped cabbage in the base is a given, but beyond that, you can add. <!--inarticleads2--> ##### Steps to make Okonomiyaki: 1. Mix the cabbage, flours, hondashi, chicken, beni-shoga, half of the green onions, and just enough water to make the batter come together. More cabbage &gt; less batter. 1. Traditionally, grated Nagaimo would create a bouncy texture; but I used Tapioca flour as a replacement. Should have the same gooey-ish consistency. 1. In a wide, shallow pan over medium heat, pour in your batter and flatten to create a circle. Heat on both sides til lightly charred. Set on a plate. 1. Here’s the fun part. Smother the okonomiyaki sauce around the pancake like pizza sauce. 1. Drizzle the mayo 1. Top with the seaweed and katsuobushi 1. ..the rest of your green onions and sesame seeds. Enjoy! Okonomiyaki - お好み焼き - is a savory Japanese pancake made with a light but substantial batter You see, okonomiyaki has a tradition of being topped with okonomi sauce, Japanese mayonnaise. With a history as rich as its flavor, Japan&#39;s &#34;pancake/pizza/crepe/omelette&#34; will fill you up and ensure you come back for more. Okonomiyaki (���D�ݏĂ�) is a popular pan-fried dish that consists of batter and cabbage. Selected toppings and ingredients are added which can vary greatly (anything from meat and seafood. Okonomiyaki(お好み焼) is a Japanese cabbage-based savory pancake. &#34;Okonomi(お好み)&#34; literary means &#34;Whatever How to make Okonomiyaki!!!! So that is going to wrap this up with this special food okonomiyaki recipe. Thank you very much for your time. I am sure that you can make this at home. There's gonna be interesting food at home recipes coming up. Remember to save this page on your browser, and share it to your loved ones, friends and colleague. Thank you for reading. Go on get cooking!
C++
UTF-8
5,704
2.921875
3
[]
no_license
#include "sprite.h" Sprite::Sprite() { _alive = 1; _leftOrRightSide = 0; _direction = 1; _animDir = 1; _animColumns = 0; _width = 0; _height = 0; _xDelay = 0; _yDelay = 0; _xCount = 0; _yCount = 0; _curFrame = 0; _totalFrames = 1; _frameCount = 0; _frameDelay = 1; _animStartX = 0; _animStartY = 0; _faceAngle = 0; _moveAngle = 0; _x = 0.0f; _y = 0.0f; _speed = 0.0; _velX = 0.0; _velY = 0.0; _passLeftSideToLose = false; _image = NULL; } Sprite::~Sprite() { if (_image != NULL) { destroy_bitmap(_image); } } int Sprite::Load(BITMAP *image) { _image = image; if (_image == NULL) { return 0; } _width = _image->w; _height = _image->h; return 1; } void Sprite::Draw(BITMAP *dest) { draw_sprite(dest, _image, (int) _x, (int) _y); } void Sprite::DrawFrame(BITMAP *dest) { int frameX = _animStartX + (_curFrame % _animColumns) * _width; int frameY = _animStartY + (_curFrame / _animColumns) * _height; masked_blit(_image, dest, frameX, frameY, (int) _x, (int) _y, _width, _height); } void Sprite::UpdatePosition() { if (++_xCount > _xDelay) { _xCount = 0; _x += _direction * _velX; } if (++_yCount > _yDelay) { _yCount = 0; _y += _direction * _velY; } } void Sprite::UpdateAnimation() { if (++_frameCount > _frameDelay) { _frameCount = 0; _curFrame += _animDir; if (_curFrame < 0) { _curFrame = _totalFrames - 1; } if (_curFrame > _totalFrames - 1) { _curFrame = 0; } } } int Sprite::Inside(int x, int y, int left, int top, int right, int bottom) { return (x > left && x < right && y < bottom && y > top) ? 1 : 0; } int Sprite::PointInside(int px, int py) { return Inside(px, py, (int) _x, (int) _y, (int) _x + _width, (int) _y + _height); } int Sprite::Collided(Sprite *other, int shrink) { int widthA = (int) _x + _width; int heightA = (int) _y + _height; int widthB = (int) other->getX() + (int) other->getWidth(); int heightB = (int) other->getY() + (int) other->getHeight(); if (Inside((int) _x, (int) _y, (int) other->getX() + shrink, (int) other->getY() + shrink, widthB - shrink, heightB - shrink) || Inside((int) _x, heightA, (int) other->getX() + shrink, (int) other->getY() + shrink, widthB - shrink, heightB - shrink) || Inside(widthA, (int) _y, (int) other->getX() + shrink, (int) other->getY() + shrink, widthB - shrink, heightB - shrink) || Inside(widthA, heightA, (int) other->getX() + shrink, (int) other->getY() + shrink, widthB - shrink, heightB - shrink)) { return 1; } else { return 0; } } void Sprite::ChangeDirection() { _direction = _direction == -1 ? 1 : -1; } double Sprite::CenterX() { return _x + (_width / 2); } double Sprite::CenterY() { return _y + (_height / 2); } void Sprite::IncreaseSpeed() { _velX += 0.5; } int Sprite::getAlive() { return _alive; } void Sprite::setAlive(int alive){ _alive = alive; } int Sprite::getLeftOrRightSide(){ return _leftOrRightSide; } void Sprite::setLeftOrRightSide(int leftOrRightSide){ _leftOrRightSide = leftOrRightSide; } int Sprite::getDirection(){ return _direction; } void Sprite::setDirection(int direction){ _direction = direction; } int Sprite::getAnimDir(){ return _animDir; } void Sprite::setAnimDir(int animDir){ _animDir = animDir; } int Sprite::getAnimColumns(){ return _animColumns; } void Sprite::setAnimColumns(int animColumns){ _animColumns = animColumns; } int Sprite::getWidth(){ return _width; } void Sprite::setWidth(int width){ _width = width; } int Sprite::getHeight(){ return _height; } void Sprite::setHeight(int height){ _height = height; } int Sprite::getXDelay(){ return _xDelay; } void Sprite::setXDelay(int xDelay){ _xDelay = xDelay; } int Sprite::getYDelay(){ return _yDelay; } void Sprite::setYDelay(int yDelay){ _yDelay = yDelay; } int Sprite::getXCount(){ return _xCount; } void Sprite::setXCount(int xCount){ _xCount = xCount; } int Sprite::getYCount(){ return _yCount; } void Sprite::setYCount(int yCount){ _yCount = yCount; } int Sprite::getCurFrame(){ return _curFrame; } void Sprite::setCurFrame(int curFrame){ _curFrame = curFrame; } int Sprite::getTotalFrames(){ return _totalFrames; } void Sprite::setTotalFrames(int totalFrames){ _totalFrames = totalFrames; } int Sprite::getFrameCount(){ return _frameCount; } void Sprite::setFrameCount(int frameCount){ _frameCount = frameCount; } int Sprite::getFrameDelay(){ return _frameDelay; } void Sprite::setFrameDelay(int frameDelay){ _frameDelay = frameDelay; } int Sprite::getAnimStartX(){ return _animStartX; } void Sprite::setAnimStartX(int animStartX){ _animStartX = animStartX; } int Sprite::getAnimStartY(){ return _animStartY; } void Sprite::setAnimStartY(int animStartY){ _animStartY = animStartY; } int Sprite::getFaceAngle(){ return _faceAngle; } void Sprite::setFaceAngle(int faceAngle){ _faceAngle = faceAngle; } int Sprite::getMoveAngle(){ return _moveAngle; } void Sprite::setMoveAngle(int moveAngle){ _moveAngle = moveAngle; } double Sprite::getX(){ return _x; } void Sprite::setX(double x){ _x = x; } double Sprite::getY(){ return _y; } void Sprite::setY(double y){ _y = y; } double Sprite::getSpeed(){ return _speed; } void Sprite::setSpeed(double speed){ _speed = speed; } double Sprite::getVelX(){ return _velX; } void Sprite::setVelX(double velX){ _velX = velX; } double Sprite::getVelY(){ return _velY; } void Sprite::setVelY(double velY){ _velY = velY; } bool Sprite::getPassLeftSideToLose() { return _passLeftSideToLose; } void Sprite::setPassLeftSideToLose(bool passLeftSideToLose) { _passLeftSideToLose = passLeftSideToLose; } BITMAP *Sprite::getImage(){ return _image; } void Sprite::setImage(BITMAP *image){ _image = image; }
Java
UTF-8
1,533
2.9375
3
[]
no_license
import org.junit.Test; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReplaceBannedWords { @Test public void readFile() throws FileNotFoundException { File bannedWords = new File("/Users/bothi/Desktop/banned_words.txt"); File prose = new File("/Users/bothi/Desktop/prose.txt"); Scanner sc = new Scanner(bannedWords); sc.skip("(\n" + "|[\n" + "\n" + "\u2028\u2029\u0085])?"); while (sc.hasNext()) { Trie.insert(sc.next()); } sc.close(); Scanner scanner = new Scanner(prose); scanner.skip("(\n" + "|[\n" + "\n" + "\u2028\u2029\u0085])?"); int wordLength=0; while (scanner.hasNextLine()) { String[] line = scanner.nextLine().split(" "); StringBuilder stringBuilder = new StringBuilder(line.length); int maxWidth=0; for (String word : line) { if (word.matches("[A-Za-z]+")) { if (Trie.search(word)) { word= new String(new char[word.length()]).replace('\0', '*'); } } maxWidth = maxWidth + word.length()+1; if(maxWidth <= 30) { System.out.print(word + " "); } else { System.out.println(); System.out.print(word + " "); maxWidth=word.length()+1; } } } } }
Java
UTF-8
1,037
2.828125
3
[]
no_license
package br.unipe.mlpIII.modelo; public class Aluno { protected String nome; protected double media; protected String matricula; protected int faltas; public Aluno(String nome,double media,String matricula,int faltas) { this.nome=nome; this.media=media; this.matricula=matricula; this.faltas=faltas; // TODO Auto-generated constructor stub } public int getFaltas() { return faltas; } public void setFaltas(int faltas) { this.faltas = faltas; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public double getMedia() { return media; } public void setMedia(double media) { this.media = media; } public String getMatricula() { return matricula; } public void setMatricula(String matricula) { this.matricula = matricula; } public String toString() { // TODO Auto-generated method stub return "matricula: "+matricula+" nome: "+ nome+" media: "+media+"\n"; } }
JavaScript
UTF-8
557
3.78125
4
[]
no_license
const dog={ name: "Baron", legs: 4 , color: "white" , age:5, bark (){ return "woof woof" ;}, // getDogInfo (){ // return `${this.name} is ${this.age} years old` // }, calcAge(){ let humanage=0; if(this.age>=2){ humanage=(2*10.5)+(this.age-2)*4; }else if(this.age==1){ humanage=10.5 } return humanage; }, getDogInfo (){ return `My name is ${this.name}.I am ${this.calcAge()} years old old in human years which is ${this.age} years old in dog years.` } } console.log(dog.getDogInfo());
C#
UTF-8
2,429
2.625
3
[ "MIT", "CC-BY-3.0-US", "CC-BY-3.0" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Collections.Generic; using System.Web.Http; using Microsoft.OData.Edm; namespace System.Web.OData.Routing { /// <summary> /// An <see cref="ODataPathSegment"/> implementation representing a dynamic property. /// </summary> public class DynamicPropertyPathSegment : ODataPathSegment { /// <summary> /// Initializes a new instance of the <see cref="DynamicPropertyPathSegment" /> class. /// </summary> /// <param name="propertyName">The name of the dynamic property.</param> public DynamicPropertyPathSegment(string propertyName) { if (propertyName == null) { throw Error.ArgumentNull("propertyName"); } PropertyName = propertyName; } /// <summary> /// Gets the name of the dynamic property. /// </summary> public string PropertyName { get; private set; } /// <summary> /// Gets the segment kind for the current segment. /// </summary> public override string SegmentKind { get { return ODataSegmentKinds.DynamicProperty; } } /// <inheritdoc/> public override IEdmType GetEdmType(IEdmType previousEdmType) { return null; } /// <inheritdoc/> public override IEdmNavigationSource GetNavigationSource(IEdmNavigationSource previousNavigationSource) { return null; } /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public override string ToString() { return PropertyName; } /// <inheritdoc/> public override bool TryMatch(ODataPathSegment pathSegment, IDictionary<string, object> values) { return pathSegment.SegmentKind == ODataSegmentKinds.DynamicProperty && ((DynamicPropertyPathSegment)pathSegment).PropertyName == PropertyName; } } }
Markdown
UTF-8
4,836
2.6875
3
[ "MIT" ]
permissive
\mainpage Main Page --- # MRAM click MRAM click features MRAM module which contains 262,144 magnetoresistive memory cells, organized into 32,768 bytes of memory. It means that MRAM click is a memory storage device with 32KB of memory space. <p align="center"> <img src="https://download.mikroe.com/images/click_for_ide/mram_click.png" height=300px> </p> [click Product page](https://www.mikroe.com/mram-click) --- #### Click library - **Author** : MikroE Team - **Date** : Dec 2019. - **Type** : SPI type # Software Support We provide a library for the MRAM Click as well as a demo application (example), developed using MikroElektronika [compilers](https://shop.mikroe.com/compilers). The demo can run on all the main MikroElektronika [development boards](https://shop.mikroe.com/development-boards). Package can be downloaded/installed directly form compilers IDE(recommended way), or downloaded from our LibStock, or found on mikroE github account. ## Library Description > This library contains API for MRAM Click driver. #### Standard key functions : - `mram_cfg_setup` Config Object Initialization function. ```c void mram_cfg_setup ( mram_cfg_t *cfg ); ``` - `mram_init` Initialization function. ```c err_t mram_init ( mram_t *ctx, mram_cfg_t *cfg ); ``` - `mram_default_cfg` Click Default Configuration function. ```c void mram_default_cfg ( mram_t *ctx ); ``` #### Example key functions : - `mram_write_data_bytes` Function writes n bytes of data from the buffer. ```c void mram_write_data_bytes ( mram_t *ctx, const uint16_t address, uint8_t *buffer, const uint16_t nBytes); ``` - `mram_read_data_bytes` Function reads n bytes of data and saves it in buffer. ```c void mram_read_data_bytes ( mram_t *ctx, const uint16_t address, uint8_t *buffer, const uint16_t n_bytes); ``` - `mram_enable_write_protect` Function enables or disables write protect. ```c void mram_enable_write_protect ( mram_t *ctx, uint8_t state); ``` ## Examples Description > This example writes and reads from the Mram Click and displays it on the terminal. **The demo application is composed of two sections :** ### Application Init > Initializes click driver. ```c void application_init ( void ) { log_cfg_t log_cfg; mram_cfg_t cfg; /** * Logger initialization. * Default baud rate: 115200 * Default log level: LOG_LEVEL_DEBUG * @note If USB_UART_RX and USB_UART_TX * are defined as HAL_PIN_NC, you will * need to define them manually for log to work. * See @b LOG_MAP_USB_UART macro definition for detailed explanation. */ LOG_MAP_USB_UART( log_cfg ); log_init( &logger, &log_cfg ); log_info( &logger, "---- Application Init ----" ); // Click initialization. mram_cfg_setup( &cfg ); MRAM_MAP_MIKROBUS( cfg, MIKROBUS_1 ); mram_init( &mram, &cfg ); mram_default_cfg( &mram ); } ``` ### Application Task > Writes 10 bytes of buffer data in memory with start address 0x0001. > Then reads 10 bytes from memory with start address 0x0001 and shows result on USB UART. ```c void application_task ( void ) { uint8_t number_bytes_write; uint8_t number_bytes_read; uint16_t i; uint8_t data_write[ 10 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; uint8_t data_read[ 20 ] = { 0 }; number_bytes_write = 10; number_bytes_read = 10; log_printf( &logger, " Data written!\r\n" ); mram_write_data_bytes ( &mram, 0x0001, data_write, number_bytes_write ); log_printf( &logger, " Read data:\r\n" ); mram_read_data_bytes ( &mram, 0x0001, data_read, number_bytes_read ); for ( i = 0; i < number_bytes_read; i++ ) { log_printf( &logger, "%d ", ( uint16_t )data_read[ i ] ); } log_printf( &logger, "\n" ); Delay_ms( 3000 ); } ``` The full application code, and ready to use projects can be installed directly form compilers IDE(recommneded) or found on LibStock page or mikroE GitHub accaunt. **Other mikroE Libraries used in the example:** - MikroSDK.Board - MikroSDK.Log - Click.MRAM **Additional notes and informations** Depending on the development board you are using, you may need [USB UART click](https://shop.mikroe.com/usb-uart-click), [USB UART 2 Click](https://shop.mikroe.com/usb-uart-2-click) or [RS232 Click](https://shop.mikroe.com/rs232-click) to connect to your PC, for development systems with no UART to USB interface available on the board. The terminal available in all Mikroelektronika [compilers](https://shop.mikroe.com/compilers), or any other terminal application of your choice, can be used to read the message. ---
Markdown
UTF-8
1,188
2.671875
3
[]
no_license
```yaml area: Cambridgeshire og: description: A man has died following a three-vehicle collision in Wansford yesterday. publish: date: 22 Apr 2020 title: Appeal following fatal collision in Wansford url: https://www.cambs.police.uk/news-and-appeals/appeal-following-fatal-collision-in-wansford-1 ``` A man has died following a three-vehicle collision in Wansford yesterday (21 April). At about 4pm, a red Renault Clio was travelling on the A47 when it was involved in a collision with a white Mazda 3SE and a silver Fiat Fullback. Emergency services attended and attempted to provide first aid, but despite their best efforts, the driver of the Mazda, a man in his 70s, died at the scene. A passenger in the Mazda was taken to Addenbrooke's Hospital where they remain in serious but stable condition. The driver of the Renault was also taken to hospital with serious, but not life threatening injuries. The driver of the Fiat was not injured. Anyone who witnessed the vehicles driving prior to the collision, or who has dashcam footage of the collision, is asked to call 101, quoting incident 300 of 21 April. Alternatively, you can report online at www.cambs.police.uk/report.
JavaScript
UTF-8
1,645
2.53125
3
[ "MIT" ]
permissive
// @flow import React, { Component } from 'react'; import $ from 'jquery'; // import timeago from '../../utils/timeago'; // const dateFormat = require('dateformat'); import type { Feedback } from '../../utils/globalTypes'; type Props = { feedback: Feedback, index: number, markClass: string, handleClick: (feedback: Feedback, index: number) => void }; class FeedbackListItem extends Component { onClick: (e: SyntheticMouseEvent) => void; constructor(props: Props) { super(props); this.onClick = this.onClick.bind(this); } onClick(e: SyntheticMouseEvent) { e.preventDefault(); const { feedback, handleClick, index } = this.props; handleClick(feedback, index); } render() { const { feedback, markClass } = this.props; let dateStr = $.timeago(feedback.createdAt); dateStr = dateStr.charAt(0).toUpperCase() + dateStr.slice(1); let quote; if (feedback.better.length < 72) { quote = feedback.better; } else { quote = `${feedback.better.substring(0, 72)}...`; } return ( <a href="#smodal" className="show-modal" onClick={this.onClick}> <div className={`${markClass} gli`}> <p className="string-date">{dateStr}</p> <div className="leftify play-ic"> <i className="fa fa-play-circle fa-5x" /> </div> <p>By {feedback.sender ? feedback.sender.username : 'User'}</p> <p> Overall: <span className="good-color">{feedback.overallUX}</span> </p> <p className="quote">{`"${quote}"`}</p> </div> </a> ); } } export default FeedbackListItem;
Markdown
UTF-8
1,461
3.671875
4
[]
no_license
在C#中,我们可以非常自由的、毫无限制的访问公有字段,但在一些场合中,我们可能希望限制只能给字段赋于某个范围的值、或是要求字段只能读或只能写,或是在改变字段时能改变对象的其他一些状态,这些单靠字段是无法做到的,于是就有了属性,属性中包含两个块:**set和get,set块负责属性的写入工作,get块负责属性的读取工作。**在两个块中都可以做一些其他操作,如在set中验证赋的值是否符合要求并决定是否进行赋值。当缺少其中一块时属性就只能读或只能写,set和get块中属性必需有一个,因为即不能读又不能写的属性是没有意义的。 ```java class MyClass { Private string name public string Name { get {return Name;} set {Name=value;} } } ``` 1. 属性可以保证安全,当不在本类中使用时可以保证使用属性名可以避免用字段的名字。 2. 属性的set和get函数可以限制字段的一些功能,以达到某种目的。 如: private int a=0; ``` public int A { get{return this.a;} set { if(value >= 0 && value <= 100) this.a=value; else throw new Exception("值的范围不合法。"); } } ``` 3.属性没有存储数据的功能,数据都存在字段中,所以只有修改字段的数据才能更改数据,修改属性的值没用。
C#
UTF-8
697
2.609375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Awesome_Meal_App_191546_181510 { public class EmployeeClass { public string EmployeeId { get; set; } public string LoginPassword{ get; set; } public EmployeeClass() { } public EmployeeClass(string EmployeeId, string LoginPassword) { this.EmployeeId = EmployeeId; this.LoginPassword = LoginPassword; } public override string ToString() { return string.Format("{0}", this.EmployeeId); } } }
Python
UTF-8
78
3.109375
3
[]
no_license
numbers = [47,95,88,73,88,84] print("Min value is: {}".format(min(numbers)))
Python
UTF-8
2,588
3
3
[]
no_license
from scipy import signal import matplotlib.pyplot as plt import numpy as np # fftfreq => gave corresponding freq from tx # fft => fourier transformation # abs => converted imaginary # to real # # fftshift => set zero at center # Number of test points N = 5000 # Fourier Transform of Signal # Select 1 for Inverse FFFT def Transform(signal, inverse): if inverse == 1: IFFT = np.fft.ifft(signal) return IFFT else: FFT = np.fft.fft(signal) return FFT # Converts FFT for Graphing def FFT_Graph(FFT): FFTG = np.fft.fftshift(abs(FFT)) FFTG = FFTG[N/2:] return FFTG # Creates Freq points for Freq Domain def Freq_points(tx): a = np.fft.fftshift(np.fft.fftfreq(tx.size, tx[1] - tx[0])) a = a[N/2:] return a # Fourier Transforms (FFT) # X points for functions (tx => Time Domain; vx => Freq Domain) tx = np.linspace(0, 2*np.pi, N) vx = Freq_points(tx) # First & Last 50 points (zeros) zero_out = np.zeros(N) zero_out[N/4 : (3*N)/4] = 1 # T means the Fourier Transformed fucntion # Create Signal f f = np.sin(2*np.pi*tx) f *= zero_out Tf = Transform(f, 0) # Create Signal g g = np.cos(2*np.pi*tx) g *= zero_out Tg= Transform(g, 0) # Convolution THM [f o g] & FFTs # Proof: T{f o g} = Tf * Tg # {f o g} ConV = np.convolve(f, g,'same') # T{f o g} TConV = Transform(ConV, 0) # Tf * Tg MT = Tf * Tg # Remove Multi-Line comment to show Proof of Equivalence """ MTG = FFT_Graph(MT) TConVG = FFT_Graph(TConV) plt.figure(5) plt.plot(vx, MTG, 'r', vx, TConVG, 'y') """ # Proof: {f o g} = T^-1{Tf * Tg} # T^-1{Tf * Tg} ITMT = Transform(MT, 1) # Remove Multi-Line comment to show Proof of Equivalence """ plt.figure(6) plt.plot(tx, ConV, 'r', tx, np.fft.fftshift(ITMT), 'b' ) """ # Remove Multi-Line comment to show graphs of Time & Freq of f & g """ TgG = FFT_Graph(Tg) TfG = FFT_Graph(Tf) plt.figure(1) plt.plot(vx, TfG,'k') plt.title('Frequency Domain of F') plt.xlabel('Frequency') plt.figure(2) plt.plot(tx,f,'k') plt.title('Time Domain of F') plt.xlabel('Time') plt.figure(3) plt.plot(vx, TgG,'b') plt.title('Frequency Domain of G') plt.xlabel('Frequency') plt.figure(4) plt.plot(tx,g,'b') plt.title('Time Domain of G') plt.xlabel('Time') """ plt.grid() plt.show()
Java
UTF-8
1,941
2.296875
2
[ "MIT" ]
permissive
package com.example.konrad.start_app; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import android.view.View; import android.widget.LinearLayout; import com.example.konrad.start_app.loginandregister.Login; /** * Pierwsze okno po uruchomieniu aplikacji */ public class MainActivity extends AppCompatActivity { private static final int PERMISSIONINT =1; public ImageView imageStart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageStart = (ImageView) findViewById(R.id.imageview1); imageStart.setImageResource(R.drawable.primary_logo_on_transparent_282x69); // ustawienie urprawnien dla aplikacji getperm(); // Pobranie z view layouta oraz utworznie onClick listenera LinearLayout xx = (LinearLayout)findViewById(R.id.glowny_lay); xx.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Login.class); //Przejscie do klasy rejestracji // Start nowej aktywnosci startActivity(intent); finish(); } }); } /** * Ustawia uprawnienia dla aplikacji */ public void getperm() { if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE},PERMISSIONINT ); } } }
Ruby
UTF-8
3,230
3.140625
3
[]
no_license
# require 'pry' # add a constructor shortcut to hash containing initial data class DataHash < Hash def initialize(probability = '0.0', credits = '0', total_probab = 0) end_of_range = total_probab + (probability.to_f * 10).to_i - 1 self[:probability] = probability.to_f / 100 self[:credits] = credits.to_f self[:random_range] = total_probab..end_of_range end end # add statistic methods to stats array class DataStats < Array def sum inject(0) { |accum, i| accum + i } end def mean sum / length.to_f end def sample_variance m = mean sum = inject(0) { |accum, i| accum + (i - m)**2 } sum / (length - 1).to_f end def standard_deviation Math.sqrt(sample_variance) end end # convert data from string form def stats_and_paylines_from_str(str) data = {} total_probab = 0 str.split(/\n\r?/).each do |text| slices = text.split(/(% \-| - | )+/) data[slices[0].to_i] = DataHash.new(slices[2], slices[4], total_probab) total_probab += (slices[2].to_f * 10).to_i end data end def simulate(payin, paylines) payout = 0.0 1.upto(payin.to_i).each do random_n = rand(1000) face = paylines.find { |_, pl| pl[:random_range].include?(random_n) }[0] payout += paylines[face][:credits] # || 0 # if !paylines[face].nil? end payout * 100 / payin end # print scores of calculation and Simulations, returns payback_percent def print_scores(payout, payin, debug) debug = debug.sort.to_h payback_percent = payout * 100 / payin puts "\nPayed out: #{payout}" puts "Payed in: #{payin}" puts "\nPayback % = #{format('%.6f', payback_percent)} % \n" puts "Occurance payloads: #{debug}" end ROUNDS_IN_GAME_CONST = 2_000.0 SIMULATIONS_NUMBER_CONST = 1_000 # border t-student value of 1_000 samples and 90% confidence level: 1,6449 TSTUDENT_VALUE_CONST = 1.644_9 payline_data = "0 - 15% - 3 credits payout 1 - 65% - 0 credits 2 - 7% - 2 credits 3 - 3% - 15 credits 4 - 1% - 1 credit 5 - 2% - 1.5 credits 6 - 1.5% - 4 credits 7 - 1.5% - 5 credits 8 - 3% - 7 credits 9 - 1% - 55 credits" paylines = stats_and_paylines_from_str(payline_data) puts "Paylines: #{paylines}\n" payout = 0.0 debug = {} paylines.each do |face, data| debug[face] = data[:probability] * ROUNDS_IN_GAME_CONST.to_i payout += data[:probability] * data[:credits] * ROUNDS_IN_GAME_CONST end print_scores(payout, ROUNDS_IN_GAME_CONST, debug) simulation_payloads = DataStats.new(SIMULATIONS_NUMBER_CONST) simulation_payloads.each_with_index do |_, index| simulation_payloads[index] = simulate(ROUNDS_IN_GAME_CONST, paylines) end puts "\nSimulations scores" # (less format)" # IO.popen('less', 'w') { |f| f.puts simulation_payloads } # puts 'was shown' puts "Mean: #{simulation_payloads.mean}" puts "Standard deviation: #{simulation_payloads.standard_deviation}" result_max = simulation_payloads.mean + (simulation_payloads.standard_deviation * TSTUDENT_VALUE_CONST) / Math.sqrt(SIMULATIONS_NUMBER_CONST.to_f) result_min = simulation_payloads.mean - (simulation_payloads.standard_deviation * TSTUDENT_VALUE_CONST) / Math.sqrt(SIMULATIONS_NUMBER_CONST.to_f) puts "\nPayload range: #{result_min} .. #{result_max}"
Java
UTF-8
2,562
2.1875
2
[]
no_license
package com.qtone.hdkt.model.classes; import java.util.Date; public class ClassLesson { private Integer id; private Integer classId; private String name; private String date; private String startTime; private String endTime; private Integer status; private String scheduleNum; private Integer sort; private Date createTime; private Date updateTime; private Date deleteTime; private Integer isDeleted; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getClassId() { return classId; } public void setClassId(Integer classId) { this.classId = classId; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getDate() { return date; } public void setDate(String date) { this.date = date == null ? null : date.trim(); } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime == null ? null : startTime.trim(); } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime == null ? null : endTime.trim(); } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getScheduleNum() { return scheduleNum; } public void setScheduleNum(String scheduleNum) { this.scheduleNum = scheduleNum == null ? null : scheduleNum.trim(); } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Date getDeleteTime() { return deleteTime; } public void setDeleteTime(Date deleteTime) { this.deleteTime = deleteTime; } public Integer getIsDeleted() { return isDeleted; } public void setIsDeleted(Integer isDeleted) { this.isDeleted = isDeleted; } }
Shell
UTF-8
5,542
3.890625
4
[]
no_license
#!/bin/bash ######################################################### # # Matthew Page # 11/20/2014 # CSCS 1730 # # timeonline - a script to caclulate number of logins # and time online. # ######################################################### #establishing user if [ $# -eq 1 ];then userexists=`last | grep $1` if [ "$userexists" == "" ];then echo "¡NO BUENO! User $1 does not exist!" exit 0 fi person=$1 else person=$(echo $USER) fi echo "Please wait...Processing..." #variables for number of logins per month auglogins=`last | grep $person | grep Aug | wc -l` seplogins=`last | grep $person | grep Sep | wc -l` octlogins=`last | grep $person | grep Oct | wc -l` novlogins=`last | grep $person | grep Nov | wc -l` declogins=`last | grep $person | grep Dec | wc -l` totallogins=$(echo "($auglogins + $seplogins + $octlogins + $novlogins + $declogins)" | bc -l) #searching for logins that contain more than a day (denoted by a plus sign) and totaling those days days=`last | grep $person | grep '+' | cut -d '(' -f2 | cut -d '+' -f1` totaldays=`echo $days | xargs | sed 's/\ /+/g' | bc -l` #searching for logins hours and minutes sections within the subset of logins that have more than a day #(denoted by a plus sign) and totaling them hoursfrompluslines=`last | grep $person | cut -d '(' -f2 | grep '+' | cut -d '+' -f2 | cut -d ':' -f1 | xargs | sed 's/\ /+/g' | bc -l` minutesfrompluslines=`last | grep $person | cut -d '(' -f2 | grep '+' | cut -d '+' -f2 | cut -d ':' -f2 | cut -d ')' -f1 | xargs | sed 's/\ /+/g' | bc -l` #some users have no plus signs (multiple day logins) so their value of the following three variables was #an empty srting so i had to check for that then set those empty string variabels to 0's if [ "$hoursfrompluslines" == "" ];then hoursfrompluslines=0 fi if [ "$minutesfrompluslines" == "" ];then minutesfrompluslines=0 fi if [ "$totaldays" == "" ];then totaldays=0 fi #searching for logins hours and minutes sections outside the subset of logins that have more than a day #(denoted by a plus sign) and totaling them hoursfromNONpluslines=`last | grep $person | grep -v '+' | grep -v "still logged in" | grep -v "gone - no logout" | cut -d '(' -f2 | cut -d ':' -f1 | xargs | sed 's/\ /+/g' | bc -l` minutesfromNONpluslines=`last | grep $person | grep -v '+' | grep -v "still logged in" | grep -v "gone - no logout" | cut -d '(' -f2 | cut -d ':' -f2 | cut -d ')' -f1 | xargs | sed 's/\ /+/g' | bc -l` #adding up the seperated 2 subsets of hours and minutes to get total hours and total minutes variables, #however called "unrefined" referring to them not being converted up, (i.e. 123 minutes would be 2 hours # and 3 minutes ultimately later) unrefinedhours=$(echo "($hoursfrompluslines+$hoursfromNONpluslines)" | bc -l) unrefinedminutes=$(echo "($minutesfrompluslines+$minutesfromNONpluslines)" | bc -l) #loop to convert up minutes to hours after every 60 minutes totalminutes=0 while [ $unrefinedminutes -ge 60 ];do unrefinedminutes=$(echo "($unrefinedminutes-60)" | bc -l) unrefinedhours=$(echo "($unrefinedhours+1)" | bc -l) totalminutes=$(echo $unrefinedminutes) done #loop to convert up hours to days fter every 24 hours totalhours=0 while [ $unrefinedhours -ge 24 ];do unrefinedhours=$(echo "($unrefinedhours-24)" | bc -l) totaldays=$(echo "($totaldays+1)" | bc -l) totalhours=$(echo $unrefinedhours) done #loop to print a star for every 10 logins in august augtemp=$(echo $auglogins) augstars=$(echo "") while [ $augtemp -ge 10 ];do augtemp=$(echo "($augtemp-10)" | bc -l) augstars=$(echo $augstars+"*") done #loop to print a star for every 10 logins in september septemp=$(echo $seplogins) sepstars=$(echo "") while [ $septemp -ge 10 ];do septemp=$(echo "($septemp-10)" | bc -l) sepstars=$(echo $sepstars+"*") done #loop to print a star for every 10 logins in october octtemp=$(echo $octlogins) octstars=$(echo "") while [ $octtemp -ge 10 ];do octtemp=$(echo "($octtemp-10)" | bc -l) octstars=$(echo $octstars+"*") done #loop to print a star for every 10 logins in november novtemp=$(echo $novlogins) novstars=$(echo "") while [ $novtemp -ge 10 ];do novtemp=$(echo "($novtemp-10)" | bc -l) novstars=$(echo $novstars+"*") done #loop to print a star for every 10 logins in december dectemp=$(echo $declogins) decstars=$(echo "") while [ $dectemp -ge 10 ];do dectemp=$(echo "($dectemp-10)" | bc -l) decstars=$(echo $decstars+"*") done #loop to print a star for every 10 logins in total logins section totaltemp=$(echo $totallogins) totalstars=$(echo "") while [ $totaltemp -ge 10 ];do totaltemp=$(echo "($totaltemp-10)" | bc -l) totalstars=$(echo $totalstars+"*") done #final output section echo "_____________________________" echo " USER : $person " echo "_____________________________" echo " Total Login Time: " echo "_____________________________" echo " Days: | $totaldays" echo " Hours: | $totalhours" echo " Minutes | $totalminutes" echo "_____________________________" echo " Total Logins Per Month: " echo "_____________________________" echo " Aug | `echo $augstars | sed 's/+//g'` $auglogins" echo " Sep | `echo $sepstars | sed 's/+//g'` $seplogins" echo " Oct | `echo $octstars | sed 's/+//g'` $octlogins" echo " Nov | `echo $novstars | sed 's/+//g'` $novlogins" echo " Dec | `echo $decstars | sed 's/+//g'` $declogins" echo "_____________________________" echo " TOTAL : `echo $totalstars | sed 's/+//g'` $totallogins"
C++
UTF-8
6,150
2.65625
3
[ "MIT" ]
permissive
// // Copyright (c) 1999-2014 Jean-Luc Thiffeault <jeanluc@mailaps.org> // // See the file LICENSE for copying permission. // #include <iostream> #include <vector> #include <complex> #include <cassert> #include <cmath> #include <jlt/matrix.hpp> #include <jlt/stlio.hpp> #include <jlt/math.hpp> class ADrwave { private: const int N, NN, N2, NT; const double D, U, L, T, T2, ULc; static const int r = 0, i = 1; public: [[nodiscard]] int pk(const int m, const int n, const int ri) const; void ipk(const int row, int& m, int& n, int& ri) const; ADrwave(int N_, double D_, double U_ = 1, double L_ = 1, double T_ = 1) : N(N_), NN(2*N+1), N2(2*N*(N+1)), NT(2*N2), D(4*M_PI*M_PI*D_/(L_*L_)), U(U_), L(L_), T(T_), T2(0.5*T), ULc(M_SQRT2*M_PI*(U/L)) {} void operator()(double t, const std::vector<double>& y, std::vector<double>& y_dot) { static double X1, X2; static int it0 = -1; double dt = jlt::Mod(t,T); int it = (int)(t/T); // Generate random angles at first, or if we reach a new interval. // This is dangerous if integrating backwards in time. if (it != it0 || it0 == -1) { X1 = 2*M_PI * ((double)random() / RAND_MAX); X2 = 2*M_PI * ((double)random() / RAND_MAX); it0 = it; } // Diffusion term. for (int row = 0; row < size(); ++row) { int m, n, ri; ipk(row,m,n,ri); y_dot[row] = -D*(m*m + n*n) * y[row]; } for (int row = 0; row < size(); ++row) y_dot[row] = 0; if (std::abs(dt) < T2) { // y-dependent wave in x direction. double cX1 = std::cos(X1), sX1 = std::sin(X1); for (int m = 1; m <= N; ++m) { for (int n = -N; n <= N; ++n) { // Real coefficients. { double term1 = 0, term2 = 0; if (n+1 <= N) term1 = cX1*y[pk(m,n+1,r)] - sX1*y[pk(m,n+1,i)]; if (n-1 >= -N) term2 = cX1*y[pk(m,n-1,r)] + sX1*y[pk(m,n-1,i)]; y_dot[pk(m,n,r)] += -ULc * m * (term1 - term2); } // Imaginary coefficients. { double term1 = 0, term2 = 0; if (n+1 <= N) term1 = cX1*y[pk(m,n+1,i)] + sX1*y[pk(m,n+1,r)]; if (n-1 >= -N) term2 = cX1*y[pk(m,n-1,i)] - sX1*y[pk(m,n-1,r)]; y_dot[pk(m,n,i)] += -ULc * m * (term1 - term2); } } } } else { // x-dependent wave in y direction. double cX2 = std::cos(X2), sX2 = std::sin(X2); for (int m = 1; m <= N; ++m) { for (int n = -N; n <= N; ++n) { if (n != 0) { // Real coefficients. { double term1 = 0, term2 = 0; if (m+1 <= N) term1 = cX2*y[pk(m+1,n,r)] - sX2*y[pk(m+1,n,i)]; if (m-1 == 0 && n < 0) term2 = cX2*y[pk(0,-n,r)] - sX2*y[pk(0,-n,i)]; else term2 = cX2*y[pk(m-1,n,r)] + sX2*y[pk(m-1,n,i)]; y_dot[pk(m,n,r)] += -ULc * n * (term1 - term2); } // Imaginary coefficients. { double term1 = 0, term2 = 0; if (m+1 <= N) term1 = cX2*y[pk(m+1,n,i)] + sX2*y[pk(m+1,n,r)]; if (m-1 == 0 && n < 0) term2 = -cX2*y[pk(0,-n,i)] - sX2*y[pk(0,-n,r)]; else term2 = cX2*y[pk(m-1,n,i)] - sX2*y[pk(m-1,n,r)]; y_dot[pk(m,n,i)] += -ULc * n * (term1 - term2); } } } } // The m=0 coefficients. for (int n = 1; n <= N; ++n) { // Real coefficients. { double term1 = cX2*y[pk(1,n,r)] - sX2*y[pk(1,n,i)]; double term2 = cX2*y[pk(1,-n,r)] - sX2*y[pk(1,-n,i)]; y_dot[pk(0,n,r)] += -ULc * n * (term1 - term2); } // Imaginary coefficients. { double term1 = cX2*y[pk(1,n,i)] + sX2*y[pk(1,n,r)]; double term2 = -cX2*y[pk(1,-n,i)] - sX2*y[pk(1,-n,r)]; y_dot[pk(0,n,i)] += -ULc * n * (term1 - term2); } } } // Source: s(x) = S sqrt(2) sin(2pi x/L). // S should be passed to the class, as should optionally a forcing vector. double S = 1; y_dot[pk(1,0,i)] += S * (-M_SQRT1_2); } void Jacobian(double t, const std::vector<double>& y, const std::vector<double>& y_dot, const double scale, jlt::matrix<double>& Jac) { // The Jacobian matrix is sparse. Inefficient for implicit methods. } void toMode(const std::vector<double> y, jlt::matrix<std::complex<double> >& Th) { Th(0,0) = 0; for (int n = 1; n <= N; ++n) { Th(N+0,N+n) = std::complex<double>(y[pk(0,n,r)],y[pk(0,n,i)]); } for (int m = 1; m <= N; ++m) { for (int n = -N; n <= N; ++n) { Th(N+m,N+n) = std::complex<double>(y[pk(m,n,r)],y[pk(m,n,i)]); } } for (int n = -N; n <= -1; ++n) { Th(N+0,N+n) = std::complex<double>(y[pk(0,-n,r)],-y[pk(0,-n,i)]); } for (int m = -N; m <= -1; ++m) { for (int n = -N; n <= N; ++n) { Th(N+m,N+n) = std::complex<double>(y[pk(-m,-n,r)],-y[pk(-m,-n,i)]); } } } std::ostream& printModeList(const std::vector<double>& y, std::ostream& strm) const { for (int n = 1; n <= N; ++n) { strm << 0 << "\t" << n << "\t"; strm << y[pk(0,n,r)] << "\t" << y[pk(0,n,i)] << std::endl; } for (int m = 1; m <= N; ++m) { for (int n = -N; n <= N; ++n) { strm << m << "\t" << n << "\t"; strm << y[pk(m,n,r)] << "\t" << y[pk(m,n,i)] << std::endl; } } return strm; } double variance(const std::vector<double>& y) { double var = 0; for (int n = 1; n <= N; ++n) { var += pow(y[pk(0,n,r)],2) + pow(y[pk(0,n,i)],2); } for (int m = 1; m <= N; ++m) { for (int n = -N; n <= N; ++n) { var += pow(y[pk(m,n,r)],2) + pow(y[pk(m,n,i)],2); } } var *= 2; return var; } // Largest mode number. [[nodiscard]] int msize() const { return N; } // Total size of system. [[nodiscard]] int size() const { return NT; } }; inline int ADrwave::pk(const int m, const int n, const int ri) const { assert(ri == 0 || ri == 1); assert(m <= N && n <= N); assert((m > 0 && n >= -N) || (m == 0 && n > 0)); int b = ri*N2; if (m == 0) { return (b + n-1); } b += N; return (b + NN*(m-1) + N + n); } inline void ADrwave::ipk(const int row, int& m, int& n, int& ri) const { assert(row >=0 && row < 2*N2); ri = row / N2; int r = row % N2; if (r < N) { m = 0; n = r+1; return; } r -= N; n = (r % NN) - N; m = (r / NN) + 1; }
Swift
UTF-8
1,134
3.609375
4
[]
no_license
// // WordTypeProtocol.swift // TypesOfWords // // Created by Raluca Ionescu on 5/9/19. // Copyright © 2019 Raluca Ionescu. All rights reserved. // import Foundation class WordTypeClass { private let dictionary: [InputDictionary] private let outputProtocol = InteractiveOutputStrategy() init(inputDictionary: [InputDictionary]){ self.dictionary = inputDictionary } func wordVerify() { var result: Bool = false let optionType = dictionary[0].optionType if optionType == .palindrome { result = self.isPalindrome(firstWord: dictionary[0].word) } else if optionType == .anagram { result = self.isAnagram(firstWord: dictionary[0].word, secondWord: dictionary[1].word) } outputProtocol.write(result: result, type: optionType) } } extension WordTypeClass{ func isAnagram(firstWord: String, secondWord: String) -> Bool{ return firstWord.isAnagramOf(secondWord) ? true : false } func isPalindrome(firstWord: String) -> Bool { return firstWord.isPalindrome() ? true : false } }
Python
UTF-8
392
3.1875
3
[]
no_license
# Uses python3 import sys import numpy as np def get_change(W): #write your code here c=0 while W!=0: if W >= 10: w1 = 10 elif W>=5 : w1 = 5 elif W>= 1: w1 =1 a = np.minimum(w1,W) W = W- a c = c+ 1 return c if __name__ == '__main__': m = int(sys.stdin.read()) print(get_change(m))
Java
UTF-8
19,144
2.03125
2
[ "MIT" ]
permissive
package com.zys.pilu.utils; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.provider.MediaStore; import android.util.Log; import com.zys.pilu.R; import com.zys.pilu.common.AppContext; import com.zys.pilu.common.Constants; import com.zys.pilu.db.DBManager; import com.zys.pilu.models.Artist; import com.zys.pilu.models.Song; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by zys on 2016/7/9. */ public class SongProvider { private final static String TAG = "SongProvider"; private static final Uri albumArtUri = Uri.parse("content://media/external/audio/albumart"); private static List<Song> songList = null; private static List<Artist> artistList = null; private static List<Song> recommendList = null; private static Map<Long, Song> songIdMap; private static Map<String, Artist> artistMap; private static DBManager dbMgr = new DBManager(); private static Context context = AppContext.getInstance(); public static List<Song> getSongList() { if (songList == null) { updateSongList(); } return songList; } static private void updateSongList() { songList = new ArrayList<>(); artistList = new ArrayList<>(); songIdMap = new HashMap<>(); artistMap = new HashMap<>(); MediaMetadataRetriever mmr = new MediaMetadataRetriever(); Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null); while (cursor.moveToNext()) { try { long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID)); byte[] data = cursor.getBlob(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)); String fileName = new String(data, 0, data.length - 1); mmr.setDataSource(fileName); String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)); // test String pinyin = PinYinUtil.getPinYinFromHanYu(name, PinYinUtil.UPPER_CASE, PinYinUtil.WITH_TONE_NUMBER, PinYinUtil.WITH_V); String artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST); if (artist == null) artist = "(无名)"; String album = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM); int duration = Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)); int size = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE)); long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)); String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)); // Store the Song Info Song newSong = new Song(id, name, fileName, size, album, artist, duration, albumId, url, pinyin); songIdMap.put(id, newSong); songList.add(newSong); //Init the DB if (!dbMgr.inSongDetail(newSong)) { dbMgr.addToSongDetail(newSong); } // Store the Artist Info if (!artistMap.containsKey(artist)) { Artist artistItem = new Artist(artist); artistItem.addSong(newSong); artistList.add(artistItem); artistMap.put(artist, artistItem); } else { artistMap.get(artist).addSong(newSong); } } catch (Exception e) { e.printStackTrace(); } } cursor.close(); sortSongByPinyin(songList); sortArtistByPinyin(artistList); } /* * Get SongList by Artist Name. */ public static List<Song> getSongListByArtist(String artist) { if (songList == null) { getSongList(); } //List<Song> songListOfArtist = new ArrayList<Song>(); Artist temp = artistMap.get(artist); sortSongByPinyin(temp.getSongListOfArtist()); return temp.getSongListOfArtist(); } /* * Get ArtistList */ public static List<Artist> getArtistList() { if (artistList == null) { getSongList(); } return artistList; } /* * Get Favorite List */ public static List<Song> getFavoriteList() { if (songList == null) { getSongList(); } List<Song> favoriteSongList = new ArrayList<Song>(); for (int i = 0 ; i < songList.size() ; i++) { if (dbMgr.isFavorite(songList.get(i))) { favoriteSongList.add(songList.get(i)); } } return favoriteSongList; } /* * Get FavoriteArtist List */ public static List<Artist> getFavoriteArtistList() { if (songList == null) { getSongList(); } List<Artist> favoriteArtistSongList = new ArrayList<Artist>(); for (int i = 0 ; i < artistList.size() ; i++) { if (dbMgr.isFavoriteArtist(artistList.get(i).getName())) { favoriteArtistSongList.add(artistList.get(i)); } } return favoriteArtistSongList; } /* * Get SongList By SongList Name */ public static List<Song> getSongListByName(String listName) { if (songList == null) getSongList(); List<Song> listOfName = new ArrayList<>(); if (listName.equals(Constants.ListName.LIST_FAVORITE)) { listOfName = getFavoriteList(); } else if (listName.equals(Constants.ListName.LIST_ALL)) { listOfName = getSongList(); } else if (listName.equals(Constants.ListName.LIST_RECENTLY)){ listOfName = getRecentlySongs(); } else if (listName.equals(Constants.ListName.LIST_AGO)) { listOfName = getAgoSongs(); } else if (listName.equals(Constants.ListName.LIST_RECOMMEND)) { listOfName = getRecommedSongs(); } else { listOfName = getSongListByArtist(listName); } return listOfName; } /* * Get 10 Songs which are Recommed */ public static List<Song> getRecommedSongs() { if (recommendList == null) updateRecommedSongs(); return recommendList; } /* * Update 10 Songs which are Recommed */ public static List<Song> updateRecommedSongs() { if (recommendList == null) recommendList = new ArrayList<>(); else recommendList.clear(); SharedPreferences preferences = AppContext.getInstance().getSharedPreferences(Constants.Preferences.PREFERENCES_KEY, Context.MODE_PRIVATE); int progressFS = preferences.getInt(Constants.Preferences.PREFERENCES_ADJUST_FAVORITE_SONG, 50); int progressFA = preferences.getInt(Constants.Preferences.PREFERENCES_ADJUST_FAVORITE_ARTIST, 50); int progressR = preferences.getInt(Constants.Preferences.PREFERENCES_ADJUST_RECENT, 50); int progressA = preferences.getInt(Constants.Preferences.PREFERENCES_ADJUST_AGO, 50); // Prevent Rate = 0 float sum = progressA + progressFA + progressFS + progressR + 40; float rateFA = (progressFA + 10) /sum; float rateFS = (progressFS + 10) /sum; float rateR = (progressR + 10) /sum; float rateA = (progressA + 10) /sum; Set<Song> set = new HashSet<>(); List<Song> listFA = new ArrayList<>(); List<Song> listFS = getFavoriteList(); List<Song> listR = getRecentlySongs(); List<Song> listA = getAgoSongs(); List<Artist>artistList = SongProvider.getFavoriteArtistList(); for (int i = 0 ; i < artistList.size() ; i++) { for (int j = 0 ; j < artistList.get(i).getSongListOfArtist().size() ; j++) { listFA.add(artistList.get(i).getSongListOfArtist().get(j)); } } // If the Count of All Songs Is Below 10 if (listR.size() < 10) { Log.e(TAG, "listR.size = " + listR.size()); return listR; } // Prevent Endless Loop int maxLoopCount = 100; while (set.size() < 10 && maxLoopCount > 0) { double randNum = Math.random(); if (randNum < rateFA && listFA.size() != 0) { //Log.e(TAG, "cata : 喜欢的歌手" + listFA.get((int)(Math.random()*listFA.size())).getName()); set.add(listFA.get((int)(Math.random()*listFA.size()))); } else if (randNum >= rateFA && randNum < rateFA+rateFS && listFS.size() != 0) { //Log.e(TAG, "cata : 收藏的歌曲" + listFS.get((int)(Math.random()*listFS.size())).getName()); set.add(listFS.get((int)(Math.random()*listFS.size()))); } else if (randNum >= rateFA+rateFS && randNum < rateFA+rateFS+rateR) { //Log.e(TAG, "cata : 最近听过" + listR.get((int)(Math.random()*listR.size())).getName()); set.add(listR.get((int)(Math.random()*listR.size()))); } else if (randNum >= rateFA+rateFS+rateR && randNum < 1){ //Log.e(TAG, "cata : 很久没听" + listA.get((int)(Math.random()*listA.size())).getName()); set.add(listA.get((int)(Math.random()*listA.size()))); } else { double randNum1 = Math.random(); if (randNum1 < 0.5) { //Log.e(TAG, "cata : 最近听过2" + listR.get((int)(Math.random()*listR.size())).getName()); set.add(listR.get((int)(Math.random()*listR.size()))); } else { //Log.e(TAG, "cata : 很久没听2" + listA.get((int)(Math.random()*listA.size())).getName()); set.add(listA.get((int)(Math.random()*listA.size()))); } } maxLoopCount--; //Log.e(TAG, "maxLoopCount = " + maxLoopCount); } for (int i = 0 ; i < set.size() ; i++) recommendList.add(songList.get(i)); sortSongByPinyin(recommendList); return recommendList; } /* * Get 10 Songs which are Listened Least */ public static List<Song> getAgoSongs() { List<Song> list = new ArrayList<>(); Cursor c = dbMgr.getAgoSongs(); while(c.moveToNext()) { long songId = c.getLong(c.getColumnIndex("song_id")); Song temp = getSongById(songId); if (temp != null) { list.add(temp); // Set Date temp.setDate(c.getString(c.getColumnIndex("time_string"))); } else { dbMgr.deleteFromSongDetailById(songId); } } c.close(); sortSongByPinyin(list); return list; } /* * Get 10 Songs which are Listened Recently */ public static List<Song> getRecentlySongs() { List<Song> list = new ArrayList<>(); Cursor c = dbMgr.getRecentlySongs(); while(c.moveToNext()) { long songId = c.getLong(c.getColumnIndex("song_id")); Song temp = getSongById(songId); if (temp != null) { list.add(temp); // Set Date temp.setDate(c.getString(c.getColumnIndex("time_string"))); } else { dbMgr.deleteFromSongDetailById(songId); } } c.close(); sortSongByPinyin(list); return list; } /* * Sort a List By Pinyin */ public static void sortSongByPinyin(List<Song> list) { Collections.sort(list); } /* * Sort a ArtistList By Pinyin */ public static void sortArtistByPinyin(List<Artist> list) { Collections.sort(list); } /* * Get the Song with Id */ public static Song getSongById(Long id) { if (songList == null) getSongList(); return songIdMap.get(id); } public static Bitmap getDefaultArtwork(Context context, boolean small) { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.RGB_565; if(small){ return BitmapFactory.decodeResource(context.getResources(), R.drawable.default_album_small); } return BitmapFactory.decodeResource(context.getResources(), R.drawable.default_album); } /** * 从文件当中获取专辑封面位图 * @param context * @param songid * @param albumid * @return */ private static Bitmap getArtworkFromFile(Context context, long songid, long albumid){ Bitmap bm = null; if(albumid < 0 && songid < 0) { throw new IllegalArgumentException("Must specify an album or a song id"); } try { BitmapFactory.Options options = new BitmapFactory.Options(); FileDescriptor fd = null; if(albumid < 0){ Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart"); ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r"); if(pfd != null) { fd = pfd.getFileDescriptor(); } } else { Uri uri = ContentUris.withAppendedId(albumArtUri, albumid); ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r"); if(pfd != null) { fd = pfd.getFileDescriptor(); } } options.inSampleSize = 1; // 只进行大小判断 options.inJustDecodeBounds = true; // 调用此方法得到options得到图片大小 BitmapFactory.decodeFileDescriptor(fd, null, options); // 我们的目标是在800pixel的画面上显示 // 所以需要调用computeSampleSize得到图片缩放的比例 options.inSampleSize = 100; // 我们得到了缩放的比例,现在开始正式读入Bitmap数据 options.inJustDecodeBounds = false; options.inDither = false; options.inPreferredConfig = Bitmap.Config.ARGB_8888; //根据options参数,减少所需要的内存 bm = BitmapFactory.decodeFileDescriptor(fd, null, options); } catch (FileNotFoundException e) { e.printStackTrace(); } return bm; } /** * 获取专辑封面位图对象 * @param context * @param song_id * @param album_id * @param allowdefalut * @return */ public static Bitmap getArtwork(Context context, long song_id, long album_id, boolean allowdefalut, boolean small){ if(album_id < 0) { if(song_id < 0) { Bitmap bm = getArtworkFromFile(context, song_id, -1); if(bm != null) { return bm; } } if(allowdefalut) { return getDefaultArtwork(context, small); } return null; } ContentResolver res = context.getContentResolver(); Uri uri = ContentUris.withAppendedId(albumArtUri, album_id); if(uri != null) { InputStream in = null; try { in = res.openInputStream(uri); BitmapFactory.Options options = new BitmapFactory.Options(); //先制定原始大小 options.inSampleSize = 1; //只进行大小判断 options.inJustDecodeBounds = true; //调用此方法得到options得到图片的大小 BitmapFactory.decodeStream(in, null, options); /** 我们的目标是在你N pixel的画面上显示。 所以需要调用computeSampleSize得到图片缩放的比例 **/ /** 这里的target为800是根据默认专辑图片大小决定的,800只是测试数字但是试验后发现完美的结合 **/ if(small){ options.inSampleSize = computeSampleSize(options, 60); } else{ options.inSampleSize = computeSampleSize(options, 600); } // 我们得到了缩放比例,现在开始正式读入Bitmap数据 options.inJustDecodeBounds = false; options.inDither = false; options.inPreferredConfig = Bitmap.Config.ARGB_8888; in = res.openInputStream(uri); return BitmapFactory.decodeStream(in, null, options); } catch (FileNotFoundException e) { Bitmap bm = getArtworkFromFile(context, song_id, album_id); if(bm != null) { if(bm.getConfig() == null) { bm = bm.copy(Bitmap.Config.RGB_565, false); if(bm == null && allowdefalut) { return getDefaultArtwork(context, small); } } } else if(allowdefalut) { bm = getDefaultArtwork(context, small); } return bm; } finally { try { if(in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } } return null; } /** * 对图片进行合适的缩放 * @param options * @param target * @return */ public static int computeSampleSize(BitmapFactory.Options options, int target) { int w = options.outWidth; int h = options.outHeight; int candidateW = w / target; int candidateH = h / target; int candidate = Math.max(candidateW, candidateH); if(candidate == 0) { return 1; } if(candidate > 1) { if((w > target) && (w / candidate) < target) { candidate -= 1; } } if(candidate > 1) { if((h > target) && (h / candidate) < target) { candidate -= 1; } } return candidate; } }
Java
UTF-8
1,943
2.140625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2013-2021, Bingo.Chen (finesoft@gmail.com). * * 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.corant.modules.jcache.shared; import java.util.Arrays; import java.util.function.Function; import javax.cache.annotation.GeneratedCacheKey; /** * corant-modules-jcache-shared * * @author bingo 下午8:32:24 * */ public class CorantGeneratedCacheKey implements GeneratedCacheKey { private static final long serialVersionUID = 9179253007871444947L; private final Object[] parameters; private final int hashCode; public CorantGeneratedCacheKey(Object[] parameters) { this.parameters = parameters; hashCode = Arrays.deepHashCode(parameters); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } if (hashCode != obj.hashCode()) { return false; } CorantGeneratedCacheKey other = (CorantGeneratedCacheKey) obj; return Arrays.deepEquals(parameters, other.parameters); } public <T> T get(Function<Object[], T> converter) { return converter.apply(parameters); } @SuppressWarnings("unchecked") public <T> T get(int i) { return (T) parameters[i]; } @Override public int hashCode() { return hashCode; } Object[] parameters() { return Arrays.copyOf(parameters, parameters.length); } }
PHP
UTF-8
787
2.703125
3
[]
no_license
<?php /** * Created by PhpStorm. * User: romix * Date: 8/3/2017 * Time: 06:15 AM */ namespace Core; use Core\Model\Repository; class Repo { /** * @var Repository */ protected static $repo; public function init() { if (!isset(static::$repo)) { self::$repo = new Repository(); } } public static function getModel($name) { return self::$repo->getModel($name); } public static function getController($module, $controller, $path = null) { return self::$repo->getModel( ucfirst($path) . CD . $module . CD . 'Controller' . CD . $controller . 'Controller' ); } public static function get($name) { return self::$repo->get($name); } }
Java
UTF-8
7,219
1.710938
2
[]
no_license
package com.hk.common.interceptor; public enum InterceptorDirectoryEnum { MASTER_USER("/master/user"), MASTER_MODULE("/master/module"), MASTER_ACCESSUSER("/master/accessuser"), MASTER_PROSPEK("/master/prospek"), MASTER_GUDANG_GRUP("/master/gudangGrup"), MASTER_SALES("/master/sales"), MASTER_GUDANG("/master/gudang"), MASTER_GEDUNG("/master/gedung"), MASTER_MATA_UANG("/master/mataUang"), MASTER_KAS_BANK("/master/kasBank"), MASTER_BARANG_MERK("/master/barangMerk"), MASTER_BARANG_GRUP("/master/barangGrup"), MASTER_BARANG_DIVISI("/master/barangDivisi"), MASTER_UNIT("/master/unit"), MASTER_AKUN("/master/akun"), MASTER_WARNA_KAIN("/master/warnaKain"), MASTER_WARNA_KAIN_LUAR("/master/warnaKainLuar"), MASTER_SUPPLIER_WARNA("/master/supplierWarna"), MASTER_WARNA_HARGA("/master/warnaHargaHdr"), MASTER_WARNA_HARGA_LUAR("/master/warnaHargaLuarHdr"), MASTER_KAIN_MOTIF("/master/kainMotif"), MASTER_JENIS_KAIN("/master/jenisKain"), MASTER_MESIN("/master/mesin"), MASTER_JASA("/master/jasa"), MASTER_JASA_GRUP("/master/jasaGrup"), MASTER_SUPPLIER("/master/supplier"), MASTER_CUSTOMER("/master/customer"), MASTER_ROLE("/master/role"), MASTER_RAK("/master/rak"), MASTER_JENIS_KAIN_TAMBAHAN("/master/jenisKainTambahan"), MASTER_BENANG("/master/benang"), MASTER_WARNA_KAIN_GRUP("/master/warnaKainGrup"), MASTER_BENANG_GRUP("/master/benangGrup"), MASTER_BENANG_TIPE("/master/benangTipe"), MASTER_REQUEST_COMPLAIN("/master/requestComplain"), MASTER_AGEN("/master/agen"), SETTING_OTORISASI("/setting/otorisasi"), SETTING_KODE_TRANSAKSI("/setting/kodeTransaksi"), INISIAL_PACKING("/setting/inisialPacking"), REQUEST_ACCESS_MENU("/setting/requestAccessMenu"), VERSION_CONTROL("/setting/versionControl"), BARANG_LAIN_AWAL_STOK("/barangLain/awalStok"), PIUTANG_AWAL_PIUTANG("/piutang/awalPiutang"), HUTANG_AWAL_HUTANG("/hutang/awalHutang"), DO_PROSES_GROUP("/master/doProsesGroup"), DO_PROSES("/proses/doProsesHdr"), BBM_PROSES_GREIGE("/proses/bbmProsesGreigeHdr"), FAKTUR_PROSES_GREIGE("/proses/fakturProsesGreigeHdr"), BBM_PROSES_WARNA("/proses/bbmProsesWarnaHdr"), FAKTUR_PROSES_WARNA("/proses/fakturProsesWarnaHdr"), BBM_PROSES_MOTIF("/proses/bbmProsesMotifHdr"), FAKTUR_PROSES_MOTIF("/proses/fakturProsesMotifHdr"), PINDAH_GUDANG("/proses/pindahGudangHdr"), PINDAH_KAIN_GRADE("/proses/pindahKainGradeHdr"), PECAH_KAIN("/proses/pecahKainHdr"), GABUNG_KAIN("/proses/gabungKainHdr"), GABUNG_KAIN_RFP("/proses/gabungKainRfpHdr"), INVENTORY_SALDO_AWAL_KAIN_GREIGE_HDR("/inventory/saldoAwalKainGreigeHdr"), INVENTORY_SALDO_AWAL_KAIN_WARNA_HDR("/inventory/saldoAwalKainWarnaHdr"), INVENTORY_SALDO_AWAL_KAIN_MOTIF_HDR("/inventory/saldoAwalKainMotifHdr"), STOCK_OPNAME_HDR("/inventory/stockOpname"), STOCK_OPNAME_CANCELED_HDR("/inventory/stockOpnameCanceled"), PINDAH_RAK("/inventory/pindahRakHdr"), STOCK_REAL_GREIGE("/stock/saldoAkhirStockRealGreige"), STOCK_REAL_WARNA("/stock/saldoAkhirStockRealWarna"), STOCK_REAL_MOTIF("/stock/saldoAkhirStockRealMotif"), STOCK_PEMUTIHAN("/stock/stockPemutihan"), KARTU_STOCK_REAL("/stock/kartuStockReal"), KAIN_GRADE("/master/kainGrade"), PROSES_BBM_MAKLOON_GREIGE_HDR("/proses/bbmMakloonGreigeHdr"), PROSES_BBM_MAKLOON_WARNA_HDR("/proses/bbmMakloonWarnaHdr"), PROSES_BBM_MAKLOON_MOTIF_HDR("/proses/bbmMakloonMotifHdr"), PROSES_DELIVERY_ORDER_HDR("/proses/deliveryOrderHdr"), PROSES_SURAT_JALAN_HDR("/proses/suratJalanHdr"), PROSES_SURAT_JALAN_PERBAIKAN_HDR("/proses/suratJalanPerbaikanHdr"), PROSES_FAKTUR_JUAL_HDR("/proses/fakturJualHdr"), PROSES_FAKTUR_JUAL_JASA_HDR("/proses/fakturJualJasaHdr"), PROSES_FAKTUR_JUAL_PERBAIKAN_HDR("/proses/fakturJualPerbaikanHdr"), PROSES_RETUR_JUAL_HDR("/proses/returJualHdr"), PROSES_NOTA_RETUR_HDR("/proses/notaReturHdr"), PEMBELIAN_ORDER_BELI_KAIN_HDR("/pembelian/orderBeliKainHdr"), PEMBELIAN_ORDER_BELI_KAIN_SINGLE_HDR("/pembelian/orderBeliKainSingleHdr"), PEMBELIAN_BBM_BELI_KAIN_GREIGE_HDR("/pembelian/bbmBeliKainGreigeHdr"), PEMBELIAN_BBM_BELI_KAIN_WARNA_HDR("/pembelian/bbmBeliKainWarnaHdr"), PEMBELIAN_BBM_BELI_KAIN_MOTIF_HDR("/pembelian/bbmBeliKainMotifHdr"), PENJUALAN_ORDER_JUAL_KAIN_HDR("/penjualan/orderJualKainHdr"), PENJUALAN_ORDER_JUAL_KAIN_JASA("/penjualan/orderJualKainJasa"), PENJUALAN_REALISASI_ORDER_JUAL_KAIN_HDR("/penjualan/realisasiOrderJualKainHdr"), PROSES_FAKTUR_BELI_GREIGE_HDR("/proses/fakturBeliGreigeHdr"), PROSES_FAKTUR_BELI_WARNA_HDR("/proses/fakturBeliWarnaHdr"), PROSES_FAKTUR_BELI_MOTIF_HDR("/proses/fakturBeliMotifHdr"), PROSES_DO_CELUP_HDR("/proses/doCelupHdr"), PROSES_JO_CELUP_HDR("/proses/joCelupHdr"), PROSES_JO_CELUP_KP_PROSES("/proses/joCelupKpProses"), PROSES_JO_PROSES_HDR("/proses/joProsesHdr"), PROSES_DO_PRINTING_HDR("/proses/doPrintingHdr"), PROSES_BBM_CELUP_HDR("/proses/bbmCelupHdr"), PROSES_RETUR_DO_CELUP_HDR("/proses/returDoCelupHdr"), PROSES_BBM_PRINTING_HDR("/proses/bbmPrintingHdr"), PROSES_FAKTUR_CELUP_HDR("/proses/fakturCelupHdr"), PROSES_FAKTUR_GABUNG_KAIN_RFP_HDR("/proses/fakturGabungKainRfpHdr"), PROSES_FAKTUR_PRINTING_HDR("/proses/fakturPrintingHdr"), PROSES_SERAH_TERIMA_PRODUKSI("/proses/serahTerimaProduksi"), PROSES_SERAH_TERIMA_PRODUKSI_PROSES_GREIGE("/proses/serahTerimaProduksiProsesGreige"), PROSES_SERAH_TERIMA_PRODUKSI_PROSES_WARNA("/proses/serahTerimaProduksiProsesWarna"), PROSES_SERAH_TERIMA_PRODUKSI_PROSES_MOTIF("/proses/serahTerimaProduksiProsesMotif"), PROSES_SERAH_TERIMA_PRODUKSI_GAGAL("/proses/serahTerimaProduksiGagal"), PROSES_SERAH_TERIMA_PRODUKSI_PROSES_GREIGE_GAGAL("/proses/serahTerimaProduksiProsesGreigeGagal"), PROSES_SERAH_TERIMA_PRODUKSI_PROSES_WARNA_GAGAL("/proses/serahTerimaProduksiProsesWarnaGagal"), PROSES_SERAH_TERIMA_PRODUKSI_PROSES_MOTIF_GAGAL("/proses/serahTerimaProduksiProsesMotifGagal"), PROSES_SERAH_TERIMA_PRODUKSI_KP("/proses/serahTerimaProduksiKp"), PROSES_HASIL_PACKING("/proses/hasilPacking"), PROSES_HASIL_PACKING_KP("/proses/hasilPackingKp"), PROSES_HASIL_PACKING_KP_JOIN("/proses/hasilPackingKpJoin"), PROSES_HASIL_REKAP_KP("/proses/rekapKp"), PROSES_HASIL_REKAP_KP_PROSES("/proses/rekapKpProses"), PEMARTAIAN_KP("/proses/pemartaianKp"), PEMARTAIAN_PROSES_KP("/proses/pemartaianProsesKp"), MUTASI_SAFETY_STOCK("/proses/mutasiSafetyStock"), SPK_HDR("/proses/spkHdr"), PACKING_LIST("/proses/packingList"), SURAT_JALAN_PACKING_LIST("/proses/suratJalanPackingList"), RETUR_JUAL_TANPA_SJ("/proses/returJualTanpaSuratJalanHdr"), DATA_KUALITAS_KAIN("/proses/dataKualitasKain"), HASIL_KERJA_PEMARTAIAN("/proses/hasilKerjaPemartaian"), CONFIRM_PROSES_JOB_ORDER("/proses/confirmProsesJobOrder"), KONTROL_PROGRES_PRODUKSI("/proses/kontrolProgresProduksi"), OUTSTANDING_HASIL_PACKING("/proses/outstandingHasilPacking"), RETUR_BELI_GREIGE("/pembelian/returBeliGreige"), RETUR_BELI_WARNA("/pembelian/returBeliWarna"), RETUR_BELI_MOTIF("/pembelian/returBeliMotif"), PEMBELIAN_NOTA_RETUR_BELI("/pembelian/notaReturBeli"); private String val; InterceptorDirectoryEnum(String val) { this.val = val; } public String getVal() { return val; } }
Java
UTF-8
2,538
3.484375
3
[]
no_license
package checkPrimesMultithreading.workers; import checkPrimesMultithreading.util.Results; import checkPrimesMultithreading.util.FileProcessor; import checkPrimesMultithreading.util.IsPrime; import checkPrimesMultithreading.util.MyLogger; import checkPrimesMultithreading.workers.ThreadPool; import java.lang.IllegalThreadStateException; import java.lang.InterruptedException; import java.util.ArrayList; public class CreateWorkers{ //The variables needed for later when printing the values to stdout public Results results; public FileProcessor inputFile; public IsPrime prime; //This is the thread pool object public ThreadPool pool; /** * This is the constructor for the object which takes these values * and stores them within the Object for later use */ public CreateWorkers(Results resultsIn, FileProcessor fileIn, IsPrime primeIn, int numThreadsIn) { String message = "Constructor for Class: " + this.getClass().getSimpleName(); MyLogger.writeMessage(message, MyLogger.DebugLevel.CONSTRUCTOR); results = resultsIn; inputFile = fileIn; prime = primeIn; //Create our new thread pool pool = new ThreadPool(); //Create 5 worker threads and add them to the object pool for(int i = 0; i < numThreadsIn; i++) { WorkerThread newThread = new WorkerThread(inputFile, results, prime); pool.addWorkerThreadObject(newThread); } } /** * * @param numThreadsIn: This tells CreateWorkers how many threads * it needs to create */ public void startWorkers(int numThreadsIn) { //The list of threads we will need to join back ArrayList<Thread> threads = new ArrayList<Thread>(); //Create a new thread for each pass and have it begin the run // method for(int i = 0; i < numThreadsIn; i++) { //If the object pool is not empty, then take a thread WorkerThread worker = pool.borrowObject(); //Add the working threads to the list and start them if(worker!=null){ Thread thread = new Thread(worker); threads.add(thread); //Begin executing each thread try { thread.start(); }catch(IllegalThreadStateException e) { System.err.println("Error: Thread is not in the proper state."); e.printStackTrace(); System.exit(1); }finally {} } } //Go through all of the threads and join them back for(Thread worker : threads) { try { worker.join(); }catch(InterruptedException e) { System.err.println("Error: The thread has an interruption error."); e.printStackTrace(); System.exit(1); }finally {} } } }
JavaScript
UTF-8
1,385
3.421875
3
[]
no_license
var vote1=localStorage.getItem('key1'); var vote2=localStorage.getItem('key2') var vote3=localStorage.getItem('key3') function vote(){ if(selector.value == 1) { vote1++; alert("You have voted for Song 1"); } else if(selector.value == 2){ vote2++; alert("You have voted for Song 2"); } else{ vote3++; alert("You have voted for Song 3"); } } function result(){ alert("Song 1:"+ vote1 +"\nSong 2:"+ vote2 +"\nSong 3:"+ vote3); voteCounter(); } // =============Local Storage========== function voteCounter(){ localStorage.setItem("key1", vote1); localStorage.setItem("key2", vote2); localStorage.setItem("key3", vote3); document.getElementById("result1").innerHTML = "song 1:" + vote1; document.getElementById("result2").innerHTML = "song 2:" + vote2; document.getElementById("result3").innerHTML = "song 3:" + vote3; }
TypeScript
UTF-8
5,146
2.8125
3
[ "MIT" ]
permissive
import { CommandAPI, Tag, Command, CommandErrorCode, CommandMetaData, CommandError } from '../../command/commandapi'; import { ExtendedBotAPI } from '../../bot/botapi'; import { DiscordChannel, DiscordPermissionResolvable } from '../../discord/discordtypes'; import { Plugin } from '../../plugins/plugin'; import { PermissionFlags } from '../../command/commanddecorator'; export class UsageCommandUtils { public static async GetUsage(commandAPI:CommandAPI, bot:ExtendedBotAPI, channel:DiscordChannel, tag:Tag | null, command:Command | null):Promise<CommandError> { // Bot commands if (tag == null) { if (command == null) { await bot.SendMessage(channel, this.GetUsageHowTo()); command = 'usage'; } if (commandAPI.IsCommand(command)) { let usageStr:string = this.GetUsageForCommandAPI(commandAPI, command); if (usageStr === '') { return CommandError.Custom('This command does not have any usage documentation.'); } await bot.SendMessage(channel, usageStr); } else { return CommandError.New(CommandErrorCode.UNRECOGNIZED_BOT_COMMAND, { command:command }); } } // Plugin commands else { if (command == null) { return CommandError.New(CommandErrorCode.UNRECOGNIZED_PLUGIN_COMMAND, { command:command }); } let pluginFound:boolean = false; const plugins:Plugin[] = await bot.GetPlugins(); for (let plugin of plugins) { if (plugin.IsThisPlugin(tag) && plugin.IsCommand(command)) { pluginFound = true; let usageStr:string = this.GetUsageForCommandAPI(plugin, command); if (usageStr === '') { return CommandError.Custom('This command does not have any usage documentation.'); } await bot.SendMessage(channel, usageStr); break; } } if (!pluginFound) { return CommandError.New(CommandErrorCode.UNRECOGNIZED_PLUGIN_COMMAND, { command:command }); } } return CommandError.Success(); } private static GetUsageHowTo():string { let helpStr:string = '__**How to use usage:**__\n'; helpStr += 'Usage is a command designed to help you understand how to use commands. When you provide a command, it will display the command\'s structure and examples for how to use it.\n\n'; return helpStr; } private static GetUsageForCommandAPI(commandAPI:CommandAPI, command:Command):string { let usageStr:string = `__**Usage for ${command}:**__\n`; let commandsStr:string = ''; const metaData:CommandMetaData[] = <CommandMetaData[]>commandAPI.m_CommandRegistry.get(command); metaData.forEach((data:CommandMetaData, index:number) => { if (index != 0) { commandsStr += '\n'; } if (data.PermissionFlags & PermissionFlags.ADMIN) { commandsStr += '**This Command is Admin Only**\n'; } else if (data.PermissionFlags != 0) { commandsStr += '**Required Permissions:** '; let needsSeperator:boolean = false; if (data.PermissionFlags & PermissionFlags.ROLE) { commandsStr += `${needsSeperator ? ' or ' : ''}\`Registered Role\``; needsSeperator = true; } if (data.PermissionFlags & PermissionFlags.USER) { commandsStr += `${needsSeperator ? ' or ' : ''}\`Registered User\``; needsSeperator = true; } if (data.PermissionFlags & PermissionFlags.PERMISSION) { commandsStr += `${needsSeperator ? ' or ' : ''}\`All of these Discord Permissions: `; needsSeperator = true; if (data.DiscordPermissions && data.DiscordPermissions.length > 0) { for (let i:number = 0; i < data.DiscordPermissions.length; ++i) { const seperator:string = i + 1 < data.DiscordPermissions.length ? ', ' : ''; commandsStr += `${data.DiscordPermissions[i]}${seperator}`; }; } commandsStr += '\`'; } commandsStr += '\n'; } commandsStr += `${data.Usage}\n`; }); if (commandsStr === '') { return ''; } else { return usageStr + commandsStr; } } }
Java
WINDOWS-1250
8,920
2.1875
2
[]
no_license
package com.github.lyokofirelyte.WaterClosetIC; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.github.lyokofirelyte.WaterClosetIC.Util.TimeStampEX; import ru.tehkode.permissions.bukkit.PermissionsEx; public class WCMail implements CommandExecutor { public static String WC = "dWC 5// d"; static List <String> mail; private Connection conn; private PreparedStatement pst; String message; WCMain plugin; public WCMail(WCMain instance){ this.plugin = instance; } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equals("mail")){ if (sender instanceof Player == false){ sender.sendMessage(AS(WC + "Sorry console, I'm too lazy to allow you to send mails. That's like, extra effort.")); return true; } Player p = (Player) sender; switch(args.length){ case 0: for (String help : WCHelp.WCHelpMail){ sender.sendMessage(AS(help)); } break; case 1: switch(args[0]){ case "send": sender.sendMessage(AS(WC + "Try /mail send <player> <message>.")); break; case "read": mailCheck(p); break; case "clear": clearCheck(p); break; case "quick": mailCheck(p); clearCheck(p); break; default: List <String> WCHelpMail = WCMain.help.getStringList("WC.Mail"); for (String help : WCHelpMail){ sender.sendMessage(AS(help)); } break; } break; default: switch(args[0]){ default: List <String> WCHelpMail = WCMain.help.getStringList("WC.Mail"); for (String help : WCHelpMail){ sender.sendMessage(AS(help)); } break; case "send": switch (args[1]){ case "staff": mailStaff(p, TimeStampEX.createString(args, 2)); break; case "website": message = TimeStampEX.createString(args, 2); mailSite(sender.getName(), message); sender.sendMessage(AS(WC + "Your message has been sent to http://www.ohsototes.com/?p=mail")); break; case "all": if (p.hasPermission("wa.staff") == false){ p.sendMessage(AS(WC + "You don't have permission to send global mails.")); break; } List <String> userList = WCMain.mail.getStringList("Users.Total"); sender.sendMessage(AS(WC + "Message sent!")); for (String current : userList){ OfflinePlayer sendTo = Bukkit.getOfflinePlayer(current); message = TimeStampEX.createString(args, 2); mail = WCMain.mail.getStringList("Users." + current + ".Mail"); mail.add(p.getDisplayName() + " &f-> &2Global &9// &3" + message); WCMain.mail.set("Users." + current + ".Mail", mail); if (sendTo.isOnline()){ Bukkit.getPlayer(current).sendMessage(AS(WC + "You've recieved a new mail! Check it with /mail read.")); } } break; default: if (args[1].equalsIgnoreCase(p.getName())){ sender.sendMessage(AS(WC + "I'm schizophrenic, and so am I. Together, I can solve this.")); break; } OfflinePlayer sendTo = Bukkit.getOfflinePlayer(args[1]); if (sendTo.hasPlayedBefore() == false){ sender.sendMessage(AS(WC + "That player has never logged in before!")); break; } message = TimeStampEX.createString(args, 2); String lastWord = message.substring(message.lastIndexOf(" ")+1); if (message.contains("!exp") && WCCommands.isInteger(lastWord)){ int xp = plugin.datacore.getInt("Users." + sender.getName() + ".MasterExp"); int xpOther = plugin.datacore.getInt("Users." + args[1] + ".MasterExp"); if (xp < Integer.parseInt(lastWord)){ sender.sendMessage(WC + "You don't have that much XP! You tried to send: " + lastWord + "."); break; } plugin.datacore.set("Users." + args[1] + ".MasterExp", (xpOther + Integer.parseInt(lastWord))); plugin.datacore.set("Users." + sender.getName() + ".MasterExp", (xp - Integer.parseInt(lastWord))); mail = WCMain.mail.getStringList("Users." + sendTo.getName() + ".Mail"); mail.add(p.getDisplayName() + " &9// &3" + message.replaceAll("!exp", "").replaceAll(lastWord, "")); mail.add(p.getDisplayName() + " &3 has included &c" + lastWord + " &3exp in this mail."); WCMain.mail.set("Users." + sendTo.getName() + ".Mail", mail); sender.sendMessage(AS(WC + "Message sent!")); if (sendTo.isOnline()){ Bukkit.getPlayer(args[1]).sendMessage(AS(WC + "You've recieved a new mail! Check it with /mail read.")); } break; } mail = WCMain.mail.getStringList("Users." + sendTo.getName() + ".Mail"); mail.add(p.getDisplayName() + " &9// &3" + message); WCMain.mail.set("Users." + sendTo.getName() + ".Mail", mail); sender.sendMessage(AS(WC + "Message sent!")); if (sendTo.isOnline()){ Bukkit.getPlayer(args[1]).sendMessage(AS(WC + "You've recieved a new mail! Check it with /mail read.")); } break; } } } } return true; } public static boolean hasPerms(OfflinePlayer player, String usepermission) { return PermissionsEx.getUser(player.getName()).has(usepermission); } private void mailStaff(Player p, String message) { if (p.hasPermission("wa.staff") == false){ p.sendMessage(WCMail.WC + "You don't have permission to send mail to staff."); return; } List<String> players = WCMain.mail.getStringList("Users.Total"); for (String bleh : players){ if (hasPerms(Bukkit.getOfflinePlayer(bleh), "wa.staff")){ mail = WCMain.mail.getStringList("Users." + bleh + ".Mail"); mail.add(p.getDisplayName() + " &f-> &aStaff &9// &3" + message); WCMain.mail.set("Users." + bleh + ".Mail", mail); OfflinePlayer sendTo = Bukkit.getOfflinePlayer(bleh); if (sendTo.isOnline()){ Bukkit.getPlayer(bleh).sendMessage(AS(WC + "You've recieved a new mail! Check it with /mail read.")); } } } } public void mailSite(String name, String message){ String url = plugin.config.getString("urlMail"); String username = plugin.config.getString("username"); String password = plugin.config.getString("password"); try { this.conn = DriverManager.getConnection(url, username, password); this.pst = this.conn.prepareStatement("INSERT INTO mail(timestamp, name, message) VALUES(?, ?, ?)"); long timestamp = System.currentTimeMillis() / 1000L; this.pst.setInt(1, (int)timestamp); this.pst.setString(2, name); this.pst.setString(3, message); this.pst.executeUpdate(); this.pst.close(); this.conn.close(); } catch (SQLException e) { e.printStackTrace(); } } public static String AS(String DecorativeToasterCozy){ String FlutterShysShed = ChatColor.translateAlternateColorCodes('&', DecorativeToasterCozy); return FlutterShysShed; } public void clearCheck(Player p){ mail = WCMain.mail.getStringList("Users." + p.getName() + ".Mail"); if (mail.size() == 0){ p.sendMessage(AS(WC + "You have no mail!")); return; } WCMain.mail.set("Users." + p.getName() + ".Mail", null); p.sendMessage(AS(WC + "Mail cleared!")); } public void mailCheck(Player p){ mail = WCMain.mail.getStringList("Users." + p.getName() + ".Mail"); if (mail.size() == 0){ p.sendMessage(AS(WC + "You have no mail!")); return; } p.sendMessage(AS(WC + "Viewing Mail &6(" + mail.size() + "&6)")); for (String singleMail : mail){ p.sendMessage(AS("&5| " + singleMail)); } } public static void mailLogin(Player p){ mail = WCMain.mail.getStringList("Users." + p.getName() + ".Mail"); List <String> userList = WCMain.mail.getStringList("Users.Total"); if (mail.size() > 0){ p.sendMessage(AS(WC + "You have " + mail.size() + " &dnew messages. Read them with /mail read.")); } if (userList.contains(p.getName())){ return; } else { userList.add(p.getName()); WCMain.mail.set("Users.Total", userList); } } }
Python
UTF-8
2,900
2.78125
3
[ "MIT" ]
permissive
import struct import unittest from datasketch.partition_minhash import PartitionMinHash, BetterWeightedPartitionMinHash class FakeHash(object): def __init__(self, h): ''' Initialize with an integer ''' self.h = h def digest(self): ''' Return the bytes representation of the integer ''' return struct.pack('<Q', self.h) class TestPartitionMinhash(unittest.TestCase): def test_init(self): m1 = PartitionMinHash(4) m2 = PartitionMinHash(4) self.assertEqual(m1, m2) self.assertEqual(m1.k_val, m2.k_val) self.assertEqual(m1.partitions, m1.partitions) def test_is_empty(self): m = PartitionMinHash(4, hashobj=FakeHash) self.assertTrue(m.is_empty()) m.update(1) self.assertFalse(m.is_empty()) def test_update(self): m1 = PartitionMinHash(4, hashobj=FakeHash) m2 = PartitionMinHash(4, hashobj=FakeHash) m1.update(12) self.assertTrue(m1 != m2) def test_jaccard(self): m1 = PartitionMinHash(4, hashobj=FakeHash) m2 = PartitionMinHash(4, hashobj=FakeHash) self.assertEqual(m1.jaccard(m2), 1.0) m2.update(12) self.assertEqual(m1.jaccard(m2), 0.0) m1.update(13) self.assertEqual(m1.jaccard(m2), 0.0) m1.update(12) self.assertEqual(m1.jaccard(m2), 0.75) m2.update(13) self.assertEqual(m1.jaccard(m2), 1.0) m1.update(14) self.assertEqual(m1.jaccard(m2), 2./3) m2.update(14) self.assertEqual(m1.jaccard(m2), 1.0) def test_better_weighting_jaccard(self): m1 = BetterWeightedPartitionMinHash(4, hashobj=FakeHash) m2 = BetterWeightedPartitionMinHash(4, hashobj=FakeHash) self.assertEqual(m1.jaccard(m2), 1.0) m2.update(12) self.assertEqual(m1.jaccard(m2), 0.0) m1.update(13) self.assertEqual(m1.jaccard(m2), 0.0) m1.update(12) self.assertEqual(m1.jaccard(m2), 0.50) m2.update(13) self.assertEqual(m1.jaccard(m2), 1.0) m1.update(14) self.assertEqual(m1.jaccard(m2), 2./3) m2.update(14) self.assertEqual(m1.jaccard(m2), 1.0) def test_eq(self): m1 = PartitionMinHash(4, hashobj=FakeHash) m2 = PartitionMinHash(4, hashobj=FakeHash) m3 = PartitionMinHash(4, hashobj=FakeHash) m4 = PartitionMinHash(4, hashobj=FakeHash) m5 = PartitionMinHash(4, hashobj=FakeHash) m1.update(11) m2.update(12) m3.update(11) m4.update(11) m5.update(11) self.assertNotEqual(m1, m2) self.assertEqual(m1, m3) self.assertEqual(m1, m4) self.assertEqual(m1, m5) m1.update(12) m2.update(11) self.assertEqual(m1, m2) if __name__ == "__main__": unittest.main()
SQL
UTF-8
2,165
3.203125
3
[]
no_license
CREATE TABLE dxf_record ( pk serial primary key, provider character varying(20) DEFAULT ''::character varying NOT NULL, service character varying(20) NOT NULL, ns character varying(20) NOT NULL, ac character varying(20) NOT NULL, detail character varying(5), dxf text NOT NULL, create_time timestamp without time zone NOT NULL, query_time timestamp without time zone NOT NULL, expire_time timestamp without time zone NOT NULL, CONSTRAINT unique_dxf UNIQUE ( provider, service, ns, ac, detail ) ); CREATE TABLE native_record ( pk serial primary key, provider character varying(20) DEFAULT ''::character varying NOT NULL, service character varying(20) DEFAULT ''::character varying NOT NULL, ns character varying(20) DEFAULT ''::character varying NOT NULL, ac character varying(20) DEFAULT ''::character varying NOT NULL, native_xml text NOT NULL, create_time timestamp without time zone NOT NULL, query_time timestamp without time zone NOT NULL, expire_time timestamp without time zone NOT NULL, CONSTRAINT unique_nr UNIQUE ( provider, service, ns, ac ) ); CREATE TABLE native_audit ( pk serial primary key, provider character varying(20) DEFAULT ''::character varying NOT NULL, service character varying(20) DEFAULT ''::character varying NOT NULL, ns character varying(20) DEFAULT ''::character varying NOT NULL, ac character varying(20) DEFAULT ''::character varying NOT NULL, time timestamp without time zone NOT NULL, delay integer DEFAULT 0 NOT NULL, status integer DEFAULT 0 NOT NULL ); /* CREATE INDEX native_idx1 ON native_record (provider, service, ns, ac); */ CREATE INDEX native_idx2 ON native_record (expire_time); CREATE INDEX native_idx3 ON native_record (query_time); /* CREATE INDEX dxf_idx1 ON dxf_record (provider, service, ns, ac, detail); */ CREATE INDEX dxf_idx2 ON dxf_record (expire_time); CREATE INDEX dxf_idx3 ON dxf_record (query_time); CREATE INDEX I12 ON native_audit (provider, service, ns, ac); CREATE INDEX I18 ON native_audit (provider, service, pk); CREATE INDEX I19 ON native_audit (provider, service, time);
Shell
UTF-8
2,090
2.84375
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#!/bin/bash # # Copyright 2012 Akiban Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # See https://docs.sonatype.org/display/Repository/Sonatype+OSS+Maven+Repository+Usage+Guide # # Run this script from the base directory. # # Package and sign artifacts. You will need a signing key in your gpg keyring. Follow # these instructions to set up gpg and generate a key-pair. You only need to do this once: # # https://docs.sonatype.org/display/Repository/How+To+Generate+PGP+Signatures+With+Maven # # The gpg:sign will ask you to enter a passphrase to access your key chain. # mvn clean javadoc:jar package gpg:sign -Dmaven.test.skip=true # # Create a bundle jar. # pushd target jar cvf bundle.jar akiban-persistit* popd # # Note: the Nexus Maven Plugin can do this automatically, but for now we are still manual. # echo ======================================================================================================= echo 1. Log in to your account on https://oss.sonatype.org/index.html#stagingRepositories echo 2. Click \"Staging Upload\" echo 3. Select Upload Mode \"Artifact Bundle\" echo 4. Click \"Select Bundle to Upload\" echo 5. Navigate to the file target/bundle.jar just created echo 6. Click \"Upload Bundle\" echo 7. Follow instructions in echo echo https://docs.sonatype.org/display/Repository/Sonatype+OSS+Maven+Repository+Usage+Guide#SonatypeOSSMavenRepositoryUsageGuide-8a.ReleaseIt echo echo to close and release the staging repository. echo =======================================================================================================
Python
UTF-8
221
2.765625
3
[]
no_license
#import sys #import os f = open("test.in",'r') count = 0 while(True): ss =f.readline().split() if not ss : break if float(ss[4])>=0.0 and float(ss[4])<=1.0: print ss[4] count+=1 print count
Java
GB18030
2,118
2.375
2
[]
no_license
package com.plugins.dirtree.service.dao.hibernate; import java.util.Iterator; import java.util.List; import org.hibernate.internal.util.collections.EmptyIterator; import org.springline.orm.dao.hibernate.HibernateCommonDao; import com.plugins.dirtree.entity.DirType; import com.plugins.dirtree.service.dao.IDirTypeDao; public class HibernateDirTypeDao extends HibernateCommonDao implements IDirTypeDao { public boolean checkEditDirTypeCode(String oldTypeCode, String newTypeCode) { // TODO Auto-generated method stub boolean flag = false; //޸ʱ<>˵ɵtypeCodeݣٸݴµtypeCodeֵƥ String hql = "from " + DirType.class.getName() + " as dt where dt.dirTypeCode<>? and dt.dirTypeCode=?" ; List list = doQuery(hql,new Object[]{oldTypeCode,newTypeCode}); if (list.size() > 0) { flag = true; } return flag; } public List selectValidDirTypes() { // TODO Auto-generated method stub return doQuery("from "+DirType.class.getName() +" as dt where dt.isValid = ? order by dt.sortOrder ",new Object[]{DirType.NORMAL_STATE}); } public DirType selectDirTypeByCode(String dirTypeCode) { // TODO Auto-generated method stub List dirTypelist= doQuery("from "+DirType.class.getName() +" as dt where dt.dirTypeCode = ?",new Object[]{dirTypeCode}); return (DirType) dirTypelist.get(0); } @Override public Integer selectUsableOrderNumber() { // TODO Auto-generated method stub StringBuffer hql = new StringBuffer("select max(dt.sortOrder) from ") .append(DirType.class.getName()).append(" as dt where dt.isValid=?"); Iterator it = super.iterate(hql.toString(), new Object[] {DirType.NORMAL_STATE}); int number = 1; if (it.hasNext()) { try { number = ((Integer) it.next()).intValue(); number++; } catch (Exception ex) { } } if (!(it instanceof EmptyIterator)) { super.closeIterator(it); } return new Integer(number); } }
Java
UTF-8
152
1.585938
2
[ "Apache-2.0" ]
permissive
package com.hyphenate.easeui.jxcontrol.login; /** * 修改备注 */ public interface RemarkInterface { public void onSuccess(Boolean sucess); }
Python
UTF-8
1,321
3.28125
3
[]
no_license
""" 多进程并发网络模型 重点代码!!! 步骤思路 创建网络套接字用于接收客户端请求 等待客户端连接 客户端连接,则创建新的进程具体处理客户端请求 主进程继续等待其他客户端连接 如果客户端退出,则销毁对应的进程 """ from socket import * from multiprocessing import Process from signal import * # 全局变量定义地址 HOST = "0.0.0.0" PORT = 8888 ADDR = (HOST,PORT) # 具体处理客户端请求 函数结束即客户端退出 def handle(connfd): while True: data = connfd.recv(1024) if not data: break print(data.decode()) connfd.send(b'OK') connfd.close() def main(): # 创建tcp套接字 sock = socket() sock.bind(ADDR) sock.listen(5) # 处理僵尸进程 signal(SIGCHLD,SIG_IGN) print("Listen the port %d..."%PORT) while True: # 循环接收端连接 try: connfd,addr = sock.accept() print("Connect from",addr) except KeyboardInterrupt: sock.close() return # 创建新的进程,处理客户端具体请求事务 p = Process(target=handle,args=(connfd,)) p.daemon = True p.start() if __name__ == '__main__': main()
Markdown
UTF-8
3,515
2.78125
3
[]
no_license
--- layout: post redirect_from: - /writeup/algo/atcoder/jag2017summer-day3-e/ - /blog/2017/10/03/jag2017summer-day3-e/ date: "2017-10-03T06:58:41+09:00" tags: [ "competitive", "writeup", "atcoder", "jag-summer", "dp", "graph" ] "target_url": [ "https://beta.atcoder.jp/contests/jag2017summer-day3/tasks/jag2017summer_day3_e" ] --- # Japan Alumni Group Summer Camp 2017 Day 3: E - Route Calculator チームメンバーに任せた(私のlaptopの電源が切れたので)が、バグったので私が$0$から書き直した。 私$\to$彼と私$\gets$彼のどちらの向きでも、大きめのコードをバグらせたら交代して$0$からが良いと踏んでいるがどうなのだろうか。 ## problem 下図のような文字列が与えられる。左上から右下への経路で、それを数式として読んだとき最大になるようなものの値を答えよ。 ``` 8+9*4*8 *5*2+3+ 1*3*2*2 *5*1+9+ 1+2*2*2 *3*6*2* 7*7+6*5 *5+7*2+ 3+3*6+8 ``` ## solution `*`, `+`を辺と見てそれぞれだけでグラフ$G\_\times, G\_+$を作る。 この上でDP。 頂点$(y, x)$から$G\_\times$の辺を任意回使って到達可能な頂点から$G\_+$の辺をちょうど$1$本使っていける頂点の値を見ていい感じにする。 右下まで直接行ける場合は例外。 $O(H^2W^2)$。 ## implementation ``` c++ #include <cctype> #include <cmath> #include <cstdio> #include <queue> #include <vector> #define repeat(i, n) for (int i = 0; (i) < int(n); ++(i)) #define repeat_reverse(i, n) for (int i = (n)-1; (i) >= 0; --(i)) using ll = long long; using namespace std; template <class T> inline void setmax(T & a, T const & b) { a = max(a, b); } int main() { // input int h, w; scanf("%d%d", &h, &w); vector<char> f(h * w); repeat (y, h) repeat (x, w) { scanf(" %c", &f[y * w + x]); } // solve // // make graphs vector<vector<int> > mul(h * w); vector<vector<int> > add(h * w); repeat (y, h) repeat (x, w) if (isdigit(f[y * w + x])) { int z = y * w + x; if (y + 1 < h) { auto & g = (f[(y + 1) * w + x] == '*' ? mul : add); if (y + 2 < h) g[z].push_back((y + 2) * w + x); if (x + 1 < w) g[z].push_back((y + 1) * w + (x + 1)); } if (x + 1 < w) { auto & g = (f[y * w + (x + 1)] == '*' ? mul : add); if (x + 2 < w) g[z].push_back(y * w + (x + 2)); if (y + 1 < h) g[z].push_back((y + 1) * w + (x + 1)); } } // // dp vector<double> dp(h * w); vector<double> muls(h * w); queue<int> que; repeat_reverse (y, h) repeat_reverse (x, w) if (isdigit(f[y * w + x])) { int z = y * w + x; muls.assign(h * w, - INFINITY); muls[z] = f[z] - '0'; que.push(z); while (not que.empty()) { int z = que.front(); // shadowing que.pop(); for (int nz : mul[z]) { if (isinf(muls[nz])) { que.push(nz); } setmax(muls[nz], muls[z] * (f[nz] - '0')); } } repeat (nz, h * w) if (not isinf(muls[nz])) { for (int nnz : add[nz]) { setmax(dp[z], muls[nz] + dp[nnz]); } } setmax(dp[z], muls[h * w - 1]); } // output if (dp[0] <= 1e16 and ll(dp[0]) <= 1000000000000000ll) { printf("%lld\n", ll(dp[0])); } else { printf("-1\n"); } return 0; } ```
PHP
UTF-8
998
2.71875
3
[ "MIT" ]
permissive
<?php namespace Repositories\Indexers; use Repositories\RepositoryWriterInterface; class Terrain implements IndexerInterface { const DEFAULT_INDEX = "terrains"; public function onNewObject(RepositoryWriterInterface $repo, $object) { if ($object->type != "terrain") { return; } $repo->append(self::DEFAULT_INDEX, $object->id); $repo->set(self::DEFAULT_INDEX.".$object->id", $object->repo_id); $repo->set("all.$object->id", $object->repo_id); if (isset($object->bash) && isset($object->id) && isset($object->bash->items)) { if (is_array($object->bash->items)) { foreach ($object->bash->items as $item) { if (isset($item->item)) { $repo->append("item.bashFromTerrain.$item->item", $object->id); } } } } } public function onFinishedLoading(RepositoryWriterInterface $repo) { } }
Python
UTF-8
2,002
2.75
3
[ "MIT" ]
permissive
from mykrobe.stats import percent_coverage_from_expected_coverage from mykrobe.stats import log_factorial from mykrobe.stats import log_lik_depth from math import log from math import exp import pytest def test_percentage_coverage(): assert percent_coverage_from_expected_coverage( 100) > percent_coverage_from_expected_coverage(10) assert percent_coverage_from_expected_coverage(100) == 1 assert percent_coverage_from_expected_coverage(1) < 1 def test_log_factorial(): assert log_factorial(4) - log(24) < 0.0001 assert log_factorial(4) - 3.17 < 0.01 assert log_factorial(4) - (log(1) + log(2) + log(3) + log(4)) < 0.0001 def test_log_lik_depth(): assert exp( log_lik_depth( expected_depth=10, depth=10)) > exp( log_lik_depth( expected_depth=10, depth=1)) assert exp( log_lik_depth( expected_depth=10, depth=10)) > exp( log_lik_depth( expected_depth=10, depth=8)) assert exp( log_lik_depth( expected_depth=10, depth=10)) == exp( log_lik_depth( expected_depth=10, depth=9)) assert exp( log_lik_depth( expected_depth=10, depth=10)) > exp( log_lik_depth( expected_depth=10, depth=11)) assert log_lik_depth( expected_depth=100, depth=50) < log_lik_depth( expected_depth=10, depth=9) with pytest.raises(ValueError) as cm: log_lik_depth(expected_depth=0, depth=0) with pytest.raises(ValueError) as cm: log_lik_depth(expected_depth=-1, depth=9) with pytest.raises(ValueError) as cm: log_lik_depth(expected_depth=12, depth=-1) with pytest.raises(ValueError) as cm: log_lik_depth(expected_depth=0, depth=1) assert log_lik_depth(expected_depth=1, depth=0) == -1 # TODO. Expect a higher % coverage if k is lower