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
Shell
UTF-8
3,583
3.609375
4
[ "MIT", "CC-BY-4.0" ]
permissive
# Copyright (c) 2016 Damien Tardy-Panis # # This file is subject to the terms and conditions defined in # file 'LICENSE', which is part of this source code package. # # Inputs validation functions ################################################################################ # Validate the position input # Globals: # POSITION # Arguments: # None # Returns: # None # Exits: # 1 if invalid ################################################################################ validation::validate_position() { if ! date --date "${POSITION}" &> /dev/null \ && [[ "${POSITION}" != 'left' ]] \ && [[ "${POSITION}" != 'center' ]] \ && [[ "${POSITION}" != 'right' ]] \ && [[ "${POSITION}" != 'last' ]]; then general::error 'Invalid position date or identifier' fi } ################################################################################ # Validate the Github username input # Globals: # GITHUB_USERNAME # Arguments: # None # Returns: # None # Exits: # 1 if invalid ################################################################################ validation::validate_github_username() { # Check that the username provided exists and is linked to an user account if [[ -n "${GITHUB_USERNAME}" ]] \ && ! curl --silent "https://api.github.com/users/${GITHUB_USERNAME}" \ | grep --quiet '"type": "User"'; then general::error 'Invalid Github username: non existing user profile' fi } ################################################################################ # Validate the shade multiplier input # Globals: # SHADE_MULTIPLIER # Arguments: # None # Returns: # None # Exits: # 1 if invalid ################################################################################ validation::validate_shade_multiplier() { if ! [[ ${SHADE_MULTIPLIER} =~ ^[1-9][0-9]* ]]; then general::error 'Invalid shade multiplier: non strictly positive integer' fi } ################################################################################ # Validate the template input # Globals: # SCRIPT_DIR # TEMPLATE # Arguments: # None # Returns: # None # Exits: # 1 if invalid ################################################################################ validation::validate_template() { if [[ ! -f "${TEMPLATE}" ]]; then local provided_template=$( find "${SCRIPT_DIR}/templates/" -name "${TEMPLATE}.tpl" -print -quit ) if [[ -f "${provided_template}" ]]; then TEMPLATE="${provided_template}" else local error_message='non existing file or invalid identifier' general::error "Invalid template value: ${error_message}" fi fi if [[ $( tr --delete 01234'\n' < "${TEMPLATE}" | wc --chars ) != 0 ]]; then local error_message='should contain only integers 0 to 4 and newlines' general::error "Invalid template: ${error_message}" fi # Ignore trailing newlines for further checks local trimmed_template=$( cat -- "${TEMPLATE}" | sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' ) if [[ $( echo "${trimmed_template}" | wc --lines ) != 7 ]]; then general::error 'Invalid template: should have 7 lines' fi local max_line_length=$( wc --max-line-length < "${TEMPLATE}" ) local line_length while read line; do line_length=${#line} if [[ "${line_length}" == 0 ]]; then general::error 'Invalid template: empty lines are not allowed' fi if [[ "${line_length}" != "${max_line_length}" ]]; then general::error 'Invalid template: all lines should have the same length' fi done < <( echo "${trimmed_template}" ) }
Markdown
UTF-8
1,504
2.625
3
[]
no_license
--- title: ०७५ सूक्तम् --- वि बाधस्व दृंहस्व वीडयस्वाधस्पदं शत्रवस्ते भवन्तु । सपत्नसाह ऋषभो जनाषाडुग्रश्चेत्ता पञ्च कृष्टीर्वि राज ।१। शिवं क्षेत्रमनमीवन्ते अस्तूत्तमे नाके अधि तिष्ठेहि । पुत्रान् भ्रातॄन् बहुलान् पश्यमानो विश्वे त्वा देवा इह धारयन्तु ।२। त्वष्टा रूपेण सविता सवेनाहर्मित्रेण वरुणेन रात्री । इन्द्रो जैष्ठ्येन ब्रह्मणायं बृहस्पतिर्धाता त्वा धीभिरभि रक्षत्विह ।३। वास्तोष्पत इह नः शर्म यच्छ घने वृत्राणां सङ्गथे वसूनाम् । वास्तोस्पत इहैवैधि ग्रामपतिर्जनाषाड् विश्वैर्देवैर्गुपितो रक्षमाणः ॥४॥ (इति चतुर्चनामप्रथमकाण्डे पञ्चदशो ऽनुवाकः)
PHP
UTF-8
4,232
2.578125
3
[ "Apache-2.0" ]
permissive
<?php require_once('../Connections/localhost.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } mysql_select_db($database_localhost, $localhost); $query_relationship = "SELECT * FROM relationship"; $relationship = mysql_query($query_relationship, $localhost) or die(mysql_error()); $row_relationship = mysql_fetch_assoc($relationship); $totalRows_relationship = mysql_num_rows($relationship); mysql_select_db($database_localhost, $localhost); $query_disease = "SELECT * FROM disease"; $disease = mysql_query($query_disease, $localhost) or die(mysql_error()); $row_disease = mysql_fetch_assoc($disease); $totalRows_disease = mysql_num_rows($disease); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <form method="post" name="form19" id="form19"> <input type="hidden" name="pr" id="pr" value="<?php echo $_GET['pr']; ?>" style="width:100%"/> <input type="hidden" name="en" id="en" value="<?php echo $_GET['en']; ?>" style="width:100%"/> <input type="hidden" name="sc" id="sc" value="<?php echo $_GET['sc']; ?>" style="width:100%"/> <input type="hidden" name="id" id="id" value="<?php echo $_GET['id']; ?>" style="width:100%"/> <input type="hidden" name="st" id="st" value="<?php echo $_GET['st']; ?>" style="width:100%"/> <input type="hidden" name="cap" id="cap" value="<?php echo $_GET['cap']; ?>" style="width:100%"/> <input type="hidden" name="lc2" id="lc2" value="<?php echo $_GET['lc2']; ?>" style="width:100%"/> <input type="hidden" name="lc" id="lc" value="<?php echo $_GET['lc']; ?>" style="width:100%"/> <input type="hidden" name="id2" id="id2" value="<?php echo $_GET['id2']; ?>" style="width:100%"/> <div id="AllHealth"></div> <table width="100%" border="1" style="border:thin; border-color:#ffffff; border-collapse:collapse;"> <?php if ($_GET['lc2'] == 2) { $disable = "disabled=\"disabled\""; } else { $disable = ""; } ?> <tr> <td width="17%"><select name="relate" id="relate" style="width:100%"> <option value=""></option> <?php do { ?> <option value="<?php echo $row_relationship['Id']?>"><?php echo $row_relationship['Relationship']?></option> <?php } while ($row_relationship = mysql_fetch_assoc($relationship)); $rows = mysql_num_rows($relationship); if($rows > 0) { mysql_data_seek($relationship, 0); $row_relationship = mysql_fetch_assoc($relationship); } ?> </select></td> <td width="16%"><input type="text" <?php echo $disable;?> name="string" id="string" value="" style="width:100%;" onchange=" LoadString2();"/></td> <td width="64%"> <div id="AllString2"></div></td> <td width="3%"><input type="button" onclick="AddHealth();" value="Add" title="Add" style="color: #07c; padding: 0px; letter-spacing: 0px; font-size:8px; width:25px; height:23px;"/></td> </tr> </table> </form> </body> </html> <?php mysql_free_result($relationship); mysql_free_result($disease); ?>
Go
UTF-8
6,041
2.859375
3
[ "Apache-2.0" ]
permissive
package GoMybatis import ( "fmt" "github.com/zhuxiujia/GoMybatis/utils" "testing" "time" ) type TestResult struct { Name string Amount1 float32 Amount2 float64 Age1 int Age2 int32 Age3 int64 Age4 uint Age5 uint8 Age6 uint16 Age7 uint32 Age8 uint64 Bool bool } //解码基本数据-int,string,time.Time... func Test_Convert_Basic_Type(t *testing.T) { var resMap = make(map[string][]byte) resMap["Amount1"] = []byte("1908") var resMapArray = make([]map[string][]byte, 0) resMapArray = append(resMapArray, resMap) var intResult int var error = GoMybatisSqlResultDecoder{}.Decode(nil, resMapArray, &intResult) if error != nil { panic(error) } fmt.Println("Test_Convert_Basic_Type,int=", intResult) var stringResult string error = GoMybatisSqlResultDecoder{}.Decode(nil, resMapArray, &stringResult) if error != nil { panic(error) } fmt.Println("Test_Convert_Basic_Type,string=", stringResult) var floatResult float64 error = GoMybatisSqlResultDecoder{}.Decode(nil, resMapArray, &floatResult) if error != nil { panic(error) } fmt.Println("Test_Convert_Basic_Type,float=", floatResult) resMap = make(map[string][]byte) resMap["Date"] = []byte(time.Now().Format(time.RFC3339)) resMapArray = make([]map[string][]byte, 0) resMapArray = append(resMapArray, resMap) var timeResult time.Time error = GoMybatisSqlResultDecoder{}.Decode(nil, resMapArray, &timeResult) if error != nil { panic(error) } fmt.Println("Test_Convert_Basic_Type,time=", timeResult) } //解码数组 func Test_Convert_Slice(t *testing.T) { var resMap = make(map[string][]byte) resMap["Amount1"] = []byte("1908") resMap["Amount2"] = []byte("1901") var resMapArray = make([]map[string][]byte, 0) resMapArray = append(resMapArray, resMap) var result []int var error = GoMybatisSqlResultDecoder{}.Decode(nil, resMapArray, &result) if error != nil { panic(error) } fmt.Println("Test_Convert_Basic_Type", result) } //解码map func Test_Convert_Map(t *testing.T) { var resMap = make(map[string][]byte) resMap["Amount1"] = []byte("1908") resMap["Amount2"] = []byte("1901") var resMapArray = make([]map[string][]byte, 0) resMapArray = append(resMapArray, resMap) var result map[string]int var error = GoMybatisSqlResultDecoder{}.Decode(nil, resMapArray, &result) if error != nil { panic(error) } fmt.Println("Test_Convert_Basic_Type", result) } func Test_convert_struct(t *testing.T) { var GoMybatisSqlResultDecoder = GoMybatisSqlResultDecoder{} var res = make([]map[string][]byte, 0) var resMap = make(map[string][]byte) resMap["Name"] = []byte("xiao ming") resMap["Amount1"] = []byte("1908.1") resMap["Amount2"] = []byte("1908.444") resMap["Age1"] = []byte("1908") resMap["Age2"] = []byte("1908") resMap["Age3"] = []byte("1908") resMap["Age4"] = []byte("1908") resMap["Age5"] = []byte("1908") resMap["Age6"] = []byte("1908") resMap["Age7"] = []byte("1908") resMap["Age8"] = []byte("1908") resMap["Bool"] = []byte("true") res = append(res, resMap) var result TestResult GoMybatisSqlResultDecoder.Decode(nil, res, &result) fmt.Println("Test_convert_struct", result) } func Test_Ignore_Case_Underscores(t *testing.T) { var GoMybatisSqlResultDecoder = GoMybatisSqlResultDecoder{} var res = make([]map[string][]byte, 0) var resMap = make(map[string][]byte) resMap["name"] = []byte("xiao ming") resMap["Amount_1"] = []byte("1908.1") resMap["amount_2"] = []byte("1908.444") resMap["age_1"] = []byte("1908") resMap["age_2"] = []byte("1908") resMap["age_3"] = []byte("1908") resMap["age_4"] = []byte("1908") resMap["age_5"] = []byte("1908") resMap["age_6"] = []byte("1908") resMap["age_7"] = []byte("1908") resMap["age_8"] = []byte("1908") resMap["Bool"] = []byte("1") res = append(res, resMap) var result TestResult GoMybatisSqlResultDecoder.Decode(nil, res, &result) fmt.Println("Test_Ignore_Case_Underscores", result) } func Test_Ignore_Case_Underscores_Tps(t *testing.T) { var GoMybatisSqlResultDecoder = GoMybatisSqlResultDecoder{} var res = make([]map[string][]byte, 0) var resMap = make(map[string][]byte) resMap["name"] = []byte("xiao ming") resMap["Amount_1"] = []byte("1908.1") resMap["amount_2"] = []byte("1908.444") resMap["age_1"] = []byte("1908") resMap["age_2"] = []byte("1908") resMap["age_3"] = []byte("1908") resMap["age_4"] = []byte("1908") resMap["age_5"] = []byte("1908") resMap["age_6"] = []byte("1908") resMap["age_7"] = []byte("1908") resMap["age_8"] = []byte("1908") resMap["Bool"] = []byte("1") res = append(res, resMap) var result TestResult defer utils.CountMethodTps(100000, time.Now(), "Test_Ignore_Case_Underscores_Tps") for i := 0; i < 100000; i++ { GoMybatisSqlResultDecoder.Decode(nil, res, &result) } } func Test_Decode_Interface(t *testing.T) { var res = make([]map[string][]byte, 0) var resMap = make(map[string][]byte) resMap["name"] = []byte("xiao ming") resMap["Amount_1"] = []byte("1908.1") resMap["amount_2"] = []byte("1908.444") resMap["age_1"] = []byte("1908") resMap["age_2"] = []byte("1908") resMap["age_3"] = []byte("1908") resMap["age_4"] = []byte("1908") resMap["age_5"] = []byte("1908") resMap["age_6"] = []byte("1908") resMap["age_7"] = []byte("1908") resMap["age_8"] = []byte("1908") resMap["Bool"] = []byte("1") res = append(res, resMap) var resultMap = make(map[string]*ResultProperty) resultMap["id"] = &ResultProperty{ XMLName: "id", Column: "id", Property: "id", GoType: "string", } resultMap["name"] = &ResultProperty{ XMLName: "result", Column: "name", Property: "Name", GoType: "string", } resultMap["Amount_1"] = &ResultProperty{ XMLName: "result", Column: "Amount_1", Property: "amount_1", GoType: "string", } resultMap["amount_2"] = &ResultProperty{ XMLName: "result", Column: "Amount_2", Property: "amount_2", GoType: "string", } var result map[string]interface{} GoMybatisSqlResultDecoder{}.Decode(resultMap, res, &result) fmt.Println("Test_Decode_Interface", result) }
C++
UTF-8
2,925
2.9375
3
[]
no_license
#include "directoryviewer.h" #include <QDirModel> #include <QTreeView> #include <QHeaderView> #include <QInputDialog> #include <QMessageBox> DirectoryViewer::DirectoryViewer(QWidget *parent) : QDialog(parent) { model = new QDirModel; /*禁止模型的只读模式,表示模型可以将修改的数据写回文件系统*/ model->setReadOnly(false); /*设置模型的排序规则,目录优先、忽略大小写、以名称排序*/ model->setSorting(QDir::DirsFirst | QDir::IgnoreCase | QDir::Name); treeView = new QTreeView(this); /*设置关联的模型*/ treeView->setModel(model); /*设置列头的延展策略,当QTreeViwe的宽度大于所有列的宽度之和时,让(true)最后一列扩展至QTreeView的边界*/ treeView->header()->setStretchLastSection(true); /*设置序号为0的列进行排序,排序方式为升序*/ treeView->header()->setSortIndicator(0, Qt::AscendingOrder); /*在排序的列的列头上显示排序的小箭头*/ treeView->header()->setSortIndicatorShown(true); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); /*获取当前目录在模型中的索引值*/ QModelIndex index = model->index(QDir::currentPath()); /*然后展开index索引值的路径*/ treeView->expand(index); /*把视图的视口移动到索引值为index的路径的位置*/ treeView->scrollTo(index); /*让序号为0的列,自动适应内容的宽度,避免因为列的宽度不够,使内容显示为...符号*/ treeView->resizeColumnToContents(0); } DirectoryViewer::~DirectoryViewer() { } /* 获取选中项的索引值 */ void DirectoryViewer::createDirectory() { /*获取选中项的索引值*/ QModelIndex index = treeView->currentIndex(); if( !index.isValid() ) return; QString dirName = QInputDialog::getText(this, tr("Create Directory"), tr("Directory name")); if( !dirName.isEmpty() ) { /*创建目录*/ if( !model->mkdir(index, dirName).isValid() ) { QMessageBox::information(this, tr("Create Directory"), tr("Failed to create the directory")); } } } /* 获取模型中的选中项,判断是否有效 判断选中项是否为目录,是,则删掉,不是,则移除 如果操作失败,则显示一个失败的message */ void DirectoryViewer::removeDirectory() { /*获取选中项的索引值*/ QModelIndex index = treeView->currentIndex(); if( !index.isValid() ) return; bool ok; /*判断是目录,还是普通文件,然后分别调用对应的函数,进行删除*/ if( model->fileInfo(index).isDir() ) { ok = model->rmdir(index); } else { ok = model->remove(index); } if( !ok ) { QMessageBox::information(this, tr("Remove"), tr("Failed to remove %1").arg(model->fileName(index))); } }
JavaScript
UTF-8
13,078
2.71875
3
[ "MIT" ]
permissive
/* * Kalender Masehi/Hijriah * * Designed by ZulNs, @Gorontalo, Indonesia, 30 April 2017 */ function Calendar(isHijriMode, firstDayOfWeek, year, month) { if (typeof HijriDate === 'undefined') throw new Error('Required HijriDate() class!'); isHijriMode = !!isHijriMode; firstDayOfWeek = (firstDayOfWeek === undefined) ? 1 : ~~firstDayOfWeek; var self = this, thisDate, currentYear, currentMonth, currentDate, isMenuDisplayed = false, isSmallScreen = ( window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth ) < 480, hasEventListeners = !!window.addEventListener, calendarElm = document.createElement('div'), yearValueElm = document.createElement('li'), monthValueElm = document.createElement('li'), weekdaysElm = document.createElement('ul'), daysElm = document.createElement('ul'), menuItemContainerElm = document.createElement('ul'), menuCalendarModeElm = document.createElement('a'), menuFirstDayOfWeekElm = document.createElement('a'); createCalendar = function() { var rootMenuElm = document.createElement('nav'), rootMenuValueElm = document.createElement('a'), menuItem1Elm = document.createElement('li'), menuItem2Elm = document.createElement('li'), menuItem3Elm = document.createElement('li'), menuItem4Elm = document.createElement('li'), menuRefreshElm = document.createElement('a'), menuResetElm = document.createElement('a'), yearHeaderElm = document.createElement('ul'), prevYearContainerElm = document.createElement('li'), prevYearElm = document.createElement('a'), nextYearContainerElm = document.createElement('li'), nextYearElm = document.createElement('a'), monthHeaderElm = document.createElement('ul'), prevMonthContainerElm = document.createElement('li'), prevMonthElm = document.createElement('a'), nextMonthContainerElm = document.createElement('li'), nextMonthElm = document.createElement('a'); // Construct the calendar menuItem1Elm.appendChild(menuCalendarModeElm); menuItem2Elm.appendChild(menuFirstDayOfWeekElm); menuItem3Elm.appendChild(menuRefreshElm); menuItem4Elm.appendChild(menuResetElm); menuItemContainerElm.appendChild(menuItem1Elm); menuItemContainerElm.appendChild(menuItem2Elm); menuItemContainerElm.appendChild(menuItem3Elm); menuItemContainerElm.appendChild(menuItem4Elm); rootMenuElm.appendChild(rootMenuValueElm); rootMenuElm.appendChild(menuItemContainerElm); prevYearContainerElm.appendChild(prevYearElm); nextYearContainerElm.appendChild(nextYearElm); yearHeaderElm.appendChild(prevYearContainerElm); yearHeaderElm.appendChild(nextYearContainerElm); yearHeaderElm.appendChild(yearValueElm); prevMonthContainerElm.appendChild(prevMonthElm); nextMonthContainerElm.appendChild(nextMonthElm); monthHeaderElm.appendChild(prevMonthContainerElm); monthHeaderElm.appendChild(nextMonthContainerElm); monthHeaderElm.appendChild(monthValueElm); calendarElm.appendChild(rootMenuElm); calendarElm.appendChild(yearHeaderElm); calendarElm.appendChild(monthHeaderElm); calendarElm.appendChild(weekdaysElm); calendarElm.appendChild(daysElm); // Add class calendarElm.classList.add('calendar-wrapper'); rootMenuElm.classList.add('menu'); menuItemContainerElm.classList.add('menu-item'); yearHeaderElm.classList.add('year'); prevYearContainerElm.classList.add('prev'); nextYearContainerElm.classList.add('next'); monthHeaderElm.classList.add('month'); prevMonthContainerElm.classList.add('prev'); nextMonthContainerElm.classList.add('next'); weekdaysElm.classList.add('weekdays'); daysElm.classList.add('days'); // Set href rootMenuValueElm.href = '#'; prevYearElm.href = '#'; menuCalendarModeElm.href = '#'; menuFirstDayOfWeekElm.href = '#'; menuRefreshElm.href = '#'; menuResetElm.href = '#'; nextYearElm.href = '#'; prevMonthElm.href = '#'; nextMonthElm.href = '#'; // Set innerHTML //rootMenuValueElm.innerHTML = '&#x25bc;'; rootMenuValueElm.innerHTML = '&#x2261;'; //prevYearElm.innerHTML = '&#x276e;'; //nextYearElm.innerHTML = '&#x276f;'; prevYearElm.innerHTML = '&#x25c4;'; nextYearElm.innerHTML = '&#x25ba;'; prevMonthElm.innerHTML = '&#x25c4;'; nextMonthElm.innerHTML = '&#x25ba;'; menuRefreshElm.innerHTML = 'Refresh'; menuResetElm.innerHTML = 'Reset'; // Add event addEvent(window, 'resize', onResizeWindow); addEvent(prevMonthElm, 'click', onDecrementMonth); addEvent(nextMonthElm, 'click', onIncrementMonth); addEvent(prevYearElm, 'click', onDecrementYear); addEvent(nextYearElm, 'click', onIncrementYear); addEvent(rootMenuValueElm, 'click', onClickMenu); addEvent(menuItemContainerElm, 'click', onSelectMenuItem); addEvent(menuItemContainerElm, 'mouseleave', onUnhoverMenuItem); addEvent(menuItem1Elm, 'click', onChangeCalendarMode); addEvent(menuItem2Elm, 'click', onChangeFirstDayOfWeek); addEvent(menuItem3Elm, 'click', onRefresh); addEvent(menuItem4Elm, 'click', onReset); updateCalendarModeMenuLabel(); updateHeader(); createWeekdayGrids(); createDayGrids(); }, updateCalendarModeMenuLabel = function() { menuCalendarModeElm.innerHTML = 'Kalender ' + (isHijriMode ? 'Masehi' : 'Hijriah'); }, updateHeader = function() { yearValueElm.innerHTML = thisDate.getFullYear() + (isHijriMode ? ' H' : ' M'); monthValueElm.innerHTML = thisDate.getMonthName(); }, createWeekdayGrids = function() { var cl; for (var i = firstDayOfWeek; i < 7 + firstDayOfWeek; i++) { var day = document.createElement('li'); day.innerHTML = isSmallScreen ? thisDate.getDayShortName(i % 7) : thisDate.getDayName(i % 7); if (i == 5) day.classList.add('friday'); if (i % 7 == 0) day.classList.add('sunday'); weekdaysElm.appendChild(day); } menuFirstDayOfWeekElm.innerHTML = 'Mulai ' + thisDate.getDayName(1 - firstDayOfWeek); }, recreateWeekdayGrids = function() { while (weekdaysElm.firstChild) weekdaysElm.removeChild(weekdaysElm.firstChild); createWeekdayGrids(); }, createDayGrids = function() { var thisTime = thisDate.getTime(), ppdr = thisDate.getDay() - firstDayOfWeek; if (ppdr < 0) ppdr += 7; var pcdr = thisDate.getDaysInMonth(); var pndr = (ppdr + pcdr) % 7; pndr = pndr > 0 ? 7 - pndr : 0; thisDate.setDate(1 - ppdr); var thatDate = isHijriMode ? thisDate.getGregorianDate() : thisDate.getHijriDate(), pdate = thisDate.getDate(), sdate = thatDate.getDate(), pdim = thisDate.getDaysInMonth(), sdim = thatDate.getDaysInMonth(), smsn = thatDate.getMonthShortName(), isFri = 6 - firstDayOfWeek, isSun = 1 - firstDayOfWeek; for (var i = 1; i <= ppdr + pcdr + pndr; i++) { var pde = document.createElement('li'), sde = document.createElement('span'); sde.classList.add('footer-date'); if (i <= ppdr || i > ppdr + pcdr) { pde.classList.add('inactive-date'); } else { if ( thisDate.getFullYear() == currentYear && thisDate.getMonth() == currentMonth && pdate == currentDate ) pde.classList.add('current-date'); if (thisTime == 262368e5 && pdate == 5) pde.classList.add('specialz-date'); if (i % 7 == isFri) pde.classList.add('friday'); if (i % 7 == isSun) pde.classList.add('sunday'); } pde.innerHTML = pdate + '<br>'; sde.innerHTML = sdate + ' ' + smsn; pde.appendChild(sde); daysElm.appendChild(pde); pdate++; if (pdate > pdim) { pdate = 1; thisDate.setDate(1); thisDate.setMonth(thisDate.getMonth() + 1); pdim = thisDate.getDaysInMonth(); } sdate++; if (sdate > sdim) { sdate = 1; thatDate.setDate(1); thatDate.setMonth(thatDate.getMonth() + 1); sdim = thatDate.getDaysInMonth(); smsn = thatDate.getMonthShortName(); } } thisDate.setTime(thisTime); }, recreateDayGrids = function() { while (daysElm.firstChild) daysElm.removeChild(daysElm.firstChild); createDayGrids(); }, updateCalendar = function() { updateHeader(); recreateDayGrids(); } onDecrementMonth = function(evt) { evt = evt || window.event; thisDate.setMonth(thisDate.getMonth() - 1); updateCalendar(); return returnEvent(evt); }, onIncrementMonth = function(evt) { evt = evt || window.event; thisDate.setMonth(thisDate.getMonth() + 1); updateCalendar(); return returnEvent(evt); }, onDecrementYear = function(evt) { evt = evt || window.event; thisDate.setFullYear(thisDate.getFullYear() - 1); updateCalendar(); return returnEvent(evt); }, onIncrementYear = function(evt) { evt = evt || window.event; thisDate.setFullYear(thisDate.getFullYear() + 1); updateCalendar(); return returnEvent(evt); }, onClickMenu = function(evt) { evt = evt || window.event; isMenuDisplayed = !isMenuDisplayed; if (isMenuDisplayed) menuItemContainerElm.classList.add('show'); else menuItemContainerElm.classList.remove('show'); return returnEvent(evt); }, onSelectMenuItem = function(evt) { evt = evt || window.event; isMenuDisplayed = false; menuItemContainerElm.classList.remove('show'); return returnEvent(evt); }, onUnhoverMenuItem = function(evt) { evt = evt || window.event; isMenuDisplayed = false; menuItemContainerElm.classList.remove('show'); return returnEvent(evt); }, onChangeCalendarMode = function(evt) { //evt = evt || window.event; self.setHijriMode(!isHijriMode); //return returnEvent(evt); }, onChangeFirstDayOfWeek = function(evt) { //evt = evt || window.event; self.setFirstDayOfWeek(1 - firstDayOfWeek); //return returnEvent(evt); }, onRefresh = function(evt) { //evt = evt || window.event; self.refresh(); //return returnEvent(evt); }, onReset = function(evt) { //evt = evt || window.event; self.reset(); //return returnEvent(evt); }, onResizeWindow = function(evt) { evt = evt || window.event; if (isSmallScreen && calendarElm.clientWidth >= 480 || !isSmallScreen && calendarElm.clientWidth < 480) { isSmallScreen = !isSmallScreen; recreateWeekdayGrids(); } return returnEvent(evt); }, addEvent = function(elm, evt, callback) { if (elm == null || typeof(elm) == 'undefined') return; if (hasEventListeners) elm.addEventListener(evt, callback, false); else if (elm.attachEvent) elm.attachEvent('on' + evt, callback); else elm['on' + evt] = callback; }, returnEvent = function(evt) { if (evt.stopPropagation) evt.stopPropagation(); if (evt.preventDefault) evt.preventDefault(); else { evt.returnValue = false; return false; } }, getCurrentDate = function() { var nd = new Date(); currentYear = nd.getFullYear(); currentMonth = nd.getMonth(); currentDate = nd.getDate(); if (isHijriMode) { nd = new Date(currentYear, currentMonth, currentDate); nd = nd.getHijriDate(); currentYear = nd.getFullYear(); currentMonth = nd.getMonth(); currentDate = nd.getDate(); } }; this.getElement = function() { return calendarElm; }; this.setHijriMode = function(hm) { if ((hm == true || hm == false) && isHijriMode != hm) { isHijriMode = hm; getCurrentDate(); thisDate = isHijriMode ? thisDate.getHijriDate() : thisDate.getGregorianDate(); var dd = thisDate.getDate(); thisDate.setDate(1); if (dd >= 15) thisDate.setMonth(thisDate.getMonth() + 1); updateCalendarModeMenuLabel(); updateCalendar(); } }; this.setFirstDayOfWeek = function(fdow) { if ((fdow == 0 || fdow == 1) && fdow != firstDayOfWeek) { firstDayOfWeek = fdow; recreateWeekdayGrids(); recreateDayGrids(); } }; this.setYear = function(year) { if (!isNaN(year) && year != thisDate.getFullYear()) { thisDate.setFullYear(year); updateCalendar(); } }; this.setMonth = function(month) { if (!isNaN(month) && month != thisDate.getMonth()) { thisDate.setMonth(month); updateCalendar(); } }; this.refresh = function() { var cy = currentYear, cm = currentMonth, cd = currentDate; getCurrentDate(); if ( (currentYear != cy || currentMonth != cm || currentDate != cd) && thisDate.getFullYear() == cy && thisDate.getMonth() == cm ) recreateDayGrids(); }; this.reset = function() { getCurrentDate(); thisDate = isHijriMode ? new HijriDate(currentYear, currentMonth, 1, 6) : new Date(currentYear, currentMonth, 1); updateCalendar(); }; getCurrentDate(); if (isNaN(year)) { year = currentYear; if (isNaN(month)) month = currentMonth; } else { if (isNaN(month)) month = 0; } thisDate = isHijriMode ? new HijriDate(year, month, 1, 6) : new Date(year, month, 1); createCalendar(); }
Java
UTF-8
9,428
3.546875
4
[]
no_license
package Assignment1; /** * Main class - game that has player as the Jedi with his forces fighting agaist Sithlord * @author Pongsathorn Cherngchaosil 012124071 */ import java.util.Random; import java.util.Scanner; public class gameMain { public static void main( String args[]){ //Initialize variable for holding the name of the player String jediName; //Arrays of strings containing the name of all the missions String[] missionsName = {"Hunt the Sith Lord", "Capture the Imperial Base"}; //Arrays of Entity that contain each team character. Entity[] rebelTeam = new Entity[8]; Entity[] imperialTeam = new Entity[6]; //Asking player to input a name for the Jedi then create Jedi as the first character in the team. System.out.println("Welcome to the Star Wars Galaxy\nPlease choose a name for your Jedi:"); @SuppressWarnings("resource") Scanner reader = new Scanner(System.in); jediName = reader.nextLine(); rebelTeam[0] = new Jedi(jediName,"For the Republic","blue"); //Initialize the rest of the Jedi team for(int i = 1; i < 6; i++){ rebelTeam[i] = new Rebel("Rebel Trooper " + i, "Pew pew pew...."); } rebelTeam[6] = new Medical("2-1B"); rebelTeam[7] = new Astromech("R2-D2"); //Initialize the imperial team. imperialTeam[0] = new SithLord("Darth Vadar","Force is Strong with this one.","red"); for(int i = 1; i < 6; i++){ imperialTeam[i] = new Stormtrooper("Stromtrooper " + i, "Bam bam bam"); } //Ask the player to choose a mission System.out.println("\nChoose a Mission:"); int missionNumber; for( int i = 0; i < missionsName.length; i++ ){ System.out.println((i+1) + ". " + missionsName[i] ); } missionNumber = checkInt(1,missionsName.length); /* * Scenario 1 - Run across the Sith Lord with troops * Scenario 2 - Run across door * Scenario 3 - Run across Computer */ //After the player selected the mission, run through each scenario of the mission int[][] scenario = {{1,1,1}, {1,2,3}}; for(int i = 0; i < scenario[missionNumber-1].length; i++){ playScenario(scenario[missionNumber-1][i],rebelTeam,imperialTeam); //Special event where player will fight Imperial Team more than once if(missionNumber == 1){ if(i<=1){ System.out.println("Enemies escaped!!!"); reset(imperialTeam); } } //If the player died during the mission, mission is ended. if(!rebelTeam[0].getActive()) break; } //Upon ending the mission, output the appropriate announcement. if(rebelTeam[0].getActive()){ System.out.println("\nMISSION COMPLETE!\n"); }else{ System.out.println("\nYour Hero has fallen"); } } /** * Play each scenario and responds according to it. * @param scenario The type of scenario that will be run * @param rebel The Rebel Team * @param imperial The Imperial Team */ public static void playScenario(int scenario,Entity[] rebel, Entity[] imperial){ switch(scenario){ case 1: //Rebel Team fight Imperial Team fight(rebel, imperial); break; case 2: //The player encounter a door System.out.print("You ran across a gaint door\nHave droid open the door? 1(Yes) or 0(No):"); int DECISION_DOOR = checkInt(0,1); if(DECISION_DOOR < 1) { System.out.print("You ran across a gaint door\nHave droid open the door? 1(Yes) or 0(No):"); DECISION_DOOR = checkInt(0,1); } rebel[7].doTask(new Door("Door",1)); break; case 3: //The player encounter a computer System.out.print("You ran across a computer room.\nHave droid hack the computer? 1(Yes) or 0(No):"); int DECISION_COMPUTER = checkInt(0,1); while(DECISION_COMPUTER < 1) { System.out.print("You ran across a computer room.\nHave droid hack the computer? 1(Yes) or 0(No):"); DECISION_COMPUTER = checkInt(0,1); } rebel[7].doTask(new Computer("Computer",1)); break; } } /** * This method take care of the fighting simulation.Printing out detail of the fight and ask * player for actions. * @param rebel Rebel Team * @param imperial Imperial Team */ public static void fight(Entity[] rebel, Entity[] imperial){ System.out.println("You run across the Sith Lord, he has troops with him. Attack!"); //While the Jedi still alive and one or more of the imperial team is still active, keep playing. while(rebel[0].getActive() && !win(imperial)){ System.out.println("\nGood Guys\n_________"); //Print details of the Rebel team printEntity(rebel); System.out.println("\nBad Guys\n________"); //Print details of the Imperial Team printEntity(imperial); //Give player choice of actions to choose System.out.println("\nWhat do you want to do?"); System.out.println("1. Attack.\n2. Have the droid to heal someone"); int PLAYER_DECISION = checkInt(1,3); //response according to the action the player chose. if(PLAYER_DECISION != 2){ //attack action //tell Jedi to do it task. chooseEntity selected the target that will be hit by Jedi attack rebel[0].doTask(chooseEntity(imperial)); }else{ // heal action System.out.println("\nChoose someone to heal:"); //Given the options for healing. for(int i =0; i < rebel.length-2; i++){ System.out.println((i+1)+". "+rebel[i].getName()); } int CHOOSE_HEAL = checkInt(1,rebel.length-2)-1; System.out.print('\n'+rebel[6].getName()+" heal "+rebel[CHOOSE_HEAL].getName()); //Tell the Medical Droid to heal. rebel[6].doTask(rebel[CHOOSE_HEAL]); } //Running through the Rebel team and telling them to do their task. for(int i = 1; i < rebel.length; i++){ //if all the imperial characters are down then end the loop. if(win(imperial)){ break; } //check if the character still active to do their task. if(rebel[i].getActive()){ rebel[i].doTask(imperial[pickTarget(imperial)]); }else{ System.out.println(rebel[i].getName()+ " is down."); } } System.out.println(); //Running through the imperial team and telling them to do their task. for(Entity e:imperial){ //if the player's character is down then the game will end. if(!rebel[0].getActive()){ break; } //check if the character still active to do their task. if(e.getActive()){ e.doTask(rebel[pickTarget(rebel)]); }else{ System.out.println(e.getName()+ " is down."); } } } //Output the appropriate announcement according to the situation. if(win(imperial)){ System.out.println("\nThe enemies are defeated!!!!\n"); } if(!rebel[0].getActive()){ System.out.println("\nGAME OVER!!!\n"); } } /** * This method is use by all the character except the player to choose the valid target to attack. * @param e The array of entity that will be selected. * @return the location of that entity in the array. */ public static int pickTarget(Entity[] e){ //generate a random location within the array Random random = new Random(); int PICK_TARGET = random.nextInt(e.length); //if the target is inactive or it is a droid then redo. while((!e[PICK_TARGET].getActive()|| (e[PICK_TARGET] instanceof Droid))){ PICK_TARGET = random.nextInt(e.length); } return PICK_TARGET; } /** * This method check if all the imperial team members are down * @param imperial Array of imperial team. * @return if all imperial team member are inactive, return true. */ public static boolean win(Entity[] imperial){ boolean win = true; for(Entity e:imperial){ if(e.getActive()) win = false; } return win; } /** * Reset the imperial team * @param e The array of the imperial team. */ public static void reset(Entity[] e){ e[0].modifyHp(100); for(int i = 1; i < e.length; i++){ e[i].modifyHp(50); } } /** * This method is use by Jedi character to ask player to select an Entity to attack. * @param entity Imperial Team. * @return The entity that has been selected. */ public static Entity chooseEntity(Entity[] entity){ System.out.println("\nChoose someone to attack:"); //print out the list of imperial team. for(int i =0; i < entity.length; i++){ System.out.println((i+1)+". "+entity[i].getName()); } //selected the entity. int CHOOSE_ATTACK = checkInt(1,entity.length); return entity[CHOOSE_ATTACK-1]; } /** * Print the list of Entity with their Hp. * @param e The array of Entity. */ public static void printEntity(Entity[] e){ final int SPACE_INDENT = 20; //Loop through each entity and print out its detail. for( Entity i: e){ System.out.print(i.getName()); for ( int ii = 0; ii < ( SPACE_INDENT - i.getName().length() ); ii++ ){ System.out.print(" "); } System.out.println(i.getHp()); } } /** * Check for invalid input. * @param low The the lowest value possible. * @param high The highest value possible * @return The valid value. */ @SuppressWarnings("resource") public static int checkInt( int low, int high){ Scanner in = new Scanner(System.in); boolean valid = false; int validNum = 0; while(!valid){ if(in.hasNextInt()){ validNum = in.nextInt(); if( validNum >= low && validNum <= high){ valid = true; }else{ System.out.print("Invalid- Retry: "); } }else{ in.next(); System.out.print("Invalid input- Retry: "); } } return validNum; } }
JavaScript
UTF-8
39,442
2.78125
3
[]
no_license
window.addEventListener("load", setup, false); /* AJOUTER UNE ANNEE - mettre à jour le fichier index.csv - generer la texture et la place dans data/years/ */ var conteneur = "carte"; // id de la balise qui doit contenir la carte var tailleCartePourTexture = 520; // largeur et hauteur de la carte à 520 pour avoir la totalité de la carte pour créer la texture var index; // garde en mémoire les infos de index.csv var canvas; // instance de la classe Canvas qui contient la scene 3d et les mouvements camera var dessin2d; // instance de la classe Dessin2D pour la carte en mode 2D var dessin3d; // instance de la classe Dessin3D pour la carte en mode 3D var limitYear = 2014; // année à mettre à jour dès qu'on rajoute une année var currentYear; // année en cours visualiser dans le programme var langue; // FR pour francais, autre pour anglais var pathFrontieres; // coordonnées des dessins des frontieres, recuperer dans dessin2d et dessiner dans dessin3d var mode = "2d"; // mode 2d / 3d var loader; // picto gif de chargement var noWebgl; // boolean si le navigateur ou l'ordinateur ne supporte pas WebGL function lireCsv(url, callback) { d3.csv(url, function(d){ callback(null, d); }); } function lireJson(url, callback) { d3.json(url, function(d){ callback(null, d); }); } function setup() { if( $("html").attr("lang") == "fr"){ langue = "FR"; } else { langue = "EN"; } currentYear = limitYear; pathFrontieres = []; mode = "2d"; noWebgl = false; // chargement du gif loader loader = new Image(); loader.addEventListener("load", function(){ document.getElementById("main").appendChild(this); }, false); loader.src= "data/loader.gif"; loader.id = "loader"; // gestion boutons 2D document.getElementById("btn_precedent").addEventListener("click", function(){ changementAnnee(-1); }, false); document.getElementById("btn_suivant").addEventListener("click", function(){ changementAnnee(1); }, false); document.getElementById("btn_2d").addEventListener("click", function(){ passage2d(); }, false); document.getElementById("btn_3d").addEventListener("click", function(){ passage3d(); }, false); document.getElementById("btn_in").addEventListener("click", function(){ zoom(1); }, false); document.getElementById("btn_out").addEventListener("click", function(){ zoom(-1); }, false); document.getElementById("btn_reset").addEventListener("click", function(){ reset(); }, false); dessin2d = new Dessin2D(); dessin2d.setup(); // si WegGL est supporté var canvasTest = document.createElement( 'canvas' ); if(window.WebGLRenderingContext && ( canvasTest.getContext( 'webgl' ) || canvasTest.getContext( 'experimental-webgl' ))) { // 3D canvas = new Canvas(); canvas.setup(); dessin3d = new Dessin3D(); dessin3d.setup(); animate(); } else { noWebgl = true; } action_resetPositionCarte(); } // fonction qui boucle sur elle meme function animate() { setTimeout(animate, 1000/50); // règle le framerate if(mode == "3d") { canvas.draw(); } } ////////////////////////////////////////////////////////// /* FUNCTION DES PASSAGES ENTRE LES DEUX MODES 2D / 3D */ //////////////////////////////////////////////////////// function passage2d() { if(mode == "3d" || mode == "noWebgl") { loader.style.display = "block"; // loader apparait action_removeFocusPaysListe(); // retire le surlignage en mode 2d du pays dans la liste action_resetPositionCarte(); // la carte est recentrée if(!noWebgl){ canvas.initCam(); } // retour de la camera à sa position d'origine setTimeout(function(){ mode = "2d"; onresize(); changementAnnee(0); document.body.setAttribute("class", "mode2d"); loader.style.display = "none"; // loader disparait }, 3000); } } function passage3d() { if(!noWebgl) { if(mode == "2d") { loader.style.display = "block"; dessin2d.reset(); action_resetPositionCarte(); setTimeout(function(){ document.body.setAttribute("class", "mode3d"); mode = "3d"; changementAnnee(0); dessin2d.resize(tailleCartePourTexture, tailleCartePourTexture, 80, tailleCartePourTexture/2, tailleCartePourTexture/2); //dessin2d.createTextureFromSvg(); dessin3d.loadTexture(); canvas.mouvementCool(); }, 800); canvas.onResize(window.innerWidth, window.innerWidth); } } else { document.body.setAttribute("class", "noWebgl"); mode = "noWebgl"; } } ////////////////////////////////////////////////////////// ////////////// DESSIN 2D //////////////////////////////// //////////////////////////////////////////////////////// var Dessin2D = function() { this.projection; this.svg; this.path; this.scale; this.focusPosition; this.traitSahara; this.svgFond; this.mouseDown; this.xSouris, this.xSourisOld; this.ySouris, this.ySourisOld; this.setup = function() { this.scale = 1; this.projection = d3.geo.mercator() .scale(80) .translate([tailleCartePourTexture / 2, tailleCartePourTexture / 2]); this.svg = d3.select("#"+conteneur).append("svg") .attr("id", "carte2d") .attr("width", tailleCartePourTexture) .attr("height", tailleCartePourTexture); this.path = d3.geo.path().projection(this.projection); this.focusPosition = [ tailleCartePourTexture/2, tailleCartePourTexture/2 ]; this.mouseDown = false; this.xSouris = 0; this.xSourisOld = 0; this.ySouris = 0; this.ySourisOld = 0; this.svgFond = this.svg.append("svg:rect").attr("x", 0).attr("y", 0) .attr("width", tailleCartePourTexture).attr("height", tailleCartePourTexture) .style("fill", "rgba(100, 0, 0, 0)"); // INTERACTION var clone = this; var t = document.getElementById("carte2d"); t.addEventListener("mousemove", function(event){ clone.onMouseMove(event); }, false); t.addEventListener("mousedown", function(event){ clone.onMouseDown(event); }, false); t.addEventListener("mouseup", function(event){ clone.onMouseUp(event); }, false); t.addEventListener("mouseout", function(event){ clone.onMouseUp(event); }, false); // releve le clic si tu sort du canvas queue() .defer(lireJson, "data/world-countries-clean.json") .defer(lireCsv, "data/index.csv") .awaitAll(this.draw); } this.draw = function(error, results){ index = results[1]; var features = results[0].features; var frontieres = dessin2d.svg.append("svg:g") .selectAll("path") .data(features) .enter().append("svg:path") .attr("class", "land") .attr("id", function(d){ return "svg"+d.id; }) .attr("d", function(d){ return dessin2d.path(d); }) .style("fill", "rgba(200, 200, 200, 1)") .style("stroke-width", "0.2") .style("stroke", "#888") .each(function(d, i){ // calcul des frontieres pour la 3d pathFrontieres[i] = getPath(dessin2d.path(d)); for (var i = 0; i < index.length; i++) { if(d.id == index[i].iso) { // Remplir la liste du classement var pays = d3.select("#liste").append("tr").attr("class", "itemPays") //.style("position", "absolute") .attr("id", index[i].iso) .on("click", function(){ clicPaysClassement(this.id); }) pays.append("td").attr("class","position"); pays.append("td").attr("class","name"); pays.append("td").attr("class","diff"); pays.append("td").attr("class","note"); } } }) .on("click", function(d){ clicPaysCarte(d.id); }); dessin2d.suiteDessin(); changementAnnee(0); if(!noWebgl){ dessin3d.draw(canvas.scene); } onresize(); loader.style.display = "none"; $("#main").slideDown(500); } this.suiteDessin = function() { var pointSahara1 = this.projection([-13.1648, 27.6665]); var pointSahara2 = this.projection([-8.6686, 27.6665]); this.traitSahara = dessin2d.svg.append("svg:line") .attr("x1", pointSahara1[0]) .attr("y1", pointSahara1[1]) .attr("x2", pointSahara2[0]) .attr("y2", pointSahara2[1]) .attr("stroke-width", 0.5) .attr("stroke", "#000"); } this.redrawSvg = function(min, max) { if(mode == "3d") { this.svgFond.style("fill", "rgba(0,0,0,1)"); } else { this.svgFond.style("fill", "rgba(0,0,0,0)"); } for(var i = 0; i < index.length; i++) { // if(currentYear > 2012) // { // var score = getScoreCurrentYear(i); // var rvb = this.couleurPaysNote(score, min, max); // } else { /* /////////// Basé sur la position /////////// */ var hauteur = getPositionCurrentYear(i); var rvb = this.couleurPaysRang(hauteur); //} var pays = this.svg.select("#svg"+index[i].iso); pays.style("fill", "rgba("+rvb[0]+","+rvb[1]+","+rvb[2]+", 1)" ); pays.style( "stroke", "rgba("+rvb[0]+","+rvb[1]+","+rvb[2]+", 1)" ); if(index[i].iso == "MAR") { var pays = this.svg.select("#svgESH"); pays.style("fill", "rgba("+rvb[0]+","+rvb[1]+","+rvb[2]+", 1)" ); pays.style( "stroke", "rgba("+rvb[0]+","+rvb[1]+","+rvb[2]+", 1)" ); } } } this.couleurPaysNote = function(score, min, max) { var red, green, blue; if(mode == "3d") { var gris = map(score, max, min, 0, 255); gris = Math.floor(gris); red = green = blue = gris; } else { var color1 = [ 0, 0, 0 ]; var color2 = [ 253, 227, 6 ]; var color3 = [ 241, 151, 3 ]; var color4 = [ 218, 0 , 46 ]; var color5 = [ 46 , 16 , 47 ]; var fourchette = max - min; var transition = [ 0.25*fourchette, 0.5*fourchette, 0.75*fourchette, 0.9*fourchette ]; if(score < transition[0]){ // de vert à jaune red = map(score, min, transition[0], color1[0], color2[0]); green = map(score, min, transition[0], color1[1], color2[1]); blue = map(score, min, transition[0], color1[2], color2[2]); } else if(score < transition[1]) { // de jaune à orange red = map(score, transition[0], transition[1], color2[0], color3[0]); green = map(score, transition[0], transition[1], color2[1], color3[1]); blue = map(score, transition[0], transition[1], color2[2], color3[2]); } else if(score < transition[2]){ // de orange à rouge red = map(score, transition[1], transition[2], color3[0], color4[0]); green = map(score, transition[1], transition[2], color3[1], color4[1]); blue = map(score, transition[1], transition[2], color3[2], color4[2]); } else { red = map(score, transition[2], transition[3], color4[0], color5[0]); green = map(score, transition[2], transition[3], color4[1], color5[1]); blue = map(score, transition[2], transition[3], color4[2], color5[2]); } red = Math.floor(red); green = Math.floor(green); blue = Math.floor(blue); } return [red, green, blue]; } this.couleurPaysRang = function(hauteur) { var hauteurMax = index.length; var red, green, blue; var color1 = [250,255,250]; var color2 = [253,227,6 ]; var color3 = [241,151,3 ]; var color4 = [218,0 ,46 ]; var color5 = [46 ,16 ,47 ]; var transition = [0.25*hauteurMax,0.5*hauteurMax,0.75*hauteurMax,hauteurMax]; if(hauteur < transition[0]){ // de vert à jaune red = map(hauteur, 0, transition[0], color1[0], color2[0]); green = map(hauteur, 0, transition[0], color1[1], color2[1]); blue = map(hauteur, 0, transition[0], color1[2], color2[2]); } else if(hauteur < transition[1]) { // de jaune à orange red = map(hauteur, transition[0], transition[1], color2[0], color3[0]); green = map(hauteur, transition[0], transition[1], color2[1], color3[1]); blue = map(hauteur, transition[0], transition[1], color2[2], color3[2]); } else if(hauteur < transition[2]){ // de orange à rouge red = map(hauteur, transition[1], transition[2], color3[0], color4[0]); green = map(hauteur, transition[1], transition[2], color3[1], color4[1]); blue = map(hauteur, transition[1], transition[2], color3[2], color4[2]); } else { red = map(hauteur, transition[2], transition[3], color4[0], color5[0]); green = map(hauteur, transition[2], transition[3], color4[1], color5[1]); blue = map(hauteur, transition[2], transition[3], color4[2], color5[2]); } red = Math.floor(red); green = Math.floor(green); blue = Math.floor(blue); return [red, green, blue]; } this.resize = function(newWidth, newHeight, scale, translateX, translateY) { this.projection .translate( [ translateX, translateY ] ) .scale(scale); this.svg .attr("width", newWidth) .attr("height", newHeight); this.focusPosition = [ newWidth/2, newHeight/2 ]; this.svg.selectAll("path").attr('d', this.path); var pointSahara1 = this.projection([-13.1648, 27.6665]); var pointSahara2 = this.projection([-8.6686, 27.6665]); this.traitSahara .attr("x1", pointSahara1[0]) .attr("y1", pointSahara1[1]) .attr("x2", pointSahara2[0]) .attr("y2", pointSahara2[1]); } this.zoom = function(sens) { if(sens < 0) { if(this.scale > 1) { this.scale--; } } else { if(this.scale < 4) { this.scale++; } } this.scaling(); } this.scaling = function() { var w = parseInt(this.svg.attr("width")); var h = parseInt(this.svg.attr("height")); this.traitSahara.transition().duration(750) .attr("transform", "translate(" + w / 2 + ", " + h / 2 + ")scale("+this.scale+")translate(" + -this.focusPosition[0] + "," + -this.focusPosition[1] + ")"); this.svg.selectAll("path").transition().duration(750) .attr("transform", "translate(" + w / 2 + ", " + h / 2 + ")scale("+this.scale+")translate(" + -this.focusPosition[0] + "," + -this.focusPosition[1] + ")"); } this.moveToPosition = function(position) { this.focusPosition = position; this.scaling(); } this.colorerPays = function(iso, position) { var paysDom = document.getElementById("svg"+iso); // reset focus style d3.selectAll(".itemPays").attr("class", "itemPays"); // set focus style d3.select("#"+iso).attr("class", "itemPays focusList"); bbox = paysDom.getBBox(); this.focusPosition = [bbox.x + bbox.width/2, bbox.y + bbox.height/2]; this.scale = 2; this.scaling(); } this.reset = function() { var w = parseInt(this.svg.attr("width")); var h = parseInt(this.svg.attr("height")); this.focusPosition = [ w/2, h/2 ]; this.scale = 1; this.scaling(); this.redrawSvg(); } this.onMouseMove = function(event) { if(this.mouseDown) { this.xSouris = event.clientX; this.ySouris = event.clientY; var decalageX = (this.xSouris - this.xSourisOld) * 0.1; var decalageY = (this.ySouris - this.ySourisOld) * 0.1; //this.scaling(); this.xSourisOld = this.xSouris; this.ySourisOld = this.ySouris; } return false; } this.onMouseDown = function(event) { this.mouseDown = true; this.xSouris = event.clientX; this.xSourisOld = this.xSouris; this.ySouris = event.clientY; this.ySourisOld = this.ySouris; } this.onMouseUp = function(event) { this.mouseDown = false; } this.createTextureFromSvg = function() { var svgImg = document.getElementById("carte2d"); // transforme le svg en image var xml = new XMLSerializer().serializeToString(svgImg); var data = "data:image/svg+xml;base64," + btoa(xml); var imageTexture = new Image(); var clone = this; imageTexture.addEventListener("load", clone.blurImage, false); imageTexture.src = data; } this.blurImage = function() { var canvas2d = document.createElement( "canvas" ); var ctx = canvas2d.getContext('2d'); canvas2d.width = tailleCartePourTexture; canvas2d.height = tailleCartePourTexture; canvas2d.id = "canvas2d"; ctx.drawImage( this, 0, 0, canvas2d.width, canvas2d.height ); // application du blur varBlur(ctx, function(x, y){ return 6.9; }); document.body.appendChild(canvas2d); // creation de la texture THREE var textureCarted3js = new THREE.Texture( canvas2d ); textureCarted3js.needsUpdate = true; dessin3d.updateTexture( textureCarted3js ); } } ////////////////////////////////////////////////////////// ////////////// DESSIN 3D //////////////////////////////// //////////////////////////////////////////////////////// var Dessin3D = function() { this.uniformsTerrain; this.setup = function() { var cube = THREE.ImageUtils.loadTexture('data/square.png'); this.uniformsTerrain = { lerp: { type:'f', value: 0.0 }, displacement: { type:'t', value: null }, tWireframe: { type:'t', value: cube } }; } this.draw = function( scene ) { this.displayBorders( scene ); this.displayRelief( scene ); //this.displayRepere( scene ); } this.updateTexture = function( texture ) { this.uniformsTerrain[ "displacement" ].value = texture; loader.style.display = "none"; } this.displayBorders = function( scene ) { var materialBorder = new THREE.LineBasicMaterial({ color:0xffffff, opacity: 1, linewidth: 1 }); for(var k = 0; k < pathFrontieres.length; k++) { var coor = pathFrontieres[k]; for(var i = 0; i < coor.length; i++) { var geometryBorder = new THREE.Geometry(); for(var j = 0; j < coor[i].length; j+=2) { var position = projectionfor3d([ coor[i][j], coor[i][j+1] ]); geometryBorder.vertices.push(new THREE.Vector3(position[0], position[1], 0)); } // dernier point pour fermer la forme var position = projectionfor3d([ coor[i][0], coor[i][1] ]); geometryBorder.vertices.push(new THREE.Vector3(position[0], position[1], 0)); // ajout dans la scene var line = new THREE.Line(geometryBorder, materialBorder); line.position.set(0, 0, 20); scene.add(line); } } pathFrontieres = null; } this.displayRelief = function( scene ) { var n = 0; function loaded() { n++; console.log("loaded: " + n); if (n == 2) { terrain.visible = true; } } // MATERIAL var material = new THREE.ShaderMaterial({ uniforms: this.uniformsTerrain, vertexShader: document.getElementById("vertexShader").textContent, fragmentShader: document.getElementById("fragmentShader").textContent, fog: false }); var geometryTerrain = new THREE.PlaneGeometry(tailleCartePourTexture, tailleCartePourTexture, 256, 256 ); //geometryTerrain.computeFaceNormals(); //geometryTerrain.computeVertexNormals(); //geometryTerrain.computeTangents(); var terrain = new THREE.Mesh( geometryTerrain, material ); terrain.position.set(0, 0, -100); scene.add(terrain); loaded(); this.terrainShader = null; } this.displayRepere = function(scene) { var geometrie = new THREE.Geometry(); geometrie.vertices.push(new THREE.Vector3(0, 0, 0)); geometrie.vertices.push(new THREE.Vector3(100, 0, 0)); var ligne = new THREE.Line(geometrie, new THREE.LineBasicMaterial({ color: 0xff0000 })); scene.add(ligne); geometrie = new THREE.Geometry(); geometrie.vertices.push(new THREE.Vector3(0, 0, 0)); geometrie.vertices.push(new THREE.Vector3(0, 100, 0)); ligne = new THREE.Line(geometrie, new THREE.LineBasicMaterial({ color: 0x00ff00 })); scene.add(ligne); geometrie = new THREE.Geometry(); geometrie.vertices.push(new THREE.Vector3(0, 0, 0)); geometrie.vertices.push(new THREE.Vector3(0, 0, 100)); ligne = new THREE.Line(geometrie, new THREE.LineBasicMaterial({ color: 0x0000ff })); scene.add(ligne); } this.loadTexture = function() { // if(currentYear > 2012) // pas de score en 2012 donc on prend le rang // { // var textureCarted3js = THREE.ImageUtils.loadTexture('data/years/score'+currentYear+'.png', null, function(){ // dessin3d.updateTexture( textureCarted3js ); // }); // } else { /* heightmap en fonction de la note */ var textureCarted3js = THREE.ImageUtils.loadTexture('data/years/'+currentYear+'.png', null, function(){ dessin3d.updateTexture( textureCarted3js ); }); //} loader.style.display = "none"; } } ///////////////////////////////////////////////////////////////////////////////// ///////////// INTERACTION ////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// function changementAnnee(sens) { if(mode == "3d") { loader.style.display = "block"; } if(sens > 0 && currentYear < limitYear) { currentYear++; } else if(sens < 0 && currentYear > 2012) { currentYear--; } var displayYear = document.getElementById("current_year"); displayYear.innerHTML = currentYear; var already = []; var classement = d3.select("#liste"); // Extremites notes var min, max; min = max = getScoreCurrentYear(0); for(var i = 0; i < index.length; i++) { var espaceEntreDeux = 30; var top = 0; top = getPositionCurrentYear(i); var positionPays = top; var paysD3 = classement.select("#"+index[i].iso); var paysD3name = paysD3.select(".name"); var paysD3position = paysD3.select(".position"); var paysdessin3diff = paysD3.select(".diff"); var paysdessin3note = paysD3.select(".note"); // SI PAS DE NOTES if(!isNaN(positionPays)) { // REGLER EGALITES for(var j = 0; j < already.length; j++) { if(top == already[j]) { top += 1; positionPays = "&nbsp;"; } } already.push(top); top *= espaceEntreDeux; var nomPays = ""; if(langue == "FR"){ nomPays = index[i].nom; } else { nomPays = index[i].name; } var diff = ""; var note = getScoreCurrentYear(i); if(currentYear == 2012){ diff = "-"; } else { currentYear--; var oldPosition = getPositionCurrentYear(i); currentYear++; diff = oldPosition - positionPays; if(diff == 0 || isNaN(diff) ) { diff = "0"; } if(diff > 0){ diff = "+"+diff; } } paysD3.transition() .duration(700) .style("display", "table") .style("top", top+"px"); paysD3name.html(nomPays); paysD3position.html(positionPays); paysdessin3diff.html(diff); paysdessin3note.html(note); // MIN MAX CLASSEMENT var score = getScoreCurrentYear(i); if(min > score){ min = score; } if(max < score){ max = score; } } else { paysD3.style("display", "none"); } } dessin2d.redrawSvg(min, max); if(mode == "3d") { loader.style.display = "block"; setTimeout( function(){ dessin3d.loadTexture(); }, 700 ); } } function reset() { if(mode == "3d") { action_resetPositionCarte(); // la carte est recentrée canvas.initCam(); } else { action_resetPositionCarte(); dessin2d.reset(); } } function zoom(sens) { if(mode == "3d") { canvas.zoom(sens); } else { dessin2d.zoom(sens); } } function rotation(range) { canvas.rotation(range); } ///////////////////////////////////////////////////////////////////////////////// //////////////////// CLIC PAYS ///////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// function clicPaysClassement(isoPays) { for(var i = 0; i < index.length; i++) { if(isoPays == index[i].iso) { if(mode == "3d") { var positionPays = projectionfor3d(getGeoCoord(index[i].latitude, index[i].longitude)); canvas.moveCamToPosition(positionPays); } else { action_centrePositionCarte(); //dessin2d.moveToPosition(getGeoCoord(index[i].latitude, index[i].longitude)); dessin2d.colorerPays(isoPays, getPositionCurrentYear(i)); focusPaysCarte(isoPays); } } } } function clicPaysCarte(isoPays) { action_focusPaysListe(isoPays); focusPaysCarte(isoPays); } function focusPaysCarte(isoPays) { d3.selectAll(".land").style("stroke-width", "0.2").style("stroke", "#888"); d3.select("#svg"+isoPays).style("stroke-width", "1").style("stroke", "#fff"); } ////////////////////////////////////////////////////////// ////////////// UTILS //////////////////////////////////// //////////////////////////////////////////////////////// function getPositionCurrentYear(i) { switch(currentYear) { case 2014: return parseInt(index[i].an2014); break; case 2013: return parseInt(index[i].an2013); break; case 2012: return parseInt(index[i].an2012); break; default: return "-"; break; } } function getScoreCurrentYear(i) { switch(currentYear) { case 2014: return parseFloat(index[i].sco2014); break; case 2013: if(index[i].iso == "PER"){ console.log(index[i].name+" // "+index[i].sco2013+" // "+index[i].capitale); } return parseFloat(index[i].sco2013); break; default: return "-"; break; } } function getPath(path) { var chaine = path.replace(/Z/g,""); chaine = chaine.replace(/[L,]/g," "); var pathFragment = chaine.split("M"); var coor = []; for(var i = 1; i < pathFragment.length; i++) // on commence a un car le split fait une premiere partie vide { var coordonnees = pathFragment[i].split(" "); coor[i-1] = []; for(var j = 0; j < coordonnees.length; j++) { coor[i-1][j] = parseFloat(coordonnees[j]); } } return coor; } function getGeoCoord(x, y) { var latitude = x; var longitude = y; var traductionCoor = [ 0, 0 ]; if(latitude != "#N/A" && longitude != "#N/A") { var lat = parseFloat(latitude.substring(0, latitude.length-1)); var sens = latitude.substring(latitude.length-1, latitude.length); if(sens == "S"){ lat *= -1; } var long = parseFloat(longitude.substring(0, longitude.length-1)); sens = longitude.substring(longitude.length-1, longitude.length); if(sens == "W"){ long *= -1; } coordonneesCapitale = [ long, lat ]; var traductionCoor = dessin2d.projection(coordonneesCapitale); } return traductionCoor; } function projectionfor3d(array) { array[0] = array[0]-tailleCartePourTexture/2; array[1] = (array[1]-tailleCartePourTexture/2)*(-1); return array; } //////////////////////////////////////////////////////////////////////////////////////// //////////// CANVAS /////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// var Canvas = function() { this.canvas; this.renderer; this.scene; this.centreCarte; this.xSouris, this.xSourisOld; this.ySouris, this.ySourisOld; this.mouseDown; this.camera; this.angleCamera; this.rayonCamera; this.positionInitCam; this.focusCamera; this.transitionCamera; this.transitionFocusCamera; this.setup = function() { var VIEW_ANGLE = 45, ASPECT = tailleCartePourTexture / tailleCartePourTexture, NEAR = 0.1, FAR = 10000; this.mouseDown = false; this.xSouris = 0; this.xSourisOld = 0; this.ySouris = 0; this.ySourisOld = 0; // SCENE this.scene = new THREE.Scene(); //this.scene.fog = new THREE.Fog( 0x000000, 1, FAR/8 ); // CAMERA this.transitionCamera = new Transition(); this.transitionFocusCamera = new Transition(); this.isZoom = false; this.angleCamera = []; this.angleCamera[0] = 0; this.angleCamera[1] = 0; this.positionInitCam = [0, 0, 1000]; this.focusCamera = [ 0,0,-100 ]; this.camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR ); this.camera.up = new THREE.Vector3( 0, 1, 0 ); this.rayonCamera = this.positionInitCam[2]; //this.camera.position.set( this.positionInitCam[0], this.positionInitCam[1], this.positionInitCam[2] ); this.camera.position.x = this.rayonCamera * Math.sin( this.angleCamera[1] * Math.PI / 360 ) * Math.cos( this.angleCamera[0] * Math.PI / 360 ); this.camera.position.y = this.rayonCamera * Math.sin( this.angleCamera[0] * Math.PI / 360 ); this.camera.position.z = this.rayonCamera * Math.cos( this.angleCamera[1] * Math.PI / 360 ) * Math.cos( this.angleCamera[0] * Math.PI / 360 ); this.camera.lookAt(new THREE.Vector3( this.focusCamera[0], this.focusCamera[1], this.focusCamera[2] )); this.scene.add(this.camera); // RENDERER this.renderer = new THREE.WebGLRenderer(); this.renderer.setSize(window.innerWidth, 4 * window.innerWidth / 6); this.renderer.setClearColor("#282828", 1); // RENDU this.canvas = this.renderer.domElement; this.canvas.id = "carte3d"; document.getElementById(conteneur).appendChild(this.canvas); } this.draw = function() { // transition pour la position de la camera if(!this.transitionCamera.isFinished) { var currentPos = this.transitionCamera.execute3d(); this.camera.position.set(currentPos[0], currentPos[1], currentPos[2]); } // transition pour le focus de la camera if(!this.transitionFocusCamera.isFinished) { var currentPos = this.transitionFocusCamera.execute3d(); this.focusCamera[0] = currentPos[0]; this.focusCamera[1] = currentPos[1]; this.focusCamera[2] = currentPos[2]; this.camera.lookAt(new THREE.Vector3(this.focusCamera[0], this.focusCamera[1], this.focusCamera[2])); } else { this.camera.lookAt(new THREE.Vector3(this.focusCamera[0], this.focusCamera[1], this.focusCamera[2])); } // rendu this.renderer.render(this.scene, this.camera); } this.onMouseMove = function(event) { if(this.mouseDown) { this.xSouris = event.clientX; this.ySouris = event.clientY; this.positionCamera(); this.xSourisOld = this.xSouris; this.ySourisOld = this.ySouris; } return false; } this.onMouseDown = function(event) { this.mouseDown = true; this.xSouris = event.clientX; this.xSourisOld = this.xSouris; this.ySouris = event.clientY; this.ySourisOld = this.ySouris; } this.onMouseUp = function(event) { this.mouseDown = false; } this.initCam = function() { this.angleCamera[0] = 0; this.angleCamera[1] = 0; this.rayonCamera = this.positionInitCam[2]; this.transitionCamera.setup( [ this.camera.position.x, this.camera.position.y, this.camera.position.z ], [ this.positionInitCam[0], this.positionInitCam[1], this.rayonCamera ] ); this.transitionFocusCamera.setup( [ this.focusCamera[0], this.focusCamera[1], this.focusCamera[2] ], [ this.positionInitCam[0], this.positionInitCam[1], this.focusCamera[2] ] ); action_recentrerPictoCam(100, 100); } this.positionCamera = function() { // ANGLES var decalageX = (this.xSouris - this.xSourisOld) * (this.rayonCamera * 0.0005); var decalageY = (this.ySouris - this.ySourisOld) * (this.rayonCamera * 0.0005); this.camera.position.x -= decalageX; this.focusCamera[0] -= decalageX; this.camera.position.y += decalageY; this.focusCamera[1] += decalageY; this.camera.lookAt(this.focusCamera[0], this.focusCamera[1], this.focusCamera[2]); } this.rotation = function(pictoX, pictoY) { this.angleCamera[0] = pictoX; this.angleCamera[1] = pictoY; // CONDITIONS ANGLES var x = this.rayonCamera * Math.sin( this.angleCamera[0] * Math.PI / 360 ) * Math.cos( this.angleCamera[1] * Math.PI / 360 ); var y = this.rayonCamera * Math.sin( this.angleCamera[1] * Math.PI / 360 ); var z = this.rayonCamera * Math.cos( this.angleCamera[0] * Math.PI / 360 ) * Math.cos( this.angleCamera[1] * Math.PI / 360 ); this.camera.position.x = x; this.camera.position.y = y; this.camera.position.z = z; // this.transitionCamera.setup( // [ this.camera.position.x, this.camera.position.y, this.camera.position.z ], // [ x, y, z ] ); } this.moveCamToPosition = function(position) { this.transitionCamera.setup( [ this.camera.position.x, this.camera.position.y, this.camera.position.z ], [ position[0], position[1], this.rayonCamera ] ); this.transitionFocusCamera.setup( [ this.focusCamera[0], this.focusCamera[1], this.focusCamera[2] ], [ position[0], position[1], this.focusCamera[2] ] ); action_recentrerPictoCam(100, 100); } this.zoom = function(sens) { var distance = 300; if(sens > 0) { if(this.rayonCamera > 500.0) { this.rayonCamera -= distance; } } else { if(this.rayonCamera < 900.0) { this.rayonCamera += distance; } } this.transitionCamera.setup( [ this.camera.position.x, this.camera.position.y, this.camera.position.z], [ this.camera.position.x, this.camera.position.y, this.rayonCamera ] ); } this.onResize = function(newWidth, newHeight) { this.renderer.setSize(newWidth, newHeight); } this.mouvementCool = function(event) { this.transitionCamera.setup( [ this.camera.position.x, this.camera.position.y, this.camera.position.z], [ this.camera.position.x, this.camera.position.y-400, this.rayonCamera ] ); action_recentrerPictoCam(100, 150); } } ///////////////////////////////////////////////////////////////////////////////// /////////////////////// RESIZE ///////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// window.addEventListener("resize", onresize, false); function onresize() { var newWidth = window.innerWidth - 40; var newHeight = window.innerHeight; var size = Math.max(newWidth, newHeight); if(mode == "3d") { canvas.onResize(size, size); } else { dessin2d.resize(size, size, size/8, size/2, size/1.8); } }
C++
UTF-8
3,090
2.5625
3
[]
no_license
#ifndef _X86EMU_X86EMUINCREMENTDECREMENTREGISTERS_H #define _X86EMU_X86EMUINCREMENTDECREMENTREGISTERS_H #include <x86emu/X86EmulatorEnvironment.h> #include <x86emu/X86EmulatorInstructionDecoder.h> #include <x86emu/x86EmulatorDebug.h> #include <x86emu/instructions/x86primitiveInstructions.h> namespace X86Emu { // opcode 0x40 to 0x43 // increment (E)AX, (E)BX, (E)CX, (E)DX void X86IncrementRegister(X86EmulatorEnvironment* env, X86EmulatorInstructionDecoder* decoder, u8 opcode) { u8 reg = (opcode & 0x3) | REGISTER_TYPE_WORD; X86EMU_DEBUG_MSG("Incrementing register " << hex << reg); u32 newValue = env->Registers()->GetRegister((X86Register)reg); if(env->Overrides()->GetOverride(PREFIX_DATA32)) newValue = IncrementDword(newValue, env); else newValue = IncrementWord(newValue, env); env->Registers()->SetRegister((X86Register)reg, newValue); env->Overrides()->Clear(); } // opcode 0x44 to 0x47 // increment (E)SP, (E)BP, (E)SI, (E)DI void X86IncrementIndexRegister(X86EmulatorEnvironment* env, X86EmulatorInstructionDecoder* decoder, u8 opcode) { u8 reg = (opcode & 0x3) | REGISTER_TYPE_INDEX; X86EMU_DEBUG_MSG("Incrementing index register " << hex << reg); u32 newValue = env->Registers()->GetRegister((X86Register)reg); if(env->Overrides()->GetOverride(PREFIX_DATA32)) newValue = IncrementDword(newValue, env); else newValue = IncrementWord(newValue, env); env->Registers()->SetRegister((X86Register)reg, newValue); env->Overrides()->Clear(); } // opcode 0x48 to 0x4b // decrement (E)AX, (E)BX, (E)CX, (E)DX void X86DecrementRegister(X86EmulatorEnvironment* env, X86EmulatorInstructionDecoder* decoder, u8 opcode) { u8 reg = (opcode & 0x3) | REGISTER_TYPE_WORD; X86EMU_DEBUG_MSG("Decrementing register " << hex << reg); u32 newValue = env->Registers()->GetRegister((X86Register)reg); if(env->Overrides()->GetOverride(PREFIX_DATA32)) newValue = DecrementDword(newValue, env); else newValue = DecrementWord(newValue, env); env->Registers()->SetRegister((X86Register)reg, newValue); env->Overrides()->Clear(); } // opcode 0x4c to 0x4f // decrement (E)SP, (E)BP, (E)SI, (E)DI void X86DecrementIndexRegister(X86EmulatorEnvironment* env, X86EmulatorInstructionDecoder* decoder, u8 opcode) { u8 reg = (opcode & 0x3) | REGISTER_TYPE_INDEX; X86EMU_DEBUG_MSG("Decrementing index register " << hex << reg); u32 newValue = env->Registers()->GetRegister((X86Register)reg); if(env->Overrides()->GetOverride(PREFIX_DATA32)) newValue = DecrementDword(newValue, env); else newValue = DecrementWord(newValue, env); env->Registers()->SetRegister((X86Register)reg, newValue); env->Overrides()->Clear(); } } #endif
Markdown
UTF-8
2,348
2.828125
3
[]
no_license
# Article Annexe 1 a) Membres de droit : Le représentant de l'Etat dans le département ou son représentant, président ; Le directeur du centre de formation en soins infirmiers. b) Représentants de l'organisme gestionnaire et personnalités compétentes : Le président du conseil d'administration de l'organisme gestionnaire ou son représentant, membre du conseil d'administration ; Le directeur de l'organisme gestionnaire ou son représentant ; L'infirmier général, directeur du service des soins infirmiers de l'établissement public de santé gestionnaire du centre de formation en soins infirmiers ou son représentant. Pour les centres de formation en soins infirmiers qui ne sont pas gérés par un établissement public de santé, le représentant de l'Etat dans le département désigne un infirmier général, directeur du service des soins infirmiers d'un établissement public de santé ou son représentant, ou une personne remplissant des fonctions équivalentes dans un établissement privé de santé. La personne désignée doit exercer ses fonctions dans un établissement dans lequel les étudiants du centre de formation en soins infirmiers concerné effectuent des stages ; Un médecin ou un pharmacien résident ou gérant proposé par le conseil d'administration de l'organisme gestionnaire ; Un infirmier exerçant dans le secteur extrahospitalier, désigné par le représentant de l'Etat dans le département. c) Représentants des étudiants : Six étudiants élus par leurs pairs à raison de deux par promotion. d) Représentants des personnels participant à la formation des étudiants : Trois surveillants participant à la formation des étudiants dans le centre de formation en soins infirmiers concerné, élus par leurs pairs ; Deux surveillants chargés de fonctions d'encadrement dans un service de soins d'un établissement de santé, le premier dans un établissements public de santé et le second dans un établissement de santé privé, élus par leurs pairs ; Un médecin, élu par ses pairs. e) La conseillère technique régionale en soins infirmiers ou la conseillère pédagogique dans les régions où il en existe. f) Un enseignant de statut universitaire lorsque le centre de formation en soins infirmiers a conclu une convention avec une université, élu par ses pairs.
Markdown
UTF-8
21,010
2.75
3
[]
no_license
### 数据库配置mysql 准备工作 * 自行搭建mysql服务5.7 * 准备一个可以外部访问的账户,root也可以 * 创建数据库,不同于sqlite,数据选择mysql时 django不会帮你创建数据库,只会关联已有的数据库 创建数据库语句:在navicat执行,autotpsite为项目名称,方便统一记录 CREATE DATABASE `autotpsite` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; 安装pymysqlclient模块 pip install mysqlclient #链接mysql数据库需要此模块 settings.py文件中配置mysql数据库信息 ```python DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # 默认引擎 'NAME': 'autotpsite', # 数据库名称 'USER': 'root', # 用户名 'PASSWORD': 'Lja199514', # 密码 'HOST': 'localhost', # mysql的IP 'PORT': '3306', # mysql的端口号 } } ``` 启动django服务,如果可以正常启动代表连接没有问题:python manage.py runserver 如果mysql用户未设置允许远程访问权限,则需要先设置 执行命令数据迁移目前会报错:原因是related_name抽象成基类被继承后导致每个模块值一样 所以修改抽象模型的related_name 加上%(class)s_ 修改Project.admin 设置null=True ```python class CommonInfo(models.Model): # 创建 create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间') created_by = models.ForeignKey(User, null=True, verbose_name='创建者', on_delete=models.SET_NULL, related_name='%(class)s_created_by') # 更新,设置更新时间null=True允许为空,因为第一次创建时候是没有更新时间的 update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间', null=True) updated_by = models.ForeignKey(User, null=True, verbose_name='更新者', on_delete=models.SET_NULL, related_name='%(class)s_updated_by') ``` 再执行迁移数据库命令: * python manage.py makemigrations * python manage.py migrate ### 模型代码继续实现 * 1、首先用包组织模型,在sqtp项目下新建models包 * 2、按模块分割创建多个文件:plan.py、case.py、pro.py、base.py(放抽象基类) * 3、__init__.py文件导入所有的模型 * 4、删除原有自带的models.py文件 ![django](img/test12.png) ```python # coding=utf-8 # @File : base.py # @Time : 2021/3/21 18:40 # @Author : jingan # @Email : 3028480064@qq.com # @Software : PyCharm # 因为使用的是Django自带的登录模型,所以需要先导入 from django.db import models from django.contrib.auth.models import User class CommonInfo(models.Model): # 创建 create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间') created_by = models.ForeignKey(User, null=True, verbose_name='创建者', on_delete=models.SET_NULL, related_name='%(class)s_created_by') # 更新,设置更新时间null=True允许为空,因为第一次创建时候是没有更新时间的 update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间', null=True) updated_by = models.ForeignKey(User, null=True, verbose_name='更新者', on_delete=models.SET_NULL, related_name='%(class)s_updated_by') # 描述 desc = models.TextField(null=True, blank=True, verbose_name='描述') # 排序(可选择此字段进行排序)s sorted_by = models.IntegerField(default=1, verbose_name='排序', editable=True) # 删除(默认不删除) is_delete = models.BooleanField(default=False, verbose_name='删除') # 直接通过模型管理器查看到名称 def __str__(self): # 检查当前对象有无name属性,有则返回,无则返回描述desc字段信息 if hasattr(self, 'name'): return self.name return self.desc class Meta: abstract = True # 原类作用:默认数据库表使用sorted_by进行排序,而不是使用主键id排序,默认升序,如果要倒序,在sorted_by前加上负号即['-sorted_by'] ordering = ['-sorted_by'] ``` ```python # coding=utf-8 # @File : case.py # @Time : 2021/3/21 18:39 # @Author : jingan # @Email : 3028480064@qq.com # @Software : PyCharm from .pro import Module from .base import CommonInfo from django.db import models # 测试用例 class Case(CommonInfo): case_status = ( ('True', 'active'), ('False', 'disable') ) module = models.ForeignKey(Module, on_delete=models.SET_NULL, null=True, verbose_name='关联模块') tags = models.ManyToManyField('Tag', verbose_name='用例标签') status = models.BooleanField(choices=case_status, default='True', verbose_name='用例状态') class Meta(CommonInfo.Meta): verbose_name = '测试用例表' # 标签 class Tag(CommonInfo): name = models.CharField(max_length=32, default='no Tag', verbose_name='标签名') class Meta(CommonInfo.Meta): verbose_name = '用例标签表' # 测试步骤 class Step(CommonInfo): # 步骤状态 step_status = ( (0, '未执行'), (1, '执行中'), (2, '中断'), (3, '成功'), (4, '失败'), (5, '错误') ) case = models.ForeignKey(Case, on_delete=models.CASCADE, verbose_name='用例步骤') httpapi = models.ForeignKey('HttpApi', on_delete=models.SET_NULL, null=True, verbose_name='http接口') expected = models.CharField(max_length=10240, default='', verbose_name='预期结果') statue = models.SmallIntegerField(choices=step_status, default=0, verbose_name='步骤状态') # 执行顺序(步骤序号) step_no = models.SmallIntegerField(default=1, verbose_name='执行顺序') class Meta(CommonInfo.Meta): verbose_name = '用例步骤' ordering = ['step_no'] # 接口 class HttpApi(CommonInfo): http_method = ( (0, 'get'), (1, 'post'), (2, 'put'), (3, 'delete') ) content_types = ( (0, 'application/json'), # sqlite不支持这种格式 (1, 'application/x-www-form-urlencoded') # 表单格式 ) # 验证的枚举类型 auth_types = ( (0, 'cookie'), (1, 'token'), (2, 'None') ) module = models.ForeignKey(Module, on_delete=models.SET_NULL, null=True, verbose_name='关联模块') # http请求方法 method = models.SmallIntegerField(default=0, choices=http_method, verbose_name='请求方法') # 请求路径path path = models.CharField(max_length=1024, null=True, default='/', verbose_name='请求路径') # 参数 data = models.CharField(max_length=10240, null=True, blank=True, verbose_name='请求参数') # 请求参数类型 content_type = models.SmallIntegerField(choices=content_types, default=0, verbose_name='请求参数类型') # 请求头,sqlite不支持JSONField这种格式,所以使用mysql headers = models.JSONField(null=True, blank=True, verbose_name='请求头') # 验证类型 auth_type = models.SmallIntegerField(choices=auth_types, default=3, verbose_name='接口认证类型') class Meta(CommonInfo.Meta): verbose_name = 'http接口' ``` ```python # coding=utf-8 # @File : plan.py # @Time : 2021/3/21 18:39 # @Author : jingan # @Email : 3028480064@qq.com # @Software : PyCharm from .pro import Module from .case import Case from .base import CommonInfo from django.db import models from .pro import Environment from django.contrib.auth.models import User # 测试计划 class Plan(CommonInfo): status_choice = ( (0, '未执行'), (1, '执行中'), (2, '中断'), (3, '已执行') ) cases = models.ManyToManyField(Case, verbose_name='测试用例', through='PlanCase') # 执行者 executor = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name='执行人') environment = models.ForeignKey(Environment, on_delete=models.SET_NULL, null=True, verbose_name='测试环境') name = models.CharField(max_length=32, verbose_name='测试计划', unique=True) status = models.SmallIntegerField(choices=status_choice, default=0, verbose_name='计划状态') # 记录执行次数 exec_counts = models.SmallIntegerField(default=0, verbose_name='执行次数') # 计划&用例中间表 class PlanCase(CommonInfo): plan = models.ForeignKey(Plan, on_delete=models.CASCADE, verbose_name='测试计划') case = models.ForeignKey(Case, on_delete=models.CASCADE, verbose_name='测试用例') # 用例的执行顺序 case_no = models.SmallIntegerField(default=1, verbose_name='执行顺序') class Meta(CommonInfo.Meta): verbose_name = '计划用例关系表' # 测试结果 class Result(CommonInfo): plan = models.ForeignKey(Plan, on_delete=models.SET_NULL, null=True, verbose_name='测试计划') # 触发时间 start_time = models.DateTimeField(null=True, blank=True, editable=True, verbose_name='触发时间') # 用例执行通过数、失败数、总数 case_num = models.SmallIntegerField(default=0, verbose_name='用例数') pass_num = models.SmallIntegerField(default=0, verbose_name='通过数') failed_num = models.SmallIntegerField(default=0, verbose_name='失败数') class Meta(CommonInfo.Meta): verbose_name = '测试结果' ``` ```python # coding=utf-8 # @File : pro.py # @Time : 2021/3/21 18:39 # @Author : jingan # @Email : 3028480064@qq.com # @Software : PyCharm from .base import CommonInfo from django.db import models from django.contrib.auth.models import User # 项目 class Project(CommonInfo): # 枚举项目状态 pro_status = ( ('developing', '开发中'), ('operating', '维护中'), ('stable', '稳定运行中') ) # 管理员 admin = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, verbose_name='项目管理员', related_name='admin') # 成员 members = models.ManyToManyField(User, verbose_name='项目成员', related_name='members') # 名称 name = models.CharField(max_length=32, unique=True, verbose_name='项目名称') # 状态 status = models.CharField(choices=pro_status, max_length=32, default='stable', verbose_name='项目状态') version = models.CharField(max_length=32, default='v1.0', verbose_name='版本') # 版本 class Meta(CommonInfo.Meta): # 显示继承才能继承父模型的元类功能,默认不会继承abstract = True verbose_name = '项目表' # 模块 class Module(CommonInfo): project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name='所属项目') name = models.CharField(max_length=32, verbose_name='模块名称') class Meta(CommonInfo.Meta): verbose_name = '模块表' # 测试环境 class Environment(CommonInfo): # 服务器类型选项枚举 service_type = ( (0, 'web服务器'), (1, '数据库服务器'), ) # 服务器操作系统选项枚举 service_os = ( (0, 'window'), (1, 'linux'), ) # 服务器状态选项枚举 service_status = ( (0, 'active'), (1, 'disable'), ) project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name='所属项目') # ip 使用Django提供的GenericIPAddressField来专门储存ip类型字段 ip = models.GenericIPAddressField(default='127.0.0.1', verbose_name='ip地址') port = models.SmallIntegerField(default=80, verbose_name='端口号') # 服务器类型 category = models.SmallIntegerField(default=0, choices=service_type, verbose_name='服务器类型') # 操作类型 os = models.SmallIntegerField(default=0, choices=service_type, verbose_name='服务器操作系统') # 状态 status = models.SmallIntegerField(default=0, choices=service_status, verbose_name='服务器状态') class Meta(CommonInfo.Meta): verbose_name = '测试环境表' ``` ### 数据库查询强化 1、反向查询 模型查询其关联的项目叫做正向查询(外键定义在模型),反过来,项目查询下面的模型叫做反向查询 * 方式1:未指定related_name时:modelobj.field_set.all() * 方式2:指定related_name时:modelobj.related_name.all() test.py文件如下 ```python from django.test import TestCase from .models import Module,Project,Environment,Plan,Step,Case,HttpApi,Tag,Result from django.contrib.auth.models import User # Create your tests here. class TestM2MQuery(TestCase): def setUp(self) -> None: # 用户 self.user = User.objects.create_user(username='admin',password='123456',first_name='管理员') # 项目 self.test_pro=Project.objects.create(name='松勤测试平台',created_by=self.user,admin=self.user) # 模块 self.test_mod = Module.objects.create(name='第三方支付-微信',project=self.test_pro,created_by=self.user) # 用例 self.test_case = Case.objects.create(desc='支付接口用例001',module=self.test_mod,created_by=self.user) # 步骤 self.test_step=Step.objects.create(desc='test_step',case=self.test_case,created_by=self.user) # 接口 self.test_api=HttpApi.objects.create(desc='合同新增接口',module=self.test_mod,created_by=self.user) # 标签 self.test_tag = Tag.objects.create(name='冒烟测试',created_by=self.user) # 环境 self.test_env = Environment.objects.create(desc='阿里云',project=self.test_pro,created_by=self.user) # 计划 self.test_plan = Plan.objects.create(name='生辰纲',environment=self.test_env,created_by=self.user) # 报告 self.test_report = Result.objects.create(plan=self.test_plan,created_by=self.user) #用例步骤关系 def test_case_step(self): #查询某用例下面的步骤 steps = self.test_case.step_set.filter() Step.objects.create(desc='step2',case=self.test_case,created_by=self.user) print(steps) #用例 标签 def test_case_tag(self): # 关联标签 self.test_case.tags.add(self.test_tag) # 用例下面的标签--正向查询 tags=self.test_case.tags.all() print(tags) # 标签关联的用例?--反向查询 cases=self.test_tag.case_set.all() print(cases) def test_user_pro(self): # 查询项目管理员--正向查询 user1=self.test_pro.admin print(user1) # 反向查询--当前用户管理的项目--用relatedname查询 Project.objects.create(name='松勤测试平台123',created_by=self.user,admin=self.user) pros=self.user.admin.all() print(pros) # 反向查询2--当前用户参与了哪些项目 pro1=Project.objects.create(name='testpro1') pro2=Project.objects.create(name='testpro2') pro3=Project.objects.create(name='testpro3') #项目关联成员 pro1.members.add(self.user) pro2.members.add(self.user) pro3.members.add(self.user) # ---正向查询 pro1.members.all() # 当前用户参与了哪些项目 pros=self.user.members.all() print(pros) # 查询当前用户创建的项目 pros2=self.user.project_created_by.all() print(pros2) ``` ### 字段条件查询 字段查询是指如何指定SQL WHERE子句的内容。它们用作QuerySet的filter(), exclude()和get()方法的关键字参数 其基本格式是:field__lookuptype=value,注意其中是双下划线 默认查找类型为exact(精确匹配) lookuptype的类型有: Django的数据库API支持20多种查询类型,下表列出了所有的字段查询参数 |字段名|说明| |----|----| |exact |精确匹配| |iexact |不区分大小写的精确匹配| |contains |包含匹配| |icontains|不区分大小写的包含匹配| |in|在..之内的匹配| |gt|大于| |gte|大于等于| |lt|小于| |lte |小于等于| |startswith |从开头匹配| |istartswith |不区分大小写从开头匹配| |endswith|从结尾处匹配| |iendswith |不区分大小写从结尾处匹配| |range|范围匹配| |date|日期匹配| |year|年份| |iso_year|以ISO 8601标准确定的年份| |month |月份| |day|日期| |week|第几周| |week_day|周几| |iso_week_day|以ISO 8601标准确定的星期几| |quarter|季度| |time|时间| |hour|小时| |minute|分钟| |second|秒| |regex|区分大小写的正则匹配| |iregex|不区分大小写的正则匹配| 实例 ```python # 字段条件查询 class TestFieldQuery(TestCase): def setUp(self) -> None: # 用户 self.user = User.objects.create_user(username='admin',password='123456',first_name='管理员') # 项目 self.test_pro=Project.objects.create(name='松勤测试平台',created_by=self.user,admin=self.user) # 模块 self.test_mod = Module.objects.create(name='第三方支付-微信',project=self.test_pro,created_by=self.user) # 用例 self.test_case = Case.objects.create(desc='支付接口用例001',module=self.test_mod,created_by=self.user) # 步骤 self.test_step=Step.objects.create(desc='test_step',case=self.test_case,created_by=self.user) # 接口 self.test_api=HttpApi.objects.create(desc='合同新增接口',module=self.test_mod,created_by=self.user) # 标签 self.test_tag = Tag.objects.create(name='冒烟测试',created_by=self.user) # 环境 self.test_env = Environment.objects.create(desc='阿里云',project=self.test_pro,created_by=self.user) # 计划 self.test_plan = Plan.objects.create(name='生辰纲',environment=self.test_env,created_by=self.user) # 报告 self.test_report = Result.objects.create(plan=self.test_plan,created_by=self.user) def test_iexact_query(self): steps = Step.objects.filter(desc__iexact='Test_Step') print(steps) def test_contains_query(self): tags = Tag.objects.filter(name__contains='冒烟') print(tags) ``` ### 跨关系查询 Django提供了强大并且直观的方式解决跨越关联的查询,它在后台自动执行包含JOIN的SQL语句。要跨 越某个关联,只需使用关联的模型字段名称,并使用双下划线分隔,直至你想要的字段(可以链式跨越,无限跨度) 例如:#查找标签是xxx的用例 * 注意:双划线关联的是字段名称 * 技巧:查什么就用对应数据模型,下面查用例,就使用用例数据模型Case.objects * res1=Case.objects.filter(tags__name='smoketest') 示例如下 ```python #跨关系查询 class TestOverRelations(TestCase): def setUp(self) -> None: # 用户 self.user = User.objects.create_user(username='admin',password='123456',first_name='管理员') # 项目 self.test_pro=Project.objects.create(name='松勤测试平台',created_by=self.user,admin=self.user) # 模块 self.test_mod = Module.objects.create(name='第三方支付-微信',project=self.test_pro,created_by=self.user) # 用例 self.test_case = Case.objects.create(desc='支付接口用例001',module=self.test_mod,created_by=self.user) # 步骤 self.test_step=Step.objects.create(desc='test_step',case=self.test_case,created_by=self.user) # 接口 self.test_api=HttpApi.objects.create(desc='合同新增接口',module=self.test_mod,created_by=self.user) # 标签 self.test_tag = Tag.objects.create(name='冒烟测试',created_by=self.user) # 环境 self.test_env = Environment.objects.create(desc='阿里云',project=self.test_pro,created_by=self.user) # 计划 self.test_plan = Plan.objects.create(name='生辰纲',environment=self.test_env,created_by=self.user) # 报告 self.test_report = Result.objects.create(plan=self.test_plan,created_by=self.user) def test_tags(self): # 通过标签名查找测试用例 # 小技巧1,查什么就用对应数据的模型 self.test_case.tags.add(self.test_tag) #关联标签 cases = Case.objects.filter(tags__name='冒烟测试') print('通过标签名查找测试用例') print(cases) def test_case_project(self): # 查找测试用例对应的项目 1.正向查抄 print('查找测试用例对应的项目 1.正向查抄') project = self.test_case.module.project print(project) # 跨关系--通过测试用例的名称 外键模型__字段 project2 = Project.objects.filter(module__case__desc='支付接口用例001')[0] print(project2) ```
Java
UTF-8
740
3.03125
3
[]
no_license
package qyh.leetcode.hard; /** * leetCode 295 * 中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。 * * 例如, * * [2,3,4]的中位数是 3 * * [2,3] 的中位数是 (2 + 3) / 2 = 2.5 * * 设计一个支持以下两种操作的数据结构: * * void addNum(int num) - 从数据流中添加一个整数到数据结构中。 * double findMedian() - 返回目前所有元素的中位数。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/find-median-from-data-stream * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ interface LeetCodeIndex295 { // 优先队列 }
Java
UTF-8
1,961
2.796875
3
[ "Apache-2.0" ]
permissive
package codeu.chat.server; import java.util.concurrent.BlockingQueue; import java.lang.Runnable; import codeu.chat.common.Writeable; import codeu.chat.util.Serializers; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.File; import java.io.IOException; import java.io.FileNotFoundException; import codeu.chat.common.User; // class to store current queued transactions and write to log file public class FileWriter implements Runnable { private BlockingQueue<Writeable> queue; public static final String TRANSACTION_FILE = "transaction.log"; public FileWriter(BlockingQueue<Writeable> q) { queue = q; } // function to constantly take from queue and write to file public void run() { try { while (true) { // use take() to wait for completed operations before taking from queue write(queue.take()); } } catch (InterruptedException ex) { } } public void insert(Writeable x) throws InterruptedException { // adding to the common queue queue.put(x); } public void write(Writeable x) { File file = new File(TRANSACTION_FILE); FileOutputStream fout = null; try { fout = new FileOutputStream(file, true); } catch (FileNotFoundException e) { System.err.println("couldn't find transaction log file"); } catch (SecurityException e) { System.err.println("can't access write to transaction log file"); } try { // writing the saved state into transaction file byte[] separator = new byte[1]; separator[0] = 0x00; // write the separator to separate between saved objects fout.write(separator); Serializers.STRING.write(fout, x.getType()); x.write(fout, x); fout.close(); } catch (IOException e) { System.err.println("couldn't write to transaction log file"); } } }
Ruby
UTF-8
66
3.265625
3
[]
no_license
puts (1..999).inject(0) {|s, i| (i%5==0 || i%3==0) ? s + i : s}
Java
UTF-8
18,049
2.109375
2
[]
no_license
package mg.studio.android.survey; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { protected Button w_btn,q1_btn,q2_btn,q3_btn,q4_btn,q5_btn,q6_btn,q7_btn,q8_btn ,q9_btn,q10_btn,q11_btn,q12_btn,f_btn,r_sum; protected TextView r_q1,r_q2,r_q3,r_q4,r_q5,r_q6,r_q7,r_q8,r_q9,r_q10,r_q11,r_q12; protected String [][]q=new String[13][10]; protected CheckBox w_b; void w_b(){ w_btn=findViewById(R.id.button); w_b=findViewById(R.id.checkBox); w_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(w_b.isChecked()) { setContentView(R.layout.question_one); q1_b(); } } }); } void q1_b() { q1_btn = findViewById(R.id.button2); RadioGroup q1_rg=findViewById(R.id.q1_rg); q1_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId){ case R.id.q1_1: q[1][1]=("Iphone"); break; case R.id.q1_2: q[1][1]=("Nokia"); break; case R.id.q1_3: q[1][1]=("Samsung"); break; case R.id.q1_4: q[1][1]=("MI"); break; case R.id.q1_5: q[1][1]=("Lenovo"); break; case R.id.q1_6: q[1][1]=("Sony"); break; case R.id.q1_7: q[1][1]=("Others"); break; } q1_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setContentView(R.layout.question_two); q2_b(); } }); } }); } void q2_b() { q2_btn = findViewById(R.id.button3); RadioGroup q2_rg=findViewById(R.id.q2_rg); q2_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId){ case R.id.q2_1: q[2][1]=("Under 1000"); break; case R.id.q2_2: q[2][1]=("1000-1999"); break; case R.id.q2_3: q[2][1]=("2000-2999"); break; case R.id.q2_4: q[2][1]=("3000-3999"); break; case R.id.q2_5: q[2][1]=("more than 4000"); break; } q2_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setContentView(R.layout.question_three); q3_b(); } }); } }); } void q3_b() { q3_btn = findViewById(R.id.button4); RadioGroup q3_rg=findViewById(R.id.q3_rg); q3_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId){ case R.id.q3_1: q[3][1]=("2G"); break; case R.id.q3_2: q[3][1]=("3G"); break; case R.id.q3_3: q[3][1]=("4G"); break; case R.id.q2_4: q[3][1]=("Others"); break; } q3_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setContentView(R.layout.question_four); q4_b(); } }); } }); } void q4_b() { q4_btn = findViewById(R.id.button5); q4_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckBox q4_1,q4_2,q4_3,q4_4,q4_5,q4_6,q4_7; q4_1=findViewById(R.id.q4_1); q4_2=findViewById(R.id.q4_2); q4_3=findViewById(R.id.q4_3); q4_4=findViewById(R.id.q4_4); q4_5=findViewById(R.id.q4_5); q4_6=findViewById(R.id.q4_6); q4_7=findViewById(R.id.q4_7); if(q4_1.isChecked()) q[4][1]=("Music functions"); if(q4_2.isChecked()) q[4][2]=("Photo functions"); if(q4_3.isChecked()) q[4][3]=("Game functions"); if(q4_4.isChecked()) q[4][4]=("Business functions(Word,Excel,ect.)"); if(q4_5.isChecked()) q[4][5]=("GPS functions"); if(q4_6.isChecked()) q[4][6]=("Data functions(Bluetooth,WLAN,ect.)"); if(q4_7.isChecked()) q[4][7]=("Others"); setContentView(R.layout.question_five); q5_b(); } }); } void q5_b() { q5_btn = findViewById(R.id.button6); q5_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckBox q5_1,q5_2,q5_3,q5_4,q5_5,q5_6,q5_7; q5_1=findViewById(R.id.q5_1); q5_2=findViewById(R.id.q5_2); q5_3=findViewById(R.id.q5_3); q5_4=findViewById(R.id.q5_4); q5_5=findViewById(R.id.q5_5); q5_6=findViewById(R.id.q5_6); q5_7=findViewById(R.id.q5_7); if(q5_1.isChecked()) q[5][1]=("Music functions"); if(q5_2.isChecked()) q[5][2]=("Photo functions"); if(q5_3.isChecked()) q[5][3]=("Game functions"); if(q5_4.isChecked()) q[5][4]=("Business functions(Word,Excel,ect.)"); if(q5_5.isChecked()) q[5][5]=("GPS functions"); if(q5_6.isChecked()) q[5][6]=("Data functions(Bluetooth,WLAN,ect.)"); if(q5_7.isChecked()) q[5][7]=("Others"); setContentView(R.layout.question_six); q6_b(); } }); } void q6_b() { q6_btn = findViewById(R.id.button7); q6_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText q6_e; q6_e=findViewById(R.id.q6_edit); q[6][1]=q6_e.getText().toString(); setContentView(R.layout.question_seven); q7_b(); } }); } void q7_b() { q7_btn = findViewById(R.id.button8); RadioGroup q7_rg=findViewById(R.id.q7_rg); q7_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId){ case R.id.q7_1: q[7][1]=("When the old phone has been used for a year or two.(but it still works)"); break; case R.id.q7_2: q[7][1]=("When the old phone has been used for more than three years.(but it still works)"); break; case R.id.q7_3: q[7][1]=("When the old phone breaks down."); break; case R.id.q7_4: q[7][1]=("When a new phone is released."); break; case R.id.q7_5: q[7][1]=("Others"); break; } q7_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setContentView(R.layout.question_eight); q8_b(); } }); } }); } void q8_b() { q8_btn = findViewById(R.id.button9); RadioGroup q8_rg=findViewById(R.id.q8_rg); q8_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId){ case R.id.q8_1: q[8][1]=("Iphone"); break; case R.id.q8_2: q[8][1]=("Nokia"); break; case R.id.q8_3: q[8][1]=("Samsung"); break; case R.id.q8_4: q[8][1]=("MI"); break; case R.id.q8_5: q[8][1]=("Lenovo"); break; case R.id.q8_6: q[8][1]=("Sony"); break; case R.id.q8_7: q[8][1]=("Others"); break; } q8_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setContentView(R.layout.question_nine); q9_b(); } }); } }); } void q9_b() { q9_btn = findViewById(R.id.button10); RadioGroup q9_rg=findViewById(R.id.q9_rg); q9_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId){ case R.id.q9_1: q[9][1]=("Appearance"); break; case R.id.q9_2: q[9][1]=("Price"); break; case R.id.q9_3: q[9][1]=("Performance"); break; case R.id.q9_4: q[9][1]=("Others"); break; } q9_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setContentView(R.layout.question_ten); q10_b(); } }); } }); } void q10_b() { q10_btn = findViewById(R.id.button11); RadioGroup q10_rg=findViewById(R.id.q10_rg); q10_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId){ case R.id.q10_1: q[10][1]=("Under 18"); break; case R.id.q10_2: q[10][1]=("19-25"); break; case R.id.q10_3: q[10][1]=("25-35"); break; case R.id.q10_4: q[10][1]=("beyond 35"); break; } q10_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setContentView(R.layout.question_eleven); q11_b(); } }); } }); } void q11_b() { q11_btn = findViewById(R.id.button12); RadioGroup q11_rg=findViewById(R.id.q11_rg); q11_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId){ case R.id.q11_1: q[11][1]=("Male"); break; case R.id.q11_2: q[11][1]=("Female"); break; } q11_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setContentView(R.layout.question_twelve); q12_b(); } }); } }); } void q12_b() { q12_btn = findViewById(R.id.button13); RadioGroup q12_rg=findViewById(R.id.q12_rg); q12_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId){ case R.id.q12_1: q[12][1]=("I haven't got a job"); break; case R.id.q12_2: q[12][1]=("Under 3000"); break; case R.id.q12_3: q[12][1]=("3000-5000"); break; case R.id.q12_4: q[12][1]=("5000-10000"); break; case R.id.q12_5: q[12][1]=("more than 10000"); break; } q1_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setContentView(R.layout.question_two); q2_b(); } }); } }); q12_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setContentView(R.layout.finish_survey); f_b(); } }); } void f_b(){ f_btn = findViewById(R.id.button14); f_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setContentView(R.layout.report_survey); R_s(); } }); } void R_s() { r_sum=findViewById(R.id.r_sum); r_sum.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { r_q1=findViewById(R.id.r_q1); r_q2=findViewById(R.id.r_q2); r_q3=findViewById(R.id.r_q3); r_q4=findViewById(R.id.r_q4); r_q5=findViewById(R.id.r_q5); r_q6=findViewById(R.id.r_q6); r_q7=findViewById(R.id.r_q7); r_q8=findViewById(R.id.r_q8); r_q9=findViewById(R.id.r_q9); r_q10=findViewById(R.id.r_q10); r_q11=findViewById(R.id.r_q11); r_q12=findViewById(R.id.r_q12); r_q1.setText("Q1:"+q[1][1]); r_q2.setText("Q2:"+q[2][1]); r_q3.setText("Q3:"+q[3][1]); r_q4.setText("Q4:"); for(int i=1;i<10;i++) { if(q[4][i]!=null) r_q4.setText(r_q4.getText().toString() + q[4][i] + " *** "); } r_q5.setText("Q5:"); for(int i=1;i<10;i++) { if(q[5][i]!=null) r_q5.setText(r_q5.getText().toString() + q[5][i] + " *** "); } r_q6.setText("Q6:"+q[6][1]); r_q7.setText("Q7:"+q[7][1]); r_q8.setText("Q8:"+q[8][1]); r_q9.setText("Q9:"+q[9][1]); r_q10.setText("Q10:"+q[10][1]); r_q11.setText("Q11:"+q[11][1]); r_q12.setText("Q12:"+q[12][1]); } }); Button r_exit; r_exit=findViewById(R.id.r_exit); r_exit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.exit(0); } }); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.welcome); w_b(); } }
Java
UTF-8
13,184
1.8125
2
[ "Apache-2.0" ]
permissive
/** */ package CIM15.IEC61970.Generation.Production; import CIM15.IEC61970.Core.Curve; import java.util.Date; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Shutdown Curve</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link CIM15.IEC61970.Generation.Production.ShutdownCurve#getShutdownDate <em>Shutdown Date</em>}</li> * <li>{@link CIM15.IEC61970.Generation.Production.ShutdownCurve#getShutdownCost <em>Shutdown Cost</em>}</li> * <li>{@link CIM15.IEC61970.Generation.Production.ShutdownCurve#getThermalGeneratingUnit <em>Thermal Generating Unit</em>}</li> * </ul> * </p> * * @generated */ public class ShutdownCurve extends Curve { /** * The default value of the '{@link #getShutdownDate() <em>Shutdown Date</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getShutdownDate() * @generated * @ordered */ protected static final Date SHUTDOWN_DATE_EDEFAULT = null; /** * The cached value of the '{@link #getShutdownDate() <em>Shutdown Date</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getShutdownDate() * @generated * @ordered */ protected Date shutdownDate = SHUTDOWN_DATE_EDEFAULT; /** * This is true if the Shutdown Date attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean shutdownDateESet; /** * The default value of the '{@link #getShutdownCost() <em>Shutdown Cost</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getShutdownCost() * @generated * @ordered */ protected static final float SHUTDOWN_COST_EDEFAULT = 0.0F; /** * The cached value of the '{@link #getShutdownCost() <em>Shutdown Cost</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getShutdownCost() * @generated * @ordered */ protected float shutdownCost = SHUTDOWN_COST_EDEFAULT; /** * This is true if the Shutdown Cost attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean shutdownCostESet; /** * The cached value of the '{@link #getThermalGeneratingUnit() <em>Thermal Generating Unit</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getThermalGeneratingUnit() * @generated * @ordered */ protected ThermalGeneratingUnit thermalGeneratingUnit; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ShutdownCurve() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ProductionPackage.Literals.SHUTDOWN_CURVE; } /** * Returns the value of the '<em><b>Shutdown Date</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Shutdown Date</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Shutdown Date</em>' attribute. * @see #isSetShutdownDate() * @see #unsetShutdownDate() * @see #setShutdownDate(Date) * @generated */ public Date getShutdownDate() { return shutdownDate; } /** * Sets the value of the '{@link CIM15.IEC61970.Generation.Production.ShutdownCurve#getShutdownDate <em>Shutdown Date</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Shutdown Date</em>' attribute. * @see #isSetShutdownDate() * @see #unsetShutdownDate() * @see #getShutdownDate() * @generated */ public void setShutdownDate(Date newShutdownDate) { shutdownDate = newShutdownDate; shutdownDateESet = true; } /** * Unsets the value of the '{@link CIM15.IEC61970.Generation.Production.ShutdownCurve#getShutdownDate <em>Shutdown Date</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetShutdownDate() * @see #getShutdownDate() * @see #setShutdownDate(Date) * @generated */ public void unsetShutdownDate() { shutdownDate = SHUTDOWN_DATE_EDEFAULT; shutdownDateESet = false; } /** * Returns whether the value of the '{@link CIM15.IEC61970.Generation.Production.ShutdownCurve#getShutdownDate <em>Shutdown Date</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Shutdown Date</em>' attribute is set. * @see #unsetShutdownDate() * @see #getShutdownDate() * @see #setShutdownDate(Date) * @generated */ public boolean isSetShutdownDate() { return shutdownDateESet; } /** * Returns the value of the '<em><b>Shutdown Cost</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Shutdown Cost</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Shutdown Cost</em>' attribute. * @see #isSetShutdownCost() * @see #unsetShutdownCost() * @see #setShutdownCost(float) * @generated */ public float getShutdownCost() { return shutdownCost; } /** * Sets the value of the '{@link CIM15.IEC61970.Generation.Production.ShutdownCurve#getShutdownCost <em>Shutdown Cost</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Shutdown Cost</em>' attribute. * @see #isSetShutdownCost() * @see #unsetShutdownCost() * @see #getShutdownCost() * @generated */ public void setShutdownCost(float newShutdownCost) { shutdownCost = newShutdownCost; shutdownCostESet = true; } /** * Unsets the value of the '{@link CIM15.IEC61970.Generation.Production.ShutdownCurve#getShutdownCost <em>Shutdown Cost</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetShutdownCost() * @see #getShutdownCost() * @see #setShutdownCost(float) * @generated */ public void unsetShutdownCost() { shutdownCost = SHUTDOWN_COST_EDEFAULT; shutdownCostESet = false; } /** * Returns whether the value of the '{@link CIM15.IEC61970.Generation.Production.ShutdownCurve#getShutdownCost <em>Shutdown Cost</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Shutdown Cost</em>' attribute is set. * @see #unsetShutdownCost() * @see #getShutdownCost() * @see #setShutdownCost(float) * @generated */ public boolean isSetShutdownCost() { return shutdownCostESet; } /** * Returns the value of the '<em><b>Thermal Generating Unit</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61970.Generation.Production.ThermalGeneratingUnit#getShutdownCurve <em>Shutdown Curve</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Thermal Generating Unit</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Thermal Generating Unit</em>' reference. * @see #setThermalGeneratingUnit(ThermalGeneratingUnit) * @see CIM15.IEC61970.Generation.Production.ThermalGeneratingUnit#getShutdownCurve * @generated */ public ThermalGeneratingUnit getThermalGeneratingUnit() { if (thermalGeneratingUnit != null && thermalGeneratingUnit.eIsProxy()) { InternalEObject oldThermalGeneratingUnit = (InternalEObject)thermalGeneratingUnit; thermalGeneratingUnit = (ThermalGeneratingUnit)eResolveProxy(oldThermalGeneratingUnit); if (thermalGeneratingUnit != oldThermalGeneratingUnit) { } } return thermalGeneratingUnit; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ThermalGeneratingUnit basicGetThermalGeneratingUnit() { return thermalGeneratingUnit; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetThermalGeneratingUnit(ThermalGeneratingUnit newThermalGeneratingUnit, NotificationChain msgs) { ThermalGeneratingUnit oldThermalGeneratingUnit = thermalGeneratingUnit; thermalGeneratingUnit = newThermalGeneratingUnit; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61970.Generation.Production.ShutdownCurve#getThermalGeneratingUnit <em>Thermal Generating Unit</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Thermal Generating Unit</em>' reference. * @see #getThermalGeneratingUnit() * @generated */ public void setThermalGeneratingUnit(ThermalGeneratingUnit newThermalGeneratingUnit) { if (newThermalGeneratingUnit != thermalGeneratingUnit) { NotificationChain msgs = null; if (thermalGeneratingUnit != null) msgs = ((InternalEObject)thermalGeneratingUnit).eInverseRemove(this, ProductionPackage.THERMAL_GENERATING_UNIT__SHUTDOWN_CURVE, ThermalGeneratingUnit.class, msgs); if (newThermalGeneratingUnit != null) msgs = ((InternalEObject)newThermalGeneratingUnit).eInverseAdd(this, ProductionPackage.THERMAL_GENERATING_UNIT__SHUTDOWN_CURVE, ThermalGeneratingUnit.class, msgs); msgs = basicSetThermalGeneratingUnit(newThermalGeneratingUnit, msgs); if (msgs != null) msgs.dispatch(); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ProductionPackage.SHUTDOWN_CURVE__THERMAL_GENERATING_UNIT: if (thermalGeneratingUnit != null) msgs = ((InternalEObject)thermalGeneratingUnit).eInverseRemove(this, ProductionPackage.THERMAL_GENERATING_UNIT__SHUTDOWN_CURVE, ThermalGeneratingUnit.class, msgs); return basicSetThermalGeneratingUnit((ThermalGeneratingUnit)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ProductionPackage.SHUTDOWN_CURVE__THERMAL_GENERATING_UNIT: return basicSetThermalGeneratingUnit(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ProductionPackage.SHUTDOWN_CURVE__SHUTDOWN_DATE: return getShutdownDate(); case ProductionPackage.SHUTDOWN_CURVE__SHUTDOWN_COST: return getShutdownCost(); case ProductionPackage.SHUTDOWN_CURVE__THERMAL_GENERATING_UNIT: if (resolve) return getThermalGeneratingUnit(); return basicGetThermalGeneratingUnit(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ProductionPackage.SHUTDOWN_CURVE__SHUTDOWN_DATE: setShutdownDate((Date)newValue); return; case ProductionPackage.SHUTDOWN_CURVE__SHUTDOWN_COST: setShutdownCost((Float)newValue); return; case ProductionPackage.SHUTDOWN_CURVE__THERMAL_GENERATING_UNIT: setThermalGeneratingUnit((ThermalGeneratingUnit)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ProductionPackage.SHUTDOWN_CURVE__SHUTDOWN_DATE: unsetShutdownDate(); return; case ProductionPackage.SHUTDOWN_CURVE__SHUTDOWN_COST: unsetShutdownCost(); return; case ProductionPackage.SHUTDOWN_CURVE__THERMAL_GENERATING_UNIT: setThermalGeneratingUnit((ThermalGeneratingUnit)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ProductionPackage.SHUTDOWN_CURVE__SHUTDOWN_DATE: return isSetShutdownDate(); case ProductionPackage.SHUTDOWN_CURVE__SHUTDOWN_COST: return isSetShutdownCost(); case ProductionPackage.SHUTDOWN_CURVE__THERMAL_GENERATING_UNIT: return thermalGeneratingUnit != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (shutdownDate: "); if (shutdownDateESet) result.append(shutdownDate); else result.append("<unset>"); result.append(", shutdownCost: "); if (shutdownCostESet) result.append(shutdownCost); else result.append("<unset>"); result.append(')'); return result.toString(); } } // ShutdownCurve
Python
UTF-8
744
3.640625
4
[]
no_license
pre=[10,8,5,9,15,16] class TreeNode: def __init__(self,val): self.val=val self.left=self.right=None def pre_to_tree(pre): if not pre: return None root=TreeNode(pre[0]) st=[root] for i in range(1,len(pre)): tmp=None while st and pre[i]>st[-1].val: # st is increasing tmp=st.pop() if tmp is None: st[-1].left=TreeNode(pre[i]) st.append(st[-1].left) else: tmp.right=TreeNode(pre[i]) st.append(tmp.right) return root def inorder(root): if not root: return inorder(root.left) print root.val, inorder(root.right) root=pre_to_tree(pre) inorder(root) """ % python pre_to_bst.py 5 8 9 10 15 16 """
Java
UTF-8
3,679
2.671875
3
[]
no_license
package com.kdi.excore.states.menu; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import com.kdi.excore.animations.ColorAnimation; import com.kdi.excore.entities.Enemy; import com.kdi.excore.game.Game; import com.kdi.excore.states.State; import com.kdi.excore.states.StateManager; import com.kdi.excore.utils.Utils; import java.util.ArrayList; import java.util.Random; /** * Created by Krum Iliev on 5/29/2015. */ public abstract class Menu extends State { protected ArrayList<Enemy> objects; protected State nextState; protected ColorAnimation anim; protected boolean showAnim; protected int alpha; protected long flashInterval = 100; public Menu(StateManager stateManager, Game game, int color, int objectsType) { super(stateManager, game); background = color; alpha = 0; objects = new ArrayList<>(); initObjects(objects, objectsType); anim = new ColorAnimation(game, Utils.getRandomColor(false)); } @Override public void update() { for (Enemy enemy : objects) enemy.update(); alpha += 5; if (alpha > 255) alpha = 255; if (showAnim) { boolean remove = anim.update(); if (remove) { showAnim = false; stateManager.setState(nextState); } } } @Override public void draw(Canvas canvas) { canvas.drawColor(background); for (Enemy enemy : objects) enemy.draw(canvas); } protected void drawButton(Canvas canvas, Rect button, String text, String subtext) { game.paint.setStyle(Paint.Style.STROKE); game.paint.setColor(Color.argb(alpha, 255, 255, 255)); game.paint.setStrokeWidth(2); canvas.drawRect(button.left, button.top, button.right, button.bottom, game.paint); game.resetPaint(); game.paint.setTypeface(game.tf); game.paint.setTextSize(30); game.paint.setColor(Color.argb(alpha, 255, 255, 255)); game.paint.setTextAlign(Paint.Align.CENTER); int centerY = ((button.bottom - button.top) / 2) + button.top; Rect bounds = new Rect(); game.paint.getTextBounds(text, 0, text.length(), bounds); canvas.drawText(text, game.width / 2, centerY - bounds.exactCenterY(), game.paint); game.resetPaint(); if (subtext != null) { game.paint.setTypeface(game.tf); game.paint.setTextSize(20); game.paint.setColor(Color.argb(alpha, 255, 255, 255)); game.paint.setTextAlign(Paint.Align.CENTER); game.paint.getTextBounds(text, 0, text.length(), bounds); canvas.drawText(subtext, game.width / 2, button.bottom - 12, game.paint); } } protected void flashButton(Canvas canvas, Rect button, long timer) { if (timer != 0) { game.paint.setStyle(Paint.Style.FILL); game.paint.setColor(Color.argb(alpha, 255, 255, 255)); canvas.drawRect(button.left, button.top, button.right, button.bottom, game.paint); game.resetPaint(); } } protected void initObjects(ArrayList objects, int type) { objects.clear(); Random random = new Random(); for (int i = 0; i < 9; i++) { if (i % 2 == 0) { objects.add(new Enemy(game, this, type, 1, -20, random.nextInt(game.height), 1)); } else { objects.add(new Enemy(game, this, type, 1, game.width + 20, random.nextInt(game.height), 1)); } } } }
Java
UTF-8
1,546
2.03125
2
[]
no_license
package com.joymain.ng.webapp.controller; import java.util.List; import com.joymain.ng.dao.SearchException; import com.joymain.ng.service.FoundationItemManager; import com.joymain.ng.model.FoundationItem; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/foundationItems*") public class FoundationItemController { private FoundationItemManager foundationItemManager; @Autowired public void setFoundationItemManager(FoundationItemManager foundationItemManager) { this.foundationItemManager = foundationItemManager; } @RequestMapping(method = RequestMethod.GET) public Model handleRequest(@RequestParam(required = false, value = "q") String query) throws Exception { Model model = new ExtendedModelMap(); try { List<FoundationItem> foundationItemList=foundationItemManager.getFoundationItemsByStatusIsEnable(); model.addAttribute("foundationItemList", foundationItemList); } catch (SearchException se) { model.addAttribute("searchError", se.getMessage()); } return model; } }
Java
UTF-8
971
1.664063
2
[]
no_license
package android.support.p022v4.view; import android.os.Build.VERSION; import android.view.ViewGroup.MarginLayoutParams; /* renamed from: android.support.v4.view.h */ public final class C0976h { /* renamed from: a */ public static int m4119a(MarginLayoutParams marginLayoutParams) { if (VERSION.SDK_INT >= 17) { return marginLayoutParams.getMarginStart(); } return marginLayoutParams.leftMargin; } /* renamed from: b */ public static int m4121b(MarginLayoutParams marginLayoutParams) { if (VERSION.SDK_INT >= 17) { return marginLayoutParams.getMarginEnd(); } return marginLayoutParams.rightMargin; } /* renamed from: a */ public static void m4120a(MarginLayoutParams marginLayoutParams, int i) { if (VERSION.SDK_INT >= 17) { marginLayoutParams.setMarginEnd(i); } else { marginLayoutParams.rightMargin = i; } } }
Markdown
UTF-8
1,953
2.671875
3
[]
no_license
--- author: [Alfresco Documentation, Alfresco Documentation] audience: category: option: --- # Editing file and folder properties Edit the basic details of a folder or file to change its name, description, and tags. **Note:** If the selected folder or file has the *Classifiable* aspect applied, there will be an additional **Categories** option available. 1. Hover over a file or folder and click **Edit Properties**. The Edit Properties dialog box displays the basic metadata for the item. The **All Properties** link in the upper right corner will display the full set of properties available for the item. 2. Edit the details. The **Name** doesn't support the following special characters: \* " < \> \\ / ? : and \|. **Note:** The name can include a period as long as it is not the last character. 3. Click **Select** beneath the **Tags** label to edit the tag associations. You can add and remove existing tags, and create new tags. On the Select page the left column lists the tags being used in this network. The right column displays the tags already associated with the folder or item. 1. **Create a new tag:** Type the tag name and click the ![Create Tag icon](../images/ico-create-tag.png) Create new item icon \(or press ENTER\). Create one tag at a time. The tag can be a single word or a string of words. 2. **Add an existing tag:** Find a tag in the left column and click the ![Add Tag icon](../images/ico-add-tag.png) Add icon to associate it with the current folder or item. 3. **Remove an existing tag:** Find a tag in the right column and click the ![Add Tag icon](../images/ico-remove-tag.png) Remove icon. 4. Click **OK** to save the changes. **Tip:** You can add, edit, and delete tags by hovering over existing tags or the **No Tags** description in the document library. 4. Click **Save**. **Parent topic:**[Editing files](../concepts/library-item-edit-intro.md)
C#
UTF-8
1,658
3.046875
3
[ "MIT", "CC-BY-4.0" ]
permissive
protected void AddUserToRoleButton_Click(object sender, EventArgs e) {      // Get the selected role and username      string selectedRoleName = RoleList.SelectedValue;      string userNameToAddToRole = UserNameToAddToRole.Text;      // Make sure that a value was entered      if (userNameToAddToRole.Trim().Length == 0)      {           ActionStatus.Text = "You must enter a username in the textbox.";           return;      }      // Make sure that the user exists in the system      MembershipUser userInfo = Membership.GetUser(userNameToAddToRole);      if (userInfo == null)      {           ActionStatus.Text = string.Format("The user {0} does not exist in the system.", userNameToAddToRole);           return;      }      // Make sure that the user doesn't already belong to this role      if (Roles.IsUserInRole(userNameToAddToRole, selectedRoleName))      {           ActionStatus.Text = string.Format("User {0} already is a member of role {1}.", userNameToAddToRole, selectedRoleName);           return;      }      // If we reach here, we need to add the user to the role      Roles.AddUserToRole(userNameToAddToRole, selectedRoleName);      // Clear out the TextBox      UserNameToAddToRole.Text = string.Empty;      // Refresh the GridView      DisplayUsersBelongingToRole();      // Display a status message      ActionStatus.Text = string.Format("User {0} was added to role {1}.", userNameToAddToRole, selectedRoleName); }
C#
UTF-8
637
3.5
4
[]
no_license
using System; using System.Linq; namespace _08._Condense_Array_to_Number { class Program { static void Main(string[] args) { int[] nums = Console.ReadLine().Split().Select(int.Parse).ToArray(); while (nums.Length != 1) { int[] condences = new int[nums.Length - 1]; for (int i = 0; i < condences.Length; i++) { condences[i] = nums[i] + nums[i + 1]; } nums = condences; } Console.WriteLine(nums[0]); } } }
Java
UTF-8
368
1.726563
2
[]
no_license
package com.ram.emailautomation.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("error") public class ErrorController { @GetMapping("error") public String error() { return "error/error"; } }
C++
UTF-8
256
2.65625
3
[]
no_license
#include <iostream> using namespace std; int main() { int x, y; cout <<"enter a numbers."<<endl; cout<<"first number :"; cin>>x; cout<<"second number :"; cin>>y; int i=x; while (i>=0) { i=y%i; y=x-i; } cout<<"hcf is : "<<i<<endl; return 0; }
Python
UTF-8
475
3.671875
4
[]
no_license
budget = float(input()) number_statists = int(input()) one_clothes = float(input()) decor = budget * 0.1; if number_statists > 150: money_clothes = (one_clothes * number_statists) * 0.9 else: money_clothes = one_clothes * number_statists leftMoney = budget - decor - money_clothes if leftMoney >=0: print(f"Action!\n Wingard starts filming with {leftMoney:.2f} leva left.") else: print(f"Not enough money! \nWingard needs {abs(leftMoney):.2f} leva more.")
Markdown
UTF-8
4,413
2.84375
3
[]
permissive
# Audio Source AM/FM/XM/DAB * Proposal: [SDL-0182](0182-audio-source-am-fm-xm.md) * Author: [Zhimin Yang](https://github.com/smartdevicelink/yang1070) * Status: **Accepted with Revisions** * Impacted Platforms: [iOS / Android / RPC / Core / HMI ] ## Introduction SDL remote control allows a mobile application to change the current audio source. When an application sets the audio source to `RADIO_TUNER`, the vehicle is supposed to use the last known/used radio band (AM/FM/XM) and frequency/station of the tuner. However, the application has no knowledge of last used radio band before sending such a request. The vehicle may or may not store the last used radio band. Therefore, the result of setting the audio source to `RADIO_TUNER` is unknown to the application. It is better for an application to set the audio source directly to `AM`, `FM`, `XM` (`XM` is for Sirius XM) or `DAB` (digital audio broadcasting, including DAB+). ## Motivation This proposal is an update to a proposal that has not been implemented but is slated for the next release of projects. The proposal is number [0099](https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0099-new-remote-control-modules-and-parameters.md). To give applications direct control of which radio band or SiriusXM radio they want to set as the audio source, in this update, we split `RADIO_TUNER` with detailed options. ## Proposed solution In this proposal, we propose to replace the `RADIO_TUNER` with three enumeration elements `AM`, `FM` and `XM`. We have the same changes for both the mobile_api and hmi_api. ```xml <enum name="PrimaryAudioSource"> <description>Reflects the current primary audio source (if selected).</description> ... <element name="MOBILE_APP"> </element> - <element name="RADIO_TUNER"> - <description>Radio may be on AM, FM or XM</description> - </element> + <element name="AM"> + </element> + <element name="FM"> + </element> + <element name="XM"> + </element> + <element name="DAB"> + </element> </enum> ``` Because the parameters (audio source, radio band, and radio frequency) belong to two different remote control moduleTypes, in order to set the audio source to a specific radio station or radio frequency, a mobile application needs to send two `setInteriorVehicleData` requests in sequence. The first request sets the audio source to `AM`/`FM`/`XM` with targeted `moduleType=AUDIO`. The second request sets the desired frequency of `AM`/`FM` radio or station number of `XM` radio with targeted `moduleType=RADIO`. This is true regardless of this proposal. ## Potential downsides None ## Impact on existing code The impact on the existing code is small. The mobile proxy libs need to allow the new enumeration values. Core needs to rebuild with updated interface xml files. SDL hmi needs to accept the new values and set the correct audio source. ## Alternatives considered The previous assumption of any `RADIO` operation is that radio is turned on and it is the current audio source of the vehicle's infotainment system. Otherwise, the operation will fail, as radio is not ready. That is why we need two requests to finish the task. A request to turn on the radio and set audio source. A request to change radio settings. Now we might change that to one request, if the request have all the information needed. For example, if a vehicle HMI (not SDL) receives a `SetInteriorVehicleData` request with parameters `moduleType = RADIO`, `radioEnabled = true`, `band = AM` and `frequencyInteger = 530`, it will turn on the radio (if not turned on already), set it as the audio source, change radio band to `AM` and tune the frequency to 530KHz. The advantage is that the application does not need to send a separate request to change audio source first. The disadvantages are (1) we change how the `RADIO` module works as we accept requests when radio is not ready. (2) We still do not know the required radio band if a request does not specify it (that is a valid request because no parameters are mandatory). It does not solve the same problem addressed in this proposal. (3) Other parameters related to audio source switching, like `keepContext` in `AUDIO`, are not available in `RADIO` module. We think this is outside the scope of SDL. It is up to each OEM to decide what their vehicle HMI will do when receiving such a request.
SQL
UTF-8
504
3
3
[]
no_license
select distinct a.osuser, a.username, a.machine, a.sid, a.serial#, 'alter system kill session ' || chr(39) || a.sid || ',' || a.serial# || chr(39) || ' immediate;' as comando_oracle, 'kill -9 ' || b.spid as comando_so, blocking_session bloqueador from gv$session a join gv$process b on (a.inst_id = b.inst_id and a.paddr = b.addr) where blocking_session is not null;
Python
UTF-8
136
3.09375
3
[]
no_license
import numpy as np print(np.linspace(1, 100, 10)) print(np.logspace(1, 2, 10)) print(np.logspace(np.log10(250), np.log10(500), 10))
Java
UTF-8
922
1.539063
2
[]
no_license
/*********************************************************************** * $Id: ReadVersionTaskTest.java,v1.0 2013-5-28 下午4:58:08 $ * * @author: Victor * * (c)Copyright 2011 Topvision All rights reserved. ***********************************************************************/ package com.topvision.framework.common; import org.junit.Test; /** * @author Victor * @created @2013-5-28-下午4:58:08 * */ public class ReadVersionTaskTest { /** * Test method for {@link com.topvision.framework.common.ReadVersionTask#execute()}. */ @Test public void testExecute() { } /** * Test method for {@link com.topvision.framework.common.ReadVersionTask#getName()}. */ @Test public void testGetName() { } /** * Test method for {@link com.topvision.framework.common.ReadVersionTask#getClazz()}. */ @Test public void testGetClazz() { } }
JavaScript
GB18030
1,508
3.0625
3
[]
no_license
function validate( ) { var f=document.myform; //ûΪ if(f.userName.value=="") { alert("û"); f.userName.focus(); return false; } var e=document.myform.email.value; if (e.length==0) //ⳤǷΪ0ǷΪ { alert("ʼΪ!"); return false; } if (e.indexOf("@",0)==-1) //Ƿ@ { alert("ʼʽȷ\n@ţ"); return false; } if (e.indexOf(".",0)==-1) //Ƿ. { alert("ʼʽȷ\n.ţ"); return false; } var p=document.myform; //绰ǷΪ if(p.phone.value==""||isNaN(p.phone.value)) { alert("ȷϵ绰"); p.phone.focus(); return false; } var a=document.myform; //ַǷΪ if(a.Address.value=="") { alert("ϵַ"); a.Address.focus(); return false; } var pass1= document.myform.password.value; // var pass2=document.myform.password2.value; if (pass1==pass2) { if (pass1.length!=0) { return true; } else { alert("벻Ϊգ\n"); return false; } } else { alert("ȷͬ"); return false; } }
C++
UTF-8
11,279
2.859375
3
[]
no_license
// // Created by aless on 05/06/2018. // #include "Graph.h" #include <fstream> #define S 1 #define A 2 #define G 3 Graph::Graph() { _users_vector.resize(1); _relations.resize(1); _empty_rel.ptr=_temporary_rel.ptr= nullptr; _n_company=_n_group=_n_simple=0; } bool Graph::readFileRelations(const string name_file) { string id1, id2, relation, line; size_t from, to; ifstream file; file.open(name_file); if(!file.is_open()){ return false; }else{ while(getline(file, line)){ from=to=0; to=line.find(',', from); id1=line.substr(from, to-from); from=to+1; to=line.find(',', from); id2=line.substr(from, to-from); from=to+1; relation=line.substr(from, line.size()-from); if(setRelation(id1, id2, relation)) { } else { return false; } } return true; } } void Graph::removeUser(const string & userID) { for (unsigned long s = 0; s < _users_vector.size(); s++) { if (_users_vector[s]->getID() == userID) { if(_users_vector[s]->getType()==S) _n_simple--; else if(_users_vector[s]->getType()==A) _n_company--; else if(_users_vector[s]->getType()==G) _n_group--; delete _users_vector[s]; _users_vector.erase(_users_vector.begin()+s); _relations.erase(_relations.begin()+s); } } } bool Graph::setRelation(string & fromID, string &toID, string &rel) { long from=-1, to=-1; string inv_rel; for(unsigned long s=0; s<_users_vector.size(); s++) { if (_users_vector[s]->getID() == fromID) { //I primi 2 if trovano l'indice dei due utenti. from = s; } if (_users_vector[s]->getID() == toID) { to = s; } if (from > -1 && to > -1 && from!=to) { if (rel == "figlio") { inv_rel="genitore"; invertRelation(_relations, from, to, rel, inv_rel); return true; } else { if (rel == "genitore") { inv_rel="figlio"; invertRelation(_relations ,from, to, rel, inv_rel ); return true; } else { if (rel == "coniuge" || rel == "amico" || rel == "dipendente" || rel == "membro") { invertRelation(_relations ,from, to, rel, rel); return true; } else{ if(rel == "conoscente" || rel == "consociata"){ _temporary_rel.link = rel; _temporary_rel.ptr = _users_vector[to]; _relations[from].insert(_relations[from].begin(), _temporary_rel); return true; } } } } } } return false; } bool Graph::removeRelation(const string &fromID, const string &toID) { long from = -1, to = -1; for (unsigned long s = 0; s < _users_vector.size(); s++) { if (_users_vector[s]->getID() == fromID) { from = s; } if (_users_vector[s]->getID() == toID) { to = s; } } for(int r=0; r<_relations[from].size(); r++){ if(_relations[from][r].ptr->getID()==toID){ _relations[from].erase(_relations[from].begin()+r); for(int j=0; j<_relations[to].size(); j++){ if(_relations[to][j].ptr->getID()==fromID){ _relations[to].erase(_relations[to].begin()+j); return true; } } } } return false; } void Graph::invertRelation(vector < vector <relationsStruct> > &Rvector, const long &from , const long &to, const string &rel, const string &inv_rel) { _temporary_rel.link = rel; _temporary_rel.ptr = _users_vector[to]; Rvector[from].insert(Rvector[from].begin(), _temporary_rel); _temporary_rel.ptr = _users_vector[from]; _temporary_rel.link = inv_rel; Rvector[to].insert(Rvector[to].begin(), _temporary_rel); } GeneralUser *Graph::getUser(const string& objID) const { for (unsigned long s = 0; s < _users_vector.size(); s++) { if (_users_vector[s]->getID() == objID) { return _users_vector[s]; } } return nullptr; } long Graph::getPosUser(const string &objID) const { for (unsigned long s = 0; s < _users_vector.size(); s++) { if (_users_vector[s]->getID() == objID) { return s; } } return -1; } long Graph::numberOfUsers(const string &type) const { if (type == "tutti") { return _users_vector.size(); } if (type == "semplice") { return _n_simple; } if (type == "azienda") { return _n_company; } if (type == "gruppo") { return _n_group; } return -1; } unsigned long Graph::nUsersAfterDate(const Date& date1) const { unsigned long num=0; for (unsigned long s = 0; s < _users_vector.size(); s++) { if (_users_vector[s]->getType() == S && _users_vector[s]->getBirth()>date1) { num++; } } return num; } float Graph::averageAgeSimpleUsers() const { float total=0; for (unsigned long s = 0; s < _users_vector.size(); s++){ if(_users_vector[s]->getType()==S){ total+=_users_vector[s]->getBirth().yearsFrom(); } } return total/_n_simple; } string Graph::userMoreRelations(const short& type_user, const string& type) const { int max=0; string user_max; for (unsigned long s = 0; s < _users_vector.size(); s++) { if (_users_vector[s]->getType()==type_user) { if(_users_vector[s]->getNumberRelations(type)>max){ max=_users_vector[s]->getNumberRelations(type); user_max=_users_vector[s]->getID(); }else{ if(_users_vector[s]->getNumberRelations(type)==max){ user_max += ", " + _users_vector[s]->getID(); } } } } return user_max; } void Graph::searchGenealogicalTree(const string & rootID) { long n=getPosUser(rootID); //Assegno ad n la posizione (indice del vector) dell'utente da cui partire per l'albero long s_pos; if(n>-1){ _color.resize(_users_vector.size()); //Preparo il vector di controllo colori e la queue. fill(_color.begin(), _color.end(), 'W'); _color[n]='G'; _Q.push(n); while(!_Q.empty()){ //Inizio a visitare i nodi(utenti) presenti nella queue. n=_Q.front(); _Q.pop(); _pos_user_tree.push_back(n); //Inserisco l'indice dell'utente che visito nel vector degli utenti per l'albero _relations_tree.resize(_relations_tree.size()+1); //e incremento di 1 la dimensione del vector di vector per i parenti. for(long v=0; v<_relations[n].size(); v++){ //Visito tutti i parenti dell'utente. if(_relations[n][v].link == "figlio"){ s_pos=getPosUser(_relations[n][v].ptr->getID()); if(_color[s_pos]=='W'){ _color[s_pos]='G'; invertRelation(_relations_tree, _relations_tree.size()-1, s_pos, "figlio", "genitore"); //Inserisco le relazioni nel vector _relations_tree. _Q.push(s_pos); //Inserisco il figlio dell'utente nella queue. } }else{ if(_relations[n][v].link == "genitore") { s_pos = getPosUser(_relations[n][v].ptr->getID()); if (_color[s_pos] == 'W') { _color[s_pos] = 'G'; invertRelation(_relations_tree, _relations_tree.size() - 1, s_pos, "genitore", "figlio"); //Inserisco le relazioni nel vector _relations_tree. _Q.push(s_pos); //Inserisco il genirote dell'utente nella queue. } } } } _color[n] = 'B'; } }else{ cerr<<"\r\nErrore, utente non trovato."; } } bool Graph::searchLoneWolf(const int rel, const int news, const short group, bool employee) { _searchList.clear(); short check; for (unsigned long s = 0; s < _users_vector.size(); s++) { check=0; if(_users_vector[s]->getType()==S){ if(rel>0){ if(_users_vector[s]->getNumberRelations("tutti")>rel) check = -1 ; } if(news>0){ if(_users_vector[s]->getNumberNews()>news) check = -1; } if(group>0){ if(_users_vector[s]->getNumberRelations("gruppi")>employee) check = -1; } if(employee>0){ if(_users_vector[s]->getNumberRelations("dipendenti")>employee) check = -1; } if(check==0){ _searchList.push_back(getPosUser(_users_vector[s]->getID())); } } } } bool Graph::searchSympathy(const int rate, bool subs) { vector<postStruct*> post; vector<sympathystruct> sympathy; sympathystruct company; short check; for(unsigned long i=0;i<_users_vector.size();i++) { check=0; if(_users_vector[i]->getType()==A) { company.name=_users_vector[i]->getID(); post=_users_vector[i]->getPrivatePost(); long like=0; long dislike=0; for(unsigned long j=0;j<post.size();j++) { like=like+post[j]->_like; dislike=dislike+post[j]->_dislike; } if(dislike!=0&&(like/dislike)>=rate) { company.rate=like/dislike; sympathy.push_back(company); } else if(like>rate) { company.rate=like; sympathy.push_back(company); } } } if(!sympathy.empty()) { sympathystruct s; int k; for(unsigned int i=0;i<sympathy.size()-1;i++) { k=i; for(int j=i+1; j<sympathy.size(); j++) if(sympathy[i].rate > sympathy[k].rate) { k=j; } s=sympathy[k]; sympathy[k]=sympathy[i]; sympathy[i]=s; } } else{ return false; } for(unsigned int i=0;i<sympathy.size();i++) { cout<<"["<<i<<"]\n"<<sympathy[i].name<<"\nCon rateo di : "<<sympathy[i].rate<<endl; } return true; }
JavaScript
UTF-8
1,565
3.078125
3
[ "MIT" ]
permissive
// C/M/n/c queue: // - a queue with constant entry rate, n servers // scheduler dequeues repeatedly until the serving queue is full, // then waits until the queue has space to start again: // while(!serving_queue_full) { // // } // Jobs return a promise // Bulk Jobs: // - take n promises and wait till all of them have resolved. // - return a promise with results of its jobs. // - Caveat: Bulks are fixed. // define circular queue object // - enqueue // - dequeue // - job generator var feed_reader = require('./feed-reader'); function update_source_timestamp(source) { source.last_acitve = (new Date()).valueOf(); db.sources.put(source) } function *rss_jobs() { var sources = yield db.sources.last_active.getAll(); yield (function *() { for(var i = 0; i < sources.length; i++) yield (function() { return feed_reader(sources[i].url) .then(function(result) { update_source_timestamp(sources[i]); log('Fetched RSS Feed from', sources[i].source); return result; }); }); }); } function *job_generator() { while (!empty_queue) { } } function *serving_queue(n) { var queue = [], jobs = job_generator(), active_jobs_count = 0, job, i = 0; // initialize serving queue do { job = jobs.next(); if (!job.done) { queue.push(job.value.call(null)); active_jobs_count++; } } while(i++ < n && !job.done); while(queue.length) { yield queue.shift().then(function(result) { job = jobs.next(); if (job.done) active_jobs_count--; else queue.push(job.value.call(null); }); } }
Python
UTF-8
10,577
2.921875
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- import pygame import random import math import sys from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * def loadTexture(textura): textureSurface = pygame.image.load(textura) #carrega imagem da textura textureData = pygame.image.tostring(textureSurface,"RGBA",1) width = textureSurface.get_width() height = textureSurface.get_height() glEnable(GL_TEXTURE_2D)#habilita textura 2D texid = glGenTextures(1)#ID da textura glBindTexture(GL_TEXTURE_2D,texid) glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,width,height,0,GL_RGBA,GL_UNSIGNED_BYTE,textureData) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) return texid class Cube(object): def __init__(self, posicao): self.posicao = posicao self.vertices = ( (-1+self.posicao[0],-1+self.posicao[1],1+self.posicao[2]), (1+self.posicao[0],-1+self.posicao[1],1+self.posicao[2]), (1+self.posicao[0],1+self.posicao[1],1+self.posicao[2]), (-1+self.posicao[0],1+self.posicao[1],1+self.posicao[2]), (1+self.posicao[0],-1+self.posicao[1],-1+self.posicao[2]), (-1+self.posicao[0],-1+self.posicao[1],-1+self.posicao[2]), (-1+self.posicao[0],1+self.posicao[1],-1+self.posicao[2]), (1+self.posicao[0],1+self.posicao[1],-1+self.posicao[2]) ) self.centro_massa = ((self.vertices[0][0]+self.vertices[len(self.vertices)-1][0])/2, (self.vertices[0][1]+self.vertices[len(self.vertices)-1][1])/2, (self.vertices[0][2]+self.vertices[len(self.vertices)-1][2])/2) #print self.vertices,"\n " #print self.centro_massa #print "_____________________________________________________\n" def desenhar(self): self.edges = ( #tras (4,5), (6,7), #frente (0,1), (2,3), #lado direito (1,4), (7,2), #lado esquerdo (5,0), (3,6), #cima (3,2), (7,6), #baixo (5,4), (1,0) ) texture_vertices = ( (0,0), (1,0), (1,1), (0,1) ) i = 0 glBegin(GL_QUADS) for edge in self.edges: for vertex in edge: glTexCoord2f(texture_vertices[i][0], texture_vertices[i][1]) glVertex3fv(self.vertices[vertex]) i += 1 if (i > 3): i = 0 glEnd() class Ground(object): def __init__(self, posicao): self.posicao = posicao def desenhar(self): chao = ( (-1+self.posicao[0],1+self.posicao[1],1+self.posicao[2]), (1+self.posicao[0],1+self.posicao[1],1+self.posicao[2]), (1+self.posicao[0],1+self.posicao[1],-1+self.posicao[2]), (-1+self.posicao[0],1+self.posicao[1],-1+self.posicao[2]), ) texture_vertices = ( (0,0), (1,0), (1,1), (0,1) ) i = 0 glBegin(GL_QUADS) for vertice in chao: glTexCoord2f(texture_vertices[i][0], texture_vertices[i][1]) glVertex3fv(vertice) i += 1 glEnd() def verificarColisao(pos_x,pos_z, vet_x ,vet_z, speed, mapa, tam_lado_cubo): nova_x = (pos_x + vet_x*speed ) nova_z = (pos_z + vet_z*speed ) #print len(mapa.cubos) colisao = True for cubo in mapa.cubos: colisao = True x, y, z = cubo.centro_massa d = math.sqrt((x-nova_x)**2 + (z-nova_z)**2) #print "dist", d #print "x", x, "---", "z",z #if(abs(x-nova_x) > 2 and abs(z - nova_z) > 2 or (pos_x == 0.0 and pos_z == -2.0)): if(d >= tam_lado_cubo): colisao = False else: return colisao return colisao class Map(): def __init__(self): self.mapa =[[0,0,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,0,1,0,1,1,0,0,1,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,1,0,1,1,1,1,1], [1,1,1,1,1,1,1,0,1,0,1,0,0,0,1], [1,1,0,0,0,0,0,0,0,0,0,0,1,0,1], [1,0,0,1,1,1,1,1,1,1,1,1,1,0,1], [1,0,1,1,1,1,0,0,1,0,0,0,0,0,1], [1,0,1,1,1,1,1,0,1,1,1,0,1,1,1], [1,0,0,1,1,1,1,0,1,0,0,0,0,0,1], [1,0,0,1,1,1,0,0,1,0,1,1,1,0,1], [1,1,0,1,1,1,0,0,1,0,1,0,1,0,1], [1,1,0,0,1,1,0,0,1,0,1,0,0,0,1], [1,1,0,0,0,0,0,0,1,0,1,1,1,1,1], [1,1,0,0,0,0,0,0,1,0,0,0,0,0,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,0,1]] self.cubos = [] self.ground = [] for i in range(len(self.mapa)): for j in range(len(self.mapa[i])): if (self.mapa[i][j] == 1): cubo = Cube((i*2,0,j*2)) self.cubos.append(cubo) if (self.mapa[i][j] == 0): ground = Ground((i*2,0,j*2)) self.ground.append(ground) def desenhar(self): #desenha as paredes com a textura tex0 = loadTexture('textura_parede.jpeg') glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D,tex0) for cubo in self.cubos: cubo.desenhar() glDisable(GL_TEXTURE_2D) #desenha o chão com a textura tex1 = loadTexture('textura_chao.jpg') glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D,tex1) for ground in self.ground: ground.desenhar() glDisable(GL_TEXTURE_2D) def iluminacao(camera_x,camera_y,camera_z): glShadeModel(GL_SMOOTH) glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) ## lightZeroPosition = [10., 10, 6., 1.] lightZeroPosition = [camera_x,camera_y,camera_z, 1.] lightZeroColor = [0.5, 0.5, 0.5, 1] lightEspecular = [2., 4., 10., 1.] glLightfv(GL_LIGHT0, GL_POSITION, lightZeroPosition) glLightfv(GL_LIGHT0, GL_DIFFUSE, lightZeroColor) glLightfv(GL_LIGHT0, GL_SPECULAR, lightEspecular) glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1) glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05) glEnable(GL_LIGHT0) def main(): pygame.init() display = (800,600) pygame.display.set_mode(display, DOUBLEBUF|OPENGL) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(45, (display[0]/display[1]), 0.1, 50) #Carrega os audios trilha_sonora = pygame.mixer.Sound('trilha_sonora.ogg') glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt(0.0,0.0,-2.0, 0.0,0.0,4.0, 0.0,-1.0,0.0) global angle, lx, lz, x, z, speed #Variáveis global usadas para movimentos da camera angle = 0.0 lx = 0.0 lz = 1.0 x = 0.0 z = -2.0 #Fração da movimentação na direção da linha de visão speed = 0.2 #Habilita o z-Buffer glEnable(GL_DEPTH_TEST) #carrega Textura ## loadTexture() #toca trilha sonora trilha_sonora.play() ## glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA) #iluminacao() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(pygame.quit()) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) glPushMatrix() mapa = Map() mapa.desenhar() glPopMatrix() if event.type == pygame.KEYDOWN: f = glGetDoublev(GL_MODELVIEW_MATRIX) camera_x = f[3][0] camera_y = f[3][1] camera_z = f[3][2] #print camera_x,",",camera_z if event.key == pygame.K_UP: global lx, lz, x, z, speed, play_x, play_z #movimentação na direção da linha de visão (sentido Frente) #print mapa.mapa[0][3] if not verificarColisao(x, z, lx, lz, speed, mapa, 1.35): x += lx * speed z += lz * speed #print camera_x,",",camera_z #print play_x,",",play_z if event.key == pygame.K_DOWN: global lx, lz, x, z, speed #movimentação na direção da linha de visão (sentido Trás) if not verificarColisao(x, z, -lx, -lz, speed, mapa, 1.35): x -= lx * speed z -= lz * speed #print camera_x,",",camera_z if event.key == pygame.K_LEFT: global lx, lz, angle #Rotaciona a linha de visão em a esquerda angle -= 0.1 lx = math.sin(angle) lz = math.cos(angle) #print camera_x,",",camera_z if event.key == pygame.K_RIGHT: global angle, lx, lz #Rotaciona a linha de visão em a direita angle += 0.1 lx = math.sin(angle) lz = math.cos(angle) #print camera_x,",",camera_z iluminacao(x+lx,camera_y,z+ lz+2)#iluminacao(camera_x,camera_y,camera_z + 10) # Reset transformations glLoadIdentity() # Set the camera gluLookAt(x, 0.0, z, x+lx, 0.0, z+lz, 0.0, -1.0, 0.0) pygame.display.flip() pygame.time.wait(10) if __name__ =="__main__": main()
Java
UTF-8
3,085
3.640625
4
[]
no_license
package enumerations; /** * The GameSprites enumeration is used as a way to easily reference the initial sprite properties for each entity. * The dimensions of the sprite are based on the associated animation's aspect ratio. * The dimensions of the sprite are used to scale the frame width and frame height to a more appropriate size for the screen dimensions. */ public enum GameSprites { GUPPY(GameAnimations.GUPPY, 125, 350), TROUT(GameAnimations.TROUT, 50, 600), DUNKLEOSTEUS(GameAnimations.DUNKLEOSTEUS, 45, 400), SWORDFISH(GameAnimations.SWORDFISH, 200, 450), STINGRAY(GameAnimations.STINGRAY, 100, 450), SHARK(GameAnimations.SHARK, 300, 450), BUBBLE(GameAnimations.BUBBLE, 20, 50), SPEEDUP(GameAnimations.SPEEDUP, 50, 50); private GameAnimations animation; private double minWidth; private double maxWidth; /** * The initial sprite properties for each entity. * The dimensions of the sprite is based on the associated animation's aspect ratio. * Which means that only the width of the sprite is needed. * Where the width of the sprite represents the desired width of the frame that contains the entity. * @param animation the initial animation properties. * @param minWidth the minimum width the sprite can be. * @param maxWidth the maximum width the sprite can be. */ private GameSprites(GameAnimations animation, double minWidth, double maxWidth){ this.animation = animation; this.minWidth = minWidth; this.maxWidth = maxWidth; } /** * Returns the initial animation properties of the sprite. * @return the animation properties. */ public GameAnimations getGameAnimation(){ return animation; } /** * Returns the minimum width of the sprite. * @return the minimum width. */ public double getMinWidth(){ return minWidth; } /** * Returns the maximum width of the sprite. * @return the maximum width. */ public double getMaxWidth(){ return maxWidth; } /** * Returns the minimum height of the sprite. * Using the aspect ratio of the sprite. * @return the minimum height. */ public double getMinHeight(){ return minWidth * getMinSpriteScaling(); } /** * Returns the maximum height of the sprite. * Using the aspect ratio of the sprite. * @return the maximum height. */ public double getMaxHeight(){ return maxWidth * getMaxSpriteScaling(); } /** * Returns the scaling factor necessary to be applied to the frame to get the minimum sprite dimensions. * @return the scaling factor. */ public double getMinSpriteScaling(){ return minWidth / animation.getFrameWidth(); } /** * Returns the scaling factor necessary to be applied to the frame to get the maximum sprite dimensions. * @return the scaling factor. */ public double getMaxSpriteScaling(){ return maxWidth / animation.getFrameWidth(); } }
Markdown
UTF-8
10,690
2.546875
3
[ "MIT" ]
permissive
--- layout: post title: "코로나로 인해 재택근무를 하며 느낀점" date: 2020-03-01 18:23:00 tags: [diary] comments: true --- [코로나 19](https://search.naver.com/search.naver?sm=top_hty&fbm=1&ie=utf8&query=%EC%BD%94%EB%A1%9C%EB%82%98) 사태로 인해 갑작스럽게 이번주 화요일부터 다음주까지 전사 재택근무를 하게 되었다. 재택근무를 처음 해보기도 하고 갑작스럽게 결정되어 약간의 걱정 반, 기대 반으로 재택근무를 시작하게 되었다. 이번주는 아직 첫 주라 그런지 대체로 만족스러웠던 것 같다. 😀 앞으로 회사에서도 점차 리모트 근무를 도입할 계획도 가지고 있어, 이번주 재택근무를 해보면서 느꼈던 점들을 잘 기록해두기로 했다. ## 재택근무를 하며 달라진 점들 ### 1. 출/퇴근 재택근무의 장점은 뭐니뭐니해도 출퇴근 시간이 사라진다는 게 가장 큰 장점인 것 같다. 리모트 근무 시 출퇴근 관리는 출퇴근 관리 앱을 통해서 이루어진다. 현재 우리 회사에서는 출퇴근, 업무 시간, 야간 근무 요청 등은 출/퇴근 관리 앱인 `시프티`를 사용하고 있다. 시프티앱을 켜서 출근하기 / 퇴근하기 버튼을 누르면 출퇴근 표시가 되는 방식이다. 이건 사무실에 출근할 때도 동일하다. `장점` 👍: **돈과 시간이 절약된다.** - 1초 만에 출/퇴근이 가능하다. 집에서 회사까지 door-to-door 로 대략 40분정도 걸리고, 출근 준비하는데 대략 40분 정도 걸리는데, 출/퇴근이 없어지니 하루 2시간 정도가 절약된다. - 점심을 집에서 먹을 수 있어 돈과 시간이 절약된다. 집에서 요리 해먹는 걸 좋아해서 이 부분은 행복감 200% 다. `단점` 👎: **딱히 없다.** 아래 단점들은 현재 사용하고 있는 출/퇴근 앱의 문제이다. - 앱에서 출퇴근을 따로 요청하는 작업이 은근 귀찮다. 정책 상 회사 와이파이가 아닌 경우 출퇴근 요청을 따로 해야하는데, 요청 란에 필수로 의미 없는 출퇴근 사유도 써야 한다. - 나는 출퇴근 요청만 하지만, 매번 팀원들의 출퇴근 요청을 승인하는 사람들은 매우 귀찮지 않을까 싶다. ### 2. 회의 방식 회의는 기본적으로 `행아웃 화상 미팅`으로 이루어진다. 회의를 잡을 때 캘린더에 참석자들을 초대하고, 화상 미팅을 활성화하여 행아웃 링크를 공유하면 끝이다. 원래 잡혀있던 회의 및 면접 등은 행아웃 화상 미팅으로 대체하고, 매일 업무 체크를 위해 `스탠드업 회의가 활성화` 되었다. 오전에 팀끼리 15분 정도 간단히 진행할 업무, 어려운 점 등을 공유한다. 중간에 급하게 구두 논의가 필요할 때도 빠르게 미팅을 잡아서 논의할 수 있다. `장점` 👍: **장소에 구애받지 않고, 바로 조용한 곳에서 회의를 할 수 있음.** - 회사에서 종종 회의실을 구할 수 없어 여러 사람이 사용하는 열린 공간에서 미팅하게 되었을 때 회의에 집중하기 어려웠던 적이 있는데, 지금은 행아웃으로 필요한 때 당장 조용한 곳에서 미팅이 가능히다. - 심지어 이번주에는 Tech 인원들이 모두 모여서 한 달간 성과를 공유하는 Tech all hands 행사가 있었는데, 행아웃을 통해 매우 원활하게 진행되었다. (채팅창에 깨알같은 드립들이 난무하며 지난 번 오프라인 행사 때 보다 더 분위기가 좋았다칸다.) `단점` 👎: **슬랙을 자주 확인하게 됨.** - 모든 커뮤니케이션을 슬랙으로 하고, 리모트를 할 때는 왠지 더 눈치가 보여서 바로 답장을 하지 않으면 안될 것 같아 슬랙을 너무 자주 확인하게 되는 것 같다. 집중하는 동안은 팀에 양해를 구하고 알림을 꺼두어야 겠다. - 기본적으로 화상 미팅을 하는데, 카메라에 집안 풍경(?)이 일부 잡히게 되어 신경쓰여서 청소를 자주하게 된다. 사실 이번주는 팀에서 개발한 기능을 배포일정이 잡혀있던 주였어서 재택근무를 한다는 소식을 들었을 때 살짝 멘붕하기도 했었다. 성공적으로 배포하기 위해서 팀원 간 의사소통, 손발이 착착 잘 맞아야 하는데, 재택근무를 하게되면 이번주에 무사히 배포를 할 수 있을까 하는 걱정이 있었다. 리모트를 위한 업무 시스템과, 서비스 배포 환경이 잘 갖춰진 탓인지, 무사히 사내 배포를 완료할 수 있었다. 배포 이후 버그도 있었지만, 버그 픽스도 시간 하루 정도로 생각보다 빠르게 해결될 수 있었다. 다음주에도 유저에게 배포되는 실서비스 배포도 안정적으로 진행해 볼 수 있을 것 같다. ### 3. 업무 환경 코로나 때문에 시행하는 재택 근무라 아쉽게도 카페 리모트는 안되고 집에서만 일할 수 있다. 업무 환경은 확실히 기존에 비해 아쉬운 점이 많은 것 같다. 사무실의 드넓은 책상과 편한 의자, 모니터, 커피, 간식 등이 다 사라졌다. `장점` 👍: **편안함. 스피커로 노래 틀기** - 노래 들을 때 에어팟을 장시간 끼고 있으면 귀가 아픈데, 집에서는 블루투스 스피커로 노래를 막 재생할 수 있어서 좋다. - 원래 집순이라 그런지 밖에 나가면 지하철 타면서 기빨리고 에너지가 쭉쭉 빠지는 스타일인데, 집 안에서 근무하니 매우 편안하고 쾌적하게 일했다. `단점` 👎: **사무실의 그 훌륭한 장비들을 사용하지 못한다. 그리고 커피가 없다.** - 이번 주는 거의 복층 2층 책상에서 양반다리를 하고 일 했었는데, 몇 시간 앉아서 일하다보면 다리가 저려오고 허리가 아팠다. 일할 때는 확실히 편한 의자와 책상이 필요한 것 같다. - 일할 때 커피를 내내 달고 있어서 하루에 보통 커피를 3잔 정도 마시는데, 집에는 커피가 없어 금방 금단 증상이 왔다. 얼른 집 앞 스타벅스에 커피를 사러 갔다 왔다. ### 4. 업무 효율 일단 무엇보다 `업무 집중도는 2배 이상` 올라간 것 같다. 그리고 회사에 출근했을 때는 출근해서 사무실에 있으니까 일 인정! 이런 느낌인데, 집에 있으니 조금이라도 쉬면 안될 것 같다는 생각에 오히려 눈치보여서 중간에 덜 쉬고 더 일하게 되었던 것 같다. `장점` 👍: **몰입이 잘 된다.** - 사무실보다 몰입이 매우 잘 된다. 사무실에서는 여러 사람들이 움직이고, 말을 걸게되는 데, 혼자 집안에서 있으니 조용해서 일에 몰입이 잘되어 평소보다 빠르게 일을 쳐냈던 것 같다. - 사무실에서는 누군가 말을 걸면 그 즉시 집중이 깨진다. 리모트를 할 때는 슬랙에서 누군가 말을 걸더라도 내가 하던 업무를 마무리하고 볼 수 있어서 몰입을 깨는 상황이 적은 것 같다. - 집에서 일하는 습관이 드니, 주말에도 좀 더 부지런해진 것(?) 같다. `단점` 👎: **몰입이 너무 잘 된다. (?)** - 예전에는 집과 회사가 분리되어 퇴근하고 집에오면 푹 퍼져서 쉬었는데, 지금은 퇴근시간을 넘기고도 자연스럽게(?) 계속 일하게 되는 것 같다. 지금은 집 == 회사가 되어버려 의식적인 출/퇴근 구분이 필요할 것 같다. ### 5. 건강 아직은 그럭저럭 괜찮은 컨디션 유지중. `장점` 👍: **피로감이 덜하다. 건강한 식사!** - 이번 주는 배포가 있어 어쩔 수 없이 거의 내내 밤 11시~12시 까지 야근을 했다. 그래도 출퇴근 시간이 없다보니 잠은 충분히 잘 수 있었어서, 평소 야근 했던 날에 비해 피로감이 덜하고 컨디션이 좋았다. - 밥먹기 귀찮으면 편의점 김밥, 샌드위치 등으로 간단히 때우는 때가 많았는데, 점심/저녁 식사로 집밥을 먹게 된 점은 좋다. `단점` 👎: **작은 외로움과 갑갑함. 그리고 허리 아픔.** - 원래 외로움을 잘 타지 않는 성격인데, 다른 사람과 말할 일이 줄어들다보니 살짝 외로움이 생긴다. - 집안에만 갇혀 있으니 갑갑하다. 이건 코로나 사태가 진정되면 해소될 것 같다. - 집의 책상과 의자가 그리 좋지 않아 장시간 컴퓨터로 일하면 허리가 아프다. 집이 좁아 새로 구매하기는 어려우므로 의식적인 바른 자세와 틈틈히 스트레칭하는 것으로 이겨내야겠다. 💪 ## 다음주를 위한 업무 환경 개선 코로나 사태가 얼마나 지속될 지 모르겠다. 일단 우리 회사는 다음주까지 재택근무를 시행하기로 했으니, 다음주 쾌적한 근무를 위해 약간의 노력으로 업무 환경을 개선해보았다. - 약간의 리모델링(?)을 통해 업무 공간을 1층으로만 한정하도록 분리했다. 2층은 온전히 쉬는 공간으로 남겨두어야지 🤐 - 일하기 편한 책상과 의자는 조그만 집에 둘 데가 없어서 못샀다. 대신 일하는 책상을 높이가 낮아 허리 아팠던 바 테이블 대신 원래 집에 딸려 있던 좀 더 높이가 높은 책상으로 바꿨다. 내년에 투룸으로 이사하면 새로 사야겠다. 😞 - 이번 기회에 찜해두었던 네스프레소 커피 머신과 스타벅스 캡슐(개인적으로 Pike Place 맛이 제일 맛있는 것 같다)을 구매했다! 😎 - 퇴근과 동시에 슬랙 끄고 노트북 덮기. 그 외 시간에는 개인 맥북을 사용하도록 서랍장에 쳐박혀있던 개인 맥북을 부활 시켰다. 👩‍💻 - 개인적 취향으로 작은 맥북 화면에서 코딩할 때 집중이 잘 되기도 해서 모니터는 굳이 구매하지 않았다. 🙃 > 첫 주 재택근무를 해 본 결과, 단점들보다는 압도적인 장점(시간, 집중)들이 많아 아직은 재택근무에 대해서 만족스럽다. > 외로움 및 갑갑함 해소를 위해 딱 하루 정도는 사무실에 출근해도 괜찮을 것 같다. 회사의 다른 분들은 이번 주 재택근무를 해보면서 어떻게 느꼈는지도 궁금하다. #### +) 그리고 뒤늦게 올려보는 깨알같은 회사 홍보 코로나에도 당황하지않고 하루만에 스무스한 재택근무 & 리모트 근무가 가능한 [뱅크샐러드](https://career.banksalad.com/) ! ~~에 지원하실 때 추천인 코드는 @전인아로 해주시면 채용보상금 반띵해드립ㄴ...~~
Python
UTF-8
2,253
2.6875
3
[]
no_license
import numpy as np import scipy as sp import matplotlib.pyplot as plt import time from scipy import ndimage #import time print "executing... takes about 5 mins.." start_time = time.time() leftim = sp.ndimage.imread('view3.png',flatten=True); rightim = sp.ndimage.imread('view1.png',flatten=True); plt.imshow(leftim,cmap='Greys_r') plt.imshow(rightim,cmap='Greys_r') o = 20 disp = np.zeros((leftim.shape[0],leftim.shape[1])) for row in range(leftim.shape[0]): cost = np.zeros((leftim.shape[1],leftim.shape[1])) M = np.zeros((leftim.shape[1],leftim.shape[1])) #<----------------- for i in range(1,leftim.shape[0]): cost[i][0] = i*o for i in range(1,leftim.shape[0]): cost[0][i] = i*o for i in range(1,leftim.shape[1]): for j in range(1,rightim.shape[1]): temp = abs(leftim[row,i]-rightim[row,j]) min1 = cost[i-1][j-1] + temp min2 = cost[i-1][j] + o min3 = cost[i][j-1] + o cmin = min(min1,min2,min3) cost[i][j] = cmin if (cmin == min1): M[i][j] = 1 elif (cmin == min2): M[i][j] = 2; elif (cmin == min3): M[i][j] = 3; i = leftim.shape[1]-1 j = leftim.shape[1]-1 while (i != 0) & (j != 0): if M[i][j] == 1: disp[row][j] = abs(j-i) i -= 1 j -= 1 if M[i][j] == 2: i -= 1 if M[i][j] == 3: j -= 1 plt.imshow(disp,cmap = 'Greys_r') disp_ground = sp.ndimage.imread('/media/23e97447-9196-4c8e-be28-b24a49d2548e/home/jayaraj/Study/CS_CVIP/project/Data/disp5.png',flatten=True ) # result = np.mean(np.square(disp_ground-disp)) result = np.mean(np.square(disp_ground[:,50:]-disp[:,50:])) # print("--- %s time taken in seconds ---" % (time.time() - start_time)) title = "Disparity map for occlusion"+ str(o) +" mse:"+str(result) plt.title(title) plt.show() # minn = np.amin(disp) # maxx = np.amax(disp) # norm_disp_map = np.zeros((disp.shape[0],disp.shape[1])) # for i in range(disp.shape[0]): # for j in range(disp.shape[1]): # norm_disp_map[i][j] = disp[i][j]*255/maxx
Java
UTF-8
304
2.15625
2
[]
no_license
package com.flink.learn.window.aggregate; import lombok.Data; @Data public class StockPrice { private String symbol; private Double price; public StockPrice() { } public StockPrice(String symbol, Double price) { this.symbol = symbol; this.price = price; } }
Markdown
UTF-8
1,874
2.921875
3
[]
no_license
# Overview In this project you had to train two agents of tennis players, that try to keep the ball in the game as long as possible. The base for this project and algorithm was layed down by the Udacity team from the DRLND, which we were allowed to use and to adapt. I followed the tip of the team to use the DDPG algorithm with a shared ReplayBuffer and a shared Actor Network. # Setup To start, you need Python 3.6, PyTorch, Numpy, Matplotlib, and the Unity ML-Agents Toolkit. With Anaconda or virtualenv you can create your python environment like: $conda create -n drlnd python=3.6 pytorch matplotlib numpy For the Unity ML-Agent you need to download the Toolkit (https://github.com/Unity-Technologies/ml-agents) go to the ml-agents/python directory and install it via: $pip install ml-agents/python # Instructions Watch the trained agent with: $ python watch.py and let the agent train again with: $ python train.py # Environment The observation space for each agent consists of 8 values and the action space for each agent consists of 2 values, which are both continuous. The Environment is considered solved, after taking the maximum score of each player for each episode and then taking the mean of the last 100 scores reaches 0.5 or higher for one episode. ![solved_env](checkpoints/scores_v2.png) 'Graph showing me solving the environment' This algorithm even succeeded 0.7 over 100 consecutive episodes once and then bounced around the 0.5 mark. The environment was first considered solved at around 700 episodes. # Architecture and Algorithms Can be viewed in the "REPORT.md" file next to this file. # Future The agent so far is pretty good in a very short learning cycle. Although additional improvements can be made, like the Generalized Advantage Estimation(GAE) to improve the prediction of the expected return.
Java
UTF-8
9,138
2.28125
2
[ "BSD-3-Clause" ]
permissive
package org.hybird.ui.hquery; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.awt.event.*; import javax.swing.JButton; import javax.swing.JComponent; import org.hybird.ui.AbstractTest; import org.hybird.ui.events.CompositeEventSource; import org.hybird.ui.events.EventListener; import org.hybird.ui.events.source.DefaultCompositeEventSource; import org.hybird.ui.events.swing.Events; import org.hybird.ui.events.swing.MouseEvents; import org.hybird.ui.tk.HButton; import org.hybird.ui.tk.HComponent; import org.hybird.ui.tk.HLabel; import org.hybird.ui.tk.HPanel; import org.junit.Before; import org.junit.Test; public class HQueryTest extends AbstractTest { @Test public void contentsAreAvailable() { assertListContainsNames ($("*").contents(), "h", "h1", "h2", "h3", "h4", "h5"); } @Test public void addRemoveStyle() { assertFalse (h.hasStyle ("added")); $ ("*").addStyle ("added"); assertTrue (h.hasStyle ("added")); $ ("*").removeStyle ("added"); assertFalse (h.hasStyle ("added")); } @Test public void toggleStyle() { assertFalse (h.hasStyle ("a")); assertFalse (h.hasStyle ("b")); $ ("*").toggleStyle ("a", "b"); assertTrue (h.hasStyle ("a")); assertFalse (h.hasStyle ("b")); $ ("*").toggleStyle ("a", "b"); assertFalse (h.hasStyle ("a")); assertTrue (h.hasStyle ("b")); $ ("*").toggleStyle ("a", "b"); assertTrue (h.hasStyle ("a")); assertFalse (h.hasStyle ("b")); } @Test public void hQueryHasSelector() { assertEquals ("*", $ ("*").selector()); assertEquals ("JPanel[attr=bobi]", $ ("JPanel[attr=bobi]").selector()); } @Test public void resultsFilteringWithFind() { assertQueryMatches (".HPanel > .HPanel", h, "h1", "h3"); assertQueryMatches (".HPanel > .HPanel:first-child > .HLabel", h, "h2"); HQuery subQuery = $ (".HPanel > .HPanel:first-child").find (".HLabel"); assertEquals (1, subQuery.count()); assertEquals ("h2", subQuery.asJComponent().getName()); } @Test public void parents() { assertListContainsNames ($ ("#h4").parents().contents (), "h", "h3"); assertListContainsNames ($ ("#h4, #h2").parents().contents (), "h", "h1", "h3"); HPanel h6 = new HPanel().as ("h6"); h6.addTo (h); assertListContainsNames ($ ("#h4, #h2, #h6").parents().contents (), "h", "h1", "h3"); HButton h7 = new HButton ().as ("h7"); h7.addTo (h6); assertListContainsNames ($ ("#h4, #h2, #h7").parents().contents (), "h", "h1", "h3", "h6"); // there should also be no duplicates assertEquals (2, $ ("#h4").parents().contents ().size ()); assertEquals (3, $ ("#h4, #h2").parents().contents ().size ()); assertEquals (3, $ ("#h4, #h2, #h6").parents().contents ().size ()); assertEquals (4, $ ("#h4, #h2, #h7").parents().contents ().size ()); } @Test public void parentsFiltering() { // all parents, h3 and h assertListContainsNames ($ ("#h4").parents ().contents (), "h3", "h"); // components matching query, h3 and h1 assertListContainsNames ($ (".HPanel > .HPanel").contents (), "h3", "h1"); // triangulation assertListContainsNames ($ ("#h4").parents (".HPanel > .HPanel").contents (), "h3"); } private static final Class<Bling> Bling = Bling.class; public static class Bling extends DelegatedHQuery { public Bling (HQuery delegate) { super (delegate); } public void bling() { for (JComponent result : contents()) result.putClientProperty ("bling", "true"); } public boolean hasBling () { for (JComponent result : contents()) { if (! "true".equals (result.getClientProperty ("bling"))) return false; } return true; } } @Test public void plugins() { assertEquals (0, $ ("[bling]").count()); $ ("#h2").with (Bling).bling(); assertEquals (1, $("[bling]").count()); assertTrue ($("#h2").with (Bling).hasBling()); } public static class Dummy extends DelegatedHQuery { public Dummy (HQuery delegate) { super (delegate); } public HQuery dummy() { return this; } } @Test public void pluginChaining() { assertEquals (0, $ ("[bling]").count()); $ ("#h2").with (Dummy.class).dummy().with (Bling).bling(); assertEquals (1, $("[bling]").count()); assertTrue ($("#h2").with (Bling).hasBling()); } @Test public void addAndRemove() { assertEquals (1, $ (new JButton()).count ()); assertEquals (3, h.asComponent ().getComponentCount ()); JButton h6 = new JButton(); h6.setName ("h6"); $ (h6).addTo (h); assertEquals (4, h.asComponent ().getComponentCount ()); $ ("#h3").removeFromParent(); assertEquals (3, h.asComponent ().getComponentCount ()); assertQueryMatches ("#h > :last-child", h, "h6"); assertQueryMatches ("#h3", h); } // effects // validation // events // jxlayer // transitions // each() method for iteration ? useful or not ? maybe implementing Iterable directly // live events & live/die ? // compiled properties // triggers @Test public void events() { //tmp: for API purposes $("#h").connect (MouseEvents.click, new EventListener<MouseEvent> () { public void onEvent (MouseEvent e) { } }); assertEquals (0, h.asComponent().getMouseListeners().length); $("#h").connect (Events.mouse, new MouseAdapter() {}); assertEquals (1, h.asComponent().getMouseListeners().length); assertEquals (0, h.asComponent().getMouseMotionListeners().length); $("#h").connect (Events.mouseMotion, new MouseAdapter() {}); assertEquals (1, h.asComponent().getMouseMotionListeners().length); assertEquals (0, h.asComponent().getMouseWheelListeners().length); $("#h").connect (Events.mouseWheel, new MouseAdapter() {}); assertEquals (1, h.asComponent().getMouseWheelListeners().length); assertEquals (1, $("#h5").asJComposite (JButton.class).getActionListeners().length); $("#h5").connect (Events.action, new ActionListener() { @Override public void actionPerformed (ActionEvent e) { } }); assertEquals (2, $("#h5").asJComposite (JButton.class).getActionListeners().length); } private static class MockMouseAdapter extends MouseAdapter { private boolean callbackCalled = false; @Override public void mouseClicked (MouseEvent e) { callbackCalled = true; } public void verify() { assertTrue ("The mouseClicked() callback should have been called!", callbackCalled); } } public static class HComponentWithEvent extends HComponent<JComponent, HComponentWithEvent> { private final DefaultCompositeEventSource<MouseListener> click = new DefaultCompositeEventSource<MouseListener> (MouseListener.class); public void fireMouseClick() { click.delegate ().mouseClicked (null); } public CompositeEventSource<MouseListener> click() { return click; } public Events events() { return new Events(); } public class Events { public CompositeEventSource<MouseListener> click() { return click; } public final CompositeEventSource<MouseListener> click = HComponentWithEvent.this.click; } } @Test public void compositeEvents() { MockMouseAdapter listener = new MockMouseAdapter(); HComponentWithEvent x = new HComponentWithEvent (); assertEquals (0, x.click.listeners().length); x.connect (x.events ().click, listener); // public variable w/ an indirection, in order not to pollute the component API with event methods assertEquals (1, x.click.listeners().length); x.connect (x.events ().click(), listener); // method call w/ an indirection, in order not to pollute the component API with event methods and return an instance of the EventSource interface assertEquals (2, x.click.listeners().length); x.connect (x.click, listener); // public variable (can sometimes pose a problem as it offers access to the delegate/even firing from outside) assertEquals (3, x.click.listeners().length); x.connect (x.click(), listener); // method call, returning an instance of the EventSource interface, which forbids access to the delegate assertEquals (4, x.click.listeners().length); x.fireMouseClick(); listener.verify (); } private HPanel h; @Before public void setUp() { h = new HPanel ().as ("h"); h.add (new HPanel().as ("h1").add (new HLabel().as ("h2"))); h.add (new HPanel().as ("h3").add (new HLabel().as ("h4"))); h.add (new HButton().as ("h5")); } public HQuery $ (JComponent component) { return HPanel.query (component); } public HQuery $ (String query) { return h.query (query); } }
Java
UTF-8
1,262
3.34375
3
[]
no_license
package ArrayProblem; import java.util.ArrayList; import java.util.List; public class Solution228 { public static void main(String[] args) { // TODO Auto-generated method stub int[] nums = {0}; int s = 0; int e = 1; String s1 = s+"->"+e; System.out.println(s1); ArraySolution228 result = new ArraySolution228(); List<String> res = result.summaryRanges(nums); System.out.println(res.toString()); } } class ArraySolution228 { public List<String> summaryRanges(int[] nums) { if(nums.length == 0) { return new ArrayList<>(); } if(nums.length == 1) { List<String> list1 = new ArrayList<>(); list1.add(nums[0]+""); return list1; } List<String> list = new ArrayList<>(); int start = nums[0]; int end = nums[0]; for(int i = 1;i<nums.length;i++) { if(nums[i] - end == 1) { end = nums[i]; }else { if(end - start != 0) { list.add(start + "->" + end); }else { list.add(end +""); } end = nums[i]; start = nums[i]; } } if(end - start != 0) { list.add(start + "->" + end); }else { list.add(end +""); } return list; } }
Java
UTF-8
1,161
2.640625
3
[ "Apache-2.0" ]
permissive
package net.osomahe.realapp.price.control; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import javax.ejb.Singleton; import net.osomahe.realapp.price.entity.Price; /** * TODO write JavaDoc * * @author Antonin Stoklasek */ @Singleton public class PriceStorage { private Map<String, Price> prices = new ConcurrentHashMap<>(); private AtomicLong counterRequested = new AtomicLong(0); private AtomicLong counterReceived = new AtomicLong(0); public void addPrice(Price price) { prices.put(price.getCode(), price); } public Collection<Price> getPrices() { return prices.values(); } public Map<String, Long> getCounters() { Map<String, Long> map = new HashMap<>(); map.put("counterRequested", counterRequested.longValue()); map.put("counterReceived", counterReceived.longValue()); return map; } public void plusReceived() { counterReceived.addAndGet(1); } public void plusRequested() { counterRequested.addAndGet(1); } }
C++
UTF-8
6,894
3.15625
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; class CPolynomial { private: vector<float> coe_table; static void set_coefficients(const bool was_x, unsigned &power, double &digit, CPolynomial &p, const int sign) { if (was_x && !power) { power = 1; } if (power >= p.coe_table.size()) { p.coe_table.resize(power + 1); } if (was_x && digit == 0.0) { digit = 1; } p.coe_table[power] += sign * digit; } public: CPolynomial() {}; CPolynomial(vector<float> vec) {}; friend istream &operator>>(istream &in, CPolynomial &coe_table); friend ostream &operator<<(ostream &out, const CPolynomial &p); friend CPolynomial operator*(const CPolynomial &ths, const CPolynomial &rhs) { CPolynomial new_p; new_p.coe_table.resize(ths.coe_table.size() + rhs.coe_table.size() + 1); for (int i = 0; i < ths.coe_table.size(); i++) for (int j = 0; j < rhs.coe_table.size(); j++) new_p.coe_table[i + j] += ths.coe_table[i] * rhs.coe_table[j]; return new_p; } CPolynomial &operator*=(const CPolynomial &other) { *this = *this * other; return *this; } friend CPolynomial operator*(const CPolynomial &p1, double digit) { CPolynomial new_p; new_p.coe_table.resize(p1.coe_table.size()); for (int i = 0; i < p1.coe_table.size(); i++) { new_p.coe_table[i] = digit * p1.coe_table[i]; } return new_p; } CPolynomial &operator*=(double digit) { *this = *this * digit; return *this; } CPolynomial &operator=(const CPolynomial &other) { if (&other == this) return *this; coe_table = other.coe_table; return *this; } CPolynomial &operator/=(float digit) { for (int i = 0; i < this->coe_table.size(); i++) this->coe_table[i] /= digit; return *this; } friend CPolynomial operator+(const CPolynomial &ths, const CPolynomial &rhs) { CPolynomial new_p; new_p = ths; new_p += rhs; return new_p; } CPolynomial &operator+=(const CPolynomial &other_p) { if (this->coe_table.size() >= other_p.coe_table.size()) for (int i = 0; i < other_p.coe_table.size(); i++) this->coe_table[i] += other_p.coe_table[i]; else { for (int i = 0; i < this->coe_table.size(); i++) this->coe_table[i] += other_p.coe_table[i]; for (int i = this->coe_table.size(); i < other_p.coe_table.size(); i++) this->coe_table.push_back(other_p.coe_table[i]); } return *this; } friend CPolynomial operator-(const CPolynomial &ths, const CPolynomial &rhs) { CPolynomial new_p; new_p = ths + rhs * (-1); return new_p; } CPolynomial &operator-=(const CPolynomial &other) { *this = *this - other; return *this; } CPolynomial operator-() const { CPolynomial p; p = *this * (-1); return p; } friend bool operator==(const CPolynomial &ths, const CPolynomial &rhs) { if (ths.coe_table.size() != rhs.coe_table.size()) { return false; } else { for (int i = 0; i < ths.coe_table.size(); i++) { if (ths.coe_table[i] != rhs.coe_table[i]) { return false; } } } return true; } friend bool operator!=(const CPolynomial &ths, const CPolynomial &rhs) { return !(ths == rhs); } float operator[](const int i) const { return this->coe_table[i - 1]; } ~CPolynomial() {}; }; ostream &operator<<(ostream &out, const CPolynomial &p) { if (!p.coe_table.empty()) { int tmp = p.coe_table.size() - 1; if (p.coe_table[tmp] > 0) if (p.coe_table[tmp] != 1) out << p.coe_table[tmp] << "x^" << tmp; else out << "x^" << tmp; else if (p.coe_table[tmp] < 0) if (p.coe_table[tmp] != -1) out << p.coe_table[tmp] << "x^" << tmp; else out << "-x^" << tmp; for (int i = p.coe_table.size() - 2; i > 1; i--) { if (p.coe_table[i] != 0) { if (p.coe_table[i] > 0) if (p.coe_table[i] != 1) out << " + " << p.coe_table[i] << "x^" << i; else out << " + " << "x^" << i; else if (p.coe_table[i] != -1) out << " - " << abs(p.coe_table[i]) << "x^" << i; else out << " - x^" << i; } } if (p.coe_table[1] > 0) if (p.coe_table[1] != 1) out << " + " << p.coe_table[1] << "x"; else out << " + x"; else if (p.coe_table[1] < 0) if (p.coe_table[1] != -1) out << " - " << abs(p.coe_table[1]) << "x"; else out << " - x"; if (p.coe_table[0] > 0) out << " + " << p.coe_table[0]; else if (p.coe_table[0] < 0) out << " - " << abs(p.coe_table[0]); out << "\n"; } else out << 0 << "\n"; return out; }; istream &operator>>(istream &in, CPolynomial &p) { vector<float> index; string str; getline(in, str); str.erase(remove(str.begin(), str.end(), ' '), str.end()); unsigned power = 0; double digit = 0; int sign = 1; bool is_coef = false, was_x = false; for (int i = 0; i < str.size(); i++) { if (str[i] == '+' || str[i] == '-') { is_coef = false; if (i != 0) CPolynomial::set_coefficients(was_x, power, digit, p, sign); digit = 0, power = 0; if (str[i] == '-') { sign = -1; } else { sign = 1; } was_x = false; } else if (str[i] == '^') { is_coef = true; power = 0; } else if (is_coef) { power = power * 10 + (str[i] - '0'); } else { if (str[i] == 'x') { was_x = true; } else { digit = digit * 10 + (str[i] - '0'); } } } CPolynomial::set_coefficients(was_x, power, digit, p, sign); return in; }; int main() { CPolynomial l, k, sum, dif; cin >> l; cin >> k; // l *= 3; sum = k + l; cout << sum; dif = l - k; cout << dif; return 0; }
Shell
UTF-8
238
2.984375
3
[]
no_license
#!/bin/bash -x # trouble: сценарий для демонстрации распространенных видов ошибок number=1 if [ $number = 1 ]; then echo "Number is equal to 1." else echo "Number is not equal to 1." fi
Java
UTF-8
1,259
2.828125
3
[]
no_license
package nitka_2; import java.awt.Color; import java.awt.Graphics; import javax.swing.JApplet; public class Nitka_2 extends JApplet implements Runnable{ int x, y; @Override public void init(){ this.setSize(170, 550); x = 0; y = 550; Thread t = new Thread(this); t.start(); } @Override public void paint(Graphics g){ g.setColor(new Color(255, 26, 26)); g.drawRect(x, y, 16, 10); g.setColor(new Color(0, 102, 0)); g.fillRect(x, y, 16, 10); } @Override public void run() { while(true){ repaint(); if(y > 0){ y -= 10; }else if(x >= 153){ x = 0; y = 550; this.setBackground(Color.WHITE); }else{ y = 540; x += 17; } try{ Thread.sleep(20); }catch(InterruptedException ex){ System.out.println("Прекинато!"); } } } }
TypeScript
UTF-8
6,275
2.953125
3
[ "Apache-2.0" ]
permissive
// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. // // Copyright 2016-2018 Pascal ECHEMANN. // // 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. import { Calculator } from "../../src/Calculator"; import { CalculatorFactory } from "../../src/CalculatorFactory"; import { CalculatorOperation } from "../../src/operations/CalculatorOperation"; import { Expression } from "./Expression"; import { ExpressionBuilder } from "./ExpressionBuilder"; import { StackState } from "./StackState"; import { StackStateError } from "./StackStateError"; import { StackStateValidator } from "./StackStateValidator"; import { StackStateMachine } from "./StackStateMachine"; import { ExpressionType } from "./ExpressionType"; /** * A sample class that emulates standard pocket calculators. */ export class StateCalculator { ////////////////////////////////////////////////////////////////////////////// // Constructor function ////////////////////////////////////////////////////////////////////////////// /** * Creates a new <code>StackedCalculator</code> instance. */ constructor() { this.initObj(); } ////////////////////////////////////////////////////////////////////////////// // Private properties ////////////////////////////////////////////////////////////////////////////// /** * The <code>Calculator</code> object used by this * <code>StackedCalculator</code> instance to perform computations. */ private _calculator:Calculator = null; /** * The list that contains expressions used to compute the current * user inputs. */ private _expStack:Expression[] = null; /** * The builder used to create new <code>Expression</code> instances. */ private _expBuilder:ExpressionBuilder = null; /** * The helper object that manages the states of the calculator. */ private _stateMachine:StackStateMachine = null; /** * The helper object that checks the states of the calculator. */ private _stateValidator:StackStateValidator = null; /** * Stores the current the state of the calculator. */ private _state:number = null;; ////////////////////////////////////////////////////////////////////////////// // Private methods ////////////////////////////////////////////////////////////////////////////// /** * Initializes this object. */ private initObj():void { const factory:CalculatorFactory = new CalculatorFactory(); this._calculator = factory.create(); this._expStack = new Array<Expression>(); this._expBuilder = new ExpressionBuilder(); this._stateMachine = new StackStateMachine(); this._stateValidator = new StackStateValidator(); this._state = StackState.EMPTY; } /** * Sets the current the state of the calculator, depending on the type * of user input specified. * * @param {number} expressionType the type of user input that is responsible * for changing the current state of the * calculator. */ private setState(expressionType:number):void { const nextState:number = this._stateMachine.getNextState( this._state, expressionType ); if(this._stateValidator.validate(nextState) === false) { throw new StackStateError("Invalid expression"); } else { this._state = nextState; } } ////////////////////////////////////////////////////////////////////////////// // Public methods ////////////////////////////////////////////////////////////////////////////// /** * Pushes the <code>CalculatorOperation.ADD</code> operation into the * calculator stack. */ public add():void { this.setState(ExpressionType.OPERATOR); this._expStack.unshift(this._expBuilder.build(CalculatorOperation.ADD)); } /** * Pushes the <code>CalculatorOperation.REMOVE</code> operation into the * calculator stack. */ public remove():void { this.setState(ExpressionType.OPERATOR); this._expStack.unshift(this._expBuilder.build(CalculatorOperation.REMOVE)); } /** * Pushes the <code>CalculatorOperation.MULTIPLY</code> operation into the * calculator stack. */ public multiply():void { this.setState(ExpressionType.OPERATOR); this._expStack.unshift(this._expBuilder.build(CalculatorOperation.MULTIPLY)); } /** * Pushes the <code>CalculatorOperation.DIVIDE</code> operation into the * calculator stack. */ public divide():void { this.setState(ExpressionType.OPERATOR); this._expStack.unshift(this._expBuilder.build(CalculatorOperation.DIVIDE)); } /** * Pushes the specified <code>value</code> into the calculator stack. * * @param {number} value the value to add to the calculator stack. */ public number(value:number):void { this.setState(ExpressionType.OPERAND); this._expStack.unshift(this._expBuilder.build(value)); } /** * Removes all expressions from the calculator stack. */ public reset():void { this.setState(ExpressionType.RESET); this._expStack.splice(0); } /** * Removes expressions strored in the calculator stack ad returns * the result. */ public compute():number { let result:number = 0; let len:number = this._expStack.length; let operand1:Expression = null; let operand2:Expression = null; let operator:Expression = null; let cursor:number = len - 1; while(len -= 3) { operand1 = this._expStack[cursor]; operator = this._expStack[cursor - 1]; operand2 = this._expStack[cursor - 2]; result += this._calculator.doOperation( operator.value, operand1.value, operand2.value ); cursor = len; } this.reset(); return result; } }
JavaScript
UTF-8
8,069
3.25
3
[]
no_license
let _confirmDialog = null; let _promptDialog = null; /** * List-item objects. */ class ListItem { /** * Injects dependencies into list item class. * @param {function} confirmDialog * @param {function} promptDialog */ static init(confirmDialog, promptDialog) { _confirmDialog = confirmDialog; _promptDialog = promptDialog; } /** * Initialize new node with no children * @param {string} caption */ constructor(caption, parent = null) { this.caption = caption; // this node's caption this.children = []; // array of child nodes (ListItem objects) this.parent = parent; // reference to a parent ListItem (null for root) this.collapsed = false; // whether the children are visible this._domObj = null; // reference to corresponding DOM <li> element this._domParent = null; // reference to parent DOM <ul> element } /** * Internal handler of onclick event (expand/collapses the node). */ _clickHandler = ev => { ev.stopPropagation(); if(this.collapsed) { this.expand(); } else { this.collapse(); } // TODO - step #6 } /** * Internal handler of the double click (starts editting the node's caption). */ _dblclickHandler = ev => { ev.stopPropagation(); this._promptForName("Item name:",this.caption).then(capt => { this.setCaption(capt) }).catch(()=>{}); // TODO (see _promptForName) } /** * Internal handler of delete icon onclick (removes the node). */ _deleteIconHandler = ev => { ev.stopPropagation(); console.log('in delete handler'); _confirmDialog(`Remove item "${this.caption}"?`).then(() => this.remove()).catch(() => {}); // TODO (see _confirmDialog) } /** * Internal handler of the add-list icon onclick. Creates sub-list and fill its first item from the prompt. */ _addlistIconHandler = ev => { ev.stopPropagation(); this._promptForName("Item name:").then(capt => { const newItem = new ListItem(capt, this); this.addChild(newItem); this.render(); }).catch(()=>{}); // TODO (see _promptForName) } /** * Internal handler of add icon onclick. Inserts new item at the end of corresponding list. */ _addIconHandler = ev => { ev.stopPropagation(); this._promptForName("Item name:").then(capt => { const newItem = new ListItem(capt, this); this.addChild(newItem); this.render(); }).catch(()=>{}); // TODO (see _promptForName) } /** * Internal function that prompts for new/change of caption. * It also highlights current node whilst inquiry is being posed. * @param {string} inquiry Message to be displayed in the prompt * @param {string} value Initial value of the input box * @return {Promise} Promise representing the prompt operation, resolving in a string */ _promptForName(inquiry, value = '') { if (this._domObj) { this._domObj.addClass('selected'); } return _promptDialog(inquiry, value).finally(() => { if (this._domObj) { this._domObj.removeClass('selected'); } }); } /** * Internal function that creates image with an icon. * @param {string} name Identifier (file name witout extension) * @param {string} title Title displayed on mouse hover * @param {function} onclickHandler Onclick (action) callback for the icon * @return {object} jQuery object representing the image */ _createImg(name, title, onclickHandler) { const img = $(`<img src="style/${name}.png" alt="${name}" title="${title}" />`); if (onclickHandler) { img.click(onclickHandler); } return img; } /** * Internal function that create icons list. * @param {bool} del Delete (remove) icon should be displayed * @param {bool} addList Add sub-list (children) icon should be displayed * @param {bool} add Add item (append) icon should be displayed * @return {object} jQuery object holding the container with the icons */ _createIcons(del, addList, add) { const icons = $('<span class="icons"></span>'); // icons container if(del) { icons.append(this._createImg('delete',"Delete item",this._deleteIconHandler)); } if(addList) { icons.append(this._createImg('add-list', "Add sub-list", this._addlistIconHandler)); } if(add) { icons.append(this._createImg('add', "Add item", this._addIconHandler)); } return icons; } /** * Render the list item into DOM. * @param {object} domParent DOM element which acts as container (parent). Should be an <ul> element. * If domParent is null (missing), the DOM parent from the last call is used. */ render(domParent = null) { const replaceDomParent = !domParent; domParent = domParent || this._domParent; if (!domParent) return; const newChildren = $("<ul></ul>"); this.children.forEach(child => child.render(newChildren)); newChildren.append($("<li></li>").append(this._createIcons(false, false, true))); if(domParent.hasClass('nested-list-container')) { // domParent.is("div")) { domParent.empty(); domParent.append(newChildren); this._domParent = domParent; return; } const newDom = $("<li></li>").text(this.caption).click(this._clickHandler) .append(this._createIcons(true, this.children.length === 0, false)) .dblclick(this._dblclickHandler); if (this.collapsed) { newDom.addClass("collapsed"); } if(this.children.length !== 0) { newDom.append(newChildren).addClass("parent"); } // TODO - step #4 mainly if (replaceDomParent) { this._domObj.replaceWith(newDom); } else { domParent.append(newDom); } // Make sure we remember, which DOM objects we have ... this._domParent = domParent; this._domObj = newDom; } /** * @param {ListItem} child The list item oject that will be appended to the child list. */ addChild(child) { if (!(child instanceof ListItem)) { throw new Error("Given child is not a ListItem object."); } // TODO - step #2 child.parent = this; this.children.push(child); if(this._domObj) { this.render(); } } /** * Change the caption of the item. * @param {string} caption New caption of the list item */ setCaption(caption) { this.caption = caption; this.render(); } /** * Make the element collapsed (hide its children). */ collapse() { // TODO - step #5 this.collapsed = true; this._domObj.addClass("collapsed"); } /** * Make the element expanded (show its children). */ expand() { // TODO - step #5 this.collapsed = false; this._domObj.removeClass("collapsed"); } /** * Remove the element from the tree structure (i.e., from the children list of its parent). */ remove() { if (!this.parent) { throw new Error("The root element cannot be removed by this function."); } // TODO - step #8 this.parent.children = this.parent.children.filter(child => child !== this); this.parent.render(); } /** * Helper function that builds a whole nested list from given data object. * @param {string|object} container jQuery selector/object pointing to DOM element which contains the list. * @param {Array} data The data structure from which the list is constructed * @return {ListItem} Root object of the constructed tree */ static buildNestedList(container, data) { console.log("container: " + container); console.log("data: " + data); // Internal recursive function that buids a ListItem (and all its children) from given data item. const build = (dataItem,parent) => { // TODO - step #3 const item = new ListItem(dataItem.caption, parent); if(dataItem.children) { dataItem.children.map(child => build(child, item)).forEach(child => item.addChild(child)); } return item; } // Prepare the container. container = $(container); container.addClass('nested-list-container'); container.empty(); // Build the root from fake dataItem which holds the data as children (root stands above these data). const root = build({ caption: '', children: data }); console.log("root:"+root); console.log("container: "+ container) root.render(container); return root; } } module.exports = { ListItem }
JavaScript
UTF-8
790
2.859375
3
[]
no_license
const hero = document.querySelector('.hero'); const text = hero.querySelector('h1'); const walk = 100; function shadow(e) { const {offsetWidth: width, offsetHeight: height} = hero; let {offsetX: x, offsetY: y} = e; if(this !== e.target) { x = x + e.target.offsetLeft; y = y + e.target.offsetTop; } const xWalk = Math.round((x / width * walk) - (walk / 2)); const yWalk = Math.round((y / width * walk) - (walk / 2)); text.style.textShadow = ` ${xWalk}px ${yWalk}px 10px rgba(138, 255, 60, 0.5), ${xWalk * -1}px ${yWalk}px 10px rgba(255, 178, 100, 0.9), ${yWalk}px ${xWalk}px 10px rgba(76, 200, 100, 200.75), ${yWalk * -1}px ${xWalk}px 10px rgba(150, 199, 255, 0.6) `; } hero.addEventListener('mousemove', shadow);
Java
UTF-8
209
2.125
2
[]
no_license
package com.deprommet.exception; public class ConflictException extends CustomException { public ConflictException(String message, String clientMessage) { super(message, clientMessage); } }
Python
UTF-8
723
2.6875
3
[]
no_license
#!/usr/bin/env python #Uncomment above line for executability under UNIX #This is for Windows, but will work under UNIX #Alex Grant spec = [] f = open( 'spec.spc' ) for line in f: if line[0] is not '#': spec.append( line ) for x in range( len( spec ) ): spec[x] = spec[x][:len( spec[x] ) -1] if __name__ == '__main__': import os os.system( 'java org.commschool.scheduler.GenerateSpecification ' + spec[0] + ' > ' + spec[1] ) os.system( 'generateInitialSchedule -s ' + spec[1] + ' > ' + spec[2] ) os.system( 'printSchedule -s ' + spec[1] + ' -t ' + spec[2] + ' > ' + spec[3] ) print "Press Control-C to interrupt" os.system( 'simulatedAnnealing ' + spec[4] + ' -s ' + spec[1] + ' -t ' + spec[2] + ' -o ' + spec[5] )
Java
UTF-8
2,445
2.671875
3
[]
no_license
package dao; import entity.TeacherEntity; import util.BaseDao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Created by Ace on 2017/5/31. */ public class TeacherDao extends BaseDao{ public List<TeacherEntity> getList(TeacherEntity search){ String sql="select *from t_teacher"; if(search!=null) { if(search.getGender()!=null) { if (search.getGender().equals("0")) { sql += " where gender='" + search.getGender() + "' and"; } else if (search.getGender().equals("1")) { sql += " where gender='" + search.getGender() + "' and"; } }else { sql+=" where "; } sql += " id like '%"; sql +=search.getId()<0?"":search.getId(); sql +="%' and name like '%"; sql +=search.getName()==null?"":search.getName(); sql +="%'"; } List<TeacherEntity> list=new ArrayList<TeacherEntity>(); ResultSet rs=this.executeQuery(sql); try{ while(rs.next()){ list.add(new TeacherEntity(rs.getLong(1),rs.getString(2),rs.getString(3))); } } catch (SQLException e) { e.printStackTrace(); }finally { this.close(); } return list; } public TeacherEntity getByID(String id){ TeacherEntity teacherEntity=new TeacherEntity(); String sql="select *from t_teacher where id=?"; ResultSet rs=this.executeQuery(sql,id); try { if(rs.next()){ teacherEntity= new TeacherEntity(rs.getLong(1),rs.getString(2),rs.getString(3)); } } catch (SQLException e) { e.printStackTrace(); }finally { this.close(); } return teacherEntity; } public int update(TeacherEntity teacherEntity,String id){ String sql="update t_teacher set id=? ,name=?,gender=? where id=?"; return this.executeUpdate(sql,teacherEntity.getId(),teacherEntity.getName(),teacherEntity.getGender(),id); } public int insert(TeacherEntity teacherEntity){ String sql="insert into t_teacher(id,name,gender) values(?,?,?)"; return this.executeUpdate(sql,teacherEntity.getId(),teacherEntity.getName(),teacherEntity.getGender()); } }
Java
UTF-8
12,961
2.21875
2
[]
no_license
package com.bianlaoshi.new1; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import static java.lang.Math.abs; /** * Created by frank on 2017/12/15. */ public class a_4zhuceActivity extends AppCompatActivity { public static int[] a = new int[1]; private Handler handler=new Handler(); public static Context context; private String phoneNo; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.a_4zhuce); final EditText phonein=(EditText)findViewById(R.id.shoujihaoma); final EditText testin=(EditText)findViewById(R.id.yanzhengma); final EditText pass1=(EditText)findViewById(R.id.shezhimima); final EditText pass2=(EditText)findViewById(R.id.querenmima); ImageButton send=(ImageButton)findViewById(R.id.imageButton6); Button lssubmit=(Button)findViewById(R.id.lsbuttonzhuce); Button xssubmit=(Button)findViewById(R.id.xsbuttonzhuce); final TextView test=(TextView)findViewById(R.id.textView64); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 final Date[] start = {null}; send.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if(phonein.getText().length()==0){ new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("手机号码不能为空") .setPositiveButton("确定",null) .show(); } else if(phonein.getText().length()!=11){ new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("手机号码应是11位") .setPositiveButton("确定",null) .show(); } else{ //防止不停点击 Date now=new Date(); if(start[0] !=null && (now.getTime()- start[0].getTime())<=180000) { test.setText("验证码正在传输,请稍后"); } else { //生成验证码 Random r=new Random(); a[0] = abs(r.nextInt())%100000; String phone=phonein.getText().toString(); sendTextThread thread=new sendTextThread(a[0],phone); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } phoneNo=phone; test.setText("验证码已发送"); start[0] =now; } } } }); lssubmit.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { //老师注册 String yzm=testin.getText().toString(); String yzm1=Integer.toString(a[0]); if(yzm.contains(yzm1)&&yzm1.contains(yzm)) { String passA=pass1.getText().toString(); String passB=pass2.getText().toString(); if(phonein.getText().length()==0){ new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("手机号码不能为空") .setPositiveButton("确定",null) .show(); } else if(phonein.getText().length()!=11){ new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("手机号码应是11位") .setPositiveButton("确定",null) .show(); } else if(passA.length()==0){ new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("密码不能为空") .setPositiveButton("确定",null) .show(); } else if(passA.length()<6){ new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("密码位数应大于等于6") .setPositiveButton("确定",null) .show(); } else if(passA.length()>20){ new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("密码位数不能大于20") .setPositiveButton("确定",null) .show(); } else{ if(passA.contains("'")){ String s =pass1.getText().toString().replace("'","‘"); pass1.setText(s); } if(passB.contains("'")){ String s =pass2.getText().toString().replace("'","‘"); pass2.setText(s); } if(testin.getText().toString().contains("'")){ String s =testin.getText().toString().replace("'","‘"); testin.setText(s); } if(passA.contains(passB)&&passB.contains(passA)) { String phone=phonein.getText().toString(); testteathread.a=1; //验证用户是否存在 String url1="http://112.74.176.171:8080/xmb/servlet/testUserServlet?uid="+phone; Thread thread=new testUserThread(url1,handler,phonein,pass1,pass2,testin,test,1,a_4zhuceActivity.this,phoneNo); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } else { //弹窗:密码不一致 new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("密码不一致") .setPositiveButton("确定",null) .show(); } } } else { //弹窗:验证码错误 new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("验证码错误") .setPositiveButton("确定",null) .show(); } } }); xssubmit.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { //学生注册 String yzm=testin.getText().toString(); String yzm1=Integer.toString(a[0]); if(yzm.contains(yzm1)&&yzm1.contains(yzm)) { String passA=pass1.getText().toString(); String passB=pass2.getText().toString(); if(phonein.getText().length()==0){ new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("手机号码不能为空") .setPositiveButton("确定",null) .show(); } else if(phonein.getText().length()!=11){ new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("手机号码应是11位") .setPositiveButton("确定",null) .show(); } else if(passA.length()==0){ new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("密码不能为空") .setPositiveButton("确定",null) .show(); } else if(passA.length()<6){ new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("密码位数应大于等于6") .setPositiveButton("确定",null) .show(); } else if(passA.length()>20){ new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("密码位数不能大于20") .setPositiveButton("确定",null) .show(); } else{ if(passA.contains("'")){ String s =pass1.getText().toString().replace("'","‘"); pass1.setText(s); } if(passB.contains("'")){ String s =pass2.getText().toString().replace("'","‘"); pass2.setText(s); } if(testin.getText().toString().contains("'")){ String s =testin.getText().toString().replace("'","‘"); testin.setText(s); } if(passA.contains(passB)&&passB.contains(passA)) { String phone=phonein.getText().toString(); teststuthread.a=1; //验证用户是否存在 String url1="http://112.74.176.171:8080/xmb/servlet/testUserServlet?uid="+phone; Thread thread=new testUserThread(url1,handler,phonein,pass1,pass2,testin,test,2,a_4zhuceActivity.this,phoneNo); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } else { //弹窗:密码不一致 new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("密码不一致") .setPositiveButton("确定",null) .show(); } } } else { new AlertDialog.Builder(a_4zhuceActivity.this) .setTitle("错误") .setMessage("验证码错误") .setPositiveButton("确定",null) .show(); //弹窗:验证码错误 } } }); } }
Markdown
UTF-8
1,330
3.171875
3
[]
no_license
# Compare reference images to generated images. ## Note the tables's non-white background color - check for transparent images. <table style="background-color:#E6E6FA; border: 1px solid black;"> <tr> <th>Reference Plots</th> <th>Generated Plots</th> </tr> <tr> <td style="background-color:#E6E6FA; border: 1px solid black;"><img src="../figure/unnamed-chunk-2.png" alt="Plot 1 reference"></td> <td style="background-color:#E6E6FA; border: 1px solid black;"><img src="../plot1.png" alt="Plot 1 generated"></td> </tr> <tr> <td style="background-color:#E6E6FA; border: 1px solid black;"><img src="../figure/unnamed-chunk-3.png" alt="Plot 2 reference"></td> <td style="background-color:#E6E6FA; border: 1px solid black;"><img src="../plot2.png" alt="Plot 2 generated"></td> </tr> <tr> <td style="background-color:#E6E6FA; border: 1px solid black;"><img src="../figure/unnamed-chunk-4.png" alt="Plot 3 reference"></td> <td style="background-color:#E6E6FA; border: 1px solid black;"><img src="../plot3.png" alt="Plot 3 generated"></td> </tr> <tr> <td style="background-color:#E6E6FA; border: 1px solid black;"><img src="../figure/unnamed-chunk-5.png" alt="Plot 4 reference"></td> <td style="background-color:#E6E6FA; border: 1px solid black;"><img src="../plot4.png" alt="Plot 4 generated"></td> </tr> </table> That's all folks
Python
UTF-8
220
3.421875
3
[]
no_license
#!/usr/bin/python #Read fucntion which reads by character size #f1=open("input.txt","r") #str=f1.read() #str=f1.read(30) #print "Read string is ",str for line in reversed(list(open("input.txt"))): print(line.rstrip())
Java
UTF-8
5,685
2.09375
2
[]
no_license
package org.netbeans.modules.groovy.editor.api.completion; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Set; import javax.lang.model.element.TypeElement; import org.netbeans.api.java.source.ClassIndex; import org.netbeans.api.java.source.ClasspathInfo; import org.netbeans.api.java.source.ElementHandle; import org.netbeans.modules.csl.api.CompletionProposal; /** * * @author Valery */ public class ImportTarget implements CompletionTarget { protected CompletionHandlerContext context; protected boolean staticImport; protected List<String> packages; protected String afterCaretIdentifier; /** * Create an instance for a given context, static flag, list of packages and before dot identifier * @param context * @param staticImport * @param packages * @param afterCaretIdentifier */ public ImportTarget(CompletionHandlerContext context, boolean staticImport, List<String> packages, String afterCaretIdentifier) { this.context = context; this.staticImport = staticImport; this.packages = packages; this.afterCaretIdentifier = afterCaretIdentifier; } public boolean isStaticImport() { return staticImport; } public void setStaticImport(boolean staticImport) { this.staticImport = staticImport; } // protected String getPath() { // return PackageInfo.getPath(context, packages, afterCaretIdentifier); // } protected String getBasePackage(String path) { if (! context.isDotCompletion()) { if ( context.getPackageInfo().hasPackage ) { if ( packages.isEmpty() && isStaticImport() && context.getPrefix().length()==0 ) { return context.getPackageInfo().getName(); } } else { return null; } } return PackageInfo.getBasePackage(context, path); } @Override public String toString() { return toString(false); /* * StringBuilder sb = new StringBuilder(); sb.append("import "); if * (isStaticImport()) { sb.append("static "); } if (packages.size() > 0) * { for (int i = packages.size() - 1; i >= 0; i--) { * sb.append(packages.get(i)); if (i != 0) { sb.append('.'); } } } * * return sb.toString(); */ } public String toString(boolean withoutPrefix) { StringBuilder sb = new StringBuilder(); sb.append("import "); if (isStaticImport()) { sb.append("static "); } int size = packages.size(); String prefix = context.getCodeContext().getPrefix(); if (prefix != null && withoutPrefix) { size = packages.size() - 1; } if (packages.size() > 0) { for (int i = 0; i < size; i++) { sb.append(packages.get(i)); if (i != 0) { sb.append('.'); } } } return sb.toString(); } @Override public List<CompletionProposal> getProposals() { List<CompletionProposal> proposals = new ArrayList<CompletionProposal>(); if (packages.isEmpty()) { if (!isStaticImport()) { getStaticKeywordProposal(proposals); } } else if ("*".equals(packages.get(0))) { return null; } getProposals(proposals); return proposals; } protected void getProposals(List<CompletionProposal> proposals) { ClasspathInfo classPath = context.getParserResult().getClassPath(); String path = PackageInfo.getPath(context, packages, afterCaretIdentifier); Set<String> pathPackages = classPath.getClassIndex(). getPackageNames(path, true, EnumSet.allOf(ClassIndex.SearchScope.class)); int anchor = context.getLexOffset() - context.getPrefix().length(); for (String p : pathPackages) { System.out.println("getProposals() FROM getPath() PACKAGE = " + p); String key = PackageInfo.getSimpleName(p); CompletionItem.PackageItem item = new CompletionItem.PackageItem(key, anchor, context.getParserResult()); proposals.add(item); item.setSortPrioOverride(2); //item.setSmart(true); } String basePackage = getBasePackage(path); System.out.println("getProposals() BASE PACKAGE = " + basePackage); Set<ElementHandle<TypeElement>> typeHandles = PackageInfo.getElementHandlesForPackage(context,basePackage); if (typeHandles != null) { for (ElementHandle<TypeElement> eh : typeHandles) { System.out.println("getProposals() Classes or Other types = " + eh.getQualifiedName()); String key = PackageInfo.getSimpleName(eh.getQualifiedName()); CompletionItem.TypeItem item = new CompletionItem.TypeItem(key, anchor, eh.getKind()); proposals.add(item); item.setSortPrioOverride(3); //item.setSmart(true); } } System.out.println("getProposals() ==========================="); } protected void getStaticKeywordProposal(List<CompletionProposal> proposals) { int anchor = context.getLexOffset() - context.getPrefix().length(); CompletionItem.KeywordItem item = new CompletionItem.KeywordItem("static", "Static Import", anchor, context.getParserResult(), true); proposals.add(item); item.setSortPrioOverride(1); } }
Markdown
UTF-8
635
2.59375
3
[ "MIT" ]
permissive
Much like its parent, [\<n-view\>](/components/n-view), basic routing information is required. ```html <n-view ...> <n-view-prompt path='<sub-path>' page-title='<route title>' visit='always|once|optional' when='<expression predicate>' src='<remote html with route sand children>' content-src='<remote content html>' transition='<animation-enter>' scroll-top-offset='' > ... </n-view-prompt> ... </n-view> ``` > The **when** attribute is a data expression that overrides the **visit** strategy. It is a predicate that produces a boolean result. **true: visit=always** false: visit=optional
Shell
UTF-8
875
2.734375
3
[]
no_license
echo "DOMAIN_HOME=${DOMAIN_HOME}" sed -i -e "s|ADMIN_PASSWORD|$s|g" /weblogic/create-T24-domain.py sed -i -e "s|ADMIN_PASSWORD|$s|g" /weblogic/t24DomainEnv.sh . /weblogic/oracle/wlserver/server/bin/setWLSEnv.sh # Create T24 domain wlst.sh -skipWLSModuleScanning /weblogic/create-T24-domain.py mkdir -p ${DOMAIN_HOME}/servers/AdminServer/security/ echo "username=${ADMIN_USERNAME}" > ${DOMAIN_HOME}/servers/AdminServer/security/boot.properties echo "password=${ADMIN_PASSWORD}" >> ${DOMAIN_HOME}/servers/AdminServer/security/boot.properties # Set Domain Environment . ${DOMAIN_HOME}/bin/setDomainEnv.sh echo "Domain Env Set.." # Start Admin Server and tail the logs mkdir -p ${DOMAIN_HOME}/servers/AdminServer/security/logs/ touch ${DOMAIN_HOME}/servers/AdminServer/security/logs/AdminServer.log tail -f ${DOMAIN_HOME}/servers/AdminServer/security/logs/AdminServer.log &
PHP
UTF-8
4,939
2.515625
3
[]
no_license
<?php declare(strict_types=1); namespace TMV\OpenIdClientModule\Client; use Interop\Container\ContainerInterface; use Interop\Container\Exception\ContainerException; use Jose\Component\Core\JWKSet; use TMV\OpenIdClient\AuthMethod\AuthMethodFactory; use TMV\OpenIdClient\AuthMethod\AuthMethodFactoryInterface; use TMV\OpenIdClient\Client\Client; use TMV\OpenIdClient\Client\ClientInterface; use TMV\OpenIdClient\Client\Metadata\ClientMetadata; use TMV\OpenIdClient\Client\Metadata\ClientMetadataInterface; use TMV\OpenIdClient\Issuer\IssuerInterface; use Zend\ServiceManager\Exception\ServiceNotCreatedException; use Zend\ServiceManager\Exception\ServiceNotFoundException; use Zend\ServiceManager\Factory\AbstractFactoryInterface; class ClientAbstractFactory implements AbstractFactoryInterface { /** * Can the factory create an instance for the service? * * @param ContainerInterface $container * @param string $requestedName * @return bool */ public function canCreate(ContainerInterface $container, $requestedName): bool { if (! \preg_match('/^openid.clients.([^.]+)$/', $requestedName, $matches)) { return false; } [, $name] = $matches; $config = $container->get('config')['openid']['clients'][$name] ?? null; if (! \is_array($config)) { return false; } return true; } /** * Create an object * * @param ContainerInterface $container * @param string $requestedName * @param null|array $options * @return ClientInterface * @throws ServiceNotFoundException if unable to resolve the service. * @throws ServiceNotCreatedException if an exception is raised when * creating a service. * @throws ContainerException if any other error occurs */ public function __invoke(ContainerInterface $container, $requestedName, array $options = null): ClientInterface { if (! \preg_match('/^openid.clients.([^.]+)$/', $requestedName, $matches)) { throw new ServiceNotFoundException('Unable to find a client named ' . $requestedName); } [, $name] = $matches; $config = $container->get('config')['openid']['clients'][$name] ?? null; if (! \is_array($config)) { throw new ServiceNotFoundException('Unable to find a valid configuration for client named ' . $requestedName); } $jwks = $config['jwks'] ?? null; $authMethods = $config['auth_methods'] ?? null; /** @var AuthMethodFactoryInterface $authMethodFactory */ $authMethodFactory = ! \is_array($authMethods) ? $container->get(AuthMethodFactoryInterface::class) : new AuthMethodFactory(\array_map([$container, 'get'], $authMethods)); $httpClientName = $config['http_client'] ?? null; $httpClient = $httpClientName ? $container->get($httpClientName) : null; return new Client( $this->getIssuer($container, $requestedName, $config['issuer'] ?? null), $this->getMetadata($container, $requestedName, $config['metadata'] ?? null), $jwks ? $this->getJWKSet($container, $requestedName, $jwks) : new JWKSet([]), $authMethodFactory, $httpClient ); } private function getIssuer(ContainerInterface $container, string $requestedName, $issuer): IssuerInterface { if (! \is_string($issuer)) { throw new ServiceNotCreatedException('Invalid issuer provided for client named ' . $requestedName); } $issuer = $container->get($issuer); if (! $issuer instanceof IssuerInterface) { throw new ServiceNotCreatedException('Invalid issuer provided for client named ' . $requestedName); } return $issuer; } private function getMetadata(ContainerInterface $container, string $requestedName, $metadata): ClientMetadataInterface { if (! \is_array($metadata)) { throw new ServiceNotCreatedException('Invalid metadata provided for client named ' . $requestedName); } return ClientMetadata::fromArray($metadata); } private function getJWKSet(ContainerInterface $container, string $requestedName, $jwks): JWKSet { if (\is_array($jwks)) { return JWKSet::createFromKeyData($jwks); } if (! \is_string($jwks)) { throw new ServiceNotCreatedException('Invalid jwks provided for client named ' . $requestedName); } $decoded = \json_decode($jwks, true); if (\is_array($decoded)) { return JWKSet::createFromKeyData($decoded); } $jwkSet = $container->get($jwks); if (! $jwkSet instanceof JWKSet) { throw new ServiceNotCreatedException('Invalid jwks provided for client named ' . $requestedName); } return $jwkSet; } }
Python
UTF-8
132
3.453125
3
[]
no_license
file = open("numbers.txt","r") number = file.readline() while number != "": print(number, end="") number = file.readline()
Markdown
UTF-8
676
2.796875
3
[ "MIT" ]
permissive
# Password Generator A tool to provide the user a way to have a password generated for them by following the prompts. The user can instruct the tool to include special characters in the password. ![ScreenShot](./Password-Generator.JPG) ## URL of Deployed Application https://designurhappy.github.io/Password-Generator/ ## GitHub Respository https://github.com/designurhappy/Password-Generator ## License [MIT](https://choosealicense.com/licenses/mit/) ## Questions * GitHub Username: designurhappy * GitHub Link: https://github.com/designurhappy * Email Address: beachgal0105@gmail.com * Contact Instructions: Please email me for additional questions or call me at (805) 990-9977
Java
UTF-8
434
1.828125
2
[]
no_license
package eflowing.example.cloud.service.redis; import org.springframework.boot.SpringApplication; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cloud.client.SpringCloudApplication; @SpringCloudApplication @EnableCaching public class RedisDemoApplication { public static void main(String[] args) { SpringApplication.run(RedisDemoApplication.class, args); } }
Shell
UTF-8
698
3.859375
4
[]
no_license
#!/bin/sh # ---- Global variables ---- input=/dev/input/event1 code_prefix="ABS" code="${code_prefix}_[XY]" val_regex=".*(${code_prefix}_\(.\)), value \([-]\?[0-9]\+\)" val_subst="\1=\2" # ---- Functions ---- send_axis() { # 1. Convert axis value ($1) from device specific units # 2. Send this axis value via UDP packet echo $1 } process_line() { while read line; do axis=$(echo $line | grep "^Event:" | grep $code | \ sed "s/$val_regex/$val_subst/") if [ -n "$axis" ]; then send_axis $axis fi done } # ---- Entry point ---- if [ $(id -u) -ne 0 ]; then echo "This script must be run from root" >&2 exit 1 fi
Java
UTF-8
2,560
2.421875
2
[]
no_license
package com.shaoyuanhu.dao.redis.impl; import com.shaoyuanhu.dao.redis.JedisClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import redis.clients.jedis.JedisCluster; import java.util.List; import java.util.Map; import java.util.Set; /** * @Description: jedis集群版实现类 * @Author: ShaoYuanHu * @Date: 2017/12/4 */ @Service("jedisClientCluster") public class JedisClientCluster implements JedisClient { @Autowired private JedisCluster jedisCluster; @Override public String set(String key, String value) { return jedisCluster.set(key, value); } @Override public String get(String key) { return jedisCluster.get(key); } @Override public Boolean exists(String key) { return jedisCluster.exists(key); } @Override public Long expire(String key, int seconds) { return jedisCluster.expire(key, seconds); } @Override public Long ttl(String key) { return jedisCluster.ttl(key); } @Override public Long incr(String key) { return jedisCluster.incr(key); } @Override public Long hset(String key, String field, String value) { return jedisCluster.hset(key, field, value); } @Override public String hget(String key, String field) { return jedisCluster.hget(key, field); } @Override public Long hdel(String key, String... field) { return jedisCluster.hdel(key, field); } @Override public Long del(String key) { return jedisCluster.del(key); } @Override public String getSet(String key, String value) { return jedisCluster.getSet(key, value); } @Override public Set<String> smembers(String key) { return jedisCluster.smembers(key); } @Override public Long setNx(String key, String value) { return jedisCluster.setnx(key, value); } @Override public Long lpush(String key, String... members) { return jedisCluster.lpush(key, members); } @Override public List<String> lrange(String key) { return jedisCluster.lrange(key,0,-1); } @Override public String rpop(String key) { return jedisCluster.rpop(key); } @Override public String hmset(String key, Map<String, String> map) { return jedisCluster.hmset(key, map); } @Override public Map<String, String> hgetAll(String key) { return jedisCluster.hgetAll(key); } }
C
UTF-8
2,519
3.015625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <err.h> typedef struct info info; struct info{ char *coms[32]; char *in; char *out; }; char *arpath[] = {"/bin", "/usr/bin", "usr/local/bin"}; int **pipes; int numcoms; info data; void createpipes() { int i; pipes = malloc(sizeof(int*) * (numcoms - 1)); for(i = 0; i < (numcoms - 1); i++){ pipes[i] = malloc(sizeof(int) * 2); pipe(pipes[i]); } } void closepipes() { int i; for(i = 0; i < numcoms - 1; i++){ close(pipes[i][0]); close(pipes[i][1]); } } void preparepipes(int i) { if(i == 0){ dup2(pipes[i][1], 1); } else if(i > 0 && (i < numcoms - 1)){ dup2(pipes[i-1][0], 0); dup2(pipes[i][1], 1); }else if(i == (numcoms - 1)){ dup2(pipes[i-1][0], 0); } closepipes(); } void insertcom(char *com) { int i; i = 0; while(data.coms[i] != NULL) i++; data.coms[i] = com; } void filldata(int argc, char *argv[]) { int i; for(i = 1; i < argc; i++){ if(strcmp(argv[i], "-i") == 0) data.in = argv[++i]; else if(strcmp(argv[i], "-o") == 0) data.out = argv[++i]; else{ insertcom(argv[i]); numcoms++; } } } void dodups() { int fd; if(data.out != NULL){ fd = creat(data.out, 0744); if (fd < 0) err(1, "Error to create file"); dup2(fd, 1); close(fd); } if(data.in != NULL){ fd = open(data.in, O_RDONLY); if (fd < 0) err(1, "Error to open file"); dup2(fd, 0); close(fd); } } char * createpath(char *str, char *str2) { char *buffer; int lenbuf; lenbuf = (strlen(str) + strlen(str2) + 2); buffer = malloc(lenbuf); snprintf(buffer, lenbuf, "%s/%s", str, str2); return buffer; } char * path2exec(int com) { int i; char *pathcom; for(i = 0;;i++){ if(arpath[i] == NULL) return NULL; pathcom = createpath(arpath[i], data.coms[com]); if(access(pathcom, X_OK) == 0) return pathcom; free(pathcom); } } void executecom(int i) { pid_t pid; char *path; pid = fork(); if(pid == 0){ if(numcoms > 1) preparepipes(i); path = path2exec(i); if(path != NULL){ execl(path, data.coms[i], NULL); } err(1, "Can't execute command '%s'", data.coms[i]); } if(pid < 0) err(1, "Error to do fork"); } void execute() { int i; if(numcoms > 1) createpipes(); for(i = 0; i < numcoms; i++) executecom(i); closepipes(); for(i = 0; i < numcoms; i++) wait(NULL); } int main(int argc, char *argv[]) { filldata(argc, argv); dodups(); execute(); exit(EXIT_SUCCESS); }
PHP
UTF-8
1,815
2.578125
3
[]
no_license
<? include ("inc/header.php"); ?> <? include ("inc/widget.php"); ?> <?php if ( empty($_SESSION['username'])) { include 'lib/redirect.php'; movePage(403,"login.php"); exit; }; include 'lib/mysql.php'; $sql = 'SELECT kundennummer, name, strasse, hausnummer, plz, ort, telefonnummer FROM kunde'; $stmt = $db_connection->prepare($sql); $stmt->execute(); $stmt->bind_result($kundennummer,$name,$strasse,$hausnummer,$plz,$ort,$telefonnummer); ?> <div id="Content"> <h2>Kunden</h2> </br> <table cellpadding="0" cellspacing="0" border="0" id="dataTable"> <thead> <tr> <th>B</th> <th>L</th> <th>Kundennummer</th> <th>Name</th> <th>Strasse</th> <th>Hausnummer</th> <th>PLZ</th> <th>Ort</th> <th>Telefonnumer</th> </tr> </thead> <tbody> <?php while ($stmt->fetch()) { #header("Content-Type: text/json"); #echo json_encode($json); ?> <tr> <td align="center"><a href="customer.php?<?php echo "kundennummer=$kundennummer&name=$name&strasse=$strasse&hausnummer=$hausnummer&plz=$plz&ort=$ort&telefonnummer=$telefonnummer&function=bearbeiten"; ?>"><img src="images/icon_edit.png" alt="bearbeiten" ></a></td> <td align="center"><a href="customer.php?<?php echo "kundennummer=$kundennummer&name=$name&strasse=$strasse&hausnummer=$hausnummer&plz=$plz&ort=$ort&telefonnummer=$telefonnummer&function=loeschen"; ?>"><img src="images/icon_delete.png" alt="l&ouml;schen"></a></td> <td><?php echo $kundennummer; ?></td> <td><?php echo $name; ?></td> <td><?php echo $strasse; ?></td> <td><?php echo $hausnummer; ?></td> <td><?php echo $plz; ?></td> <td><?php echo $ort; ?></td> <td><?php echo $telefonnummer; ?></td> </tr> <?php } ?> </tbody> </table> </div> <? include ("inc/footer.php"); ?>
Markdown
UTF-8
1,159
3.0625
3
[ "Apache-2.0" ]
permissive
#记录在数据库设计以及操作过程中的某些设计思路和问题 *** >1.数据库连接类以及操作的封装 >>自己的打算是学习JFinal的设计思想,将所有的访问记录用一个Record类进行封装 也就是说一个Record相当于一条记录。这里的设计思想是由于ResultSet中记录和Model 层具有对应性,这样我可以在Record中持有Model,就可以产生与Model中每个字段 相对应的Map,用于存储一条记录。但是这里出现的问题是有些时候数据库表字段命名和 Model中对应字段命名可能是不同的,所以在建立映射关系的时候很麻烦。因此将这种设计思想搁置了。(这里利用反射的思想以及集合类建立对应关系) >>本次采用的方式:数据的查询以及更新操作全部封装到一个类中,参数列表为SQL语句以及参数列表对象数组,在进行所有的操作过后,返回的是一个List<Map>数组,其中一个Map代表一条记录,List代表所有返回的记录集合。这里的方法封装了相应的事物以及非事物方法。除此之外也提供了手动操作的方法。
Java
UTF-8
2,900
1.960938
2
[]
no_license
/* * @Title: TravelCore.java * @Package: com.t2mobile.logman.travel * @Project: Logman * @Version: 1.0.0 * @CopyRight: @2015 T2M-VAL */ package com.t2mobile.logman.travel; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.message.BasicNameValuePair; import com.t2mobile.logman.storage.StageConfig.Stage; import android.os.AsyncTask; /** * * * @author songlin.ji */ public class TravelCore { private static final String URI_HOST = "172.24.212.40:8080"; private static final String BASE_URI = "http://" + URI_HOST + "/BugTravel/"; private static final String URI_STAGE = BASE_URI + "FormatStage"; private static final String URI_UPLOAD_RECORD = BASE_URI + "UploadRecord"; private static final String URI_UPLOAD_FILE = BASE_URI + "UploadFile"; private static final String URI_SUGGESTION = BASE_URI + "Suggestion"; public static final void registStage(Stage stage) { } public static final void uploadRecord() { } public static final void uploadFiles() { MultipartEntity a = new MultipartEntity(); HttpPost post = new HttpPost(); post.setEntity(a); } public static final void suggest(int stageID, String content, IResponseHandle responseHandle) { try { HttpPost httpPost = new HttpPost(URI_SUGGESTION); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); if (stageID > 0) { pairs.add(new BasicNameValuePair("id", String.valueOf(stageID))); } pairs.add(new BasicNameValuePair("suggestion", content)); httpPost.setEntity(new UrlEncodedFormEntity(pairs)); HttpClientManager.httpHandle(httpPost, responseHandle); } catch (UnsupportedEncodingException e) { e.printStackTrace(); responseHandle.UnsupportedEncodingException(e); } } private class httpAsyncTask extends AsyncTask<IHttpRequest, Integer, Long> { private httpAsyncTask() { } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); } @Override protected void onPostExecute(Long result) { // TODO Auto-generated method stub super.onPostExecute(result); } @Override protected void onProgressUpdate(Integer... values) { // TODO Auto-generated method stub super.onProgressUpdate(values); } @Override protected Long doInBackground(IHttpRequest... params) { // TODO Auto-generated method stub return null; } } private interface IHttpRequest { HttpUriRequest getRequest(); } }
Markdown
UTF-8
305
2.96875
3
[]
no_license
*The program calculates the hash of the file using the function **md5**, implemented in the library **openssl**.* *The complexity of the **O (n)** algorithm, because you need to analyze the entire file to get the result.* *The speed of the calculation depends on the size of the transferred file.*
PHP
UTF-8
1,208
2.65625
3
[ "Unlicense" ]
permissive
<?php namespace app\common; class OrderStatus extends \Prefab { const INITIAL = 0; const PREPARING = 1; const PREPARED = 2; const ALLOCATED = 3; const UPPER = 4; const SOLE = 5; const FINISH = 6; const CANCEL = 7; const WAITING = 8; function get() { $class = new \ReflectionClass('app\common\OrderStatus'); return $class->getConstants(); } function next($status) { switch ($status) { case self::PREPARED: return self::ALLOCATED; case self::ALLOCATED: return self::UPPER; case self::UPPER: return self::SOLE; case self::SOLE: return self::FINISH; } return $status; } function name() { return [ self::INITIAL => '新建', self::PREPARING => '缺料', self::PREPARED => '材料备齐', self::ALLOCATED => '下料', self::UPPER => '面部', self::SOLE => '底部', self::FINISH => '出货', self::CANCEL => '取消', self::WAITING => '材料计算中', ]; } }
Python
UTF-8
291
3.78125
4
[]
no_license
# Дан список чисел. Выведите все элементы списка, которые больше предыдущего # элемента.(input:1, 5, 2, 4, 3 output: 5, 4) a = input().split() for i in range(1, len(a)): if int(a[i])>int(a[i-1]): print(a[i])
Python
UTF-8
5,306
2.8125
3
[]
no_license
import subprocess import json import re from datetime import datetime from datetime import timedelta ''' PDF parser tool. https://github.com/pdfminer/pdfminer.six pip3 install pdfminer.six ''' #from tool import pdf2txt # from pdfminer.six class NKUST_Calendar: def __init__(self,file,term_year): self.res = {} self.week_startDays = None data = None try: data = self.raw_Calendar_decode(file=file) except Exception as e: print(e) print('error in raw_Calendar_decode') if data != None: self.Speculate_calendar(data,tw_year=term_year) def raw_Calendar_decode(self,file): '''file = xxx.pdf ''' process = subprocess.Popen(['pdf2txt.py', file], stdout=subprocess.PIPE) raw_pdf_text, err = process.communicate() raw_pdf_text = raw_pdf_text.decode('utf-8') raw_pdf_list = raw_pdf_text.split('\n') self.raw_list = raw_pdf_list # get office name dict for i in raw_pdf_list: if i.find('單位簡稱') > -1: unit_text = i break replace_dict = {} for unit in unit_text[unit_text.find('單位簡稱: ')+6::].replace(' ','').split('/'): replace_text,office = unit.split('-') replace_dict[replace_text] = office res = {'data':[]} for i in raw_pdf_text.split('\n'): if re.match('.{0,7}([0-9]{1,2}/[0-9]{1,2})',i) != None and i.find('單位簡稱') == -1: for k,v in replace_dict.items(): if i.find(k) > -1: break #print(v,i[i.find('(')::]) res['data'].append({'office':v,'info':i[i.find('(')::]}) return res def json_make(self,date,info,office): 'date type : datetime' week = 0 if self.week_startDays != None: week = int(((date-self.week_startDays).days)/7)+1 if week > 18: #will next term #self.week_startDays = None if date.month == 1 : week ='寒' elif date.month == 7 or date.month == 6: week ='暑' else: if week not in ['寒','暑']: week = 0 if date.month == 8: week ='暑' if (date.month == 9 or date.month ==2) and week==0: week ='預備週' if self.res.get(str(week)) != None: self.res[str(week)]['events'].append(info) # self.res[date.strftime("%Y%m%d")]['events'].append({'office':office,'events':info}) else: self.res[str(week)] = {'events':[info]} def get_json(self): replace_char = { '0':'不可能出現的周,出現表示該修了QQ', '1':'第一週', '2':'第二週', '3':'第三週', '4':'第四週', '5':'第五週', '6':'第六週', '7':'第七週', '8':'第八週', '9':'第九週', '10':'第十週', '11':'第十一週', '12':'第十二週', '13':'第十三週', '14':'第十四週', '15':'第十五週', '16':'第十六週', '17':'第十七週', '18':'第十八週', '暑':'暑', '寒':'預備週', '預備週':'預備週' } res_json = [] for k,v in self.res.items(): tmp = {'week':replace_char[k],'events':[]} for event in v['events']: tmp['events'].append(event.replace('\n','')) res_json.append(tmp) return json.dumps(res_json,ensure_ascii=False) def Speculate_calendar(self,data,tw_year=(datetime.now().year-1911)): '''data = raw_Calender_decode type: dict { data:[ {'office':...,'info':....} ... ] } tw_year hmmm 106 107.. ''' #same_year_list = ['8','9','10','11','12'] #these months are in the same term years next_year_list = ['1','2','3','4','5','6','7'] #year +1 for i in data['data']: year = tw_year+1911 info = i['info'] date_info = info[info.find('(')+1:info.find(')')] #print(date_info,i['info']) if re.match('^[0-9]{1,2}/[0-9]{1,2}',date_info) != None: 'only match (01/01 )...events_info... just single day ' date_info = re.match('^[0-9]{1,2}/[0-9]{1,2}',date_info).group(0) if date_info[0:date_info.find('/')] in next_year_list: year += 1 day = datetime.strptime('%s %s'%(year,date_info), '%Y %m/%d') if i['info'].find('開始上課') > -1: diff = timedelta(days=day.isoweekday()) self.week_startDays = day-diff info=info.replace('-',' ~ ') self.json_make(date=day,info=info,office=i['office']) if __name__ == "__main__": data = NKUST_Calendar('cal107-1.pdf',term_year=107).get_json() print(data)
Java
UTF-8
2,149
2.859375
3
[]
no_license
import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import org.imgscalr.Scalr; public class MaloWFrame { public class Panel extends JPanel { private static final long serialVersionUID = 1L; public BufferedImage img; public Panel(BufferedImage img) { this.img = img; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (img != null) { g.drawImage(img, 0, 0, this); } } @Override public Dimension getPreferredSize() { if (img != null) { return new Dimension(img.getWidth(), img.getHeight()); } return super.getPreferredSize(); } } public JFrame frame; public Panel panel; public String curImg = ""; public MaloWFrame() { this.frame = new JFrame("MaloWScreenShotShare"); this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.frame.setBounds(200, 200, 400, 400); this.frame.setLocationRelativeTo(null); this.frame.setVisible(true); this.frame.setAutoRequestFocus(false); } public void DisplayImage(String path) { if(path == "") return; this.curImg = path; try { BufferedImage img = ImageIO.read(new File(path)); img = Scalr.resize(img, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_EXACT, this.frame.getContentPane().getWidth(), this.frame.getContentPane().getHeight(), Scalr.OP_ANTIALIAS); this.frame.getContentPane().removeAll(); if(this.panel != null) { this.panel.img = null; this.panel = null; } this.panel = new Panel(img); this.frame.getContentPane().add(this.panel); this.frame.setVisible(true); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } public void ResizeImageIfNeeded() { if(this.panel != null && this.panel.img != null) { if(this.panel.img.getWidth() != this.frame.getContentPane().getWidth() || this.panel.img.getHeight() != this.frame.getContentPane().getHeight()) { this.DisplayImage(this.curImg); } } } }
Markdown
UTF-8
9,927
2.5625
3
[]
no_license
1. What do you know in SQL? 1. Tell me how you use SQL at your company? What are the queries you wrote? 1. Tell me how you used SQL at UH Energy? 1. Why can't you use Excel instead of SQL? Is there a difference? 1. What is the difference between DELETE and TRUNCATE statements? 2. What are the different subsets of SQL? 3. What do you mean by DBMS? What are its different types? 4. What do you mean by table and field in SQL? 5. What are joins in SQL? 6. What is the difference between CHAR and VARCHAR2 datatype in SQL? 7. What is a Primary key? 8. What are Constraints? 9. What is the difference between SQL and MySQL? 10. What is a Unique key? 11. What is a Foreign key? 12. What do you mean by data integrity? 13. What is the difference between clustered and non clustered index in SQL? 14. Write a SQL query to display the current date? 15. List the different type of joins? And give examples with two test tables 16. What do you mean by Denormalization? 17. What are Entities and Relationships? 18. What is an Index? 19. Explain different types of index. 20. What is Normalization and what are the advantages of it? 21. What is the difference between DROP and TRUNCATE commands? 22. Explain different types of Normalization. 23. What is ACID property in a database? 24. What do you mean by “Trigger” in SQL? 25. What are the different operators available in SQL? 26. Are NULL values same as that of zero or a blank space? 27. What is the difference between cross join and natural join? 28. What is subquery in SQL? 29. What are the different types of a subquery? 30. List the ways to get the count of records in a table? 31. Write a SQL query to find the names of employees that begin with ‘A’? 32. Write a SQL query to get the third highest salary of an employee from employee_table? 33. What is the need for group functions in SQL? 34 . What is a Relationship and what are they? 35. How can you insert NULL values in a column while inserting the data? 36. What is the main difference between ‘BETWEEN’ and ‘IN’ condition operators? 37. Why are SQL functions used? 38. What is the need of MERGE statement? 39. What do you mean by recursive stored procedure? 40. What is CLAUSE in SQL? 41. What is the difference between ‘HAVING’ CLAUSE and a ‘WHERE’ CLAUSE? 42. List the ways in which Dynamic SQL can be executed? 43. What are the various levels of constraints? 44. How can you fetch common records from two tables? 45. List some case manipulation functions in SQL? 46. What are the different set operators available in SQL? 47. What is an ALIAS command? 48. What are aggregate and scalar functions? 49. How can you fetch alternate records from a table? 50. Name the operator which is used in the query for pattern matching? 51. How can you select unique records from a table? 52. How can you fetch first 5 characters of the string? 53. What is the main difference between SQL and PL/SQL? 54. What is a View? 55. What are Views used for? 56. What is a Stored Procedure? 57. List some advantages and disadvantages of Stored Procedure? 58. List all the types of user-defined functions? 59. What do you mean by Collation? 60. What are the different types of Collation Sensitivity? 61. What are Local and Global variables? 62. What is Auto Increment in SQL? 63. What is a Datawarehouse? 64. What are the different authentication modes in SQL Server? How can it be changed? 65. What are STUFF and REPLACE function? 1. What is a Database? 5. What is a Record in a Database? 6. What is a column in a Table? 7. What is DBMS? 9. What is RDBMS? 10. What are the popular Database Management Systems in the IT Industry? 11. What is SQL? 12. What are the different types of SQL commands? 13. What are the different DDL commands in SQL? 14. What are the different DML commands in SQL? 15. What are the different DCL commands in SQL? 16. What are the different TCL commands in SQL? 18. What are all the different types of indexes? 19. What is the difference between Cluster and Non-Cluster Index? 21. What are the advantages of Views? 23. What is a query? 26. What is Synchronized Subquery? 30. What is a temp table? 32. What is the difference between Rename and Alias? 33. What is a Join? 40. Can a table contain multiple PRIMARY KEY’s? 41. What is a Composite PRIMARY KEY? 43. Can a table contain multiple FOREIGN KEY’s? 44. What is the difference between UNIQUE and PRIMARY KEY constraints? 45. What is a NULL value? 47. How to Test for NULL Values? 48. What is SQL NOT NULL constraint? 49. What is a CHECK constraint? 50. What is a DEFAULT constraint? 51. What is Normalization? 52. What are all the different Normalization? 53. What is Denormalization? 55. What is a Trigger? 56. Explain SQL Data Types? 57. What are the possible values that can be stored in a BOOLEAN data field? 58. What is the largest value that can be stored in a BYTE data field? 60. Which TCP/IP port does SQL Server run? 62. Define the SELECT INTO statement. 63. What is the difference between Delete, Truncate and Drop command? 65. What is the difference between Union and Union All command? 66. What is CLAUSE in SQL? 68. What are aggregate functions in SQL? 69. What are string functions in SQL? 70. What are user defined functions? 71. What are all types of user-defined functions? 72. What is Self-Join? Give 2 examples. 73. What is Cross-Join? Give 2 examples. 75. What are all different types of collation sensitivity? 76. How to get unique records from a table? 77. What is the command used to fetch the first 5 characters of a string? 78 How to add new Employee details in an Employee_Details table with the following details Employee_Name: John, Salary: 5500, Age: 29? 79. How to add a column ‘Salary’ to a table Employee_Details? How to change a value of the field ‘Salary’ as 7500 for an Employee_Name ‘John’ in a table Employee_Details? 82. How To Get List of All Tables From A DataBase? 83. Define SQL Delete statement. 84. Write the command to remove all Players named Sachin from the Players table. 85. How to fetch values from TestTable1 that are not in TestTable2 without using NOT keyword? 86. How to get each name only once from an employee table? 87. How to rename a column in the output of SQL query? 88. What is the order of SQL SELECT? 89. Write an SQL Query to find an Employee_Name whose Salary is equal or greater than 5000 from the below table Employee_Details. 90. Write an SQL Query to find list of Employee_Name start with ‘E’ from the below table 94. How to select all the even number records from a table? 95. How to select all the odd number records from a table? 96. What is the SQL CASE statement? Can you display the result from the below table TestTable based on the criteria M,m as M and F, f as F and Null as N and g, k, I as U 98. What will be the result of the query below? select case when null = null then 'True' else 'False' end as Result; 99. What will be the result of the query below? 100. How do you update F as M and M as F from the below table TestTable? 101. Describe SQL? 102. What is the difference between NVL function, IFNULL function, and ISNULL function? 103. What is Database Testing? 104. What are UNION queries? Give at least 2 examples. 105. What are UNION ALL queries? How do you contrast with UNION queries. Give at least 2 examples. 106. Draw Venn Diagrams for UNION, INTERSECT and EXCEPT. 107. What are the guidelines for UNION operator? 108. What are Intersect Queries? Give at least 2 examples. 109. What are Except queries? Give at least 2 examples. 110. What are the different syntax of subqueries? 111. What is a correlated subquery? Give one example. 111. What is a self- contained subquery? 111. What are the properties of a correlated subquery? 111. What is an APPLY operator? 111. How is an APPLY operator different from a Join? 111. What are the types of APPLY operator? Explain with an example for each type in detail. 111. What is Cross Apply? 111. What is Outer Apply? 111. SQL is ____________ not ____________. 111. What are entities in SQL? 111. What is a schema? 111. What is a syntax for fully -qualified name? 111. What is the SQL processing order of a query? 111. What are the different data types in SQL? 111. What is an Implicit conversion? Give at least 2 examples. 111. What is an Explicit conversion? 111. List out and explain the conversion functions in SQL 111. Explain COALESCE with an example 111. Describe ANSI behavior of NULLs 111. State and explain the 3 important NULL functions 111. What are Table Variables? Give 2 examples. 111. What are table valued functions? Give 2 examples. 111. What are derived tables? Give 2 examples. 111. What are derived table guidelines? Give 2 examples. 111. What are common table expressions? Give 2 examples. 111. What are CTEs Recursion? 111. Write about ORDER BY Clause. What are the two main important yet subtle points? 111. How do you limit sorted results in SQL? 111. How do you page through reults in ORDER BY? 111. What are the predicated used in the WHERE clause? 111. What is GROUPING SETS? Write down it's syntax and explain with an example. 111. Explain ROLLUP and CUBE with an example. 111. How to Identify Grouping in results in SQL? 111. How do you pivot data in SQL? Give an example. 111. How do you unpivot data in SQL? Give an example. 111. Describe Batches in SQL. 111. What are variables in SQL? 111. What is Conditional Branching? 111. How do you perform looping in SQL? 111. Write a stored procedure and execute it 111. Explain scalar functions in SQL. 111. What are Built-in functions in SQL. 111. What are the Logical functions in SQL? 111. What is a window function? 111. Explain the types of Ranking functions with examples. 111. What are aggregate functions? 111. Explain Grouping with Group By. 111. Explain the process flow of WHERE, HAVING, GROUP BY. 111. Give a list of all function types and explain each function from each type.
PHP
UTF-8
1,918
2.515625
3
[]
no_license
<?php /* * 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. */ /** * Description of Invoice * * @author DABBY(3pleMinds) */ require_once 'Connection.php'; require_once '../core/Core.php'; class PreformerInvoice { private $invoiceNumber; private $jobNumber; private $customer; private $labour; private $invoiceStatus; private $stockRows; private $materials; public function __construct($materials) { $this->labour = 0; $this->stockRows = ""; $this->initInvoice(); $this->materials = $materials; } private function initInvoice() { $core = new Core(); $this->invoiceNumber = $core->generatePreformerInvoiceNumber(); $this->jobNumber = $core->generateCmJobId(); $details = $core->getAllStockDetails($this->materials); $this->stockRows.='<tr class="item-row" id="item0">' . '<td>1</td>' . '<td class="item-name"><textarea data-role="none" class="item_name" >'.$details['part_number'].'</textarea></td>' . '<td class="description"><textarea disabled data-role="none" class="item_description">'.$details['description'].'</textarea></td>' . '<td><span disabled class="cost" data-role="none" id="unitCost1"><del>N</del>'.$details['price'].'</span></td>' . '<td><textarea disabled class="qty" data-role="none" id="quantity1">1</textarea></td>' . '<td><span class="price" >0.00</span></td></tr>'; } //put your code here public function genrateInvoice(){ return array("invoicenumber"=>$this->invoiceNumber,"jobid"=>$this->jobNumber,"customer"=>$this->customer,"stockRows"=>$this->stockRows,"labour"=>$this->labour); } public function checkInvoiceStatus(){ return $this->invoiceStatus; } }
Python
UTF-8
644
3.890625
4
[]
no_license
import random import sys randnumber=random.randint(1,10) #print(randnumber) print('What is your name') name=input() print('Hi',name,'Welcome to my guessing game. I am thinking of a number between 1 to 10. Take a guess') for i in range (0,5): number=int(input()) if number == randnumber: print('Good job',name,'you guessed the number in',i+1,'tries') sys.exit() elif number >randnumber: print('number too high') i=i+1 elif number < randnumber: print('number too low') i=i+1 print('Sorry',name,'you have exhausted your 5 tries') print('my guess is',randnumber)
C++
UTF-8
2,095
3
3
[]
no_license
// g++ -std=c++11 solucionador.cpp -o solucionador #include "tabuleiro.hpp" #include <iostream> #include <cassert> Tabuleiro jogo; bool validarEDefinir(unsigned short valor, unsigned short i, unsigned short j) { jogo.setValorQuadrado(valor, i, j); // força a cor if ( jogo.regrasValidasPara(valor, i, j) ) return true; // apaga o valor do quadrado e retorna 'false' return !jogo.setValorQuadrado(AUSENCIA_DE_VALOR, i, j); } bool solucionar(unsigned short i, unsigned short j) { if (i == jogo.tamanho) return true; // já chegou no quadrado do canto inferior direito if (j == jogo.tamanho) return solucionar(i+1, 0); // próxima linha if(jogo.matriz[i][j].valor != AUSENCIA_DE_VALOR) return solucionar(i, j+1); // próximo quadrado for (unsigned short cor=1; cor <= jogo.tamanho; ++cor) { if ( validarEDefinir(cor, i,j) && solucionar(i, j+1) ) return true; } // apaga o valor do quadrado e retorna 'false' return !jogo.setValorQuadrado(AUSENCIA_DE_VALOR, i, j); } int main(void) { unsigned short N; // tamanho do tabuleiro unsigned short R; // quantidade de restrições cin >> N; jogo = Tabuleiro(N); // leitura quadro-por-quadro dos valores do tabuleiro for (unsigned short i=0; i < N; i++) { for (unsigned short j=0; j < N; j++) { unsigned short valor; cin >> valor; jogo.setValorQuadrado(valor, i, j); } } // leitura das restrições for (cin >> R; R-- > 0; ) { unsigned short ai,aj, bi,bj; char operador; cin >> ai; --ai; cin >> aj; --aj; cin >> operador; cin >> bi; --bi; cin >> bj; --bj; Quadrado* quadradoA = &jogo.matriz[ai][aj]; Quadrado* quadradoB = &jogo.matriz[bi][bj]; if (operador == '>') { quadradoA->menores.push_back(quadradoB); quadradoB->maiores.push_back(quadradoA); } else { quadradoA->maiores.push_back(quadradoB); quadradoB->menores.push_back(quadradoA); } } #ifdef DEBUG jogo.mostrar(true); assert( solucionar(0, 0) == true ); #else solucionar(0, 0); jogo.mostrar(); #endif }
C#
UTF-8
8,296
3.0625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace Ropes { class Program { static void Main(string[] args) { Console.WriteLine(); Console.WriteLine("DELETE FROM MIDDLE"); string y = "01234567890123456789012345678901234567890123456789012345678901234578901234567890123456789012345678901234567890123456789"; string z = "0123456789"; Rope R = new Rope(z); R = R.Delete(1, 9); R.Print(); R = new Rope(z); R = R.Delete(2, 8); R.Print(); R = new Rope(z); R = R.Delete(3, 7); R.Print(); R = new Rope(z); R = R.Delete(4, 6); R.Print(); R = new Rope(z); R = R.Delete(5, 5); R.Print(); R = new Rope(y); R.Print(); while (R.Root.Length > 0) { if (R.Root.Length / 2 -4 < 0) { R = R.Delete(0, R.Root.Length); R.Print(); } else { R = R.Delete((R.Root.Length / 2)-4 , R.Root.Length / 2 ); R.Print(); } } Console.WriteLine(); Console.WriteLine("DELETE FROM END"); R = new Rope(y); while (R.Root.Length > 0) { if (R.Root.Length / 2 - 1 < 0) { R = R.Delete(0, R.Root.Length); R.Print(); } else { R = R.Delete(R.Root.Length -1, R.Root.Length); R.Print(); } } Console.WriteLine(); Console.WriteLine("DELETE FROM START"); R = new Rope(y); while (R.Root.Length > 0) { R = R.Delete(0, 1); R.Print(); } //Part B: //Create string: string x = "0123456789"; Console.WriteLine("STRING TEST"); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 2000; i++) { x += "0123456789"; } //delete everything from the string while (x.Length > 0) { if ((x.Length / 2) - 10 >= 0) { x = x.Remove((x.Length / 2) - 10, 20); } else { x = x.Remove(0, x.Length); } } sw.Stop(); Console.WriteLine("Elapsed={0}", sw.ElapsedMilliseconds); Console.WriteLine(); Console.WriteLine("ROPE TEST"); x = "0123456789"; Stopwatch sw1 = new Stopwatch(); sw1.Start(); Rope R1 = new Rope(x); Rope R2 = new Rope(x); for (int i = 0; i < 2000; i++) { R1 = R1.Insert(R1,x,R1.Root.Length); } while (R1.Root.Length > 0) { if (R1.Root.Length / 2 - 5 < 0) { R1 = R1.Delete(0, R1.Root.Length); } else { R1 = R1.Delete(R1.Root.Length / 2 -5 , R1.Root.Length / 2 + 5); } } sw1.Stop(); Console.WriteLine("Elapsed={0}", sw1.ElapsedMilliseconds); Console.WriteLine(); Console.WriteLine("STRING TEST"); sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 5000; i++) { x += "0123456789"; } //delete everything from the string while (x.Length > 0) { if ((x.Length / 2) - 10 >= 0) { x = x.Remove((x.Length / 2) - 10, 20); } else { x = x.Remove(0, x.Length); } } sw.Stop(); Console.WriteLine("Elapsed={0}", sw.ElapsedMilliseconds); Console.WriteLine(); Console.WriteLine("ROPE TEST"); x = "0123456789"; sw1 = new Stopwatch(); sw1.Start(); R1 = new Rope(x); R2 = new Rope(x); for (int i = 0; i < 5000; i++) { R1 = R1.Insert(R1, x, R1.Root.Length); } while (R1.Root.Length > 0) { if (R1.Root.Length / 2 - 5 < 0) { R1 = R1.Delete(0, R1.Root.Length); } else { R1 = R1.Delete(R1.Root.Length / 2 - 5, R1.Root.Length / 2 + 5); } } sw1.Stop(); Console.WriteLine("Elapsed={0}", sw1.ElapsedMilliseconds); Console.WriteLine(); Console.WriteLine("STRING TEST"); sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 10000; i++) { x += "0123456789"; } //delete everything from the string while (x.Length > 0) { if ((x.Length / 2) - 10 >= 0) { x = x.Remove((x.Length / 2) - 10, 20); } else { x = x.Remove(0, x.Length); } } sw.Stop(); Console.WriteLine("Elapsed={0}", sw.ElapsedMilliseconds); Console.WriteLine(); Console.WriteLine("ROPE TEST"); x = "0123456789"; sw1 = new Stopwatch(); sw1.Start(); R1 = new Rope(x); R2 = new Rope(x); for (int i = 0; i < 10000; i++) { R1 = R1.Insert(R1, x, R1.Root.Length); } while (R1.Root.Length > 0) { if (R1.Root.Length / 2 - 5 < 0) { R1 = R1.Delete(0, R1.Root.Length); } else { R1 = R1.Delete(R1.Root.Length / 2 - 5, R1.Root.Length / 2 + 5); } } sw1.Stop(); Console.WriteLine("Elapsed={0}", sw1.ElapsedMilliseconds); /* string x = "happy bear banana 123yjgyjhfyhghcghchhkjjnilfjbihosdfojsdhsdjoxgdjljdfjmbjksvjdxcvjksdjkxvsnkdzxcnxznvklsdvnkdfmfgrlmflfg;lfdlkmfglkghlgmddfflkdlkjgrsflmkfzdlmk;fdmlfdlk;l;flkmzsgflmkzvflmkfzlmkfzslsdflmsdzflmksfzmlkdsfmlklmkflmvffv4567897654321234567841012345678901234567890123456789539876543231234564567876987654345678765432104654rygrdyv54rcegdvdfhgaecdsfsnhbfgsdhbtrdfxgfvfdcgvdssgvkdfnbgvjshdbzvbguskrjhfe4ruethfue4rhguisgr"; Rope R1 = new Rope(x); Console.WriteLine(R1.GetLength()); R1.Print(); Console.WriteLine(); Console.WriteLine("DELETE TEST"); Console.WriteLine(); R1 = new Rope(x); while (R1.Root.Length > 0) { R1 = R1.Delete2((R1.GetLength()/2)-10, (R1.GetLength()/2)+10); Console.WriteLine(); R1.Print(); } Console.WriteLine("INSERT AT EVERY INDEX"); Console.WriteLine(); x="Tesing insert at every index"; R1 = new Rope(x); for (int i = 0; i < R1.GetLength()-2; i++) { R1 = new Rope(x); R1 = R1.Insert(R1, "FIN", i); R1.Print(); } R1 = new Rope("Please"); R1= R1.Insert(R1," Work", 6); R1.Print(); //Console.WriteLine(); /* for (int i = 0; i < 20; i++) { R1 = R1.Delete2(R1.Root.Length/2, (R1.Root.Length/2)+1); R1.Print(); } Console.WriteLine(); R1 = new Rope(x); for (int i = 0; i < 10; i++) { R1 = R1.Delete2(R1.Root.Length - 5, R1.Root.Length); R1.Print(); } /* R1 = R1.Delete2(6, 18); R1.Print(); Console.WriteLine("test"); R1 = R1.Delete(8, 12); R1.Print(); //R1.Insert("Some ", 1); R1 = R1.Split2(20).Item1; R1.Print(); R1 = R1.Split2(18).Item1; R1.Print(); R1 = R1.Split2(15).Item1; R1.Print(); R1 = R1.Split2(12).Item1; R1.Print(); /*for (int i = 0; i < R1.GetLength() - 1; i++) { //R1 = new Rope(x); R1 = R1.Split2(i).Item2; R1.Print(); } Console.WriteLine("INSERT AT EVERY INDEX"); Console.WriteLine(); Rope R1 = new Rope(x); for (int i = 0; i < 86; i++) { R1 = new Rope(x); R1 = R1.Insert(R1, "FIN", i); R1.Print(); } Console.WriteLine("DELETE TEST"); Console.WriteLine(); R1 = new Rope(x); for (int i = 0; i < 10; i++) { R1 = R1.Delete(0, 5); R1.Print(); } R1 = new Rope(x); for (int i = 0; i < 10; i++) { R1 = R1.Delete(R1.Root.Length - 5, R1.Root.Length); R1.Print(); } R1 = new Rope(x); for (int i = 0; i < 6; i++) { if (R1.Root.Length / 2 - 10 < 0) { R1 = R1.Delete(0, R1.Root.Length); R1.Print(); } else { R1 = R1.Delete(R1.Root.Length / 2 - 10, R1.Root.Length / 2 + 10); R1.Print(); } } */ Console.Read(); } } }
C++
UTF-8
801
2.796875
3
[]
no_license
// // Step.hpp // day01 // // Created by fangyukui on 2018/4/19. // Copyright © 2018年 fangyukui. All rights reserved. // #pragma once #include <iostream> using namespace std; class Step_Parent{ protected: int a; public: Step_Parent(int a){ this->a = a; } virtual void description(){ cout << "父类描述" << endl; } virtual ~Step_Parent(){ } }; class Step_Chird:public Step_Parent{ private: int b; int c; public: Step_Chird(int a,int b):Step_Parent(a){ this->b = b; this->a = a; } Step_Chird(int a):Step_Parent(a){ } virtual void description(){ cout << "子类描述" << endl; } virtual ~Step_Chird(){ } };
Java
UTF-8
2,350
2.578125
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
/* Copyright (c) 2020 W.T.J. Riezebos * * 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 net.riezebos.thoth.beans; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class Book implements Comparable<Book> { private String name; private String path; private String folder; private String title; private Map<String, String> metaTags = new HashMap<String, String>(); public Book(String name, String path) { super(); setName(name); setPath(path); setFolder(path); setTitle(name); } private void setFolder(String path) { int idx = path.replaceAll("\\\\", "/").lastIndexOf("/"); if (idx != -1) path = path.substring(0, idx); folder = path; } private void setTitle(String name) { title = name; int idx = title.lastIndexOf("."); if (idx != -1) title = title.substring(0, idx); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getTitle() { return title; } public String getFolder() { return folder; } @Override public int compareTo(Book o) { return getName().compareTo(o.getName()); } public void setMetaTags(Map<String, String> metaTags) { this.metaTags = metaTags; } public Map<String, String> getMetaTags() { return metaTags; } public List<String> getMetaTagKeys() { List<String> keys = new ArrayList<String>(metaTags.keySet()); Collections.sort(keys); return keys; } public String getMetaTag(String key) { return getMetaTags().get(key); } @Override public String toString() { return getPath(); } }
C#
UTF-8
820
2.515625
3
[]
no_license
 using Sandbox; using Sandbox.UI; using Sandbox.UI.Construct; using System; using System.Linq; using System.Threading.Tasks; using System.Collections.Generic; using System.Reflection; namespace Sandbox.UI { public class Form : Panel { public object Bound; public Form() { AddClass( "form" ); } public void BindObject( object obj ) { Bound = obj; foreach ( var property in Reflection.GetProperties( obj ) ) { AddRow( property ); } } public void AddRow( Property property ) { var row = Add.Panel( "form-row" ); var title = row.Add.Panel( "form-label" ); title.Add.Label( property.Name ); var value = row.Add.Panel( "form-value" ); //value.Add.Label( $"{property.Value}" ); var control = value.Add.TextEntry( "" ); control.DataBind = property; } } }
Python
UTF-8
3,117
3.453125
3
[]
no_license
# -*- coding: utf-8 -*- from __future__ import unicode_literals import sys # Step 1 - read input into data sctructure class Vessel: def __init__(self, vesselType, vesselWidth): self.vesselType = vesselType self.vesselWidth = vesselWidth filename = sys.argv[1] print("reading " + filename + "...") lineNumber = 0 vessels = [] for line in open(filename, 'r'): if lineNumber < 4: # first 4 lines (indexes 0, 1, 2, 3) are header info lineNumber += 1 continue lineSplitIntoKVPairs = line.split(' ') vesselTypeString = lineSplitIntoKVPairs[7].split(':')[1][:1] vesselWidth = lineSplitIntoKVPairs[8].split(':')[1] print "Line " + str(lineNumber + 1) + " type: " + vesselTypeString print "Line " + str(lineNumber + 1) + " width: " + vesselWidth print "\n" newVessel = Vessel(vesselType=vesselTypeString, vesselWidth=float(vesselWidth)) vessels.append(newVessel) lineNumber += 1 print str(len(vessels)) + " vessels read" print "\n" # Step 2 - calculations # Get the average of the 6 largest veins. # Get the average of the 6 largest arteries. # Divide the average of the veins, by the arteries. # If there are more than 6 veins and/or arteries, exclude the smallest ones from the set. # If there is less than 6 veins/arteries (say only 5 veins and 7 arteries), then get the average of the lesser vessels for both (so average of 5 veins and 5 arteries) # Ideally, if possible, in the above instance, also get the average if you include 6 arteries arteryWidths = [] veinWidths = [] for v in vessels: if (v.vesselType == "V"): veinWidths.append(v.vesselWidth) else: arteryWidths.append(v.vesselWidth) sortedArteryWidths = list(reversed(sorted(arteryWidths))) sortedVeinWidths = list(reversed(sorted(veinWidths))) print "sortedArteryWidths: " + str(sortedArteryWidths) print "sortedVeinWidths: " + str(sortedVeinWidths) print "\n" minSampleSize = min(len(sortedVeinWidths), len(sortedArteryWidths)) if minSampleSize < 6: print "Min sample size is " + str(minSampleSize) splicedVeinSample = sortedVeinWidths[:minSampleSize] splicedArterySample = sortedArteryWidths[:minSampleSize] minSampleAverageOfVeins = reduce(lambda x, y: x + y, splicedVeinSample) / minSampleSize minSampleAverageOfArteries = reduce(lambda x, y: x + y, splicedArterySample) / minSampleSize print "Average of " + str(minSampleSize) + " (min sample size) largest veins:" + str(minSampleAverageOfVeins) print "Average of " + str(minSampleSize) + " (min sample size) largest arteries:" + str(minSampleAverageOfArteries) print "\n" if len(sortedVeinWidths) > 5: splicedVeinSample = sortedVeinWidths[:6] averageOfSixLargestVeins = reduce(lambda x, y: x + y, splicedVeinSample) / 6 print "Average of 6 largest arteries: " + str(averageOfSixLargestVeins) if len(sortedArteryWidths) > 5: splicedArterySample = sortedArteryWidths[:6] averageOfSixLargestArteries = reduce(lambda x, y: x + y, splicedArterySample) / 6 print "Average of 6 largest arteries: " + str(averageOfSixLargestArteries) print "=================" print "DONE!" print "================="
Shell
UTF-8
1,174
4.03125
4
[]
no_license
#!/bin/sh die () { echo >&2 "$@" exit 1 } # Validate arguments [ "$#" -ge 1 ] || die "Usage: $0 <path-to-srt>" [ -e "$1" ] || die "File $1 does not exist." # Find the associated MKV file and make sure it exists fullfile="$1" srtfile="${fullfile##*/}" mkvfile="${srtfile%.*}.mkv" tmpfile="${srtfile%.*}-subs.mkv" path="${fullfile%/*}" [ -e "$path/$mkvfile" ] || die "Video file $mkvfile does not exist." # Make sure that docker is installed docker -v >/dev/null 2>&1 || die "Docker is not installed" # Run a docker container to mkvmerge the subtitles in uid="$(id -u $USER)" gid="$(id -g $USER)" docker run --name "mkvmerge-subs" -v "$path":/source -w /source -it moul/mkvtoolnix /bin/bash -c "mkvmerge -o /source/'$tmpfile' '$mkvfile' '$srtfile'; chown '$uid'.'$gid' /source/'$tmpfile'" docker rm "mkvmerge-subs" # Make sure that the merged file exists if [ -e "$path/$tmpfile" ]; then # Remove the original mkvfile and replace it with the merged file rm "$path/$mkvfile" mv "$path/$tmpfile" "$path/$mkvfile" echo "Succesfully merged subtitles from $srtfile into $mkvfile" else echo "Merging subtitles from $srtfile into $mkvfile failed!" fi
Python
UTF-8
5,623
2.671875
3
[]
no_license
from fake_useragent import UserAgent from bs4 import BeautifulSoup as BS from dateutil.parser import parse import requests as rq import datetime import time import json import os, glob from copy import deepcopy CATEGORIES = ['정치', '경제', '사회', '생활', '세계', '과학'] CATEGORIES_ENGLISH = ['politics', 'economy', 'society', 'living', 'world', 'science'] def save_json_contents(dir_path, date, json_contents) : if (os.path.exists(dir_path)) : pass else : os.makedirs(dir_path) with open(dir_path + "/" + date + ".json", "w", encoding = 'utf-8') as fp : json_val = json.dumps(json_contents, indent = 4, ensure_ascii = False) fp.write(json_val) def main() : global CATEGORIES_KOREAN global CATEGORIES_ENGLISH # fake userAgent 생성 ua = UserAgent() fake_headers = {"User-Agent" : ua.google} path = "./naver_news/crawling_links/" if (os.path.exists(path)) : # 경로에 존재하는 모든 json 파일들을 읽어옴 link_files = glob.glob(path + "*.json") link_files.reverse() else : print("[ {} ] ==> 해당 경로가 존재하지 않습니다.".format(path)) quit() contents_path = "./naver_news/news_contents" if (os.path.exists(contents_path)) : print("[ {} ] ==> 해당 경로가 존재합니다.".format(contents_path)) pass else : print("[ {} ] ==> 해당 경로가 존재하지 않습니다.".format(contents_path)) for category in CATEGORIES_ENGLISH : os.makedirs("{}./{}".format(contents_path, category)) while True : try : start_date = int(input("시작 날짜(연도월일 8글자 ex : 20160425) : ")) end_date = int(input("마지막 날짜(연도월일 8글자 ex : 20160422) : ")) break except ValueError as e : print("날짜를 다시 입력해주세요") continue # 파일명에서 날짜만 추출 date_files = [file[28 : 45] for file in link_files] date_files = [[int(date_range[ : 8]), int(date_range[9 : ])] for date_range in date_files] from_ = -1; to_ = -1; for idx, lists in enumerate(date_files) : if (lists[0] <= start_date) and (start_date <= lists[1]) : from_ = idx if (lists[0] <= end_date) and (end_date <= lists[1]) : to_ = idx if (from_ != -1 and to_ != -1) : break if (from_ == -1 or to_ == -1) : print("해당 날짜를 찾을 수 없습니다.") quit() link_files = link_files[from_ : to_ + 1] print("\n시작 : ", link_files[0], " 끝 : ", link_files[-1]) start_date = parse(str(start_date)) contents = {} for file in link_files : with open(file, "r", encoding = 'utf-8') as fp : data = fp.read() json_data = json.loads(data) for day in range(7) : date_str = start_date.strftime('%Y%m%d') print("\n {}".format(date_str)) # 파일에 해당 날짜가 존재하면 if date_str in list(json_data.keys()) : date_links = json_data[date_str] # 정치, 경제, 사회, 생활, 세계, 과학 for index in range(6) : print("\n", CATEGORIES[index]) category_links = date_links[CATEGORIES[index]] dir_path = contents_path + "/{}".format(CATEGORIES_ENGLISH[index]) temp = {} for idx, news_info in enumerate(category_links) : title, link = news_info[0], news_info[1] temp['title'] = title temp['link'] = link time.sleep(1) news_res = rq.get(link, headers = fake_headers) soup = BS(news_res.content, 'lxml') [s.extract() for s in soup(['script', 'span', 'a', 'h4'])] try : texts = soup.find(id = 'articleBodyContents') article = texts.get_text().lstrip() temp['original'] = article contents[idx] = deepcopy(temp) except AttributeError as e : try : texts = soup.find(id = 'articeBody') article = texts.get_text().lstrip() temp['original'] = article contents[idx] = deepcopy(temp) except AttributeError as e : temp['original'] = u"본문을 찾을 수 없습니다." contents[idx] = deepcopy(temp) save_json_contents(dir_path, date_str, contents) contents.clear() start_date -= datetime.timedelta(days = 1) else : break if __name__ == "__main__" : main()
Java
UTF-8
21,451
2.5625
3
[ "MIT" ]
permissive
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package android.support.v4.util; public final class CircularArray { public CircularArray() { this(8); // 0 0:aload_0 // 1 1:bipush 8 // 2 3:invokespecial #17 <Method void CircularArray(int)> // 3 6:return } public CircularArray(int i) { // 0 0:aload_0 // 1 1:invokespecial #20 <Method void Object()> if(i < 1) //* 2 4:iload_1 //* 3 5:iconst_1 //* 4 6:icmpge 19 throw new IllegalArgumentException("capacity must be >= 1"); // 5 9:new #22 <Class IllegalArgumentException> // 6 12:dup // 7 13:ldc1 #24 <String "capacity must be >= 1"> // 8 15:invokespecial #27 <Method void IllegalArgumentException(String)> // 9 18:athrow if(i > 0x40000000) //* 10 19:iload_1 //* 11 20:ldc1 #28 <Int 0x40000000> //* 12 22:icmple 35 throw new IllegalArgumentException("capacity must be <= 2^30"); // 13 25:new #22 <Class IllegalArgumentException> // 14 28:dup // 15 29:ldc1 #30 <String "capacity must be <= 2^30"> // 16 31:invokespecial #27 <Method void IllegalArgumentException(String)> // 17 34:athrow if(Integer.bitCount(i) != 1) //* 18 35:iload_1 //* 19 36:invokestatic #36 <Method int Integer.bitCount(int)> //* 20 39:iconst_1 //* 21 40:icmpeq 71 i = Integer.highestOneBit(i - 1) << 1; // 22 43:iload_1 // 23 44:iconst_1 // 24 45:isub // 25 46:invokestatic #39 <Method int Integer.highestOneBit(int)> // 26 49:iconst_1 // 27 50:ishl // 28 51:istore_1 mCapacityBitmask = i - 1; // 29 52:aload_0 // 30 53:iload_1 // 31 54:iconst_1 // 32 55:isub // 33 56:putfield #41 <Field int mCapacityBitmask> mElements = (Object[])new Object[i]; // 34 59:aload_0 // 35 60:iload_1 // 36 61:anewarray Object[] // 37 64:checkcast #42 <Class Object[]> // 38 67:putfield #44 <Field Object[] mElements> // 39 70:return //* 40 71:goto 52 } private void doubleCapacity() { int i = mElements.length; // 0 0:aload_0 // 1 1:getfield #44 <Field Object[] mElements> // 2 4:arraylength // 3 5:istore_1 int j = i - mHead; // 4 6:iload_1 // 5 7:aload_0 // 6 8:getfield #47 <Field int mHead> // 7 11:isub // 8 12:istore_2 int k = i << 1; // 9 13:iload_1 // 10 14:iconst_1 // 11 15:ishl // 12 16:istore_3 if(k < 0) //* 13 17:iload_3 //* 14 18:ifge 31 { throw new RuntimeException("Max array capacity exceeded"); // 15 21:new #49 <Class RuntimeException> // 16 24:dup // 17 25:ldc1 #51 <String "Max array capacity exceeded"> // 18 27:invokespecial #52 <Method void RuntimeException(String)> // 19 30:athrow } else { Object aobj[] = new Object[k]; // 20 31:iload_3 // 21 32:anewarray Object[] // 22 35:astore 4 System.arraycopy(((Object) (mElements)), mHead, ((Object) (aobj)), 0, j); // 23 37:aload_0 // 24 38:getfield #44 <Field Object[] mElements> // 25 41:aload_0 // 26 42:getfield #47 <Field int mHead> // 27 45:aload 4 // 28 47:iconst_0 // 29 48:iload_2 // 30 49:invokestatic #58 <Method void System.arraycopy(Object, int, Object, int, int)> System.arraycopy(((Object) (mElements)), 0, ((Object) (aobj)), j, mHead); // 31 52:aload_0 // 32 53:getfield #44 <Field Object[] mElements> // 33 56:iconst_0 // 34 57:aload 4 // 35 59:iload_2 // 36 60:aload_0 // 37 61:getfield #47 <Field int mHead> // 38 64:invokestatic #58 <Method void System.arraycopy(Object, int, Object, int, int)> mElements = (Object[])aobj; // 39 67:aload_0 // 40 68:aload 4 // 41 70:checkcast #42 <Class Object[]> // 42 73:putfield #44 <Field Object[] mElements> mHead = 0; // 43 76:aload_0 // 44 77:iconst_0 // 45 78:putfield #47 <Field int mHead> mTail = i; // 46 81:aload_0 // 47 82:iload_1 // 48 83:putfield #60 <Field int mTail> mCapacityBitmask = k - 1; // 49 86:aload_0 // 50 87:iload_3 // 51 88:iconst_1 // 52 89:isub // 53 90:putfield #41 <Field int mCapacityBitmask> return; // 54 93:return } } public void addFirst(Object obj) { mHead = mHead - 1 & mCapacityBitmask; // 0 0:aload_0 // 1 1:aload_0 // 2 2:getfield #47 <Field int mHead> // 3 5:iconst_1 // 4 6:isub // 5 7:aload_0 // 6 8:getfield #41 <Field int mCapacityBitmask> // 7 11:iand // 8 12:putfield #47 <Field int mHead> mElements[mHead] = obj; // 9 15:aload_0 // 10 16:getfield #44 <Field Object[] mElements> // 11 19:aload_0 // 12 20:getfield #47 <Field int mHead> // 13 23:aload_1 // 14 24:aastore if(mHead == mTail) //* 15 25:aload_0 //* 16 26:getfield #47 <Field int mHead> //* 17 29:aload_0 //* 18 30:getfield #60 <Field int mTail> //* 19 33:icmpne 40 doubleCapacity(); // 20 36:aload_0 // 21 37:invokespecial #64 <Method void doubleCapacity()> // 22 40:return } public void addLast(Object obj) { mElements[mTail] = obj; // 0 0:aload_0 // 1 1:getfield #44 <Field Object[] mElements> // 2 4:aload_0 // 3 5:getfield #60 <Field int mTail> // 4 8:aload_1 // 5 9:aastore mTail = mTail + 1 & mCapacityBitmask; // 6 10:aload_0 // 7 11:aload_0 // 8 12:getfield #60 <Field int mTail> // 9 15:iconst_1 // 10 16:iadd // 11 17:aload_0 // 12 18:getfield #41 <Field int mCapacityBitmask> // 13 21:iand // 14 22:putfield #60 <Field int mTail> if(mTail == mHead) //* 15 25:aload_0 //* 16 26:getfield #60 <Field int mTail> //* 17 29:aload_0 //* 18 30:getfield #47 <Field int mHead> //* 19 33:icmpne 40 doubleCapacity(); // 20 36:aload_0 // 21 37:invokespecial #64 <Method void doubleCapacity()> // 22 40:return } public void clear() { removeFromStart(size()); // 0 0:aload_0 // 1 1:aload_0 // 2 2:invokevirtual #72 <Method int size()> // 3 5:invokevirtual #75 <Method void removeFromStart(int)> // 4 8:return } public Object get(int i) { if(i < 0 || i >= size()) //* 0 0:iload_1 //* 1 1:iflt 12 //* 2 4:iload_1 //* 3 5:aload_0 //* 4 6:invokevirtual #72 <Method int size()> //* 5 9:icmplt 20 throw new ArrayIndexOutOfBoundsException(); // 6 12:new #79 <Class ArrayIndexOutOfBoundsException> // 7 15:dup // 8 16:invokespecial #80 <Method void ArrayIndexOutOfBoundsException()> // 9 19:athrow else return mElements[mHead + i & mCapacityBitmask]; // 10 20:aload_0 // 11 21:getfield #44 <Field Object[] mElements> // 12 24:aload_0 // 13 25:getfield #47 <Field int mHead> // 14 28:iload_1 // 15 29:iadd // 16 30:aload_0 // 17 31:getfield #41 <Field int mCapacityBitmask> // 18 34:iand // 19 35:aaload // 20 36:areturn } public Object getFirst() { if(mHead == mTail) //* 0 0:aload_0 //* 1 1:getfield #47 <Field int mHead> //* 2 4:aload_0 //* 3 5:getfield #60 <Field int mTail> //* 4 8:icmpne 19 throw new ArrayIndexOutOfBoundsException(); // 5 11:new #79 <Class ArrayIndexOutOfBoundsException> // 6 14:dup // 7 15:invokespecial #80 <Method void ArrayIndexOutOfBoundsException()> // 8 18:athrow else return mElements[mHead]; // 9 19:aload_0 // 10 20:getfield #44 <Field Object[] mElements> // 11 23:aload_0 // 12 24:getfield #47 <Field int mHead> // 13 27:aaload // 14 28:areturn } public Object getLast() { if(mHead == mTail) //* 0 0:aload_0 //* 1 1:getfield #47 <Field int mHead> //* 2 4:aload_0 //* 3 5:getfield #60 <Field int mTail> //* 4 8:icmpne 19 throw new ArrayIndexOutOfBoundsException(); // 5 11:new #79 <Class ArrayIndexOutOfBoundsException> // 6 14:dup // 7 15:invokespecial #80 <Method void ArrayIndexOutOfBoundsException()> // 8 18:athrow else return mElements[mTail - 1 & mCapacityBitmask]; // 9 19:aload_0 // 10 20:getfield #44 <Field Object[] mElements> // 11 23:aload_0 // 12 24:getfield #60 <Field int mTail> // 13 27:iconst_1 // 14 28:isub // 15 29:aload_0 // 16 30:getfield #41 <Field int mCapacityBitmask> // 17 33:iand // 18 34:aaload // 19 35:areturn } public boolean isEmpty() { return mHead == mTail; // 0 0:aload_0 // 1 1:getfield #47 <Field int mHead> // 2 4:aload_0 // 3 5:getfield #60 <Field int mTail> // 4 8:icmpne 13 // 5 11:iconst_1 // 6 12:ireturn // 7 13:iconst_0 // 8 14:ireturn } public Object popFirst() { if(mHead == mTail) //* 0 0:aload_0 //* 1 1:getfield #47 <Field int mHead> //* 2 4:aload_0 //* 3 5:getfield #60 <Field int mTail> //* 4 8:icmpne 19 { throw new ArrayIndexOutOfBoundsException(); // 5 11:new #79 <Class ArrayIndexOutOfBoundsException> // 6 14:dup // 7 15:invokespecial #80 <Method void ArrayIndexOutOfBoundsException()> // 8 18:athrow } else { Object obj = mElements[mHead]; // 9 19:aload_0 // 10 20:getfield #44 <Field Object[] mElements> // 11 23:aload_0 // 12 24:getfield #47 <Field int mHead> // 13 27:aaload // 14 28:astore_1 mElements[mHead] = null; // 15 29:aload_0 // 16 30:getfield #44 <Field Object[] mElements> // 17 33:aload_0 // 18 34:getfield #47 <Field int mHead> // 19 37:aconst_null // 20 38:aastore mHead = mHead + 1 & mCapacityBitmask; // 21 39:aload_0 // 22 40:aload_0 // 23 41:getfield #47 <Field int mHead> // 24 44:iconst_1 // 25 45:iadd // 26 46:aload_0 // 27 47:getfield #41 <Field int mCapacityBitmask> // 28 50:iand // 29 51:putfield #47 <Field int mHead> return obj; // 30 54:aload_1 // 31 55:areturn } } public Object popLast() { if(mHead == mTail) //* 0 0:aload_0 //* 1 1:getfield #47 <Field int mHead> //* 2 4:aload_0 //* 3 5:getfield #60 <Field int mTail> //* 4 8:icmpne 19 { throw new ArrayIndexOutOfBoundsException(); // 5 11:new #79 <Class ArrayIndexOutOfBoundsException> // 6 14:dup // 7 15:invokespecial #80 <Method void ArrayIndexOutOfBoundsException()> // 8 18:athrow } else { int i = mTail - 1 & mCapacityBitmask; // 9 19:aload_0 // 10 20:getfield #60 <Field int mTail> // 11 23:iconst_1 // 12 24:isub // 13 25:aload_0 // 14 26:getfield #41 <Field int mCapacityBitmask> // 15 29:iand // 16 30:istore_1 Object obj = mElements[i]; // 17 31:aload_0 // 18 32:getfield #44 <Field Object[] mElements> // 19 35:iload_1 // 20 36:aaload // 21 37:astore_2 mElements[i] = null; // 22 38:aload_0 // 23 39:getfield #44 <Field Object[] mElements> // 24 42:iload_1 // 25 43:aconst_null // 26 44:aastore mTail = i; // 27 45:aload_0 // 28 46:iload_1 // 29 47:putfield #60 <Field int mTail> return obj; // 30 50:aload_2 // 31 51:areturn } } public void removeFromEnd(int i) { if(i > 0) //* 0 0:iload_1 //* 1 1:ifgt 5 //* 2 4:return { if(i > size()) //* 3 5:iload_1 //* 4 6:aload_0 //* 5 7:invokevirtual #72 <Method int size()> //* 6 10:icmple 21 throw new ArrayIndexOutOfBoundsException(); // 7 13:new #79 <Class ArrayIndexOutOfBoundsException> // 8 16:dup // 9 17:invokespecial #80 <Method void ArrayIndexOutOfBoundsException()> // 10 20:athrow int j = 0; // 11 21:iconst_0 // 12 22:istore_2 if(i < mTail) //* 13 23:iload_1 //* 14 24:aload_0 //* 15 25:getfield #60 <Field int mTail> //* 16 28:icmpge 38 j = mTail - i; // 17 31:aload_0 // 18 32:getfield #60 <Field int mTail> // 19 35:iload_1 // 20 36:isub // 21 37:istore_2 for(int l = j; l < mTail; l++) //* 22 38:iload_2 //* 23 39:istore_3 //* 24 40:iload_3 //* 25 41:aload_0 //* 26 42:getfield #60 <Field int mTail> //* 27 45:icmpge 62 mElements[l] = null; // 28 48:aload_0 // 29 49:getfield #44 <Field Object[] mElements> // 30 52:iload_3 // 31 53:aconst_null // 32 54:aastore // 33 55:iload_3 // 34 56:iconst_1 // 35 57:iadd // 36 58:istore_3 //* 37 59:goto 40 j = mTail - j; // 38 62:aload_0 // 39 63:getfield #60 <Field int mTail> // 40 66:iload_2 // 41 67:isub // 42 68:istore_2 i -= j; // 43 69:iload_1 // 44 70:iload_2 // 45 71:isub // 46 72:istore_1 mTail = mTail - j; // 47 73:aload_0 // 48 74:aload_0 // 49 75:getfield #60 <Field int mTail> // 50 78:iload_2 // 51 79:isub // 52 80:putfield #60 <Field int mTail> if(i > 0) //* 53 83:iload_1 //* 54 84:ifle 4 { mTail = mElements.length; // 55 87:aload_0 // 56 88:aload_0 // 57 89:getfield #44 <Field Object[] mElements> // 58 92:arraylength // 59 93:putfield #60 <Field int mTail> int k = mTail - i; // 60 96:aload_0 // 61 97:getfield #60 <Field int mTail> // 62 100:iload_1 // 63 101:isub // 64 102:istore_2 for(i = k; i < mTail; i++) //* 65 103:iload_2 //* 66 104:istore_1 //* 67 105:iload_1 //* 68 106:aload_0 //* 69 107:getfield #60 <Field int mTail> //* 70 110:icmpge 127 mElements[i] = null; // 71 113:aload_0 // 72 114:getfield #44 <Field Object[] mElements> // 73 117:iload_1 // 74 118:aconst_null // 75 119:aastore // 76 120:iload_1 // 77 121:iconst_1 // 78 122:iadd // 79 123:istore_1 //* 80 124:goto 105 mTail = k; // 81 127:aload_0 // 82 128:iload_2 // 83 129:putfield #60 <Field int mTail> return; // 84 132:return } } } public void removeFromStart(int i) { if(i > 0) //* 0 0:iload_1 //* 1 1:ifgt 5 //* 2 4:return { if(i > size()) //* 3 5:iload_1 //* 4 6:aload_0 //* 5 7:invokevirtual #72 <Method int size()> //* 6 10:icmple 21 throw new ArrayIndexOutOfBoundsException(); // 7 13:new #79 <Class ArrayIndexOutOfBoundsException> // 8 16:dup // 9 17:invokespecial #80 <Method void ArrayIndexOutOfBoundsException()> // 10 20:athrow int k = mElements.length; // 11 21:aload_0 // 12 22:getfield #44 <Field Object[] mElements> // 13 25:arraylength // 14 26:istore_3 int j = k; // 15 27:iload_3 // 16 28:istore_2 if(i < k - mHead) //* 17 29:iload_1 //* 18 30:iload_3 //* 19 31:aload_0 //* 20 32:getfield #47 <Field int mHead> //* 21 35:isub //* 22 36:icmpge 46 j = mHead + i; // 23 39:aload_0 // 24 40:getfield #47 <Field int mHead> // 25 43:iload_1 // 26 44:iadd // 27 45:istore_2 for(k = mHead; k < j; k++) //* 28 46:aload_0 //* 29 47:getfield #47 <Field int mHead> //* 30 50:istore_3 //* 31 51:iload_3 //* 32 52:iload_2 //* 33 53:icmpge 70 mElements[k] = null; // 34 56:aload_0 // 35 57:getfield #44 <Field Object[] mElements> // 36 60:iload_3 // 37 61:aconst_null // 38 62:aastore // 39 63:iload_3 // 40 64:iconst_1 // 41 65:iadd // 42 66:istore_3 //* 43 67:goto 51 k = j - mHead; // 44 70:iload_2 // 45 71:aload_0 // 46 72:getfield #47 <Field int mHead> // 47 75:isub // 48 76:istore_3 j = i - k; // 49 77:iload_1 // 50 78:iload_3 // 51 79:isub // 52 80:istore_2 mHead = mHead + k & mCapacityBitmask; // 53 81:aload_0 // 54 82:aload_0 // 55 83:getfield #47 <Field int mHead> // 56 86:iload_3 // 57 87:iadd // 58 88:aload_0 // 59 89:getfield #41 <Field int mCapacityBitmask> // 60 92:iand // 61 93:putfield #47 <Field int mHead> if(j > 0) //* 62 96:iload_2 //* 63 97:ifle 4 { for(i = 0; i < j; i++) //* 64 100:iconst_0 //* 65 101:istore_1 //* 66 102:iload_1 //* 67 103:iload_2 //* 68 104:icmpge 121 mElements[i] = null; // 69 107:aload_0 // 70 108:getfield #44 <Field Object[] mElements> // 71 111:iload_1 // 72 112:aconst_null // 73 113:aastore // 74 114:iload_1 // 75 115:iconst_1 // 76 116:iadd // 77 117:istore_1 //* 78 118:goto 102 mHead = j; // 79 121:aload_0 // 80 122:iload_2 // 81 123:putfield #47 <Field int mHead> return; // 82 126:return } } } public int size() { return mTail - mHead & mCapacityBitmask; // 0 0:aload_0 // 1 1:getfield #60 <Field int mTail> // 2 4:aload_0 // 3 5:getfield #47 <Field int mHead> // 4 8:isub // 5 9:aload_0 // 6 10:getfield #41 <Field int mCapacityBitmask> // 7 13:iand // 8 14:ireturn } private int mCapacityBitmask; private Object mElements[]; private int mHead; private int mTail; }
PHP
UTF-8
2,002
3.140625
3
[ "MIT" ]
permissive
<?php namespace Core; use PDO; abstract class DB { /** * The PDO instance. * * @var \PDO */ private static $pdo; /** * The PDO data types. * * @var array */ protected static $dataTypes = [ 'boolean' => PDO::PARAM_BOOL, 'string' => PDO::PARAM_STR, 'integer' => PDO::PARAM_INT, 'double' => PDO::PARAM_STR, 'NULL' => PDO::PARAM_NULL, ]; /** * Get the PDO instance. * * @return \PDO */ private static function getInstance () { if (is_null(self::$pdo)) { $host = Config::get('database', 'host'); $port = Config::get('database', 'port'); $name = Config::get('database', 'name'); $user = Config::get('database', 'user'); $pass = Config::get('database', 'pass'); self::$pdo = new PDO("mysql:host={$host};port={$port};dbname={$name};charset=utf8", $user, $pass); self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); self::$pdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER); self::$pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING); self::$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); } return self::$pdo; } /** * Perform a query to database. * * @param string $sql * @return \PDOStatement */ protected static function query ($sql) { return self::getInstance()->query($sql); } /** * Prepare a query to be performed. * * @param string $sql * @return \PDOStatement */ protected static function prepare ($sql) { return self::getInstance()->prepare($sql); } /** * Get the last inserted id from database. * * @return int */ protected static function getInsertedId () { return self::getInstance()->lastInsertId(); } }
C#
UTF-8
404
2.75
3
[]
no_license
namespace ClassLibrary1 { public class Logger { public static string AssemblyGuid; public static void Init() { Assembly a = Assembly.GetCallingAssembly(); var attribute = (GuidAttribute)a.GetCustomAttributes(typeof(GuidAttribute), true)[0]; AssemblyGuid = attribute.Value; } } }
JavaScript
UTF-8
13,141
2.6875
3
[ "BSD-3-Clause" ]
permissive
/** * PongUI * * @license http://opensource.org/licenses/bsd-license.php The BSD License */ PongUI.prototype = new PongObject(); function PongUI(){ this.ScoreBoards = {}; this.PlayerNames = {}; this.ReadyBoxes = {}; this.Buttons = {}; this.Lobby = null; this.Labels = {}; this.Paddles = {one: null, two: null}; this.Canvas = null; this.Context = null; this.Board = null; this.Ball = null; this.MessageBox = {window: null, title: null, message: null}; } /** * init * * Initialize UI bindings. */ PongUI.prototype.init = function(){ this.ScoreBoards['one'] = document.getElementById('scoreboards_player_one'); this.ScoreBoards['two'] = document.getElementById('scoreboards_player_two'); this.PlayerNames['one'] = document.getElementById('players_name_one'); this.PlayerNames['two'] = document.getElementById('players_name_two'); this.ReadyBoxes['one'] = document.getElementById('readyboxes_one'); this.ReadyBoxes['two'] = document.getElementById('readyboxes_two'); this.Buttons['connect'] = document.getElementById('buttons_connect'); this.Buttons['ready'] = document.getElementById('buttons_ready'); this.Buttons['message_close'] = document.getElementById('buttons_message_box_close'); this.setupButtons(); this.Lobby = document.getElementById('lobby'); this.Connect = document.getElementById('connect'); this.Labels['lobby_name'] = document.getElementById('labels_lobby_name'); this.MessageBox = { window: document.getElementById("message_box"), title: document.getElementById("message_box_title"), message: document.getElementById("message_box_message") }; this.Canvas = document.getElementById("playarea"); this.Context = this.Canvas.getContext("2d"); this.Board = new PongGameBoard(this.Context); this.Ball = new PongBall( 0.19, 0.5, 0.05, 0.05, -0.005, 0.005 ); this.Paddles['one'] = new PongPaddle(0.03, 0.5, 0.02, 0.3, 0, 0.03); this.Paddles['two'] = new PongPaddle(0.97, 0.5, 0.02, 0.3, 0, 0.03); this.Board.addObject(this.Ball); this.Board.addObject(this.Paddles['one']); this.Board.addObject(this.Paddles['two']); document.addEventListener("out_of_bounds", function(e) { PongUI.Ball.x = 0.5; PongUI.Ball.y = Math.random(); PongUI.Ball.dx = -PongUI.Ball.dx; PongUI.Ball.dy = -PongUI.Ball.dy; }); setInterval(PongUI.onTimerTick, 16); }; /** * setupButtons * * Sets up the different buttons of the ui and attach different event handlers. */ PongUI.prototype.setupButtons = function(){ this.Buttons['connect'].addEventListener('click', function(e){ e.stopPropagation(); var address = document.getElementById('inputs_server_address').value; PongNetwork.connect(address); this.style.display = 'none'; return false; }, true); this.Buttons['ready'].addEventListener('click', function(e){ e.stopPropagation(); PongNetwork.ready(); this.style.display = 'none'; return false; }, true); this.Buttons['message_close'].addEventListener('click', function(e){ e.stopPropagation(); this.MessageBox.window.style.display='none'; }.bind(this), false); }; /** * onTimerTick * * Game global timer for drawing. */ PongUI.prototype.onTimerTick = function(){ PongUI.Board.update(); PongUI.Board.draw(); }; /** * alert * * Displays a message * * @param string title The message title * @param string message The message to be displayed */ PongUI.prototype.alert = function(title, message){ this.MessageBox.title.innerText = title; this.MessageBox.message.innerText = message; this.MessageBox.window.style.display = 'block'; this.MessageBox.window.style.top = (document.height / 2 - this.MessageBox.window.clientHeight / 2 ) + 'px'; this.MessageBox.window.style.left = (document.width / 2 - this.MessageBox.window.clientWidth / 2) + 'px'; }; /** * setPlayerScore * * Sets a player's score. * * @param string player Player id * @param string score Score value */ PongUI.prototype.setPlayerScore = function(player, score){ this.ScoreBoards[player].innerText = score; }; /** * setPlayerName * * Displays the name of a player * * @param string player Player id * @param string name Player name */ PongUI.prototype.setPlayerName = function(player, name){ this.PlayerNames[player].innerText = name; }; /** * setPlayerReady * * Display the state of a player as ready or not. * @param string player Player id * @param boolean ready Ready state */ PongUI.prototype.setPlayerReady = function(player, ready){ var state = ''; if (ready){ state = 'Ready'; }else{ state = 'Not Ready'; } this.ReadyBoxes[player].innerText = state; }; /** * showButton * * Shows a button * * @param string button Button id to be shown. */ PongUI.prototype.showButton = function(button){ this.Buttons[button].style.display = 'block'; }; /** * hideButton * * Hides a button * * @param string button Button id to be hidden. */ PongUI.prototype.hideButton = function(button){ this.Buttons[button].style.display = 'none'; }; PongUI.prototype.hideConnect = function(){ this.Connect.style.display = 'none'; }; PongUI.prototype.showConnect = function(){ this.Buttons['connect'].style.display = ''; this.Connect.style.display = ''; }; /** * showLobby * * Shows the lobby. */ PongUI.prototype.showLobby = function(){ this.Labels['lobby_name'].innerText = "You are " + PongData.Players[PongData.Players.Me]; this.Lobby.style.display = ''; }; /** * hideLobby * * Hides the lobby. */ PongUI.prototype.hideLobby = function(){ this.Lobby.style.display = 'none'; }; /** * enablePaddles * * Initialize paddles and binds the mouse move event to onPaddleMove */ PongUI.prototype.enablePaddles = function(){ switch(PongData.Players.me){ default: //TODO: Better handling of this exception alert("PongUI.enablePaddles error: Invalid player id."); return; break;bind; case 'one': case 'two': this.MyPaddle = this.Paddles(PongData.Players.me); break; } document.addEventListener("mousemove", this.onPaddleMove); }; PongUI.prototype.disablePaddles = function(){ //TODO: Double check this. probably wrong document.removeEventListener("mousemove"); }; /** * onPaddleMove * * Moves a paddle on the board. Triggered after a mousemove event. * @param event evt Mouse move event. */ PongUI.prototype.onPaddleMove = function(evt){ var paddle = this.Paddles[PongData.Players.Me]; paddle.setTarget(evt.x, evt.y - PongUI.Canvas.offsetTop); PongNetwork.updatePaddle((evt.y - PongUI.Canvas.offsetTop) / PongUI.Canvas.clientHeight); }; /** * updatePaddleLocation * * Updates the other player paddle location * * @param string player Player id * @param float pos Paddle position */ PongUI.prototype.updatePaddle = function(player, pos){ var paddle = null; if(player == this.Players.me){ paddle = this.Paddles.mine; }else{ paddle = this.Paddles.other; } paddle.setTarget(0, pos * this.Canvas.clientHeight); }; PongUI.prototype.stop = function(){ this.disablePaddles(); //TODO: Stop and reset the game. }; /** * PongBall * * @param x * @param y * @param width * @param height * @param dx * @param dy */ function PongBall(x, y, width, height, dx, dy) { this.x = x; this.y = y; this.width = width; this.height = height; this.dx = dx; this.dy = dy; this.halfWidth = this.width / 2; this.halfHeight = this.height / 2; this.leftBoundary = 1.0 - this.halfWidth; this.rightBoundary = 0.0; this.topBoundary = 0.0; this.bottomBoundary = 1.0 - this.halfHeight; this.image = new Image(); this.image.src = "images/Chrome_Logo.svg"; } PongBall.prototype.setBoard = function(board) { this.board = board; }; PongBall.prototype.update = function() { this.x += this.dx; this.y += this.dy; this.collisionDetection(); }; PongBall.prototype.collisionDetection = function() { var intersection = null; for (var i in this.board.items){ if (this == this.board.items[i]){ continue; } // This will only check for intersection if the item is on the same side of the board. if(this.board.items[i].x > 0.9 && this.x > 0.9 || this.board.items[i].x < 0.1 && this.x < 0.1){ intersection = this.board.items[i].intersects(this); }else{ //Skip the other paddle continue; } if (intersection != null) { this.dx = intersection.x * this.dx; this.dy = intersection.y * this.dy; } } if (this.x < this.rightBoundary || this.x > this.leftBoundary ) { var changeEvent = document.createEvent("Event"); changeEvent.initEvent("out_of_bounds", true, false); document.dispatchEvent(changeEvent); } if (this.y < this.topBoundary || this.y > this.bottomBoundary) { this.dy = -this.dy; } }; PongBall.prototype.intersects = function(object) { return null; }; PongBall.prototype.draw = function(context) { var x = this.board.relativeX(this.x - this.halfWidth); var y = this.board.relativeY(this.y - this.halfHeight); context.drawImage(this.image, x, y, this.board.relativeX(this.width), this.board.relativeX(this.height)); }; function PongPaddle(x, y, width, height, sx, sy) { this.x = x; this.y = y; this.target_x = x; this.target_y = y; this.width = width; this.height = height; this.speed_x = sx; this.speed_y = sy; this.dx = 0; this.dy = 0; this.halfWidth = this.width / 2; this.halfHeight = this.height / 2; } PongPaddle.prototype.setBoard = function(board) { this.board = board; }; PongPaddle.prototype.setTarget = function(x, y) { this.target_x = x; this.target_y = y; var rx = this.board.relativeX(this.x); var ry = this.board.relativeY(this.y); var rspeed_x = this.board.relativeX(this.speed_x); var rspeed_y = this.board.relativeY(this.speed_y); if (rx < this.target_x - rspeed_x) { this.dx = this.speed_x; } else if (rx > this.target_x + rspeed_x) { this.dx = -this.speed_x; } if (ry < this.target_y - rspeed_y) { this.dy = this.speed_y; } else if (ry > this.target_y + rspeed_y) { this.dy = -this.speed_y; } }; PongPaddle.prototype.update = function() { this.x += this.dx; this.y += this.dy; this.collisionDetection(); }; PongPaddle.prototype.collisionDetection = function() { var w2 = this.halfWidth; var h2 = this.halfHeight; if (this.x < w2) { this.x = w2; } else if (this.x > 1.0 - w2) { this.x = 1.0 - w2; } if (this.y < h2) { this.y = h2; } else if (this.y > 1.0 - h2) { this.y = 1.0 - h2; } var rx = this.board.relativeX(this.x); var ry = this.board.relativeY(this.y); var rspeed_x = this.board.relativeY(this.speed_x); var rspeed_y = this.board.relativeY(this.speed_y); if (Math.abs(rx - this.target_x) <= rspeed_x) { this.dx = 0; this.x = this.target_x / this.board.width; } if (Math.abs(ry - this.target_y) <= rspeed_y) { this.dy = 0; this.y = this.target_y / this.board.height; } }; PongPaddle.prototype.intersects = function(object) { var this_w2 = this.halfWidth; var this_h2 = this.halfHeight; var object_w2 = object.width / 2.0; var object_h2 = object.height / 2.0; var object_north = object.y - object_h2; var object_south = object.y + object_h2; var object_east = object.x + object_w2; var object_west = object.x - object_w2; var this_north = this.y - this_h2; var this_south = this.y + this_h2; var this_east = this.x + this_w2; var this_west = this.x - this_w2; var intersect_north = false; var intersect_south = false; var intersect_east = false; var intersect_west = false; // North if (object_south >= this_north && object_south < this_south) { intersect_north = true; } // South if (object_north <= this_south && object_north > this_north) { intersect_south = true; } // East if (object_west <= this_east && object_west > this_west) { intersect_east = true; } // West if (object_east >= this_west && object_east < this_east) { intersect_west = true; } if (intersect_east && (intersect_north || intersect_south)) { return {x: -1, y: 1, type: 'east'}; } if (intersect_west && (intersect_north || intersect_south)) { return {x: -1, y: 1, type: 'west'}; } return null; }; PongPaddle.prototype.draw = function(context) { context.fillStyle = '#fff'; var x = this.board.relativeX(this.x - this.halfWidth); var y = this.board.relativeY(this.y - this.halfHeight); context.fillRect(x, y, this.board.relativeX(this.width), this.board.relativeY(this.height)); }; PongGameBoard.prototype = new PongObject(); function PongGameBoard(context){ this.context = context; this.width = context.canvas.scrollWidth; this.height = context.canvas.scrollHeight; this.context.canvas.width = this.width; this.context.canvas.height = this.height; this.items = []; }; PongGameBoard.prototype.addObject = function(object) { object.setBoard(this); this.items.push(object); }; PongGameBoard.prototype.update = function() { for (var i in this.items) { this.items[i].update(); } }; PongGameBoard.prototype.draw = function() { this.context.clearRect(0, 0, this.width, this.height); for (var i in this.items) { this.items[i].draw(this.context); } }; PongGameBoard.prototype.relativeX = function(value) { return value * this.width; }; PongGameBoard.prototype.relativeY = function(value) { return value * this.height; };
TypeScript
UTF-8
13,050
2.515625
3
[]
no_license
/* eslint-disable @typescript-eslint/ban-ts-comment */ /** * Space Navigator Controls Component for A-Frame. * * Forked from: * https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API * */ import { Vector3, Euler, Object3D } from "three"; const MAX_DELTA = 200, // ms ROTATION_EPS = 0.0, DEFAULT_FOV = 60, DEG_TO_RAD = (1 / 180) * Math.PI, RAD_TO_DEG = 180 / Math.PI; // main export class SpaceNavigator { schema: any; constructor(args: any) { this.schema = { // Enable/disable features enabled: { default: true }, movementEnabled: { default: true }, lookEnabled: { default: true }, rollEnabled: { default: true }, invertPitch: { default: false }, fovEnabled: { default: true }, fovMin: { default: 2 }, fovMax: { default: 115 }, // Constants rotationSensitivity: { default: 0.05 }, movementEasing: { default: 3 }, movementAcceleration: { default: 700 }, fovSensitivity: { default: 0.01 }, fovEasing: { default: 3 }, fovAcceleration: { default: 5 }, invertScroll: { default: false } }; args = args || {}; // eslint-disable-next-line @typescript-eslint/no-this-alias const this_ = this; this_.data = {}; Object.keys(this_.schema).forEach(function (argName) { if (args[argName] !== undefined) { // use argument this_.data[argName] = args[argName]; } else { // set default this_.data[argName] = this_.schema[argName].default; } }); this_.init(); } position: Vector3; movement: Vector3; movementVelocity: Vector3; movementDirection: Vector3; rotation: Euler; pitch: Object3D; roll: Object3D; yaw: Object3D; fov: number; fovVelocity: number; buttons: any; scrollDelta: number; _previousUpdate: number; data: any; scroll: number; el: any; _getMovementVector: any; _updateRotation: any; _updateFov: any; spaceNavigatorId: any; /** * Called once when component is attached. Generally for initial setup. */ init() { // Movement this.position = new Vector3(0, 0, 0); this.movement = new Vector3(0, 0, 0); this.movementVelocity = new Vector3(0, 0, 0); this.movementDirection = new Vector3(0, 0, 0); // Rotation this.rotation = new Euler(0, 0, 0, "YXZ"); this.pitch = new Object3D(); this.roll = new Object3D(); this.yaw = new Object3D(); this.yaw.position.y = 10; this.yaw.add(this.pitch); // FOV this.fov = DEFAULT_FOV; this.fovVelocity = 0; // Button state this.buttons = {}; // scroll wheel this.scrollDelta = 0; // time this._previousUpdate = performance.now(); if (!this.getSpaceNavigator()) { console.warn("Space Navigator not found. Connect and press any button to continue."); } } /** * THREE specific: Called on each iteration of main render loop. */ update() { const time = performance.now(); const dt = time - this._previousUpdate; this._previousUpdate = time; this.updateRotation(); this.updatePosition(dt); if (this.data.fovEnabled) this.updateFov(dt); } /******************************************************************* * Movement */ updatePosition(dt: number) { const data = this.data; const acceleration = data.movementAcceleration; const easing = data.movementEasing; const velocity = this.movementVelocity; const spaceNavigator = this.getSpaceNavigator(); // If data has changed or FPS is too low // we reset the velocity if (dt > MAX_DELTA) { velocity.x = 0; velocity.x = 0; velocity.z = 0; return; } velocity.z -= (velocity.z * easing * dt) / 1000; velocity.x -= (velocity.x * easing * dt) / 1000; velocity.y -= (velocity.y * easing * dt) / 1000; if (data.enabled && data.movementEnabled && spaceNavigator) { /* * 3dconnexion space navigator position axes * * "right handed coordinate system" * 0: - left / + right (pos: X axis pointing to the right) * 1: - backwards / + forward (pos: Z axis pointing forwards) * 2: - up / + down (pos: Y axis pointing down) */ const xDelta = spaceNavigator.axes[0], yDelta = spaceNavigator.axes[2], zDelta = spaceNavigator.axes[1]; velocity.x += (xDelta * acceleration * dt) / 1000; velocity.z += (zDelta * acceleration * dt) / 1000; velocity.y -= (yDelta * acceleration * dt) / 1000; } const movementVector = this.getMovementVector(dt); this.movement.copy(movementVector); this.position.add(movementVector); } getMovementVector(dt: number) { if (this._getMovementVector) return this._getMovementVector(dt); const euler = new Euler(0, 0, 0, "YXZ"), rotation = new Vector3(), direction = this.movementDirection, velocity = this.movementVelocity; this._getMovementVector = function (dt: number) { rotation.set( this.rotation.x * RAD_TO_DEG, this.rotation.y * RAD_TO_DEG, this.rotation.z * RAD_TO_DEG ); direction.copy(velocity); direction.multiplyScalar(dt / 1000); if (!rotation) return direction; euler.set(rotation.x * DEG_TO_RAD, rotation.y * DEG_TO_RAD, rotation.z * DEG_TO_RAD); direction.applyEuler(euler); return direction; }; return this._getMovementVector(dt); } /******************************************************************* * Rotation */ updateRotation() { if (this._updateRotation) return this._updateRotation(); const initialRotation = new Vector3(), prevInitialRotation = new Vector3(), prevFinalRotation = new Vector3(); let tCurrent, tLastLocalActivity = 0, tLastExternalActivity = 0; const rotationEps = 0.0001, debounce = 500; this._updateRotation = function () { const spaceNavigator = this.getSpaceNavigator(); if (!this.data.lookEnabled || !spaceNavigator) return; tCurrent = Date.now(); initialRotation.set( this.rotation.x * RAD_TO_DEG, this.rotation.y * RAD_TO_DEG, this.rotation.z * RAD_TO_DEG ); // If initial rotation for this frame is different from last frame, and // doesn't match last spaceNavigator state, assume an external component is // active on this element. if ( initialRotation.distanceToSquared(prevInitialRotation) > rotationEps && initialRotation.distanceToSquared(prevFinalRotation) > rotationEps ) { prevInitialRotation.copy(initialRotation); tLastExternalActivity = tCurrent; return; } prevInitialRotation.copy(initialRotation); // If external controls have been active in last 500ms, wait. if (tCurrent - tLastExternalActivity < debounce) return; /* * 3dconnexion space navigator rotation axes * * "right handed coordinate system" * 3: - pitch down / + pitch up (rot: X axis clock wise) * 4: - roll right / + roll left (rot: Z axis clock wise) * 5: - yaw right / + yaw left (rot: Y axis clock wise) */ const delta = new Vector3( spaceNavigator.axes[3], spaceNavigator.axes[5], spaceNavigator.axes[4] ); if (delta.x < ROTATION_EPS && delta.x > -ROTATION_EPS) delta.z = 0; if (delta.y < ROTATION_EPS && delta.y > -ROTATION_EPS) delta.y = 0; if (delta.z < ROTATION_EPS && delta.z > -ROTATION_EPS) delta.x = 0; if (this.data.invertPitch) delta.x *= -delta.x; // If external controls have been active more recently than spaceNavigator, // and spaceNavigator hasn't moved, don't overwrite the existing rotation. if (tLastExternalActivity > tLastLocalActivity && !delta.lengthSq()) return; delta.multiplyScalar(this.data.rotationSensitivity); this.pitch.rotation.x += delta.x; this.yaw.rotation.y -= delta.y; this.roll.rotation.z += delta.z; this.rotation.set( this.pitch.rotation.x, this.yaw.rotation.y, this.data.rollEnabled ? this.roll.rotation.z : 0 ); prevFinalRotation.set( this.rotation.x * RAD_TO_DEG, this.rotation.y * RAD_TO_DEG, this.rotation.z * RAD_TO_DEG ); tLastLocalActivity = tCurrent; }; return this._updateRotation(); } updateFov(dt: number) { if (this._updateFov) return this._updateFov(dt); // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; let previousScroll = 0; this._updateFov = function (dt: number) { const fovFromAttribute: any = null; let fov = fovFromAttribute ? parseFloat(fovFromAttribute) : self.fov; const lensDistance = 1 / Math.tan((fov / 2) * DEG_TO_RAD); // easing if (dt > 1000) return; self.fovVelocity = self.fovVelocity - ((self.fovVelocity * dt) / 1000) * self.data.fovEasing; if (self.fovVelocity > -0.001 && self.fovVelocity < 0.001) self.fovVelocity = 0; // acceleration const scrollDelta = previousScroll - self.scroll; self.fovVelocity += ((scrollDelta * dt) / 1000) * self.data.fovAcceleration; // applay const newLensDistance = lensDistance + self.fovVelocity * self.data.fovSensitivity; //const newFov = Math.min(140, Math.max(10, Math.atan( 1 / newLensDistance ) * 2)) fov = Math.atan(1 / newLensDistance) * 2 * RAD_TO_DEG; if (fov > self.data.fovMin && fov < self.data.fovMax) { self.fov = fov; } previousScroll = self.scroll; }; return this._updateFov(dt); } /******************************************************************* * SpaceNavigator state */ /** * Returns SpaceNavigator instance attached to the component. If connected, * a proxy-controls component may provide access to spaceNavigator input from a * remote device. * * @return {SpaceNavigator} */ getSpaceNavigator() { // use local space navigator if (!navigator.getGamepads) { console.error( "Gamepad API is not supported on this browser. Please use Firefox or Chrome." ); return false; } if (this.spaceNavigatorId === undefined) { // find space navigator // eslint-disable-next-line @typescript-eslint/no-this-alias const this_ = this; const gamepadList = navigator.getGamepads(); Object.keys(gamepadList).forEach(function (i) { const gamepadName = gamepadList[i] ? gamepadList[i].id : null; if ( gamepadName && (gamepadName.toLowerCase().indexOf("spacenavigator") > -1 || gamepadName.toLowerCase().indexOf("space navigator") > -1 || gamepadName.toLowerCase().indexOf("spacemouse wireless") > -1) ) { this_.spaceNavigatorId = i; } }); } return navigator.getGamepads()[this.spaceNavigatorId]; } /** * Returns true if Space Navigator is currently connected to the system. * @return {boolean} */ isConnected() { const spaceNavigator = this.getSpaceNavigator(); return !!(spaceNavigator && spaceNavigator.connected); } /** * Returns a string containing some information about the controller. Result * may vary across browsers, for a given controller. * @return {string} */ getID() { //@ts-ignore return this.getSpaceNavigator().id; } }
Markdown
UTF-8
2,798
2.78125
3
[]
no_license
# TicketingService This is a ticketing service using tornado framework. Tornado version : 5.1.1 Torndb version : 0.3 Author : Mohammad Ali Poorafsahi # PreRequirements - python - mysql # Debian distribution command to install python and mysql: `$ apt install python mysql` # installation ## step 0:cloning the repository ` $ git clone https://github.com/MohammadAliAfsahi/TicketingService.git $ cd ticketing_project ` ## step 1: Mysql check if mysql service is running using following command: `$ service mysql status` if mysql is running you're free to skip, if not use following command in order to start mysql service: `$ service mysql start` run following command as a user that has root privillege or a user that can create database(you can change root to desired user): `$ mysql -u root` `mysql> CREATE DATABASE ticket;` Allow the "ticket" user to connect with the password "ticket": `mysql> GRANT ALL PRIVILEGES ON ticket.* TO 'ticket'@'localhost' IDENTIFIED BY 'ticket';` # step 2: create table `mysql> use ticket;` `mysql> CREATE TABLE user ( id smallint unsigned not null auto_increment, username varchar(20) not null, password varchar(20) not null,firstname varchar(20),lastname varchar(20),apitoken varchar(100), admin BOOLEAN NOT NULL,constraint pk_example primary key (id));` `mysql> CREATE TABLE tickets ( id smallint unsigned not null auto_increment, subject varchar(50) not null,body varchar(500) NOT NULL, status VARCHAR(20) NOT NULL, userid INT NOT NULL, date DATETIME DEFAULT CURRENT_TIMESTAMP, response VARCHAR(500),constraint pk_example primary key (id) );` # Give a user Admin privilege if you want to give a specific user admin privilege you need to do it manully in mysql database using following command: `mysql> update user set admin=1 where id = userid` you need to replace userid in where clause with id of user you want to become admin. # Run project ` $ python server/server.py ` # Usage There is a .mp4 file in this page which you can see how to use this project. For both POST and GET method running codes are the same(the difference is in implementation). The main features are: 1. login 2. signup 3. logout 4. Sending ticket 5. Get tickets (user privilege) 6. Close ticket(user privilege) 7. Change status of ticket (admin privilege) 8. Response to ticket (admin privilege) 9. Get tickets (admin privilege) This project supports both POST and GET methods. # Client In order to run client code you need request module which is pre-installed in python but if not use following command: ` $ pip install requests ` ` $ python client/client-get.py ` or ` $ python client/client-post.py ` # Support: - Telegram : [@MohammadAliAfsahi](https://t.me/MohammadAliAfsahi) - gmail : MohammadAliAfsahi.ce@gmail.com ###### special thanks to : [@limner](https://gitlab.com/limner)
Python
UTF-8
1,107
3.109375
3
[]
no_license
import unittest from main import line_checksum_min_max, line_checksum_division, file_checksum class TestLineChecksumMinMax(unittest.TestCase): def test_easy(self): self.assertEqual(line_checksum_min_max('1234'), 3) def test_samples(self): self.assertEqual(line_checksum_min_max('5195'), 8) def test_decr_string(self): self.assertEqual(line_checksum_min_max('753'), 4) def test_incr_string(self): self.assertEqual(line_checksum_min_max('2468'), 6) class TestLineChecksumDivision(unittest.TestCase): def test_samples(self): self.assertEqual(line_checksum_division('5928'), 4) self.assertEqual(line_checksum_division('9473'), 3) self.assertEqual(line_checksum_division('3865'), 2) class TestFileChecksum(unittest.TestCase): def test_easy(self): input = [ '1 2 3 4\n', # 3 '20 50 60 10\n', # 50 '11 19 67 567\n', # 556 '5 8 7 2\n' # 6 ] self.assertEqual(file_checksum(input), 615) if __name__ == '__main__': unittest.main()
Java
UTF-8
1,849
2.375
2
[]
no_license
package com.nongguanjia.doctorTian.bean; import android.os.Parcel; import android.os.Parcelable; public class AllEcho implements Parcelable{ private String TalkId; private String Photo; private String Name; private String Phone; private String Massage; private String Date; public String getTalkId() { return TalkId; } public void setTalkId(String talkId) { TalkId = talkId; } public String getPhoto() { return Photo; } public void setPhoto(String photo) { Photo = photo; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getPhone() { return Phone; } public void setPhone(String phone) { Phone = phone; } public String getMassage() { return Massage; } public void setMassage(String massage) { Massage = massage; } public String getDate() { return Date; } public void setDate(String date) { Date = date; } @Override public int describeContents() { // TODO Auto-generated method stub return 0; } @Override public void writeToParcel(Parcel out, int flags) { // TODO Auto-generated method stub out.writeString(TalkId); out.writeString(Photo); out.writeString(Name); out.writeString(Phone); out.writeString(Massage); out.writeString(Date); } public static final Parcelable.Creator<AllEcho> CREATOR = new Creator<AllEcho>(){ @Override public AllEcho createFromParcel(Parcel in) { // TODO Auto-generated method stub AllEcho echo = new AllEcho(); echo.TalkId = in.readString(); echo.Photo = in.readString(); echo.Name = in.readString(); echo.Phone = in.readString(); echo.Massage = in.readString(); echo.Date = in.readString(); return echo; } @Override public AllEcho[] newArray(int size) { // TODO Auto-generated method stub return new AllEcho[size]; } }; }
C++
GB18030
380
2.734375
3
[]
no_license
#include <iostream> using namespace std; void foo(void); //LNq禡AΨܰϰܼƭ int x = 10;//ŧiܼ x int main(void) { cout<<"ܼ x = "<<x<<endl; foo(); cout<<"ܼ x = "<<x<<endl; return 0; } void foo(void) { int x = 20;//ŧiϰܼ x printf( "ϰܼ x = %d\n", x ); }
Markdown
UTF-8
4,294
2.8125
3
[ "Apache-2.0" ]
permissive
### Terraform Template to create a Single instance of FMCv, Ubuntu 18.04 LTS and Windows 10 all on the same Subnet. Simple Usage ----- This contains the bare minimum options to be configured for the VM to be provisioned. The entire code block provisions a Windows, a Linux VM and Cisco FMCv 7.0. An Ubuntu Server 18.04-LTS VM and a Windows 10 VM are provisioned using single VNet and opens up ports 22 for SSH and 3389 for RDP access via the attached public IP to each VM. The Ubuntu Server will use the ssh key found in the default location `~/.ssh/id_rsa.pub`. All resources are provisioned into the default resource group called `FMC_RG`. The Windows and Linux VM can be omitted if not required. The outputs are included to make it convenient to know the address to connect to the VMs after provisioning completes. ## Preinstallation First step is to set up the a workstation to install Terrraform and Azure CLI. - Install Terraform on Ubuntu : [Doc](https://www.terraform.io/docs/cli/install/apt.html) - Install Azure CLI on Ubuntu : [Doc](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-linux?pivots=apt) Make sure to login to Azure using below command to use Azure as a provider in Terraform template `az login --use-device-code` The template has been tested on : - Terraform Version = 1.0.1 - Hashicorp AzureRM Provider = 2.65.0 Using this Terraform template, following resources will be deployed in azure. - one new VPC with four subnets (1 Management networks, 3 data networks) - Windows 10 instance with Public IP for Managament. - Ubuntu 18.04 LTS with Public IP. - FMCv instance with Public IP. The variables should be defined with a value in the "terraform.tfvars" file before using the templates. ### Variables | Variable | Meaning | | --- | --- | | `resource_group_name = "FMC_RG"` | Resorce group Name in Azure | | `resource_group_location = "centraleurope"` | Resorce group Location in Azure | | `virtual_network_name = "vnetprod01"` | Virtual Network in Azure | | `subnet_name_1 = "subnet01"` | Subnet name in Azure | | `subnet_name_2 = "subnet02"` | Subnet name in Azure | | `subnet_name_3 = "subnet03"` | Subnet name in Azure | | `subnet_name_4 = "subnet04"` | Subnet name in Azure | | `public_ip_ubuntu = "publicip01"` | public ip name of linux VM | | `public_ip_win = "publicip02"` | public ip name of windows VM | | `public_ip_fmc = "publicfmcip01"` | public ip name of FMCv VM | | `network_security_group_VM = "nsgprod01"` | Network Security Group for Windows and FMCv VM | | `network_security_group_ALL = "nsgprod02"` | Network Security Group for linux VM | | `network_interface_win = "nicwin01"` | Network interface name of Windows VM | | `network_interface_name = "nicprod01"` | Network interface name of linux VM | | `network_interface_fmc = "fmcmgmt"` | Network interface name of FMCv VM | | `linux_virtual_machine_name = "linuxvm01"` | Linux VM name | | `fmc_virtual_machine_name = "linuxvm01"` | FMCv VM name | | `win_virtual_machine_name = "linuxvm01"` | Windows VM name | | `fmc_version = "70094.0.0"` | FMCv Version | ### SSH Keys creation; 1) ``` - Check for existing key $ cd ~/.ssh $ ls ``` 2) ``` - If no keys exist, generate new keys $ ssh-keygen -o Generating public/private rsa key pair. ``` 3) ``` - validate key $ cat ~/.ssh/id_rsa.pub ``` ## Deployment Procedure 1) Clone or Download the Repository 2) Input the values in the terraform ".tfvars" for variables in .tf 3) Initialize the providers and modules ``` - go to the specific terraform folder from the cli cd xxxx terraform init ``` 4) submit the terraform plan ``` terraform plan -out <filename> ``` 5) verify the output of the plan in the terminal; if everything is fine, then apply the plan ``` terraform apply <out filename generated earlier> ``` 6) Check the output and confirm it by typing "yes." ## Post Deployment Procedure 1) SSH to the instance by using ssh admin@PublicIP *Note: The security group attached to the interfaces in this template allow traffic from anywhere. It is necessary to change the security group to allow only the required traffic to and from the specific IP address and ports.*
Go
UTF-8
1,851
2.546875
3
[ "Apache-2.0" ]
permissive
package mgo import ( "context" "github.com/yaziming/mgo/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" "time" ) type Pipe struct { pipeline interface{} query coll *Collection } func (p *Pipe) AllowDiskUse() *Pipe { p.allowDisk = true return p } func (p *Pipe) Batch(n int) *Pipe { p.op.limit = n return p } func (p *Pipe) Collation(collation *Collation) *Pipe { if collation != nil { p.collation = collation } return p } func (p *Pipe) Explain(result interface{}) error { command := bson.D{ {"aggregate", p.coll.collection.Name()}, {"pipeline", p.pipeline}, {"explain", true}, } opts := options.RunCmd().SetReadPreference(readpref.Primary()) if err := p.coll.collection.Database().RunCommand(nil, command, opts).Decode(result); err != nil { return err } return nil } func (p *Pipe) aggregate(others ...*options.AggregateOptions) (*mongo.Cursor, error) { var ctx context.Context if p.maxTimeMS > 0 { ctx, _ = context.WithTimeout(context.Background(), time.Duration(p.maxTimeMS)*time.Millisecond) } opts := p.toAggregateOptions() for _, other := range others { opts = options.MergeAggregateOptions(opts, other) } return p.coll.collection.Aggregate(ctx, p.pipeline, opts) } func (p *Pipe) All(result interface{}) error { cs, err := p.aggregate() if err != nil { return err } return cs.All(nil, result) } func (p *Pipe) Iter() *Iter { cs, err := p.aggregate() return &Iter{ cursor: cs, done: false, err: err, } } func (p *Pipe) One(result interface{}) (err error) { iter := p.Iter() if iter.Next(result) { return nil } if err := iter.Err(); err != nil { return err } return ErrNotFound } func (p *Pipe) SetMaxTime(d time.Duration) *Pipe { p.maxTimeMS = int64(d / time.Millisecond) return p }
JavaScript
UTF-8
9,618
3.28125
3
[ "Apache-2.0" ]
permissive
/* Copyright 2015 Aleksandar Jankovic 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. */ const storageManager = require('./StorageManager'); /** * Characters used when generating random text * Removed l and i to decrease user errors when reading the random strings * @type {string} */ const chars = 'abcdefghjkmnopqrstuvwxyz'; /** * Numbers used when generating random text * Removed 1 to decrease user errors when reading the random string * @type {string} */ const numbers = '023456789'; /** * Special characters used when generating random text * @type {string} */ const specials = '/\\!;:#&*'; /** * Used when generating random binary text * @type {string} */ const binary = '01'; const allowedRegex = /^[\w\d\såäöÅÄÖ\-]+$/g; class TextTools { /** * Beautifies number by adding a 0 before the number if it is lower than 10 * @static * @param {Number} number - Number to be beautified * @returns {Number|string} - Single number or string with 0 + number */ static beautifyNumber(number) { return number > 9 ? number : `0${number}`; } /** * Takes date and returns shorter human-readable time * @static * @param {Object} params - Parameters * @param {Date|number} params.date - Date * @param {Number} [params.offset] - Should hours be modified from the final time? * @param {boolean} [params.lockYear] - Should the year stay unmodified? * @returns {Object} Human-readable time and date */ static generateTimeStamp({ date, offset, lockDate }) { const newDate = new Date(date); const timeStamp = {}; const yearModification = storageManager.getYearModification(); if (offset) { newDate.setHours(newDate.getHours() + offset); } if (!lockDate && !isNaN(yearModification)) { newDate.setFullYear(newDate.getFullYear() + parseInt(yearModification, 10)); } timeStamp.mins = this.beautifyNumber(newDate.getMinutes()); timeStamp.hours = this.beautifyNumber(newDate.getHours()); timeStamp.seconds = this.beautifyNumber(newDate.getSeconds()); timeStamp.month = this.beautifyNumber(newDate.getMonth() + 1); timeStamp.day = this.beautifyNumber(newDate.getDate()); timeStamp.year = newDate.getFullYear(); timeStamp.halfTime = `${timeStamp.hours}:${timeStamp.mins}`; timeStamp.fullTime = `${timeStamp.halfTime}:${timeStamp.seconds}`; timeStamp.halfDate = `${timeStamp.day}/${timeStamp.month}`; timeStamp.fullDate = `${timeStamp.halfDate}/${timeStamp.year}`; return timeStamp; } /** * Does the string contain only legal (a-zA-z0-9) alphanumerics? * @static * @param {string} text - String to be checked * @returns {boolean} - Does string contain only legal (a-zA-z0-9) alphanumerics? */ static isTextAllowed(text) { return allowedRegex.test(text); } /** * Replaces part of the sent string and returns it * @static * @param {string} text - Original string * @param {string} find - Substring to replace * @param {string} replaceWith - String that will replace the found substring * @returns {string} - Modified string */ static findOneReplace(text, find, replaceWith) { return text.replace(new RegExp(find), replaceWith); } /** * Trims whitespaces from beginning and end of the string * Needed for Android 2.1. trim() is not supported * @static * @param {string} sentText - String to be trimmed * @returns {string} - String with no whitespaces in the beginning and end */ static trimSpace(sentText) { return this.findOneReplace(sentText, /^\s+|\s+$/, ''); } /** * Creates and returns a randomised string * @static * @param {Object} params - Parameters * @param {string} params.selection - Characters to randomise from * @param {Number} params.length - Length of randomised string * @param {boolean} [params.upperCase] - Should all characters be in upper case? * @param {boolean} [params.codeMode] - Should there be extra {} and () inserted into the string? * @returns {string} - Randomised string */ static createRandString({ selection, length, upperCase, codeMode }) { const randomLength = selection.length; let result = ''; for (let i = 0; i < length; i += 1) { const randomVal = Math.round(Math.random() * (randomLength - 1)); let val = Math.random() > 0.5 ? selection[randomVal].toUpperCase() : selection[randomVal]; if (codeMode) { const rand = Math.random(); // If new value is a character or number if (i < length - 2 && (chars + numbers).indexOf(val) > -1) { if (rand > 0.95) { val = `${val}{}`; i += 2; } else if (rand < 0.05) { val = `${val}()`; i += 2; } } } result += val; } if (upperCase) { return result.toUpperCase(); } return result; } /** * Creates and returns a randomised string * @static * @param {Number} length - Length of randomised string * @param {boolean} upperCase - Should all characters be in upper case? * @returns {string} - Randomised string */ static createCharString(length, upperCase) { return this.createRandString({ selection: chars, length, upperCase, }); } /** * Creates and returns a alphanumerical randomised string * @static * @param {Number} length - Length of randomised string * @param {boolean} upperCase - Should all characters be in upper case? * @returns {string} - Randomised string */ static createAlphaNumbericalString(length, upperCase) { return this.createRandString({ selection: numbers + chars, length, upperCase, }); } /** * Creates and returns a randomised string, only containing 0 and 1 * @static * @param {Number} length - Length of randomised string * @returns {string} - Randomised string */ static createBinaryString(length) { return this.createRandString({ selection: binary, length, }); } /** * Creates and returns a randomised string, containing alphanumeric and special characters * @static * @param {Number} length - Length of randomised string * @param {boolean} upperCase - Should all characters be in upper case? * @param {boolean} codeMode - Should there be extra {} and () inserted into the string? * @returns {string} - Randomised string */ static createMixedString(length, upperCase, codeMode) { return this.createRandString({ selection: numbers + chars + specials, length, upperCase, codeMode, }); } /** * Creates array with randomised strings. * It will also insert substrings into the randomised strings, if requiredStrings is set * @static * @param {Object} params - Parameters * @param {Number} params.amount - Number of randomised strings * @param {Number} params.length - Length of randomised string * @param {boolean} params.upperCase - Should all characters be in upper case? * @param {boolean} params.codeMode - Should there be extra {} and () inserted into the string? * @param {string[]} params.requiredStrings - Substrings to be added into the randomised strings * @returns {string[]} - Randomised strings */ static createMixedArray(params) { const amount = params.amount; const length = params.length; const upperCase = params.upperCase; const codeMode = params.codeMode; const requiredStrings = params.requiredStrings || []; const text = []; const requiredIndexes = []; for (let i = 0; i < amount; i += 1) { text.push(this.createMixedString(length, upperCase, codeMode)); } for (let i = 0; i < requiredStrings.length; i += 1) { const stringLength = requiredStrings[i].length; const randomStringIndex = Math.floor(Math.random() * (length - stringLength - 1)); let randomArrayIndex = Math.floor(Math.random() * (amount - 2)); /** * Max 1 required string per randomised string * Stores the indexes of the ones who already had a substring added to them * This rule will be ignored and multiple substrings can appear in a randomised string if the amount of required string is higher than the amount of strings to be generated */ while (requiredIndexes.length < amount && requiredIndexes.indexOf(randomArrayIndex) > -1) { randomArrayIndex = Math.floor(Math.random() * (amount - 2)); } /** * Inserts required string and cuts away enough characters from the left and right of the random string to keep the length intact */ text[randomArrayIndex] = text[randomArrayIndex].slice(0, randomStringIndex) + requiredStrings[i] + text[randomArrayIndex].slice(randomStringIndex + stringLength); requiredIndexes.push(randomArrayIndex); } return text; } /** * Copies string to avoid the original being consumed * @static * @param {string} string - String to copy * @returns {string} - String copy */ static copyString(string) { return string && string !== null ? JSON.parse(JSON.stringify(string)) : ''; } } module.exports = TextTools;
Java
UTF-8
229
1.5
2
[]
no_license
import com.sam.ui.Main; /*Run sql script in the file SQLscript in your database console to add required tables*/ public class OnlineretailDBProject3 { public static void main(String[] args) { new Main().start(); } }
C#
UTF-8
2,771
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Text; using BTCrawler.Common.Crawler; using BTCrawler.Common.FileHandler; namespace BTCrawler.Common { public class Controller { private readonly IAlreadyDownloadListFileLoader _alreadyDownloadListFileLoader; private readonly IHtmlLoader _detailPageLoader; private readonly IHtmlLoader _listingPageloader; private readonly string _outputPath; private readonly Action<string> _writeMessage; public Controller(IAlreadyDownloadListFileLoader alreadyDownloadListFileLoader, IHtmlLoader listingPageLoader, IHtmlLoader detailPageLoader, string outputPath, Action<string> writeMessage) { _alreadyDownloadListFileLoader = alreadyDownloadListFileLoader; _detailPageLoader = detailPageLoader; _listingPageloader = listingPageLoader; _outputPath = outputPath; _writeMessage = writeMessage; } public void DoDownload(string alreadyDownloadedListFileName) { List<string> alreadyDownloadedList = _alreadyDownloadListFileLoader.LoadListFromFile(alreadyDownloadedListFileName); ListingPageCrawler listingPageCrawler = new ListingPageCrawler(_listingPageloader); var links = listingPageCrawler.GetLinks(); foreach (var link in links) { //DetailPageCrawler detailPageCrawler = new DetailPageCrawler(_detailPageLoader, link.Url); //DownloadLink detailLink = detailPageCrawler.GetLink(); if (!alreadyDownloadedList.Contains(link.Name) && !link.Name.ToLower().Contains("divx")) { int retryCount = 0; HtmlSourceDownloader downloader = new HtmlSourceDownloader(); while (!File.Exists(_outputPath + @"\" + link.Name) && retryCount < 10) { downloader.DownloadFile(link.Url, _outputPath, retryCount); retryCount++; } if (File.Exists(_outputPath + @"\" + link.Name)) { _writeMessage(string.Format("Downloaded file {0}", link.Name)); File.AppendAllText(alreadyDownloadedListFileName, link.Name + Environment.NewLine, Encoding.UTF8); File.AppendAllText(alreadyDownloadedListFileName, link.Name.Replace("_1280x720", "") + Environment.NewLine, Encoding.UTF8); } } else { _writeMessage(string.Format("Already downloaded: {0}", link.Name)); } } } } }
Java
UTF-8
568
3.5625
4
[]
no_license
public class Main { public static void main(String[] args) { NumberGenerator oneToTen = new NumberGenerator(1,10); NumberGenerator elevenToTwenty = new NumberGenerator(11,20); Thread thread1 = new Thread(oneToTen); Thread thread2 = new Thread(elevenToTwenty); thread1.setPriority(Thread.MIN_PRIORITY); thread2.setPriority(Thread.MAX_PRIORITY); System.out.println("thread 1 priority is " + thread1.getPriority()); System.out.println("thread 2 priority is " + thread2.getPriority()); thread1.start(); thread2.start(); } }
JavaScript
UTF-8
5,694
3.53125
4
[]
no_license
// validar login function validateEmail() { const emailInput = document.getElementById('login'); if (emailInput.value === 'tryber@teste.com') { return true; } return false; } // validar senha function validatePassword() { const passwordInput = document.getElementById('password'); if (passwordInput.value === '123456') { return true; } return false; } // validar login e senha mediante click function validateAccess() { const loginButton = document.getElementById('login-button'); loginButton.addEventListener('click', () => { if (validateEmail() && validatePassword()) { window.alert('Olá, Tryber!'); } else { window.alert('Login ou senha inválidos.'); } }); } // valida checkbox termos function enableSubmit() { const getSubmitButton = document.getElementById('submit-btn'); const getAgreementCheck = document.getElementById('agreement'); getSubmitButton.disabled = true; getAgreementCheck.addEventListener('click', () => { if (getAgreementCheck.checked === true) { getSubmitButton.disabled = false; } else { getSubmitButton.disabled = true; } }); } // contar caracteres function countCharacters() { const counter = document.getElementById('counter'); const textarea = document.getElementById('textarea'); let count = 500; textarea.addEventListener('keyup', () => { count = 500 - textarea.value.length; counter.innerText = count; }); } // cria parágrafo com nome e sobrenome function returnNameValue(getFormDiv) { const fullNameDiv = document.querySelector('.first-row'); const nameInput = document.getElementById('input-name'); const lastNameInput = document.getElementById('input-lastname'); const fullName = document.createElement('p'); fullName.innerText = `Nome: ${nameInput.value} ${lastNameInput.value}`; getFormDiv.appendChild(fullName); fullNameDiv.parentNode.removeChild(fullNameDiv); } // cria parágrafo com email e casa selecionada function returnEmailHouseValue(getFormDiv) { const emailHouseDiv = document.querySelector('.second-row'); const emailInput = document.getElementById('input-email'); const houseInput = document.getElementById('house'); const email = document.createElement('p'); email.innerText = `Email: ${emailInput.value}`; const house = document.createElement('p'); house.innerText = `Casa: ${houseInput.value}`; getFormDiv.appendChild(email); getFormDiv.appendChild(house); emailHouseDiv.parentNode.removeChild(emailHouseDiv); } // cria parágrafo com família function returnFamilyValue(getFormDiv) { const getFamilyWrapper = document.querySelector('.family-wrapper'); const checkFamily = document.querySelector('input[type=radio][name=family]:checked').value; const returnFamily = document.createElement('p'); returnFamily.innerText = `Família: ${checkFamily}`; getFormDiv.appendChild(returnFamily); getFamilyWrapper.parentNode.removeChild(getFamilyWrapper); } // function verifica checked contents function checkedContents(array) { const checksArray = []; for (let index = 0; index < array.length; index += 1) { if (array[index].checked === true) { checksArray.push(` ${array[index].value}`); } } return checksArray.toString(); } // cria parágrafo com matérias function returunContentValues(getFormDiv) { const getContentWrapper = document.querySelector('.content-wrapper'); const getRadioCheckWrapper = document.querySelector('.radio-check-wrapper'); const checkContent = document.getElementsByClassName('subject'); const checkedValues = document.createElement('p'); checkedValues.innerText = `Matérias: ${checkedContents(checkContent)}`; getFormDiv.appendChild(checkedValues); getContentWrapper.parentNode.removeChild(getContentWrapper); getRadioCheckWrapper.parentNode.removeChild(getRadioCheckWrapper); } // cria parágrafo com o valor da avaliação function returnCsatValue(getFormDiv) { const getCsatDiv = document.querySelector('.csat'); const checkCsat = document.querySelector('input[type=radio][name=rate]:checked').value; const returnCsat = document.createElement('p'); returnCsat.innerText = `Avaliação: ${checkCsat}`; getFormDiv.appendChild(returnCsat); getCsatDiv.parentNode.removeChild(getCsatDiv); } // cria parágrafo com o valor do comentário function returnCommentValue(getFormDiv) { const getCommentValue = document.getElementById('textarea').value; const getCommentDiv = document.querySelector('.comment-area'); const commentValue = document.createElement('p'); commentValue.innerText = `Observações: ${getCommentValue}`; getFormDiv.appendChild(commentValue); getCommentDiv.parentNode.removeChild(getCommentDiv); } // retira checkbox termos de uso e botão enviar function removeAgreementSubmit(getSubmitButton) { const getAgreementCheck = document.querySelector('.agreement-check'); getAgreementCheck.parentNode.removeChild(getAgreementCheck); getSubmitButton.parentNode.removeChild(getSubmitButton); } // altera elementos do formulário function changeFormChilds() { const getSubmitButton = document.getElementById('submit-btn'); const getFormDiv = document.getElementById('evaluation-form'); getSubmitButton.addEventListener('click', (event) => { event.preventDefault(getFormDiv); returnNameValue(getFormDiv); returnEmailHouseValue(getFormDiv); returnFamilyValue(getFormDiv); returunContentValues(getFormDiv); returnCsatValue(getFormDiv); returnCommentValue(getFormDiv); removeAgreementSubmit(getSubmitButton); }); } window.onload = function start() { validateAccess(); enableSubmit(); countCharacters(); changeFormChilds(); };
Java
UTF-8
1,572
3.1875
3
[]
no_license
package com.javarush.task.task13.task1326; /* Сортировка четных чисел из файла */ import java.io.*; import java.util.ArrayList; import java.util.Collections; public class Solution { public static void main(String[] args) throws IOException { // напишите тут ваш код // try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String fileName = br.readLine(); FileInputStream fr = new FileInputStream(fileName); BufferedReader reader = new BufferedReader(new InputStreamReader(fr)); ArrayList<Integer> arrayList = new ArrayList<>(); String line = ""; try { while (line != null) { line = reader.readLine(); if (line.isEmpty()) { } else { arrayList.add(Integer.parseInt(line)); } } Collections.sort(arrayList); br.close(); fr.close(); reader.close(); // } // catch (FileNotFoundException e) {} // catch (IOException e) {} } catch (NullPointerException e){ Collections.sort(arrayList); br.close(); fr.close(); reader.close(); } // } // finally { // } for (int i = 0; i < arrayList.size(); i++) { if (arrayList.get(i) % 2.0 == 0) { System.out.println(arrayList.get(i)); } } } }